Merge fix for X.509 compatibility issues
diff --git a/ChangeLog b/ChangeLog
index 489c4bf..87768ff 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -31,6 +31,21 @@
      a contribution from Tobias Tangemann. #541
    * Fixed cert_app sample program for debug output and for use when no root
      certificates are provided.
+   * Fix conditional statement that would cause a 1 byte overread in
+     mbedtls_asn1_get_int(). Found and fixed by Guido Vranken. #599
+   * Fixed pthread implementation to avoid unintended double initialisations
+     and double frees. (found by Niklas Amnebratt)
+   * Fixed the sample applications gen_key.c, cert_req.c and cert_write.c for
+     builds where the configuration MBEDTLS_PEM_WRITE_C is not defined. Found
+     by inestlerode. #559.
+   * Fix mbedtls_x509_get_sig() to update the ASN1 type in the mbedtls_x509_buf
+     data structure until after error checks are successful. Found by
+     subramanyam-c. #622
+   * Fix documentation and implementation missmatch for function arguments of
+     mbedtls_gcm_finish(). Found by cmiatpaar. #602
+   * Guarantee that P>Q at RSA key generation. Found by inestlerode. #558
+   * Fix potential byte overread when verifying malformed SERVER_HELLO in
+     ssl_parse_hello_verify_request() for DTLS. Found by Guido Vranken.
 
 Changes
    * Extended test coverage of special cases, and added new timing test suite.
diff --git a/include/mbedtls/cmac.h b/include/mbedtls/cmac.h
index f64ae69..75e0b97 100644
--- a/include/mbedtls/cmac.h
+++ b/include/mbedtls/cmac.h
@@ -44,7 +44,6 @@
  */
 struct mbedtls_cmac_context_t
 {
-
     /** Internal state of the CMAC algorithm  */
     unsigned char       state[MBEDTLS_CIPHER_BLKSIZE_MAX];
 
@@ -54,9 +53,6 @@
 
     /** Length of data pending to be processed */
     size_t              unprocessed_len;
-
-    /** Flag to indicate if the last block needs padding */
-    int                 padding_flag;
 };
 
 /**
diff --git a/include/mbedtls/gcm.h b/include/mbedtls/gcm.h
index 6743ac9..1b77aae 100644
--- a/include/mbedtls/gcm.h
+++ b/include/mbedtls/gcm.h
@@ -190,8 +190,8 @@
  *                  16 bytes.
  *
  * \param ctx       GCM context
- * \param tag       buffer for holding the tag (may be NULL if tag_len is 0)
- * \param tag_len   length of the tag to generate
+ * \param tag       buffer for holding the tag
+ * \param tag_len   length of the tag to generate (must be at least 4)
  *
  * \return          0 if successful or MBEDTLS_ERR_GCM_BAD_INPUT
  */
diff --git a/include/mbedtls/x509_csr.h b/include/mbedtls/x509_csr.h
index 7a9c2e0..fe9843c 100644
--- a/include/mbedtls/x509_csr.h
+++ b/include/mbedtls/x509_csr.h
@@ -282,7 +282,7 @@
  *
  * \note            f_rng may be NULL if RSA is used for signature and the
  *                  signature is made offline (otherwise f_rng is desirable
- *                  for couermeasures against timing attacks).
+ *                  for countermeasures against timing attacks).
  *                  ECDSA signatures always require a non-NULL f_rng.
  */
 int mbedtls_x509write_csr_pem( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size,
diff --git a/library/asn1parse.c b/library/asn1parse.c
index ffa2f52..4dd65c0 100644
--- a/library/asn1parse.c
+++ b/library/asn1parse.c
@@ -153,7 +153,7 @@
     if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )
         return( ret );
 
-    if( len > sizeof( int ) || ( **p & 0x80 ) != 0 )
+    if( len == 0 || len > sizeof( int ) || ( **p & 0x80 ) != 0 )
         return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
 
     *val = 0;
diff --git a/library/cmac.c b/library/cmac.c
index 03d9392..ee2fe05 100644
--- a/library/cmac.c
+++ b/library/cmac.c
@@ -235,7 +235,6 @@
     ctx->cmac_ctx = cmac_ctx;
 
     mbedtls_zeroize( cmac_ctx->state, sizeof( cmac_ctx->state ) );
-    cmac_ctx->padding_flag = 1;
 
     return 0;
 }
@@ -256,8 +255,8 @@
     block_size = ctx->cipher_info->block_size;
     state = ctx->cmac_ctx->state;
 
-    /* Is their data still to process from the last call, that's equal to
-     * or greater than a block? */
+    /* Is there data still to process from the last call, that's greater in
+     * size than a block? */
     if( cmac_ctx->unprocessed_len > 0 &&
         ilen > block_size - cmac_ctx->unprocessed_len )
     {
@@ -273,9 +272,8 @@
            goto exit;
         }
 
-        ilen -= block_size;
-        input += cmac_ctx->unprocessed_len;
-
+        input += block_size - cmac_ctx->unprocessed_len;
+        ilen -= block_size - cmac_ctx->unprocessed_len;
         cmac_ctx->unprocessed_len = 0;
     }
 
@@ -293,20 +291,15 @@
 
         ilen -= block_size;
         input += block_size;
-
-        cmac_ctx->padding_flag = 0;
     }
 
     /* If there is data left over that wasn't aligned to a block */
     if( ilen > 0 )
     {
-        memcpy( &cmac_ctx->unprocessed_block, input, ilen );
-        cmac_ctx->unprocessed_len = ilen;
-
-        if( ilen % block_size > 0 )
-            cmac_ctx->padding_flag = 1;
-        else
-            cmac_ctx->padding_flag = 0;
+        memcpy( &cmac_ctx->unprocessed_block[cmac_ctx->unprocessed_len],
+                input,
+                ilen );
+        cmac_ctx->unprocessed_len += ilen;
     }
 
 exit:
@@ -339,7 +332,7 @@
     last_block = cmac_ctx->unprocessed_block;
 
     /* Calculate last block */
