[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Bug#770617: marked as done (unblock: polarssl/1.3.9-2)



Your message dated Wed, 26 Nov 2014 19:32:19 +0100
with message-id <54761CB3.6090705@thykier.net>
and subject line Re: Bug#770617: unblock: polarssl/1.3.9-2
has caused the Debian Bug report #770617,
regarding unblock: polarssl/1.3.9-2
to be marked as done.

This means that you claim that the problem has been dealt with.
If this is not the case it is now your responsibility to reopen the
Bug report if necessary, and/or fix the problem forthwith.

(NB: If you are a system administrator and have no idea what this
message is talking about, this may indicate a serious mail system
misconfiguration somewhere. Please contact owner@bugs.debian.org
immediately.)


-- 
770617: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=770617
Debian Bug Tracking System
Contact owner@bugs.debian.org with problems
--- Begin Message ---
Package: release.debian.org
Severity: normal
User: release.debian.org@packages.debian.org
Usertags: unblock

This is an unblock request for polarssl/1.3.9-2. The unblock request was
sent by the maintainer to the mailing list, I'm filing it here for proper
processing.

Upstream maintenance release 1.3.9 fixes several security issues besides
other bugfixes. Debian revision -2 disables SSLv3.

Attached is the full debdiff; but the majority of changes are in tests; if
you exclude those with filterdiff -x '*/tests/*', you get attached
filtered debdiff that boils down to
 48 files changed, 861 insertions(+), 294 deletions(-)


Cheers,
Thijs
diff -ruN polarssl-1.3.8/ChangeLog polarssl-1.3.9/ChangeLog
--- polarssl-1.3.8/ChangeLog	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/ChangeLog	2014-10-20 13:59:19.000000000 +0200
@@ -1,5 +1,52 @@
 PolarSSL ChangeLog (Sorted per branch, date)
 
+= 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).
diff -ruN polarssl-1.3.8/CMakeLists.txt polarssl-1.3.9/CMakeLists.txt
--- polarssl-1.3.8/CMakeLists.txt	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/CMakeLists.txt	2014-10-20 13:59:19.000000000 +0200
@@ -4,22 +4,22 @@
 string(REGEX MATCH "Clang" CMAKE_COMPILER_IS_CLANG "${CMAKE_C_COMPILER_ID}")
 
 if(CMAKE_COMPILER_IS_GNUCC)
-  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -W -Wdeclaration-after-statement")
+  set(CMAKE_C_FLAGS "-Wall -Wextra -W -Wdeclaration-after-statement -Wlogical-op -Wwrite-strings")
   set(CMAKE_C_FLAGS_RELEASE "-O2")
   set(CMAKE_C_FLAGS_DEBUG "-g3 -O0")
   set(CMAKE_C_FLAGS_COVERAGE "-g3 -O0 --coverage")
-  set(CMAKE_C_FLAGS_ASAN "-fsanitize=address -fno-omit-frame-pointer -g3 -O1")
-  set(CMAKE_C_FLAGS_CHECK "${CMAKE_C_FLAGS} -Werror -O1 -Wlogical-op -Wwrite-strings")
+  set(CMAKE_C_FLAGS_ASAN "-fsanitize=address -fno-omit-frame-pointer -g3 -O1 -Werror")
+  set(CMAKE_C_FLAGS_CHECK "-O1 -Werror")
   set(CMAKE_C_FLAGS_CHECKFULL "${CMAKE_C_FLAGS_CHECK} -Wcast-qual")
 endif(CMAKE_COMPILER_IS_GNUCC)
 
 if(CMAKE_COMPILER_IS_CLANG)
-  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -W -Wdeclaration-after-statement")
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -W -Wdeclaration-after-statement -Wpointer-arith -Wwrite-strings -Wdocumentation -Wunreachable-code")
   set(CMAKE_C_FLAGS_RELEASE "-O2")
   set(CMAKE_C_FLAGS_DEBUG "-g3 -O0")
   set(CMAKE_C_FLAGS_COVERAGE "-g3 -O0 --coverage")
-  set(CMAKE_C_FLAGS_ASAN "-fsanitize=address -fno-omit-frame-pointer -g3 -O1")
-  set(CMAKE_C_FLAGS_CHECK "${CMAKE_C_FLAGS} -Werror -O1 -Wpointer-arith -Wwrite-strings -Wdocumentation -Wunreachable-code")
+  set(CMAKE_C_FLAGS_ASAN "-fsanitize=address -fno-omit-frame-pointer -g3 -O1 -Werror")
+  set(CMAKE_C_FLAGS_CHECK "-O1 -Werror")
 endif(CMAKE_COMPILER_IS_CLANG)
 
 set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE}
diff -ruN polarssl-1.3.8/debian/changelog polarssl-1.3.9/debian/changelog
--- polarssl-1.3.8/debian/changelog	2014-08-31 14:21:26.000000000 +0200
+++ polarssl-1.3.9/debian/changelog	2014-11-07 10:31:12.000000000 +0100
@@ -1,3 +1,17 @@
+polarssl (1.3.9-2) unstable; urgency=medium
+
+  * Disabled POLARSSL_SSL_PROTO_SSL3 at compile time to prevent potential
+    attacks, TLS considered standard for clients now, and consistency w/
+    OpenSSL in Debian
+
+ -- Roland Stigge <stigge@antcom.de>  Fri, 07 Nov 2014 10:28:34 +0100
+
+polarssl (1.3.9-1) unstable; urgency=medium
+
+  * New upstream release
+
+ -- Roland Stigge <stigge@antcom.de>  Wed, 05 Nov 2014 18:34:31 +0100
+
 polarssl (1.3.8-1) unstable; urgency=medium
 
   * New upstream release
diff -ruN polarssl-1.3.8/debian/control polarssl-1.3.9/debian/control
--- polarssl-1.3.8/debian/control	2014-08-31 14:24:23.000000000 +0200
+++ polarssl-1.3.9/debian/control	2014-11-05 18:37:35.000000000 +0100
@@ -2,7 +2,7 @@
 Section: libs
 Priority: optional
 Maintainer: Roland Stigge <stigge@antcom.de>
-Standards-Version: 3.9.5
+Standards-Version: 3.9.6
 Build-Depends: debhelper (>= 9)
 Homepage: http://polarssl.org
 
diff -ruN polarssl-1.3.8/debian/patches/01-config.patch polarssl-1.3.9/debian/patches/01-config.patch
--- polarssl-1.3.8/debian/patches/01-config.patch	2014-07-15 21:40:38.000000000 +0200
+++ polarssl-1.3.9/debian/patches/01-config.patch	2014-11-07 10:28:20.000000000 +0100
@@ -3,9 +3,18 @@
  capabilities
 Author: Arnaud Cornet <arnaud.cornet@gmail.com>
 
---- polarssl-1.3.7.orig/include/polarssl/config.h
-+++ polarssl-1.3.7/include/polarssl/config.h
-@@ -953,7 +953,7 @@
+--- polarssl-1.3.9.orig/include/polarssl/config.h
++++ polarssl-1.3.9/include/polarssl/config.h
+@@ -860,7 +860,7 @@
+  *
+  * Comment this macro to disable support for SSL 3.0
+  */
+-#define POLARSSL_SSL_PROTO_SSL3
++//#define POLARSSL_SSL_PROTO_SSL3
+ 
+ /**
+  * \def POLARSSL_SSL_PROTO_TLS1
+@@ -973,7 +973,7 @@
   *
   * Uncomment this to enable pthread mutexes.
   */
@@ -14,7 +23,7 @@
  
  /**
   * \def POLARSSL_VERSION_FEATURES
-@@ -1473,7 +1473,7 @@
+@@ -1518,7 +1518,7 @@
   *
   * Uncomment to enable the HAVEGE random generator.
   */
@@ -23,7 +32,7 @@
  
  /**
   * \def POLARSSL_HMAC_DRBG_C
-@@ -1511,7 +1511,7 @@
+@@ -1556,7 +1556,7 @@
   *
   * Uncomment to enable support for (rare) MD2-signed X.509 certs.
   */
@@ -32,7 +41,7 @@
  
  /**
   * \def POLARSSL_MD4_C
-@@ -1523,7 +1523,7 @@
+@@ -1568,7 +1568,7 @@
   *
   * Uncomment to enable support for (rare) MD4-signed X.509 certs.
   */
@@ -41,7 +50,7 @@
  
  /**
   * \def POLARSSL_MD5_C
-@@ -1914,7 +1914,7 @@
+@@ -1959,7 +1959,7 @@
   *
   * Enable this layer to allow use of mutexes within PolarSSL
   */
diff -ruN polarssl-1.3.8/doxygen/input/doc_mainpage.h polarssl-1.3.9/doxygen/input/doc_mainpage.h
--- polarssl-1.3.8/doxygen/input/doc_mainpage.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/doxygen/input/doc_mainpage.h	2014-10-20 13:59:19.000000000 +0200
@@ -4,7 +4,7 @@
  */
 
 /**
- * @mainpage PolarSSL v1.3.8 source code documentation
+ * @mainpage PolarSSL v1.3.9 source code documentation
  *
  * This documentation describes the internal structure of PolarSSL.  It was
  * automatically generated from specially formatted comment blocks in
diff -ruN polarssl-1.3.8/doxygen/polarssl.doxyfile polarssl-1.3.9/doxygen/polarssl.doxyfile
--- polarssl-1.3.8/doxygen/polarssl.doxyfile	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/doxygen/polarssl.doxyfile	2014-10-20 13:59:19.000000000 +0200
@@ -28,7 +28,7 @@
 # identify the project. Note that if you do not use Doxywizard you need
 # to put quotes around the project name if it contains spaces.
 
-PROJECT_NAME           = "PolarSSL v1.3.8"
+PROJECT_NAME           = "PolarSSL v1.3.9"
 
 # The PROJECT_NUMBER tag can be used to enter a project or revision number.
 # This could be handy for archiving the generated documentation or
diff -ruN polarssl-1.3.8/include/polarssl/bignum.h polarssl-1.3.9/include/polarssl/bignum.h
--- polarssl-1.3.8/include/polarssl/bignum.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/bignum.h	2014-10-20 13:59:19.000000000 +0200
@@ -90,7 +90,7 @@
  * Note: Calculations can results temporarily in larger MPIs. So the number
  * of limbs required (POLARSSL_MPI_MAX_LIMBS) is higher.
  */
-#define POLARSSL_MPI_MAX_SIZE                              512      /**< Maximum number of bytes for usable MPIs. */
+#define POLARSSL_MPI_MAX_SIZE                              1024     /**< Maximum number of bytes for usable MPIs. */
 #endif /* !POLARSSL_MPI_MAX_SIZE */
 
 #define POLARSSL_MPI_MAX_BITS                              ( 8 * POLARSSL_MPI_MAX_SIZE )    /**< Maximum number of bits for usable MPIs. */
diff -ruN polarssl-1.3.8/include/polarssl/bn_mul.h polarssl-1.3.9/include/polarssl/bn_mul.h
--- polarssl-1.3.8/include/polarssl/bn_mul.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/bn_mul.h	2014-10-20 13:59:19.000000000 +0200
@@ -833,8 +833,8 @@
 
 #define MULADDC_CORE                    \
     r   = *(s++) * (t_udbl) b;          \
-    r0  = r;                            \
-    r1  = r >> biL;                     \
+    r0  = (t_uint) r;                   \
+    r1  = (t_uint)( r >> biL );         \
     r0 += c;  r1 += (r0 <  c);          \
     r0 += *d; r1 += (r0 < *d);          \
     c = r1; *(d++) = r0;
diff -ruN polarssl-1.3.8/include/polarssl/config.h polarssl-1.3.9/include/polarssl/config.h
--- polarssl-1.3.8/include/polarssl/config.h	2014-11-11 11:35:29.000000000 +0100
+++ polarssl-1.3.9/include/polarssl/config.h	2014-11-11 11:35:35.000000000 +0100
@@ -2113,7 +2113,7 @@
 
 /* MPI / BIGNUM options */
 //#define POLARSSL_MPI_WINDOW_SIZE            6 /**< Maximum windows size used. */
-//#define POLARSSL_MPI_MAX_SIZE             512 /**< Maximum number of bytes for usable MPIs. */
+//#define POLARSSL_MPI_MAX_SIZE            1024 /**< Maximum number of bytes for usable MPIs. */
 
 /* CTR_DRBG options */
 //#define CTR_DRBG_ENTROPY_LEN               48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */
diff -ruN polarssl-1.3.8/include/polarssl/error.h polarssl-1.3.9/include/polarssl/error.h
--- polarssl-1.3.8/include/polarssl/error.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/error.h	2014-10-20 13:59:19.000000000 +0200
@@ -91,7 +91,7 @@
  * ECP       4   8 (Started from top)
  * MD        5   4
  * CIPHER    6   6
- * SSL       6   9 (Started from top)
+ * SSL       6   10 (Started from top)
  * SSL       7   31
  *
  * Module dependent error code (5 bits 0x.00.-0x.F8.)
diff -ruN polarssl-1.3.8/include/polarssl/ssl.h polarssl-1.3.9/include/polarssl/ssl.h
--- polarssl-1.3.8/include/polarssl/ssl.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/ssl.h	2014-10-20 13:59:19.000000000 +0200
@@ -145,6 +145,7 @@
 #define POLARSSL_ERR_SSL_UNKNOWN_IDENTITY                  -0x6C80  /**< Unknown identity received (eg, PSK identity) */
 #define POLARSSL_ERR_SSL_INTERNAL_ERROR                    -0x6C00  /**< Internal error (eg, unexpected failure in lower-level module) */
 #define POLARSSL_ERR_SSL_COUNTER_WRAPPING                  -0x6B80  /**< A counter would wrap (eg, too many messages exchanged). */
+#define POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO       -0x6B00  /**< Unexpected message at ServerHello in renegotiation. */
 
 /*
  * Various constants
@@ -204,6 +205,7 @@
 
 #define SSL_IS_CLIENT                   0
 #define SSL_IS_SERVER                   1
+
 #define SSL_COMPRESS_NULL               0
 #define SSL_COMPRESS_DEFLATE            1
 
@@ -560,8 +562,8 @@
 
 #if defined(POLARSSL_SSL_PROTO_SSL3)
     /* Needed only for SSL v3.0 secret */
-    unsigned char mac_enc[48];          /*!<  SSL v3.0 secret (enc)   */
-    unsigned char mac_dec[48];          /*!<  SSL v3.0 secret (dec)   */
+    unsigned char mac_enc[20];          /*!<  SSL v3.0 secret (enc)   */
+    unsigned char mac_dec[20];          /*!<  SSL v3.0 secret (dec)   */
 #endif /* POLARSSL_SSL_PROTO_SSL3 */
 
     md_context_t md_ctx_enc;            /*!<  MAC (encryption)        */
@@ -1491,23 +1493,26 @@
 /**
  * \brief          Enforce server-requested renegotiation.
  *                 (Default: enforced, max_records = 16)
- *                 (No effect on client.)
  *
- *                 When a server requests a renegotiation, the client can
- *                 comply or ignore the request. This function allows the
- *                 server to decide if it should enforce its renegotiation
- *                 requests by closing the connection if the client doesn't
- *                 initiate a renegotiation.
- *
- *                 However, records could already be in transit from the
- *                 client to the server when the request is emitted. In order
- *                 to increase reliability, the server can accept a number of
- *                 records containing application data before the ClientHello
- *                 that was requested.
+ *                 When we request a renegotiation, the peer can comply or
+ *                 ignore the request. This function allows us to decide
+ *                 whether to enforce our renegotiation requests by closing
+ *                 the connection if the peer doesn't comply.
+ *
+ *                 However, records could already be in transit from the peer
+ *                 when the request is emitted. In order to increase
+ *                 reliability, we can accept a number of records before the
+ *                 expected handshake records.
  *
  *                 The optimal value is highly dependent on the specific usage
  *                 scenario.
  *
+ * \warning        On client, the grace period can only happen during
+ *                 ssl_read(), as opposed to ssl_write() and ssl_renegotiate()
+ *                 which always behave as if max_record was 0. The reason is,
+ *                 if we receive application data from the server, we need a
+ *                 place to write it, which only happens during ssl_read().
+ *
  * \param ssl      SSL context
  * \param max_records Use SSL_RENEGOTIATION_NOT_ENFORCED if you don't want to
  *                 enforce renegotiation, or a non-negative value to enforce
@@ -1632,7 +1637,7 @@
  *
  * \param ssl      SSL context
  * \param buf      buffer that will hold the data
- * \param len      how many bytes must be read
+ * \param len      maximum number of bytes to read
  *
  * \return         This function returns the number of bytes read, 0 for EOF,
  *                 or a negative error code.
diff -ruN polarssl-1.3.8/include/polarssl/version.h polarssl-1.3.9/include/polarssl/version.h
--- polarssl-1.3.8/include/polarssl/version.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/version.h	2014-10-20 13:59:19.000000000 +0200
@@ -43,16 +43,16 @@
  */
 #define POLARSSL_VERSION_MAJOR  1
 #define POLARSSL_VERSION_MINOR  3
-#define POLARSSL_VERSION_PATCH  8
+#define POLARSSL_VERSION_PATCH  9
 
 /**
  * The single version number has the following structure:
  *    MMNNPP00
  *    Major version | Minor version | Patch version
  */
-#define POLARSSL_VERSION_NUMBER         0x01030800
-#define POLARSSL_VERSION_STRING         "1.3.8"
-#define POLARSSL_VERSION_STRING_FULL    "PolarSSL 1.3.8"
+#define POLARSSL_VERSION_NUMBER         0x01030900
+#define POLARSSL_VERSION_STRING         "1.3.9"
+#define POLARSSL_VERSION_STRING_FULL    "PolarSSL 1.3.9"
 
 #if defined(POLARSSL_VERSION_C)
 
diff -ruN polarssl-1.3.8/include/polarssl/x509.h polarssl-1.3.9/include/polarssl/x509.h
--- polarssl-1.3.8/include/polarssl/x509.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/x509.h	2014-10-20 13:59:19.000000000 +0200
@@ -143,6 +143,8 @@
 #define X509_FORMAT_DER                 1
 #define X509_FORMAT_PEM                 2
 
+#define X509_MAX_DN_NAME_SIZE         256 /**< Maximum value size of a DN entry */
+
 #ifdef __cplusplus
 extern "C" {
 #endif
diff -ruN polarssl-1.3.8/library/asn1parse.c polarssl-1.3.9/library/asn1parse.c
--- polarssl-1.3.8/library/asn1parse.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/asn1parse.c	2014-10-20 13:59:19.000000000 +0200
@@ -47,6 +47,11 @@
 #include <string.h>
 #include <stdlib.h>
 
+/* Implementation that should never be optimized out by the compiler */
+static void polarssl_zeroize( void *v, size_t n ) {
+    volatile unsigned char *p = v; while( n-- ) *p++ = 0;
+}
+
 /*
  * ASN.1 DER decoding routines
  */
@@ -311,7 +316,7 @@
 
     if( *p == end )
     {
-        memset( params, 0, sizeof(asn1_buf) );
+        polarssl_zeroize( params, sizeof(asn1_buf) );
         return( 0 );
     }
 
@@ -356,7 +361,7 @@
     polarssl_free( cur->oid.p );
     polarssl_free( cur->val.p );
 
-    memset( cur, 0, sizeof( asn1_named_data ) );
+    polarssl_zeroize( cur, sizeof( asn1_named_data ) );
 }
 
 void asn1_free_named_data_list( asn1_named_data **head )
diff -ruN polarssl-1.3.8/library/base64.c polarssl-1.3.9/library/base64.c
--- polarssl-1.3.8/library/base64.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/base64.c	2014-10-20 13:59:19.000000000 +0200
@@ -147,8 +147,21 @@
     uint32_t j, x;
     unsigned char *p;
 
+    /* First pass: check for validity and get output length */
     for( i = n = j = 0; i < slen; i++ )
     {
+        /* Skip spaces before checking for EOL */
+        x = 0;
+        while( i < slen && src[i] == ' ' )
+        {
+            ++i;
+            ++x;
+        }
+
+        /* Spaces at end of buffer are OK */
+        if( i == slen )
+            break;
+
         if( ( slen - i ) >= 2 &&
             src[i] == '\r' && src[i + 1] == '\n' )
             continue;
@@ -156,6 +169,10 @@
         if( src[i] == '\n' )
             continue;
 
+        /* Space inside a line is an error */
+        if( x != 0 )
+            return( POLARSSL_ERR_BASE64_INVALID_CHARACTER );
+
         if( src[i] == '=' && ++j > 2 )
             return( POLARSSL_ERR_BASE64_INVALID_CHARACTER );
 
@@ -182,7 +199,7 @@
 
    for( j = 3, n = x = 0, p = dst; i > 0; i--, src++ )
    {
-        if( *src == '\r' || *src == '\n' )
+        if( *src == '\r' || *src == '\n' || *src == ' ' )
             continue;
 
         j -= ( base64_dec_map[*src] == 64 );
diff -ruN polarssl-1.3.8/library/bignum.c polarssl-1.3.9/library/bignum.c
--- polarssl-1.3.8/library/bignum.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/bignum.c	2014-10-20 13:59:19.000000000 +0200
@@ -2057,7 +2057,11 @@
                   void *p_rng )
 {
     int ret;
-    const mpi XX = { 1, X->n, X->p }; /* Abs(X) */
+    mpi XX;
+
+    XX.s = 1;
+    XX.n = X->n;
+    XX.p = X->p;
 
     if( mpi_cmp_int( &XX, 0 ) == 0 ||
         mpi_cmp_int( &XX, 1 ) == 0 )
diff -ruN polarssl-1.3.8/library/cipher_wrap.c polarssl-1.3.9/library/cipher_wrap.c
--- polarssl-1.3.8/library/cipher_wrap.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/cipher_wrap.c	2014-10-20 13:59:19.000000000 +0200
@@ -1313,7 +1313,7 @@
 
 static void * null_ctx_alloc( void )
 {
-    return( (void *) 1 )
+    return( (void *) 1 );
 }
 
 static void null_ctx_free( void *ctx )
diff -ruN polarssl-1.3.8/library/CMakeLists.txt polarssl-1.3.9/library/CMakeLists.txt
--- polarssl-1.3.8/library/CMakeLists.txt	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/CMakeLists.txt	2014-10-20 13:59:19.000000000 +0200
@@ -118,7 +118,7 @@
 
 if(USE_SHARED_POLARSSL_LIBRARY)
 	add_library(polarssl SHARED ${src})
-	set_target_properties(polarssl PROPERTIES VERSION 1.3.8 SOVERSION 7)
+	set_target_properties(polarssl PROPERTIES VERSION 1.3.9 SOVERSION 7)
 
 	target_link_libraries(polarssl ${libs})
 
diff -ruN polarssl-1.3.8/library/ecp.c polarssl-1.3.9/library/ecp.c
--- polarssl-1.3.8/library/ecp.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/ecp.c	2014-10-20 13:59:19.000000000 +0200
@@ -495,7 +495,7 @@
     int ret;
     size_t plen;
 
-    if ( ilen < 1 )
+    if( ilen < 1 )
         return( POLARSSL_ERR_ECP_BAD_INPUT_DATA );
 
     if( buf[0] == 0x00 )
@@ -952,7 +952,9 @@
         MOD_SUB( X3 );
     }
     else
+    {
         MPI_CHK( mpi_mul_mpi( &X3,  &X3,    &grp->A ) ); MOD_MUL( X3 );
+    }
 
     MPI_CHK( mpi_add_mpi( &T3,  &T3,    &X3     ) ); MOD_ADD( T3 );
     MPI_CHK( mpi_mul_mpi( &X3,  &T3,    &T3     ) ); MOD_MUL( X3 );
diff -ruN polarssl-1.3.8/library/error.c polarssl-1.3.9/library/error.c
--- polarssl-1.3.8/library/error.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/error.c	2014-10-20 13:59:19.000000000 +0200
@@ -450,6 +450,8 @@
             snprintf( buf, buflen, "SSL - Internal error (eg, unexpected failure in lower-level module)" );
         if( use_ret == -(POLARSSL_ERR_SSL_COUNTER_WRAPPING) )
             snprintf( buf, buflen, "SSL - A counter would wrap (eg, too many messages exchanged)" );
+        if( use_ret == -(POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO) )
+            snprintf( buf, buflen, "SSL - Unexpected message at ServerHello in renegotiation" );
 #endif /* POLARSSL_SSL_TLS_C */
 
 #if defined(POLARSSL_X509_USE_C) || defined(POLARSSL_X509_CREATE_C)
diff -ruN polarssl-1.3.8/library/gcm.c polarssl-1.3.9/library/gcm.c
--- polarssl-1.3.8/library/gcm.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/gcm.c	2014-10-20 13:59:19.000000000 +0200
@@ -220,7 +220,6 @@
 #endif /* POLARSSL_AESNI_C && POLARSSL_HAVE_X86_64 */
 
     lo = x[15] & 0xf;
-    hi = x[15] >> 4;
 
     zh = ctx->HH[lo];
     zl = ctx->HL[lo];
@@ -354,7 +353,7 @@
     /* Total length is restricted to 2^39 - 256 bits, ie 2^36 - 2^5 bytes
      * Also check for possible overflow */
     if( ctx->len + length < ctx->len ||
-        (uint64_t) ctx->len + length > 0x03FFFFE0llu )
+        (uint64_t) ctx->len + length > 0x03FFFFE0ull )
     {
         return( POLARSSL_ERR_GCM_BAD_INPUT );
     }
diff -ruN polarssl-1.3.8/library/md.c polarssl-1.3.9/library/md.c
--- polarssl-1.3.8/library/md.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/md.c	2014-10-20 13:59:19.000000000 +0200
@@ -53,13 +53,13 @@
 static const int supported_digests[] = {
 
 #if defined(POLARSSL_SHA512_C)
-        POLARSSL_MD_SHA384,
         POLARSSL_MD_SHA512,
+        POLARSSL_MD_SHA384,
 #endif
 
 #if defined(POLARSSL_SHA256_C)
-        POLARSSL_MD_SHA224,
         POLARSSL_MD_SHA256,
+        POLARSSL_MD_SHA224,
 #endif
 
 #if defined(POLARSSL_SHA1_C)
diff -ruN polarssl-1.3.8/library/memory_buffer_alloc.c polarssl-1.3.9/library/memory_buffer_alloc.c
--- polarssl-1.3.8/library/memory_buffer_alloc.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/memory_buffer_alloc.c	2014-10-20 13:59:19.000000000 +0200
@@ -37,10 +37,10 @@
 
 #if defined(POLARSSL_MEMORY_DEBUG)
 #include <stdio.h>
+#endif
 #if defined(POLARSSL_MEMORY_BACKTRACE)
 #include <execinfo.h>
 #endif
-#endif
 
 #if defined(POLARSSL_THREADING_C)
 #include "polarssl/threading.h"
@@ -109,11 +109,11 @@
     size_t i;
 #endif
 
-    polarssl_fprintf( stderr, "HDR:  PTR(%10u), PREV(%10u), NEXT(%10u), "
-                              "ALLOC(%u), SIZE(%10u)\n",
+    polarssl_fprintf( stderr, "HDR:  PTR(%10zu), PREV(%10zu), NEXT(%10zu), "
+                              "ALLOC(%zu), SIZE(%10zu)\n",
                       (size_t) hdr, (size_t) hdr->prev, (size_t) hdr->next,
                       hdr->alloc, hdr->size );
-    polarssl_fprintf( stderr, "      FPREV(%10u), FNEXT(%10u)\n",
+    polarssl_fprintf( stderr, "      FPREV(%10zu), FNEXT(%10zu)\n",
                       (size_t) hdr->prev_free, (size_t) hdr->next_free );
 
 #if defined(POLARSSL_MEMORY_BACKTRACE)
@@ -511,8 +511,8 @@
 void memory_buffer_alloc_status()
 {
     polarssl_fprintf( stderr,
-                      "Current use: %u blocks / %u bytes, max: %u blocks / "
-                      "%u bytes (total %u bytes), malloc / free: %u / %u\n",
+                      "Current use: %zu blocks / %zu bytes, max: %zu blocks / "
+                      "%zu bytes (total %zu bytes), malloc / free: %zu / %zu\n",
                       heap.header_count, heap.total_used,
                       heap.maximum_header_count, heap.maximum_used,
                       heap.maximum_header_count * sizeof( memory_header )
diff -ruN polarssl-1.3.8/library/net.c polarssl-1.3.9/library/net.c
--- polarssl-1.3.8/library/net.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/net.c	2014-10-20 13:59:19.000000000 +0200
@@ -434,7 +434,7 @@
 
     if( *client_fd < 0 )
     {
-        if( net_would_block( *client_fd ) != 0 )
+        if( net_would_block( bind_fd ) != 0 )
             return( POLARSSL_ERR_NET_WANT_READ );
 
         return( POLARSSL_ERR_NET_ACCEPT_FAILED );
@@ -497,7 +497,12 @@
 {
     struct timeval tv;
     tv.tv_sec  = 0;
+#if !defined(_WIN32) && ( defined(__unix__) || defined(__unix) || \
+    ( defined(__APPLE__) && defined(__MACH__) ) )
+    tv.tv_usec = (suseconds_t) usec;
+#else
     tv.tv_usec = usec;
+#endif
     select( 0, NULL, NULL, NULL, &tv );
 }
 #endif /* POLARSSL_HAVE_TIME */
@@ -508,7 +513,7 @@
 int net_recv( void *ctx, unsigned char *buf, size_t len )
 {
     int fd = *((int *) ctx);
-    int ret = read( fd, buf, len );
+    int ret = (int) read( fd, buf, len );
 
     if( ret < 0 )
     {
@@ -539,7 +544,7 @@
 int net_send( void *ctx, const unsigned char *buf, size_t len )
 {
     int fd = *((int *) ctx);
-    int ret = write( fd, buf, len );
+    int ret = (int) write( fd, buf, len );
 
     if( ret < 0 )
     {
diff -ruN polarssl-1.3.8/library/pk.c polarssl-1.3.9/library/pk.c
--- polarssl-1.3.8/library/pk.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/pk.c	2014-10-20 13:59:19.000000000 +0200
@@ -222,7 +222,7 @@
 
         ret = rsa_rsassa_pss_verify_ext( pk_rsa( *ctx ),
                 NULL, NULL, RSA_PUBLIC,
-                md_alg, hash_len, hash,
+                md_alg, (unsigned int) hash_len, hash,
                 pss_opts->mgf1_hash_id,
                 pss_opts->expected_salt_len,
                 sig );
diff -ruN polarssl-1.3.8/library/pkcs5.c polarssl-1.3.9/library/pkcs5.c
--- polarssl-1.3.8/library/pkcs5.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/pkcs5.c	2014-10-20 13:59:19.000000000 +0200
@@ -408,7 +408,7 @@
 exit:
     md_free( &sha1_ctx );
 
-    return( 0 );
+    return( ret );
 }
 #endif /* POLARSSL_SHA1_C */
 
diff -ruN polarssl-1.3.8/library/pkwrite.c polarssl-1.3.9/library/pkwrite.c
--- polarssl-1.3.8/library/pkwrite.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/pkwrite.c	2014-10-20 13:59:19.000000000 +0200
@@ -294,10 +294,93 @@
 #define PEM_BEGIN_PRIVATE_KEY_EC    "-----BEGIN EC PRIVATE KEY-----\n"
 #define PEM_END_PRIVATE_KEY_EC      "-----END EC PRIVATE KEY-----\n"
 
+/*
+ * Max sizes of key per types. Shown as tag + len (+ content).
+ */
+
+#if defined(POLARSSL_RSA_C)
+/*
+ * RSA public keys:
+ *  SubjectPublicKeyInfo  ::=  SEQUENCE  {          1 + 3
+ *       algorithm            AlgorithmIdentifier,  1 + 1 (sequence)
+ *                                                + 1 + 1 + 9 (rsa oid)
+ *                                                + 1 + 1 (params null)
+ *       subjectPublicKey     BIT STRING }          1 + 3 + (1 + below)
+ *  RSAPublicKey ::= SEQUENCE {                     1 + 3
+ *      modulus           INTEGER,  -- n            1 + 3 + MPI_MAX + 1
+ *      publicExponent    INTEGER   -- e            1 + 3 + MPI_MAX + 1
+ *  }
+ */
+#define RSA_PUB_DER_MAX_BYTES   38 + 2 * POLARSSL_MPI_MAX_SIZE
+
+/*
+ * RSA private keys:
+ *  RSAPrivateKey ::= SEQUENCE {                    1 + 3
+ *      version           Version,                  1 + 1 + 1
+ *      modulus           INTEGER,                  1 + 3 + MPI_MAX + 1
+ *      publicExponent    INTEGER,                  1 + 3 + MPI_MAX + 1
+ *      privateExponent   INTEGER,                  1 + 3 + MPI_MAX + 1
+ *      prime1            INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
+ *      prime2            INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
+ *      exponent1         INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
+ *      exponent2         INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
+ *      coefficient       INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
+ *      otherPrimeInfos   OtherPrimeInfos OPTIONAL  0 (not supported)
+ *  }
+ */
+#define MPI_MAX_SIZE_2          POLARSSL_MPI_MAX_SIZE / 2 + \
+                                POLARSSL_MPI_MAX_SIZE % 2
+#define RSA_PRV_DER_MAX_BYTES   47 + 3 * POLARSSL_MPI_MAX_SIZE \
+                                   + 5 * MPI_MAX_SIZE_2
+
+#else /* POLARSSL_RSA_C */
+
+#define RSA_PUB_DER_MAX_BYTES   0
+#define RSA_PRV_DER_MAX_BYTES   0
+
+#endif /* POLARSSL_RSA_C */
+
+#if defined(POLARSSL_ECP_C)
+/*
+ * EC public keys:
+ *  SubjectPublicKeyInfo  ::=  SEQUENCE  {      1 + 2
+ *    algorithm         AlgorithmIdentifier,    1 + 1 (sequence)
+ *                                            + 1 + 1 + 7 (ec oid)
+ *                                            + 1 + 1 + 9 (namedCurve oid)
+ *    subjectPublicKey  BIT STRING              1 + 2 + 1               [1]
+ *                                            + 1 (point format)        [1]
+ *                                            + 2 * ECP_MAX (coords)    [1]
+ *  }
+ */
+#define ECP_PUB_DER_MAX_BYTES   30 + 2 * POLARSSL_ECP_MAX_BYTES
+
+/*
+ * EC private keys:
+ * ECPrivateKey ::= SEQUENCE {                  1 + 2
+ *      version        INTEGER ,                1 + 1 + 1
+ *      privateKey     OCTET STRING,            1 + 1 + ECP_MAX
+ *      parameters [0] ECParameters OPTIONAL,   1 + 1 + (1 + 1 + 9)
+ *      publicKey  [1] BIT STRING OPTIONAL      1 + 2 + [1] above
+ *    }
+ */
+#define ECP_PRV_DER_MAX_BYTES   29 + 3 * POLARSSL_ECP_MAX_BYTES
+
+#else /* POLARSSL_ECP_C */
+
+#define ECP_PUB_DER_MAX_BYTES   0
+#define ECP_PRV_DER_MAX_BYTES   0
+
+#endif /* POLARSSL_ECP_C */
+
+#define PUB_DER_MAX_BYTES   RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
+                            RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES
+#define PRV_DER_MAX_BYTES   RSA_PRV_DER_MAX_BYTES > ECP_PRV_DER_MAX_BYTES ? \
+                            RSA_PRV_DER_MAX_BYTES : ECP_PRV_DER_MAX_BYTES
+
 int pk_write_pubkey_pem( pk_context *key, unsigned char *buf, size_t size )
 {
     int ret;
-    unsigned char output_buf[4096];
+    unsigned char output_buf[PUB_DER_MAX_BYTES];
     size_t olen = 0;
 
     if( ( ret = pk_write_pubkey_der( key, output_buf,
@@ -319,7 +402,7 @@
 int pk_write_key_pem( pk_context *key, unsigned char *buf, size_t size )
 {
     int ret;
-    unsigned char output_buf[4096];
+    unsigned char output_buf[PRV_DER_MAX_BYTES];
     const char *begin, *end;
     size_t olen = 0;
 
diff -ruN polarssl-1.3.8/library/rsa.c polarssl-1.3.9/library/rsa.c
--- polarssl-1.3.8/library/rsa.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/rsa.c	2014-10-20 13:59:19.000000000 +0200
@@ -1005,7 +1005,7 @@
 {
     size_t nb_pad, olen, oid_size = 0;
     unsigned char *p = sig;
-    const char *oid;
+    const char *oid = NULL;
 
     if( mode == RSA_PRIVATE && ctx->padding != RSA_PKCS_V15 )
         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
diff -ruN polarssl-1.3.8/library/ssl_ciphersuites.c polarssl-1.3.9/library/ssl_ciphersuites.c
--- polarssl-1.3.8/library/ssl_ciphersuites.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/ssl_ciphersuites.c	2014-10-20 13:59:19.000000000 +0200
@@ -260,7 +260,7 @@
     TLS_PSK_WITH_NULL_SHA256,
     TLS_PSK_WITH_NULL_SHA,
 
-#endif
+#endif /* SSL_CIPHERSUITES */
     0
 };
 
@@ -1077,7 +1077,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_PSK_WITH_AES_128_CBC_SHA256, "TLS-PSK-WITH-AES-128-CBC-SHA256",
       POLARSSL_CIPHER_AES_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1085,7 +1085,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_PSK_WITH_AES_256_CBC_SHA384, "TLS-PSK-WITH-AES-256-CBC-SHA384",
       POLARSSL_CIPHER_AES_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1133,7 +1133,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256, "TLS-PSK-WITH-CAMELLIA-128-CBC-SHA256",
       POLARSSL_CIPHER_CAMELLIA_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1141,7 +1141,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384, "TLS-PSK-WITH-CAMELLIA-256-CBC-SHA384",
       POLARSSL_CIPHER_CAMELLIA_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1213,7 +1213,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, "TLS-DHE-PSK-WITH-AES-128-CBC-SHA256",
       POLARSSL_CIPHER_AES_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1221,7 +1221,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, "TLS-DHE-PSK-WITH-AES-256-CBC-SHA384",
       POLARSSL_CIPHER_AES_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1269,7 +1269,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, "TLS-DHE-PSK-WITH-CAMELLIA-128-CBC-SHA256",
       POLARSSL_CIPHER_CAMELLIA_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1277,7 +1277,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, "TLS-DHE-PSK-WITH-CAMELLIA-256-CBC-SHA384",
       POLARSSL_CIPHER_CAMELLIA_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1428,7 +1428,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, "TLS-RSA-PSK-WITH-AES-128-CBC-SHA256",
       POLARSSL_CIPHER_AES_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1436,7 +1436,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, "TLS-RSA-PSK-WITH-AES-256-CBC-SHA384",
       POLARSSL_CIPHER_AES_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1444,13 +1444,13 @@
 #if defined(POLARSSL_SHA1_C)
     { TLS_RSA_PSK_WITH_AES_128_CBC_SHA, "TLS-RSA-PSK-WITH-AES-128-CBC-SHA",
       POLARSSL_CIPHER_AES_128_CBC, POLARSSL_MD_SHA1, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 
     { TLS_RSA_PSK_WITH_AES_256_CBC_SHA, "TLS-RSA-PSK-WITH-AES-256-CBC-SHA",
       POLARSSL_CIPHER_AES_256_CBC, POLARSSL_MD_SHA1, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA1_C */
@@ -1462,7 +1462,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256, "TLS-RSA-PSK-WITH-CAMELLIA-128-CBC-SHA256",
       POLARSSL_CIPHER_CAMELLIA_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1470,7 +1470,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384, "TLS-RSA-PSK-WITH-CAMELLIA-256-CBC-SHA384",
       POLARSSL_CIPHER_CAMELLIA_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1500,7 +1500,7 @@
 #if defined(POLARSSL_SHA1_C)
     { TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, "TLS-RSA-PSK-WITH-3DES-EDE-CBC-SHA",
       POLARSSL_CIPHER_DES_EDE3_CBC, POLARSSL_MD_SHA1, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA1_C */
@@ -1511,7 +1511,7 @@
 #if defined(POLARSSL_SHA1_C)
     { TLS_RSA_PSK_WITH_RC4_128_SHA, "TLS-RSA-PSK-WITH-RC4-128-SHA",
       POLARSSL_CIPHER_ARC4_128, POLARSSL_MD_SHA1, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA1_C */
@@ -1540,7 +1540,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_RSA_WITH_NULL_SHA256, "TLS-RSA-WITH-NULL-SHA256",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_RSA,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1558,7 +1558,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_PSK_WITH_NULL_SHA256, "TLS-PSK-WITH-NULL-SHA256",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1566,7 +1566,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_PSK_WITH_NULL_SHA384, "TLS-PSK-WITH-NULL-SHA384",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1584,7 +1584,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_DHE_PSK_WITH_NULL_SHA256, "TLS-DHE-PSK-WITH-NULL-SHA256",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1592,7 +1592,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_DHE_PSK_WITH_NULL_SHA384, "TLS-DHE-PSK-WITH-NULL-SHA384",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1628,7 +1628,7 @@
 #if defined(POLARSSL_SHA1_C)
     { TLS_RSA_PSK_WITH_NULL_SHA, "TLS-RSA-PSK-WITH-NULL-SHA",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA1, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif /* POLARSSL_SHA1_C */
@@ -1636,7 +1636,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_RSA_PSK_WITH_NULL_SHA256, "TLS-RSA-PSK-WITH-NULL-SHA256",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1644,7 +1644,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_RSA_PSK_WITH_NULL_SHA384, "TLS-RSA-PSK-WITH-NULL-SHA384",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
diff -ruN polarssl-1.3.8/library/ssl_cli.c polarssl-1.3.9/library/ssl_cli.c
--- polarssl-1.3.8/library/ssl_cli.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/ssl_cli.c	2014-10-20 13:59:19.000000000 +0200
@@ -875,7 +875,7 @@
 {
     int ret, i, comp;
     size_t n;
-    size_t ext_len = 0;
+    size_t ext_len;
     unsigned char *buf, *ext;
     int renegotiation_info_seen = 0;
     int handshake_failure = 0;
@@ -902,6 +902,22 @@
 
     if( ssl->in_msgtype != SSL_MSG_HANDSHAKE )
     {
+        if( ssl->renegotiation == SSL_RENEGOTIATION )
+        {
+            ssl->renego_records_seen++;
+
+            if( ssl->renego_max_records >= 0 &&
+                ssl->renego_records_seen > ssl->renego_max_records )
+            {
+                SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
+                                    "but not honored by server" ) );
+                return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
+            }
+
+            SSL_DEBUG_MSG( 1, ( "non-handshake message during renego" ) );
+            return( POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );
+        }
+
         SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
         return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
     }
@@ -965,7 +981,7 @@
      *   42+n . 43+n  extensions length
      *   44+n . 44+n+m extensions
      */
-    if( ssl->in_hslen > 42 + n )
+    if( ssl->in_hslen > 43 + n )
     {
         ext_len = ( ( buf[42 + n] <<  8 )
                   | ( buf[43 + n]       ) );
@@ -977,6 +993,15 @@
             return( POLARSSL_ERR_SSL_BAD_HS_SERVER_HELLO );
         }
     }
+    else if( ssl->in_hslen == 42 + n )
+    {
+        ext_len = 0;
+    }
+    else
+    {
+        SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
+        return( POLARSSL_ERR_SSL_BAD_HS_SERVER_HELLO );
+    }
 
     i = ( buf[39 + n] << 8 ) | buf[40 + n];
     comp = buf[41 + n];
diff -ruN polarssl-1.3.8/library/ssl_srv.c polarssl-1.3.9/library/ssl_srv.c
--- polarssl-1.3.8/library/ssl_srv.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/ssl_srv.c	2014-10-20 13:59:19.000000000 +0200
@@ -494,11 +494,16 @@
         for( p = buf + 2; p < end; p += 2 ) {
             if( *md_cur == (int) ssl_md_alg_from_hash( p[0] ) ) {
                 ssl->handshake->sig_alg = p[0];
-                break;
+                goto have_sig_alg;
             }
         }
     }
 
+    /* Some key echanges do not need signatures at all */
+    SSL_DEBUG_MSG( 3, ( "no signature_algorithm in common" ) );
+    return( 0 );
+
+have_sig_alg:
     SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d",
                    ssl->handshake->sig_alg ) );
 
@@ -521,6 +526,13 @@
     {
         SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
         return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
+    }
+
+    /* Should never happen unless client duplicates the extension */
+    if( ssl->handshake->curves != NULL )
+    {
+        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
+        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
     }
 
     /* Don't allow our peer to make us allocate too much memory,
diff -ruN polarssl-1.3.8/library/ssl_tls.c polarssl-1.3.9/library/ssl_tls.c
--- polarssl-1.3.8/library/ssl_tls.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/ssl_tls.c	2014-10-20 13:59:19.000000000 +0200
@@ -991,18 +991,15 @@
 {
     unsigned char header[11];
     unsigned char padding[48];
-    int padlen = 0;
+    int padlen;
     int md_size = md_get_size( md_ctx->md_info );
     int md_type = md_get_type( md_ctx->md_info );
 
+    /* Only MD5 and SHA-1 supported */
     if( md_type == POLARSSL_MD_MD5 )
         padlen = 48;
-    else if( md_type == POLARSSL_MD_SHA1 )
+    else
         padlen = 40;
-    else if( md_type == POLARSSL_MD_SHA256 )
-        padlen = 32;
-    else if( md_type == POLARSSL_MD_SHA384 )
-        padlen = 16;
 
     memcpy( header, ctr, 8 );
     header[ 8] = (unsigned char)  type;
@@ -2230,10 +2227,6 @@
         {
             SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
                            ssl->in_msg[1] ) );
-            /**
-             * Subtract from error code as ssl->in_msg[1] is 7-bit positive
-             * error identifier.
-             */
             return( POLARSSL_ERR_SSL_FATAL_ALERT_MESSAGE );
         }
 
@@ -3345,7 +3338,7 @@
             (ssl_session *) polarssl_malloc( sizeof(ssl_session) );
     }
 
-    if( ssl->handshake == NULL)
+    if( ssl->handshake == NULL )
     {
         ssl->handshake = (ssl_handshake_params *)
             polarssl_malloc( sizeof(ssl_handshake_params) );
@@ -4174,8 +4167,6 @@
         return( ret );
     }
 
-    ssl->renegotiation = SSL_RENEGOTIATION_PENDING;
-
     SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
 
     return( 0 );
@@ -4184,10 +4175,10 @@
 
 /*
  * Actually renegotiate current connection, triggered by either:
- * - calling ssl_renegotiate() on client,
- * - receiving a HelloRequest on client during ssl_read(),
- * - receiving any handshake message on server during ssl_read() after the
- *   initial handshake is completed
+ * - any side: calling ssl_renegotiate(),
+ * - client: receiving a HelloRequest during ssl_read(),
+ * - server: receiving any handshake message on server during ssl_read() after
+ *   the initial handshake is completed.
  * If the handshake doesn't complete due to waiting for I/O, it will continue
  * during the next calls to ssl_renegotiate() or ssl_read() respectively.
  */
@@ -4229,6 +4220,12 @@
         if( ssl->state != SSL_HANDSHAKE_OVER )
             return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
 
+        ssl->renegotiation = SSL_RENEGOTIATION_PENDING;
+
+        /* Did we already try/start sending HelloRequest? */
+        if( ssl->out_left != 0 )
+            return( ssl_flush_output( ssl ) );
+
         return( ssl_write_hello_request( ssl ) );
     }
 #endif /* POLARSSL_SSL_SRV_C */
@@ -4267,14 +4264,19 @@
  */
 int ssl_read( ssl_context *ssl, unsigned char *buf, size_t len )
 {
-    int ret;
+    int ret, record_read = 0;
     size_t n;
 
     SSL_DEBUG_MSG( 2, ( "=> read" ) );
 
     if( ssl->state != SSL_HANDSHAKE_OVER )
     {
-        if( ( ret = ssl_handshake( ssl ) ) != 0 )
+        ret = ssl_handshake( ssl );
+        if( ret == POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO )
+        {
+            record_read = 1;
+        }
+        else if( ret != 0 )
         {
             SSL_DEBUG_RET( 1, "ssl_handshake", ret );
             return( ret );
@@ -4283,13 +4285,16 @@
 
     if( ssl->in_offt == NULL )
     {
-        if( ( ret = ssl_read_record( ssl ) ) != 0 )
+        if( ! record_read )
         {
-            if( ret == POLARSSL_ERR_SSL_CONN_EOF )
-                return( 0 );
+            if( ( ret = ssl_read_record( ssl ) ) != 0 )
+            {
+                if( ret == POLARSSL_ERR_SSL_CONN_EOF )
+                    return( 0 );
 
-            SSL_DEBUG_RET( 1, "ssl_read_record", ret );
-            return( ret );
+                SSL_DEBUG_RET( 1, "ssl_read_record", ret );
+                return( ret );
+            }
         }
 
         if( ssl->in_msglen  == 0 &&
@@ -4359,14 +4364,22 @@
             }
             else
             {
-                if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
+                ret = ssl_start_renegotiation( ssl );
+                if( ret == POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO )
+                {
+                    record_read = 1;
+                }
+                else if( ret != 0 )
                 {
                     SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
                     return( ret );
                 }
+            }
 
+            /* If a non-handshake record was read during renego, fallthrough,
+             * else tell the user they should call ssl_read() again */
+            if( ! record_read )
                 return( POLARSSL_ERR_NET_WANT_READ );
-            }
         }
         else if( ssl->renegotiation == SSL_RENEGOTIATION_PENDING )
         {
@@ -4380,7 +4393,15 @@
                 return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
             }
         }
-        else if( ssl->in_msgtype != SSL_MSG_APPLICATION_DATA )
+
+        /* Fatal and closure alerts handled by ssl_read_record() */
+        if( ssl->in_msgtype == SSL_MSG_ALERT )
+        {
+            SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
+            return( POLARSSL_ERR_NET_WANT_READ );
+        }
+
+        if( ssl->in_msgtype != SSL_MSG_APPLICATION_DATA )
         {
             SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
             return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
@@ -4480,11 +4501,8 @@
 
     SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
 
-    if( ( ret = ssl_flush_output( ssl ) ) != 0 )
-    {
-        SSL_DEBUG_RET( 1, "ssl_flush_output", ret );
-        return( ret );
-    }
+    if( ssl->out_left != 0 )
+        return( ssl_flush_output( ssl ) );
 
     if( ssl->state == SSL_HANDSHAKE_OVER )
     {
@@ -4492,13 +4510,14 @@
                         SSL_ALERT_LEVEL_WARNING,
                         SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
         {
+            SSL_DEBUG_RET( 1, "ssl_send_alert_message", ret );
             return( ret );
         }
     }
 
     SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
 
-    return( ret );
+    return( 0 );
 }
 
 void ssl_transform_free( ssl_transform *transform )
diff -ruN polarssl-1.3.8/library/timing.c polarssl-1.3.9/library/timing.c
--- polarssl-1.3.8/library/timing.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/timing.c	2014-10-20 13:59:19.000000000 +0200
@@ -283,15 +283,16 @@
 
     gettimeofday( &offset, NULL );
 
-    delta = ( offset.tv_sec  - t->start.tv_sec  ) * 1000
-          + ( offset.tv_usec - t->start.tv_usec ) / 1000;
-
     if( reset )
     {
         t->start.tv_sec  = offset.tv_sec;
         t->start.tv_usec = offset.tv_usec;
+        return( 0 );
     }
 
+    delta = ( offset.tv_sec  - t->start.tv_sec  ) * 1000
+          + ( offset.tv_usec - t->start.tv_usec ) / 1000;
+
     return( delta );
 }
 
@@ -332,7 +333,7 @@
 #if defined(POLARSSL_SELF_TEST)
 
 /* To test net_usleep against our functions */
-#if defined(POLARSSL_NET_C)
+#if defined(POLARSSL_NET_C) && defined(POLARSSL_HAVE_TIME)
 #include "polarssl/net.h"
 #endif
 
@@ -378,7 +379,7 @@
     {
         (void) get_timer( &hires, 1 );
 
-        m_sleep( 500 * secs );
+        m_sleep( (int)( 500 * secs ) );
 
         millisecs = get_timer( &hires, 0 );
 
@@ -401,7 +402,7 @@
     {
         (void) get_timer( &hires, 1 );
 
-        set_alarm( secs );
+        set_alarm( (int) secs );
         while( !alarmed )
             ;
 
@@ -464,7 +465,7 @@
     if( verbose != 0 )
         polarssl_printf( "passed\n" );
 
-#if defined(POLARSSL_NET_C)
+#if defined(POLARSSL_NET_C) && defined(POLARSSL_HAVE_TIME)
     if( verbose != 0 )
         polarssl_printf( "  TIMING test #4 (net_usleep/ get_timer): " );
 
diff -ruN polarssl-1.3.8/library/x509.c polarssl-1.3.9/library/x509.c
--- polarssl-1.3.8/library/x509.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/x509.c	2014-10-20 13:59:19.000000000 +0200
@@ -409,58 +409,47 @@
  *  AttributeType ::= OBJECT IDENTIFIER
  *
  *  AttributeValue ::= ANY DEFINED BY AttributeType
+ *
+ *  We restrict RelativeDistinguishedName to be a set of 1 element. This is
+ *  the most common case, and our x509_name structure currently can't handle
+ *  more than that.
  */
 int x509_get_name( unsigned char **p, const unsigned char *end,
                    x509_name *cur )
 {
     int ret;
-    size_t len;
-    const unsigned char *end2;
-    x509_name *use;
+    size_t set_len;
+    const unsigned char *end_set;
 
-    if( ( ret = asn1_get_tag( p, end, &len,
+    /*
+     * parse first SET, restricted to 1 element
+     */
+    if( ( ret = asn1_get_tag( p, end, &set_len,
             ASN1_CONSTRUCTED | ASN1_SET ) ) != 0 )
         return( POLARSSL_ERR_X509_INVALID_NAME + ret );
 
-    end2 = end;
-    end  = *p + len;
-    use = cur;
-
-    do
-    {
-        if( ( ret = x509_get_attr_type_value( p, end, use ) ) != 0 )
-            return( ret );
+    end_set  = *p + set_len;
 
-        if( *p != end )
-        {
-            use->next = (x509_name *) polarssl_malloc(
-                    sizeof( x509_name ) );
-
-            if( use->next == NULL )
-                return( POLARSSL_ERR_X509_MALLOC_FAILED );
+    if( ( ret = x509_get_attr_type_value( p, end_set, cur ) ) != 0 )
+        return( ret );
 
-            memset( use->next, 0, sizeof( x509_name ) );
-
-            use = use->next;
-        }
-    }
-    while( *p != end );
+    if( *p != end_set )
+        return( POLARSSL_ERR_X509_FEATURE_UNAVAILABLE );
 
     /*
      * recurse until end of SEQUENCE is reached
      */
-    if( *p == end2 )
+    if( *p == end )
         return( 0 );
 
-    cur->next = (x509_name *) polarssl_malloc(
-         sizeof( x509_name ) );
+    cur->next = (x509_name *) polarssl_malloc( sizeof( x509_name ) );
 
     if( cur->next == NULL )
         return( POLARSSL_ERR_X509_MALLOC_FAILED );
 
     memset( cur->next, 0, sizeof( x509_name ) );
 
-    return( x509_get_name( p, end2, cur->next ) );
+    return( x509_get_name( p, end, cur->next ) );
 }
 
 /*
@@ -750,7 +739,7 @@
     unsigned char c;
     const x509_name *name;
     const char *short_name = NULL;
-    char s[128], *p;
+    char s[X509_MAX_DN_NAME_SIZE], *p;
 
     memset( s, 0, sizeof( s ) );
 
@@ -876,7 +865,7 @@
     ((void) sig_opts);
 #endif /* POLARSSL_X509_RSASSA_PSS_SUPPORT */
 
-    return( (int) size - n );
+    return( (int)( size - n ) );
 }
 
 /*
diff -ruN polarssl-1.3.8/library/x509_create.c polarssl-1.3.9/library/x509_create.c
--- polarssl-1.3.8/library/x509_create.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/x509_create.c	2014-10-20 13:59:19.000000000 +0200
@@ -100,6 +100,8 @@
     const char *end = s + strlen( s );
     const char *oid = NULL;
     int in_tag = 1;
+    char data[X509_MAX_DN_NAME_SIZE];
+    char *d = data;
 
     /* Clear existing chain if present */
     asn1_free_named_data_list( head );
@@ -116,13 +118,25 @@
 
             s = c + 1;
             in_tag = 0;
+            d = data;
         }
 
-        if( !in_tag && ( *c == ',' || c == end ) )
+        if( !in_tag && *c == '\\' && c != end )
+        {
+            c++;
+
+            /* Check for valid escaped characters */
+            if( c == end || *c != ',' )
+            {
+                ret = POLARSSL_ERR_X509_INVALID_NAME;
+                goto exit;
+            }
+        }
+        else if( !in_tag && ( *c == ',' || c == end ) )
         {
             if( asn1_store_named_data( head, oid, strlen( oid ),
-                                       (unsigned char *) s,
-                                       c - s ) == NULL )
+                                       (unsigned char *) data,
+                                       d - data ) == NULL )
             {
                 return( POLARSSL_ERR_X509_MALLOC_FAILED );
             }
@@ -133,6 +147,18 @@
             s = c + 1;
             in_tag = 1;
         }
+
+        if( !in_tag && s != c + 1 )
+        {
+            *(d++) = *c;
+
+            if( d - data == X509_MAX_DN_NAME_SIZE )
+            {
+                ret = POLARSSL_ERR_X509_INVALID_NAME;
+                goto exit;
+            }
+        }
+
         c++;
     }
 
diff -ruN polarssl-1.3.8/library/x509_crt.c polarssl-1.3.9/library/x509_crt.c
--- polarssl-1.3.8/library/x509_crt.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/x509_crt.c	2014-10-20 13:59:19.000000000 +0200
@@ -898,6 +898,7 @@
                 if( first_error == 0 )
                     first_error = ret;
 
+                total_failed++;
                 continue;
             }
             else
@@ -1528,8 +1529,10 @@
 }
 #endif /* POLARSSL_X509_CRL_PARSE_C */
 
-// Equal == 0, inequal == 1
-static int x509_name_cmp( const void *s1, const void *s2, size_t len )
+/*
+ * Like memcmp, but case-insensitive and always returns -1 if different
+ */
+static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
 {
     size_t i;
     unsigned char diff;
@@ -1549,12 +1552,16 @@
             continue;
         }
 
-        return( 1 );
+        return( -1 );
     }
 
     return( 0 );
 }
 
+/*
+ * Return 1 if match, 0 if not
+ * TODO: inverted return value!
+ */
 static int x509_wildcard_verify( const char *cn, x509_buf *name )
 {
     size_t i;
@@ -1576,7 +1583,7 @@
         return( 0 );
 
     if( cn_len - cn_idx == name->len - 1 &&
-        x509_name_cmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
+        x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
     {
         return( 1 );
     }
@@ -1585,6 +1592,65 @@
 }
 
 /*
+ * Compare two X.509 strings, case-insensitive, and allowing for some encoding
+ * variations (but not all).
+ *
+ * Return 0 if equal, -1 otherwise.
+ */
+static int x509_string_cmp( const x509_buf *a, const x509_buf *b )
+{
+    if( a->tag == b->tag &&
+        a->len == b->len &&
+        memcmp( a->p, b->p, b->len ) == 0 )
+    {
+        return( 0 );
+    }
+
+    if( ( a->tag == ASN1_UTF8_STRING || a->tag == ASN1_PRINTABLE_STRING ) &&
+        ( b->tag == ASN1_UTF8_STRING || b->tag == ASN1_PRINTABLE_STRING ) &&
+        a->len == b->len &&
+        x509_memcasecmp( a->p, b->p, b->len ) == 0 )
+    {
+        return( 0 );
+    }
+
+    return( -1 );
+}
+
+/*
+ * Compare two X.509 Names (aka rdnSequence).
+ *
+ * See RFC 5280 section 7.1, though we don't implement the whole algorithm:
+ * we sometimes return unequal when the full algorithm would return equal,
+ * but never the other way. (In particular, we don't do Unicode normalisation
+ * or space folding.)
+ *
+ * Return 0 if equal, -1 otherwise.
+ */
+static int x509_name_cmp( const x509_name *a, const x509_name *b )
+{
+    if( a == NULL && b == NULL )
+        return( 0 );
+
+    if( a == NULL || b == NULL )
+        return( -1 );
+
+    /* type */
+    if( a->oid.tag != b->oid.tag ||
+        a->oid.len != b->oid.len ||
+        memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
+    {
+        return( -1 );
+    }
+
+    /* value */
+    if( x509_string_cmp( &a->val, &b->val ) != 0 )
+        return( -1 );
+
+    return( x509_name_cmp( a->next, b->next ) );
+}
+
+/*
  * Check if 'parent' is a suitable parent (signing CA) for 'child'.
  * Return 0 if yes, -1 if not.
  *
@@ -1598,12 +1664,8 @@
     int need_ca_bit;
 
     /* Parent must be the issuer */
-    if( child->issuer_raw.len != parent->subject_raw.len ||
-        memcmp( child->issuer_raw.p, parent->subject_raw.p,
-                child->issuer_raw.len ) != 0 )
-    {
+    if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )
         return( -1 );
-    }
 
     /* Parent must have the basicConstraints CA bit set as a general rule */
     need_ca_bit = 1;
@@ -1858,7 +1920,7 @@
             while( cur != NULL )
             {
                 if( cur->buf.len == cn_len &&
-                    x509_name_cmp( cn, cur->buf.p, cn_len ) == 0 )
+                    x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )
                     break;
 
                 if( cur->buf.len > 2 &&
@@ -1879,7 +1941,7 @@
                 if( OID_CMP( OID_AT_CN, &name->oid ) )
                 {
                     if( name->val.len == cn_len &&
-                        x509_name_cmp( name->val.p, cn, cn_len ) == 0 )
+                        x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )
                         break;
 
                     if( name->val.len > 2 &&
diff -ruN polarssl-1.3.8/programs/pkey/gen_key.c polarssl-1.3.9/programs/pkey/gen_key.c
--- polarssl-1.3.8/programs/pkey/gen_key.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/pkey/gen_key.c	2014-10-20 13:59:19.000000000 +0200
@@ -64,11 +64,16 @@
 
 #define DFL_TYPE                POLARSSL_PK_RSA
 #define DFL_RSA_KEYSIZE         4096
-#define DFL_EC_CURVE            ecp_curve_list()->grp_id
 #define DFL_FILENAME            "keyfile.key"
 #define DFL_FORMAT              FORMAT_PEM
 #define DFL_USE_DEV_RANDOM      0
 
+#if defined(POLARSSL_ECP_C)
+#define DFL_EC_CURVE            ecp_curve_list()->grp_id
+#else
+#define DFL_EC_CURVE            0
+#endif
+
 /*
  * global options
  */
@@ -248,15 +253,18 @@
         else if( strcmp( p, "rsa_keysize" ) == 0 )
         {
             opt.rsa_keysize = atoi( q );
-            if( opt.rsa_keysize < 1024 || opt.rsa_keysize > 8192 )
+            if( opt.rsa_keysize < 1024 ||
+                opt.rsa_keysize > POLARSSL_MPI_MAX_BITS )
                 goto usage;
         }
+#if defined(POLARSSL_ECP_C)
         else if( strcmp( p, "ec_curve" ) == 0 )
         {
             if( ( curve_info = ecp_curve_info_from_name( q ) ) == NULL )
                 goto usage;
             opt.ec_curve = curve_info->grp_id;
         }
+#endif
         else if( strcmp( p, "filename" ) == 0 )
             opt.filename = q;
         else if( strcmp( p, "use_dev_random" ) == 0 )
@@ -373,7 +381,18 @@
 #endif
         printf("  ! key type not supported\n");
 
-    write_private_key( &key, opt.filename );
+    /*
+     * 1.3 Export key
+     */
+    printf( "  . Writing key to file..." );
+
+    if( ( ret = write_private_key( &key, opt.filename ) ) != 0 )
+    {
+        printf( " failed\n" );
+        goto exit;
+    }
+
+    printf( " ok\n" );
 
 exit:
 
diff -ruN polarssl-1.3.8/programs/ssl/ssl_client2.c polarssl-1.3.9/programs/ssl/ssl_client2.c
--- polarssl-1.3.8/programs/ssl/ssl_client2.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/ssl/ssl_client2.c	2014-10-20 13:59:19.000000000 +0200
@@ -85,6 +85,7 @@
 #define DFL_RENEGOTIATION       SSL_RENEGOTIATION_DISABLED
 #define DFL_ALLOW_LEGACY        SSL_LEGACY_NO_RENEGOTIATION
 #define DFL_RENEGOTIATE         0
+#define DFL_EXCHANGES           1
 #define DFL_MIN_VERSION         -1
 #define DFL_MAX_VERSION         -1
 #define DFL_AUTH_MODE           SSL_VERIFY_REQUIRED
@@ -120,6 +121,8 @@
     int renegotiation;          /* enable / disable renegotiation           */
     int allow_legacy;           /* allow legacy renegotiation               */
     int renegotiate;            /* attempt renegotiation?                   */
+    int renego_delay;           /* delay before enforcing renegotiation     */
+    int exchanges;              /* number of data exchanges                 */
     int min_version;            /* minimum protocol version accepted        */
     int max_version;            /* maximum protocol version accepted        */
     int auth_mode;              /* verify mode for connection               */
@@ -303,6 +306,7 @@
     "    renegotiation=%%d    default: 1 (enabled)\n"       \
     "    allow_legacy=%%d     default: 0 (disabled)\n"      \
     "    renegotiate=%%d      default: 0 (disabled)\n"      \
+    "    exchanges=%%d        default: 1\n"                 \
     "    reconnect=%%d        default: 0 (disabled)\n"      \
     USAGE_TIME                                              \
     USAGE_TICKETS                                           \
@@ -322,7 +326,7 @@
 
 int main( int argc, char *argv[] )
 {
-    int ret = 0, len, server_fd, i, written, frags;
+    int ret = 0, len, tail_len, server_fd, i, written, frags;
     unsigned char buf[SSL_MAX_CONTENT_LEN + 1];
 #if defined(POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED)
     unsigned char psk[POLARSSL_PSK_MAX_LEN];
@@ -399,6 +403,7 @@
     opt.renegotiation       = DFL_RENEGOTIATION;
     opt.allow_legacy        = DFL_ALLOW_LEGACY;
     opt.renegotiate         = DFL_RENEGOTIATE;
+    opt.exchanges           = DFL_EXCHANGES;
     opt.min_version         = DFL_MIN_VERSION;
     opt.max_version         = DFL_MAX_VERSION;
     opt.auth_mode           = DFL_AUTH_MODE;
@@ -486,6 +491,12 @@
             if( opt.renegotiate < 0 || opt.renegotiate > 1 )
                 goto usage;
         }
+        else if( strcmp( p, "exchanges" ) == 0 )
+        {
+            opt.exchanges = atoi( q );
+            if( opt.exchanges < 1 )
+                goto usage;
+        }
         else if( strcmp( p, "reconnect" ) == 0 )
         {
             opt.reconnect = atoi( q );
@@ -1055,27 +1066,21 @@
     printf( "  > Write to server:" );
     fflush( stdout );
 
-    if( strcmp( opt.request_page, "SERVERQUIT" ) == 0 )
-        len = sprintf( (char *) buf, "%s", opt.request_page );
-    else
-    {
-        size_t tail_len = strlen( GET_REQUEST_END );
-
-        len = snprintf( (char *) buf, sizeof(buf) - 1, GET_REQUEST,
-                        opt.request_page );
+    len = snprintf( (char *) buf, sizeof(buf) - 1, GET_REQUEST,
+                    opt.request_page );
+    tail_len = strlen( GET_REQUEST_END );
 
-        /* Add padding to GET request to reach opt.request_size in length */
-        if( opt.request_size != DFL_REQUEST_SIZE &&
-            len + tail_len < (size_t) opt.request_size )
-        {
-            memset( buf + len, 'A', opt.request_size - len - tail_len );
-            len += opt.request_size - len - tail_len;
-        }
-
-        strncpy( (char *) buf + len, GET_REQUEST_END, sizeof(buf) - len - 1 );
-        len += tail_len;
+    /* Add padding to GET request to reach opt.request_size in length */
+    if( opt.request_size != DFL_REQUEST_SIZE &&
+        len + tail_len < opt.request_size )
+    {
+        memset( buf + len, 'A', opt.request_size - len - tail_len );
+        len += opt.request_size - len - tail_len;
     }
 
+    strncpy( (char *) buf + len, GET_REQUEST_END, sizeof(buf) - len - 1 );
+    len += tail_len;
+
     /* Truncate if request size is smaller than the "natural" size */
     if( opt.request_size != DFL_REQUEST_SIZE &&
         len > opt.request_size )
@@ -1114,31 +1119,80 @@
         memset( buf, 0, sizeof( buf ) );
         ret = ssl_read( &ssl, buf, len );
 
-        if( ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE )
+        if( ret == POLARSSL_ERR_NET_WANT_READ ||
+            ret == POLARSSL_ERR_NET_WANT_WRITE )
             continue;
 
-        if( ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY )
-            break;
+        if( ret <= 0 )
+        {
+            switch( ret )
+            {
+                case POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY:
+                    printf( " connection was closed gracefully\n" );
+                    ret = 0;
+                    goto close_notify;
+
+                case 0:
+                case POLARSSL_ERR_NET_CONN_RESET:
+                    printf( " connection was reset by peer\n" );
+                    ret = 0;
+                    goto reconnect;
+
+                default:
+                    printf( " ssl_read returned -0x%x\n", -ret );
+                    goto exit;
+            }
+        }
+
+        len = ret;
+        buf[len] = '\0';
+        printf( " %d bytes read\n\n%s", len, (char *) buf );
 
-        if( ret < 0 )
+        /* End of message should be detected according to the syntax of the
+         * application protocol (eg HTTP), just use a dummy test here. */
+        if( ret > 0 && buf[len-1] == '\n' )
         {
-            printf( "failed\n  ! ssl_read returned -0x%x\n\n", -ret );
+            ret = 0;
             break;
         }
+    }
+    while( 1 );
 
-        if( ret == 0 )
+    /*
+     * 7b. Continue doing data exchanges?
+     */
+    if( --opt.exchanges > 0 )
+        goto send_request;
+
+    /*
+     * 8. Done, cleanly close the connection
+     */
+close_notify:
+    printf( "  . Closing the connection..." );
+
+    while( ( ret = ssl_close_notify( &ssl ) ) < 0 )
+    {
+        if( ret == POLARSSL_ERR_NET_CONN_RESET )
         {
-            printf("\n\nEOF\n\n");
-            ssl_close_notify( &ssl );
-            break;
+            printf( " ok (already closed by peer)\n" );
+            ret = 0;
+            goto reconnect;
         }
 
-        len = ret;
-        buf[len] = '\0';
-        printf( " %d bytes read\n\n%s", len, (char *) buf );
+        if( ret != POLARSSL_ERR_NET_WANT_READ &&
+            ret != POLARSSL_ERR_NET_WANT_WRITE )
+        {
+            printf( " failed\n  ! ssl_close_notify returned %d\n\n", ret );
+            goto reconnect;
+        }
     }
-    while( 1 );
 
+    printf( " ok\n" );
+
+    /*
+     * 9. Reconnect?
+     */
+reconnect:
     if( opt.reconnect != 0 )
     {
         --opt.reconnect;
@@ -1187,10 +1241,10 @@
         goto send_request;
     }
 
+    /*
+     * Cleanup and exit
+     */
 exit:
-    if( ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY )
-        ret = 0;
-
 #ifdef POLARSSL_ERROR_C
     if( ret != 0 )
     {
@@ -1202,6 +1256,7 @@
 
     if( server_fd )
         net_close( server_fd );
+
 #if defined(POLARSSL_X509_CRT_PARSE_C)
     x509_crt_free( &clicert );
     x509_crt_free( &cacert );
@@ -1212,8 +1267,6 @@
     ctr_drbg_free( &ctr_drbg );
     entropy_free( &entropy );
 
-    memset( &ssl, 0, sizeof( ssl ) );
-
 #if defined(_WIN32)
     printf( "  + Press Enter to exit this program.\n" );
     fflush( stdout ); getchar();
diff -ruN polarssl-1.3.8/programs/ssl/ssl_mail_client.c polarssl-1.3.9/programs/ssl/ssl_mail_client.c
--- polarssl-1.3.8/programs/ssl/ssl_mail_client.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/ssl/ssl_mail_client.c	2014-10-20 13:59:19.000000000 +0200
@@ -375,6 +375,7 @@
      */
     server_fd = 0;
     memset( &ssl, 0, sizeof( ssl_context ) );
+    memset( &buf, 0, sizeof( buf ) );
     x509_crt_init( &cacert );
     x509_crt_init( &clicert );
     pk_init( &pkey );
@@ -718,8 +719,13 @@
         fflush( stdout );
 
         n = sizeof( buf );
-        len = base64_encode( base, &n, (const unsigned char *) opt.user_name,
+        ret = base64_encode( base, &n, (const unsigned char *) opt.user_name,
                              strlen( opt.user_name ) );
+
+        if( ret != 0 ) {
+            printf( " failed\n  ! base64_encode returned %d\n\n", ret );
+            goto exit;
+        }
         len = sprintf( (char *) buf, "%s\r\n", base );
         ret = write_ssl_and_get_response( &ssl, buf, len );
         if( ret < 300 || ret > 399 )
@@ -733,8 +739,13 @@
         printf( "  > Write password to server: %s", opt.user_pwd );
         fflush( stdout );
 
-        len = base64_encode( base, &n, (const unsigned char *) opt.user_pwd,
+        ret = base64_encode( base, &n, (const unsigned char *) opt.user_pwd,
                              strlen( opt.user_pwd ) );
+
+        if( ret != 0 ) {
+            printf( " failed\n  ! base64_encode returned %d\n\n", ret );
+            goto exit;
+        }
         len = sprintf( (char *) buf, "%s\r\n", base );
         ret = write_ssl_and_get_response( &ssl, buf, len );
         if( ret < 200 || ret > 399 )
diff -ruN polarssl-1.3.8/programs/ssl/ssl_pthread_server.c polarssl-1.3.9/programs/ssl/ssl_pthread_server.c
--- polarssl-1.3.8/programs/ssl/ssl_pthread_server.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/ssl/ssl_pthread_server.c	2014-10-20 13:59:19.000000000 +0200
@@ -129,6 +129,10 @@
     ssl_context ssl;
     ctr_drbg_context ctr_drbg;
 
+    /* Make sure memory references are valid */
+    memset( &ssl, 0, sizeof( ssl_context ) );
+    memset( &ctr_drbg, 0, sizeof( ctr_drbg_context ) );
+
     snprintf( pers, sizeof(pers), "SSL Pthread Thread %d", thread_id );
     printf( "  [ #%d ]  Client FD %d\n", thread_id, client_fd );
     printf( "  [ #%d ]  Seeding the random number generator...\n", thread_id );
@@ -176,7 +180,7 @@
     if( ( ret = ssl_set_own_cert( &ssl, thread_info->server_cert, thread_info->server_key ) ) != 0 )
     {
         printf( " failed\n  ! ssl_set_own_cert returned %d\n\n", ret );
-        goto exit;
+        goto thread_exit;
     }
 
     printf( "  [ #%d ]  ok\n", thread_id );
@@ -236,8 +240,6 @@
                             thread_id, -ret );
                     goto thread_exit;
             }
-
-            break;
         }
 
         len = ret;
@@ -308,6 +310,7 @@
 #endif
 
     net_close( client_fd );
+    ctr_drbg_free( &ctr_drbg );
     ssl_free( &ssl );
 
     thread_info->thread_complete = 1;
@@ -492,7 +495,6 @@
 #if defined(POLARSSL_SSL_CACHE_C)
     ssl_cache_free( &cache );
 #endif
-    ctr_drbg_free( &ctr_drbg );
     entropy_free( &entropy );
 
     polarssl_mutex_free( &debug_mutex );
diff -ruN polarssl-1.3.8/programs/ssl/ssl_server2.c polarssl-1.3.9/programs/ssl/ssl_server2.c
--- polarssl-1.3.8/programs/ssl/ssl_server2.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/ssl/ssl_server2.c	2014-10-20 13:59:19.000000000 +0200
@@ -64,6 +64,10 @@
 #include <stdlib.h>
 #include <stdio.h>
 
+#if !defined(_WIN32)
+#include <signal.h>
+#endif
+
 #include "polarssl/net.h"
 #include "polarssl/ssl.h"
 #include "polarssl/entropy.h"
@@ -100,6 +104,7 @@
 #define DFL_ALLOW_LEGACY        SSL_LEGACY_NO_RENEGOTIATION
 #define DFL_RENEGOTIATE         0
 #define DFL_RENEGO_DELAY        -2
+#define DFL_EXCHANGES           1
 #define DFL_MIN_VERSION         -1
 #define DFL_MAX_VERSION         -1
 #define DFL_AUTH_MODE           SSL_VERIFY_OPTIONAL
@@ -159,6 +164,7 @@
     int allow_legacy;           /* allow legacy renegotiation               */
     int renegotiate;            /* attempt renegotiation?                   */
     int renego_delay;           /* delay before enforcing renegotiation     */
+    int exchanges;              /* number of data exchanges                 */
     int min_version;            /* minimum protocol version accepted        */
     int max_version;            /* maximum protocol version accepted        */
     int auth_mode;              /* verify mode for connection               */
@@ -312,6 +318,8 @@
     "    renegotiation=%%d    default: 1 (enabled)\n"       \
     "    allow_legacy=%%d     default: 0 (disabled)\n"      \
     "    renegotiate=%%d      default: 0 (disabled)\n"      \
+    "    renego_delay=%%d     default: -2 (library default)\n" \
+    "    exchanges=%%d        default: 1\n"                 \
     USAGE_TICKETS                                           \
     USAGE_CACHE                                             \
     USAGE_MAX_FRAG_LEN                                      \
@@ -564,10 +572,22 @@
 }
 #endif /* POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED */
 
+static int listen_fd;
+
+/* Interruption handler to ensure clean exit (for valgrind testing) */
+#if !defined(_WIN32)
+static int received_sigterm = 0;
+void term_handler( int sig )
+{
+    ((void) sig);
+    received_sigterm = 1;
+    net_close( listen_fd ); /* causes net_accept() to abort */
+}
+#endif
+
 int main( int argc, char *argv[] )
 {
-    int ret = 0, len, written, frags;
-    int listen_fd;
+    int ret = 0, len, written, frags, exchanges;
     int client_fd = -1;
     int version_suites[4][2];
     unsigned char buf[IO_BUF_LEN];
@@ -635,6 +655,11 @@
     memset( (void *) alpn_list, 0, sizeof( alpn_list ) );
 #endif
 
+#if !defined(_WIN32)
+    /* Abort cleanly on SIGTERM */
+    signal( SIGTERM, term_handler );
+#endif
+
     if( argc == 0 )
     {
     usage:
@@ -676,6 +701,7 @@
     opt.allow_legacy        = DFL_ALLOW_LEGACY;
     opt.renegotiate         = DFL_RENEGOTIATE;
     opt.renego_delay        = DFL_RENEGO_DELAY;
+    opt.exchanges           = DFL_EXCHANGES;
     opt.min_version         = DFL_MIN_VERSION;
     opt.max_version         = DFL_MAX_VERSION;
     opt.auth_mode           = DFL_AUTH_MODE;
@@ -769,6 +795,12 @@
         {
             opt.renego_delay = atoi( q );
         }
+        else if( strcmp( p, "exchanges" ) == 0 )
+        {
+            opt.exchanges = atoi( q );
+            if( opt.exchanges < 1 )
+                goto usage;
+        }
         else if( strcmp( p, "min_version" ) == 0 )
         {
             if( strcmp( q, "ssl3" ) == 0 )
@@ -1377,6 +1409,15 @@
 
     if( ( ret = net_accept( listen_fd, &client_fd, NULL ) ) != 0 )
     {
+#if !defined(_WIN32)
+        if( received_sigterm )
+        {
+            printf( " interrupted by SIGTERM\n" );
+            ret = 0;
+            goto exit;
+        }
+#endif
+
         printf( " failed\n  ! net_accept returned -0x%x\n\n", -ret );
         goto exit;
     }
@@ -1461,6 +1502,8 @@
     }
 #endif /* POLARSSL_X509_CRT_PARSE_C */
 
+    exchanges = opt.exchanges;
+data_exchange:
     /*
      * 6. Read the HTTP Request
      */
@@ -1469,11 +1512,13 @@
 
     do
     {
+        int terminated = 0;
         len = sizeof( buf ) - 1;
         memset( buf, 0, sizeof( buf ) );
         ret = ssl_read( &ssl, buf, len );
 
-        if( ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE )
+        if( ret == POLARSSL_ERR_NET_WANT_READ ||
+            ret == POLARSSL_ERR_NET_WANT_WRITE )
             continue;
 
         if( ret <= 0 )
@@ -1482,18 +1527,18 @@
             {
                 case POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY:
                     printf( " connection was closed gracefully\n" );
-                    break;
+                    goto close_notify;
 
+                case 0:
                 case POLARSSL_ERR_NET_CONN_RESET:
                     printf( " connection was reset by peer\n" );
-                    break;
+                    ret = POLARSSL_ERR_NET_CONN_RESET;
+                    goto reset;
 
                 default:
                     printf( " ssl_read returned -0x%x\n", -ret );
-                    break;
+                    goto reset;
             }
-
-            break;
         }
 
         if( ssl_get_bytes_avail( &ssl ) == 0 )
@@ -1501,6 +1546,11 @@
             len = ret;
             buf[len] = '\0';
             printf( " %d bytes read\n\n%s\n", len, (char *) buf );
+
+            /* End of message should be detected according to the syntax of the
+             * application protocol (eg HTTP), just use a dummy test here. */
+            if( buf[len - 1] == '\n' )
+                terminated = 1;
         }
         else
         {
@@ -1515,7 +1565,7 @@
             {
                 printf( "  ! memory allocation failed\n" );
                 ret = 1;
-                goto exit;
+                goto reset;
             }
 
             memset( larger_buf, 0, ori_len + extra_len );
@@ -1528,7 +1578,7 @@
             {
                 printf( "  ! ssl_read failed on cached data\n" );
                 ret = 1;
-                goto exit;
+                goto reset;
             }
 
             larger_buf[ori_len + extra_len] = '\0';
@@ -1536,22 +1586,45 @@
                     ori_len + extra_len, ori_len, extra_len,
                     (char *) larger_buf );
 
+            /* End of message should be detected according to the syntax of the
+             * application protocol (eg HTTP), just use a dummy test here. */
+            if( larger_buf[ori_len + extra_len - 1] == '\n' )
+                terminated = 1;
+
             polarssl_free( larger_buf );
         }
 
-
-        if( memcmp( buf, "SERVERQUIT", 10 ) == 0 )
+        if( terminated )
         {
             ret = 0;
-            goto exit;
-        }
-
-        if( ret > 0 )
             break;
+        }
     }
     while( 1 );
 
     /*
+     * 7a. Request renegotiation while client is waiting for input from us.
+     * (only if we're going to exhange more data afterwards)
+     */
+    if( opt.renegotiate && exchanges > 1 )
+    {
+        printf( "  . Requestion renegotiation..." );
+        fflush( stdout );
+
+        while( ( ret = ssl_renegotiate( &ssl ) ) != 0 )
+        {
+            if( ret != POLARSSL_ERR_NET_WANT_READ &&
+                ret != POLARSSL_ERR_NET_WANT_WRITE )
+            {
+                printf( " failed\n  ! ssl_renegotiate returned %d\n\n", ret );
+                goto reset;
+            }
+        }
+
+        printf( " ok\n" );
+    }
+
+    /*
      * 7. Write the 200 Response
      */
     printf( "  > Write to client:" );
@@ -1573,7 +1646,7 @@
             if( ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE )
             {
                 printf( " failed\n  ! ssl_write returned %d\n\n", ret );
-                goto exit;
+                goto reset;
             }
         }
     }
@@ -1581,53 +1654,28 @@
     buf[written] = '\0';
     printf( " %d bytes written in %d fragments\n\n%s\n", written, frags, (char *) buf );
 
-    if( opt.renegotiate )
-    {
-        /*
-         * Request renegotiation (this must be done when the client is still
-         * waiting for input from our side).
-         */
-        printf( "  . Requestion renegotiation..." );
-        fflush( stdout );
-        while( ( ret = ssl_renegotiate( &ssl ) ) != 0 )
-        {
-            if( ret != POLARSSL_ERR_NET_WANT_READ &&
-                ret != POLARSSL_ERR_NET_WANT_WRITE )
-            {
-                printf( " failed\n  ! ssl_renegotiate returned %d\n\n", ret );
-                goto exit;
-            }
-        }
 
-        /*
-         * Should be a while loop, not an if, but here we're not actually
-         * expecting data from the client, and since we're running tests
-         * locally, we can just hope the handshake will finish the during the
-         * first call.
-         */
-        if( ( ret = ssl_read( &ssl, buf, 0 ) ) != 0 )
-        {
-            if( ret != POLARSSL_ERR_NET_WANT_READ &&
-                ret != POLARSSL_ERR_NET_WANT_WRITE )
-            {
-                printf( " failed\n  ! ssl_read returned %d\n\n", ret );
-
-                /* Unexpected message probably means client didn't renegotiate
-                 * as requested */
-                if( ret == POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE )
-                    goto reset;
-                else
-                    goto exit;
-            }
-        }
-
-        printf( " ok\n" );
-    }
+    /*
+     * 7b. Continue doing data exchanges?
+     */
+    if( --exchanges > 0 )
+        goto data_exchange;
 
+    /*
+     * 8. Done, cleanly close the connection
+     */
+close_notify:
     printf( "  . Closing the connection..." );
 
     while( ( ret = ssl_close_notify( &ssl ) ) < 0 )
     {
+        if( ret == POLARSSL_ERR_NET_CONN_RESET )
+        {
+            printf( " ok (already closed by peer)\n" );
+            ret = 0;
+            goto reset;
+        }
+
         if( ret != POLARSSL_ERR_NET_WANT_READ &&
             ret != POLARSSL_ERR_NET_WANT_WRITE )
         {
@@ -1637,12 +1685,12 @@
     }
 
     printf( " ok\n" );
-
-    ret = 0;
     goto reset;
 
+    /*
+     * Cleanup and exit
+     */
 exit:
-
 #ifdef POLARSSL_ERROR_C
     if( ret != 0 )
     {
diff -ruN polarssl-1.3.8/programs/test/ssl_test.c polarssl-1.3.9/programs/test/ssl_test.c
--- polarssl-1.3.8/programs/test/ssl_test.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/test/ssl_test.c	2014-10-20 13:59:19.000000000 +0200
@@ -142,7 +142,7 @@
  */
 static int ssl_test( struct options *opt )
 {
-    int ret, i;
+    int ret = 1, i;
     int client_fd = -1;
     int bytes_to_read;
     int bytes_to_write;
@@ -169,8 +169,6 @@
     x509_crt srvcert;
     pk_context pkey;
 
-    ret = 1;
-
     memset( &ssl, 0, sizeof(ssl_context) );
     entropy_init( &entropy );
     x509_crt_init( &srvcert );
diff -ruN polarssl-1.3.8/programs/util/pem2der.c polarssl-1.3.9/programs/util/pem2der.c
--- polarssl-1.3.8/programs/util/pem2der.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/util/pem2der.c	2014-10-20 13:59:19.000000000 +0200
@@ -134,6 +134,7 @@
     {
         fclose( f );
         free( *buf );
+        *buf = NULL;
         return( -1 );
     }
 
diff -ruN polarssl-1.3.8/scripts/config.pl polarssl-1.3.9/scripts/config.pl
--- polarssl-1.3.8/scripts/config.pl	1970-01-01 01:00:00.000000000 +0100
+++ polarssl-1.3.9/scripts/config.pl	2014-10-20 13:59:19.000000000 +0200
@@ -0,0 +1,112 @@
+#!/usr/bin/perl
+
+# Tune the configuration file
+
+use warnings;
+use strict;
+
+my $usage = <<EOU;
+$0 [-f <file>] full
+$0 [-f <file>] unset <name>
+$0 [-f <file>] set <name> [<value>]
+EOU
+
+# Things that shouldn't be enabled with "full".
+# Notes:
+# - POLARSSL_X509_ALLOW_EXTENSIONS_NON_V3 and
+#   POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION could be enabled if the
+#   respective tests were adapted
+my @excluded = qw(
+POLARSSL_HAVE_INT8
+POLARSSL_HAVE_INT16
+POLARSSL_HAVE_SSE2
+POLARSSL_PLATFORM_NO_STD_FUNCTIONS
+POLARSSL_ECP_DP_M221_ENABLED
+POLARSSL_ECP_DP_M383_ENABLED
+POLARSSL_ECP_DP_M511_ENABLED
+POLARSSL_NO_DEFAULT_ENTROPY_SOURCES
+POLARSSL_NO_PLATFORM_ENTROPY
+POLARSSL_SSL_HW_RECORD_ACCEL
+POLARSSL_X509_ALLOW_EXTENSIONS_NON_V3
+POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION
+POLARSSL_ZLIB_SUPPORT
+POLARSSL_PKCS11_C
+_ALT\s*$
+);
+
+my $config_file = "include/polarssl/config.h";
+
+# get -f option
+if (@ARGV >= 2 && $ARGV[0] eq "-f") {
+    shift; # -f
+    $config_file = shift;
+
+    -f $config_file or die "No such file: $config_file\n";
+} else {
+    if (! -f $config_file)  {
+        chdir '..' or die;
+        -d $config_file
+            or die "Without -f, must be run from root or scripts\n"
+    }
+}
+
+# get action
+die $usage unless @ARGV;
+my $action = shift;
+
+my ($name, $value);
+if ($action eq "full") {
+    # nothing to do
+} elsif ($action eq "unset") {
+    die $usage unless @ARGV;
+    $name = shift;
+} elsif ($action eq "set") {
+    die $usage unless @ARGV;
+    $name = shift;
+    $value = shift if @ARGV;
+} else {
+    die $usage;
+}
+die $usage if @ARGV;
+
+open my $config_read, '<', $config_file or die "read $config_file: $!\n";
+my @config_lines = <$config_read>;
+close $config_read;
+
+my $exclude_re = join '|', @excluded;
+
+open my $config_write, '>', $config_file or die "write $config_file: $!\n";
+
+my $done;
+for my $line (@config_lines) {
+    if ($action eq "full") {
+        if ($line =~ /name SECTION: Module configuration options/) {
+            $done = 1;
+        }
+
+        if (!$done && $line =~ m!^//\s?#define! && $line !~ /$exclude_re/) {
+            $line =~ s!^//!!;
+        }
+    } elsif ($action eq "unset") {
+        if (!$done && $line =~ /^\s*#define\s*$name/) {
+            $line = '//' . $line;
+            $done = 1;
+        }
+    } elsif (!$done && $action eq "set") {
+        if ($line =~ m!^(?://)?\s*#define\s*$name!) {
+            $line = "#define $name";
+            $line .= " $value" if defined $value && $value ne "";
+            $line .= "\n";
+            $done = 1;
+        }
+    }
+
+    print $config_write $line;
+}
+
+close $config_write;
+
+warn "configuration section not found" if ($action eq "full" && !$done);
+warn "$name not found" if ($action ne "full" && !$done);
+
+__END__
diff -ruN polarssl-1.3.8/tests/CMakeLists.txt polarssl-1.3.9/tests/CMakeLists.txt
--- polarssl-1.3.8/tests/CMakeLists.txt	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/CMakeLists.txt	2014-10-20 13:59:19.000000000 +0200
@@ -32,7 +32,7 @@
 set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unused-function -Wno-unused-value")
 set(CMAKE_C_FLAGS_CHECK "${CMAKE_C_FLAGS_CHECK} -Wno-unused-function -Wno-unused-value")
 if(CMAKE_COMPILER_IS_CLANG)
-    set(CMAKE_C_FLAGS_CHECK "${CMAKE_C_FLAGS_CHECK} -Wno-unreachable-code")
+    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unreachable-code")
 endif(CMAKE_COMPILER_IS_CLANG)
 
 add_test_suite(aes aes.ecb)
diff -ruN polarssl-1.3.8/tests/compat.sh polarssl-1.3.9/tests/compat.sh
--- polarssl-1.3.8/tests/compat.sh	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/compat.sh	2014-10-20 13:59:19.000000000 +0200
@@ -1,24 +1,21 @@
-#!/bin/bash
+#!/bin/sh
 
 # Test interop with OpenSSL and GnuTLS (and self-op while at it).
 #
 # Check each common ciphersuite, with each version, both ways (client/server),
 # with and without client authentication.
+#
+# Peer version requirements:
+# - OpenSSL 1.0.1e 11 Feb 2013 (probably since 1.0.1, tested with 1.0.1e)
+# - GnuTLS 3.2.15 (probably works since 3.2.12 but tested only with 3.2.15)
 
 set -u
 
-# test if those two are set in the environment before assigning defaults
-if [ -n "${GNUTLS_CLI:-}" -a -n "${GNUTLS_SERV:-}" ]; then
-    GNUTLS_AVAILABLE=1
-else
-    GNUTLS_AVAILABLE=0
-fi
-
 # initialise counters
-let "tests = 0"
-let "failed = 0"
-let "skipped = 0"
-let "srvmem = 0"
+TESTS=0
+FAILED=0
+SKIPPED=0
+SRVMEM=0
 
 # default commands, can be overriden by the environment
 : ${P_SRV:=../programs/ssl/ssl_server2}
@@ -27,6 +24,21 @@
 : ${GNUTLS_CLI:=gnutls-cli}
 : ${GNUTLS_SERV:=gnutls-serv}
 
+# do we have a recent enough GnuTLS?
+if ( which $GNUTLS_CLI && which $GNUTLS_SERV ) >/dev/null; then
+    eval $( $GNUTLS_CLI --version | head -n1 | sed 's/.* \([0-9]*\)\.\([0-9]\)*\.\([0-9]*\)$/MAJOR="\1" MINOR="\2" PATCH="\3"/' )
+    if [ $MAJOR -lt 3 -o \
+        \( $MAJOR -eq 3 -a $MINOR -lt 2 \) -o \
+        \( $MAJOR -eq 3 -a $MINOR -eq 2 -a $PATCH -lt 15 \) ]
+    then
+        PEER_GNUTLS=""
+    else
+        PEER_GNUTLS=" GnuTLS"
+    fi
+else
+    PEER_GNUTLS=""
+fi
+
 # default values for options
 MODES="ssl3 tls1 tls1_1 tls1_2"
 VERIFIES="NO YES"
@@ -35,12 +47,7 @@
 EXCLUDE='NULL\|DES-CBC-' # avoid plain DES but keep 3DES-EDE-CBC (PolarSSL), DES-CBC3 (OpenSSL)
 VERBOSE=""
 MEMCHECK=0
-# GnuTLS not enabled by default, 3.2.4 might not be available everywhere
-if [ "$GNUTLS_AVAILABLE" -gt 0 ]; then
-    PEERS="OpenSSL PolarSSL GnuTLS"
-else
-    PEERS="OpenSSL PolarSSL"
-fi
+PEERS="OpenSSL$PEER_GNUTLS PolarSSL"
 
 print_usage() {
     echo "Usage: $0"
@@ -51,7 +58,7 @@
     echo -e "  -t|--types\tWhich key exchange type to perform (Default: '$TYPES')"
     echo -e "  -V|--verify\tWhich verification modes to perform (Default: '$VERIFIES')"
     echo -e "  -p|--peers\tWhich peers to use (Default: '$PEERS')"
-    echo -e "            \tAlso available: GnuTLS (needs v3.2.4 or higher)"
+    echo -e "            \tAlso available: GnuTLS (needs v3.2.15 or higher)"
     echo -e "  -M|--memcheck\tCheck memory leaks and errors."
     echo -e "  -v|--verbose\tSet verbose output."
 }
@@ -202,7 +209,6 @@
                 TLS-RSA-WITH-RC4-128-MD5                \
                 TLS-RSA-WITH-NULL-MD5                   \
                 TLS-RSA-WITH-NULL-SHA                   \
-                TLS-RSA-WITH-NULL-SHA256                \
                 "
             G_CIPHERS="$G_CIPHERS                       \
                 +DHE-RSA:+AES-128-CBC:+SHA1             \
@@ -219,7 +225,6 @@
                 +RSA:+ARCFOUR-128:+MD5                  \
                 +RSA:+NULL:+MD5                         \
                 +RSA:+NULL:+SHA1                        \
-                +RSA:+NULL:+SHA256                      \
                 "
             O_CIPHERS="$O_CIPHERS               \
                 DHE-RSA-AES128-SHA              \
@@ -410,6 +415,15 @@
             ;;
 
         "RSA")
+            if [ "$MODE" != "ssl3" ];
+            then
+                P_CIPHERS="$P_CIPHERS                           \
+                    TLS-RSA-WITH-NULL-SHA256                    \
+                    "
+                G_CIPHERS="$G_CIPHERS                           \
+                    +RSA:+NULL:+SHA256                          \
+                    "
+            fi
             if [ "$MODE" = "tls1_2" ];
             then
                 P_CIPHERS="$P_CIPHERS                           \
@@ -444,30 +458,39 @@
             ;;
 
         "PSK")
-            # GnuTLS 3.2.11 (2014-02-13) requires TLS 1.x for most *PSK suites
+            P_CIPHERS="$P_CIPHERS                               \
+                TLS-DHE-PSK-WITH-3DES-EDE-CBC-SHA               \
+                TLS-DHE-PSK-WITH-AES-128-CBC-SHA                \
+                TLS-DHE-PSK-WITH-AES-256-CBC-SHA                \
+                TLS-DHE-PSK-WITH-RC4-128-SHA                    \
+                "
+            G_CIPHERS="$G_CIPHERS                               \
+                +DHE-PSK:+3DES-CBC:+SHA1                        \
+                +DHE-PSK:+AES-128-CBC:+SHA1                     \
+                +DHE-PSK:+AES-256-CBC:+SHA1                     \
+                +DHE-PSK:+ARCFOUR-128:+SHA1                     \
+                "
             if [ "$MODE" != "ssl3" ];
             then
                 P_CIPHERS="$P_CIPHERS                           \
                     TLS-ECDHE-PSK-WITH-AES-256-CBC-SHA          \
                     TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA          \
                     TLS-ECDHE-PSK-WITH-3DES-EDE-CBC-SHA         \
-                    TLS-DHE-PSK-WITH-3DES-EDE-CBC-SHA           \
-                    TLS-DHE-PSK-WITH-AES-128-CBC-SHA            \
-                    TLS-DHE-PSK-WITH-AES-256-CBC-SHA            \
+                    TLS-ECDHE-PSK-WITH-RC4-128-SHA              \
                     TLS-RSA-PSK-WITH-3DES-EDE-CBC-SHA           \
                     TLS-RSA-PSK-WITH-AES-256-CBC-SHA            \
                     TLS-RSA-PSK-WITH-AES-128-CBC-SHA            \
+                    TLS-RSA-PSK-WITH-RC4-128-SHA                \
                     "
                 G_CIPHERS="$G_CIPHERS                           \
-                    +ECDHE-PSK:+AES-256-CBC:+SHA1               \
-                    +ECDHE-PSK:+AES-128-CBC:+SHA1               \
                     +ECDHE-PSK:+3DES-CBC:+SHA1                  \
-                    +DHE-PSK:+3DES-CBC:+SHA1                    \
-                    +DHE-PSK:+AES-128-CBC:+SHA1                 \
-                    +DHE-PSK:+AES-256-CBC:+SHA1                 \
+                    +ECDHE-PSK:+AES-128-CBC:+SHA1               \
+                    +ECDHE-PSK:+AES-256-CBC:+SHA1               \
+                    +ECDHE-PSK:+ARCFOUR-128:+SHA1               \
                     +RSA-PSK:+3DES-CBC:+SHA1                    \
                     +RSA-PSK:+AES-256-CBC:+SHA1                 \
                     +RSA-PSK:+AES-128-CBC:+SHA1                 \
+                    +RSA-PSK:+ARCFOUR-128:+SHA1                 \
                     "
             fi
             if [ "$MODE" = "tls1_2" ];
@@ -595,17 +618,16 @@
             ;;
 
         "PSK")
+            # *PKS-NULL-SHA suites supported by GnuTLS 3.3.5 but not 3.2.15
             P_CIPHERS="$P_CIPHERS                        \
                 TLS-PSK-WITH-NULL-SHA                    \
-                TLS-DHE-PSK-WITH-RC4-128-SHA             \
                 TLS-DHE-PSK-WITH-NULL-SHA                \
-                TLS-RSA-PSK-WITH-RC4-128-SHA             \
                 "
             if [ "$MODE" != "ssl3" ];
             then
                 P_CIPHERS="$P_CIPHERS                    \
-                    TLS-ECDHE-PSK-WITH-RC4-128-SHA       \
                     TLS-ECDHE-PSK-WITH-NULL-SHA          \
+                    TLS-RSA-PSK-WITH-NULL-SHA            \
                     "
             fi
             if [ "$MODE" = "tls1_2" ];
@@ -764,40 +786,15 @@
     sleep 1
 }
 
-# terminate the running server (closing it cleanly if it is ours)
+# terminate the running server
 stop_server() {
-    case $SERVER_NAME in
-        [Pp]olar*)
-            # start watchdog in case SERVERQUIT fails
-            ( sleep 20; echo "SERVERQUIT TIMEOUT"; kill $MAIN_PID ) &
-            WATCHDOG_PID=$!
-
-            # we must force a PSK suite when in PSK mode (otherwise client
-            # auth will fail), so try every entry in $P_CIPHERS in turn (in
-            # case the first one is not implemented in this configuration)
-            for i in $P_CIPHERS; do
-                log "$P_CLI $P_CLIENT_ARGS request_page=SERVERQUIT auth_mode=none force_ciphersuite=$i"
-                "$P_CLI" $P_CLIENT_ARGS request_page=SERVERQUIT auth_mode=none \
-                    force_ciphersuite=$i >/dev/null
-                if [ "$?" == 0 ]; then
-                    break
-                fi
-            done
-
-            wait $PROCESS_ID 2>/dev/null
-            kill $WATCHDOG_PID 2>/dev/null
-            wait $WATCHDOG_PID 2>/dev/null
-            ;;
-        *)
-            kill $PROCESS_ID 2>/dev/null
-            wait $PROCESS_ID 2>/dev/null
-    esac
-
+    kill $PROCESS_ID 2>/dev/null
+    wait $PROCESS_ID 2>/dev/null
 
     if [ "$MEMCHECK" -gt 0 ]; then
         if is_polar "$SERVER_CMD" && has_mem_err $SRV_OUT; then
             echo "  ! Server had memory errors"
-            let "srvmem++"
+            SRVMEM=$(( $SRVMEM + 1 ))
             return
         fi
     fi
@@ -808,19 +805,37 @@
 # kill the running server (used when killed by signal)
 cleanup() {
     rm -f $SRV_OUT $CLI_OUT
-    kill $PROCESS_ID
+    kill $PROCESS_ID >/dev/null 2>&1
+    kill $WATCHDOG_PID >/dev/null 2>&1
     exit 1
 }
 
+# wait for client to terminate and set EXIT
+# must be called right after starting the client
+wait_client_done() {
+    CLI_PID=$!
+
+    ( sleep "$DOG_DELAY"; echo "TIMEOUT" >> $CLI_OUT; kill $CLI_PID ) &
+    WATCHDOG_PID=$!
+
+    wait $CLI_PID
+    EXIT=$?
+
+    kill $WATCHDOG_PID
+    wait $WATCHDOG_PID
+
+    echo "EXIT: $EXIT" >> $CLI_OUT
+}
+
 # run_client <name> <cipher>
 run_client() {
     # announce what we're going to do
-    let "tests++"
+    TESTS=$(( $TESTS + 1 ))
     VERIF=$(echo $VERIFY | tr '[:upper:]' '[:lower:]')
-    TITLE="${1:0:1}->${SERVER_NAME:0:1} $MODE,$VERIF $2"
+    TITLE="`echo $1 | head -c1`->`echo $SERVER_NAME | head -c1`"
+    TITLE="$TITLE $MODE,$VERIF $2"
     echo -n "$TITLE "
-    LEN=`echo "$TITLE" | wc -c`
-    LEN=`echo 72 - $LEN | bc`
+    LEN=$(( 72 - `echo "$TITLE" | wc -c` ))
     for i in `seq 1 $LEN`; do echo -n '.'; done; echo -n ' '
 
     # run the command and interpret result
@@ -829,10 +844,10 @@
             CLIENT_CMD="$OPENSSL_CMD s_client $O_CLIENT_ARGS -cipher $2"
             log "$CLIENT_CMD"
             echo "$CLIENT_CMD" > $CLI_OUT
-            ( echo -e 'GET HTTP/1.0'; echo; ) | $CLIENT_CMD >> $CLI_OUT 2>&1
-            EXIT=$?
+            ( echo -e 'GET HTTP/1.0'; echo; ) | $CLIENT_CMD >> $CLI_OUT 2>&1 &
+            wait_client_done
 
-            if [ "$EXIT" == "0" ]; then
+            if [ $EXIT -eq 0 ]; then
                 RESULT=0
             else
                 if grep 'Cipher is (NONE)' $CLI_OUT >/dev/null; then
@@ -847,10 +862,10 @@
             CLIENT_CMD="$GNUTLS_CLI $G_CLIENT_ARGS --priority $G_PRIO_MODE:$2 localhost"
             log "$CLIENT_CMD"
             echo "$CLIENT_CMD" > $CLI_OUT
-            ( echo -e 'GET HTTP/1.0'; echo; ) | $CLIENT_CMD >> $CLI_OUT 2>&1
-            EXIT=$?
+            ( echo -e 'GET HTTP/1.0'; echo; ) | $CLIENT_CMD >> $CLI_OUT 2>&1 &
+            wait_client_done
 
-            if [ "$EXIT" == "0" ]; then
+            if [ $EXIT -eq 0 ]; then
                 RESULT=0
             else
                 RESULT=2
@@ -872,8 +887,8 @@
             fi
             log "$CLIENT_CMD"
             echo "$CLIENT_CMD" > $CLI_OUT
-            $CLIENT_CMD >> $CLI_OUT 2>&1
-            EXIT=$?
+            $CLIENT_CMD >> $CLI_OUT 2>&1 &
+            wait_client_done
 
             case $EXIT in
                 "0")    RESULT=0    ;;
@@ -904,14 +919,23 @@
             ;;
         "1")
             echo SKIP
-            let "skipped++"
+            SKIPPED=$(( $SKIPPED + 1 ))
             ;;
         "2")
             echo FAIL
-            cp $SRV_OUT c-srv-${tests}.log
-            cp $CLI_OUT c-cli-${tests}.log
-            echo "  ! outputs saved to c-srv-${tests}.log, c-cli-${tests}.log"
-            let "failed++"
+            cp $SRV_OUT c-srv-${TESTS}.log
+            cp $CLI_OUT c-cli-${TESTS}.log
+            echo "  ! outputs saved to c-srv-${TESTS}.log, c-cli-${TESTS}.log"
+
+            if [ "X${USER:-}" = Xbuildbot -o "X${LOGNAME:-}" = Xbuildbot ]; then
+                echo "  ! server output:"
+                cat c-srv-${TESTS}.log
+                echo "  ! ==================================================="
+                echo "  ! client output:"
+                cat c-cli-${TESTS}.log
+            fi
+
+            FAILED=$(( $FAILED + 1 ))
             ;;
     esac
 
@@ -960,9 +984,6 @@
     esac
 done
 
-# used by watchdog
-MAIN_PID="$$"
-
 # Pick a "unique" port in the range 10000-19999.
 PORT="0000$$"
 PORT="1$(echo $PORT | tail -c 5)"
@@ -971,6 +992,13 @@
 SRV_OUT="srv_out.$$"
 CLI_OUT="cli_out.$$"
 
+# client timeout delay: be more patient with valgrind
+if [ "$MEMCHECK" -gt 0 ]; then
+    DOG_DELAY=30
+else
+    DOG_DELAY=10
+fi
+
 trap cleanup INT TERM HUP
 
 for VERIFY in $VERIFIES; do
@@ -1065,7 +1093,7 @@
 
 echo "------------------------------------------------------------------------"
 
-if (( failed != 0 || srvmem != 0 ));
+if [ $FAILED -ne 0 -o $SRVMEM -ne 0 ];
 then
     echo -n "FAILED"
 else
@@ -1073,13 +1101,13 @@
 fi
 
 if [ "$MEMCHECK" -gt 0 ]; then
-    MEMREPORT=", $srvmem server memory errors"
+    MEMREPORT=", $SRVMEM server memory errors"
 else
     MEMREPORT=""
 fi
 
-let "passed = tests - failed"
-echo " ($passed / $tests tests ($skipped skipped$MEMREPORT))"
+PASSED=$(( $TESTS - $FAILED ))
+echo " ($PASSED / $TESTS tests ($SKIPPED skipped$MEMREPORT))"
 
-let "failed += srvmem"
-exit $failed
+FAILED=$(( $FAILED + $SRVMEM ))
+exit $FAILED
diff -ruN polarssl-1.3.8/tests/data_files/enco-ca-prstr.pem polarssl-1.3.9/tests/data_files/enco-ca-prstr.pem
--- polarssl-1.3.8/tests/data_files/enco-ca-prstr.pem	1970-01-01 01:00:00.000000000 +0100
+++ polarssl-1.3.9/tests/data_files/enco-ca-prstr.pem	2014-10-20 13:59:19.000000000 +0200
@@ -0,0 +1,14 @@
+-----BEGIN CERTIFICATE-----
+MIICDTCCAXagAwIBAgIETZt8lzANBgkqhkiG9w0BAQUFADBCMUAwPgYDVQQDEzdP
+cGVuVlBOIFdlYiBDQSAyMDExLjA0LjA1IDIwOjMzOjI3IFVUQyBhc2RlbW8ueW9u
+YW4ubmV0MB4XDTExMDMyOTIwMzMyN1oXDTIxMDQwMjIwMzMyN1owQjFAMD4GA1UE
+AxM3T3BlblZQTiBXZWIgQ0EgMjAxMS4wNC4wNSAyMDozMzoyNyBVVEMgYXNkZW1v
+LnlvbmFuLm5ldDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA38U3wA/eTGN/
+/AJHo2OsEHjLdO9k3Mo5QcShvg+6IoAThD7HEyOYm4Ild8s4+eEy2i9ecWvMKG6M
+YSO+GwG9xOd9wDFtODpF+z6rIt8a4bLbQHcsp9Ccu+ZmjxkJkmxOCz774lxETArX
+SaksAB5P6Web/LwKUv/Iy9crRM9HzSECAwEAAaMQMA4wDAYDVR0TBAUwAwEB/zAN
+BgkqhkiG9w0BAQUFAAOBgQARCDFYCb9n151hgwitxzbuacIVDqIH8EouV2VBqlNR
+tj8q1maliDE3pW7WRAwMi5i3+5c0auKwhTGESsBPjasd5QnjqXOkRbcZhkeVQ1ln
+6NEn6xC+M+H2LGVHSSropcGa8olLlo98LrsFuHVHMewTs7SK2lc+7rU/ILec3ymj
+og==
+-----END CERTIFICATE-----
diff -ruN polarssl-1.3.8/tests/data_files/enco-cert-utf8str.pem polarssl-1.3.9/tests/data_files/enco-cert-utf8str.pem
--- polarssl-1.3.8/tests/data_files/enco-cert-utf8str.pem	1970-01-01 01:00:00.000000000 +0100
+++ polarssl-1.3.9/tests/data_files/enco-cert-utf8str.pem	2014-10-20 13:59:19.000000000 +0200
@@ -0,0 +1,13 @@
+-----BEGIN CERTIFICATE-----
+MIIB8jCCAVugAwIBAgIETZt8+zANBgkqhkiG9w0BAQUFADBCMUAwPgYDVQQDDDdP
+cGVuVlBOIFdlYiBDQSAyMDExLjA0LjA1IDIwOjMzOjI3IFVUQyBhc2RlbW8ueW9u
+YW4ubmV0MB4XDTE0MDcyOTAzNTMzM1oXDTI0MDgwMjAzNTMzM1owFzEVMBMGA1UE
+AwwMZHcueW9uYW4ubmV0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHYW8q
+ZZ/HIIlU8j/YIyTh3h59JcJF0Es7RsPg25QVJkDkfhMn6l15f2neB2KPLKxCLpLD
+ozYD4s/If8aq74A1C2vvOLo/Gq1erNS4b9IS5xLs3Lu643XGxS93Rf6jrsGa8lfb
+Wa7DsQrp7FLT5GApwCp6CebmZq7jEImj0pDFRwIDAQABoyAwHjAJBgNVHRMEAjAA
+MBEGCWCGSAGG+EIBAQQEAwIGQDANBgkqhkiG9w0BAQUFAAOBgQAS1Ulo7iBABpm/
+S23mCnIFRY1+eFfYg4h8EiK9f8kWDwduXSYGVUqRHqh4LcNSdTOIaSEG4RGyV/EA
+5RfTviaQ9PxPiSFegNja8/aHel/nORfsEk4rwBCPGKDveL5KYhAtyAs865ZzLtv+
+kEkfhaTgrBIikwlnquoX5UHOdL/iaw==
+-----END CERTIFICATE-----
diff -ruN polarssl-1.3.8/tests/data_files/mpi_10 polarssl-1.3.9/tests/data_files/mpi_10
--- polarssl-1.3.8/tests/data_files/mpi_10	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/data_files/mpi_10	2014-10-20 13:59:19.000000000 +0200
@@ -1 +1 @@
-643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153
+label_1234567890=643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153
diff -ruN polarssl-1.3.8/tests/data_files/mpi_too_big polarssl-1.3.9/tests/data_files/mpi_too_big
--- polarssl-1.3.8/tests/data_files/mpi_too_big	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/data_files/mpi_too_big	2014-10-20 13:59:19.000000000 +0200
@@ -1 +1 @@
-64380800680355443923012985496149269915138610753401343291807343952413826484237063006136971539473913409092293733259038472039713333596954925632262097903668663321390395296617510709676918001764616185157314759639015364380800680355443923012985496149269915138610753401343291807343952413826484237063006136971539473913409092293733259038472039713333596954925632262097903668663321390395296617510709676918001764616185157314759639015364380800680355443923012985496149269915138610753401343291807343952413826484237063006136971539473913409092293733259038472039713333596954925632262097903668663321390395296617510709676918001764616185157314759639015364380800680355443923012985496149269915138610753401343291807343952413826484237063006136971539473913409092293733259038472039713333596954925632262097903668663321390395296617510709676918001764616185157314759639015364380800680355443923012985496149269915138610753401343291807343952413826484237063006136971539473913409092293733259038472039713333596954925632262097903668663321390395296617510709676918001764616185157314759639015364380800680355443923012985496149269915138610753401343291807343952413826484237063006136971539473913409092293733259038472039713333596954925632262097903668663321390395296617510709676918001764616185157
+label_1234567890=1090748135619415929462984244733782862448264161996232692431832786189721331849119295216264234525201987223957291796157025273109870820177184063610979765077554799078906298842192989538609825228048205159696851613591638196771886542609324560121290553901886301017900252535799917200010079600026535836800905297805880952350501630195475653911005312364560014847426035293551245843928918752768696279344088055617515694349945406677825140814900616105920256438504578013326493565836047242407382442812245131517757519164899226365743722432277368075027627883045206501792761700945699168497257879683851737049996900961120515655050115561271491492515342105748966629547032786321505730828430221664970324396138635251626409516168005427623435996308921691446181187406395310665404885739434832877428167407495370993511868756359970390117021823616749458620969857006263612082706715408157066575137281027022310927564910276759160520878304632411049364568754920967322982459184763427383790272448438018526977764941072715611580434690827459339991961414242741410599117426060556483763756314527611362658628383368621157993638020878537675545336789915694234433955666315070087213535470255670312004130725495834508357439653828936077080978550578912967907352780054935621561090795845172954115972927479877527738560008204118558930004777748727761853813510493840581861598652211605960308356405941821189714037868726219481498727603653616298856174822413033485438785324024751419417183012281078209729303537372804574372095228703622776363945290869806258422355148507571039619387449629866808188769662815778153079393179093143648340761738581819563002994422790754955061288818308430079648693232179158765918035565216157115402992120276155607873107937477466841528362987708699450152031231862594203085693838944657061346236704234026821102958954951197087076546186622796294536451620756509351018906023773821539532776208676978589731966330308893304665169436185078350641568336944530051437491311298834367265238595404904273455928723949525227184617404367854754610474377019768025576605881038077270707717942221977090385438585844095492116099852538903974655703943973086090930596963360767529964938414598185705963754561497355827813623833288906309004288017321424808663962671333528009232758350873059614118723781422101460198615747386855096896089189180441339558524822867541113212638793675567650340362970031930023397828465318547238244232028015189689660418822976000815437610652254270163595650875433851147123214227266605403581781469090806576468950587661997186505665475715792896
diff -ruN polarssl-1.3.8/tests/data_files/rsa4096_prv.pem polarssl-1.3.9/tests/data_files/rsa4096_prv.pem
--- polarssl-1.3.8/tests/data_files/rsa4096_prv.pem	1970-01-01 01:00:00.000000000 +0100
+++ polarssl-1.3.9/tests/data_files/rsa4096_prv.pem	2014-10-20 13:59:19.000000000 +0200
@@ -0,0 +1,51 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIJKQIBAAKCAgEA5F2mqEsdntPAEij6HfCYnKiLMGnm6PcfsaFYeFYO1EufOjN5
+ZJP90cr3CrCnN9JOAdpBbTpzA0RcIcAdWBzvNNAtIMvSfi22WJYVjzD0Bvs2rCYH
+76Yc6vfx7y9zXZcanh8S/2t7B64xmxOWL4RE+f8HWTijAWlyUFDk+DuJWpQK2o0b
+hE4S8mX+uUl3afNW5CiPsRky1N1v4a7/J2b7cG+7pDWUcjnvmNCN84v+gSucXfKg
+/LiAnZgY7xih2ePEhkkIqn6kU0cVBQj1cZ7hXGRaZ/MnqZ2y+KjiuFot2saNk/v0
+vjjW+xOx76qJV99LtN/1qvCYnO1RqMv2EM8WhErLcgiRrihzaz3a2GaumL30CcNi
+xrEXRyEjFaO/klqkpuZRHTtyUnkvhUkPUHuHn45XPxZ7a2XRyrSbFyyS0amTjQwQ
+CveSRiJFjK5TZ56CVGKF/DmuLSHeTY3vwi+WXVdKMYQ6Zi9jwFJo/S4TRpzp+DTS
+H68FrFRqE1+qIVyWQjmhWxuvPhqVkG0IT7CZ0M8lWesysyI759f5D8DhEp/KbWLD
+eXWCzcNSbgWGHW5JA+fCV7+8m0PqodIy5D8Lhwm2tI5dA6Qcro8X127RWVaVsN8L
+Izdf1THXfnZIm1fDBNUfhXapKfnFV8EvALFX2Gy8M3kZQ3slaGegILfqRKcCAwEA
+AQKCAgBg8z1gr1so5b7iNtFQyqcPwyIscJleiCPFdrknhWmQSXaU7+t2frnASkmt
+GSg0s6z4bl9ebvULCweOMJCEquwG4OZ3yPBZLzD91OHcQ60mFZq1ZQPzgvM98fud
+TujMb+0V+h1HoKq/rP1UV/FnxOC/vbyx7TCO1eR5Io7CsAv1D2q4NDXdaoPyssh8
+gysWKP/Xpzyxs//3jPcFuhSK9taCen0QDssx31TP7KKHJgTrc8dTv0EHaZD41uym
+/S8hYOg7FmB+eXtr+355/76r+Qa2Aci73ugUw2WK2bA/EdHr0mWi0NGrvFfQiiD9
+ncnnK15psLcMVk6EOOB1J/oUUsa8n6/lQiTJYRfFlf0hr+mbMEgdfImM2Xn4wF8Y
+Ovapp8Gj/XO7FVVaWW8dIVUrgyrCuOz5SW11Pb0/KFebzOQytST0S3z1j55bUl5L
+mDxR0rJU+fMvbdJvMgHgi6YYI1MBbSFmK7/Ue9HZaGxfUPBqXJetOgAJnuoWUqO4
+AtpYbLaIiqvdIDi1xF4jDMGIoOl7CnFzU9B3PjCkX4aGdARpXqRABwFT9bpf1lWe
+DsEhbIg4/qTWKcA6DxIXaDhgP9eH6NDWS6WKb8L1SZ3mMytjaCxKsV6p7p9DjJR1
+dwOmY0Hv7eBYhjVYUj3ybZs6dfFlIg+M5RtarlOsFhZJ9nVhEQKCAQEA/l0FHos6
+k5c1726blx7zlRm9mOt+rV1nbEOSZUny++oXGyXrUYvX5NX+p8soF0Im9dCuiguQ
+sdKNK6DZCIayennwwEncjKWH+O9VahXxMS9RwtaRDNWJRx3SP6b2s4T1W6PVZdTd
+K7MlMB182ckvs67WQ2hMHNcKrTHuTddpAYSD5Lh/QYD6IdWqs6lwLAtmL7/WTkN7
+XdPhzVfCXLjeBBqr7PakNM9qI7duw29QpSfnArshDmvwiuVOGVGCcm4qB1RV0sQg
+KQJ5nt9X5VoK2SMDR2IzYbq5I/wexiHIbr4kThaGok55lGiCNRjkane+/rSOirZX
+Yo0sJ3RTUrBLyQKCAQEA5dXPAYF7lAo3Xpwo0Qou9IFc0qtiFK9pAp0q81DSbDJC
+lkZOMm/ofzE6vF6jxja2skXccbEhIDu876m9370uRUAAmfimAdmRhUk+JzrlHXxO
+tFSxbyG0iCmwtCSZmiBcMfvFJ/5HepBhxbUDBIc6Pi8EOgjcQdnJYr60KJxbovK0
+wr9mnwwaK7SrE+mX5vN2aOwGpG9n61ibUT1aELR9alOZ8H4SlhLtZvgP02YoOCSW
+BKKe44fbOk/qUlZG1D6O6/H/OMT4TMyYgaswy0QuMHTjOBXrkAmVSch5dwo0eoxx
+dFhn31nF9S5rBZt/PdBPR3imz7U6MoBh6/8olHFk7wKCAQEAxbOTGQxqOPDccP7t
+W+YouQjKvqK7URA6JIHYtXVmsLpfvzAX2Mfyw+A4ED7tKDa4hXLvVkhq7GuUYgag
+6emXq24/25UNIRw/tRKAtvXbA7mduOyAzRLjoizhj6u8MAf1lIaghIeQaDjTfLRO
+qA+hTe1kh/v2vKu/lqIqcMIu0Ykn4owsDMOspsOl7AKUNwedIxvd+/KjXmgjJzFA
+1kSx+0qnuoRxWMKl4qDeLHTGn7eF7C96H/VxfuN/clpSI5LQg+Xe1vStcnKECSHa
+9V6o8+As2jzPZvR0li2N1b3IRZrwKOmFN337LYiVO6PfVYlBIENCTzoubWEAoqHd
+aXWxUQKCAQEAuMDYuLMnbeeQfuM1BGUVPcNHpKnUHCCtX0aMIi+UFxmH4Vj+vxiq
+YqRmPMovCMUus7vo6xOiN1EOHfHrChH/QfejBCKW/+GvUt9/sPVs+/jTI675OwZz
+IwmwW/8X4oek1SE4aV/EgcfScKWDmX5C2X3d/fDlbaHuewwlsoeOOjy0BeDqU2vd
+FckTxNwAGc0YIFurMz/C37LIl9OjtM4CCxjNJD+UHUN1x1IdFqiGKCtw1KUM6IZr
+OkLHcAyevzrSlORhb3cWylWlOocsoBlcr+MmTA2C4LRzZ25aBdEUQnbnNMlkJmz5
+7o+zxDwtWrk7IY7hORLLh5EgJh9ktX85zQKCAQAZILSp21azS3KzKdAvq5u2KVAV
+GumDf1douO5o+5HjV2Kcf5tkzj4A1ffVZKt7auZCNURAG4jaNIccScZBz33EtCuB
+wvRQp5f8DN9EQH4yjaNIbPkFrKzgz5AY08n10PBm+X3cY48P27oR/IDfr2wVtCAE
+UufjLZCkuUjdCFD1wJSCj7LNwjZURuCTocvtaa7HEqnjW9VB4aAbdtf53WRsbYwt
+ZFEWVp8sYc917I6OUJFQcT7jxbv4kbUAXICLaLtaLW2bWfdRtFQSo08pmZAKxxCv
+6Vu5VLZ8LGLVkpie8FEaYd/89gEsHh6HgY9LsJN7WxoaJn1sLmEtmyw9xRSW
+-----END RSA PRIVATE KEY-----
diff -ruN polarssl-1.3.8/tests/data_files/rsa4096_pub.pem polarssl-1.3.9/tests/data_files/rsa4096_pub.pem
--- polarssl-1.3.8/tests/data_files/rsa4096_pub.pem	1970-01-01 01:00:00.000000000 +0100
+++ polarssl-1.3.9/tests/data_files/rsa4096_pub.pem	2014-10-20 13:59:19.000000000 +0200
@@ -0,0 +1,14 @@
+-----BEGIN PUBLIC KEY-----
+MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA5F2mqEsdntPAEij6HfCY
+nKiLMGnm6PcfsaFYeFYO1EufOjN5ZJP90cr3CrCnN9JOAdpBbTpzA0RcIcAdWBzv
+NNAtIMvSfi22WJYVjzD0Bvs2rCYH76Yc6vfx7y9zXZcanh8S/2t7B64xmxOWL4RE
++f8HWTijAWlyUFDk+DuJWpQK2o0bhE4S8mX+uUl3afNW5CiPsRky1N1v4a7/J2b7
+cG+7pDWUcjnvmNCN84v+gSucXfKg/LiAnZgY7xih2ePEhkkIqn6kU0cVBQj1cZ7h
+XGRaZ/MnqZ2y+KjiuFot2saNk/v0vjjW+xOx76qJV99LtN/1qvCYnO1RqMv2EM8W
+hErLcgiRrihzaz3a2GaumL30CcNixrEXRyEjFaO/klqkpuZRHTtyUnkvhUkPUHuH
+n45XPxZ7a2XRyrSbFyyS0amTjQwQCveSRiJFjK5TZ56CVGKF/DmuLSHeTY3vwi+W
+XVdKMYQ6Zi9jwFJo/S4TRpzp+DTSH68FrFRqE1+qIVyWQjmhWxuvPhqVkG0IT7CZ
+0M8lWesysyI759f5D8DhEp/KbWLDeXWCzcNSbgWGHW5JA+fCV7+8m0PqodIy5D8L
+hwm2tI5dA6Qcro8X127RWVaVsN8LIzdf1THXfnZIm1fDBNUfhXapKfnFV8EvALFX
+2Gy8M3kZQ3slaGegILfqRKcCAwEAAQ==
+-----END PUBLIC KEY-----
diff -ruN polarssl-1.3.8/tests/data_files/server7_all_space.crt polarssl-1.3.9/tests/data_files/server7_all_space.crt
--- polarssl-1.3.8/tests/data_files/server7_all_space.crt	1970-01-01 01:00:00.000000000 +0100
+++ polarssl-1.3.9/tests/data_files/server7_all_space.crt	2014-10-20 13:59:19.000000000 +0200
@@ -0,0 +1,47 @@
+-----BEGIN CERTIFICATE-----
+MIIDwjCCAaqgAwIBAgIBEDANBgkqhkiG9w0BAQsFADBIMQswCQYDVQQGEwJOTDER
+MA8GA1UEChMIUG9sYXJTU0wxJjAkBgNVBAMTHVBvbGFyU1NMIFRlc3QgSW50ZXJt
+ZWRpYXRlIENBMB4XDTEzMDkyNDE2MTIyNFoXDTIzMDkyMjE2MTIyNFowNDELMAk G
+A1UEBhMCTkwxETAPBgNVBAoTCFBvbGFyU1NMMRIwEAYDVQQDEwlsb2NhbGhvc3Qw
+WTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQcbffp2qXqoZyychmoCRxzrd4Vu96m
+47NPBehtEC46aTeXgDnBdf++znABrAtfXBRNQz8ARIeYBmskr22rlKjyo4GVMIGS
+MAkGA1UdEwQCMAAwHQYDVR0OBBYEFNIK06V3H85VsFxGoo5zbL+hYCa7MGYGA1Ud
+IwRfMF2AFDh32Gt3nCh3gotO2BupHveUFrcOoUKkQDA+MQswCQYDVQQGEwJOTDER
+MA8GA1UEChMIUG9sYXJTU0wxHDAaBgNVBAMTE1BvbGFyc3NsIFRlc3QgRUMgQ0GC
+AQ4wDQYJKoZIhvcNAQELBQADggIBADRoQ5fHKw+vkl0D3aqLX1XrZidb+25AWbhr
+FYXdaskN219PrXBL3cV8x5tK6qsPKSyyw1lue80OmhXs/w7PJkOHHUSWRnmTv7lr
+8Us3Zr/yOF/VVqzdGs7DlOTpyzEBdugI9uar/aCqHDoltN8wOduOoQB9aojYpROj
++gjlEO0mgt/87XpjYOig1o0jv44QYDQZQzpj1zeIn6WMe6xk9YDwCLMjRIpg++c7
+QyxvcEJTn80wX1SaEBM2gau97G7bORLMwBVkMT4oSY+iKYgpPpawOnMJbqUP73Dm
+yfJExDdrW/BbWZ/vKIcSqSZIbkHdkNjUDVHczyVwQxZxzvLFw/B1k9s7jYFsi5eK
+TNAdXFa4et1H2sd+uhu24GxsjmJioDrftixcgzPVBjDCjH8QWkBEX292WJ58on0e
+deWLpZUnzPdE1B4rsiPw1Vg28mGgr2O1xgBQr/fx6A+8ItNTzAXbZfEcult9ypwM
+0b6YDNe5IvdKk8iwz3mof0VNy47K6xoCaE/fxxWkjoXK8x2wfswGeP2QgUzQE93b
+OtjdHpsG1c7gIVFQmKATyAPUz4vqmezgNRleXU0oL0PYtoCmKQ51UjNMUfmO9xCj
+VJaNa2iTQ5Dgic+CW4TYAgj5/9g9X3WfwnDNxrZ0UxxawGElczHXqbrNleTtPaKp
+a8Si6UK5
+-----END CERTIFICATE-----
+-----BEGIN CERTIFICATE-----
+MIIEATCCA4egAwIBAgIBDjAKBggqhkjOPQQDAjA+MQswCQYDVQQGEwJOTDERMA8G
+A1UEChMIUG9sYXJTU0wxHDAaBgNVBAMTE1BvbGFyc3NsIFRlc3QgRUMgQ0EwHhcN
+MTMwOTI0MTU1NTE0WhcNMjMwOTIyMTU1NTE0WjBIMQswCQYDVQQGEwJOTDERMA8G
+A1UEChMIUG9sYXJTU0wxJjAkBgNVBAMTHVBvbGFyU1NMIFRlc3QgSW50ZXJtZWRp
+YXRlIENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAo1Oc8nr6fMTq
+vowV+CpC55i5BZGFGc50Eb4RLBSRTH1e7JepdFjAVbBtyQRJSiY1ja0tgLQDDKZR
+wfEI+b4azse460InPHv7C1TN0upXlxuj6m9B1IlP+sBaM7WBC6dVfPO+jVMIxgkF
+CaBCLhhdK1Fjf8HjkT/PkctWnho8NTwivc9+nqRZjXe/eIcqm5HwjDDhu+gz+o0g
+Vz9MfZNi1JyCrOyNZcy+cr2QeNnNVGnFq8xTxtu6dLunhpmLFj2mm0Vjwa7Ypj5q
+AjpqTMtDvqbRuToyoyzajhMNcCAf7gwzIupJJFVdjdtgYAcQwzikwF5HoITJzzJ2
+qgxF7CmvGZNb7G99mLdLdhtclH3wAQKHYwEGJo7XKyNEuHPQgB+e0cg1SD1HqlAM
+uCfGGTWQ6me7Bjan3t0NzoTdDq6IpKTesbaY+/9e2xn8DCrhBKLXQMZFDZqUoLYA
+kGPOEGgvlPnIIXAawouxCaNYEh5Uw871YMSPT28rLdFr49dwYOtDg9foA8hDIW2P
+d6KXbrZteesvA1nYzEOs+3AjrbT79Md2W8Bz9bqBVNlNOESSqm4kiCJFmslm/6br
+Np0MSQd+o22PQ4xRtmP6UsTfU0ueiMpYc8TYYhMbfnfFyo4m707ebcflPbBEN2dg
+updQ66cvfCJB0QJt9upafY0lpdV1qUkCAwEAAaOBoDCBnTAdBgNVHQ4EFgQUOHf Y
+a3ecKHeCi07YG6ke95QWtw4wbgYDVR0jBGcwZYAUnW0gJEkBPyvLeLUZvH4kydv7
+NnyhQqRAMD4xCzAJBgNVBAYTAk5MMREwDwYDVQQKEwhQb2xhclNTTDEcMBoGA1UE
+AxMTUG9sYXJzc2wgVGVzdCBFQyBDQYIJAMFD4n5iQ8zoMAwGA1UdEwQFMAMBAf8w
+CgYIKoZIzj0EAwIDaAAwZQIxAPyE+u+eP7gRrSFjQicmpYg8jiFUCYEowWY2zuOG
+i1HXYwmpDHfasQ3rNSuf/gHvjwIwbSSjumDk+uYNci/KMELDsD0MFHxZhhBc9Hp9
+Af5cNR8KhzegznL6amRObGGKmX1F
+-----END CERTIFICATE-----
diff -ruN polarssl-1.3.8/tests/data_files/server7_pem_space.crt polarssl-1.3.9/tests/data_files/server7_pem_space.crt
--- polarssl-1.3.8/tests/data_files/server7_pem_space.crt	1970-01-01 01:00:00.000000000 +0100
+++ polarssl-1.3.9/tests/data_files/server7_pem_space.crt	2014-10-20 13:59:19.000000000 +0200
@@ -0,0 +1,47 @@
+-----BEGIN CERTIFICATE-----
+MIIDwjCCAaqgAwIBAgIBEDANBgkqhkiG9w0BAQsFADBIMQswCQYDVQQGEwJOTDER
+MA8GA1UEChMIUG9sYXJTU0wxJjAkBgNVBAMTHVBvbGFyU1NMIFRlc3QgSW50ZXJt
+ZWRpYXRlIENBMB4XDTEzMDkyNDE2MTIyNFoXDTIzMDkyMjE2MTIyNFowNDELMAk G
+A1UEBhMCTkwxETAPBgNVBAoTCFBvbGFyU1NMMRIwEAYDVQQDEwlsb2NhbGhvc3Qw
+WTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQcbffp2qXqoZyychmoCRxzrd4Vu96m
+47NPBehtEC46aTeXgDnBdf++znABrAtfXBRNQz8ARIeYBmskr22rlKjyo4GVMIGS
+MAkGA1UdEwQCMAAwHQYDVR0OBBYEFNIK06V3H85VsFxGoo5zbL+hYCa7MGYGA1Ud
+IwRfMF2AFDh32Gt3nCh3gotO2BupHveUFrcOoUKkQDA+MQswCQYDVQQGEwJOTDER
+MA8GA1UEChMIUG9sYXJTU0wxHDAaBgNVBAMTE1BvbGFyc3NsIFRlc3QgRUMgQ0GC
+AQ4wDQYJKoZIhvcNAQELBQADggIBADRoQ5fHKw+vkl0D3aqLX1XrZidb+25AWbhr
+FYXdaskN219PrXBL3cV8x5tK6qsPKSyyw1lue80OmhXs/w7PJkOHHUSWRnmTv7lr
+8Us3Zr/yOF/VVqzdGs7DlOTpyzEBdugI9uar/aCqHDoltN8wOduOoQB9aojYpROj
++gjlEO0mgt/87XpjYOig1o0jv44QYDQZQzpj1zeIn6WMe6xk9YDwCLMjRIpg++c7
+QyxvcEJTn80wX1SaEBM2gau97G7bORLMwBVkMT4oSY+iKYgpPpawOnMJbqUP73Dm
+yfJExDdrW/BbWZ/vKIcSqSZIbkHdkNjUDVHczyVwQxZxzvLFw/B1k9s7jYFsi5eK
+TNAdXFa4et1H2sd+uhu24GxsjmJioDrftixcgzPVBjDCjH8QWkBEX292WJ58on0e
+deWLpZUnzPdE1B4rsiPw1Vg28mGgr2O1xgBQr/fx6A+8ItNTzAXbZfEcult9ypwM
+0b6YDNe5IvdKk8iwz3mof0VNy47K6xoCaE/fxxWkjoXK8x2wfswGeP2QgUzQE93b
+OtjdHpsG1c7gIVFQmKATyAPUz4vqmezgNRleXU0oL0PYtoCmKQ51UjNMUfmO9xCj
+VJaNa2iTQ5Dgic+CW4TYAgj5/9g9X3WfwnDNxrZ0UxxawGElczHXqbrNleTtPaKp
+a8Si6UK5
+-----END CERTIFICATE-----
+-----BEGIN CERTIFICATE-----
+MIIEATCCA4egAwIBAgIBDjAKBggqhkjOPQQDAjA+MQswCQYDVQQGEwJOTDERMA8G
+A1UEChMIUG9sYXJTU0wxHDAaBgNVBAMTE1BvbGFyc3NsIFRlc3QgRUMgQ0EwHhcN
+MTMwOTI0MTU1NTE0WhcNMjMwOTIyMTU1NTE0WjBIMQswCQYDVQQGEwJOTDERMA8G
+A1UEChMIUG9sYXJTU0wxJjAkBgNVBAMTHVBvbGFyU1NMIFRlc3QgSW50ZXJtZWRp
+YXRlIENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAo1Oc8nr6fMTq
+vowV+CpC55i5BZGFGc50Eb4RLBSRTH1e7JepdFjAVbBtyQRJSiY1ja0tgLQDDKZR
+wfEI+b4azse460InPHv7C1TN0upXlxuj6m9B1IlP+sBaM7WBC6dVfPO+jVMIxgkF
+CaBCLhhdK1Fjf8HjkT/PkctWnho8NTwivc9+nqRZjXe/eIcqm5HwjDDhu+gz+o0g
+Vz9MfZNi1JyCrOyNZcy+cr2QeNnNVGnFq8xTxtu6dLunhpmLFj2mm0Vjwa7Ypj5q
+AjpqTMtDvqbRuToyoyzajhMNcCAf7gwzIupJJFVdjdtgYAcQwzikwF5HoITJzzJ2
+qgxF7CmvGZNb7G99mLdLdhtclH3wAQKHYwEGJo7XKyNEuHPQgB+e0cg1SD1HqlAM
+uCfGGTWQ6me7Bjan3t0NzoTdDq6IpKTesbaY+/9e2xn8DCrhBKLXQMZFDZqUoLYA
+kGPOEGgvlPnIIXAawouxCaNYEh5Uw871YMSPT28rLdFr49dwYOtDg9foA8hDIW2P
+d6KXbrZteesvA1nYzEOs+3AjrbT79Md2W8Bz9bqBVNlNOESSqm4kiCJFmslm/6br
+Np0MSQd+o22PQ4xRtmP6UsTfU0ueiMpYc8TYYhMbfnfFyo4m707ebcflPbBEN2dg
+updQ66cvfCJB0QJt9upafY0lpdV1qUkCAwEAAaOBoDCBnTAdBgNVHQ4EFgQUOHfY
+a3ecKHeCi07YG6ke95QWtw4wbgYDVR0jBGcwZYAUnW0gJEkBPyvLeLUZvH4kydv7
+NnyhQqRAMD4xCzAJBgNVBAYTAk5MMREwDwYDVQQKEwhQb2xhclNTTDEcMBoGA1UE
+AxMTUG9sYXJzc2wgVGVzdCBFQyBDQYIJAMFD4n5iQ8zoMAwGA1UdEwQFMAMBAf8w
+CgYIKoZIzj0EAwIDaAAwZQIxAPyE+u+eP7gRrSFjQicmpYg8jiFUCYEowWY2zuOG
+i1HXYwmpDHfasQ3rNSuf/gHvjwIwbSSjumDk+uYNci/KMELDsD0MFHxZhhBc9Hp9
+Af5cNR8KhzegznL6amRObGGKmX1F
+-----END CERTIFICATE-----
diff -ruN polarssl-1.3.8/tests/scripts/all.sh polarssl-1.3.9/tests/scripts/all.sh
--- polarssl-1.3.8/tests/scripts/all.sh	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/scripts/all.sh	2014-10-20 13:59:19.000000000 +0200
@@ -17,6 +17,9 @@
     exit 1
 fi
 
+CONFIG_H='include/polarssl/config.h'
+CONFIG_BAK="$CONFIG_H.bak"
+
 MEMORY=0
 
 while [ $# -gt 0 ]; do
@@ -40,12 +43,19 @@
 cleanup()
 {
     make clean
+
     find -iname '*cmake*' -not -name CMakeLists.txt -exec rm -rf {} \+
     rm -f include/Makefile include/polarssl/Makefile programs/*/Makefile
     git update-index --no-skip-worktree Makefile library/Makefile programs/Makefile tests/Makefile
     git checkout -- Makefile library/Makefile programs/Makefile tests/Makefile
+
+    if [ -f "$CONFIG_BAK" ]; then
+        mv "$CONFIG_BAK" "$CONFIG_H"
+    fi
 }
 
+trap cleanup INT TERM HUP
+
 msg()
 {
     echo ""
@@ -56,12 +66,13 @@
 
 # The test ordering tries to optimize for the following criteria:
 # 1. Catch possible problems early, by running first test that run quickly
-#    and/or are more likely to fail than others.
+#    and/or are more likely to fail than others (eg I use Clang most of the
+#    time, so start with a GCC build).
 # 2. Minimize total running time, by avoiding useless rebuilds
 #
 # Indicative running times are given for reference.
 
-msg "build: cmake, gcc with lots of warnings" # ~ 1 min
+msg "build: cmake, -Werror (gcc)" # ~ 1 min
 cleanup
 CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Check .
 make
@@ -69,9 +80,9 @@
 msg "test: main suites with valgrind" # ~ 2 min 10s
 make memcheck
 
-msg "build: with ASan" # ~ 1 min
+msg "build: with ASan (clang)" # ~ 1 min
 cleanup
-cmake -D CMAKE_BUILD_TYPE:String=ASan .
+CC=clang cmake -D CMAKE_BUILD_TYPE:String=ASan .
 make
 
 msg "test: ssl-opt.sh (ASan build)" # ~ 1 min 10s
@@ -96,24 +107,40 @@
 ./compat.sh
 cd ..
 
-msg "build: cmake, clang with lots of warnings" # ~ 40s
+msg "build: cmake, full config" # ~ 40s
 cleanup
-CC=clang cmake -D CMAKE_BUILD_TYPE:String=Check .
+cp "$CONFIG_H" "$CONFIG_BAK"
+scripts/config.pl full
+scripts/config.pl unset POLARSSL_MEMORY_BACKTRACE # too slow for tests
+cmake -D CMAKE_BUILD_TYPE:String=Check .
 make
 
-msg "build: Unix make, -O2" # ~ 30s
+msg "test: main suites (full config)"
+make test
+
+msg "test: ssl-opt.sh default (full config)"
+cd tests
+./ssl-opt.sh -f Default
+cd ..
+
+msg "test: compat.sh 3DES & NULL (full config)"
+cd tests
+./compat.sh -e '^$' -f 'NULL\|3DES-EDE-CBC\|DES-CBC3'
+cd ..
+
+msg "build: Unix make, -O2 (gcc)" # ~ 30s
 cleanup
-make
+CC=gcc make
 
 # Optional parts that take a long time to run
 
-if [ "$MEMORY" -gt 0 ]; then
+if [ "$MEMORY" -ge 1 ]; then
     msg "test: ssl-opt --memcheck (-02 build)" # ~ 8 min
     cd tests
     ./ssl-opt.sh --memcheck
     cd ..
 
-    if [ "$MEMORY" -gt 1 ]; then
+    if [ "$MEMORY" -ge 2 ]; then
         msg "test: compat --memcheck (-02 build)" # ~ 42 min
         cd tests
         ./compat.sh --memcheck
diff -ruN polarssl-1.3.8/tests/ssl-opt.sh polarssl-1.3.9/tests/ssl-opt.sh
--- polarssl-1.3.8/tests/ssl-opt.sh	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/ssl-opt.sh	2014-10-20 13:59:19.000000000 +0200
@@ -10,34 +10,27 @@
 
 set -u
 
-# test if it is defined from the environment before assining default
-# if yes, assume it means it's a build with all the options we need (SSLv2)
-if [ -n "${OPENSSL_CMD:-}" ]; then
-    OPENSSL_OK=1
-else
-    OPENSSL_OK=0
-fi
-
 # default values, can be overriden by the environment
 : ${P_SRV:=../programs/ssl/ssl_server2}
 : ${P_CLI:=../programs/ssl/ssl_client2}
 : ${OPENSSL_CMD:=openssl} # OPENSSL would conflict with the build system
+: ${GNUTLS_CLI:=gnutls-cli}
+: ${GNUTLS_SERV:=gnutls-serv}
 
 O_SRV="$OPENSSL_CMD s_server -www -cert data_files/server5.crt -key data_files/server5.key"
 O_CLI="echo 'GET / HTTP/1.0' | $OPENSSL_CMD s_client"
+G_SRV="$GNUTLS_SERV --x509certfile data_files/server5.crt --x509keyfile data_files/server5.key"
+G_CLI="$GNUTLS_CLI"
 
 TESTS=0
 FAILS=0
+SKIPS=0
 
 CONFIG_H='../include/polarssl/config.h'
 
 MEMCHECK=0
 FILTER='.*'
-if [ "$OPENSSL_OK" -gt 0 ]; then
-    EXCLUDE='^$'
-else
-    EXCLUDE='SSLv2'
-fi
+EXCLUDE='^$'
 
 print_usage() {
     echo "Usage: $0 [options]"
@@ -73,15 +66,42 @@
     done
 }
 
+# skip next test if OpenSSL can't send SSLv2 ClientHello
+requires_openssl_with_sslv2() {
+    if [ -z "${OPENSSL_HAS_SSL2:-}" ]; then
+        if $OPENSSL_CMD ciphers -ssl2 >/dev/null 2>&1; then
+            OPENSSL_HAS_SSL2="YES"
+        else
+            OPENSSL_HAS_SSL2="NO"
+        fi
+    fi
+    if [ "$OPENSSL_HAS_SSL2" = "NO" ]; then
+        SKIP_NEXT="YES"
+    fi
+}
+
+# skip next test if GnuTLS isn't available
+requires_gnutls() {
+    if [ -z "${GNUTLS_AVAILABLE:-}" ]; then
+        if ( which "$GNUTLS_CLI" && which "$GNUTLS_SERV" ) >/dev/null; then
+            GNUTLS_AVAILABLE="YES"
+        else
+            GNUTLS_AVAILABLE="NO"
+        fi
+    fi
+    if [ "$GNUTLS_AVAILABLE" = "NO" ]; then
+        SKIP_NEXT="YES"
+    fi
+}
+
 # print_name <name>
 print_name() {
     echo -n "$1 "
-    LEN=`echo "$1" | wc -c`
-    LEN=`echo 72 - $LEN | bc`
+    LEN=$(( 72 - `echo "$1" | wc -c` ))
     for i in `seq 1 $LEN`; do echo -n '.'; done
     echo -n ' '
 
-    TESTS=`echo $TESTS + 1 | bc`
+    TESTS=$(( $TESTS + 1 ))
 }
 
 # fail <message>
@@ -89,11 +109,19 @@
     echo "FAIL"
     echo "  ! $1"
 
-    cp $SRV_OUT o-srv-${TESTS}.log
-    cp $CLI_OUT o-cli-${TESTS}.log
+    mv $SRV_OUT o-srv-${TESTS}.log
+    mv $CLI_OUT o-cli-${TESTS}.log
     echo "  ! outputs saved to o-srv-${TESTS}.log and o-cli-${TESTS}.log"
 
-    FAILS=`echo $FAILS + 1 | bc`
+    if [ "X${USER:-}" = Xbuildbot -o "X${LOGNAME:-}" = Xbuildbot ]; then
+        echo "  ! server output:"
+        cat o-srv-${TESTS}.log
+        echo "  ! ============================================================"
+        echo "  ! client output:"
+        cat o-cli-${TESTS}.log
+    fi
+
+    FAILS=$(( $FAILS + 1 ))
 }
 
 # is_polar <cmd_line>
@@ -129,6 +157,23 @@
     fi
 }
 
+# wait for client to terminate and set CLI_EXIT
+# must be called right after starting the client
+wait_client_done() {
+    CLI_PID=$!
+
+    ( sleep "$DOG_DELAY"; echo "TIMEOUT" >> $CLI_OUT; kill $CLI_PID ) &
+    WATCHDOG_PID=$!
+
+    wait $CLI_PID
+    CLI_EXIT=$?
+
+    kill $WATCHDOG_PID
+    wait $WATCHDOG_PID
+
+    echo "EXIT: $CLI_EXIT" >> $CLI_OUT
+}
+
 # Usage: run_test name srv_cmd cli_cmd cli_exit [option [...]]
 # Options:  -s pattern  pattern that must be present in server output
 #           -c pattern  pattern that must be present in client output
@@ -148,6 +193,14 @@
 
     print_name "$NAME"
 
+    # should we skip?
+    if [ "X$SKIP_NEXT" = "XYES" ]; then
+        SKIP_NEXT="NO"
+        echo "SKIP"
+        SKIPS=$(( $SKIPS + 1 ))
+        return
+    fi
+
     # prepend valgrind to our commands if active
     if [ "$MEMCHECK" -gt 0 ]; then
         if is_polar "$SRV_CMD"; then
@@ -163,28 +216,14 @@
     $SRV_CMD >> $SRV_OUT 2>&1 &
     SRV_PID=$!
     wait_server_start
-    echo "$CLI_CMD" > $CLI_OUT
-    eval "$CLI_CMD" >> $CLI_OUT 2>&1
-    CLI_EXIT=$?
-    echo "EXIT: $CLI_EXIT" >> $CLI_OUT
 
-    if is_polar "$SRV_CMD"; then
-        # start watchdog in case SERVERQUIT fails
-        ( sleep "$DOG_DELAY"; echo "SERVERQUIT TIMEOUT"; kill $MAIN_PID ) &
-        WATCHDOG_PID=$!
-
-        # psk is useful when server only has bad certs
-        $P_CLI request_page=SERVERQUIT tickets=0 auth_mode=none psk=abc123 \
-            crt_file=data_files/cli2.crt key_file=data_files/cli2.key \
-            >/dev/null 2>&1
+    echo "$CLI_CMD" > $CLI_OUT
+    eval "$CLI_CMD" >> $CLI_OUT 2>&1 &
+    wait_client_done
 
-        wait $SRV_PID
-        kill $WATCHDOG_PID
-        wait $WATCHDOG_PID
-    else
-        kill $SRV_PID
-        wait $SRV_PID
-    fi
+    # kill the server
+    kill $SRV_PID
+    wait $SRV_PID
 
     # check if the client and server went at least to the handshake stage
     # (useful to avoid tests with only negative assertions and non-zero
@@ -220,32 +259,33 @@
     fi
 
     # check other assertions
+    # lines beginning with == are added by valgrind, ignore them
     while [ $# -gt 0 ]
     do
         case $1 in
             "-s")
-                if grep "$2" $SRV_OUT >/dev/null; then :; else
+                if grep -v '^==' $SRV_OUT | grep "$2" >/dev/null; then :; else
                     fail "-s $2"
                     return
                 fi
                 ;;
 
             "-c")
-                if grep "$2" $CLI_OUT >/dev/null; then :; else
+                if grep -v '^==' $CLI_OUT | grep "$2" >/dev/null; then :; else
                     fail "-c $2"
                     return
                 fi
                 ;;
 
             "-S")
-                if grep "$2" $SRV_OUT >/dev/null; then
+                if grep -v '^==' $SRV_OUT | grep "$2" >/dev/null; then
                     fail "-S $2"
                     return
                 fi
                 ;;
 
             "-C")
-                if grep "$2" $CLI_OUT >/dev/null; then
+                if grep -v '^==' $CLI_OUT | grep "$2" >/dev/null; then
                     fail "-C $2"
                     return
                 fi
@@ -323,17 +363,39 @@
 P_CLI="$P_CLI server_port=$PORT"
 O_SRV="$O_SRV -accept $PORT"
 O_CLI="$O_CLI -connect localhost:$PORT"
+G_SRV="$G_SRV -p $PORT"
+G_CLI="$G_CLI -p $PORT"
 
 # Also pick a unique name for intermediate files
 SRV_OUT="srv_out.$$"
 CLI_OUT="cli_out.$$"
 SESSION="session.$$"
 
+SKIP_NEXT="NO"
+
 trap cleanup INT TERM HUP
 
+# Basic test
+
+# Checks that:
+# - things work with all ciphersuites active (used with config-full in all.sh)
+# - the expected (highest security) parameters are selected
+#   ("signature_algorithm ext: 6" means SHA-512 (highest common hash))
+run_test    "Default" \
+            "$P_SRV debug_level=3" \
+            "$P_CLI" \
+            0 \
+            -s "Protocol is TLSv1.2" \
+            -s "Ciphersuite is TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384" \
+            -s "client hello v3, signature_algorithm ext: 6" \
+            -s "ECDHE curve: secp521r1" \
+            -S "error" \
+            -C "error"
+
 # Test for SSLv2 ClientHello
 
-run_test    "SSLv2 ClientHello #0 (reference)" \
+requires_openssl_with_sslv2
+run_test    "SSLv2 ClientHello: reference" \
             "$P_SRV debug_level=3" \
             "$O_CLI -no_ssl2" \
             0 \
@@ -341,8 +403,9 @@
             -S "ssl_handshake returned"
 
 # Adding a SSL2-only suite makes OpenSSL client send SSLv2 ClientHello
-run_test    "SSLv2 ClientHello #1 (actual test)" \
-            "$P_SRV debug_level=3" \
+requires_openssl_with_sslv2
+run_test    "SSLv2 ClientHello: actual test" \
+            "$P_SRV debug_level=2" \
             "$O_CLI -cipher 'DES-CBC-MD5:ALL'" \
             0 \
             -s "parse client hello v2" \
@@ -350,23 +413,23 @@
 
 # Tests for Truncated HMAC extension
 
-run_test    "Truncated HMAC #0" \
-            "$P_SRV debug_level=5" \
+run_test    "Truncated HMAC: reference" \
+            "$P_SRV debug_level=4" \
             "$P_CLI trunc_hmac=0 force_ciphersuite=TLS-RSA-WITH-AES-128-CBC-SHA" \
             0 \
             -s "dumping 'computed mac' (20 bytes)"
 
-run_test    "Truncated HMAC #1" \
-            "$P_SRV debug_level=5" \
+run_test    "Truncated HMAC: actual test" \
+            "$P_SRV debug_level=4" \
             "$P_CLI trunc_hmac=1 force_ciphersuite=TLS-RSA-WITH-AES-128-CBC-SHA" \
             0 \
             -s "dumping 'computed mac' (10 bytes)"
 
 # Tests for Session Tickets
 
-run_test    "Session resume using tickets #1 (basic)" \
-            "$P_SRV debug_level=4 tickets=1" \
-            "$P_CLI debug_level=4 tickets=1 reconnect=1" \
+run_test    "Session resume using tickets: basic" \
+            "$P_SRV debug_level=3 tickets=1" \
+            "$P_CLI debug_level=3 tickets=1 reconnect=1" \
             0 \
             -c "client hello, adding session ticket extension" \
             -s "found session ticket extension" \
@@ -378,9 +441,9 @@
             -s "a session has been resumed" \
             -c "a session has been resumed"
 
-run_test    "Session resume using tickets #2 (cache disabled)" \
-            "$P_SRV debug_level=4 tickets=1 cache_max=0" \
-            "$P_CLI debug_level=4 tickets=1 reconnect=1" \
+run_test    "Session resume using tickets: cache disabled" \
+            "$P_SRV debug_level=3 tickets=1 cache_max=0" \
+            "$P_CLI debug_level=3 tickets=1 reconnect=1" \
             0 \
             -c "client hello, adding session ticket extension" \
             -s "found session ticket extension" \
@@ -392,9 +455,9 @@
             -s "a session has been resumed" \
             -c "a session has been resumed"
 
-run_test    "Session resume using tickets #3 (timeout)" \
-            "$P_SRV debug_level=4 tickets=1 cache_max=0 ticket_timeout=1" \
-            "$P_CLI debug_level=4 tickets=1 reconnect=1 reco_delay=2" \
+run_test    "Session resume using tickets: timeout" \
+            "$P_SRV debug_level=3 tickets=1 cache_max=0 ticket_timeout=1" \
+            "$P_CLI debug_level=3 tickets=1 reconnect=1 reco_delay=2" \
             0 \
             -c "client hello, adding session ticket extension" \
             -s "found session ticket extension" \
@@ -406,17 +469,17 @@
             -S "a session has been resumed" \
             -C "a session has been resumed"
 
-run_test    "Session resume using tickets #4 (openssl server)" \
+run_test    "Session resume using tickets: openssl server" \
             "$O_SRV" \
-            "$P_CLI debug_level=4 tickets=1 reconnect=1" \
+            "$P_CLI debug_level=3 tickets=1 reconnect=1" \
             0 \
             -c "client hello, adding session ticket extension" \
             -c "found session_ticket extension" \
             -c "parse new session ticket" \
             -c "a session has been resumed"
 
-run_test    "Session resume using tickets #5 (openssl client)" \
-            "$P_SRV debug_level=4 tickets=1" \
+run_test    "Session resume using tickets: openssl client" \
+            "$P_SRV debug_level=3 tickets=1" \
             "( $O_CLI -sess_out $SESSION; \
                $O_CLI -sess_in $SESSION; \
                rm -f $SESSION )" \
@@ -429,9 +492,9 @@
 
 # Tests for Session Resume based on session-ID and cache
 
-run_test    "Session resume using cache #1 (tickets enabled on client)" \
-            "$P_SRV debug_level=4 tickets=0" \
-            "$P_CLI debug_level=4 tickets=1 reconnect=1" \
+run_test    "Session resume using cache: tickets enabled on client" \
+            "$P_SRV debug_level=3 tickets=0" \
+            "$P_CLI debug_level=3 tickets=1 reconnect=1" \
             0 \
             -c "client hello, adding session ticket extension" \
             -s "found session ticket extension" \
@@ -443,9 +506,9 @@
             -s "a session has been resumed" \
             -c "a session has been resumed"
 
-run_test    "Session resume using cache #2 (tickets enabled on server)" \
-            "$P_SRV debug_level=4 tickets=1" \
-            "$P_CLI debug_level=4 tickets=0 reconnect=1" \
+run_test    "Session resume using cache: tickets enabled on server" \
+            "$P_SRV debug_level=3 tickets=1" \
+            "$P_CLI debug_level=3 tickets=0 reconnect=1" \
             0 \
             -C "client hello, adding session ticket extension" \
             -S "found session ticket extension" \
@@ -457,53 +520,53 @@
             -s "a session has been resumed" \
             -c "a session has been resumed"
 
-run_test    "Session resume using cache #3 (cache_max=0)" \
-            "$P_SRV debug_level=4 tickets=0 cache_max=0" \
-            "$P_CLI debug_level=4 tickets=0 reconnect=1" \
+run_test    "Session resume using cache: cache_max=0" \
+            "$P_SRV debug_level=3 tickets=0 cache_max=0" \
+            "$P_CLI debug_level=3 tickets=0 reconnect=1" \
             0 \
             -S "session successfully restored from cache" \
             -S "session successfully restored from ticket" \
             -S "a session has been resumed" \
             -C "a session has been resumed"
 
-run_test    "Session resume using cache #4 (cache_max=1)" \
-            "$P_SRV debug_level=4 tickets=0 cache_max=1" \
-            "$P_CLI debug_level=4 tickets=0 reconnect=1" \
+run_test    "Session resume using cache: cache_max=1" \
+            "$P_SRV debug_level=3 tickets=0 cache_max=1" \
+            "$P_CLI debug_level=3 tickets=0 reconnect=1" \
             0 \
             -s "session successfully restored from cache" \
             -S "session successfully restored from ticket" \
             -s "a session has been resumed" \
             -c "a session has been resumed"
 
-run_test    "Session resume using cache #5 (timemout > delay)" \
-            "$P_SRV debug_level=4 tickets=0" \
-            "$P_CLI debug_level=4 tickets=0 reconnect=1 reco_delay=0" \
+run_test    "Session resume using cache: timemout > delay" \
+            "$P_SRV debug_level=3 tickets=0" \
+            "$P_CLI debug_level=3 tickets=0 reconnect=1 reco_delay=0" \
             0 \
             -s "session successfully restored from cache" \
             -S "session successfully restored from ticket" \
             -s "a session has been resumed" \
             -c "a session has been resumed"
 
-run_test    "Session resume using cache #6 (timeout < delay)" \
-            "$P_SRV debug_level=4 tickets=0 cache_timeout=1" \
-            "$P_CLI debug_level=4 tickets=0 reconnect=1 reco_delay=2" \
+run_test    "Session resume using cache: timeout < delay" \
+            "$P_SRV debug_level=3 tickets=0 cache_timeout=1" \
+            "$P_CLI debug_level=3 tickets=0 reconnect=1 reco_delay=2" \
             0 \
             -S "session successfully restored from cache" \
             -S "session successfully restored from ticket" \
             -S "a session has been resumed" \
             -C "a session has been resumed"
 
-run_test    "Session resume using cache #7 (no timeout)" \
-            "$P_SRV debug_level=4 tickets=0 cache_timeout=0" \
-            "$P_CLI debug_level=4 tickets=0 reconnect=1 reco_delay=2" \
+run_test    "Session resume using cache: no timeout" \
+            "$P_SRV debug_level=3 tickets=0 cache_timeout=0" \
+            "$P_CLI debug_level=3 tickets=0 reconnect=1 reco_delay=2" \
             0 \
             -s "session successfully restored from cache" \
             -S "session successfully restored from ticket" \
             -s "a session has been resumed" \
             -c "a session has been resumed"
 
-run_test    "Session resume using cache #8 (openssl client)" \
-            "$P_SRV debug_level=4 tickets=0" \
+run_test    "Session resume using cache: openssl client" \
+            "$P_SRV debug_level=3 tickets=0" \
             "( $O_CLI -sess_out $SESSION; \
                $O_CLI -sess_in $SESSION; \
                rm -f $SESSION )" \
@@ -514,9 +577,9 @@
             -S "session successfully restored from ticket" \
             -s "a session has been resumed"
 
-run_test    "Session resume using cache #9 (openssl server)" \
+run_test    "Session resume using cache: openssl server" \
             "$O_SRV" \
-            "$P_CLI debug_level=4 tickets=0 reconnect=1" \
+            "$P_CLI debug_level=3 tickets=0 reconnect=1" \
             0 \
             -C "found session_ticket extension" \
             -C "parse new session ticket" \
@@ -524,38 +587,46 @@
 
 # Tests for Max Fragment Length extension
 
-run_test    "Max fragment length #1" \
-            "$P_SRV debug_level=4" \
-            "$P_CLI debug_level=4" \
+run_test    "Max fragment length: not used, reference" \
+            "$P_SRV debug_level=3" \
+            "$P_CLI debug_level=3" \
             0 \
             -C "client hello, adding max_fragment_length extension" \
             -S "found max fragment length extension" \
             -S "server hello, max_fragment_length extension" \
             -C "found max_fragment_length extension"
 
-run_test    "Max fragment length #2" \
-            "$P_SRV debug_level=4" \
-            "$P_CLI debug_level=4 max_frag_len=4096" \
+run_test    "Max fragment length: used by client" \
+            "$P_SRV debug_level=3" \
+            "$P_CLI debug_level=3 max_frag_len=4096" \
             0 \
             -c "client hello, adding max_fragment_length extension" \
             -s "found max fragment length extension" \
             -s "server hello, max_fragment_length extension" \
             -c "found max_fragment_length extension"
 
-run_test    "Max fragment length #3" \
-            "$P_SRV debug_level=4 max_frag_len=4096" \
-            "$P_CLI debug_level=4" \
+run_test    "Max fragment length: used by server" \
+            "$P_SRV debug_level=3 max_frag_len=4096" \
+            "$P_CLI debug_level=3" \
             0 \
             -C "client hello, adding max_fragment_length extension" \
             -S "found max fragment length extension" \
             -S "server hello, max_fragment_length extension" \
             -C "found max_fragment_length extension"
 
+requires_gnutls
+run_test    "Max fragment length: gnutls server" \
+            "$G_SRV" \
+            "$P_CLI debug_level=3 max_frag_len=4096" \
+            0 \
+            -c "client hello, adding max_fragment_length extension" \
+            -c "found max_fragment_length extension"
+
 # Tests for renegotiation
 
-run_test    "Renegotiation #0 (none)" \
-            "$P_SRV debug_level=4" \
-            "$P_CLI debug_level=4" \
+run_test    "Renegotiation: none, for reference" \
+            "$P_SRV debug_level=3 exchanges=2" \
+            "$P_CLI debug_level=3 exchanges=2" \
             0 \
             -C "client hello, adding renegotiation extension" \
             -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
@@ -566,9 +637,9 @@
             -S "=> renegotiate" \
             -S "write hello request"
 
-run_test    "Renegotiation #1 (enabled, client-initiated)" \
-            "$P_SRV debug_level=4 renegotiation=1" \
-            "$P_CLI debug_level=4 renegotiation=1 renegotiate=1" \
+run_test    "Renegotiation: client-initiated" \
+            "$P_SRV debug_level=3 exchanges=2 renegotiation=1" \
+            "$P_CLI debug_level=3 exchanges=2 renegotiation=1 renegotiate=1" \
             0 \
             -c "client hello, adding renegotiation extension" \
             -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
@@ -579,9 +650,9 @@
             -s "=> renegotiate" \
             -S "write hello request"
 
-run_test    "Renegotiation #2 (enabled, server-initiated)" \
-            "$P_SRV debug_level=4 renegotiation=1 renegotiate=1" \
-            "$P_CLI debug_level=4 renegotiation=1" \
+run_test    "Renegotiation: server-initiated" \
+            "$P_SRV debug_level=3 exchanges=2 renegotiation=1 renegotiate=1" \
+            "$P_CLI debug_level=3 exchanges=2 renegotiation=1" \
             0 \
             -c "client hello, adding renegotiation extension" \
             -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
@@ -592,9 +663,9 @@
             -s "=> renegotiate" \
             -s "write hello request"
 
-run_test    "Renegotiation #3 (enabled, double)" \
-            "$P_SRV debug_level=4 renegotiation=1 renegotiate=1" \
-            "$P_CLI debug_level=4 renegotiation=1 renegotiate=1" \
+run_test    "Renegotiation: double" \
+            "$P_SRV debug_level=3 exchanges=2 renegotiation=1 renegotiate=1" \
+            "$P_CLI debug_level=3 exchanges=2 renegotiation=1 renegotiate=1" \
             0 \
             -c "client hello, adding renegotiation extension" \
             -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
@@ -605,9 +676,9 @@
             -s "=> renegotiate" \
             -s "write hello request"
 
-run_test    "Renegotiation #4 (client-initiated, server-rejected)" \
-            "$P_SRV debug_level=4 renegotiation=0" \
-            "$P_CLI debug_level=4 renegotiation=1 renegotiate=1" \
+run_test    "Renegotiation: client-initiated, server-rejected" \
+            "$P_SRV debug_level=3 exchanges=2 renegotiation=0" \
+            "$P_CLI debug_level=3 exchanges=2 renegotiation=1 renegotiate=1" \
             1 \
             -c "client hello, adding renegotiation extension" \
             -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
@@ -617,12 +688,12 @@
             -c "=> renegotiate" \
             -S "=> renegotiate" \
             -S "write hello request" \
-            -c "SSL - An unexpected message was received from our peer" \
+            -c "SSL - Unexpected message at ServerHello in renegotiation" \
             -c "failed"
 
-run_test    "Renegotiation #5 (server-initiated, client-rejected, default)" \
-            "$P_SRV debug_level=4 renegotiation=1 renegotiate=1" \
-            "$P_CLI debug_level=4 renegotiation=0" \
+run_test    "Renegotiation: server-initiated, client-rejected, default" \
+            "$P_SRV debug_level=3 exchanges=2 renegotiation=1 renegotiate=1" \
+            "$P_CLI debug_level=3 exchanges=2 renegotiation=0" \
             0 \
             -C "client hello, adding renegotiation extension" \
             -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
@@ -635,10 +706,10 @@
             -S "SSL - An unexpected message was received from our peer" \
             -S "failed"
 
-run_test    "Renegotiation #6 (server-initiated, client-rejected, not enforced)" \
-            "$P_SRV debug_level=4 renegotiation=1 renegotiate=1 \
+run_test    "Renegotiation: server-initiated, client-rejected, not enforced" \
+            "$P_SRV debug_level=3 exchanges=2 renegotiation=1 renegotiate=1 \
              renego_delay=-1" \
-            "$P_CLI debug_level=4 renegotiation=0" \
+            "$P_CLI debug_level=3 exchanges=2 renegotiation=0" \
             0 \
             -C "client hello, adding renegotiation extension" \
             -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
@@ -651,10 +722,11 @@
             -S "SSL - An unexpected message was received from our peer" \
             -S "failed"
 
-run_test    "Renegotiation #7 (server-initiated, client-rejected, delay 1)" \
-            "$P_SRV debug_level=4 renegotiation=1 renegotiate=1 \
-             renego_delay=1" \
-            "$P_CLI debug_level=4 renegotiation=0" \
+# delay 2 for 1 alert record + 1 application data record
+run_test    "Renegotiation: server-initiated, client-rejected, delay 2" \
+            "$P_SRV debug_level=3 exchanges=2 renegotiation=1 renegotiate=1 \
+             renego_delay=2" \
+            "$P_CLI debug_level=3 exchanges=2 renegotiation=0" \
             0 \
             -C "client hello, adding renegotiation extension" \
             -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
@@ -667,10 +739,10 @@
             -S "SSL - An unexpected message was received from our peer" \
             -S "failed"
 
-run_test    "Renegotiation #8 (server-initiated, client-rejected, delay 0)" \
-            "$P_SRV debug_level=4 renegotiation=1 renegotiate=1 \
+run_test    "Renegotiation: server-initiated, client-rejected, delay 0" \
+            "$P_SRV debug_level=3 exchanges=2 renegotiation=1 renegotiate=1 \
              renego_delay=0" \
-            "$P_CLI debug_level=4 renegotiation=0" \
+            "$P_CLI debug_level=3 exchanges=2 renegotiation=0" \
             0 \
             -C "client hello, adding renegotiation extension" \
             -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
@@ -680,13 +752,12 @@
             -C "=> renegotiate" \
             -S "=> renegotiate" \
             -s "write hello request" \
-            -s "SSL - An unexpected message was received from our peer" \
-            -s "failed"
+            -s "SSL - An unexpected message was received from our peer"
 
-run_test    "Renegotiation #9 (server-initiated, client-accepted, delay 0)" \
-            "$P_SRV debug_level=4 renegotiation=1 renegotiate=1 \
+run_test    "Renegotiation: server-initiated, client-accepted, delay 0" \
+            "$P_SRV debug_level=3 exchanges=2 renegotiation=1 renegotiate=1 \
              renego_delay=0" \
-            "$P_CLI debug_level=4 renegotiation=1" \
+            "$P_CLI debug_level=3 exchanges=2 renegotiation=1" \
             0 \
             -c "client hello, adding renegotiation extension" \
             -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
@@ -699,41 +770,89 @@
             -S "SSL - An unexpected message was received from our peer" \
             -S "failed"
 
+run_test    "Renegotiation: nbio, client-initiated" \
+            "$P_SRV debug_level=3 nbio=2 exchanges=2 renegotiation=1" \
+            "$P_CLI debug_level=3 nbio=2 exchanges=2 renegotiation=1 renegotiate=1" \
+            0 \
+            -c "client hello, adding renegotiation extension" \
+            -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
+            -s "found renegotiation extension" \
+            -s "server hello, secure renegotiation extension" \
+            -c "found renegotiation extension" \
+            -c "=> renegotiate" \
+            -s "=> renegotiate" \
+            -S "write hello request"
+
+run_test    "Renegotiation: nbio, server-initiated" \
+            "$P_SRV debug_level=3 nbio=2 exchanges=2 renegotiation=1 renegotiate=1" \
+            "$P_CLI debug_level=3 nbio=2 exchanges=2 renegotiation=1" \
+            0 \
+            -c "client hello, adding renegotiation extension" \
+            -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
+            -s "found renegotiation extension" \
+            -s "server hello, secure renegotiation extension" \
+            -c "found renegotiation extension" \
+            -c "=> renegotiate" \
+            -s "=> renegotiate" \
+            -s "write hello request"
+
+run_test    "Renegotiation: openssl server, client-initiated" \
+            "$O_SRV" \
+            "$P_CLI debug_level=3 exchanges=1 renegotiation=1 renegotiate=1" \
+            0 \
+            -c "client hello, adding renegotiation extension" \
+            -c "found renegotiation extension" \
+            -c "=> renegotiate" \
+            -C "ssl_handshake returned" \
+            -C "error" \
+            -c "HTTP/1.0 200 [Oo][Kk]"
+
+run_test    "Renegotiation: gnutls server, client-initiated" \
+            "$G_SRV" \
+            "$P_CLI debug_level=3 exchanges=1 renegotiation=1 renegotiate=1" \
+            0 \
+            -c "client hello, adding renegotiation extension" \
+            -c "found renegotiation extension" \
+            -c "=> renegotiate" \
+            -C "ssl_handshake returned" \
+            -C "error" \
+            -c "HTTP/1.0 200 [Oo][Kk]"
+
 # Tests for auth_mode
 
-run_test    "Authentication #1 (server badcert, client required)" \
+run_test    "Authentication: server badcert, client required" \
             "$P_SRV crt_file=data_files/server5-badsign.crt \
              key_file=data_files/server5.key" \
-            "$P_CLI debug_level=2 auth_mode=required" \
+            "$P_CLI debug_level=1 auth_mode=required" \
             1 \
             -c "x509_verify_cert() returned" \
             -c "! self-signed or not signed by a trusted CA" \
             -c "! ssl_handshake returned" \
             -c "X509 - Certificate verification failed"
 
-run_test    "Authentication #2 (server badcert, client optional)" \
+run_test    "Authentication: server badcert, client optional" \
             "$P_SRV crt_file=data_files/server5-badsign.crt \
              key_file=data_files/server5.key" \
-            "$P_CLI debug_level=2 auth_mode=optional" \
+            "$P_CLI debug_level=1 auth_mode=optional" \
             0 \
             -c "x509_verify_cert() returned" \
             -c "! self-signed or not signed by a trusted CA" \
             -C "! ssl_handshake returned" \
             -C "X509 - Certificate verification failed"
 
-run_test    "Authentication #3 (server badcert, client none)" \
+run_test    "Authentication: server badcert, client none" \
             "$P_SRV crt_file=data_files/server5-badsign.crt \
              key_file=data_files/server5.key" \
-            "$P_CLI debug_level=2 auth_mode=none" \
+            "$P_CLI debug_level=1 auth_mode=none" \
             0 \
             -C "x509_verify_cert() returned" \
             -C "! self-signed or not signed by a trusted CA" \
             -C "! ssl_handshake returned" \
             -C "X509 - Certificate verification failed"
 
-run_test    "Authentication #4 (client badcert, server required)" \
-            "$P_SRV debug_level=4 auth_mode=required" \
-            "$P_CLI debug_level=4 crt_file=data_files/server5-badsign.crt \
+run_test    "Authentication: client badcert, server required" \
+            "$P_SRV debug_level=3 auth_mode=required" \
+            "$P_CLI debug_level=3 crt_file=data_files/server5-badsign.crt \
              key_file=data_files/server5.key" \
             1 \
             -S "skip write certificate request" \
@@ -748,9 +867,9 @@
             -c "! ssl_handshake returned" \
             -s "X509 - Certificate verification failed"
 
-run_test    "Authentication #5 (client badcert, server optional)" \
-            "$P_SRV debug_level=4 auth_mode=optional" \
-            "$P_CLI debug_level=4 crt_file=data_files/server5-badsign.crt \
+run_test    "Authentication: client badcert, server optional" \
+            "$P_SRV debug_level=3 auth_mode=optional" \
+            "$P_CLI debug_level=3 crt_file=data_files/server5-badsign.crt \
              key_file=data_files/server5.key" \
             0 \
             -S "skip write certificate request" \
@@ -765,9 +884,9 @@
             -C "! ssl_handshake returned" \
             -S "X509 - Certificate verification failed"
 
-run_test    "Authentication #6 (client badcert, server none)" \
-            "$P_SRV debug_level=4 auth_mode=none" \
-            "$P_CLI debug_level=4 crt_file=data_files/server5-badsign.crt \
+run_test    "Authentication: client badcert, server none" \
+            "$P_SRV debug_level=3 auth_mode=none" \
+            "$P_CLI debug_level=3 crt_file=data_files/server5-badsign.crt \
              key_file=data_files/server5.key" \
             0 \
             -s "skip write certificate request" \
@@ -782,9 +901,9 @@
             -C "! ssl_handshake returned" \
             -S "X509 - Certificate verification failed"
 
-run_test    "Authentication #7 (client no cert, server optional)" \
-            "$P_SRV debug_level=4 auth_mode=optional" \
-            "$P_CLI debug_level=4 crt_file=none key_file=none" \
+run_test    "Authentication: client no cert, server optional" \
+            "$P_SRV debug_level=3 auth_mode=optional" \
+            "$P_CLI debug_level=3 crt_file=none key_file=none" \
             0 \
             -S "skip write certificate request" \
             -C "skip parse certificate request" \
@@ -799,8 +918,8 @@
             -C "! ssl_handshake returned" \
             -S "X509 - Certificate verification failed"
 
-run_test    "Authentication #8 (openssl client no cert, server optional)" \
-            "$P_SRV debug_level=4 auth_mode=optional" \
+run_test    "Authentication: openssl client no cert, server optional" \
+            "$P_SRV debug_level=3 auth_mode=optional" \
             "$O_CLI" \
             0 \
             -S "skip write certificate request" \
@@ -809,9 +928,9 @@
             -S "! ssl_handshake returned" \
             -S "X509 - Certificate verification failed"
 
-run_test    "Authentication #9 (client no cert, openssl server optional)" \
+run_test    "Authentication: client no cert, openssl server optional" \
             "$O_SRV -verify 10" \
-            "$P_CLI debug_level=4 crt_file=none key_file=none" \
+            "$P_CLI debug_level=3 crt_file=none key_file=none" \
             0 \
             -C "skip parse certificate request" \
             -c "got a certificate request" \
@@ -819,9 +938,9 @@
             -c "skip write certificate verify" \
             -C "! ssl_handshake returned"
 
-run_test    "Authentication #10 (client no cert, ssl3)" \
-            "$P_SRV debug_level=4 auth_mode=optional force_version=ssl3" \
-            "$P_CLI debug_level=4 crt_file=none key_file=none" \
+run_test    "Authentication: client no cert, ssl3" \
+            "$P_SRV debug_level=3 auth_mode=optional force_version=ssl3" \
+            "$P_CLI debug_level=3 crt_file=none key_file=none" \
             0 \
             -S "skip write certificate request" \
             -C "skip parse certificate request" \
@@ -838,8 +957,8 @@
 
 # tests for SNI
 
-run_test    "SNI #0 (no SNI callback)" \
-            "$P_SRV debug_level=4 server_addr=127.0.0.1 \
+run_test    "SNI: no SNI callback" \
+            "$P_SRV debug_level=3 server_addr=127.0.0.1 \
              crt_file=data_files/server5.crt key_file=data_files/server5.key" \
             "$P_CLI debug_level=0 server_addr=127.0.0.1 \
              server_name=localhost" \
@@ -848,8 +967,8 @@
              -c "issuer name *: C=NL, O=PolarSSL, CN=Polarssl Test EC CA" \
              -c "subject name *: C=NL, O=PolarSSL, CN=localhost"
 
-run_test    "SNI #1 (matching cert 1)" \
-            "$P_SRV debug_level=4 server_addr=127.0.0.1 \
+run_test    "SNI: matching cert 1" \
+            "$P_SRV debug_level=3 server_addr=127.0.0.1 \
              crt_file=data_files/server5.crt key_file=data_files/server5.key \
              sni=localhost,data_files/server2.crt,data_files/server2.key,polarssl.example,data_files/server1-nospace.crt,data_files/server1.key" \
             "$P_CLI debug_level=0 server_addr=127.0.0.1 \
@@ -859,8 +978,8 @@
              -c "issuer name *: C=NL, O=PolarSSL, CN=PolarSSL Test CA" \
              -c "subject name *: C=NL, O=PolarSSL, CN=localhost"
 
-run_test    "SNI #2 (matching cert 2)" \
-            "$P_SRV debug_level=4 server_addr=127.0.0.1 \
+run_test    "SNI: matching cert 2" \
+            "$P_SRV debug_level=3 server_addr=127.0.0.1 \
              crt_file=data_files/server5.crt key_file=data_files/server5.key \
              sni=localhost,data_files/server2.crt,data_files/server2.key,polarssl.example,data_files/server1-nospace.crt,data_files/server1.key" \
             "$P_CLI debug_level=0 server_addr=127.0.0.1 \
@@ -870,8 +989,8 @@
              -c "issuer name *: C=NL, O=PolarSSL, CN=PolarSSL Test CA" \
              -c "subject name *: C=NL, O=PolarSSL, CN=polarssl.example"
 
-run_test    "SNI #3 (no matching cert)" \
-            "$P_SRV debug_level=4 server_addr=127.0.0.1 \
+run_test    "SNI: no matching cert" \
+            "$P_SRV debug_level=3 server_addr=127.0.0.1 \
              crt_file=data_files/server5.crt key_file=data_files/server5.key \
              sni=localhost,data_files/server2.crt,data_files/server2.key,polarssl.example,data_files/server1-nospace.crt,data_files/server1.key" \
             "$P_CLI debug_level=0 server_addr=127.0.0.1 \
@@ -885,7 +1004,7 @@
 
 # Tests for non-blocking I/O: exercise a variety of handshake flows
 
-run_test    "Non-blocking I/O #1 (basic handshake)" \
+run_test    "Non-blocking I/O: basic handshake" \
             "$P_SRV nbio=2 tickets=0 auth_mode=none" \
             "$P_CLI nbio=2 tickets=0" \
             0 \
@@ -893,7 +1012,7 @@
             -C "ssl_handshake returned" \
             -c "Read from server: .* bytes read"
 
-run_test    "Non-blocking I/O #2 (client auth)" \
+run_test    "Non-blocking I/O: client auth" \
             "$P_SRV nbio=2 tickets=0 auth_mode=required" \
             "$P_CLI nbio=2 tickets=0" \
             0 \
@@ -901,7 +1020,7 @@
             -C "ssl_handshake returned" \
             -c "Read from server: .* bytes read"
 
-run_test    "Non-blocking I/O #3 (ticket)" \
+run_test    "Non-blocking I/O: ticket" \
             "$P_SRV nbio=2 tickets=1 auth_mode=none" \
             "$P_CLI nbio=2 tickets=1" \
             0 \
@@ -909,7 +1028,7 @@
             -C "ssl_handshake returned" \
             -c "Read from server: .* bytes read"
 
-run_test    "Non-blocking I/O #4 (ticket + client auth)" \
+run_test    "Non-blocking I/O: ticket + client auth" \
             "$P_SRV nbio=2 tickets=1 auth_mode=required" \
             "$P_CLI nbio=2 tickets=1" \
             0 \
@@ -917,7 +1036,7 @@
             -C "ssl_handshake returned" \
             -c "Read from server: .* bytes read"
 
-run_test    "Non-blocking I/O #5 (ticket + client auth + resume)" \
+run_test    "Non-blocking I/O: ticket + client auth + resume" \
             "$P_SRV nbio=2 tickets=1 auth_mode=required" \
             "$P_CLI nbio=2 tickets=1 reconnect=1" \
             0 \
@@ -925,7 +1044,7 @@
             -C "ssl_handshake returned" \
             -c "Read from server: .* bytes read"
 
-run_test    "Non-blocking I/O #6 (ticket + resume)" \
+run_test    "Non-blocking I/O: ticket + resume" \
             "$P_SRV nbio=2 tickets=1 auth_mode=none" \
             "$P_CLI nbio=2 tickets=1 reconnect=1" \
             0 \
@@ -933,7 +1052,7 @@
             -C "ssl_handshake returned" \
             -c "Read from server: .* bytes read"
 
-run_test    "Non-blocking I/O #7 (session-id resume)" \
+run_test    "Non-blocking I/O: session-id resume" \
             "$P_SRV nbio=2 tickets=0 auth_mode=none" \
             "$P_CLI nbio=2 tickets=0 reconnect=1" \
             0 \
@@ -943,7 +1062,7 @@
 
 # Tests for version negotiation
 
-run_test    "Version check #1 (all -> 1.2)" \
+run_test    "Version check: all -> 1.2" \
             "$P_SRV" \
             "$P_CLI" \
             0 \
@@ -952,7 +1071,7 @@
             -s "Protocol is TLSv1.2" \
             -c "Protocol is TLSv1.2"
 
-run_test    "Version check #2 (cli max 1.1 -> 1.1)" \
+run_test    "Version check: cli max 1.1 -> 1.1" \
             "$P_SRV" \
             "$P_CLI max_version=tls1_1" \
             0 \
@@ -961,7 +1080,7 @@
             -s "Protocol is TLSv1.1" \
             -c "Protocol is TLSv1.1"
 
-run_test    "Version check #3 (srv max 1.1 -> 1.1)" \
+run_test    "Version check: srv max 1.1 -> 1.1" \
             "$P_SRV max_version=tls1_1" \
             "$P_CLI" \
             0 \
@@ -970,7 +1089,7 @@
             -s "Protocol is TLSv1.1" \
             -c "Protocol is TLSv1.1"
 
-run_test    "Version check #4 (cli+srv max 1.1 -> 1.1)" \
+run_test    "Version check: cli+srv max 1.1 -> 1.1" \
             "$P_SRV max_version=tls1_1" \
             "$P_CLI max_version=tls1_1" \
             0 \
@@ -979,7 +1098,7 @@
             -s "Protocol is TLSv1.1" \
             -c "Protocol is TLSv1.1"
 
-run_test    "Version check #5 (cli max 1.1, srv min 1.1 -> 1.1)" \
+run_test    "Version check: cli max 1.1, srv min 1.1 -> 1.1" \
             "$P_SRV min_version=tls1_1" \
             "$P_CLI max_version=tls1_1" \
             0 \
@@ -988,7 +1107,7 @@
             -s "Protocol is TLSv1.1" \
             -c "Protocol is TLSv1.1"
 
-run_test    "Version check #6 (cli min 1.1, srv max 1.1 -> 1.1)" \
+run_test    "Version check: cli min 1.1, srv max 1.1 -> 1.1" \
             "$P_SRV max_version=tls1_1" \
             "$P_CLI min_version=tls1_1" \
             0 \
@@ -997,7 +1116,7 @@
             -s "Protocol is TLSv1.1" \
             -c "Protocol is TLSv1.1"
 
-run_test    "Version check #7 (cli min 1.2, srv max 1.1 -> fail)" \
+run_test    "Version check: cli min 1.2, srv max 1.1 -> fail" \
             "$P_SRV max_version=tls1_1" \
             "$P_CLI min_version=tls1_2" \
             1 \
@@ -1005,7 +1124,7 @@
             -c "ssl_handshake returned" \
             -c "SSL - Handshake protocol not within min/max boundaries"
 
-run_test    "Version check #8 (srv min 1.2, cli max 1.1 -> fail)" \
+run_test    "Version check: srv min 1.2, cli max 1.1 -> fail" \
             "$P_SRV min_version=tls1_2" \
             "$P_CLI max_version=tls1_1" \
             1 \
@@ -1017,9 +1136,9 @@
 
 if grep '^#define POLARSSL_SSL_ALPN' $CONFIG_H >/dev/null; then
 
-run_test    "ALPN #0 (none)" \
-            "$P_SRV debug_level=4" \
-            "$P_CLI debug_level=4" \
+run_test    "ALPN: none" \
+            "$P_SRV debug_level=3" \
+            "$P_CLI debug_level=3" \
             0 \
             -C "client hello, adding alpn extension" \
             -S "found alpn extension" \
@@ -1029,9 +1148,9 @@
             -C "Application Layer Protocol is" \
             -S "Application Layer Protocol is"
 
-run_test    "ALPN #1 (client only)" \
-            "$P_SRV debug_level=4" \
-            "$P_CLI debug_level=4 alpn=abc,1234" \
+run_test    "ALPN: client only" \
+            "$P_SRV debug_level=3" \
+            "$P_CLI debug_level=3 alpn=abc,1234" \
             0 \
             -c "client hello, adding alpn extension" \
             -s "found alpn extension" \
@@ -1041,9 +1160,9 @@
             -c "Application Layer Protocol is (none)" \
             -S "Application Layer Protocol is"
 
-run_test    "ALPN #2 (server only)" \
-            "$P_SRV debug_level=4 alpn=abc,1234" \
-            "$P_CLI debug_level=4" \
+run_test    "ALPN: server only" \
+            "$P_SRV debug_level=3 alpn=abc,1234" \
+            "$P_CLI debug_level=3" \
             0 \
             -C "client hello, adding alpn extension" \
             -S "found alpn extension" \
@@ -1053,9 +1172,9 @@
             -C "Application Layer Protocol is" \
             -s "Application Layer Protocol is (none)"
 
-run_test    "ALPN #3 (both, common cli1-srv1)" \
-            "$P_SRV debug_level=4 alpn=abc,1234" \
-            "$P_CLI debug_level=4 alpn=abc,1234" \
+run_test    "ALPN: both, common cli1-srv1" \
+            "$P_SRV debug_level=3 alpn=abc,1234" \
+            "$P_CLI debug_level=3 alpn=abc,1234" \
             0 \
             -c "client hello, adding alpn extension" \
             -s "found alpn extension" \
@@ -1065,9 +1184,9 @@
             -c "Application Layer Protocol is abc" \
             -s "Application Layer Protocol is abc"
 
-run_test    "ALPN #4 (both, common cli2-srv1)" \
-            "$P_SRV debug_level=4 alpn=abc,1234" \
-            "$P_CLI debug_level=4 alpn=1234,abc" \
+run_test    "ALPN: both, common cli2-srv1" \
+            "$P_SRV debug_level=3 alpn=abc,1234" \
+            "$P_CLI debug_level=3 alpn=1234,abc" \
             0 \
             -c "client hello, adding alpn extension" \
             -s "found alpn extension" \
@@ -1077,9 +1196,9 @@
             -c "Application Layer Protocol is abc" \
             -s "Application Layer Protocol is abc"
 
-run_test    "ALPN #5 (both, common cli1-srv2)" \
-            "$P_SRV debug_level=4 alpn=abc,1234" \
-            "$P_CLI debug_level=4 alpn=1234,abcde" \
+run_test    "ALPN: both, common cli1-srv2" \
+            "$P_SRV debug_level=3 alpn=abc,1234" \
+            "$P_CLI debug_level=3 alpn=1234,abcde" \
             0 \
             -c "client hello, adding alpn extension" \
             -s "found alpn extension" \
@@ -1089,9 +1208,9 @@
             -c "Application Layer Protocol is 1234" \
             -s "Application Layer Protocol is 1234"
 
-run_test    "ALPN #6 (both, no common)" \
-            "$P_SRV debug_level=4 alpn=abc,123" \
-            "$P_CLI debug_level=4 alpn=1234,abcde" \
+run_test    "ALPN: both, no common" \
+            "$P_SRV debug_level=3 alpn=abc,123" \
+            "$P_CLI debug_level=3 alpn=1234,abcde" \
             1 \
             -c "client hello, adding alpn extension" \
             -s "found alpn extension" \
@@ -1106,7 +1225,7 @@
 # Tests for keyUsage in leaf certificates, part 1:
 # server-side certificate/suite selection
 
-run_test    "keyUsage srv #1 (RSA, digitalSignature -> (EC)DHE-RSA)" \
+run_test    "keyUsage srv: RSA, digitalSignature -> (EC)DHE-RSA" \
             "$P_SRV key_file=data_files/server2.key \
              crt_file=data_files/server2.ku-ds.crt" \
             "$P_CLI" \
@@ -1114,22 +1233,21 @@
             -c "Ciphersuite is TLS-[EC]*DHE-RSA-WITH-"
 
 
-run_test    "keyUsage srv #2 (RSA, keyEncipherment -> RSA)" \
+run_test    "keyUsage srv: RSA, keyEncipherment -> RSA" \
             "$P_SRV key_file=data_files/server2.key \
              crt_file=data_files/server2.ku-ke.crt" \
             "$P_CLI" \
             0 \
             -c "Ciphersuite is TLS-RSA-WITH-"
 
-# add psk to leave an option for client to send SERVERQUIT
-run_test    "keyUsage srv #3 (RSA, keyAgreement -> fail)" \
-            "$P_SRV psk=abc123 key_file=data_files/server2.key \
+run_test    "keyUsage srv: RSA, keyAgreement -> fail" \
+            "$P_SRV key_file=data_files/server2.key \
              crt_file=data_files/server2.ku-ka.crt" \
-            "$P_CLI psk=badbad" \
+            "$P_CLI" \
             1 \
             -C "Ciphersuite is "
 
-run_test    "keyUsage srv #4 (ECDSA, digitalSignature -> ECDHE-ECDSA)" \
+run_test    "keyUsage srv: ECDSA, digitalSignature -> ECDHE-ECDSA" \
             "$P_SRV key_file=data_files/server5.key \
              crt_file=data_files/server5.ku-ds.crt" \
             "$P_CLI" \
@@ -1137,78 +1255,77 @@
             -c "Ciphersuite is TLS-ECDHE-ECDSA-WITH-"
 
 
-run_test    "keyUsage srv #5 (ECDSA, keyAgreement -> ECDH-)" \
+run_test    "keyUsage srv: ECDSA, keyAgreement -> ECDH-" \
             "$P_SRV key_file=data_files/server5.key \
              crt_file=data_files/server5.ku-ka.crt" \
             "$P_CLI" \
             0 \
             -c "Ciphersuite is TLS-ECDH-"
 
-# add psk to leave an option for client to send SERVERQUIT
-run_test    "keyUsage srv #6 (ECDSA, keyEncipherment -> fail)" \
-            "$P_SRV psk=abc123 key_file=data_files/server5.key \
+run_test    "keyUsage srv: ECDSA, keyEncipherment -> fail" \
+            "$P_SRV key_file=data_files/server5.key \
              crt_file=data_files/server5.ku-ke.crt" \
-            "$P_CLI psk=badbad" \
+            "$P_CLI" \
             1 \
             -C "Ciphersuite is "
 
 # Tests for keyUsage in leaf certificates, part 2:
 # client-side checking of server cert
 
-run_test    "keyUsage cli #1 (DigitalSignature+KeyEncipherment, RSA: OK)" \
+run_test    "keyUsage cli: DigitalSignature+KeyEncipherment, RSA: OK" \
             "$O_SRV -key data_files/server2.key \
              -cert data_files/server2.ku-ds_ke.crt" \
-            "$P_CLI debug_level=2 \
+            "$P_CLI debug_level=1 \
              force_ciphersuite=TLS-RSA-WITH-AES-128-CBC-SHA" \
             0 \
             -C "bad certificate (usage extensions)" \
             -C "Processing of the Certificate handshake message failed" \
             -c "Ciphersuite is TLS-"
 
-run_test    "keyUsage cli #2 (DigitalSignature+KeyEncipherment, DHE-RSA: OK)" \
+run_test    "keyUsage cli: DigitalSignature+KeyEncipherment, DHE-RSA: OK" \
             "$O_SRV -key data_files/server2.key \
              -cert data_files/server2.ku-ds_ke.crt" \
-            "$P_CLI debug_level=2 \
+            "$P_CLI debug_level=1 \
              force_ciphersuite=TLS-DHE-RSA-WITH-AES-128-CBC-SHA" \
             0 \
             -C "bad certificate (usage extensions)" \
             -C "Processing of the Certificate handshake message failed" \
             -c "Ciphersuite is TLS-"
 
-run_test    "keyUsage cli #3 (KeyEncipherment, RSA: OK)" \
+run_test    "keyUsage cli: KeyEncipherment, RSA: OK" \
             "$O_SRV -key data_files/server2.key \
              -cert data_files/server2.ku-ke.crt" \
-            "$P_CLI debug_level=2 \
+            "$P_CLI debug_level=1 \
              force_ciphersuite=TLS-RSA-WITH-AES-128-CBC-SHA" \
             0 \
             -C "bad certificate (usage extensions)" \
             -C "Processing of the Certificate handshake message failed" \
             -c "Ciphersuite is TLS-"
 
-run_test    "keyUsage cli #4 (KeyEncipherment, DHE-RSA: fail)" \
+run_test    "keyUsage cli: KeyEncipherment, DHE-RSA: fail" \
             "$O_SRV -key data_files/server2.key \
              -cert data_files/server2.ku-ke.crt" \
-            "$P_CLI debug_level=2 \
+            "$P_CLI debug_level=1 \
              force_ciphersuite=TLS-DHE-RSA-WITH-AES-128-CBC-SHA" \
             1 \
             -c "bad certificate (usage extensions)" \
             -c "Processing of the Certificate handshake message failed" \
             -C "Ciphersuite is TLS-"
 
-run_test    "keyUsage cli #5 (DigitalSignature, DHE-RSA: OK)" \
+run_test    "keyUsage cli: DigitalSignature, DHE-RSA: OK" \
             "$O_SRV -key data_files/server2.key \
              -cert data_files/server2.ku-ds.crt" \
-            "$P_CLI debug_level=2 \
+            "$P_CLI debug_level=1 \
              force_ciphersuite=TLS-DHE-RSA-WITH-AES-128-CBC-SHA" \
             0 \
             -C "bad certificate (usage extensions)" \
             -C "Processing of the Certificate handshake message failed" \
             -c "Ciphersuite is TLS-"
 
-run_test    "keyUsage cli #5 (DigitalSignature, RSA: fail)" \
+run_test    "keyUsage cli: DigitalSignature, RSA: fail" \
             "$O_SRV -key data_files/server2.key \
              -cert data_files/server2.ku-ds.crt" \
-            "$P_CLI debug_level=2 \
+            "$P_CLI debug_level=1 \
              force_ciphersuite=TLS-RSA-WITH-AES-128-CBC-SHA" \
             1 \
             -c "bad certificate (usage extensions)" \
@@ -1218,40 +1335,40 @@
 # Tests for keyUsage in leaf certificates, part 3:
 # server-side checking of client cert
 
-run_test    "keyUsage cli-auth #1 (RSA, DigitalSignature: OK)" \
-            "$P_SRV debug_level=2 auth_mode=optional" \
+run_test    "keyUsage cli-auth: RSA, DigitalSignature: OK" \
+            "$P_SRV debug_level=1 auth_mode=optional" \
             "$O_CLI -key data_files/server2.key \
              -cert data_files/server2.ku-ds.crt" \
             0 \
             -S "bad certificate (usage extensions)" \
             -S "Processing of the Certificate handshake message failed"
 
-run_test    "keyUsage cli-auth #2 (RSA, KeyEncipherment: fail (soft))" \
-            "$P_SRV debug_level=2 auth_mode=optional" \
+run_test    "keyUsage cli-auth: RSA, KeyEncipherment: fail (soft)" \
+            "$P_SRV debug_level=1 auth_mode=optional" \
             "$O_CLI -key data_files/server2.key \
              -cert data_files/server2.ku-ke.crt" \
             0 \
             -s "bad certificate (usage extensions)" \
             -S "Processing of the Certificate handshake message failed"
 
-run_test    "keyUsage cli-auth #3 (RSA, KeyEncipherment: fail (hard))" \
-            "$P_SRV debug_level=2 auth_mode=required" \
+run_test    "keyUsage cli-auth: RSA, KeyEncipherment: fail (hard)" \
+            "$P_SRV debug_level=1 auth_mode=required" \
             "$O_CLI -key data_files/server2.key \
              -cert data_files/server2.ku-ke.crt" \
             1 \
             -s "bad certificate (usage extensions)" \
             -s "Processing of the Certificate handshake message failed"
 
-run_test    "keyUsage cli-auth #4 (ECDSA, DigitalSignature: OK)" \
-            "$P_SRV debug_level=2 auth_mode=optional" \
+run_test    "keyUsage cli-auth: ECDSA, DigitalSignature: OK" \
+            "$P_SRV debug_level=1 auth_mode=optional" \
             "$O_CLI -key data_files/server5.key \
              -cert data_files/server5.ku-ds.crt" \
             0 \
             -S "bad certificate (usage extensions)" \
             -S "Processing of the Certificate handshake message failed"
 
-run_test    "keyUsage cli-auth #5 (ECDSA, KeyAgreement: fail (soft))" \
-            "$P_SRV debug_level=2 auth_mode=optional" \
+run_test    "keyUsage cli-auth: ECDSA, KeyAgreement: fail (soft)" \
+            "$P_SRV debug_level=1 auth_mode=optional" \
             "$O_CLI -key data_files/server5.key \
              -cert data_files/server5.ku-ka.crt" \
             0 \
@@ -1260,26 +1377,26 @@
 
 # Tests for extendedKeyUsage, part 1: server-side certificate/suite selection
 
-run_test    "extKeyUsage srv #1 (serverAuth -> OK)" \
+run_test    "extKeyUsage srv: serverAuth -> OK" \
             "$P_SRV key_file=data_files/server5.key \
              crt_file=data_files/server5.eku-srv.crt" \
             "$P_CLI" \
             0
 
-run_test    "extKeyUsage srv #2 (serverAuth,clientAuth -> OK)" \
+run_test    "extKeyUsage srv: serverAuth,clientAuth -> OK" \
             "$P_SRV key_file=data_files/server5.key \
              crt_file=data_files/server5.eku-srv.crt" \
             "$P_CLI" \
             0
 
-run_test    "extKeyUsage srv #3 (codeSign,anyEKU -> OK)" \
+run_test    "extKeyUsage srv: codeSign,anyEKU -> OK" \
             "$P_SRV key_file=data_files/server5.key \
              crt_file=data_files/server5.eku-cs_any.crt" \
             "$P_CLI" \
             0
 
 # add psk to leave an option for client to send SERVERQUIT
-run_test    "extKeyUsage srv #4 (codeSign -> fail)" \
+run_test    "extKeyUsage srv: codeSign -> fail" \
             "$P_SRV psk=abc123 key_file=data_files/server5.key \
              crt_file=data_files/server5.eku-cli.crt" \
             "$P_CLI psk=badbad" \
@@ -1287,37 +1404,37 @@
 
 # Tests for extendedKeyUsage, part 2: client-side checking of server cert
 
-run_test    "extKeyUsage cli #1 (serverAuth -> OK)" \
+run_test    "extKeyUsage cli: serverAuth -> OK" \
             "$O_SRV -key data_files/server5.key \
              -cert data_files/server5.eku-srv.crt" \
-            "$P_CLI debug_level=2" \
+            "$P_CLI debug_level=1" \
             0 \
             -C "bad certificate (usage extensions)" \
             -C "Processing of the Certificate handshake message failed" \
             -c "Ciphersuite is TLS-"
 
-run_test    "extKeyUsage cli #2 (serverAuth,clientAuth -> OK)" \
+run_test    "extKeyUsage cli: serverAuth,clientAuth -> OK" \
             "$O_SRV -key data_files/server5.key \
              -cert data_files/server5.eku-srv_cli.crt" \
-            "$P_CLI debug_level=2" \
+            "$P_CLI debug_level=1" \
             0 \
             -C "bad certificate (usage extensions)" \
             -C "Processing of the Certificate handshake message failed" \
             -c "Ciphersuite is TLS-"
 
-run_test    "extKeyUsage cli #3 (codeSign,anyEKU -> OK)" \
+run_test    "extKeyUsage cli: codeSign,anyEKU -> OK" \
             "$O_SRV -key data_files/server5.key \
              -cert data_files/server5.eku-cs_any.crt" \
-            "$P_CLI debug_level=2" \
+            "$P_CLI debug_level=1" \
             0 \
             -C "bad certificate (usage extensions)" \
             -C "Processing of the Certificate handshake message failed" \
             -c "Ciphersuite is TLS-"
 
-run_test    "extKeyUsage cli #4 (codeSign -> fail)" \
+run_test    "extKeyUsage cli: codeSign -> fail" \
             "$O_SRV -key data_files/server5.key \
              -cert data_files/server5.eku-cs.crt" \
-            "$P_CLI debug_level=2" \
+            "$P_CLI debug_level=1" \
             1 \
             -c "bad certificate (usage extensions)" \
             -c "Processing of the Certificate handshake message failed" \
@@ -1325,40 +1442,40 @@
 
 # Tests for extendedKeyUsage, part 3: server-side checking of client cert
 
-run_test    "extKeyUsage cli-auth #1 (clientAuth -> OK)" \
-            "$P_SRV debug_level=2 auth_mode=optional" \
+run_test    "extKeyUsage cli-auth: clientAuth -> OK" \
+            "$P_SRV debug_level=1 auth_mode=optional" \
             "$O_CLI -key data_files/server5.key \
              -cert data_files/server5.eku-cli.crt" \
             0 \
             -S "bad certificate (usage extensions)" \
             -S "Processing of the Certificate handshake message failed"
 
-run_test    "extKeyUsage cli-auth #2 (serverAuth,clientAuth -> OK)" \
-            "$P_SRV debug_level=2 auth_mode=optional" \
+run_test    "extKeyUsage cli-auth: serverAuth,clientAuth -> OK" \
+            "$P_SRV debug_level=1 auth_mode=optional" \
             "$O_CLI -key data_files/server5.key \
              -cert data_files/server5.eku-srv_cli.crt" \
             0 \
             -S "bad certificate (usage extensions)" \
             -S "Processing of the Certificate handshake message failed"
 
-run_test    "extKeyUsage cli-auth #3 (codeSign,anyEKU -> OK)" \
-            "$P_SRV debug_level=2 auth_mode=optional" \
+run_test    "extKeyUsage cli-auth: codeSign,anyEKU -> OK" \
+            "$P_SRV debug_level=1 auth_mode=optional" \
             "$O_CLI -key data_files/server5.key \
              -cert data_files/server5.eku-cs_any.crt" \
             0 \
             -S "bad certificate (usage extensions)" \
             -S "Processing of the Certificate handshake message failed"
 
-run_test    "extKeyUsage cli-auth #4 (codeSign -> fail (soft))" \
-            "$P_SRV debug_level=2 auth_mode=optional" \
+run_test    "extKeyUsage cli-auth: codeSign -> fail (soft)" \
+            "$P_SRV debug_level=1 auth_mode=optional" \
             "$O_CLI -key data_files/server5.key \
              -cert data_files/server5.eku-cs.crt" \
             0 \
             -s "bad certificate (usage extensions)" \
             -S "Processing of the Certificate handshake message failed"
 
-run_test    "extKeyUsage cli-auth #4b (codeSign -> fail (hard))" \
-            "$P_SRV debug_level=2 auth_mode=required" \
+run_test    "extKeyUsage cli-auth: codeSign -> fail (hard)" \
+            "$P_SRV debug_level=1 auth_mode=required" \
             "$O_CLI -key data_files/server5.key \
              -cert data_files/server5.eku-cs.crt" \
             1 \
@@ -1367,7 +1484,7 @@
 
 # Tests for DHM parameters loading
 
-run_test    "DHM parameters #0 (reference)" \
+run_test    "DHM parameters: reference" \
             "$P_SRV" \
             "$P_CLI force_ciphersuite=TLS-DHE-RSA-WITH-AES-128-CBC-SHA \
                     debug_level=3" \
@@ -1375,7 +1492,7 @@
             -c "value of 'DHM: P ' (2048 bits)" \
             -c "value of 'DHM: G ' (2048 bits)"
 
-run_test    "DHM parameters #1 (other parameters)" \
+run_test    "DHM parameters: other parameters" \
             "$P_SRV dhm_file=data_files/dhparams.pem" \
             "$P_CLI force_ciphersuite=TLS-DHE-RSA-WITH-AES-128-CBC-SHA \
                     debug_level=3" \
@@ -1385,7 +1502,7 @@
 
 # Tests for PSK callback
 
-run_test    "PSK callback #0a (psk, no callback)" \
+run_test    "PSK callback: psk, no callback" \
             "$P_SRV psk=abc123 psk_identity=foo" \
             "$P_CLI force_ciphersuite=TLS-PSK-WITH-AES-128-CBC-SHA \
             psk_identity=foo psk=abc123" \
@@ -1394,7 +1511,7 @@
             -S "SSL - Unknown identity received" \
             -S "SSL - Verification of the message MAC failed"
 
-run_test    "PSK callback #0b (no psk, no callback)" \
+run_test    "PSK callback: no psk, no callback" \
             "$P_SRV" \
             "$P_CLI force_ciphersuite=TLS-PSK-WITH-AES-128-CBC-SHA \
             psk_identity=foo psk=abc123" \
@@ -1403,7 +1520,7 @@
             -S "SSL - Unknown identity received" \
             -S "SSL - Verification of the message MAC failed"
 
-run_test    "PSK callback #1 (callback overrides other settings)" \
+run_test    "PSK callback: callback overrides other settings" \
             "$P_SRV psk=abc123 psk_identity=foo psk_list=abc,dead,def,beef" \
             "$P_CLI force_ciphersuite=TLS-PSK-WITH-AES-128-CBC-SHA \
             psk_identity=foo psk=abc123" \
@@ -1412,7 +1529,7 @@
             -s "SSL - Unknown identity received" \
             -S "SSL - Verification of the message MAC failed"
 
-run_test    "PSK callback #2 (first id matches)" \
+run_test    "PSK callback: first id matches" \
             "$P_SRV psk_list=abc,dead,def,beef" \
             "$P_CLI force_ciphersuite=TLS-PSK-WITH-AES-128-CBC-SHA \
             psk_identity=abc psk=dead" \
@@ -1421,7 +1538,7 @@
             -S "SSL - Unknown identity received" \
             -S "SSL - Verification of the message MAC failed"
 
-run_test    "PSK callback #3 (second id matches)" \
+run_test    "PSK callback: second id matches" \
             "$P_SRV psk_list=abc,dead,def,beef" \
             "$P_CLI force_ciphersuite=TLS-PSK-WITH-AES-128-CBC-SHA \
             psk_identity=def psk=beef" \
@@ -1430,7 +1547,7 @@
             -S "SSL - Unknown identity received" \
             -S "SSL - Verification of the message MAC failed"
 
-run_test    "PSK callback #4 (no match)" \
+run_test    "PSK callback: no match" \
             "$P_SRV psk_list=abc,dead,def,beef" \
             "$P_CLI force_ciphersuite=TLS-PSK-WITH-AES-128-CBC-SHA \
             psk_identity=ghi psk=beef" \
@@ -1439,7 +1556,7 @@
             -s "SSL - Unknown identity received" \
             -S "SSL - Verification of the message MAC failed"
 
-run_test    "PSK callback #5 (wrong key)" \
+run_test    "PSK callback: wrong key" \
             "$P_SRV psk_list=abc,dead,def,beef" \
             "$P_CLI force_ciphersuite=TLS-PSK-WITH-AES-128-CBC-SHA \
             psk_identity=abc psk=beef" \
@@ -1450,25 +1567,25 @@
 
 # Tests for ciphersuites per version
 
-run_test    "Per-version suites #1" \
+run_test    "Per-version suites: SSL3" \
             "$P_SRV version_suites=TLS-RSA-WITH-3DES-EDE-CBC-SHA,TLS-RSA-WITH-RC4-128-SHA,TLS-RSA-WITH-AES-128-CBC-SHA,TLS-RSA-WITH-AES-128-GCM-SHA256" \
             "$P_CLI force_version=ssl3" \
             0 \
             -c "Ciphersuite is TLS-RSA-WITH-3DES-EDE-CBC-SHA"
 
-run_test    "Per-version suites #2" \
+run_test    "Per-version suites: TLS 1.0" \
             "$P_SRV version_suites=TLS-RSA-WITH-3DES-EDE-CBC-SHA,TLS-RSA-WITH-RC4-128-SHA,TLS-RSA-WITH-AES-128-CBC-SHA,TLS-RSA-WITH-AES-128-GCM-SHA256" \
             "$P_CLI force_version=tls1" \
             0 \
             -c "Ciphersuite is TLS-RSA-WITH-RC4-128-SHA"
 
-run_test    "Per-version suites #3" \
+run_test    "Per-version suites: TLS 1.1" \
             "$P_SRV version_suites=TLS-RSA-WITH-3DES-EDE-CBC-SHA,TLS-RSA-WITH-RC4-128-SHA,TLS-RSA-WITH-AES-128-CBC-SHA,TLS-RSA-WITH-AES-128-GCM-SHA256" \
             "$P_CLI force_version=tls1_1" \
             0 \
             -c "Ciphersuite is TLS-RSA-WITH-AES-128-CBC-SHA"
 
-run_test    "Per-version suites #4" \
+run_test    "Per-version suites: TLS 1.2" \
             "$P_SRV version_suites=TLS-RSA-WITH-3DES-EDE-CBC-SHA,TLS-RSA-WITH-RC4-128-SHA,TLS-RSA-WITH-AES-128-CBC-SHA,TLS-RSA-WITH-AES-128-GCM-SHA256" \
             "$P_CLI force_version=tls1_2" \
             0 \
@@ -1476,13 +1593,13 @@
 
 # Tests for ssl_get_bytes_avail()
 
-run_test    "ssl_get_bytes_avail #1 (no extra data)" \
+run_test    "ssl_get_bytes_avail: no extra data" \
             "$P_SRV" \
             "$P_CLI request_size=100" \
             0 \
             -s "Read from client: 100 bytes read$"
 
-run_test    "ssl_get_bytes_avail #2 (extra data)" \
+run_test    "ssl_get_bytes_avail: extra data" \
             "$P_SRV" \
             "$P_CLI request_size=500" \
             0 \
@@ -1735,7 +1852,7 @@
 else
     echo -n "FAILED"
 fi
-PASSES=`echo $TESTS - $FAILS | bc`
-echo " ($PASSES / $TESTS tests)"
+PASSES=$(( $TESTS - $FAILS ))
+echo " ($PASSES / $TESTS tests ($SKIPS skipped))"
 
 exit $FAILS
diff -ruN polarssl-1.3.8/tests/suites/test_suite_base64.data polarssl-1.3.9/tests/suites/test_suite_base64.data
--- polarssl-1.3.8/tests/suites/test_suite_base64.data	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/suites/test_suite_base64.data	2014-10-20 13:59:19.000000000 +0200
@@ -55,6 +55,78 @@
 Base64 decode (Invalid char after equal signs)
 base64_decode:"zm=masd":"":POLARSSL_ERR_BASE64_INVALID_CHARACTER
 
+Base64 decode (Space inside string)
+base64_decode:"zm masd":"":POLARSSL_ERR_BASE64_INVALID_CHARACTER
+
+Base64 decode "Zm9vYmFy" (no newline nor '\0' at end)
+base64_decode_hex_src:"5a6d3976596d4679":"foobar":0
+
+Base64 decode "Zm9vYmFy\n" (LF at end)
+base64_decode_hex_src:"5a6d3976596d46790a":"foobar":0
+
+Base64 decode "Zm9vYmFy\r\n" (CRLF at end)
+base64_decode_hex_src:"5a6d3976596d46790d0a":"foobar":0
+
+Base64 decode "Zm9vYmFy\r" (CR at end)
+base64_decode_hex_src:"5a6d3976596d46790d":"":POLARSSL_ERR_BASE64_INVALID_CHARACTER
+
+Base64 decode "Zm9vYmFy " (SP at end)
+base64_decode_hex_src:"5a6d3976596d467920":"foobar":0
+
+Base64 decode "Zm9vYmFy \n" (SP+LF at end)
+base64_decode_hex_src:"5a6d3976596d4679200a":"foobar":0
+
+Base64 decode "Zm9vYmFy \r\n" (SP+CRLF at end)
+base64_decode_hex_src:"5a6d3976596d4679200d0a":"foobar":0
+
+Base64 decode "Zm9vYmFy \r" (SP+CR at end)
+base64_decode_hex_src:"5a6d3976596d4679200d":"":POLARSSL_ERR_BASE64_INVALID_CHARACTER
+
+Base64 decode "Zm9vYmFy  " (2SP at end)
+base64_decode_hex_src:"5a6d3976596d46792020":"foobar":0
+
+Base64 decode "Zm9vYmFy  \n" (2SP+LF at end)
+base64_decode_hex_src:"5a6d3976596d467920200a":"foobar":0
+
+Base64 decode "Zm9vYmFy  \r\n" (2SP+CRLF at end)
+base64_decode_hex_src:"5a6d3976596d467920200d0a":"foobar":0
+
+Base64 decode "Zm9vYmFy  \r" (2SP+CR at end)
+base64_decode_hex_src:"5a6d3976596d467920200d":"":POLARSSL_ERR_BASE64_INVALID_CHARACTER
+
+Base64 decode "Zm9vYmF\ny" (LF inside)
+base64_decode_hex_src:"5a6d3976596d460a79":"foobar":0
+
+Base64 decode "Zm9vYmF\ry" (CRLF inside)
+base64_decode_hex_src:"5a6d3976596d460d0a79":"foobar":0
+
+Base64 decode "Zm9vYmF\ry" (CR inside)
+base64_decode_hex_src:"5a6d3976596d460d79":"":POLARSSL_ERR_BASE64_INVALID_CHARACTER
+
+Base64 decode "Zm9vYmF y" (SP inside)
+base64_decode_hex_src:"5a6d3976596d462079":"":POLARSSL_ERR_BASE64_INVALID_CHARACTER
+
+Base64 decode "Zm9vYmF \ny" (SP+LF inside)
+base64_decode_hex_src:"5a6d3976596d46200a79":"foobar":0
+
+Base64 decode "Zm9vYmF \ry" (SP+CRLF inside)
+base64_decode_hex_src:"5a6d3976596d46200d0a79":"foobar":0
+
+Base64 decode "Zm9vYmF \ry" (SP+CR inside)
+base64_decode_hex_src:"5a6d3976596d46200d79":"":POLARSSL_ERR_BASE64_INVALID_CHARACTER
+
+Base64 decode "Zm9vYmF  y" (2SP inside)
+base64_decode_hex_src:"5a6d3976596d46202079":"":POLARSSL_ERR_BASE64_INVALID_CHARACTER
+
+Base64 decode "Zm9vYmF  \ny" (2SP+LF inside)
+base64_decode_hex_src:"5a6d3976596d4620200a79":"foobar":0
+
+Base64 decode "Zm9vYmF  \ry" (2SP+CRLF inside)
+base64_decode_hex_src:"5a6d3976596d4620200d0a79":"foobar":0
+
+Base64 decode "Zm9vYmF  \ry" (2SP+CR inside)
+base64_decode_hex_src:"5a6d3976596d4620200d79":"":POLARSSL_ERR_BASE64_INVALID_CHARACTER
+
 Base64 encode hex #1
 base64_encode_hex:"010203040506070809":"AQIDBAUGBwgJ":13:0
 
@@ -85,3 +157,4 @@
 Base64 Selftest
 depends_on:POLARSSL_SELF_TEST
 base64_selftest:
+
diff -ruN polarssl-1.3.8/tests/suites/test_suite_base64.function polarssl-1.3.9/tests/suites/test_suite_base64.function
--- polarssl-1.3.8/tests/suites/test_suite_base64.function	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/suites/test_suite_base64.function	2014-10-20 13:59:19.000000000 +0200
@@ -33,7 +33,7 @@
     unsigned char src_str[1000];
     unsigned char dst_str[1000];
     size_t len = 1000;
-    int res; 
+    int res;
 
     memset(src_str, 0x00, 1000);
     memset(dst_str, 0x00, 1000);
@@ -95,6 +95,28 @@
 }
 /* END_CASE */
 
+/* BEGIN_CASE */
+void base64_decode_hex_src( char *src_hex, char *dst_ref, int result )
+{
+    unsigned char dst[1000] = { 0 };
+    unsigned char *src;
+    size_t src_len, len;
+
+    src = unhexify_alloc( src_hex, &src_len );
+
+    len = sizeof( dst );
+    TEST_ASSERT( base64_decode( dst, &len, src, src_len ) == result );
+    if( result == 0 )
+    {
+        TEST_ASSERT( len == strlen( dst_ref ) );
+        TEST_ASSERT( memcmp( dst, dst_ref, len ) == 0 );
+    }
+
+exit:
+    polarssl_free( src );
+}
+/* END_CASE */
+
 /* BEGIN_CASE depends_on:POLARSSL_SELF_TEST */
 void base64_selftest()
 {
diff -ruN polarssl-1.3.8/tests/suites/test_suite_pkwrite.data polarssl-1.3.9/tests/suites/test_suite_pkwrite.data
--- polarssl-1.3.8/tests/suites/test_suite_pkwrite.data	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/suites/test_suite_pkwrite.data	2014-10-20 13:59:19.000000000 +0200
@@ -2,14 +2,38 @@
 depends_on:POLARSSL_RSA_C:POLARSSL_BASE64_C
 pk_write_pubkey_check:"data_files/server1.pubkey"
 
-Public key write check EC
+Public key write check RSA 4096
+depends_on:POLARSSL_RSA_C:POLARSSL_BASE64_C
+pk_write_pubkey_check:"data_files/rsa4096_pub.pem"
+
+Public key write check EC 192 bits
 depends_on:POLARSSL_ECP_C:POLARSSL_BASE64_C:POLARSSL_ECP_DP_SECP192R1_ENABLED
 pk_write_pubkey_check:"data_files/ec_pub.pem"
 
+Public key write check EC 521 bits
+depends_on:POLARSSL_ECP_C:POLARSSL_BASE64_C:POLARSSL_ECP_DP_SECP521R1_ENABLED
+pk_write_pubkey_check:"data_files/ec_521_pub.pem"
+
+Public key write check EC Brainpool 512 bits
+depends_on:POLARSSL_ECP_C:POLARSSL_BASE64_C:POLARSSL_ECP_DP_BP512R1_ENABLED
+pk_write_pubkey_check:"data_files/ec_bp512_pub.pem"
+
 Private key write check RSA
 depends_on:POLARSSL_RSA_C:POLARSSL_BASE64_C
 pk_write_key_check:"data_files/server1.key"
 
-Private key write check EC
+Private key write check RSA 4096
+depends_on:POLARSSL_RSA_C:POLARSSL_BASE64_C
+pk_write_key_check:"data_files/rsa4096_prv.pem"
+
+Private key write check EC 192 bits
 depends_on:POLARSSL_ECP_C:POLARSSL_BASE64_C:POLARSSL_ECP_DP_SECP192R1_ENABLED
 pk_write_key_check:"data_files/ec_prv.sec1.pem"
+
+Private key write check EC 521 bits
+depends_on:POLARSSL_ECP_C:POLARSSL_BASE64_C:POLARSSL_ECP_DP_SECP521R1_ENABLED
+pk_write_key_check:"data_files/ec_521_prv.pem"
+
+Private key write check EC Brainpool 512 bits
+depends_on:POLARSSL_ECP_C:POLARSSL_BASE64_C:POLARSSL_ECP_DP_SECP192R1_ENABLED
+pk_write_key_check:"data_files/ec_bp512_prv.pem"
diff -ruN polarssl-1.3.8/tests/suites/test_suite_rsa.data polarssl-1.3.9/tests/suites/test_suite_rsa.data
--- polarssl-1.3.8/tests/suites/test_suite_rsa.data	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/suites/test_suite_rsa.data	2014-10-20 13:59:19.000000000 +0200
@@ -294,11 +294,11 @@
 RSA Check Public key #5 (N smaller than 128 bits)
 rsa_check_pubkey:16:"7edcba9876543210deadbeefcafe4321":16:"3":POLARSSL_ERR_RSA_KEY_CHECK_FAILED
 
-RSA Check Public key #6 (N exactly 4096 bits)
-rsa_check_pubkey:16:"00b38ac65c8141f7f5c96e14470e851936a67bf94cc6821a39ac12c05f7c0b06d9e6ddba2224703b02e25f31452f9c4a8417b62675fdc6df46b94813bc7b9769a892c482b830bfe0ad42e46668ace68903617faf6681f4babf1cc8e4b0420d3c7f61dc45434c6b54e2c3ee0fc07908509d79c9826e673bf8363255adb0add2401039a7bcd1b4ecf0fbe6ec8369d2da486eec59559dd1d54c9b24190965eafbdab203b35255765261cd0909acf93c3b8b8428cbb448de4715d1b813d0c94829c229543d391ce0adab5351f97a3810c1f73d7b1458b97daed4209c50e16d064d2d5bfda8c23893d755222793146d0a78c3d64f35549141486c3b0961a7b4c1a2034fb38ac65c8141f7f5c96e14470e851936a67bf94cc6821a39ac12c05f7c0b06d9e6ddba2224703b02e25f31452f9c4a8417b62675fdc6df46b94813bc7b9769a892c482b830bfe0ad42e46668ace68903617faf6681f4babf1cc8e4b0420d3c7f61dc45434c6b54e2c3ee0fc07908509d79c9826e673bf8363255adb0add2401039a7bcd1b4ecf0fbe6ec8369d2da486eec59559dd1d54c9b24190965eafbdab203b35255765261cd0909acf93c3b8b8428cbb448de4715d1b813d0c94829c229543d391ce0adab5351f97a3810c1f73d7b1458b97daed4209c50e16d064d2d5bfda8c23893d755222793146d0a78c3d64f35549141486c3b0961a7b4c1a2034f":16:"3":0
+RSA Check Public key #6 (N exactly 8192 bits)
+rsa_check_pubkey:16:"88F48075BF29E95C1C6AE8716678B74E957B69CC2E49708C160C6343AAD2F076D25397ACE74220311ED18AEEB681F463611B3340C3945CAAEAD3ACC616E08A25A55683A32979BD55EA5DAB7630AF393886896F11DDC5F07E15EDF949324CF0F0B2A5C0E85DFA23167193182D1A43079DC8645F6C2C029629F475575802F7D326DE5BD891A9C5F84A433D45154181EC05685A4B368A5B6434775A00ABC6B0A04647D4598CEEE566B552230F691C98CA30B402A76C686A94B373CCD2F60EFA3878A867BB5F585D088E27C507937262D098A477B9218BE7C03B2E4C102D244CA701645F1827CD947E5E796446378B848862E689F0D1773F752056841A1F0EECE7CAB74921A42DBF2EF264ADCF4ABE05A1242E5F629A657A2D67958A2DAC9A2245074A37099B45064723ABE21241058252632C2BA6FE85AB1C75FF310891B84C9C40AB646FE1D90BC716FB3A4B56DA3EA25CA397C04B994F7C6AD1DD0CB9E994CA6B835F7830F4F4E0F976BBEA5AE8556BC7C90B3E50E21C19AD1F6BC4A8FF15F2909D9CC5F3DA533BADFF50F487869D631C3E34D69636B4C25A55127EF5B715F2FC0565734B38DF996D1970E56F7F64EBECB9D00A587AAEC608F2D3AAA51E66BF53E92C3096BF78D1DCBCE1A645FA4F0542E6F68E5A94AAA6E839F75620FABED5D2BCF40AB8EAF95F838BFA962429F281578882DF0F2721C27C8905C9E776B1D3251FC066A8BC64C0CE7FBA2B8E21F65EF6739AB6F19EC2AB07817DFF03DAB7C846AB5CC86C103642D7664A85DC2D846A8004CD6A144C72CCCAC86DB5901A047324927B80E281F5F7315FA2F9083BDE0DB7AA46DC055E36BB73FB6DBD3A14759D06CBBE8D57CBC213C4D55DE4478679E0A5902C8655BE1391C0E88D2B1FBD57E9232A2CEBC67569ECD94E4BF0FCC6C003F9AA51A2A5E6EE084A46DAE65E52400A727F9713D29E92CD6CA37FD599598B3F677624A2A484A8B36B98EFEAD662C0A23BC1D9280EF2A31F887065EB20A93B41F7A264ECFA65B3555F3E400927018186EAA2D4F00C6B7AB1BCED5F893D64478177592C7F2B945307AB474D7EC7FF2E7E55834CC763BEF81DA9BD70FB3D423AE5ADB86B336734C8A3BEC90CEB05438B5BA030D0D30DEC1442D2EB08450480FBAE090FFA1A5ADD748A415BDCDE45094E792420F0AF94BCA0A80A2096D1A478D3428A214A7E68C0F07F58C6FB232ECC3D8B821AE29AE76E13EB751193F6ECA670016D54F3D796937DDBB8900062EF116CCA3F5B3AECA618272875336C9C050FBC0FC7EDD5B88D85DA0061D21E176E1419CF573629BE7B0496E761EAD45FE32B59EB00D47CDD178AC8F8EC8D6F26DED34F7576CD938422E18E936F16A704B483A48EE3BEA59D95F688136119894930EC8E9282E5974740CF031DF8DBB07EB08F2DA0ACCADECE15A6A57502890F4A03740E60BD":16:"010001":0
 
-RSA Check Public key #7 (N larger than 4096 bits)
-rsa_check_pubkey:16:"01b38ac65c8141f7f5c96e14470e851936a67bf94cc6821a39ac12c05f7c0b06d9e6ddba2224703b02e25f31452f9c4a8417b62675fdc6df46b94813bc7b9769a892c482b830bfe0ad42e46668ace68903617faf6681f4babf1cc8e4b0420d3c7f61dc45434c6b54e2c3ee0fc07908509d79c9826e673bf8363255adb0add2401039a7bcd1b4ecf0fbe6ec8369d2da486eec59559dd1d54c9b24190965eafbdab203b35255765261cd0909acf93c3b8b8428cbb448de4715d1b813d0c94829c229543d391ce0adab5351f97a3810c1f73d7b1458b97daed4209c50e16d064d2d5bfda8c23893d755222793146d0a78c3d64f35549141486c3b0961a7b4c1a2034fb38ac65c8141f7f5c96e14470e851936a67bf94cc6821a39ac12c05f7c0b06d9e6ddba2224703b02e25f31452f9c4a8417b62675fdc6df46b94813bc7b9769a892c482b830bfe0ad42e46668ace68903617faf6681f4babf1cc8e4b0420d3c7f61dc45434c6b54e2c3ee0fc07908509d79c9826e673bf8363255adb0add2401039a7bcd1b4ecf0fbe6ec8369d2da486eec59559dd1d54c9b24190965eafbdab203b35255765261cd0909acf93c3b8b8428cbb448de4715d1b813d0c94829c229543d391ce0adab5351f97a3810c1f73d7b1458b97daed4209c50e16d064d2d5bfda8c23893d755222793146d0a78c3d64f35549141486c3b0961a7b4c1a2034f":16:"3":POLARSSL_ERR_RSA_KEY_CHECK_FAILED
+RSA Check Public key #7 (N larger than 8192 bits)
+rsa_check_pubkey:16:"01631CD83F3F2D67FA52E13B44416EA65043A322ECD65467558EACD4C6B6D92DA7471D2DBD58E6921F9465C4900E92DFC6EB35C90637285A7E1F3D27C1C32FD6A5CB324D8253C6B2E480B63F66E3B09F4300C3E683011C7803BDEAD682F0F55473FC8A187734573A11ECDCE802022F539BC2074E94703C23E48FF8AE35702352E70AF921B42E6A143A3EFEE20DF77A97AA703AA271CE96EB78062452D87A4ADCACF83FFB9683818BF2ED234D0ECFB1B935827708050C4D007215D7A028152798045AF6A0B741A7B22F3FCCEBC26D285B9AA22CEF858858702BAE7D945FA0C45E2D8AADFF2FD0A64DF02C241F871C799AD73738E626D9A6D4BFFBCE000C4087F0CE74EF21526402FDCD07649175122697FD01041B84AD0A3FEDABD5C25E953686B2272F8C8B748A486F54CB767A1C79CA499B2C9A300AC8A214A0BFA06280A9235D5B7AFB8A76FFDD78FC72038C5B809569A6125D6A588684A16D222EF93F2469EA78948037957DE9B449AB722044FDFF3B6AC89367D72F0CF3ED1F85EDFD0DE3EEEDD39F6EFD68A0368F83B389B7A7B9C7713F4148F53E82CDF6D9CC002A3A16F1E6A1D78C48CE7849584164661664153A499ACAE5927728B2F1A2E911648676DF316DFCBF5E44F393B7B296A4A21ED59744E3855FCD4A21F2B42CFE5C52860B244D467103107E3DC40A82077269897528CCBF80B2F216A535C52A6A2643E64B53276A1B63348038706328FE369AE2409568160481C07A3ED5B0198EC6CC07F8F250B1DE0D97110F834AA3D1C0862FB719393EA08D530225CE0647FD5488F483FA065196D1160FAFA54CD3FF63B6ADDBE84D09F3CFF98F22CC71DE2FC19735126C3BBA9A2C293D1DB118F0512C144C1C616492BE0D19BFD245955840F640EBE6FCFF2830C683852046F36C3CDA4F4460ABA4B2FEEB700C9DD80418C42673858CDD11E70682D5A41ED7D8010EC7DD5B57B4E206F84DB8A430B246002FEA49AFF45940B1F18AE28863F5AA41D3B42ABCD3D1BAB7644B86E060865997E1BA23A768F233D8A859332F8B9D5D1633F9C462328C17E2B07D6DFD813C94D675873592E5CBB001C112A790B10B9F9E07BE105C4FD328C7E3887C3EF13E8ECE6106B73A3341AF200D8663BDF96FFDB6F794FBB04D976B87423A868882F15CAE8DC9F6CAF4917EFC844E74BAD48F21E34530CB4E20006444706FC95658735553CA99E18F0E820D78DEF8FB84034B10CE44B1AE36B50147558415E5E78A77E2FC7C8C580B54CCC40EE3904C04950846A6D51BF5C80E0B6E2ADC4989DA1D3DD01F99AA369C2E6B53394BA0CB5E6E811BFA004A5B3B3C34C60433AB5EB0EC8050246B9AF10B49EAA51487CCE0C4C8F4CDAF926D582D7E4924C33765E00AC952A38669150EA322CDF886B46DE4D0970A060B670D50C9BF3D2020B529838E192EF92BFE2F06FDF1D5":16:"010001":POLARSSL_ERR_RSA_KEY_CHECK_FAILED
 
 RSA Check Public key #8 (E exactly 2 bits)
 rsa_check_pubkey:16:"fedcba9876543210deadbeefcafe4321":16:"3":0
diff -ruN polarssl-1.3.8/tests/suites/test_suite_version.data polarssl-1.3.9/tests/suites/test_suite_version.data
--- polarssl-1.3.8/tests/suites/test_suite_version.data	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/suites/test_suite_version.data	2014-10-20 13:59:19.000000000 +0200
@@ -1,8 +1,8 @@
 Check compiletime library version
-check_compiletime_version:"1.3.8"
+check_compiletime_version:"1.3.9"
 
 Check runtime library version
-check_runtime_version:"1.3.8"
+check_runtime_version:"1.3.9"
 
 Check for POLARSSL_VERSION_C
 check_feature:"POLARSSL_VERSION_C":0
diff -ruN polarssl-1.3.8/tests/suites/test_suite_x509parse.data polarssl-1.3.9/tests/suites/test_suite_x509parse.data
--- polarssl-1.3.8/tests/suites/test_suite_x509parse.data	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/suites/test_suite_x509parse.data	2014-10-20 13:59:19.000000000 +0200
@@ -219,23 +219,23 @@
 x509_csr_info:"data_files/server1.req.sha512":"CSR version   \: 1\nsubject name  \: C=NL, O=PolarSSL, CN=PolarSSL Server 1\nsigned using  \: RSA with SHA-512\nRSA key size  \: 2048 bits\n"
 
 X509 CSR Information EC with SHA1
-depends_on:POLARSSL_PEM_PARSE_C
+depends_on:POLARSSL_ECP_C:POLARSSL_PEM_PARSE_C
 x509_csr_info:"data_files/server5.req.sha1":"CSR version   \: 1\nsubject name  \: C=NL, O=PolarSSL, CN=localhost\nsigned using  \: ECDSA with SHA1\nEC key size   \: 256 bits\n"
 
 X509 CSR Information EC with SHA224
-depends_on:POLARSSL_PEM_PARSE_C
+depends_on:POLARSSL_ECP_C:POLARSSL_PEM_PARSE_C
 x509_csr_info:"data_files/server5.req.sha224":"CSR version   \: 1\nsubject name  \: C=NL, O=PolarSSL, CN=localhost\nsigned using  \: ECDSA with SHA224\nEC key size   \: 256 bits\n"
 
 X509 CSR Information EC with SHA256
-depends_on:POLARSSL_PEM_PARSE_C
+depends_on:POLARSSL_ECP_C:POLARSSL_PEM_PARSE_C
 x509_csr_info:"data_files/server5.req.sha256":"CSR version   \: 1\nsubject name  \: C=NL, O=PolarSSL, CN=localhost\nsigned using  \: ECDSA with SHA256\nEC key size   \: 256 bits\n"
 
 X509 CSR Information EC with SHA384
-depends_on:POLARSSL_PEM_PARSE_C
+depends_on:POLARSSL_ECP_C:POLARSSL_PEM_PARSE_C
 x509_csr_info:"data_files/server5.req.sha384":"CSR version   \: 1\nsubject name  \: C=NL, O=PolarSSL, CN=localhost\nsigned using  \: ECDSA with SHA384\nEC key size   \: 256 bits\n"
 
 X509 CSR Information EC with SHA512
-depends_on:POLARSSL_PEM_PARSE_C
+depends_on:POLARSSL_ECP_C:POLARSSL_PEM_PARSE_C
 x509_csr_info:"data_files/server5.req.sha512":"CSR version   \: 1\nsubject name  \: C=NL, O=PolarSSL, CN=localhost\nsigned using  \: ECDSA with SHA512\nEC key size   \: 256 bits\n"
 
 X509 CSR Information RSA-PSS with SHA1
@@ -607,7 +607,7 @@
 x509_verify:"data_files/server9-badsign.crt":"data_files/test-ca.crt":"data_files/crl.pem":"NULL":POLARSSL_ERR_X509_CERT_VERIFY_FAILED:BADCERT_NOT_TRUSTED:"NULL"
 
 X509 Certificate verification #66 (RSASSA-PSS, SHA1, no RSA CA)
-depends_on:POLARSSL_PEM_PARSE_C:POLARSSL_X509_RSASSA_PSS_SUPPORT:POLARSSL_SHA1_C
+depends_on:POLARSSL_PEM_PARSE_C:POLARSSL_X509_RSASSA_PSS_SUPPORT:POLARSSL_SHA1_C:POLARSSL_ECP_C
 x509_verify:"data_files/server9.crt":"data_files/test-ca2.crt":"data_files/crl.pem":"NULL":POLARSSL_ERR_X509_CERT_VERIFY_FAILED:BADCERT_NOT_TRUSTED:"NULL"
 
 X509 Certificate verification #67 (Valid, RSASSA-PSS, all defaults)
@@ -642,6 +642,10 @@
 depends_on:POLARSSL_PEM_PARSE_C:POLARSSL_ECDSA_C:POLARSSL_SHA256_C
 x509_verify:"data_files/server6-ss-child.crt":"data_files/server5-selfsigned.crt":"data_files/crl.pem":"NULL":POLARSSL_ERR_X509_CERT_VERIFY_FAILED:BADCERT_NOT_TRUSTED:"NULL"
 
+X509 Certificate verification #75 (encoding mismatch)
+depends_on:POLARSSL_PEM_PARSE_C
+x509_verify:"data_files/enco-cert-utf8str.pem":"data_files/enco-ca-prstr.pem":"data_files/crl.pem":"NULL":0:0:"NULL"
+
 X509 Parse Selftest
 depends_on:POLARSSL_SHA1_C:POLARSSL_PEM_PARSE_C:POLARSSL_CERTS_C
 x509_selftest:
@@ -750,7 +754,7 @@
 x509parse_crt:"30253023a0030201028204deadbeef300d06092a864886f70d0101020500300731053003060013":"":POLARSSL_ERR_X509_INVALID_NAME + POLARSSL_ERR_ASN1_OUT_OF_DATA
 
 X509 Certificate ASN1 (TBSCertificate, issuer, no full following string)
-x509parse_crt:"302b3029a0030201028204deadbeef300d06092a864886f70d0101020500300d310b3009060013045465737400":"":POLARSSL_ERR_X509_INVALID_NAME + POLARSSL_ERR_ASN1_UNEXPECTED_TAG
+x509parse_crt:"302b3029a0030201028204deadbeef300d06092a864886f70d0101020500300d310b3009060013045465737400":"":POLARSSL_ERR_X509_FEATURE_UNAVAILABLE
 
 X509 Certificate ASN1 (TBSCertificate, valid issuer, no validity)
 x509parse_crt:"302a3028a0030201028204deadbeef300d06092a864886f70d0101020500300c310a30080600130454657374":"":POLARSSL_ERR_X509_INVALID_DATE + POLARSSL_ERR_ASN1_OUT_OF_DATA
@@ -1056,31 +1060,31 @@
 x509_check_key_usage:"data_files/server1.key_usage.crt":KU_KEY_ENCIPHERMENT|KU_KEY_AGREEMENT:POLARSSL_ERR_X509_BAD_INPUT_DATA
 
 X509 crt extendedKeyUsage #1 (no extension, serverAuth)
-depends_on:POLARSSL_ECP_DP_SECP256R1_ENABLED
+depends_on:POLARSSL_ECP_C:POLARSSL_ECP_DP_SECP256R1_ENABLED
 x509_check_extended_key_usage:"data_files/server5.crt":"2B06010505070301":0
 
 X509 crt extendedKeyUsage #2 (single value, present)
-depends_on:POLARSSL_ECP_DP_SECP256R1_ENABLED
+depends_on:POLARSSL_ECP_C:POLARSSL_ECP_DP_SECP256R1_ENABLED
 x509_check_extended_key_usage:"data_files/server5.eku-srv.crt":"2B06010505070301":0
 
 X509 crt extendedKeyUsage #3 (single value, absent)
-depends_on:POLARSSL_ECP_DP_SECP256R1_ENABLED
+depends_on:POLARSSL_ECP_C:POLARSSL_ECP_DP_SECP256R1_ENABLED
 x509_check_extended_key_usage:"data_files/server5.eku-cli.crt":"2B06010505070301":POLARSSL_ERR_X509_BAD_INPUT_DATA
 
 X509 crt extendedKeyUsage #4 (two values, first)
-depends_on:POLARSSL_ECP_DP_SECP256R1_ENABLED
+depends_on:POLARSSL_ECP_C:POLARSSL_ECP_DP_SECP256R1_ENABLED
 x509_check_extended_key_usage:"data_files/server5.eku-srv_cli.crt":"2B06010505070301":0
 
 X509 crt extendedKeyUsage #5 (two values, second)
-depends_on:POLARSSL_ECP_DP_SECP256R1_ENABLED
+depends_on:POLARSSL_ECP_C:POLARSSL_ECP_DP_SECP256R1_ENABLED
 x509_check_extended_key_usage:"data_files/server5.eku-srv_cli.crt":"2B06010505070302":0
 
 X509 crt extendedKeyUsage #6 (two values, other)
-depends_on:POLARSSL_ECP_DP_SECP256R1_ENABLED
+depends_on:POLARSSL_ECP_C:POLARSSL_ECP_DP_SECP256R1_ENABLED
 x509_check_extended_key_usage:"data_files/server5.eku-srv_cli.crt":"2B06010505070303":POLARSSL_ERR_X509_BAD_INPUT_DATA
 
 X509 crt extendedKeyUsage #7 (any, random)
-depends_on:POLARSSL_ECP_DP_SECP256R1_ENABLED
+depends_on:POLARSSL_ECP_C:POLARSSL_ECP_DP_SECP256R1_ENABLED
 x509_check_extended_key_usage:"data_files/server5.eku-cs_any.crt":"2B060105050703FF":0
 
 X509 RSASSA-PSS parameters ASN1 (good, all defaults)
@@ -1186,6 +1190,7 @@
 x509_parse_rsassa_pss_params:"A303020102":ASN1_CONSTRUCTED | ASN1_SEQUENCE:POLARSSL_MD_SHA1:POLARSSL_MD_SHA1:20:POLARSSL_ERR_X509_INVALID_ALG
 
 X509 CSR ASN.1 (OK)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"308201183081BF0201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFFA029302706092A864886F70D01090E311A301830090603551D1304023000300B0603551D0F0404030205E0300906072A8648CE3D04010349003046022100B49FD8C8F77ABFA871908DFBE684A08A793D0F490A43D86FCF2086E4F24BB0C2022100F829D5CCD3742369299E6294394717C4B723A0F68B44E831B6E6C3BCABF97243":"CSR version   \: 1\nsubject name  \: C=NL, O=PolarSSL, CN=localhost\nsigned using  \: ECDSA with SHA1\nEC key size   \: 256 bits\n":0
 
 X509 CSR ASN.1 (bad first tag)
@@ -1231,34 +1236,57 @@
 x509_csr_parse:"30173014020100300D310B3009060355040613024E4C300100":"":POLARSSL_ERR_PK_KEY_INVALID_FORMAT + POLARSSL_ERR_ASN1_OUT_OF_DATA
 
 X509 CSR ASN.1 (bad attributes: missing)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"3081973081940201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFF":"":POLARSSL_ERR_X509_INVALID_FORMAT + POLARSSL_ERR_ASN1_OUT_OF_DATA
 
 X509 CSR ASN.1 (bad attributes: bad tag)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"3081993081960201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFF0500":"":POLARSSL_ERR_X509_INVALID_FORMAT + POLARSSL_ERR_ASN1_UNEXPECTED_TAG
 
 X509 CSR ASN.1 (bad attributes: overlong)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"30819A3081960201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFFA00100":"":POLARSSL_ERR_X509_INVALID_FORMAT + POLARSSL_ERR_ASN1_OUT_OF_DATA
 
 X509 CSR ASN.1 (bad sigAlg: missing)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"3081C23081BF0201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFFA029302706092A864886F70D01090E311A301830090603551D1304023000300B0603551D0F0404030205E0":"":POLARSSL_ERR_X509_INVALID_ALG + POLARSSL_ERR_ASN1_OUT_OF_DATA
 
 X509 CSR ASN.1 (bad sigAlg: not a sequence)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"3081C43081BF0201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFFA029302706092A864886F70D01090E311A301830090603551D1304023000300B0603551D0F0404030205E03100":"":POLARSSL_ERR_X509_INVALID_ALG + POLARSSL_ERR_ASN1_UNEXPECTED_TAG
 
 X509 CSR ASN.1 (bad sigAlg: overlong)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"3081C43081BF0201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFFA029302706092A864886F70D01090E311A301830090603551D1304023000300B0603551D0F0404030205E03001":"":POLARSSL_ERR_X509_INVALID_ALG + POLARSSL_ERR_ASN1_OUT_OF_DATA
 
 X509 CSR ASN.1 (bad sigAlg: unknown)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"3081CD3081BF0201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFFA029302706092A864886F70D01090E311A301830090603551D1304023000300B0603551D0F0404030205E0300906072A8648CE3D04FF":"":POLARSSL_ERR_X509_UNKNOWN_SIG_ALG
 
 X509 CSR ASN.1 (bad sig: missing)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"3081CD3081BF0201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFFA029302706092A864886F70D01090E311A301830090603551D1304023000300B0603551D0F0404030205E0300906072A8648CE3D0401":"":POLARSSL_ERR_X509_INVALID_SIGNATURE + POLARSSL_ERR_ASN1_OUT_OF_DATA
 
 X509 CSR ASN.1 (bad sig: not a bit string)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"3081CF3081BF0201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFFA029302706092A864886F70D01090E311A301830090603551D1304023000300B0603551D0F0404030205E0300906072A8648CE3D04010400":"":POLARSSL_ERR_X509_INVALID_SIGNATURE + POLARSSL_ERR_ASN1_UNEXPECTED_TAG
 
 X509 CSR ASN.1 (bad sig: overlong)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"3081CF3081BF0201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFFA029302706092A864886F70D01090E311A301830090603551D1304023000300B0603551D0F0404030205E0300906072A8648CE3D04010301":"":POLARSSL_ERR_X509_INVALID_SIGNATURE + POLARSSL_ERR_ASN1_OUT_OF_DATA
 
 X509 CSR ASN.1 (extra data after signature)
+depends_on:POLARSSL_ECP_C
 x509_csr_parse:"308201193081BF0201003034310B3009060355040613024E4C3111300F060355040A1308506F6C617253534C31123010060355040313096C6F63616C686F73743059301306072A8648CE3D020106082A8648CE3D0301070342000437CC56D976091E5A723EC7592DFF206EEE7CF9069174D0AD14B5F768225962924EE500D82311FFEA2FD2345D5D16BD8A88C26B770D55CD8A2A0EFA01C8B4EDFFA029302706092A864886F70D01090E311A301830090603551D1304023000300B0603551D0F0404030205E0300906072A8648CE3D04010349003046022100B49FD8C8F77ABFA871908DFBE684A08A793D0F490A43D86FCF2086E4F24BB0C2022100F829D5CCD3742369299E6294394717C4B723A0F68B44E831B6E6C3BCABF9724300":"":POLARSSL_ERR_X509_INVALID_FORMAT + POLARSSL_ERR_ASN1_LENGTH_MISMATCH
+
+X509 File parse (no issues)
+depends_on:POLARSSL_ECP_C
+x509parse_crt_file:"data_files/server7_int-ca.crt":0
+
+X509 File parse (extra space in one certificate)
+depends_on:POLARSSL_ECP_C
+x509parse_crt_file:"data_files/server7_pem_space.crt":1
+
+X509 File parse (all certificates fail)
+depends_on:POLARSSL_ECP_C
+x509parse_crt_file:"data_files/server7_all_space.crt":POLARSSL_ERR_PEM_INVALID_DATA + POLARSSL_ERR_BASE64_INVALID_CHARACTER
diff -ruN polarssl-1.3.8/tests/suites/test_suite_x509parse.function polarssl-1.3.9/tests/suites/test_suite_x509parse.function
--- polarssl-1.3.8/tests/suites/test_suite_x509parse.function	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/suites/test_suite_x509parse.function	2014-10-20 13:59:19.000000000 +0200
@@ -4,6 +4,7 @@
 #include <polarssl/x509_csr.h>
 #include <polarssl/pem.h>
 #include <polarssl/oid.h>
+#include <polarssl/base64.h>
 
 int verify_none( void *data, x509_crt *crt, int certificate_depth, int *flags )
 {
@@ -213,6 +214,20 @@
 
 exit:
     x509_crt_free( &crt );
+}
+/* END_CASE */
+
+/* BEGIN_CASE depends_on:POLARSSL_X509_CRT_PARSE_C:POLARSSL_FS_IO */
+void x509parse_crt_file( char *crt_file, int result )
+{
+    x509_crt crt;
+
+    x509_crt_init( &crt );
+
+    TEST_ASSERT( x509_crt_parse_file( &crt, crt_file ) == result );
+
+exit:
+    x509_crt_free( &crt );
 }
 /* END_CASE */
 
diff -ruN polarssl-1.3.8/tests/suites/test_suite_x509write.data polarssl-1.3.9/tests/suites/test_suite_x509write.data
--- polarssl-1.3.8/tests/suites/test_suite_x509write.data	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/suites/test_suite_x509write.data	2014-10-20 13:59:19.000000000 +0200
@@ -57,3 +57,21 @@
 Certificate write check Server1 SHA1, version 1
 depends_on:POLARSSL_SHA1_C:POLARSSL_RSA_C:POLARSSL_PKCS1_V15:POLARSSL_DES_C:POLARSSL_CIPHER_MODE_CBC:POLARSSL_MD5_C
 x509_crt_check:"data_files/server1.key":"":"C=NL,O=PolarSSL,CN=PolarSSL Server 1":"data_files/test-ca.key":"PolarSSLTest":"C=NL,O=PolarSSL,CN=PolarSSL Test CA":"1":"20110212144406":"20210212144406":POLARSSL_MD_SHA1:0:0:X509_CRT_VERSION_1:"data_files/server1.v1.crt"
+
+X509 String to Names #1
+x509_string_to_names:"C=NL,O=Offspark\, Inc., OU=PolarSSL":"C=NL, O=Offspark, Inc., OU=PolarSSL":0
+
+X509 String to Names #2
+x509_string_to_names:"C=NL, O=Offspark, Inc., OU=PolarSSL":"":POLARSSL_ERR_X509_UNKNOWN_OID
+
+X509 String to Names #3 (Name precisely 255 bytes)
+x509_string_to_names:"C=NL, O=123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345,OU=PolarSSL":"C=NL, O=123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345, OU=PolarSSL":0
+
+X509 String to Names #4 (Name larger than 255 bytes)
+x509_string_to_names:"C=NL, O=1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456, OU=PolarSSL":"":POLARSSL_ERR_X509_INVALID_NAME
+
+X509 String to Names #5 (Escape non-allowed characters)
+x509_string_to_names:"C=NL, O=Offspark\a Inc., OU=PolarSSL":"":POLARSSL_ERR_X509_INVALID_NAME
+
+X509 String to Names #6 (Escape at end)
+x509_string_to_names:"C=NL, O=Offspark\":"":POLARSSL_ERR_X509_INVALID_NAME
diff -ruN polarssl-1.3.8/tests/suites/test_suite_x509write.function polarssl-1.3.9/tests/suites/test_suite_x509write.function
--- polarssl-1.3.8/tests/suites/test_suite_x509write.function	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/tests/suites/test_suite_x509write.function	2014-10-20 13:59:19.000000000 +0200
@@ -132,3 +132,47 @@
     mpi_free( &serial );
 }
 /* END_CASE */
+
+/* BEGIN_CASE depends_on:POLARSSL_X509_CREATE_C:POLARSSL_X509_USE_C */
+void x509_string_to_names( char *name, char *parsed_name, int result )
+{
+    int ret;
+    size_t len = 0;
+    asn1_named_data *names = NULL;
+    x509_name parsed, *parsed_cur, *parsed_prv;
+    unsigned char buf[2048], *c;
+
+    memset( &parsed, 0, sizeof( parsed ) );
+    memset( buf, 0, sizeof( buf ) );
+    c = buf + sizeof( buf );
+
+    ret = x509_string_to_names( &names, name );
+    TEST_ASSERT( ret == result );
+
+    if( ret != 0 )
+        goto exit;
+
+    ret = x509_write_names( &c, buf, names );
+    TEST_ASSERT( ret > 0 );
+
+    TEST_ASSERT( asn1_get_tag( &c, buf + sizeof( buf ), &len,
+                        ASN1_CONSTRUCTED | ASN1_SEQUENCE ) == 0 );
+    TEST_ASSERT( x509_get_name( &c, buf + sizeof( buf ), &parsed ) == 0 );
+
+    ret = x509_dn_gets( (char *) buf, sizeof( buf ), &parsed );
+    TEST_ASSERT( ret > 0 );
+
+    TEST_ASSERT( strcmp( (char *) buf, parsed_name ) == 0 );
+
+exit:
+    asn1_free_named_data_list( &names );
+
+    parsed_cur = parsed.next;
+    while( parsed_cur != 0 )
+    {
+        parsed_prv = parsed_cur;
+        parsed_cur = parsed_cur->next;
+        polarssl_free( parsed_prv );
+    }
+}
+/* END_CASE */
diff -ruN polarssl-1.3.8/.travis.yml polarssl-1.3.9/.travis.yml
--- polarssl-1.3.8/.travis.yml	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/.travis.yml	2014-10-20 13:59:19.000000000 +0200
@@ -3,7 +3,7 @@
 - clang
 - gcc
 before_install: sudo apt-get update
-install: sudo apt-get install bc gnutls-bin valgrind perl
+install: sudo apt-get install gnutls-bin valgrind perl
 script:
 - cmake -D CMAKE_BUILD_TYPE:String="Check" .
 - make
diff -ruN polarssl-1.3.8/visualc/VS2010/PolarSSL.vcxproj polarssl-1.3.9/visualc/VS2010/PolarSSL.vcxproj
--- polarssl-1.3.8/visualc/VS2010/PolarSSL.vcxproj	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/visualc/VS2010/PolarSSL.vcxproj	2014-10-20 13:59:19.000000000 +0200
@@ -256,7 +256,6 @@
     <ClCompile Include="..\..\library\pkwrite.c" />
     <ClCompile Include="..\..\library\platform.c" />
     <ClCompile Include="..\..\library\ripemd160.c" />
-    <ClCompile Include="..\..\library\rnd_test.c" />
     <ClCompile Include="..\..\library\rsa.c" />
     <ClCompile Include="..\..\library\sha1.c" />
     <ClCompile Include="..\..\library\sha256.c" />
diff -ruN polarssl-1.3.8/visualc/VS6/polarssl.dsp polarssl-1.3.9/visualc/VS6/polarssl.dsp
--- polarssl-1.3.8/visualc/VS6/polarssl.dsp	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/visualc/VS6/polarssl.dsp	2014-10-20 13:59:19.000000000 +0200
@@ -273,10 +273,6 @@
 # End Source File
 # Begin Source File
 
-SOURCE=..\..\library\rnd_test.c
-# End Source File
-# Begin Source File
-
 SOURCE=..\..\library\rsa.c
 # End Source File
 # Begin Source File
diff -ruN polarssl-1.3.8/ChangeLog polarssl-1.3.9/ChangeLog
--- polarssl-1.3.8/ChangeLog	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/ChangeLog	2014-10-20 13:59:19.000000000 +0200
@@ -1,5 +1,52 @@
 PolarSSL ChangeLog (Sorted per branch, date)
 
+= 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).
diff -ruN polarssl-1.3.8/CMakeLists.txt polarssl-1.3.9/CMakeLists.txt
--- polarssl-1.3.8/CMakeLists.txt	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/CMakeLists.txt	2014-10-20 13:59:19.000000000 +0200
@@ -4,22 +4,22 @@
 string(REGEX MATCH "Clang" CMAKE_COMPILER_IS_CLANG "${CMAKE_C_COMPILER_ID}")
 
 if(CMAKE_COMPILER_IS_GNUCC)
-  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -W -Wdeclaration-after-statement")
+  set(CMAKE_C_FLAGS "-Wall -Wextra -W -Wdeclaration-after-statement -Wlogical-op -Wwrite-strings")
   set(CMAKE_C_FLAGS_RELEASE "-O2")
   set(CMAKE_C_FLAGS_DEBUG "-g3 -O0")
   set(CMAKE_C_FLAGS_COVERAGE "-g3 -O0 --coverage")
-  set(CMAKE_C_FLAGS_ASAN "-fsanitize=address -fno-omit-frame-pointer -g3 -O1")
-  set(CMAKE_C_FLAGS_CHECK "${CMAKE_C_FLAGS} -Werror -O1 -Wlogical-op -Wwrite-strings")
+  set(CMAKE_C_FLAGS_ASAN "-fsanitize=address -fno-omit-frame-pointer -g3 -O1 -Werror")
+  set(CMAKE_C_FLAGS_CHECK "-O1 -Werror")
   set(CMAKE_C_FLAGS_CHECKFULL "${CMAKE_C_FLAGS_CHECK} -Wcast-qual")
 endif(CMAKE_COMPILER_IS_GNUCC)
 
 if(CMAKE_COMPILER_IS_CLANG)
-  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -W -Wdeclaration-after-statement")
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -W -Wdeclaration-after-statement -Wpointer-arith -Wwrite-strings -Wdocumentation -Wunreachable-code")
   set(CMAKE_C_FLAGS_RELEASE "-O2")
   set(CMAKE_C_FLAGS_DEBUG "-g3 -O0")
   set(CMAKE_C_FLAGS_COVERAGE "-g3 -O0 --coverage")
-  set(CMAKE_C_FLAGS_ASAN "-fsanitize=address -fno-omit-frame-pointer -g3 -O1")
-  set(CMAKE_C_FLAGS_CHECK "${CMAKE_C_FLAGS} -Werror -O1 -Wpointer-arith -Wwrite-strings -Wdocumentation -Wunreachable-code")
+  set(CMAKE_C_FLAGS_ASAN "-fsanitize=address -fno-omit-frame-pointer -g3 -O1 -Werror")
+  set(CMAKE_C_FLAGS_CHECK "-O1 -Werror")
 endif(CMAKE_COMPILER_IS_CLANG)
 
 set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE}
diff -ruN polarssl-1.3.8/debian/changelog polarssl-1.3.9/debian/changelog
--- polarssl-1.3.8/debian/changelog	2014-08-31 14:21:26.000000000 +0200
+++ polarssl-1.3.9/debian/changelog	2014-11-07 10:31:12.000000000 +0100
@@ -1,3 +1,17 @@
+polarssl (1.3.9-2) unstable; urgency=medium
+
+  * Disabled POLARSSL_SSL_PROTO_SSL3 at compile time to prevent potential
+    attacks, TLS considered standard for clients now, and consistency w/
+    OpenSSL in Debian
+
+ -- Roland Stigge <stigge@antcom.de>  Fri, 07 Nov 2014 10:28:34 +0100
+
+polarssl (1.3.9-1) unstable; urgency=medium
+
+  * New upstream release
+
+ -- Roland Stigge <stigge@antcom.de>  Wed, 05 Nov 2014 18:34:31 +0100
+
 polarssl (1.3.8-1) unstable; urgency=medium
 
   * New upstream release
diff -ruN polarssl-1.3.8/debian/control polarssl-1.3.9/debian/control
--- polarssl-1.3.8/debian/control	2014-08-31 14:24:23.000000000 +0200
+++ polarssl-1.3.9/debian/control	2014-11-05 18:37:35.000000000 +0100
@@ -2,7 +2,7 @@
 Section: libs
 Priority: optional
 Maintainer: Roland Stigge <stigge@antcom.de>
-Standards-Version: 3.9.5
+Standards-Version: 3.9.6
 Build-Depends: debhelper (>= 9)
 Homepage: http://polarssl.org
 
diff -ruN polarssl-1.3.8/debian/patches/01-config.patch polarssl-1.3.9/debian/patches/01-config.patch
--- polarssl-1.3.8/debian/patches/01-config.patch	2014-07-15 21:40:38.000000000 +0200
+++ polarssl-1.3.9/debian/patches/01-config.patch	2014-11-07 10:28:20.000000000 +0100
@@ -3,9 +3,18 @@
  capabilities
 Author: Arnaud Cornet <arnaud.cornet@gmail.com>
 
---- polarssl-1.3.7.orig/include/polarssl/config.h
-+++ polarssl-1.3.7/include/polarssl/config.h
-@@ -953,7 +953,7 @@
+--- polarssl-1.3.9.orig/include/polarssl/config.h
++++ polarssl-1.3.9/include/polarssl/config.h
+@@ -860,7 +860,7 @@
+  *
+  * Comment this macro to disable support for SSL 3.0
+  */
+-#define POLARSSL_SSL_PROTO_SSL3
++//#define POLARSSL_SSL_PROTO_SSL3
+ 
+ /**
+  * \def POLARSSL_SSL_PROTO_TLS1
+@@ -973,7 +973,7 @@
   *
   * Uncomment this to enable pthread mutexes.
   */
@@ -14,7 +23,7 @@
  
  /**
   * \def POLARSSL_VERSION_FEATURES
-@@ -1473,7 +1473,7 @@
+@@ -1518,7 +1518,7 @@
   *
   * Uncomment to enable the HAVEGE random generator.
   */
@@ -23,7 +32,7 @@
  
  /**
   * \def POLARSSL_HMAC_DRBG_C
-@@ -1511,7 +1511,7 @@
+@@ -1556,7 +1556,7 @@
   *
   * Uncomment to enable support for (rare) MD2-signed X.509 certs.
   */
@@ -32,7 +41,7 @@
  
  /**
   * \def POLARSSL_MD4_C
-@@ -1523,7 +1523,7 @@
+@@ -1568,7 +1568,7 @@
   *
   * Uncomment to enable support for (rare) MD4-signed X.509 certs.
   */
@@ -41,7 +50,7 @@
  
  /**
   * \def POLARSSL_MD5_C
-@@ -1914,7 +1914,7 @@
+@@ -1959,7 +1959,7 @@
   *
   * Enable this layer to allow use of mutexes within PolarSSL
   */
diff -ruN polarssl-1.3.8/doxygen/input/doc_mainpage.h polarssl-1.3.9/doxygen/input/doc_mainpage.h
--- polarssl-1.3.8/doxygen/input/doc_mainpage.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/doxygen/input/doc_mainpage.h	2014-10-20 13:59:19.000000000 +0200
@@ -4,7 +4,7 @@
  */
 
 /**
- * @mainpage PolarSSL v1.3.8 source code documentation
+ * @mainpage PolarSSL v1.3.9 source code documentation
  *
  * This documentation describes the internal structure of PolarSSL.  It was
  * automatically generated from specially formatted comment blocks in
diff -ruN polarssl-1.3.8/doxygen/polarssl.doxyfile polarssl-1.3.9/doxygen/polarssl.doxyfile
--- polarssl-1.3.8/doxygen/polarssl.doxyfile	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/doxygen/polarssl.doxyfile	2014-10-20 13:59:19.000000000 +0200
@@ -28,7 +28,7 @@
 # identify the project. Note that if you do not use Doxywizard you need
 # to put quotes around the project name if it contains spaces.
 
-PROJECT_NAME           = "PolarSSL v1.3.8"
+PROJECT_NAME           = "PolarSSL v1.3.9"
 
 # The PROJECT_NUMBER tag can be used to enter a project or revision number.
 # This could be handy for archiving the generated documentation or
diff -ruN polarssl-1.3.8/include/polarssl/bignum.h polarssl-1.3.9/include/polarssl/bignum.h
--- polarssl-1.3.8/include/polarssl/bignum.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/bignum.h	2014-10-20 13:59:19.000000000 +0200
@@ -90,7 +90,7 @@
  * Note: Calculations can results temporarily in larger MPIs. So the number
  * of limbs required (POLARSSL_MPI_MAX_LIMBS) is higher.
  */
-#define POLARSSL_MPI_MAX_SIZE                              512      /**< Maximum number of bytes for usable MPIs. */
+#define POLARSSL_MPI_MAX_SIZE                              1024     /**< Maximum number of bytes for usable MPIs. */
 #endif /* !POLARSSL_MPI_MAX_SIZE */
 
 #define POLARSSL_MPI_MAX_BITS                              ( 8 * POLARSSL_MPI_MAX_SIZE )    /**< Maximum number of bits for usable MPIs. */
diff -ruN polarssl-1.3.8/include/polarssl/bn_mul.h polarssl-1.3.9/include/polarssl/bn_mul.h
--- polarssl-1.3.8/include/polarssl/bn_mul.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/bn_mul.h	2014-10-20 13:59:19.000000000 +0200
@@ -833,8 +833,8 @@
 
 #define MULADDC_CORE                    \
     r   = *(s++) * (t_udbl) b;          \
-    r0  = r;                            \
-    r1  = r >> biL;                     \
+    r0  = (t_uint) r;                   \
+    r1  = (t_uint)( r >> biL );         \
     r0 += c;  r1 += (r0 <  c);          \
     r0 += *d; r1 += (r0 < *d);          \
     c = r1; *(d++) = r0;
diff -ruN polarssl-1.3.8/include/polarssl/config.h polarssl-1.3.9/include/polarssl/config.h
--- polarssl-1.3.8/include/polarssl/config.h	2014-11-11 11:35:29.000000000 +0100
+++ polarssl-1.3.9/include/polarssl/config.h	2014-11-11 11:35:35.000000000 +0100
@@ -2113,7 +2113,7 @@
 
 /* MPI / BIGNUM options */
 //#define POLARSSL_MPI_WINDOW_SIZE            6 /**< Maximum windows size used. */
-//#define POLARSSL_MPI_MAX_SIZE             512 /**< Maximum number of bytes for usable MPIs. */
+//#define POLARSSL_MPI_MAX_SIZE            1024 /**< Maximum number of bytes for usable MPIs. */
 
 /* CTR_DRBG options */
 //#define CTR_DRBG_ENTROPY_LEN               48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */
diff -ruN polarssl-1.3.8/include/polarssl/error.h polarssl-1.3.9/include/polarssl/error.h
--- polarssl-1.3.8/include/polarssl/error.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/error.h	2014-10-20 13:59:19.000000000 +0200
@@ -91,7 +91,7 @@
  * ECP       4   8 (Started from top)
  * MD        5   4
  * CIPHER    6   6
- * SSL       6   9 (Started from top)
+ * SSL       6   10 (Started from top)
  * SSL       7   31
  *
  * Module dependent error code (5 bits 0x.00.-0x.F8.)
diff -ruN polarssl-1.3.8/include/polarssl/ssl.h polarssl-1.3.9/include/polarssl/ssl.h
--- polarssl-1.3.8/include/polarssl/ssl.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/ssl.h	2014-10-20 13:59:19.000000000 +0200
@@ -145,6 +145,7 @@
 #define POLARSSL_ERR_SSL_UNKNOWN_IDENTITY                  -0x6C80  /**< Unknown identity received (eg, PSK identity) */
 #define POLARSSL_ERR_SSL_INTERNAL_ERROR                    -0x6C00  /**< Internal error (eg, unexpected failure in lower-level module) */
 #define POLARSSL_ERR_SSL_COUNTER_WRAPPING                  -0x6B80  /**< A counter would wrap (eg, too many messages exchanged). */
+#define POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO       -0x6B00  /**< Unexpected message at ServerHello in renegotiation. */
 
 /*
  * Various constants
@@ -204,6 +205,7 @@
 
 #define SSL_IS_CLIENT                   0
 #define SSL_IS_SERVER                   1
+
 #define SSL_COMPRESS_NULL               0
 #define SSL_COMPRESS_DEFLATE            1
 
@@ -560,8 +562,8 @@
 
 #if defined(POLARSSL_SSL_PROTO_SSL3)
     /* Needed only for SSL v3.0 secret */
-    unsigned char mac_enc[48];          /*!<  SSL v3.0 secret (enc)   */
-    unsigned char mac_dec[48];          /*!<  SSL v3.0 secret (dec)   */
+    unsigned char mac_enc[20];          /*!<  SSL v3.0 secret (enc)   */
+    unsigned char mac_dec[20];          /*!<  SSL v3.0 secret (dec)   */
 #endif /* POLARSSL_SSL_PROTO_SSL3 */
 
     md_context_t md_ctx_enc;            /*!<  MAC (encryption)        */
@@ -1491,23 +1493,26 @@
 /**
  * \brief          Enforce server-requested renegotiation.
  *                 (Default: enforced, max_records = 16)
- *                 (No effect on client.)
  *
- *                 When a server requests a renegotiation, the client can
- *                 comply or ignore the request. This function allows the
- *                 server to decide if it should enforce its renegotiation
- *                 requests by closing the connection if the client doesn't
- *                 initiate a renegotiation.
- *
- *                 However, records could already be in transit from the
- *                 client to the server when the request is emitted. In order
- *                 to increase reliability, the server can accept a number of
- *                 records containing application data before the ClientHello
- *                 that was requested.
+ *                 When we request a renegotiation, the peer can comply or
+ *                 ignore the request. This function allows us to decide
+ *                 whether to enforce our renegotiation requests by closing
+ *                 the connection if the peer doesn't comply.
+ *
+ *                 However, records could already be in transit from the peer
+ *                 when the request is emitted. In order to increase
+ *                 reliability, we can accept a number of records before the
+ *                 expected handshake records.
  *
  *                 The optimal value is highly dependent on the specific usage
  *                 scenario.
  *
+ * \warning        On client, the grace period can only happen during
+ *                 ssl_read(), as opposed to ssl_write() and ssl_renegotiate()
+ *                 which always behave as if max_record was 0. The reason is,
+ *                 if we receive application data from the server, we need a
+ *                 place to write it, which only happens during ssl_read().
+ *
  * \param ssl      SSL context
  * \param max_records Use SSL_RENEGOTIATION_NOT_ENFORCED if you don't want to
  *                 enforce renegotiation, or a non-negative value to enforce
@@ -1632,7 +1637,7 @@
  *
  * \param ssl      SSL context
  * \param buf      buffer that will hold the data
- * \param len      how many bytes must be read
+ * \param len      maximum number of bytes to read
  *
  * \return         This function returns the number of bytes read, 0 for EOF,
  *                 or a negative error code.
diff -ruN polarssl-1.3.8/include/polarssl/version.h polarssl-1.3.9/include/polarssl/version.h
--- polarssl-1.3.8/include/polarssl/version.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/version.h	2014-10-20 13:59:19.000000000 +0200
@@ -43,16 +43,16 @@
  */
 #define POLARSSL_VERSION_MAJOR  1
 #define POLARSSL_VERSION_MINOR  3
-#define POLARSSL_VERSION_PATCH  8
+#define POLARSSL_VERSION_PATCH  9
 
 /**
  * The single version number has the following structure:
  *    MMNNPP00
  *    Major version | Minor version | Patch version
  */
-#define POLARSSL_VERSION_NUMBER         0x01030800
-#define POLARSSL_VERSION_STRING         "1.3.8"
-#define POLARSSL_VERSION_STRING_FULL    "PolarSSL 1.3.8"
+#define POLARSSL_VERSION_NUMBER         0x01030900
+#define POLARSSL_VERSION_STRING         "1.3.9"
+#define POLARSSL_VERSION_STRING_FULL    "PolarSSL 1.3.9"
 
 #if defined(POLARSSL_VERSION_C)
 
diff -ruN polarssl-1.3.8/include/polarssl/x509.h polarssl-1.3.9/include/polarssl/x509.h
--- polarssl-1.3.8/include/polarssl/x509.h	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/include/polarssl/x509.h	2014-10-20 13:59:19.000000000 +0200
@@ -143,6 +143,8 @@
 #define X509_FORMAT_DER                 1
 #define X509_FORMAT_PEM                 2
 
+#define X509_MAX_DN_NAME_SIZE         256 /**< Maximum value size of a DN entry */
+
 #ifdef __cplusplus
 extern "C" {
 #endif
diff -ruN polarssl-1.3.8/library/asn1parse.c polarssl-1.3.9/library/asn1parse.c
--- polarssl-1.3.8/library/asn1parse.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/asn1parse.c	2014-10-20 13:59:19.000000000 +0200
@@ -47,6 +47,11 @@
 #include <string.h>
 #include <stdlib.h>
 
+/* Implementation that should never be optimized out by the compiler */
+static void polarssl_zeroize( void *v, size_t n ) {
+    volatile unsigned char *p = v; while( n-- ) *p++ = 0;
+}
+
 /*
  * ASN.1 DER decoding routines
  */
@@ -311,7 +316,7 @@
 
     if( *p == end )
     {
-        memset( params, 0, sizeof(asn1_buf) );
+        polarssl_zeroize( params, sizeof(asn1_buf) );
         return( 0 );
     }
 
@@ -356,7 +361,7 @@
     polarssl_free( cur->oid.p );
     polarssl_free( cur->val.p );
 
-    memset( cur, 0, sizeof( asn1_named_data ) );
+    polarssl_zeroize( cur, sizeof( asn1_named_data ) );
 }
 
 void asn1_free_named_data_list( asn1_named_data **head )
diff -ruN polarssl-1.3.8/library/base64.c polarssl-1.3.9/library/base64.c
--- polarssl-1.3.8/library/base64.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/base64.c	2014-10-20 13:59:19.000000000 +0200
@@ -147,8 +147,21 @@
     uint32_t j, x;
     unsigned char *p;
 
+    /* First pass: check for validity and get output length */
     for( i = n = j = 0; i < slen; i++ )
     {
+        /* Skip spaces before checking for EOL */
+        x = 0;
+        while( i < slen && src[i] == ' ' )
+        {
+            ++i;
+            ++x;
+        }
+
+        /* Spaces at end of buffer are OK */
+        if( i == slen )
+            break;
+
         if( ( slen - i ) >= 2 &&
             src[i] == '\r' && src[i + 1] == '\n' )
             continue;
@@ -156,6 +169,10 @@
         if( src[i] == '\n' )
             continue;
 
+        /* Space inside a line is an error */
+        if( x != 0 )
+            return( POLARSSL_ERR_BASE64_INVALID_CHARACTER );
+
         if( src[i] == '=' && ++j > 2 )
             return( POLARSSL_ERR_BASE64_INVALID_CHARACTER );
 
@@ -182,7 +199,7 @@
 
    for( j = 3, n = x = 0, p = dst; i > 0; i--, src++ )
    {
-        if( *src == '\r' || *src == '\n' )
+        if( *src == '\r' || *src == '\n' || *src == ' ' )
             continue;
 
         j -= ( base64_dec_map[*src] == 64 );
diff -ruN polarssl-1.3.8/library/bignum.c polarssl-1.3.9/library/bignum.c
--- polarssl-1.3.8/library/bignum.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/bignum.c	2014-10-20 13:59:19.000000000 +0200
@@ -2057,7 +2057,11 @@
                   void *p_rng )
 {
     int ret;
-    const mpi XX = { 1, X->n, X->p }; /* Abs(X) */
+    mpi XX;
+
+    XX.s = 1;
+    XX.n = X->n;
+    XX.p = X->p;
 
     if( mpi_cmp_int( &XX, 0 ) == 0 ||
         mpi_cmp_int( &XX, 1 ) == 0 )
diff -ruN polarssl-1.3.8/library/cipher_wrap.c polarssl-1.3.9/library/cipher_wrap.c
--- polarssl-1.3.8/library/cipher_wrap.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/cipher_wrap.c	2014-10-20 13:59:19.000000000 +0200
@@ -1313,7 +1313,7 @@
 
 static void * null_ctx_alloc( void )
 {
-    return( (void *) 1 )
+    return( (void *) 1 );
 }
 
 static void null_ctx_free( void *ctx )
diff -ruN polarssl-1.3.8/library/CMakeLists.txt polarssl-1.3.9/library/CMakeLists.txt
--- polarssl-1.3.8/library/CMakeLists.txt	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/CMakeLists.txt	2014-10-20 13:59:19.000000000 +0200
@@ -118,7 +118,7 @@
 
 if(USE_SHARED_POLARSSL_LIBRARY)
 	add_library(polarssl SHARED ${src})
-	set_target_properties(polarssl PROPERTIES VERSION 1.3.8 SOVERSION 7)
+	set_target_properties(polarssl PROPERTIES VERSION 1.3.9 SOVERSION 7)
 
 	target_link_libraries(polarssl ${libs})
 
diff -ruN polarssl-1.3.8/library/ecp.c polarssl-1.3.9/library/ecp.c
--- polarssl-1.3.8/library/ecp.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/ecp.c	2014-10-20 13:59:19.000000000 +0200
@@ -495,7 +495,7 @@
     int ret;
     size_t plen;
 
-    if ( ilen < 1 )
+    if( ilen < 1 )
         return( POLARSSL_ERR_ECP_BAD_INPUT_DATA );
 
     if( buf[0] == 0x00 )
@@ -952,7 +952,9 @@
         MOD_SUB( X3 );
     }
     else
+    {
         MPI_CHK( mpi_mul_mpi( &X3,  &X3,    &grp->A ) ); MOD_MUL( X3 );
+    }
 
     MPI_CHK( mpi_add_mpi( &T3,  &T3,    &X3     ) ); MOD_ADD( T3 );
     MPI_CHK( mpi_mul_mpi( &X3,  &T3,    &T3     ) ); MOD_MUL( X3 );
diff -ruN polarssl-1.3.8/library/error.c polarssl-1.3.9/library/error.c
--- polarssl-1.3.8/library/error.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/error.c	2014-10-20 13:59:19.000000000 +0200
@@ -450,6 +450,8 @@
             snprintf( buf, buflen, "SSL - Internal error (eg, unexpected failure in lower-level module)" );
         if( use_ret == -(POLARSSL_ERR_SSL_COUNTER_WRAPPING) )
             snprintf( buf, buflen, "SSL - A counter would wrap (eg, too many messages exchanged)" );
+        if( use_ret == -(POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO) )
+            snprintf( buf, buflen, "SSL - Unexpected message at ServerHello in renegotiation" );
 #endif /* POLARSSL_SSL_TLS_C */
 
 #if defined(POLARSSL_X509_USE_C) || defined(POLARSSL_X509_CREATE_C)
diff -ruN polarssl-1.3.8/library/gcm.c polarssl-1.3.9/library/gcm.c
--- polarssl-1.3.8/library/gcm.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/gcm.c	2014-10-20 13:59:19.000000000 +0200
@@ -220,7 +220,6 @@
 #endif /* POLARSSL_AESNI_C && POLARSSL_HAVE_X86_64 */
 
     lo = x[15] & 0xf;
-    hi = x[15] >> 4;
 
     zh = ctx->HH[lo];
     zl = ctx->HL[lo];
@@ -354,7 +353,7 @@
     /* Total length is restricted to 2^39 - 256 bits, ie 2^36 - 2^5 bytes
      * Also check for possible overflow */
     if( ctx->len + length < ctx->len ||
-        (uint64_t) ctx->len + length > 0x03FFFFE0llu )
+        (uint64_t) ctx->len + length > 0x03FFFFE0ull )
     {
         return( POLARSSL_ERR_GCM_BAD_INPUT );
     }
diff -ruN polarssl-1.3.8/library/md.c polarssl-1.3.9/library/md.c
--- polarssl-1.3.8/library/md.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/md.c	2014-10-20 13:59:19.000000000 +0200
@@ -53,13 +53,13 @@
 static const int supported_digests[] = {
 
 #if defined(POLARSSL_SHA512_C)
-        POLARSSL_MD_SHA384,
         POLARSSL_MD_SHA512,
+        POLARSSL_MD_SHA384,
 #endif
 
 #if defined(POLARSSL_SHA256_C)
-        POLARSSL_MD_SHA224,
         POLARSSL_MD_SHA256,
+        POLARSSL_MD_SHA224,
 #endif
 
 #if defined(POLARSSL_SHA1_C)
diff -ruN polarssl-1.3.8/library/memory_buffer_alloc.c polarssl-1.3.9/library/memory_buffer_alloc.c
--- polarssl-1.3.8/library/memory_buffer_alloc.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/memory_buffer_alloc.c	2014-10-20 13:59:19.000000000 +0200
@@ -37,10 +37,10 @@
 
 #if defined(POLARSSL_MEMORY_DEBUG)
 #include <stdio.h>
+#endif
 #if defined(POLARSSL_MEMORY_BACKTRACE)
 #include <execinfo.h>
 #endif
-#endif
 
 #if defined(POLARSSL_THREADING_C)
 #include "polarssl/threading.h"
@@ -109,11 +109,11 @@
     size_t i;
 #endif
 
-    polarssl_fprintf( stderr, "HDR:  PTR(%10u), PREV(%10u), NEXT(%10u), "
-                              "ALLOC(%u), SIZE(%10u)\n",
+    polarssl_fprintf( stderr, "HDR:  PTR(%10zu), PREV(%10zu), NEXT(%10zu), "
+                              "ALLOC(%zu), SIZE(%10zu)\n",
                       (size_t) hdr, (size_t) hdr->prev, (size_t) hdr->next,
                       hdr->alloc, hdr->size );
-    polarssl_fprintf( stderr, "      FPREV(%10u), FNEXT(%10u)\n",
+    polarssl_fprintf( stderr, "      FPREV(%10zu), FNEXT(%10zu)\n",
                       (size_t) hdr->prev_free, (size_t) hdr->next_free );
 
 #if defined(POLARSSL_MEMORY_BACKTRACE)
@@ -511,8 +511,8 @@
 void memory_buffer_alloc_status()
 {
     polarssl_fprintf( stderr,
-                      "Current use: %u blocks / %u bytes, max: %u blocks / "
-                      "%u bytes (total %u bytes), malloc / free: %u / %u\n",
+                      "Current use: %zu blocks / %zu bytes, max: %zu blocks / "
+                      "%zu bytes (total %zu bytes), malloc / free: %zu / %zu\n",
                       heap.header_count, heap.total_used,
                       heap.maximum_header_count, heap.maximum_used,
                       heap.maximum_header_count * sizeof( memory_header )
diff -ruN polarssl-1.3.8/library/net.c polarssl-1.3.9/library/net.c
--- polarssl-1.3.8/library/net.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/net.c	2014-10-20 13:59:19.000000000 +0200
@@ -434,7 +434,7 @@
 
     if( *client_fd < 0 )
     {
-        if( net_would_block( *client_fd ) != 0 )
+        if( net_would_block( bind_fd ) != 0 )
             return( POLARSSL_ERR_NET_WANT_READ );
 
         return( POLARSSL_ERR_NET_ACCEPT_FAILED );
@@ -497,7 +497,12 @@
 {
     struct timeval tv;
     tv.tv_sec  = 0;
+#if !defined(_WIN32) && ( defined(__unix__) || defined(__unix) || \
+    ( defined(__APPLE__) && defined(__MACH__) ) )
+    tv.tv_usec = (suseconds_t) usec;
+#else
     tv.tv_usec = usec;
+#endif
     select( 0, NULL, NULL, NULL, &tv );
 }
 #endif /* POLARSSL_HAVE_TIME */
@@ -508,7 +513,7 @@
 int net_recv( void *ctx, unsigned char *buf, size_t len )
 {
     int fd = *((int *) ctx);
-    int ret = read( fd, buf, len );
+    int ret = (int) read( fd, buf, len );
 
     if( ret < 0 )
     {
@@ -539,7 +544,7 @@
 int net_send( void *ctx, const unsigned char *buf, size_t len )
 {
     int fd = *((int *) ctx);
-    int ret = write( fd, buf, len );
+    int ret = (int) write( fd, buf, len );
 
     if( ret < 0 )
     {
diff -ruN polarssl-1.3.8/library/pk.c polarssl-1.3.9/library/pk.c
--- polarssl-1.3.8/library/pk.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/pk.c	2014-10-20 13:59:19.000000000 +0200
@@ -222,7 +222,7 @@
 
         ret = rsa_rsassa_pss_verify_ext( pk_rsa( *ctx ),
                 NULL, NULL, RSA_PUBLIC,
-                md_alg, hash_len, hash,
+                md_alg, (unsigned int) hash_len, hash,
                 pss_opts->mgf1_hash_id,
                 pss_opts->expected_salt_len,
                 sig );
diff -ruN polarssl-1.3.8/library/pkcs5.c polarssl-1.3.9/library/pkcs5.c
--- polarssl-1.3.8/library/pkcs5.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/pkcs5.c	2014-10-20 13:59:19.000000000 +0200
@@ -408,7 +408,7 @@
 exit:
     md_free( &sha1_ctx );
 
-    return( 0 );
+    return( ret );
 }
 #endif /* POLARSSL_SHA1_C */
 
diff -ruN polarssl-1.3.8/library/pkwrite.c polarssl-1.3.9/library/pkwrite.c
--- polarssl-1.3.8/library/pkwrite.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/pkwrite.c	2014-10-20 13:59:19.000000000 +0200
@@ -294,10 +294,93 @@
 #define PEM_BEGIN_PRIVATE_KEY_EC    "-----BEGIN EC PRIVATE KEY-----\n"
 #define PEM_END_PRIVATE_KEY_EC      "-----END EC PRIVATE KEY-----\n"
 
+/*
+ * Max sizes of key per types. Shown as tag + len (+ content).
+ */
+
+#if defined(POLARSSL_RSA_C)
+/*
+ * RSA public keys:
+ *  SubjectPublicKeyInfo  ::=  SEQUENCE  {          1 + 3
+ *       algorithm            AlgorithmIdentifier,  1 + 1 (sequence)
+ *                                                + 1 + 1 + 9 (rsa oid)
+ *                                                + 1 + 1 (params null)
+ *       subjectPublicKey     BIT STRING }          1 + 3 + (1 + below)
+ *  RSAPublicKey ::= SEQUENCE {                     1 + 3
+ *      modulus           INTEGER,  -- n            1 + 3 + MPI_MAX + 1
+ *      publicExponent    INTEGER   -- e            1 + 3 + MPI_MAX + 1
+ *  }
+ */
+#define RSA_PUB_DER_MAX_BYTES   38 + 2 * POLARSSL_MPI_MAX_SIZE
+
+/*
+ * RSA private keys:
+ *  RSAPrivateKey ::= SEQUENCE {                    1 + 3
+ *      version           Version,                  1 + 1 + 1
+ *      modulus           INTEGER,                  1 + 3 + MPI_MAX + 1
+ *      publicExponent    INTEGER,                  1 + 3 + MPI_MAX + 1
+ *      privateExponent   INTEGER,                  1 + 3 + MPI_MAX + 1
+ *      prime1            INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
+ *      prime2            INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
+ *      exponent1         INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
+ *      exponent2         INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
+ *      coefficient       INTEGER,                  1 + 3 + MPI_MAX / 2 + 1
+ *      otherPrimeInfos   OtherPrimeInfos OPTIONAL  0 (not supported)
+ *  }
+ */
+#define MPI_MAX_SIZE_2          POLARSSL_MPI_MAX_SIZE / 2 + \
+                                POLARSSL_MPI_MAX_SIZE % 2
+#define RSA_PRV_DER_MAX_BYTES   47 + 3 * POLARSSL_MPI_MAX_SIZE \
+                                   + 5 * MPI_MAX_SIZE_2
+
+#else /* POLARSSL_RSA_C */
+
+#define RSA_PUB_DER_MAX_BYTES   0
+#define RSA_PRV_DER_MAX_BYTES   0
+
+#endif /* POLARSSL_RSA_C */
+
+#if defined(POLARSSL_ECP_C)
+/*
+ * EC public keys:
+ *  SubjectPublicKeyInfo  ::=  SEQUENCE  {      1 + 2
+ *    algorithm         AlgorithmIdentifier,    1 + 1 (sequence)
+ *                                            + 1 + 1 + 7 (ec oid)
+ *                                            + 1 + 1 + 9 (namedCurve oid)
+ *    subjectPublicKey  BIT STRING              1 + 2 + 1               [1]
+ *                                            + 1 (point format)        [1]
+ *                                            + 2 * ECP_MAX (coords)    [1]
+ *  }
+ */
+#define ECP_PUB_DER_MAX_BYTES   30 + 2 * POLARSSL_ECP_MAX_BYTES
+
+/*
+ * EC private keys:
+ * ECPrivateKey ::= SEQUENCE {                  1 + 2
+ *      version        INTEGER ,                1 + 1 + 1
+ *      privateKey     OCTET STRING,            1 + 1 + ECP_MAX
+ *      parameters [0] ECParameters OPTIONAL,   1 + 1 + (1 + 1 + 9)
+ *      publicKey  [1] BIT STRING OPTIONAL      1 + 2 + [1] above
+ *    }
+ */
+#define ECP_PRV_DER_MAX_BYTES   29 + 3 * POLARSSL_ECP_MAX_BYTES
+
+#else /* POLARSSL_ECP_C */
+
+#define ECP_PUB_DER_MAX_BYTES   0
+#define ECP_PRV_DER_MAX_BYTES   0
+
+#endif /* POLARSSL_ECP_C */
+
+#define PUB_DER_MAX_BYTES   RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
+                            RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES
+#define PRV_DER_MAX_BYTES   RSA_PRV_DER_MAX_BYTES > ECP_PRV_DER_MAX_BYTES ? \
+                            RSA_PRV_DER_MAX_BYTES : ECP_PRV_DER_MAX_BYTES
+
 int pk_write_pubkey_pem( pk_context *key, unsigned char *buf, size_t size )
 {
     int ret;
-    unsigned char output_buf[4096];
+    unsigned char output_buf[PUB_DER_MAX_BYTES];
     size_t olen = 0;
 
     if( ( ret = pk_write_pubkey_der( key, output_buf,
@@ -319,7 +402,7 @@
 int pk_write_key_pem( pk_context *key, unsigned char *buf, size_t size )
 {
     int ret;
-    unsigned char output_buf[4096];
+    unsigned char output_buf[PRV_DER_MAX_BYTES];
     const char *begin, *end;
     size_t olen = 0;
 
diff -ruN polarssl-1.3.8/library/rsa.c polarssl-1.3.9/library/rsa.c
--- polarssl-1.3.8/library/rsa.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/rsa.c	2014-10-20 13:59:19.000000000 +0200
@@ -1005,7 +1005,7 @@
 {
     size_t nb_pad, olen, oid_size = 0;
     unsigned char *p = sig;
-    const char *oid;
+    const char *oid = NULL;
 
     if( mode == RSA_PRIVATE && ctx->padding != RSA_PKCS_V15 )
         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
diff -ruN polarssl-1.3.8/library/ssl_ciphersuites.c polarssl-1.3.9/library/ssl_ciphersuites.c
--- polarssl-1.3.8/library/ssl_ciphersuites.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/ssl_ciphersuites.c	2014-10-20 13:59:19.000000000 +0200
@@ -260,7 +260,7 @@
     TLS_PSK_WITH_NULL_SHA256,
     TLS_PSK_WITH_NULL_SHA,
 
-#endif
+#endif /* SSL_CIPHERSUITES */
     0
 };
 
@@ -1077,7 +1077,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_PSK_WITH_AES_128_CBC_SHA256, "TLS-PSK-WITH-AES-128-CBC-SHA256",
       POLARSSL_CIPHER_AES_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1085,7 +1085,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_PSK_WITH_AES_256_CBC_SHA384, "TLS-PSK-WITH-AES-256-CBC-SHA384",
       POLARSSL_CIPHER_AES_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1133,7 +1133,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256, "TLS-PSK-WITH-CAMELLIA-128-CBC-SHA256",
       POLARSSL_CIPHER_CAMELLIA_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1141,7 +1141,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384, "TLS-PSK-WITH-CAMELLIA-256-CBC-SHA384",
       POLARSSL_CIPHER_CAMELLIA_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1213,7 +1213,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, "TLS-DHE-PSK-WITH-AES-128-CBC-SHA256",
       POLARSSL_CIPHER_AES_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1221,7 +1221,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, "TLS-DHE-PSK-WITH-AES-256-CBC-SHA384",
       POLARSSL_CIPHER_AES_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1269,7 +1269,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, "TLS-DHE-PSK-WITH-CAMELLIA-128-CBC-SHA256",
       POLARSSL_CIPHER_CAMELLIA_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1277,7 +1277,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, "TLS-DHE-PSK-WITH-CAMELLIA-256-CBC-SHA384",
       POLARSSL_CIPHER_CAMELLIA_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1428,7 +1428,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, "TLS-RSA-PSK-WITH-AES-128-CBC-SHA256",
       POLARSSL_CIPHER_AES_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1436,7 +1436,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, "TLS-RSA-PSK-WITH-AES-256-CBC-SHA384",
       POLARSSL_CIPHER_AES_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1444,13 +1444,13 @@
 #if defined(POLARSSL_SHA1_C)
     { TLS_RSA_PSK_WITH_AES_128_CBC_SHA, "TLS-RSA-PSK-WITH-AES-128-CBC-SHA",
       POLARSSL_CIPHER_AES_128_CBC, POLARSSL_MD_SHA1, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 
     { TLS_RSA_PSK_WITH_AES_256_CBC_SHA, "TLS-RSA-PSK-WITH-AES-256-CBC-SHA",
       POLARSSL_CIPHER_AES_256_CBC, POLARSSL_MD_SHA1, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA1_C */
@@ -1462,7 +1462,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256, "TLS-RSA-PSK-WITH-CAMELLIA-128-CBC-SHA256",
       POLARSSL_CIPHER_CAMELLIA_128_CBC, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA256_C */
@@ -1470,7 +1470,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384, "TLS-RSA-PSK-WITH-CAMELLIA-256-CBC-SHA384",
       POLARSSL_CIPHER_CAMELLIA_256_CBC, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA512_C */
@@ -1500,7 +1500,7 @@
 #if defined(POLARSSL_SHA1_C)
     { TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, "TLS-RSA-PSK-WITH-3DES-EDE-CBC-SHA",
       POLARSSL_CIPHER_DES_EDE3_CBC, POLARSSL_MD_SHA1, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA1_C */
@@ -1511,7 +1511,7 @@
 #if defined(POLARSSL_SHA1_C)
     { TLS_RSA_PSK_WITH_RC4_128_SHA, "TLS-RSA-PSK-WITH-RC4-128-SHA",
       POLARSSL_CIPHER_ARC4_128, POLARSSL_MD_SHA1, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       0 },
 #endif /* POLARSSL_SHA1_C */
@@ -1540,7 +1540,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_RSA_WITH_NULL_SHA256, "TLS-RSA-WITH-NULL-SHA256",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_RSA,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1558,7 +1558,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_PSK_WITH_NULL_SHA256, "TLS-PSK-WITH-NULL-SHA256",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1566,7 +1566,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_PSK_WITH_NULL_SHA384, "TLS-PSK-WITH-NULL-SHA384",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1584,7 +1584,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_DHE_PSK_WITH_NULL_SHA256, "TLS-DHE-PSK-WITH-NULL-SHA256",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1592,7 +1592,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_DHE_PSK_WITH_NULL_SHA384, "TLS-DHE-PSK-WITH-NULL-SHA384",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_DHE_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1628,7 +1628,7 @@
 #if defined(POLARSSL_SHA1_C)
     { TLS_RSA_PSK_WITH_NULL_SHA, "TLS-RSA-PSK-WITH-NULL-SHA",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA1, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif /* POLARSSL_SHA1_C */
@@ -1636,7 +1636,7 @@
 #if defined(POLARSSL_SHA256_C)
     { TLS_RSA_PSK_WITH_NULL_SHA256, "TLS-RSA-PSK-WITH-NULL-SHA256",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA256, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
@@ -1644,7 +1644,7 @@
 #if defined(POLARSSL_SHA512_C)
     { TLS_RSA_PSK_WITH_NULL_SHA384, "TLS-RSA-PSK-WITH-NULL-SHA384",
       POLARSSL_CIPHER_NULL, POLARSSL_MD_SHA384, POLARSSL_KEY_EXCHANGE_RSA_PSK,
-      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0,
+      SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1,
       SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_3,
       POLARSSL_CIPHERSUITE_WEAK },
 #endif
diff -ruN polarssl-1.3.8/library/ssl_cli.c polarssl-1.3.9/library/ssl_cli.c
--- polarssl-1.3.8/library/ssl_cli.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/ssl_cli.c	2014-10-20 13:59:19.000000000 +0200
@@ -875,7 +875,7 @@
 {
     int ret, i, comp;
     size_t n;
-    size_t ext_len = 0;
+    size_t ext_len;
     unsigned char *buf, *ext;
     int renegotiation_info_seen = 0;
     int handshake_failure = 0;
@@ -902,6 +902,22 @@
 
     if( ssl->in_msgtype != SSL_MSG_HANDSHAKE )
     {
+        if( ssl->renegotiation == SSL_RENEGOTIATION )
+        {
+            ssl->renego_records_seen++;
+
+            if( ssl->renego_max_records >= 0 &&
+                ssl->renego_records_seen > ssl->renego_max_records )
+            {
+                SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
+                                    "but not honored by server" ) );
+                return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
+            }
+
+            SSL_DEBUG_MSG( 1, ( "non-handshake message during renego" ) );
+            return( POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );
+        }
+
         SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
         return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
     }
@@ -965,7 +981,7 @@
      *   42+n . 43+n  extensions length
      *   44+n . 44+n+m extensions
      */
-    if( ssl->in_hslen > 42 + n )
+    if( ssl->in_hslen > 43 + n )
     {
         ext_len = ( ( buf[42 + n] <<  8 )
                   | ( buf[43 + n]       ) );
@@ -977,6 +993,15 @@
             return( POLARSSL_ERR_SSL_BAD_HS_SERVER_HELLO );
         }
     }
+    else if( ssl->in_hslen == 42 + n )
+    {
+        ext_len = 0;
+    }
+    else
+    {
+        SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
+        return( POLARSSL_ERR_SSL_BAD_HS_SERVER_HELLO );
+    }
 
     i = ( buf[39 + n] << 8 ) | buf[40 + n];
     comp = buf[41 + n];
diff -ruN polarssl-1.3.8/library/ssl_srv.c polarssl-1.3.9/library/ssl_srv.c
--- polarssl-1.3.8/library/ssl_srv.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/ssl_srv.c	2014-10-20 13:59:19.000000000 +0200
@@ -494,11 +494,16 @@
         for( p = buf + 2; p < end; p += 2 ) {
             if( *md_cur == (int) ssl_md_alg_from_hash( p[0] ) ) {
                 ssl->handshake->sig_alg = p[0];
-                break;
+                goto have_sig_alg;
             }
         }
     }
 
+    /* Some key echanges do not need signatures at all */
+    SSL_DEBUG_MSG( 3, ( "no signature_algorithm in common" ) );
+    return( 0 );
+
+have_sig_alg:
     SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d",
                    ssl->handshake->sig_alg ) );
 
@@ -521,6 +526,13 @@
     {
         SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
         return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
+    }
+
+    /* Should never happen unless client duplicates the extension */
+    if( ssl->handshake->curves != NULL )
+    {
+        SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
+        return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO );
     }
 
     /* Don't allow our peer to make us allocate too much memory,
diff -ruN polarssl-1.3.8/library/ssl_tls.c polarssl-1.3.9/library/ssl_tls.c
--- polarssl-1.3.8/library/ssl_tls.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/ssl_tls.c	2014-10-20 13:59:19.000000000 +0200
@@ -991,18 +991,15 @@
 {
     unsigned char header[11];
     unsigned char padding[48];
-    int padlen = 0;
+    int padlen;
     int md_size = md_get_size( md_ctx->md_info );
     int md_type = md_get_type( md_ctx->md_info );
 
+    /* Only MD5 and SHA-1 supported */
     if( md_type == POLARSSL_MD_MD5 )
         padlen = 48;
-    else if( md_type == POLARSSL_MD_SHA1 )
+    else
         padlen = 40;
-    else if( md_type == POLARSSL_MD_SHA256 )
-        padlen = 32;
-    else if( md_type == POLARSSL_MD_SHA384 )
-        padlen = 16;
 
     memcpy( header, ctr, 8 );
     header[ 8] = (unsigned char)  type;
@@ -2230,10 +2227,6 @@
         {
             SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
                            ssl->in_msg[1] ) );
-            /**
-             * Subtract from error code as ssl->in_msg[1] is 7-bit positive
-             * error identifier.
-             */
             return( POLARSSL_ERR_SSL_FATAL_ALERT_MESSAGE );
         }
 
@@ -3345,7 +3338,7 @@
             (ssl_session *) polarssl_malloc( sizeof(ssl_session) );
     }
 
-    if( ssl->handshake == NULL)
+    if( ssl->handshake == NULL )
     {
         ssl->handshake = (ssl_handshake_params *)
             polarssl_malloc( sizeof(ssl_handshake_params) );
@@ -4174,8 +4167,6 @@
         return( ret );
     }
 
-    ssl->renegotiation = SSL_RENEGOTIATION_PENDING;
-
     SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
 
     return( 0 );
@@ -4184,10 +4175,10 @@
 
 /*
  * Actually renegotiate current connection, triggered by either:
- * - calling ssl_renegotiate() on client,
- * - receiving a HelloRequest on client during ssl_read(),
- * - receiving any handshake message on server during ssl_read() after the
- *   initial handshake is completed
+ * - any side: calling ssl_renegotiate(),
+ * - client: receiving a HelloRequest during ssl_read(),
+ * - server: receiving any handshake message on server during ssl_read() after
+ *   the initial handshake is completed.
  * If the handshake doesn't complete due to waiting for I/O, it will continue
  * during the next calls to ssl_renegotiate() or ssl_read() respectively.
  */
@@ -4229,6 +4220,12 @@
         if( ssl->state != SSL_HANDSHAKE_OVER )
             return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
 
+        ssl->renegotiation = SSL_RENEGOTIATION_PENDING;
+
+        /* Did we already try/start sending HelloRequest? */
+        if( ssl->out_left != 0 )
+            return( ssl_flush_output( ssl ) );
+
         return( ssl_write_hello_request( ssl ) );
     }
 #endif /* POLARSSL_SSL_SRV_C */
@@ -4267,14 +4264,19 @@
  */
 int ssl_read( ssl_context *ssl, unsigned char *buf, size_t len )
 {
-    int ret;
+    int ret, record_read = 0;
     size_t n;
 
     SSL_DEBUG_MSG( 2, ( "=> read" ) );
 
     if( ssl->state != SSL_HANDSHAKE_OVER )
     {
-        if( ( ret = ssl_handshake( ssl ) ) != 0 )
+        ret = ssl_handshake( ssl );
+        if( ret == POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO )
+        {
+            record_read = 1;
+        }
+        else if( ret != 0 )
         {
             SSL_DEBUG_RET( 1, "ssl_handshake", ret );
             return( ret );
@@ -4283,13 +4285,16 @@
 
     if( ssl->in_offt == NULL )
     {
-        if( ( ret = ssl_read_record( ssl ) ) != 0 )
+        if( ! record_read )
         {
-            if( ret == POLARSSL_ERR_SSL_CONN_EOF )
-                return( 0 );
+            if( ( ret = ssl_read_record( ssl ) ) != 0 )
+            {
+                if( ret == POLARSSL_ERR_SSL_CONN_EOF )
+                    return( 0 );
 
-            SSL_DEBUG_RET( 1, "ssl_read_record", ret );
-            return( ret );
+                SSL_DEBUG_RET( 1, "ssl_read_record", ret );
+                return( ret );
+            }
         }
 
         if( ssl->in_msglen  == 0 &&
@@ -4359,14 +4364,22 @@
             }
             else
             {
-                if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
+                ret = ssl_start_renegotiation( ssl );
+                if( ret == POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO )
+                {
+                    record_read = 1;
+                }
+                else if( ret != 0 )
                 {
                     SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
                     return( ret );
                 }
+            }
 
+            /* If a non-handshake record was read during renego, fallthrough,
+             * else tell the user they should call ssl_read() again */
+            if( ! record_read )
                 return( POLARSSL_ERR_NET_WANT_READ );
-            }
         }
         else if( ssl->renegotiation == SSL_RENEGOTIATION_PENDING )
         {
@@ -4380,7 +4393,15 @@
                 return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
             }
         }
-        else if( ssl->in_msgtype != SSL_MSG_APPLICATION_DATA )
+
+        /* Fatal and closure alerts handled by ssl_read_record() */
+        if( ssl->in_msgtype == SSL_MSG_ALERT )
+        {
+            SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
+            return( POLARSSL_ERR_NET_WANT_READ );
+        }
+
+        if( ssl->in_msgtype != SSL_MSG_APPLICATION_DATA )
         {
             SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
             return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
@@ -4480,11 +4501,8 @@
 
     SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
 
-    if( ( ret = ssl_flush_output( ssl ) ) != 0 )
-    {
-        SSL_DEBUG_RET( 1, "ssl_flush_output", ret );
-        return( ret );
-    }
+    if( ssl->out_left != 0 )
+        return( ssl_flush_output( ssl ) );
 
     if( ssl->state == SSL_HANDSHAKE_OVER )
     {
@@ -4492,13 +4510,14 @@
                         SSL_ALERT_LEVEL_WARNING,
                         SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
         {
+            SSL_DEBUG_RET( 1, "ssl_send_alert_message", ret );
             return( ret );
         }
     }
 
     SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
 
-    return( ret );
+    return( 0 );
 }
 
 void ssl_transform_free( ssl_transform *transform )
diff -ruN polarssl-1.3.8/library/timing.c polarssl-1.3.9/library/timing.c
--- polarssl-1.3.8/library/timing.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/timing.c	2014-10-20 13:59:19.000000000 +0200
@@ -283,15 +283,16 @@
 
     gettimeofday( &offset, NULL );
 
-    delta = ( offset.tv_sec  - t->start.tv_sec  ) * 1000
-          + ( offset.tv_usec - t->start.tv_usec ) / 1000;
-
     if( reset )
     {
         t->start.tv_sec  = offset.tv_sec;
         t->start.tv_usec = offset.tv_usec;
+        return( 0 );
     }
 
+    delta = ( offset.tv_sec  - t->start.tv_sec  ) * 1000
+          + ( offset.tv_usec - t->start.tv_usec ) / 1000;
+
     return( delta );
 }
 
@@ -332,7 +333,7 @@
 #if defined(POLARSSL_SELF_TEST)
 
 /* To test net_usleep against our functions */
-#if defined(POLARSSL_NET_C)
+#if defined(POLARSSL_NET_C) && defined(POLARSSL_HAVE_TIME)
 #include "polarssl/net.h"
 #endif
 
@@ -378,7 +379,7 @@
     {
         (void) get_timer( &hires, 1 );
 
-        m_sleep( 500 * secs );
+        m_sleep( (int)( 500 * secs ) );
 
         millisecs = get_timer( &hires, 0 );
 
@@ -401,7 +402,7 @@
     {
         (void) get_timer( &hires, 1 );
 
-        set_alarm( secs );
+        set_alarm( (int) secs );
         while( !alarmed )
             ;
 
@@ -464,7 +465,7 @@
     if( verbose != 0 )
         polarssl_printf( "passed\n" );
 
-#if defined(POLARSSL_NET_C)
+#if defined(POLARSSL_NET_C) && defined(POLARSSL_HAVE_TIME)
     if( verbose != 0 )
         polarssl_printf( "  TIMING test #4 (net_usleep/ get_timer): " );
 
diff -ruN polarssl-1.3.8/library/x509.c polarssl-1.3.9/library/x509.c
--- polarssl-1.3.8/library/x509.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/x509.c	2014-10-20 13:59:19.000000000 +0200
@@ -409,58 +409,47 @@
  *  AttributeType ::= OBJECT IDENTIFIER
  *
  *  AttributeValue ::= ANY DEFINED BY AttributeType
+ *
+ *  We restrict RelativeDistinguishedName to be a set of 1 element. This is
+ *  the most common case, and our x509_name structure currently can't handle
+ *  more than that.
  */
 int x509_get_name( unsigned char **p, const unsigned char *end,
                    x509_name *cur )
 {
     int ret;
-    size_t len;
-    const unsigned char *end2;
-    x509_name *use;
+    size_t set_len;
+    const unsigned char *end_set;
 
-    if( ( ret = asn1_get_tag( p, end, &len,
+    /*
+     * parse first SET, restricted to 1 element
+     */
+    if( ( ret = asn1_get_tag( p, end, &set_len,
             ASN1_CONSTRUCTED | ASN1_SET ) ) != 0 )
         return( POLARSSL_ERR_X509_INVALID_NAME + ret );
 
-    end2 = end;
-    end  = *p + len;
-    use = cur;
-
-    do
-    {
-        if( ( ret = x509_get_attr_type_value( p, end, use ) ) != 0 )
-            return( ret );
+    end_set  = *p + set_len;
 
-        if( *p != end )
-        {
-            use->next = (x509_name *) polarssl_malloc(
-                    sizeof( x509_name ) );
-
-            if( use->next == NULL )
-                return( POLARSSL_ERR_X509_MALLOC_FAILED );
+    if( ( ret = x509_get_attr_type_value( p, end_set, cur ) ) != 0 )
+        return( ret );
 
-            memset( use->next, 0, sizeof( x509_name ) );
-
-            use = use->next;
-        }
-    }
-    while( *p != end );
+    if( *p != end_set )
+        return( POLARSSL_ERR_X509_FEATURE_UNAVAILABLE );
 
     /*
      * recurse until end of SEQUENCE is reached
      */
-    if( *p == end2 )
+    if( *p == end )
         return( 0 );
 
-    cur->next = (x509_name *) polarssl_malloc(
-         sizeof( x509_name ) );
+    cur->next = (x509_name *) polarssl_malloc( sizeof( x509_name ) );
 
     if( cur->next == NULL )
         return( POLARSSL_ERR_X509_MALLOC_FAILED );
 
     memset( cur->next, 0, sizeof( x509_name ) );
 
-    return( x509_get_name( p, end2, cur->next ) );
+    return( x509_get_name( p, end, cur->next ) );
 }
 
 /*
@@ -750,7 +739,7 @@
     unsigned char c;
     const x509_name *name;
     const char *short_name = NULL;
-    char s[128], *p;
+    char s[X509_MAX_DN_NAME_SIZE], *p;
 
     memset( s, 0, sizeof( s ) );
 
@@ -876,7 +865,7 @@
     ((void) sig_opts);
 #endif /* POLARSSL_X509_RSASSA_PSS_SUPPORT */
 
-    return( (int) size - n );
+    return( (int)( size - n ) );
 }
 
 /*
diff -ruN polarssl-1.3.8/library/x509_create.c polarssl-1.3.9/library/x509_create.c
--- polarssl-1.3.8/library/x509_create.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/x509_create.c	2014-10-20 13:59:19.000000000 +0200
@@ -100,6 +100,8 @@
     const char *end = s + strlen( s );
     const char *oid = NULL;
     int in_tag = 1;
+    char data[X509_MAX_DN_NAME_SIZE];
+    char *d = data;
 
     /* Clear existing chain if present */
     asn1_free_named_data_list( head );
@@ -116,13 +118,25 @@
 
             s = c + 1;
             in_tag = 0;
+            d = data;
         }
 
-        if( !in_tag && ( *c == ',' || c == end ) )
+        if( !in_tag && *c == '\\' && c != end )
+        {
+            c++;
+
+            /* Check for valid escaped characters */
+            if( c == end || *c != ',' )
+            {
+                ret = POLARSSL_ERR_X509_INVALID_NAME;
+                goto exit;
+            }
+        }
+        else if( !in_tag && ( *c == ',' || c == end ) )
         {
             if( asn1_store_named_data( head, oid, strlen( oid ),
-                                       (unsigned char *) s,
-                                       c - s ) == NULL )
+                                       (unsigned char *) data,
+                                       d - data ) == NULL )
             {
                 return( POLARSSL_ERR_X509_MALLOC_FAILED );
             }
@@ -133,6 +147,18 @@
             s = c + 1;
             in_tag = 1;
         }
+
+        if( !in_tag && s != c + 1 )
+        {
+            *(d++) = *c;
+
+            if( d - data == X509_MAX_DN_NAME_SIZE )
+            {
+                ret = POLARSSL_ERR_X509_INVALID_NAME;
+                goto exit;
+            }
+        }
+
         c++;
     }
 
diff -ruN polarssl-1.3.8/library/x509_crt.c polarssl-1.3.9/library/x509_crt.c
--- polarssl-1.3.8/library/x509_crt.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/library/x509_crt.c	2014-10-20 13:59:19.000000000 +0200
@@ -898,6 +898,7 @@
                 if( first_error == 0 )
                     first_error = ret;
 
+                total_failed++;
                 continue;
             }
             else
@@ -1528,8 +1529,10 @@
 }
 #endif /* POLARSSL_X509_CRL_PARSE_C */
 
-// Equal == 0, inequal == 1
-static int x509_name_cmp( const void *s1, const void *s2, size_t len )
+/*
+ * Like memcmp, but case-insensitive and always returns -1 if different
+ */
+static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
 {
     size_t i;
     unsigned char diff;
@@ -1549,12 +1552,16 @@
             continue;
         }
 
-        return( 1 );
+        return( -1 );
     }
 
     return( 0 );
 }
 
+/*
+ * Return 1 if match, 0 if not
+ * TODO: inverted return value!
+ */
 static int x509_wildcard_verify( const char *cn, x509_buf *name )
 {
     size_t i;
@@ -1576,7 +1583,7 @@
         return( 0 );
 
     if( cn_len - cn_idx == name->len - 1 &&
-        x509_name_cmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
+        x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
     {
         return( 1 );
     }
@@ -1585,6 +1592,65 @@
 }
 
 /*
+ * Compare two X.509 strings, case-insensitive, and allowing for some encoding
+ * variations (but not all).
+ *
+ * Return 0 if equal, -1 otherwise.
+ */
+static int x509_string_cmp( const x509_buf *a, const x509_buf *b )
+{
+    if( a->tag == b->tag &&
+        a->len == b->len &&
+        memcmp( a->p, b->p, b->len ) == 0 )
+    {
+        return( 0 );
+    }
+
+    if( ( a->tag == ASN1_UTF8_STRING || a->tag == ASN1_PRINTABLE_STRING ) &&
+        ( b->tag == ASN1_UTF8_STRING || b->tag == ASN1_PRINTABLE_STRING ) &&
+        a->len == b->len &&
+        x509_memcasecmp( a->p, b->p, b->len ) == 0 )
+    {
+        return( 0 );
+    }
+
+    return( -1 );
+}
+
+/*
+ * Compare two X.509 Names (aka rdnSequence).
+ *
+ * See RFC 5280 section 7.1, though we don't implement the whole algorithm:
+ * we sometimes return unequal when the full algorithm would return equal,
+ * but never the other way. (In particular, we don't do Unicode normalisation
+ * or space folding.)
+ *
+ * Return 0 if equal, -1 otherwise.
+ */
+static int x509_name_cmp( const x509_name *a, const x509_name *b )
+{
+    if( a == NULL && b == NULL )
+        return( 0 );
+
+    if( a == NULL || b == NULL )
+        return( -1 );
+
+    /* type */
+    if( a->oid.tag != b->oid.tag ||
+        a->oid.len != b->oid.len ||
+        memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
+    {
+        return( -1 );
+    }
+
+    /* value */
+    if( x509_string_cmp( &a->val, &b->val ) != 0 )
+        return( -1 );
+
+    return( x509_name_cmp( a->next, b->next ) );
+}
+
+/*
  * Check if 'parent' is a suitable parent (signing CA) for 'child'.
  * Return 0 if yes, -1 if not.
  *
@@ -1598,12 +1664,8 @@
     int need_ca_bit;
 
     /* Parent must be the issuer */
-    if( child->issuer_raw.len != parent->subject_raw.len ||
-        memcmp( child->issuer_raw.p, parent->subject_raw.p,
-                child->issuer_raw.len ) != 0 )
-    {
+    if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )
         return( -1 );
-    }
 
     /* Parent must have the basicConstraints CA bit set as a general rule */
     need_ca_bit = 1;
@@ -1858,7 +1920,7 @@
             while( cur != NULL )
             {
                 if( cur->buf.len == cn_len &&
-                    x509_name_cmp( cn, cur->buf.p, cn_len ) == 0 )
+                    x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )
                     break;
 
                 if( cur->buf.len > 2 &&
@@ -1879,7 +1941,7 @@
                 if( OID_CMP( OID_AT_CN, &name->oid ) )
                 {
                     if( name->val.len == cn_len &&
-                        x509_name_cmp( name->val.p, cn, cn_len ) == 0 )
+                        x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )
                         break;
 
                     if( name->val.len > 2 &&
diff -ruN polarssl-1.3.8/programs/pkey/gen_key.c polarssl-1.3.9/programs/pkey/gen_key.c
--- polarssl-1.3.8/programs/pkey/gen_key.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/pkey/gen_key.c	2014-10-20 13:59:19.000000000 +0200
@@ -64,11 +64,16 @@
 
 #define DFL_TYPE                POLARSSL_PK_RSA
 #define DFL_RSA_KEYSIZE         4096
-#define DFL_EC_CURVE            ecp_curve_list()->grp_id
 #define DFL_FILENAME            "keyfile.key"
 #define DFL_FORMAT              FORMAT_PEM
 #define DFL_USE_DEV_RANDOM      0
 
+#if defined(POLARSSL_ECP_C)
+#define DFL_EC_CURVE            ecp_curve_list()->grp_id
+#else
+#define DFL_EC_CURVE            0
+#endif
+
 /*
  * global options
  */
@@ -248,15 +253,18 @@
         else if( strcmp( p, "rsa_keysize" ) == 0 )
         {
             opt.rsa_keysize = atoi( q );
-            if( opt.rsa_keysize < 1024 || opt.rsa_keysize > 8192 )
+            if( opt.rsa_keysize < 1024 ||
+                opt.rsa_keysize > POLARSSL_MPI_MAX_BITS )
                 goto usage;
         }
+#if defined(POLARSSL_ECP_C)
         else if( strcmp( p, "ec_curve" ) == 0 )
         {
             if( ( curve_info = ecp_curve_info_from_name( q ) ) == NULL )
                 goto usage;
             opt.ec_curve = curve_info->grp_id;
         }
+#endif
         else if( strcmp( p, "filename" ) == 0 )
             opt.filename = q;
         else if( strcmp( p, "use_dev_random" ) == 0 )
@@ -373,7 +381,18 @@
 #endif
         printf("  ! key type not supported\n");
 
-    write_private_key( &key, opt.filename );
+    /*
+     * 1.3 Export key
+     */
+    printf( "  . Writing key to file..." );
+
+    if( ( ret = write_private_key( &key, opt.filename ) ) != 0 )
+    {
+        printf( " failed\n" );
+        goto exit;
+    }
+
+    printf( " ok\n" );
 
 exit:
 
diff -ruN polarssl-1.3.8/programs/ssl/ssl_client2.c polarssl-1.3.9/programs/ssl/ssl_client2.c
--- polarssl-1.3.8/programs/ssl/ssl_client2.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/ssl/ssl_client2.c	2014-10-20 13:59:19.000000000 +0200
@@ -85,6 +85,7 @@
 #define DFL_RENEGOTIATION       SSL_RENEGOTIATION_DISABLED
 #define DFL_ALLOW_LEGACY        SSL_LEGACY_NO_RENEGOTIATION
 #define DFL_RENEGOTIATE         0
+#define DFL_EXCHANGES           1
 #define DFL_MIN_VERSION         -1
 #define DFL_MAX_VERSION         -1
 #define DFL_AUTH_MODE           SSL_VERIFY_REQUIRED
@@ -120,6 +121,8 @@
     int renegotiation;          /* enable / disable renegotiation           */
     int allow_legacy;           /* allow legacy renegotiation               */
     int renegotiate;            /* attempt renegotiation?                   */
+    int renego_delay;           /* delay before enforcing renegotiation     */
+    int exchanges;              /* number of data exchanges                 */
     int min_version;            /* minimum protocol version accepted        */
     int max_version;            /* maximum protocol version accepted        */
     int auth_mode;              /* verify mode for connection               */
@@ -303,6 +306,7 @@
     "    renegotiation=%%d    default: 1 (enabled)\n"       \
     "    allow_legacy=%%d     default: 0 (disabled)\n"      \
     "    renegotiate=%%d      default: 0 (disabled)\n"      \
+    "    exchanges=%%d        default: 1\n"                 \
     "    reconnect=%%d        default: 0 (disabled)\n"      \
     USAGE_TIME                                              \
     USAGE_TICKETS                                           \
@@ -322,7 +326,7 @@
 
 int main( int argc, char *argv[] )
 {
-    int ret = 0, len, server_fd, i, written, frags;
+    int ret = 0, len, tail_len, server_fd, i, written, frags;
     unsigned char buf[SSL_MAX_CONTENT_LEN + 1];
 #if defined(POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED)
     unsigned char psk[POLARSSL_PSK_MAX_LEN];
@@ -399,6 +403,7 @@
     opt.renegotiation       = DFL_RENEGOTIATION;
     opt.allow_legacy        = DFL_ALLOW_LEGACY;
     opt.renegotiate         = DFL_RENEGOTIATE;
+    opt.exchanges           = DFL_EXCHANGES;
     opt.min_version         = DFL_MIN_VERSION;
     opt.max_version         = DFL_MAX_VERSION;
     opt.auth_mode           = DFL_AUTH_MODE;
@@ -486,6 +491,12 @@
             if( opt.renegotiate < 0 || opt.renegotiate > 1 )
                 goto usage;
         }
+        else if( strcmp( p, "exchanges" ) == 0 )
+        {
+            opt.exchanges = atoi( q );
+            if( opt.exchanges < 1 )
+                goto usage;
+        }
         else if( strcmp( p, "reconnect" ) == 0 )
         {
             opt.reconnect = atoi( q );
@@ -1055,27 +1066,21 @@
     printf( "  > Write to server:" );
     fflush( stdout );
 
-    if( strcmp( opt.request_page, "SERVERQUIT" ) == 0 )
-        len = sprintf( (char *) buf, "%s", opt.request_page );
-    else
-    {
-        size_t tail_len = strlen( GET_REQUEST_END );
-
-        len = snprintf( (char *) buf, sizeof(buf) - 1, GET_REQUEST,
-                        opt.request_page );
+    len = snprintf( (char *) buf, sizeof(buf) - 1, GET_REQUEST,
+                    opt.request_page );
+    tail_len = strlen( GET_REQUEST_END );
 
-        /* Add padding to GET request to reach opt.request_size in length */
-        if( opt.request_size != DFL_REQUEST_SIZE &&
-            len + tail_len < (size_t) opt.request_size )
-        {
-            memset( buf + len, 'A', opt.request_size - len - tail_len );
-            len += opt.request_size - len - tail_len;
-        }
-
-        strncpy( (char *) buf + len, GET_REQUEST_END, sizeof(buf) - len - 1 );
-        len += tail_len;
+    /* Add padding to GET request to reach opt.request_size in length */
+    if( opt.request_size != DFL_REQUEST_SIZE &&
+        len + tail_len < opt.request_size )
+    {
+        memset( buf + len, 'A', opt.request_size - len - tail_len );
+        len += opt.request_size - len - tail_len;
     }
 
+    strncpy( (char *) buf + len, GET_REQUEST_END, sizeof(buf) - len - 1 );
+    len += tail_len;
+
     /* Truncate if request size is smaller than the "natural" size */
     if( opt.request_size != DFL_REQUEST_SIZE &&
         len > opt.request_size )
@@ -1114,31 +1119,80 @@
         memset( buf, 0, sizeof( buf ) );
         ret = ssl_read( &ssl, buf, len );
 
-        if( ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE )
+        if( ret == POLARSSL_ERR_NET_WANT_READ ||
+            ret == POLARSSL_ERR_NET_WANT_WRITE )
             continue;
 
-        if( ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY )
-            break;
+        if( ret <= 0 )
+        {
+            switch( ret )
+            {
+                case POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY:
+                    printf( " connection was closed gracefully\n" );
+                    ret = 0;
+                    goto close_notify;
+
+                case 0:
+                case POLARSSL_ERR_NET_CONN_RESET:
+                    printf( " connection was reset by peer\n" );
+                    ret = 0;
+                    goto reconnect;
+
+                default:
+                    printf( " ssl_read returned -0x%x\n", -ret );
+                    goto exit;
+            }
+        }
+
+        len = ret;
+        buf[len] = '\0';
+        printf( " %d bytes read\n\n%s", len, (char *) buf );
 
-        if( ret < 0 )
+        /* End of message should be detected according to the syntax of the
+         * application protocol (eg HTTP), just use a dummy test here. */
+        if( ret > 0 && buf[len-1] == '\n' )
         {
-            printf( "failed\n  ! ssl_read returned -0x%x\n\n", -ret );
+            ret = 0;
             break;
         }
+    }
+    while( 1 );
 
-        if( ret == 0 )
+    /*
+     * 7b. Continue doing data exchanges?
+     */
+    if( --opt.exchanges > 0 )
+        goto send_request;
+
+    /*
+     * 8. Done, cleanly close the connection
+     */
+close_notify:
+    printf( "  . Closing the connection..." );
+
+    while( ( ret = ssl_close_notify( &ssl ) ) < 0 )
+    {
+        if( ret == POLARSSL_ERR_NET_CONN_RESET )
         {
-            printf("\n\nEOF\n\n");
-            ssl_close_notify( &ssl );
-            break;
+            printf( " ok (already closed by peer)\n" );
+            ret = 0;
+            goto reconnect;
         }
 
-        len = ret;
-        buf[len] = '\0';
-        printf( " %d bytes read\n\n%s", len, (char *) buf );
+        if( ret != POLARSSL_ERR_NET_WANT_READ &&
+            ret != POLARSSL_ERR_NET_WANT_WRITE )
+        {
+            printf( " failed\n  ! ssl_close_notify returned %d\n\n", ret );
+            goto reconnect;
+        }
     }
-    while( 1 );
 
+    printf( " ok\n" );
+
+    /*
+     * 9. Reconnect?
+     */
+reconnect:
     if( opt.reconnect != 0 )
     {
         --opt.reconnect;
@@ -1187,10 +1241,10 @@
         goto send_request;
     }
 
+    /*
+     * Cleanup and exit
+     */
 exit:
-    if( ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY )
-        ret = 0;
-
 #ifdef POLARSSL_ERROR_C
     if( ret != 0 )
     {
@@ -1202,6 +1256,7 @@
 
     if( server_fd )
         net_close( server_fd );
+
 #if defined(POLARSSL_X509_CRT_PARSE_C)
     x509_crt_free( &clicert );
     x509_crt_free( &cacert );
@@ -1212,8 +1267,6 @@
     ctr_drbg_free( &ctr_drbg );
     entropy_free( &entropy );
 
-    memset( &ssl, 0, sizeof( ssl ) );
-
 #if defined(_WIN32)
     printf( "  + Press Enter to exit this program.\n" );
     fflush( stdout ); getchar();
diff -ruN polarssl-1.3.8/programs/ssl/ssl_mail_client.c polarssl-1.3.9/programs/ssl/ssl_mail_client.c
--- polarssl-1.3.8/programs/ssl/ssl_mail_client.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/ssl/ssl_mail_client.c	2014-10-20 13:59:19.000000000 +0200
@@ -375,6 +375,7 @@
      */
     server_fd = 0;
     memset( &ssl, 0, sizeof( ssl_context ) );
+    memset( &buf, 0, sizeof( buf ) );
     x509_crt_init( &cacert );
     x509_crt_init( &clicert );
     pk_init( &pkey );
@@ -718,8 +719,13 @@
         fflush( stdout );
 
         n = sizeof( buf );
-        len = base64_encode( base, &n, (const unsigned char *) opt.user_name,
+        ret = base64_encode( base, &n, (const unsigned char *) opt.user_name,
                              strlen( opt.user_name ) );
+
+        if( ret != 0 ) {
+            printf( " failed\n  ! base64_encode returned %d\n\n", ret );
+            goto exit;
+        }
         len = sprintf( (char *) buf, "%s\r\n", base );
         ret = write_ssl_and_get_response( &ssl, buf, len );
         if( ret < 300 || ret > 399 )
@@ -733,8 +739,13 @@
         printf( "  > Write password to server: %s", opt.user_pwd );
         fflush( stdout );
 
-        len = base64_encode( base, &n, (const unsigned char *) opt.user_pwd,
+        ret = base64_encode( base, &n, (const unsigned char *) opt.user_pwd,
                              strlen( opt.user_pwd ) );
+
+        if( ret != 0 ) {
+            printf( " failed\n  ! base64_encode returned %d\n\n", ret );
+            goto exit;
+        }
         len = sprintf( (char *) buf, "%s\r\n", base );
         ret = write_ssl_and_get_response( &ssl, buf, len );
         if( ret < 200 || ret > 399 )
diff -ruN polarssl-1.3.8/programs/ssl/ssl_pthread_server.c polarssl-1.3.9/programs/ssl/ssl_pthread_server.c
--- polarssl-1.3.8/programs/ssl/ssl_pthread_server.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/ssl/ssl_pthread_server.c	2014-10-20 13:59:19.000000000 +0200
@@ -129,6 +129,10 @@
     ssl_context ssl;
     ctr_drbg_context ctr_drbg;
 
+    /* Make sure memory references are valid */
+    memset( &ssl, 0, sizeof( ssl_context ) );
+    memset( &ctr_drbg, 0, sizeof( ctr_drbg_context ) );
+
     snprintf( pers, sizeof(pers), "SSL Pthread Thread %d", thread_id );
     printf( "  [ #%d ]  Client FD %d\n", thread_id, client_fd );
     printf( "  [ #%d ]  Seeding the random number generator...\n", thread_id );
@@ -176,7 +180,7 @@
     if( ( ret = ssl_set_own_cert( &ssl, thread_info->server_cert, thread_info->server_key ) ) != 0 )
     {
         printf( " failed\n  ! ssl_set_own_cert returned %d\n\n", ret );
-        goto exit;
+        goto thread_exit;
     }
 
     printf( "  [ #%d ]  ok\n", thread_id );
@@ -236,8 +240,6 @@
                             thread_id, -ret );
                     goto thread_exit;
             }
-
-            break;
         }
 
         len = ret;
@@ -308,6 +310,7 @@
 #endif
 
     net_close( client_fd );
+    ctr_drbg_free( &ctr_drbg );
     ssl_free( &ssl );
 
     thread_info->thread_complete = 1;
@@ -492,7 +495,6 @@
 #if defined(POLARSSL_SSL_CACHE_C)
     ssl_cache_free( &cache );
 #endif
-    ctr_drbg_free( &ctr_drbg );
     entropy_free( &entropy );
 
     polarssl_mutex_free( &debug_mutex );
diff -ruN polarssl-1.3.8/programs/ssl/ssl_server2.c polarssl-1.3.9/programs/ssl/ssl_server2.c
--- polarssl-1.3.8/programs/ssl/ssl_server2.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/ssl/ssl_server2.c	2014-10-20 13:59:19.000000000 +0200
@@ -64,6 +64,10 @@
 #include <stdlib.h>
 #include <stdio.h>
 
+#if !defined(_WIN32)
+#include <signal.h>
+#endif
+
 #include "polarssl/net.h"
 #include "polarssl/ssl.h"
 #include "polarssl/entropy.h"
@@ -100,6 +104,7 @@
 #define DFL_ALLOW_LEGACY        SSL_LEGACY_NO_RENEGOTIATION
 #define DFL_RENEGOTIATE         0
 #define DFL_RENEGO_DELAY        -2
+#define DFL_EXCHANGES           1
 #define DFL_MIN_VERSION         -1
 #define DFL_MAX_VERSION         -1
 #define DFL_AUTH_MODE           SSL_VERIFY_OPTIONAL
@@ -159,6 +164,7 @@
     int allow_legacy;           /* allow legacy renegotiation               */
     int renegotiate;            /* attempt renegotiation?                   */
     int renego_delay;           /* delay before enforcing renegotiation     */
+    int exchanges;              /* number of data exchanges                 */
     int min_version;            /* minimum protocol version accepted        */
     int max_version;            /* maximum protocol version accepted        */
     int auth_mode;              /* verify mode for connection               */
@@ -312,6 +318,8 @@
     "    renegotiation=%%d    default: 1 (enabled)\n"       \
     "    allow_legacy=%%d     default: 0 (disabled)\n"      \
     "    renegotiate=%%d      default: 0 (disabled)\n"      \
+    "    renego_delay=%%d     default: -2 (library default)\n" \
+    "    exchanges=%%d        default: 1\n"                 \
     USAGE_TICKETS                                           \
     USAGE_CACHE                                             \
     USAGE_MAX_FRAG_LEN                                      \
@@ -564,10 +572,22 @@
 }
 #endif /* POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED */
 
+static int listen_fd;
+
+/* Interruption handler to ensure clean exit (for valgrind testing) */
+#if !defined(_WIN32)
+static int received_sigterm = 0;
+void term_handler( int sig )
+{
+    ((void) sig);
+    received_sigterm = 1;
+    net_close( listen_fd ); /* causes net_accept() to abort */
+}
+#endif
+
 int main( int argc, char *argv[] )
 {
-    int ret = 0, len, written, frags;
-    int listen_fd;
+    int ret = 0, len, written, frags, exchanges;
     int client_fd = -1;
     int version_suites[4][2];
     unsigned char buf[IO_BUF_LEN];
@@ -635,6 +655,11 @@
     memset( (void *) alpn_list, 0, sizeof( alpn_list ) );
 #endif
 
+#if !defined(_WIN32)
+    /* Abort cleanly on SIGTERM */
+    signal( SIGTERM, term_handler );
+#endif
+
     if( argc == 0 )
     {
     usage:
@@ -676,6 +701,7 @@
     opt.allow_legacy        = DFL_ALLOW_LEGACY;
     opt.renegotiate         = DFL_RENEGOTIATE;
     opt.renego_delay        = DFL_RENEGO_DELAY;
+    opt.exchanges           = DFL_EXCHANGES;
     opt.min_version         = DFL_MIN_VERSION;
     opt.max_version         = DFL_MAX_VERSION;
     opt.auth_mode           = DFL_AUTH_MODE;
@@ -769,6 +795,12 @@
         {
             opt.renego_delay = atoi( q );
         }
+        else if( strcmp( p, "exchanges" ) == 0 )
+        {
+            opt.exchanges = atoi( q );
+            if( opt.exchanges < 1 )
+                goto usage;
+        }
         else if( strcmp( p, "min_version" ) == 0 )
         {
             if( strcmp( q, "ssl3" ) == 0 )
@@ -1377,6 +1409,15 @@
 
     if( ( ret = net_accept( listen_fd, &client_fd, NULL ) ) != 0 )
     {
+#if !defined(_WIN32)
+        if( received_sigterm )
+        {
+            printf( " interrupted by SIGTERM\n" );
+            ret = 0;
+            goto exit;
+        }
+#endif
+
         printf( " failed\n  ! net_accept returned -0x%x\n\n", -ret );
         goto exit;
     }
@@ -1461,6 +1502,8 @@
     }
 #endif /* POLARSSL_X509_CRT_PARSE_C */
 
+    exchanges = opt.exchanges;
+data_exchange:
     /*
      * 6. Read the HTTP Request
      */
@@ -1469,11 +1512,13 @@
 
     do
     {
+        int terminated = 0;
         len = sizeof( buf ) - 1;
         memset( buf, 0, sizeof( buf ) );
         ret = ssl_read( &ssl, buf, len );
 
-        if( ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE )
+        if( ret == POLARSSL_ERR_NET_WANT_READ ||
+            ret == POLARSSL_ERR_NET_WANT_WRITE )
             continue;
 
         if( ret <= 0 )
@@ -1482,18 +1527,18 @@
             {
                 case POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY:
                     printf( " connection was closed gracefully\n" );
-                    break;
+                    goto close_notify;
 
+                case 0:
                 case POLARSSL_ERR_NET_CONN_RESET:
                     printf( " connection was reset by peer\n" );
-                    break;
+                    ret = POLARSSL_ERR_NET_CONN_RESET;
+                    goto reset;
 
                 default:
                     printf( " ssl_read returned -0x%x\n", -ret );
-                    break;
+                    goto reset;
             }
-
-            break;
         }
 
         if( ssl_get_bytes_avail( &ssl ) == 0 )
@@ -1501,6 +1546,11 @@
             len = ret;
             buf[len] = '\0';
             printf( " %d bytes read\n\n%s\n", len, (char *) buf );
+
+            /* End of message should be detected according to the syntax of the
+             * application protocol (eg HTTP), just use a dummy test here. */
+            if( buf[len - 1] == '\n' )
+                terminated = 1;
         }
         else
         {
@@ -1515,7 +1565,7 @@
             {
                 printf( "  ! memory allocation failed\n" );
                 ret = 1;
-                goto exit;
+                goto reset;
             }
 
             memset( larger_buf, 0, ori_len + extra_len );
@@ -1528,7 +1578,7 @@
             {
                 printf( "  ! ssl_read failed on cached data\n" );
                 ret = 1;
-                goto exit;
+                goto reset;
             }
 
             larger_buf[ori_len + extra_len] = '\0';
@@ -1536,22 +1586,45 @@
                     ori_len + extra_len, ori_len, extra_len,
                     (char *) larger_buf );
 
+            /* End of message should be detected according to the syntax of the
+             * application protocol (eg HTTP), just use a dummy test here. */
+            if( larger_buf[ori_len + extra_len - 1] == '\n' )
+                terminated = 1;
+
             polarssl_free( larger_buf );
         }
 
-
-        if( memcmp( buf, "SERVERQUIT", 10 ) == 0 )
+        if( terminated )
         {
             ret = 0;
-            goto exit;
-        }
-
-        if( ret > 0 )
             break;
+        }
     }
     while( 1 );
 
     /*
+     * 7a. Request renegotiation while client is waiting for input from us.
+     * (only if we're going to exhange more data afterwards)
+     */
+    if( opt.renegotiate && exchanges > 1 )
+    {
+        printf( "  . Requestion renegotiation..." );
+        fflush( stdout );
+
+        while( ( ret = ssl_renegotiate( &ssl ) ) != 0 )
+        {
+            if( ret != POLARSSL_ERR_NET_WANT_READ &&
+                ret != POLARSSL_ERR_NET_WANT_WRITE )
+            {
+                printf( " failed\n  ! ssl_renegotiate returned %d\n\n", ret );
+                goto reset;
+            }
+        }
+
+        printf( " ok\n" );
+    }
+
+    /*
      * 7. Write the 200 Response
      */
     printf( "  > Write to client:" );
@@ -1573,7 +1646,7 @@
             if( ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE )
             {
                 printf( " failed\n  ! ssl_write returned %d\n\n", ret );
-                goto exit;
+                goto reset;
             }
         }
     }
@@ -1581,53 +1654,28 @@
     buf[written] = '\0';
     printf( " %d bytes written in %d fragments\n\n%s\n", written, frags, (char *) buf );
 
-    if( opt.renegotiate )
-    {
-        /*
-         * Request renegotiation (this must be done when the client is still
-         * waiting for input from our side).
-         */
-        printf( "  . Requestion renegotiation..." );
-        fflush( stdout );
-        while( ( ret = ssl_renegotiate( &ssl ) ) != 0 )
-        {
-            if( ret != POLARSSL_ERR_NET_WANT_READ &&
-                ret != POLARSSL_ERR_NET_WANT_WRITE )
-            {
-                printf( " failed\n  ! ssl_renegotiate returned %d\n\n", ret );
-                goto exit;
-            }
-        }
 
-        /*
-         * Should be a while loop, not an if, but here we're not actually
-         * expecting data from the client, and since we're running tests
-         * locally, we can just hope the handshake will finish the during the
-         * first call.
-         */
-        if( ( ret = ssl_read( &ssl, buf, 0 ) ) != 0 )
-        {
-            if( ret != POLARSSL_ERR_NET_WANT_READ &&
-                ret != POLARSSL_ERR_NET_WANT_WRITE )
-            {
-                printf( " failed\n  ! ssl_read returned %d\n\n", ret );
-
-                /* Unexpected message probably means client didn't renegotiate
-                 * as requested */
-                if( ret == POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE )
-                    goto reset;
-                else
-                    goto exit;
-            }
-        }
-
-        printf( " ok\n" );
-    }
+    /*
+     * 7b. Continue doing data exchanges?
+     */
+    if( --exchanges > 0 )
+        goto data_exchange;
 
+    /*
+     * 8. Done, cleanly close the connection
+     */
+close_notify:
     printf( "  . Closing the connection..." );
 
     while( ( ret = ssl_close_notify( &ssl ) ) < 0 )
     {
+        if( ret == POLARSSL_ERR_NET_CONN_RESET )
+        {
+            printf( " ok (already closed by peer)\n" );
+            ret = 0;
+            goto reset;
+        }
+
         if( ret != POLARSSL_ERR_NET_WANT_READ &&
             ret != POLARSSL_ERR_NET_WANT_WRITE )
         {
@@ -1637,12 +1685,12 @@
     }
 
     printf( " ok\n" );
-
-    ret = 0;
     goto reset;
 
+    /*
+     * Cleanup and exit
+     */
 exit:
-
 #ifdef POLARSSL_ERROR_C
     if( ret != 0 )
     {
diff -ruN polarssl-1.3.8/programs/test/ssl_test.c polarssl-1.3.9/programs/test/ssl_test.c
--- polarssl-1.3.8/programs/test/ssl_test.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/test/ssl_test.c	2014-10-20 13:59:19.000000000 +0200
@@ -142,7 +142,7 @@
  */
 static int ssl_test( struct options *opt )
 {
-    int ret, i;
+    int ret = 1, i;
     int client_fd = -1;
     int bytes_to_read;
     int bytes_to_write;
@@ -169,8 +169,6 @@
     x509_crt srvcert;
     pk_context pkey;
 
-    ret = 1;
-
     memset( &ssl, 0, sizeof(ssl_context) );
     entropy_init( &entropy );
     x509_crt_init( &srvcert );
diff -ruN polarssl-1.3.8/programs/util/pem2der.c polarssl-1.3.9/programs/util/pem2der.c
--- polarssl-1.3.8/programs/util/pem2der.c	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/programs/util/pem2der.c	2014-10-20 13:59:19.000000000 +0200
@@ -134,6 +134,7 @@
     {
         fclose( f );
         free( *buf );
+        *buf = NULL;
         return( -1 );
     }
 
diff -ruN polarssl-1.3.8/scripts/config.pl polarssl-1.3.9/scripts/config.pl
--- polarssl-1.3.8/scripts/config.pl	1970-01-01 01:00:00.000000000 +0100
+++ polarssl-1.3.9/scripts/config.pl	2014-10-20 13:59:19.000000000 +0200
@@ -0,0 +1,112 @@
+#!/usr/bin/perl
+
+# Tune the configuration file
+
+use warnings;
+use strict;
+
+my $usage = <<EOU;
+$0 [-f <file>] full
+$0 [-f <file>] unset <name>
+$0 [-f <file>] set <name> [<value>]
+EOU
+
+# Things that shouldn't be enabled with "full".
+# Notes:
+# - POLARSSL_X509_ALLOW_EXTENSIONS_NON_V3 and
+#   POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION could be enabled if the
+#   respective tests were adapted
+my @excluded = qw(
+POLARSSL_HAVE_INT8
+POLARSSL_HAVE_INT16
+POLARSSL_HAVE_SSE2
+POLARSSL_PLATFORM_NO_STD_FUNCTIONS
+POLARSSL_ECP_DP_M221_ENABLED
+POLARSSL_ECP_DP_M383_ENABLED
+POLARSSL_ECP_DP_M511_ENABLED
+POLARSSL_NO_DEFAULT_ENTROPY_SOURCES
+POLARSSL_NO_PLATFORM_ENTROPY
+POLARSSL_SSL_HW_RECORD_ACCEL
+POLARSSL_X509_ALLOW_EXTENSIONS_NON_V3
+POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION
+POLARSSL_ZLIB_SUPPORT
+POLARSSL_PKCS11_C
+_ALT\s*$
+);
+
+my $config_file = "include/polarssl/config.h";
+
+# get -f option
+if (@ARGV >= 2 && $ARGV[0] eq "-f") {
+    shift; # -f
+    $config_file = shift;
+
+    -f $config_file or die "No such file: $config_file\n";
+} else {
+    if (! -f $config_file)  {
+        chdir '..' or die;
+        -d $config_file
+            or die "Without -f, must be run from root or scripts\n"
+    }
+}
+
+# get action
+die $usage unless @ARGV;
+my $action = shift;
+
+my ($name, $value);
+if ($action eq "full") {
+    # nothing to do
+} elsif ($action eq "unset") {
+    die $usage unless @ARGV;
+    $name = shift;
+} elsif ($action eq "set") {
+    die $usage unless @ARGV;
+    $name = shift;
+    $value = shift if @ARGV;
+} else {
+    die $usage;
+}
+die $usage if @ARGV;
+
+open my $config_read, '<', $config_file or die "read $config_file: $!\n";
+my @config_lines = <$config_read>;
+close $config_read;
+
+my $exclude_re = join '|', @excluded;
+
+open my $config_write, '>', $config_file or die "write $config_file: $!\n";
+
+my $done;
+for my $line (@config_lines) {
+    if ($action eq "full") {
+        if ($line =~ /name SECTION: Module configuration options/) {
+            $done = 1;
+        }
+
+        if (!$done && $line =~ m!^//\s?#define! && $line !~ /$exclude_re/) {
+            $line =~ s!^//!!;
+        }
+    } elsif ($action eq "unset") {
+        if (!$done && $line =~ /^\s*#define\s*$name/) {
+            $line = '//' . $line;
+            $done = 1;
+        }
+    } elsif (!$done && $action eq "set") {
+        if ($line =~ m!^(?://)?\s*#define\s*$name!) {
+            $line = "#define $name";
+            $line .= " $value" if defined $value && $value ne "";
+            $line .= "\n";
+            $done = 1;
+        }
+    }
+
+    print $config_write $line;
+}
+
+close $config_write;
+
+warn "configuration section not found" if ($action eq "full" && !$done);
+warn "$name not found" if ($action ne "full" && !$done);
+
+__END__
diff -ruN polarssl-1.3.8/tests/CMakeLists.txt polarssl-1.3.9/tests/CMakeLists.txt
diff -ruN polarssl-1.3.8/tests/compat.sh polarssl-1.3.9/tests/compat.sh
diff -ruN polarssl-1.3.8/tests/data_files/enco-ca-prstr.pem polarssl-1.3.9/tests/data_files/enco-ca-prstr.pem
diff -ruN polarssl-1.3.8/tests/data_files/enco-cert-utf8str.pem polarssl-1.3.9/tests/data_files/enco-cert-utf8str.pem
diff -ruN polarssl-1.3.8/tests/data_files/mpi_10 polarssl-1.3.9/tests/data_files/mpi_10
diff -ruN polarssl-1.3.8/tests/data_files/mpi_too_big polarssl-1.3.9/tests/data_files/mpi_too_big
diff -ruN polarssl-1.3.8/tests/data_files/rsa4096_prv.pem polarssl-1.3.9/tests/data_files/rsa4096_prv.pem
diff -ruN polarssl-1.3.8/tests/data_files/rsa4096_pub.pem polarssl-1.3.9/tests/data_files/rsa4096_pub.pem
diff -ruN polarssl-1.3.8/tests/data_files/server7_all_space.crt polarssl-1.3.9/tests/data_files/server7_all_space.crt
diff -ruN polarssl-1.3.8/tests/data_files/server7_pem_space.crt polarssl-1.3.9/tests/data_files/server7_pem_space.crt
diff -ruN polarssl-1.3.8/tests/scripts/all.sh polarssl-1.3.9/tests/scripts/all.sh
diff -ruN polarssl-1.3.8/tests/ssl-opt.sh polarssl-1.3.9/tests/ssl-opt.sh
diff -ruN polarssl-1.3.8/tests/suites/test_suite_base64.data polarssl-1.3.9/tests/suites/test_suite_base64.data
diff -ruN polarssl-1.3.8/tests/suites/test_suite_base64.function polarssl-1.3.9/tests/suites/test_suite_base64.function
diff -ruN polarssl-1.3.8/tests/suites/test_suite_pkwrite.data polarssl-1.3.9/tests/suites/test_suite_pkwrite.data
diff -ruN polarssl-1.3.8/tests/suites/test_suite_rsa.data polarssl-1.3.9/tests/suites/test_suite_rsa.data
diff -ruN polarssl-1.3.8/tests/suites/test_suite_version.data polarssl-1.3.9/tests/suites/test_suite_version.data
diff -ruN polarssl-1.3.8/tests/suites/test_suite_x509parse.data polarssl-1.3.9/tests/suites/test_suite_x509parse.data
diff -ruN polarssl-1.3.8/tests/suites/test_suite_x509parse.function polarssl-1.3.9/tests/suites/test_suite_x509parse.function
diff -ruN polarssl-1.3.8/tests/suites/test_suite_x509write.data polarssl-1.3.9/tests/suites/test_suite_x509write.data
diff -ruN polarssl-1.3.8/tests/suites/test_suite_x509write.function polarssl-1.3.9/tests/suites/test_suite_x509write.function
diff -ruN polarssl-1.3.8/.travis.yml polarssl-1.3.9/.travis.yml
--- polarssl-1.3.8/.travis.yml	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/.travis.yml	2014-10-20 13:59:19.000000000 +0200
@@ -3,7 +3,7 @@
 - clang
 - gcc
 before_install: sudo apt-get update
-install: sudo apt-get install bc gnutls-bin valgrind perl
+install: sudo apt-get install gnutls-bin valgrind perl
 script:
 - cmake -D CMAKE_BUILD_TYPE:String="Check" .
 - make
diff -ruN polarssl-1.3.8/visualc/VS2010/PolarSSL.vcxproj polarssl-1.3.9/visualc/VS2010/PolarSSL.vcxproj
--- polarssl-1.3.8/visualc/VS2010/PolarSSL.vcxproj	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/visualc/VS2010/PolarSSL.vcxproj	2014-10-20 13:59:19.000000000 +0200
@@ -256,7 +256,6 @@
     <ClCompile Include="..\..\library\pkwrite.c" />
     <ClCompile Include="..\..\library\platform.c" />
     <ClCompile Include="..\..\library\ripemd160.c" />
-    <ClCompile Include="..\..\library\rnd_test.c" />
     <ClCompile Include="..\..\library\rsa.c" />
     <ClCompile Include="..\..\library\sha1.c" />
     <ClCompile Include="..\..\library\sha256.c" />
diff -ruN polarssl-1.3.8/visualc/VS6/polarssl.dsp polarssl-1.3.9/visualc/VS6/polarssl.dsp
--- polarssl-1.3.8/visualc/VS6/polarssl.dsp	2014-07-11 11:28:56.000000000 +0200
+++ polarssl-1.3.9/visualc/VS6/polarssl.dsp	2014-10-20 13:59:19.000000000 +0200
@@ -273,10 +273,6 @@
 # End Source File
 # Begin Source File
 
-SOURCE=..\..\library\rnd_test.c
-# End Source File
-# Begin Source File
-
 SOURCE=..\..\library\rsa.c
 # End Source File
 # Begin Source File

--- End Message ---
--- Begin Message ---
On 2014-11-22 18:13, Thijs Kinkhorst wrote:
> Package: release.debian.org
> Severity: normal
> User: release.debian.org@packages.debian.org
> Usertags: unblock
> 
> This is an unblock request for polarssl/1.3.9-2. The unblock request was
> sent by the maintainer to the mailing list, I'm filing it here for proper
> processing.
> 
> Upstream maintenance release 1.3.9 fixes several security issues besides
> other bugfixes. Debian revision -2 disables SSLv3.
> 
> Attached is the full debdiff; but the majority of changes are in tests; if
> you exclude those with filterdiff -x '*/tests/*', you get attached
> filtered debdiff that boils down to
>  48 files changed, 861 insertions(+), 294 deletions(-)
> 
> 
> Cheers,
> Thijs
> 

Vastly larger than I liked, but unblocked, thanks.

~Niels

--- End Message ---

Reply to: