Merge remote-tracking branch 'upstream-restricted/pr/443' into mbedtls-1.3-restricted
diff --git a/ChangeLog b/ChangeLog
index 4cee23e..8148b74 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -30,6 +30,9 @@
      Reported by Marco Macchetti, Kudelski Group.
    * Wipe stack buffer temporarily holding EC private exponent
      after keypair generation.
+   * Change default choice of DHE parameters from untrustworthy RFC 5114
+     to RFC 3526 containing parameters generated in a nothing-up-my-sleeve
+     manner.
    * Fix a potential heap buffer overread in ALPN extension parsing
      (server-side). Could result in application crash, but only if an ALPN
      name larger than 16 bytes had been configured on the server.
@@ -79,8 +82,14 @@
    * Fix word size check in in pk.c to not depend on MBEDTLS_HAVE_INT64.
    * Fix crash when calling mbedtls_ssl_cache_free() twice. Found by
      MilenkoMitrovic, #1104
-   * Fix mbedtls_timing_alarm(0) on Unix.
+   * Fix mbedtls_timing_alarm(0) on Unix and MinGW.
    * Fix use of uninitialized memory in mbedtls_timing_get_timer when reset=1.
+   * Fix issue in RSA key generation program programs/x509/rsa_genkey
+     where the failure of CTR DRBG initialization lead to freeing an
+     RSA context without proper initialization beforehand.
+   * Fix bug in cipher decryption with POLARSSL_PADDING_ONE_AND_ZEROS that
+     sometimes accepted invalid padding. (Not used in TLS.) Found and fixed
+     by Micha Kraus.
 
 Changes
    * Extend cert_write example program by options to set the CRT version
diff --git a/include/polarssl/dhm.h b/include/polarssl/dhm.h
index 8d64a5f..e8ea172 100644
--- a/include/polarssl/dhm.h
+++ b/include/polarssl/dhm.h
@@ -55,6 +55,12 @@
  *  RFC 3526 4.    3072-bit MODP Group
  *  RFC 5114 2.1.  1024-bit MODP Group with 160-bit Prime Order Subgroup
  *  RFC 5114 2.2.  2048-bit MODP Group with 224-bit Prime Order Subgroup
+ *
+ * \warning The primes from RFC 5114 do not come together with information
+ *          on how they were generated and are therefore not considered
+ *          trustworthy. It is recommended to avoid them and to use the
+ *          nothing-up-my-sleeve primes from RFC 3526 instead.
+ *
  */
 #define POLARSSL_DHM_RFC2409_MODP_1024_P               \
     "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \
diff --git a/library/cipher.c b/library/cipher.c
index 7ea25cf..35c5184 100644
--- a/library/cipher.c
+++ b/library/cipher.c
@@ -500,14 +500,14 @@
     if( NULL == input || NULL == data_len )
         return( POLARSSL_ERR_CIPHER_BAD_INPUT_DATA );
 