-    if( cmac_ctx->padding_flag )
+    if( cmac_ctx->unprocessed_len < block_size )
     {
         cmac_pad( M_last, block_size, last_block, cmac_ctx->unprocessed_len );
         cmac_xor_block( M_last, M_last, K2, block_size );
@@ -366,7 +359,6 @@
     mbedtls_zeroize( K1, sizeof( K1 ) );
     mbedtls_zeroize( K2, sizeof( K2 ) );
 
-    cmac_ctx->padding_flag = 1;
     cmac_ctx->unprocessed_len = 0;
     mbedtls_zeroize( cmac_ctx->unprocessed_block,
                      sizeof( cmac_ctx->unprocessed_block ) );
@@ -390,7 +382,6 @@
                      sizeof( cmac_ctx->unprocessed_block ) );
     mbedtls_zeroize( cmac_ctx->state,
                      sizeof( cmac_ctx->state ) );
-    cmac_ctx->padding_flag = 1;
 
     return( 0 );
 }
@@ -746,19 +737,19 @@
         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
     }
 
-    mbedtls_cipher_init( &ctx );
-
     for( i = 0; i < num_tests; i++ )
     {
         if( verbose != 0 )
             mbedtls_printf( "  %s CMAC subkey #%u: ", testname, i + 1 );
 
+        mbedtls_cipher_init( &ctx );
+
         if( ( ret = mbedtls_cipher_setup( &ctx, cipher_info ) ) != 0 )
         {
             if( verbose != 0 )
                 mbedtls_printf( "test execution failed\n" );
 
-            goto exit;
+            goto cleanup;
         }
 
         if( ( ret = mbedtls_cipher_setkey( &ctx, key, keybits,
@@ -767,7 +758,7 @@
             if( verbose != 0 )
                 mbedtls_printf( "test execution failed\n" );
 
-            goto exit;
+            goto cleanup;
         }
 
         ret = cmac_generate_subkeys( &ctx, K1, K2 );
@@ -775,24 +766,31 @@
         {
            if( verbose != 0 )
                 mbedtls_printf( "failed\n" );
-            goto exit;
+
+            goto cleanup;
         }
 
-        if( ( ret = memcmp( K1, subkeys, block_size ) != 0 ) ||
-            ( ret = memcmp( K2, &subkeys[block_size], block_size ) != 0 ) )
+        if( ( ret = memcmp( K1, subkeys, block_size ) ) != 0  ||
+            ( ret = memcmp( K2, &subkeys[block_size], block_size ) ) != 0 )
         {
             if( verbose != 0 )
                 mbedtls_printf( "failed\n" );
-            goto exit;
+
+            goto cleanup;
         }
 
         if( verbose != 0 )
             mbedtls_printf( "passed\n" );
+
+        mbedtls_cipher_free( &ctx );
     }
 
-exit:
+    goto exit;
+
+cleanup:
     mbedtls_cipher_free( &ctx );
 
+exit:
     return( ret );
 }
 
@@ -889,7 +887,7 @@
                                    (const unsigned char*)aes_128_subkeys,
                                    MBEDTLS_CIPHER_AES_128_ECB,
                                    MBEDTLS_AES_BLOCK_SIZE,
-                                   NB_CMAC_TESTS_PER_KEY ) != 0 ) )
+                                   NB_CMAC_TESTS_PER_KEY ) ) != 0 )
     {
         return( ret );
     }
@@ -903,7 +901,7 @@
                                       (const unsigned char*)aes_128_expected_result,
                                       MBEDTLS_CIPHER_AES_128_ECB,
                                       MBEDTLS_AES_BLOCK_SIZE,
-                                      NB_CMAC_TESTS_PER_KEY ) != 0 ) )
+                                      NB_CMAC_TESTS_PER_KEY ) ) != 0 )
     {
         return( ret );
     }
@@ -916,7 +914,7 @@
                                    (const unsigned char*)aes_192_subkeys,
                                    MBEDTLS_CIPHER_AES_192_ECB,
                                    MBEDTLS_AES_BLOCK_SIZE,
-                                   NB_CMAC_TESTS_PER_KEY ) != 0 ) )
+                                   NB_CMAC_TESTS_PER_KEY ) ) != 0 )
     {
         return( ret );
     }
@@ -930,7 +928,7 @@
                                       (const unsigned char*)aes_192_expected_result,
                                       MBEDTLS_CIPHER_AES_192_ECB,
                                       MBEDTLS_AES_BLOCK_SIZE,
-                                      NB_CMAC_TESTS_PER_KEY ) != 0 ) )
+                                      NB_CMAC_TESTS_PER_KEY ) ) != 0 )
     {
         return( ret );
     }
@@ -943,7 +941,7 @@
                                    (const unsigned char*)aes_256_subkeys,
                                    MBEDTLS_CIPHER_AES_256_ECB,
                                    MBEDTLS_AES_BLOCK_SIZE,
-                                   NB_CMAC_TESTS_PER_KEY ) != 0 ) )
+                                   NB_CMAC_TESTS_PER_KEY ) ) != 0 )
     {
         return( ret );
     }
@@ -957,7 +955,7 @@
                                        (const unsigned char*)aes_256_expected_result,
                                        MBEDTLS_CIPHER_AES_256_ECB,
                                        MBEDTLS_AES_BLOCK_SIZE,
-                                       NB_CMAC_TESTS_PER_KEY ) != 0 ) )
+                                       NB_CMAC_TESTS_PER_KEY ) ) != 0 )
     {
         return( ret );
     }
@@ -972,7 +970,7 @@
                                    (const unsigned char*)des3_2key_subkeys,
                                    MBEDTLS_CIPHER_DES_EDE3_ECB,
                                    MBEDTLS_DES3_BLOCK_SIZE,
-                                   NB_CMAC_TESTS_PER_KEY ) != 0 ) )
+                                   NB_CMAC_TESTS_PER_KEY ) ) != 0 )
     {
         return( ret );
     }
@@ -986,7 +984,7 @@
                                       (const unsigned char*)des3_2key_expected_result,
                                       MBEDTLS_CIPHER_DES_EDE3_ECB,
                                       MBEDTLS_DES3_BLOCK_SIZE,
-                                      NB_CMAC_TESTS_PER_KEY ) != 0 ) )
+                                      NB_CMAC_TESTS_PER_KEY ) ) != 0 )
     {
         return( ret );
     }
@@ -999,7 +997,7 @@
                                    (const unsigned char*)des3_3key_subkeys,
                                    MBEDTLS_CIPHER_DES_EDE3_ECB,
                                    MBEDTLS_DES3_BLOCK_SIZE,
-                                   NB_CMAC_TESTS_PER_KEY ) != 0 ) )
+                                   NB_CMAC_TESTS_PER_KEY ) ) != 0 )
     {
         return( ret );
     }
