Fix possible client crash on API misuse
diff --git a/ChangeLog b/ChangeLog
index d3636f0..fdab585 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -6,6 +6,11 @@
    * Added support for yotta as a build system.
    * Primary open source license changed to Apache 2.0 license.
 
+Security
+   * Fix possible client-side NULL pointer dereference (read) when the client
+     tries to continue the handshake after it failed (a misuse of the API).
+     (Found by GDS Labs using afl-fuzz, patch provided by GDS Labs.)
+
 Bugfix
    * Fix segfault in the benchmark program when benchmarking DHM.
    * Fix build error with CMake and pre-4.5 versions of GCC (found by Hugo
diff --git a/library/ssl_cli.c b/library/ssl_cli.c
index 5a9c432..c82e2e7 100644
--- a/library/ssl_cli.c
+++ b/library/ssl_cli.c
@@ -1771,6 +1771,12 @@
 
     ssl->handshake->pmslen = 48;
 
+    if( ssl->session_negotiate->peer_cert == NULL )
+    {
+        MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
+        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
+    }
+
     /*
      * Now write it out, encrypted
      */
@@ -1873,6 +1879,12 @@
     int ret;
     const mbedtls_ecp_keypair *peer_key;
 
+    if( ssl->session_negotiate->peer_cert == NULL )
+    {
+        MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
+        return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
+    }
+
     if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
                      MBEDTLS_PK_ECKEY ) )
     {
@@ -2182,6 +2194,12 @@
         MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
             (unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
 
+        if( ssl->session_negotiate->peer_cert == NULL )
+        {
+            MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
+            return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
+        }
+
         /*
          * Verify signature
          */