Fix a couple more malloc test crashes.

The ex_data index may fail to be allocated. Also don't leave a dangling pointer
in handshake_dgst if EVP_DigestInit_ex fails and check a few more init function
failures.

Change-Id: I2e99a89b2171c9d73ccc925a2f35651af34ac5fb
Reviewed-on: https://boringssl-review.googlesource.com/2342
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/ssl/s3_enc.c b/ssl/s3_enc.c
index 2474934..393db77 100644
--- a/ssl/s3_enc.c
+++ b/ssl/s3_enc.c
@@ -300,7 +300,8 @@
 
 	memcpy(mac_secret,ms,i);
 
-	EVP_CipherInit_ex(dd,c,NULL,key,iv,(which & SSL3_CC_WRITE));
+	if (!EVP_CipherInit_ex(dd,c,NULL,key,iv,(which & SSL3_CC_WRITE)))
+		goto err2;
 
 #ifdef OPENSSL_SSL_TRACE_CRYPTO
 	if (s->msg_callback)
@@ -561,6 +562,7 @@
 			if (!EVP_DigestInit_ex(s->s3->handshake_dgst[i], md, NULL))
 				{
 				EVP_MD_CTX_destroy(s->s3->handshake_dgst[i]);
+				s->s3->handshake_dgst[i] = NULL;
 				OPENSSL_PUT_ERROR(SSL, ssl3_digest_cached_records, ERR_LIB_EVP);
 				return 0;
 				}
diff --git a/ssl/ssl_lib.c b/ssl/ssl_lib.c
index ee66093..40ea252 100644
--- a/ssl/ssl_lib.c
+++ b/ssl/ssl_lib.c
@@ -3167,9 +3167,11 @@
 {
 	ssl_clear_hash_ctx(hash);
 	*hash = EVP_MD_CTX_create();
-	if (md != NULL && *hash != NULL)
+	if (md != NULL && *hash != NULL &&
+		!EVP_DigestInit_ex(*hash, md, NULL))
 		{
-		EVP_DigestInit_ex(*hash,md,NULL);
+		EVP_MD_CTX_destroy(*hash);
+		*hash = NULL;
 		}
 	return *hash;
 }
diff --git a/ssl/t1_lib.c b/ssl/t1_lib.c
index ffd80d8..6ba8585 100644
--- a/ssl/t1_lib.c
+++ b/ssl/t1_lib.c
@@ -2397,10 +2397,15 @@
 		/* Check key name matches */
 		if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
 			return 2;
-		HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
-					tlsext_tick_md(), NULL);
-		EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
-				tctx->tlsext_tick_aes_key, etick + 16);
+		if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
+				tlsext_tick_md(), NULL) ||
+			!EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
+				tctx->tlsext_tick_aes_key, etick + 16))
+			{
+			HMAC_CTX_cleanup(&hctx);
+			EVP_CIPHER_CTX_cleanup(&ctx);
+			return -1;
+			}
 		}
 	/* Attempt to process session ticket, first conduct sanity and
 	 * integrity checks on ticket.
@@ -2408,6 +2413,7 @@
 	mlen = HMAC_size(&hctx);
 	if (mlen < 0)
 		{
+		HMAC_CTX_cleanup(&hctx);
 		EVP_CIPHER_CTX_cleanup(&ctx);
 		return -1;
 		}
diff --git a/ssl/test/bssl_shim.cc b/ssl/test/bssl_shim.cc
index 9f9fac3..4239ee3 100644
--- a/ssl/test/bssl_shim.cc
+++ b/ssl/test/bssl_shim.cc
@@ -669,6 +669,9 @@
     return 1;
   }
   g_ex_data_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
+  if (g_ex_data_index < 0) {
+    return 1;
+  }
 
   TestConfig config;
   if (!ParseConfig(argc - 1, argv + 1, &config)) {