@@ -1013,14 +1011,14 @@
                                       (const unsigned char*)des3_3key_expected_result,
                                       MBEDTLS_CIPHER_DES_EDE3_ECB,
                                       MBEDTLS_DES3_BLOCK_SIZE,
-                                      NB_CMAC_TESTS_PER_KEY ) != 0 ) )
+                                      NB_CMAC_TESTS_PER_KEY ) ) != 0 )
     {
         return( ret );
     }
 #endif /* MBEDTLS_DES_C */
 
 #if defined(MBEDTLS_AES_C)
-    if( ( ret = test_aes128_cmac_prf( verbose ) != 0 ) )
+    if( ( ret = test_aes128_cmac_prf( verbose ) ) != 0 )
         return( ret );
 #endif /* MBEDTLS_AES_C */
 
diff --git a/library/gcm.c b/library/gcm.c
index aaacf97..f1210c5 100644
--- a/library/gcm.c
+++ b/library/gcm.c
@@ -415,8 +415,7 @@
     if( tag_len > 16 || tag_len < 4 )
         return( MBEDTLS_ERR_GCM_BAD_INPUT );
 
-    if( tag_len != 0 )
-        memcpy( tag, ctx->base_ectr, tag_len );
+    memcpy( tag, ctx->base_ectr, tag_len );
 
     if( orig_len || orig_add_len )
     {
diff --git a/library/rsa.c b/library/rsa.c
index 7a33689..40ef2a9 100644
--- a/library/rsa.c
+++ b/library/rsa.c
@@ -102,7 +102,10 @@
     if( f_rng == NULL || nbits < 128 || exponent < 3 )
         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
 
-    mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 ); 
+    if( nbits % 2 )
+        return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
+
+    mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 );
     mbedtls_mpi_init( &H ); mbedtls_mpi_init( &G );
 
     /*
@@ -116,16 +119,8 @@
         MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, nbits >> 1, 0,
                                 f_rng, p_rng ) );
 
-        if( nbits % 2 )
-        {
-            MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, ( nbits >> 1 ) + 1, 0,
+        MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1, 0,
                                 f_rng, p_rng ) );
-        }
-        else
-        {
-            MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1, 0,
-                                f_rng, p_rng ) );
-        }
 
         if( mbedtls_mpi_cmp_mpi( &ctx->P, &ctx->Q ) == 0 )
             continue;
@@ -134,6 +129,9 @@
         if( mbedtls_mpi_bitlen( &ctx->N ) != nbits )
             continue;
 
+        if( mbedtls_mpi_cmp_mpi( &ctx->P, &ctx->Q ) < 0 )
+                                mbedtls_mpi_swap( &ctx->P, &ctx->Q );
+
         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1, &ctx->P, 1 ) );
         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1, &ctx->Q, 1 ) );
         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &H, &P1, &Q1 ) );
diff --git a/library/sha256.c b/library/sha256.c
index 4e82c0b..ad25d38 100644
--- a/library/sha256.c
+++ b/library/sha256.c
@@ -41,7 +41,10 @@
 #include "mbedtls/platform.h"
 #else
 #include <stdio.h>
+#include <stdlib.h>
 #define mbedtls_printf printf
+#define mbedtls_calloc    calloc
+#define mbedtls_free       free
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_SELF_TEST */
 
@@ -389,10 +392,19 @@
 int mbedtls_sha256_self_test( int verbose )
 {
     int i, j, k, buflen, ret = 0;
-    unsigned char buf[1024];
+    unsigned char *buf;
     unsigned char sha256sum[32];
     mbedtls_sha256_context ctx;
 
+    buf = mbedtls_calloc( 1024, sizeof(unsigned char) );
+    if( NULL == buf )
+    {
+        if( verbose != 0 )
+            mbedtls_printf( "Buffer allocation failed\n" );
+
+        return( 1 );
+    }
+
     mbedtls_sha256_init( &ctx );
 
     for( i = 0; i < 6; i++ )
@@ -436,6 +448,7 @@
 
 exit:
     mbedtls_sha256_free( &ctx );
+    mbedtls_free( buf );
 
     return( ret );
 }
diff --git a/library/sha512.c b/library/sha512.c
index 0f9e1e5..724522a 100644
--- a/library/sha512.c
+++ b/library/sha512.c
@@ -47,7 +47,10 @@
 #include "mbedtls/platform.h"
 #else
 #include <stdio.h>
+#include <stdlib.h>
 #define mbedtls_printf printf
+#define mbedtls_calloc    calloc
+#define mbedtls_free       free
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_SELF_TEST */
 
@@ -445,10 +448,19 @@
 int mbedtls_sha512_self_test( int verbose )
 {
     int i, j, k, buflen, ret = 0;
-    unsigned char buf[1024];
+    unsigned char *buf;
     unsigned char sha512sum[64];
     mbedtls_sha512_context ctx;
 
+    buf = mbedtls_calloc( 1024, sizeof(unsigned char) );
+    if( NULL == buf )
+    {
+        if( verbose != 0 )
+            mbedtls_printf( "Buffer allocation failed\n" );
+
+        return( 1 );
+    }
+
     mbedtls_sha512_init( &ctx );
 
     for( i = 0; i < 6; i++ )
@@ -492,6 +504,7 @@
 
 exit:
     mbedtls_sha512_free( &ctx );
+    mbedtls_free( buf );
 
     return( ret );
 }
diff --git a/library/ssl_cli.c b/library/ssl_cli.c
index 29a3943..39fcd6c 100644
--- a/library/ssl_cli.c
+++ b/library/ssl_cli.c
@@ -1355,6 +1355,15 @@
     cookie_len = *p++;
     MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len );
 
+    if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len )
+    {
+        MBEDTLS_SSL_DEBUG_MSG( 1,
+            ( "cookie length does not match incoming message size" ) );
+        mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
+                                    MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
+        return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
+    }
+
     mbedtls_free( ssl->handshake->verify_cookie );
 
     ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len );
