Memory leak and NULL dereference fixes.

PR#3403

(Imported from upstream's e42c208235a86beee16ff0d0e6ca4e164a57d21a)

Change-Id: Ibcdd8c95604f661055bfb1e91b15fd3686a04c0d
diff --git a/crypto/asn1/a_utctm.c b/crypto/asn1/a_utctm.c
index 41f3594..cb29d4c 100644
--- a/crypto/asn1/a_utctm.c
+++ b/crypto/asn1/a_utctm.c
@@ -224,24 +224,29 @@
 	struct tm *ts;
 	struct tm data;
 	size_t len = 20;
+	int free_s = 0;
 
 	if (s == NULL)
+		{
+		free_s = 1;
 		s=M_ASN1_UTCTIME_new();
+		}
 	if (s == NULL)
-		return(NULL);
+		goto err;
+
 
 	ts=OPENSSL_gmtime(&t, &data);
 	if (ts == NULL)
-		return(NULL);
+		goto err;
 
 	if (offset_day || offset_sec)
 		{ 
 		if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
-			return NULL;
+			goto err;
 		}
 
 	if((ts->tm_year < 50) || (ts->tm_year >= 150))
-		return NULL;
+		goto err;
 
 	p=(char *)s->data;
 	if ((p == NULL) || ((size_t)s->length < len))
@@ -250,7 +255,7 @@
 		if (p == NULL)
 			{
 			OPENSSL_PUT_ERROR(ASN1, ASN1_UTCTIME_adj, ERR_R_MALLOC_FAILURE);
-			return(NULL);
+			goto err;
 			}
 		if (s->data != NULL)
 			OPENSSL_free(s->data);
@@ -262,6 +267,10 @@
 	s->length=strlen(p);
 	s->type=V_ASN1_UTCTIME;
 	return(s);
+	err:
+	if (free_s && s)
+		M_ASN1_UTCTIME_free(s);
+	return NULL;
 	}
 
 
diff --git a/crypto/asn1/bio_asn1.c b/crypto/asn1/bio_asn1.c
index 5658839..38787a8 100644
--- a/crypto/asn1/bio_asn1.c
+++ b/crypto/asn1/bio_asn1.c
@@ -151,7 +151,10 @@
 	if (!ctx)
 		return 0;
 	if (!asn1_bio_init(ctx, DEFAULT_ASN1_BUF_SIZE))
+		{
+		OPENSSL_free(ctx);
 		return 0;
+		}
 	b->init = 1;
 	b->ptr = (char *)ctx;
 	b->flags = 0;
diff --git a/crypto/asn1/tasn_enc.c b/crypto/asn1/tasn_enc.c
index 5912e01..54f784a 100644
--- a/crypto/asn1/tasn_enc.c
+++ b/crypto/asn1/tasn_enc.c
@@ -450,9 +450,14 @@
 			{
 			derlst = OPENSSL_malloc(sk_ASN1_VALUE_num(sk)
 						* sizeof(*derlst));
-			tmpdat = OPENSSL_malloc(skcontlen);
-			if (!derlst || !tmpdat)
+			if (!derlst)
 				return 0;
+			tmpdat = OPENSSL_malloc(skcontlen);
+			if (!tmpdat)
+				{
+				OPENSSL_free(derlst);
+				return 0;
+				}
 			}
 		}
 	/* If not sorting just output each item */
diff --git a/crypto/pkcs8/p5_pbev2.c b/crypto/pkcs8/p5_pbev2.c
index 66746df..85170a4 100644
--- a/crypto/pkcs8/p5_pbev2.c
+++ b/crypto/pkcs8/p5_pbev2.c
@@ -88,7 +88,11 @@
 	ASN1_STRING *os;
 
 	if ((os=M_ASN1_OCTET_STRING_new()) == NULL) return(0);
-	if (!M_ASN1_OCTET_STRING_set(os,data,len)) return(0);
+	if (!M_ASN1_OCTET_STRING_set(os,data,len))
+		{
+		M_ASN1_OCTET_STRING_free(os);
+		return 0;
+		}
 	ASN1_TYPE_set(a,V_ASN1_OCTET_STRING,os);
 	return(1);
 	}
diff --git a/crypto/x509/t_x509.c b/crypto/x509/t_x509.c
index 91a52de..3a28e33 100644
--- a/crypto/x509/t_x509.c
+++ b/crypto/x509/t_x509.c
@@ -463,6 +463,8 @@
 	l=80-2-obase;
 
 	b=X509_NAME_oneline(name,NULL,0);
+	if (!b)
+		return 0;
 	if (!*b)
 		{
 		OPENSSL_free(b);