Fix a failure to NULL a pointer freed on error.

Reported by the LibreSSL project as a follow on to CVE-2015-0209

(Imported from upstream's 5e5d53d341fd9a9b9cc0a58eb3690832ca7a511f.)

Change-Id: Ic2e5dc5c96e316c55f76bedc6ea55b416be3287a
Reviewed-on: https://boringssl-review.googlesource.com/4049
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/ec/ec_asn1.c b/crypto/ec/ec_asn1.c
index ab52389..87e91e1 100644
--- a/crypto/ec/ec_asn1.c
+++ b/crypto/ec/ec_asn1.c
@@ -509,18 +509,21 @@
       OPENSSL_PUT_ERROR(EC, d2i_ECParameters, ERR_R_MALLOC_FAILURE);
       return NULL;
     }
-    if (key) {
-      *key = ret;
-    }
   } else {
     ret = *key;
   }
 
   if (!d2i_ECPKParameters(&ret->group, inp, len)) {
     OPENSSL_PUT_ERROR(EC, d2i_ECParameters, ERR_R_EC_LIB);
+    if (key == NULL || *key == NULL) {
+      EC_KEY_free(ret);
+    }
     return NULL;
   }
 
+  if (key) {
+    *key = ret;
+  }
   return ret;
 }
 
diff --git a/crypto/x509/x_x509.c b/crypto/x509/x_x509.c
index 5cda3c7..00d4a6a 100644
--- a/crypto/x509/x_x509.c
+++ b/crypto/x509/x_x509.c
@@ -171,8 +171,13 @@
 {
 	const unsigned char *q;
 	X509 *ret;
+	int freeret = 0;
+
 	/* Save start position */
 	q = *pp;
+
+	if (!a || *a == NULL)
+		freeret = 1;
 	ret = d2i_X509(a, pp, length);
 	/* If certificate unreadable then forget it */
 	if(!ret) return NULL;
@@ -182,7 +187,12 @@
 	if(!d2i_X509_CERT_AUX(&ret->aux, pp, length)) goto err;
 	return ret;
 	err:
-	X509_free(ret);
+	if (freeret)
+		{
+		X509_free(ret);
+		if (a)
+			*a = NULL;
+		}
 	return NULL;
 }