diff --git a/library/threading.c b/library/threading.c
index 1b6d9cd..83ec01a 100644
--- a/library/threading.c
+++ b/library/threading.c
@@ -32,7 +32,7 @@
 #if defined(MBEDTLS_THREADING_PTHREAD)
 static void threading_mutex_init_pthread( mbedtls_threading_mutex_t *mutex )
 {
-    if( mutex == NULL )
+    if( mutex == NULL || mutex->is_valid )
         return;
 
     mutex->is_valid = pthread_mutex_init( &mutex->mutex, NULL ) == 0;
@@ -40,10 +40,11 @@
 
 static void threading_mutex_free_pthread( mbedtls_threading_mutex_t *mutex )
 {
-    if( mutex == NULL )
+    if( mutex == NULL || !mutex->is_valid )
         return;
 
     (void) pthread_mutex_destroy( &mutex->mutex );
+    mutex->is_valid = 0;
 }
 
 static int threading_mutex_lock_pthread( mbedtls_threading_mutex_t *mutex )
diff --git a/library/x509.c b/library/x509.c
index bc3bfe0..6df5dc8 100644
--- a/library/x509.c
+++ b/library/x509.c
@@ -559,16 +559,18 @@
 {
     int ret;
     size_t len;
+    int tag_type;
 
     if( ( end - *p ) < 1 )
         return( MBEDTLS_ERR_X509_INVALID_SIGNATURE +
                 MBEDTLS_ERR_ASN1_OUT_OF_DATA );
 
-    sig->tag = **p;
+    tag_type = **p;
 
     if( ( ret = mbedtls_asn1_get_bitstring_null( p, end, &len ) ) != 0 )
         return( MBEDTLS_ERR_X509_INVALID_SIGNATURE + ret );
 
+    sig->tag = tag_type;
     sig->len = len;
     sig->p = *p;
 
diff --git a/programs/x509/cert_req.c b/programs/x509/cert_req.c
index 5cafb80..30df216 100644
--- a/programs/x509/cert_req.c
+++ b/programs/x509/cert_req.c
@@ -34,7 +34,8 @@
 
 #if !defined(MBEDTLS_X509_CSR_WRITE_C) || !defined(MBEDTLS_FS_IO) ||  \
     !defined(MBEDTLS_PK_PARSE_C) || !defined(MBEDTLS_SHA256_C) || \
-    !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C)
+    !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) || \
+    !defined(MBEDTLS_PEM_WRITE_C)
 int main( void )
 {
     mbedtls_printf( "MBEDTLS_X509_CSR_WRITE_C and/or MBEDTLS_FS_IO and/or "
@@ -341,4 +342,4 @@
     return( ret );
 }
 #endif /* MBEDTLS_X509_CSR_WRITE_C && MBEDTLS_PK_PARSE_C && MBEDTLS_FS_IO &&
-          MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C */
+          MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C && MBEDTLS_PEM_WRITE_C */
diff --git a/programs/x509/cert_write.c b/programs/x509/cert_write.c
index 7907d82..66e5f1d 100644
--- a/programs/x509/cert_write.c
+++ b/programs/x509/cert_write.c
@@ -32,10 +32,11 @@
 #define mbedtls_printf     printf
 #endif
 
-#if !defined(MBEDTLS_X509_CRT_WRITE_C) ||                                  \
-    !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_FS_IO) ||      \
-    !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) ||        \
-    !defined(MBEDTLS_ERROR_C) || !defined(MBEDTLS_SHA256_C)
+#if !defined(MBEDTLS_X509_CRT_WRITE_C) || \
+    !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_FS_IO) || \
+    !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) || \
+    !defined(MBEDTLS_ERROR_C) || !defined(MBEDTLS_SHA256_C) || \
+    !defined(MBEDTLS_PEM_WRITE_C)
 int main( void )
 {
     mbedtls_printf( "MBEDTLS_X509_CRT_WRITE_C and/or MBEDTLS_X509_CRT_PARSE_C and/or "
@@ -664,4 +665,4 @@
 }
 #endif /* MBEDTLS_X509_CRT_WRITE_C && MBEDTLS_X509_CRT_PARSE_C &&
           MBEDTLS_FS_IO && MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C &&
-          MBEDTLS_ERROR_C */
+          MBEDTLS_ERROR_C && MBEDTLS_PEM_WRITE_C */
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 13659de..21583c4 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -61,6 +61,7 @@
 add_test_suite(cipher cipher.gcm)
 add_test_suite(cipher cipher.null)
 add_test_suite(cipher cipher.padding)
+add_test_suite(cmac)
 add_test_suite(ctr_drbg)
 add_test_suite(debug)
 add_test_suite(des)
diff --git a/tests/scripts/all.sh b/tests/scripts/all.sh
index ee0df0c..6b33960 100755
--- a/tests/scripts/all.sh
+++ b/tests/scripts/all.sh
@@ -32,6 +32,7 @@
 
 MEMORY=0
 FORCE=0
+RELEASE=0
 
 # Default commands, can be overriden by the environment
 : ${OPENSSL:="openssl"}
@@ -48,6 +49,8 @@
     printf "  -h|--help\t\tPrint this help.\n"
     printf "  -m|--memory\t\tAdditional optional memory tests.\n"
     printf "  -f|--force\t\tForce the tests to overwrite any modified files.\n"
+    printf "  -s|--seed\t\tInteger seed value to use for this test run.\n"
+    printf "  -r|--release-test\t\tRun this script in release mode. This fixes the seed value to 1.\n"
     printf "     --out-of-source-dir=<path>\t\tDirectory used for CMake out-of-source build tests."
     printf "     --openssl=<OpenSSL_path>\t\tPath to OpenSSL executable to use for most tests.\n"
     printf "     --openssl-legacy=<OpenSSL_path>\t\tPath to OpenSSL executable to use for legacy tests e.g. SSLv3.\n"
@@ -106,6 +109,13 @@
         --force|-f)
             FORCE=1
             ;;
+        --seed|-s)
+            shift
+            SEED="$1"
+            ;;
+        --release-test|-r)
+            RELEASE=1
+            ;;
         --out-of-source-dir)
             shift
             OUT_OF_SOURCE_DIR="$1"
@@ -171,9 +181,15 @@
     fi
 fi
 
+if [ $RELEASE -eq 1 ]; then
+    # Fix the seed value to 1 to ensure that the tests are deterministic.
+    SEED=1
+fi
+
 msg "info: $0 configuration"
 echo "MEMORY: $MEMORY"
 echo "FORCE: $FORCE"
+echo "SEED: ${SEED-"UNSET"}"
 echo "OPENSSL: $OPENSSL"
 echo "OPENSSL_LEGACY: $OPENSSL_LEGACY"
 echo "GNUTLS_CLI: $GNUTLS_CLI"