-    bad = 0xFF;
+    bad = 0x80;
     *data_len = 0;
     for( i = input_len; i > 0; i-- )
     {
         prev_done = done;
-        done |= ( input[i-1] != 0 );
+        done |= ( input[i - 1] != 0 );
         *data_len |= ( i - 1 ) * ( done != prev_done );
-        bad &= ( input[i-1] ^ 0x80 ) | ( done == prev_done );
+        bad ^= input[i - 1] * ( done != prev_done );
     }
 
     return( POLARSSL_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
diff --git a/library/ssl_srv.c b/library/ssl_srv.c
index 2cdf227..2200041 100644
--- a/library/ssl_srv.c
+++ b/library/ssl_srv.c
@@ -1971,7 +1971,7 @@
     const ssl_ciphersuite_t *suite = NULL;
     const cipher_info_t *cipher = NULL;
 
-    if( ssl->session_negotiate->encrypt_then_mac == SSL_EXTENDED_MS_DISABLED ||
+    if( ssl->session_negotiate->encrypt_then_mac == SSL_ETM_DISABLED ||
         ssl->minor_ver == SSL_MINOR_VERSION_0 )
     {
         *olen = 0;
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 855872b..aa478e2 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -3711,9 +3711,9 @@
 
 #if defined(POLARSSL_DHM_C)
     if( ( ret = mpi_read_string( &ssl->dhm_P, 16,
-                                 POLARSSL_DHM_RFC5114_MODP_2048_P) ) != 0 ||
+                                 POLARSSL_DHM_RFC3526_MODP_2048_P) ) != 0 ||
         ( ret = mpi_read_string( &ssl->dhm_G, 16,
-                                 POLARSSL_DHM_RFC5114_MODP_2048_G) ) != 0 )
+                                 POLARSSL_DHM_RFC3526_MODP_2048_G) ) != 0 )
     {
         SSL_DEBUG_RET( 1, "mpi_read_string", ret );
         return( ret );
diff --git a/library/timing.c b/library/timing.c
index 1489383..83d0287 100644
--- a/library/timing.c
+++ b/library/timing.c
@@ -268,6 +268,14 @@
 {
     DWORD ThreadId;
 
+    if( seconds == 0 )
+    {
+        /* No need to create a thread for this simple case.
+         * Also, this shorcut is more reliable at least on MinGW32 */
+        alarmed = 1;
+        return;
+    }
+
     alarmed = 0;
     alarmMs = seconds * 1000;
     CloseHandle( CreateThread( NULL, 0, TimerProc, NULL, 0, &ThreadId ) );
diff --git a/programs/pkey/rsa_genkey.c b/programs/pkey/rsa_genkey.c
index 0270b53..305158b 100644
--- a/programs/pkey/rsa_genkey.c
+++ b/programs/pkey/rsa_genkey.c
@@ -74,6 +74,7 @@
     fflush( stdout );
 
     entropy_init( &entropy );
+    rsa_init( &rsa, RSA_PKCS_V15, 0 );
     if( ( ret = ctr_drbg_init( &ctr_drbg, entropy_func, &entropy,
                                (const unsigned char *) pers,
                                strlen( pers ) ) ) != 0 )
@@ -85,7 +86,6 @@
     polarssl_printf( " ok\n  . Generating the RSA key [ %d-bit ]...", KEY_SIZE );
     fflush( stdout );
 
-    rsa_init( &rsa, RSA_PKCS_V15, 0 );
 
     if( ( ret = rsa_gen_key( &rsa, ctr_drbg_random, &ctr_drbg, KEY_SIZE,
                              EXPONENT ) ) != 0 )
diff --git a/programs/ssl/ssl_server2.c b/programs/ssl/ssl_server2.c
index b99aeb6..f7f79ab 100644
--- a/programs/ssl/ssl_server2.c
+++ b/programs/ssl/ssl_server2.c
@@ -1598,8 +1598,8 @@
         ret = ssl_set_dh_param_ctx( &ssl, &dhm );
     else
 #endif
-        ret = ssl_set_dh_param( &ssl, POLARSSL_DHM_RFC5114_MODP_2048_P,
-                                      POLARSSL_DHM_RFC5114_MODP_2048_G );
+        ret = ssl_set_dh_param( &ssl, POLARSSL_DHM_RFC3526_MODP_2048_P,
+                                      POLARSSL_DHM_RFC3526_MODP_2048_G );
 
     if( ret != 0 )
     {
@@ -1620,8 +1620,13 @@
 #if !defined(_WIN32)
     if( received_sigterm )
     {
-        polarssl_printf( " interrupted by SIGTERM\n" );
-        ret = 0;
+        polarssl_printf( " interrupted by SIGTERM (not in net_accept())\n" );
+        if( ret == POLARSSL_ERR_NET_RECV_FAILED ||
+            ret == POLARSSL_ERR_NET_SEND_FAILED )
+        {
+            ret = 0;
+        }
+
         goto exit;
     }
 #endif
@@ -1653,8 +1658,10 @@
 #if !defined(_WIN32)
         if( received_sigterm )
         {
-            polarssl_printf( " interrupted by signal\n" );
-            ret = 0;
+            polarssl_printf( " interrupted by SIGTERM (in net_accept())\n" );
+            if( ret == POLARSSL_ERR_NET_ACCEPT_FAILED )
+                ret = 0;
+
             goto exit;
         }
 #endif
diff --git a/programs/test/benchmark.c b/programs/test/benchmark.c
index 00abe52..d5eceef 100644
--- a/programs/test/benchmark.c
+++ b/programs/test/benchmark.c
@@ -135,15 +135,6 @@
                      ( hardclock() - tsc ) / ( jj * BUFSIZE ) );        \
 } while( 0 )
 
-#if defined(POLARSSL_ERROR_C)
-#define PRINT_ERROR                                                     \
-        polarssl_strerror( ret, ( char * )tmp, sizeof( tmp ) );         \
-        polarssl_printf( "FAILED: %s\n", tmp );
-#else
-#define PRINT_ERROR                                                     \
-        polarssl_printf( "FAILED: -0x%04x\n", -ret );
-#endif
-
 #if defined(POLARSSL_MEMORY_BUFFER_ALLOC_C) && defined(POLARSSL_MEMORY_DEBUG)
 
 #define MEMORY_MEASURE_INIT                                             \
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index e0ac8b3..7793dd7 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -31,7 +31,7 @@
     include_directories(${CMAKE_CURRENT_SOURCE_DIR})
     add_executable(test_suite_${data_name} test_suite_${data_name}.c)
     target_link_libraries(test_suite_${data_name} ${libs})
-    add_test(${data_name}-suite test_suite_${data_name})
+    add_test(${data_name}-suite test_suite_${data_name} --verbose)
 endfunction(add_test_suite)
 
 set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unused-function")
diff --git a/tests/compat.sh b/tests/compat.sh
index d22a281..dcbe1bf 100755
--- a/tests/compat.sh
+++ b/tests/compat.sh
@@ -780,8 +780,9 @@
         done
     }
 else
