From 0768585d2db6bac9e138bbc0901ffec196a75148 Mon Sep 17 00:00:00 2001
From: Adam Langley <agl@chromium.org>
Date: Tue, 23 Apr 2013 15:12:36 -0400
Subject: [PATCH 09/11] ec_private_key_dont_crash

This change saves several EC routines from crashing when an EC_KEY is
missing a public key. The public key is optional in the EC private key
format and, without this patch, running the following through `openssl
ec` causes a crash:

-----BEGIN EC PRIVATE KEY-----
MBkCAQEECAECAwQFBgcIoAoGCCqGSM49AwEH
-----END EC PRIVATE KEY-----
---
 crypto/ec/ec_ameth.c | 15 +++++++++------
 crypto/ec/ec_asn1.c  |  2 +-
 2 files changed, 10 insertions(+), 7 deletions(-)

diff --git a/crypto/ec/ec_ameth.c b/crypto/ec/ec_ameth.c
index 0ce4524..02e7a6f 100644
--- a/crypto/ec/ec_ameth.c
+++ b/crypto/ec/ec_ameth.c
@@ -452,14 +452,17 @@ static int do_EC_KEY_print(BIO *bp, const EC_KEY *x, int off, int ktype)
 	if (ktype > 0)
 		{
 		public_key = EC_KEY_get0_public_key(x);
-		if ((pub_key = EC_POINT_point2bn(group, public_key,
-			EC_KEY_get_conv_form(x), NULL, ctx)) == NULL)
+		if (public_key != NULL)
 			{
-			reason = ERR_R_EC_LIB;
-			goto err;
+			if ((pub_key = EC_POINT_point2bn(group, public_key,
+				EC_KEY_get_conv_form(x), NULL, ctx)) == NULL)
+				{
+				reason = ERR_R_EC_LIB;
+				goto err;
+				}
+			if (pub_key)
+				buf_len = (size_t)BN_num_bytes(pub_key);
 			}
-		if (pub_key)
-			buf_len = (size_t)BN_num_bytes(pub_key);
 		}
 
 	if (ktype == 2)
diff --git a/crypto/ec/ec_asn1.c b/crypto/ec/ec_asn1.c
index 145807b..8c29681 100644
--- a/crypto/ec/ec_asn1.c
+++ b/crypto/ec/ec_asn1.c
@@ -1277,7 +1277,7 @@ int	i2d_ECPrivateKey(EC_KEY *a, unsigned char **out)
 			}
 		}
 
-	if (!(a->enc_flag & EC_PKEY_NO_PUBKEY))
+	if (!(a->enc_flag & EC_PKEY_NO_PUBKEY) && a->pub_key != NULL)
 		{
 		priv_key->publicKey = M_ASN1_BIT_STRING_new();
 		if (priv_key->publicKey == NULL)
-- 
1.8.2.1