@@ -187,6 +203,9 @@
 export GNUTLS_CLI="$GNUTLS_CLI"
 export GNUTLS_SERV="$GNUTLS_SERV"
 
+# Avoid passing --seed flag in every call to ssl-opt.sh
+[ ! -z ${SEED+set} ] && export SEED
+
 # Make sure the tools we need are available.
 check_tools "$OPENSSL" "$OPENSSL_LEGACY" "$GNUTLS_CLI" "$GNUTLS_SERV" \
     "$GNUTLS_LEGACY_CLI" "$GNUTLS_LEGACY_SERV" "doxygen" "dot" \
diff --git a/tests/ssl-opt.sh b/tests/ssl-opt.sh
index d9c45cd..429d9cd 100755
--- a/tests/ssl-opt.sh
+++ b/tests/ssl-opt.sh
@@ -58,6 +58,7 @@
     printf "  -n|--number\tExecute only numbered test (comma-separated, e.g. '245,256')\n"
     printf "  -s|--show-numbers\tShow test numbers in front of test names\n"
     printf "  -p|--preserve-logs\tPreserve logs of successful tests as well\n"
+    printf "     --seed\tInteger seed value to use for this test run\n"
 }
 
 get_options() {
@@ -81,6 +82,9 @@
             -p|--preserve-logs)
                 PRESERVE_LOGS=1
                 ;;
+            --seed)
+                shift; SEED="$1"
+                ;;
             -h|--help)
                 print_usage
                 exit 0
@@ -595,7 +599,7 @@
 # +SRV_PORT will be replaced by either $SRV_PORT or $PXY_PORT later
 P_SRV="$P_SRV server_addr=127.0.0.1 server_port=$SRV_PORT"
 P_CLI="$P_CLI server_addr=127.0.0.1 server_port=+SRV_PORT"
-P_PXY="$P_PXY server_addr=127.0.0.1 server_port=$SRV_PORT listen_addr=127.0.0.1 listen_port=$PXY_PORT"
+P_PXY="$P_PXY server_addr=127.0.0.1 server_port=$SRV_PORT listen_addr=127.0.0.1 listen_port=$PXY_PORT ${SEED:+"seed=$SEED"}"
 O_SRV="$O_SRV -accept $SRV_PORT -dhparam data_files/dhparams.pem"
 O_CLI="$O_CLI -connect localhost:+SRV_PORT"
 G_SRV="$G_SRV -p $SRV_PORT"
diff --git a/tests/suites/helpers.function b/tests/suites/helpers.function
index d12be75..63815df 100644
--- a/tests/suites/helpers.function
+++ b/tests/suites/helpers.function
@@ -8,16 +8,13 @@
 #include "mbedtls/platform.h"
 #else
 #include <stdio.h>
-#define mbedtls_printf     printf
 #define mbedtls_fprintf    fprintf
-#define mbedtls_calloc    calloc
+#define mbedtls_snprintf   snprintf
+#define mbedtls_calloc     calloc
 #define mbedtls_free       free
 #define mbedtls_exit       exit
 #define mbedtls_time       time
 #define mbedtls_time_t     time_t
-#define mbedtls_fprintf    fprintf
-#define mbedtls_printf     printf
-#define mbedtls_snprintf   snprintf
 #define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
 #define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
 #endif
@@ -37,6 +34,9 @@
 
 #include <string.h>
 
+#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
+#include <unistd.h>
+#endif
 
 /*----------------------------------------------------------------------------*/
 /* Constants */
@@ -105,6 +105,48 @@
 /*----------------------------------------------------------------------------*/
 /* Helper Functions */
 
+#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
+static int redirect_output( FILE** out_stream, const char* path )
+{
+    int stdout_fd = dup( fileno( *out_stream ) );
+
+    if( stdout_fd == -1 )
+    {
+        return -1;
+    }
+
+    fflush( *out_stream );
+    fclose( *out_stream );
+    *out_stream = fopen( path, "w" );
+
+    if( *out_stream == NULL )
+    {
+        return -1;
+    }
+
+    return stdout_fd;
+}
+
+static int restore_output( FILE** out_stream, int old_fd )
+{
+    fflush( *out_stream );
+    fclose( *out_stream );
+
+    *out_stream = fdopen( old_fd, "w" );
+    if( *out_stream == NULL )
+    {
+        return -1;
+    }
+
+    return 0;
+}
+
+static void close_output( FILE* out_stream )
+{
+    fclose( out_stream );
+}
+#endif /* __unix__ || __APPLE__ __MACH__ */
+
 static int unhexify( unsigned char *obuf, const char *ibuf )
 {
     unsigned char c, c2;
@@ -355,7 +397,8 @@
 {
     test_errors++;
     if( test_errors == 1 )
-        mbedtls_printf( "FAILED\n" );
-    mbedtls_printf( "  %s\n  at line %d, %s\n", test, line_no, filename );
+        mbedtls_fprintf( stdout, "FAILED\n" );
+    mbedtls_fprintf( stdout, "  %s\n  at line %d, %s\n", test, line_no,
+                        filename );
 }
 
diff --git a/tests/suites/main_test.function b/tests/suites/main_test.function
index ac5322e..afff5a4 100644
--- a/tests/suites/main_test.function
+++ b/tests/suites/main_test.function
@@ -7,7 +7,8 @@
     if( (*str)[0] != '"' ||
         (*str)[strlen( *str ) - 1] != '"' )
     {
-        mbedtls_printf( "Expected string (with \"\") for parameter and got: %s\n", *str );
+        mbedtls_fprintf( stderr,
+            "Expected string (with \"\") for parameter and got: %s\n", *str );
         return( -1 );
     }
 
@@ -60,7 +61,8 @@
 
 MAPPING_CODE
 
-    mbedtls_printf( "Expected integer for parameter and got: %s\n", str );
+    mbedtls_fprintf( stderr,
+                    "Expected integer for parameter and got: %s\n", str );
     return( KEY_VALUE_MAPPING_NOT_FOUND );
 }
 
@@ -259,6 +261,7 @@
     char buf[5000];
     char *params[50];
     void *pointer;
+    int stdout_fd = -1;
 
 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) && \
     !defined(TEST_SUITE_MEMORY_BUFFER_ALLOC)