+    echo "Warning: lsof not available, wait_server_start = sleep"
     wait_server_start() {
-        sleep 1
+        sleep 2
     }
 fi
 
diff --git a/tests/ssl-opt.sh b/tests/ssl-opt.sh
index c027bc0..40d47b8 100755
--- a/tests/ssl-opt.sh
+++ b/tests/ssl-opt.sh
@@ -187,6 +187,7 @@
         done
     }
 else
+    echo "Warning: lsof not available, wait_server_start = sleep $START_DELAY"
     wait_server_start() {
         sleep "$START_DELAY"
     }
@@ -409,13 +410,22 @@
 # used by watchdog
 MAIN_PID="$$"
 
-# be more patient with valgrind
+# We use somewhat arbitrary delays for tests:
+# - how long do we wait for the server to start (when lsof not available)?
+# - how long do we allow for the client to finish?
+#   (not to check performance, just to avoid waiting indefinitely)
+# Things are slower with valgrind, so give extra time here.
+#
+# Note: without lsof, there is a trade-off between the running time of this
+# script and the risk of spurious errors because we didn't wait long enough.
+# The watchdog delay on the other hand doesn't affect normal running time of
+# the script, only the case where a client or server gets stuck.
 if [ "$MEMCHECK" -gt 0 ]; then
-    START_DELAY=3
-    DOG_DELAY=30
+    START_DELAY=6
+    DOG_DELAY=60
 else
-    START_DELAY=1
-    DOG_DELAY=10
+    START_DELAY=2
+    DOG_DELAY=20
 fi
 
 # Pick a "unique" port in the range 10000-19999.
@@ -2331,7 +2341,7 @@
                     debug_level=3" \
             0 \
             -c "value of 'DHM: P ' (2048 bits)" \
-            -c "value of 'DHM: G ' (2048 bits)"
+            -c "value of 'DHM: G ' (2 bits)"
 
 run_test    "DHM parameters: other parameters" \
             "$P_SRV dhm_file=data_files/dhparams.pem" \
diff --git a/tests/suites/test_suite_cipher.padding.data b/tests/suites/test_suite_cipher.padding.data
index 9b5f290..627c123 100644
--- a/tests/suites/test_suite_cipher.padding.data
+++ b/tests/suites/test_suite_cipher.padding.data
@@ -184,6 +184,10 @@
 depends_on:POLARSSL_CIPHER_PADDING_ONE_AND_ZEROS
 check_padding:POLARSSL_PADDING_ONE_AND_ZEROS:"0000000000":POLARSSL_ERR_CIPHER_INVALID_PADDING:4
 
+Check one and zeros padding #8 (last byte 0x80 | x)
+depends_on:POLARSSL_CIPHER_PADDING_ONE_AND_ZEROS
+check_padding:POLARSSL_PADDING_ONE_AND_ZEROS:"0000000082":POLARSSL_ERR_CIPHER_INVALID_PADDING:4
+
 Check zeros and len padding #1 (correct)
 depends_on:POLARSSL_CIPHER_PADDING_ZEROS_AND_LEN
 check_padding:POLARSSL_PADDING_ZEROS_AND_LEN:"DABBAD0001":0:4
diff --git a/tests/suites/test_suite_mpi.function b/tests/suites/test_suite_mpi.function
index c0fdf8e..ad2b32e 100644
--- a/tests/suites/test_suite_mpi.function
+++ b/tests/suites/test_suite_mpi.function
@@ -823,7 +823,8 @@
         TEST_ASSERT( mpi_is_prime( &X, rnd_std_rand, NULL ) == 0 );
         if( safe )
         {
-            mpi_shift_r( &X, 1 ); /* X = ( X - 1 ) / 2 */
+            /* X = ( X - 1 ) / 2 */
+            TEST_ASSERT( mpi_shift_r( &X, 1 ) == 0 );
             TEST_ASSERT( mpi_is_prime( &X, rnd_std_rand, NULL ) == 0 );
         }
     }