@@ -343,7 +346,8 @@
         {
             if( unmet_dep_count > 0 )
             {
-                mbedtls_printf("FATAL: Dep count larger than zero at start of loop\n");
+                mbedtls_fprintf( stderr,
+                    "FATAL: Dep count larger than zero at start of loop\n" );
                 mbedtls_exit( MBEDTLS_EXIT_FAILURE );
             }
             unmet_dep_count = 0;
@@ -379,7 +383,7 @@
                         unmet_dependencies[ unmet_dep_count ] = strdup(params[i]);
                         if(  unmet_dependencies[ unmet_dep_count ] == NULL )
                         {
-                            mbedtls_printf("FATAL: Out of memory\n");
+                            mbedtls_fprintf( stderr, "FATAL: Out of memory\n" );
                             mbedtls_exit( MBEDTLS_EXIT_FAILURE );
                         }
                         unmet_dep_count++;
@@ -395,7 +399,32 @@
             if( unmet_dep_count == 0 )
             {
                 test_errors = 0;
+
+#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
+                /* Suppress all output from the library unless we're verbose
+                 * mode
+                 */
+                if( !option_verbose )
+                {
+                    stdout_fd = redirect_output( &stdout, "/dev/null" );
+                    if( stdout_fd == -1 )
+                    {
+                        /* Redirection has failed with no stdout so exit */
+                        exit( 1 );
+                    }
+                }
+#endif /* __unix__ || __APPLE__ __MACH__ */
+
                 ret = dispatch_test( cnt, params );
+
+#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
+                if( !option_verbose && restore_output( &stdout, stdout_fd ) )
+                {
+                        /* Redirection has failed with no stdout so exit */
+                        exit( 1 );
+                }
+#endif /* __unix__ || __APPLE__ __MACH__ */
+
             }
 
             if( unmet_dep_count > 0 || ret == DISPATCH_UNSUPPORTED_SUITE )
@@ -470,6 +499,11 @@
     mbedtls_memory_buffer_alloc_free();
 #endif
 
+#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
+    if( stdout_fd != -1 )
+        close_output( stdout );
+#endif /* __unix__ || __APPLE__ __MACH__ */
+
     return( total_errors != 0 );
 }
 
diff --git a/tests/suites/test_suite_cmac.data b/tests/suites/test_suite_cmac.data
index a913ffd..70b7609 100644
--- a/tests/suites/test_suite_cmac.data
+++ b/tests/suites/test_suite_cmac.data
@@ -1,6 +1,9 @@
 CMAC self test
 mbedtls_cmac_self_test:
 
+CMAC null arguments
+mbedtls_cmac_null_args:
+
 CMAC init #1 AES-128: OK
 depends_on:MBEDTLS_AES_C
 mbedtls_cmac_setkey:MBEDTLS_CIPHER_AES_128_ECB:128:0
@@ -21,7 +24,41 @@
 depends_on:MBEDTLS_AES_C
 mbedtls_cmac_setkey:MBEDTLS_CIPHER_ID_AES:224:MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA
 
-CMAC init #6 Camellia: wrong cipher
+CMAC init #6 AES-0: bad key size
+depends_on:MBEDTLS_AES_C
+mbedtls_cmac_setkey:MBEDTLS_CIPHER_ID_AES:0:MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA
+
+CMAC init #7 Camellia: wrong cipher
 depends_on:MBEDTLS_CAMELLIA_C
 mbedtls_cmac_setkey:MBEDTLS_CIPHER_ID_CAMELLIA:128:MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA
 
+CMAC Single Blocks #1 - Empty block, no updates
+mbedtls_cmac_multiple_blocks:MBEDTLS_CIPHER_AES_128_ECB:"2b7e151628aed2a6abf7158809cf4f3c":128:16:"":-1:"":-1:"":-1:"":-1:"bb1d6929e95937287fa37d129b756746"
+
+CMAC Single Blocks #2 - Single 16 byte block
+mbedtls_cmac_multiple_blocks:MBEDTLS_CIPHER_AES_128_ECB:"2b7e151628aed2a6abf7158809cf4f3c":128:16:"6bc1bee22e409f96e93d7e117393172a":16:"":-1:"":-1:"":-1:"070a16b46b4d4144f79bdd9dd04a287c"
+
+CMAC Single Blocks #3 - Single 64 byte block
+mbedtls_cmac_multiple_blocks:MBEDTLS_CIPHER_AES_128_ECB:"2b7e151628aed2a6abf7158809cf4f3c":128:16:"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710":64:"":-1:"":-1:"":-1:"51f0bebf7e3b9d92fc49741779363cfe"
+
+CMAC Multiple Blocks #1 - Multiple 8 byte blocks
+mbedtls_cmac_multiple_blocks:MBEDTLS_CIPHER_AES_128_ECB:"2b7e151628aed2a6abf7158809cf4f3c":128:16:"6bc1bee22e409f96":8:"e93d7e117393172a":8:"":-1:"":-1:"070a16b46b4d4144f79bdd9dd04a287c"
+
+CMAC Multiple Blocks #2 - Multiple 16 byte blocks
+mbedtls_cmac_multiple_blocks:MBEDTLS_CIPHER_AES_128_ECB:"2b7e151628aed2a6abf7158809cf4f3c":128:16:"6bc1bee22e409f96e93d7e117393172a":16:"ae2d8a571e03ac9c9eb76fac45af8e51":16:"30c81c46a35ce411e5fbc1191a0a52ef":16:"f69f2445df4f9b17ad2b417be66c3710":16:"51f0bebf7e3b9d92fc49741779363cfe"
+
+CMAC Multiple Blocks #3 - Multiple variable sized blocks
+mbedtls_cmac_multiple_blocks:MBEDTLS_CIPHER_AES_128_ECB:"2b7e151628aed2a6abf7158809cf4f3c":128:16:"6bc1bee22e409f96":8:"e93d7e117393172aae2d8a571e03ac9c":16:"9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52ef":24:"f69f2445df4f9b17ad2b417be66c3710":16:"51f0bebf7e3b9d92fc49741779363cfe"
+
+CMAC Multiple Blocks #4 - Multiple 8 byte blocks with gaps
+mbedtls_cmac_multiple_blocks:MBEDTLS_CIPHER_AES_128_ECB:"2b7e151628aed2a6abf7158809cf4f3c":128:16:"":0:"6bc1bee22e409f96":8:"":0:"e93d7e117393172a":8:"070a16b46b4d4144f79bdd9dd04a287c"
+
+CMAC Multiple Operations, same key #1 - Empty, empty
+mbedtls_cmac_multiple_operations_same_key:MBEDTLS_CIPHER_AES_192_ECB:"8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b":192:16:"":-1:"":-1:"":-1:"d17ddf46adaacde531cac483de7a9367":"":-1:"":-1:"":-1:"d17ddf46adaacde531cac483de7a9367"
+
+CMAC Multiple Operations, same key #2 - Empty, 64 byte block
+mbedtls_cmac_multiple_operations_same_key:MBEDTLS_CIPHER_AES_192_ECB:"8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b":192:16:"":-1:"":-1:"":-1:"d17ddf46adaacde531cac483de7a9367":"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710":64:"":-1:"":-1:"a1d5df0eed790f794d77589659f39a11"
+
+CMAC Multiple Operations, same key #3 - variable byte blocks
+mbedtls_cmac_multiple_operations_same_key:MBEDTLS_CIPHER_AES_192_ECB:"8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b":192:16:"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51":32:"30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710":32:"":-1:"a1d5df0eed790f794d77589659f39a11":"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51":32:"30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710":32:"":-1:"a1d5df0eed790f794d77589659f39a11"
+
diff --git a/tests/suites/test_suite_cmac.function b/tests/suites/test_suite_cmac.function
index 3b23b52..4b31ab2 100644
--- a/tests/suites/test_suite_cmac.function
+++ b/tests/suites/test_suite_cmac.function
@@ -16,6 +16,89 @@
 /* END_CASE */
 
 /* BEGIN_CASE */
+void mbedtls_cmac_null_args( )
+{
+    mbedtls_cipher_context_t ctx;
+    const mbedtls_cipher_info_t *cipher_info;
+    unsigned char test_key[MBEDTLS_CIPHER_BLKSIZE_MAX];
+    unsigned char test_data[MBEDTLS_CIPHER_BLKSIZE_MAX];
+    unsigned char test_output[MBEDTLS_CIPHER_BLKSIZE_MAX];
+
+    mbedtls_cipher_init( &ctx );
+
+    /* Test NULL cipher info */
+    TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx, test_data, 16 ) ==
+                                         MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    cipher_info = mbedtls_cipher_info_from_type( MBEDTLS_CIPHER_AES_128_ECB );
+    TEST_ASSERT( mbedtls_cipher_setup( &ctx, cipher_info ) == 0 );
+
+    TEST_ASSERT( mbedtls_cipher_cmac_starts( NULL, test_key, 128 ) ==
+                                         MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_cipher_cmac_starts( &ctx, NULL, 128 ) ==
+                                         MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_cipher_cmac_update( NULL, test_data, 16 ) ==
+                                         MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx, NULL, 16 ) ==
+                                         MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_cipher_cmac_finish( NULL, test_output ) ==
+                                         MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_cipher_cmac_finish( &ctx, NULL ) ==
+                                         MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_cipher_cmac_reset( NULL ) ==
+                                         MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_cipher_cmac( NULL,
+                                      test_key, 128,
+                                      test_data, 16,
+                                      test_output ) ==
+                                            MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_cipher_cmac( cipher_info,
+                                      NULL, 128,
+                                      test_data, 16,
+                                      test_output ) ==
+                                            MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_cipher_cmac( cipher_info,
+                                      test_key, 128,
+                                      NULL, 16,
+                                      test_output ) ==
+                                            MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_cipher_cmac( cipher_info,
+                                      test_key, 128,
+                                      test_data, 16,
+                                      NULL ) ==
+                                            MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_aes_cmac_prf_128( NULL, 16,
+                                           test_data, 16,
+                                           test_output ) ==
+                                           MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_aes_cmac_prf_128( test_key, 16,
+                                           NULL, 16,
+                                           test_output ) ==
+                                              MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_aes_cmac_prf_128( test_key, 16,
+                                           test_data, 16,
+                                           NULL ) ==
+                                              MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+exit:
+    mbedtls_cipher_free( &ctx );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
 void mbedtls_cmac_setkey( int cipher_type, int key_size,
                           int result )
 {
@@ -30,8 +113,198 @@
     TEST_ASSERT( ( cipher_info = mbedtls_cipher_info_from_type( cipher_type ) )
                     != NULL );
 
-    TEST_ASSERT( result == mbedtls_cipher_cmac( cipher_info, key, key_size,
-                                                buf, 16, tmp ) );
+    memset( buf, 0x2A, sizeof( buf ) );
+    TEST_ASSERT( ( result == mbedtls_cipher_cmac( cipher_info, key, key_size,
+                                                buf, 16, tmp ) ) != 0 );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void mbedtls_cmac_multiple_blocks( int cipher_type,
+                                   char *key_string, int keybits,
+                                   int block_size,
+                                   char *block1_string, int block1_len,
+                                   char *block2_string, int block2_len,
+                                   char *block3_string, int block3_len,
+                                   char *block4_string, int block4_len,
+                                   char *expected_result_string )
+{
+    unsigned char key[100];
+    unsigned char block1[100];
+    unsigned char block2[100];
+    unsigned char block3[100];
+    unsigned char block4[100];
+    unsigned char expected_result[100];
+    const mbedtls_cipher_info_t *cipher_info;
+    mbedtls_cipher_context_t ctx;
+    unsigned char output[MBEDTLS_CIPHER_BLKSIZE_MAX];
+
+    /* Convert the test parameters to binary data */
+    unhexify( key, key_string );
+    unhexify( block1, block1_string );
+    unhexify( block2, block2_string );
+    unhexify( block3, block3_string );
+    unhexify( block4, block4_string );
+    unhexify( expected_result, expected_result_string );
+
+    mbedtls_cipher_init( &ctx );
+
+    /* Validate the test inputs */
+    TEST_ASSERT( block1_len <= 100 );
+    TEST_ASSERT( block2_len <= 100 );
+    TEST_ASSERT( block3_len <= 100 );
+    TEST_ASSERT( block4_len <= 100 );
+
+    /* Set up */
+    TEST_ASSERT( ( cipher_info = mbedtls_cipher_info_from_type( cipher_type ) )
+                    != NULL );
+
+    TEST_ASSERT( mbedtls_cipher_setup( &ctx, cipher_info ) == 0 );
+
+    TEST_ASSERT( mbedtls_cipher_cmac_starts( &ctx,
+                                             (const unsigned char*)key,
+                                             keybits ) == 0 );
+
+    /* Multiple partial and complete blocks. A negative length means skip the
+     * update operation */
+    if( block1_len >= 0)
+        TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx,
+                                                 (unsigned char*)block1,
+                                                 block1_len ) == 0);
+
+    if( block2_len >= 0 )
+        TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx,
+                                                 (unsigned char*)block2,
+                                                 block2_len ) == 0);
+
+    if( block3_len >= 0 )
+        TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx,
+                                                 (unsigned char*)block3,
+                                                 block3_len ) == 0);
+
+    if( block4_len >= 0 )
+        TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx,
+                                                 (unsigned char*)block4,
+                                                 block4_len ) == 0);
+
+    TEST_ASSERT( mbedtls_cipher_cmac_finish( &ctx, output ) == 0 );
+
+    TEST_ASSERT( memcmp( output, expected_result, block_size )  == 0 );
+
+exit:
+    mbedtls_cipher_free( &ctx );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void mbedtls_cmac_multiple_operations_same_key( int cipher_type,
+                                   char *key_string, int keybits,
+                                   int block_size,
+                                   char *block_a1_string, int block_a1_len,
+                                   char *block_a2_string, int block_a2_len,
+                                   char *block_a3_string, int block_a3_len,
+                                   char *expected_result_a_string,
+                                   char *block_b1_string, int block_b1_len,
+                                   char *block_b2_string, int block_b2_len,
+                                   char *block_b3_string, int block_b3_len,
+                                   char *expected_result_b_string )
+{
+    unsigned char key[100];
+    unsigned char block_a1[100];
+    unsigned char block_a2[100];
+    unsigned char block_a3[100];
+    unsigned char block_b1[100];
+    unsigned char block_b2[100];
+    unsigned char block_b3[100];
+    unsigned char expected_result_a[100], expected_result_b[100];
+    const mbedtls_cipher_info_t *cipher_info;
+    mbedtls_cipher_context_t ctx;
+    unsigned char output[MBEDTLS_CIPHER_BLKSIZE_MAX];
+
+    /* Convert the test parameters to binary data */
+    unhexify( key, key_string );
+    unhexify( block_a1, block_a1_string );
+    unhexify( block_a2, block_a2_string );
+    unhexify( block_a3, block_a3_string );
+
+    unhexify( block_b1, block_b1_string );
+    unhexify( block_b2, block_b2_string );
+    unhexify( block_b3, block_b3_string );
+
+    unhexify( expected_result_a, expected_result_a_string );
+    unhexify( expected_result_b, expected_result_b_string );
+
+    mbedtls_cipher_init( &ctx );
+
+    /* Validate the test inputs */
+    TEST_ASSERT( block_a1_len <= 100 );
+    TEST_ASSERT( block_a2_len <= 100 );
+    TEST_ASSERT( block_a3_len <= 100 );
+
+    TEST_ASSERT( block_b1_len <= 100 );
+    TEST_ASSERT( block_b2_len <= 100 );
+    TEST_ASSERT( block_b3_len <= 100 );
+
+    /* Set up */
+    TEST_ASSERT( ( cipher_info = mbedtls_cipher_info_from_type( cipher_type ) )
+                    != NULL );
+
+    TEST_ASSERT( mbedtls_cipher_setup( &ctx, cipher_info ) == 0 );
+
+    TEST_ASSERT( mbedtls_cipher_cmac_starts( &ctx,
+                                             (const unsigned char*)key,
+                                             keybits ) == 0 );
+
+    /* Sequence A */
+
+    /* Multiple partial and complete blocks. A negative length means skip the
+     * update operation */
+    if( block_a1_len >= 0 )
+        TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx,
+                                                 (unsigned char*)block_a1,
+                                                 block_a1_len ) == 0);
+
+    if( block_a2_len >= 0 )
+        TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx,
+                                                 (unsigned char*)block_a2,
+                                                 block_a2_len ) == 0);
+
+    if( block_a3_len >= 0 )
+        TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx,
+                                                 (unsigned char*)block_a3,
+                                                  block_a3_len ) == 0);
+
+    TEST_ASSERT( mbedtls_cipher_cmac_finish( &ctx, output ) == 0 );
+
+    TEST_ASSERT( memcmp( output, expected_result_a, block_size )  == 0 );
+
+    TEST_ASSERT( mbedtls_cipher_cmac_reset( &ctx ) == 0 );
+
+    /* Sequence B */
+
+    /* Multiple partial and complete blocks. A negative length means skip the
+     * update operation */
+    if( block_b1_len >= 0)
+        TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx,
+                                                 (unsigned char*)block_b1,
+                                                 block_b1_len ) == 0);
+
+    if( block_b2_len >= 0 )
+        TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx,
+                                                 (unsigned char*)block_b2,
+                                                 block_b2_len ) == 0);
+
+    if( block_b3_len >= 0 )
+        TEST_ASSERT( mbedtls_cipher_cmac_update( &ctx,
+                                                 (unsigned char*)block_b3,
+                                                 block_b3_len ) == 0);
+
+    TEST_ASSERT( mbedtls_cipher_cmac_finish( &ctx, output ) == 0 );
+
+    TEST_ASSERT( memcmp( output, expected_result_b, block_size )  == 0 );
+
+exit:
+    mbedtls_cipher_free( &ctx );
 }
 /* END_CASE */
 
diff --git a/tests/suites/test_suite_rsa.data b/tests/suites/test_suite_rsa.data
index d522332..af16880 100644
--- a/tests/suites/test_suite_rsa.data
+++ b/tests/suites/test_suite_rsa.data
@@ -361,7 +361,7 @@
 mbedtls_rsa_gen_key:2048:3:0
 
 RSA Generate Key - 1025 bit key
-mbedtls_rsa_gen_key:1025:3:0
+mbedtls_rsa_gen_key:1025:3:MBEDTLS_ERR_RSA_BAD_INPUT_DATA
 
 RSA PKCS1 Encrypt Bad RNG
 depends_on:MBEDTLS_PKCS1_V15
diff --git a/tests/suites/test_suite_rsa.function b/tests/suites/test_suite_rsa.function
index 8837e3a..d48bc85 100644
--- a/tests/suites/test_suite_rsa.function
+++ b/tests/suites/test_suite_rsa.function
@@ -678,6 +678,7 @@
     if( result == 0 )
     {
         TEST_ASSERT( mbedtls_rsa_check_privkey( &ctx ) == 0 );
+        TEST_ASSERT( mbedtls_mpi_cmp_mpi( &ctx.P, &ctx.Q ) > 0 );
     }
 
 exit: