Fix memory leak in i2b_PVK in error handling.
authorbcook <bcook@openbsd.org>
Sun, 5 Aug 2018 11:19:25 +0000 (11:19 +0000)
committerbcook <bcook@openbsd.org>
Sun, 5 Aug 2018 11:19:25 +0000 (11:19 +0000)
Simplify parameter checks since this is only called from one place.
Found by Coverity, CID 183502.

ok beck@

lib/libcrypto/pem/pvkfmt.c

index 18de5d5..76cc6fe 100644 (file)
@@ -1,4 +1,4 @@
-/* $OpenBSD: pvkfmt.c,v 1.19 2017/05/02 03:59:44 deraadt Exp $ */
+/* $OpenBSD: pvkfmt.c,v 1.20 2018/08/05 11:19:25 bcook Exp $ */
 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
  * project 2005.
  */
@@ -847,17 +847,10 @@ i2b_PVK(unsigned char **out, EVP_PKEY*pk, int enclevel, pem_password_cb *cb,
        if (pklen < 0)
                return -1;
        outlen += pklen;
-       if (!out)
-               return outlen;
-       if (*out)
-               p = *out;
-       else {
-               p = malloc(outlen);
-               if (!p) {
-                       PEMerror(ERR_R_MALLOC_FAILURE);
-                       return -1;
-               }
-               *out = p;
+       p = malloc(outlen);
+       if (!p) {
+               PEMerror(ERR_R_MALLOC_FAILURE);
+               return -1;
        }
 
        write_ledword(&p, MS_PVKMAGIC);
@@ -875,9 +868,10 @@ i2b_PVK(unsigned char **out, EVP_PKEY*pk, int enclevel, pem_password_cb *cb,
                p += PVK_SALTLEN;
        }
        do_i2b(&p, pk, 0);
-       if (enclevel == 0)
+       if (enclevel == 0) {
+               *out = p;
                return outlen;
-       else {
+       else {
                char psbuf[PEM_BUFSIZE];
                unsigned char keybuf[20];
                int enctmplen, inlen;
@@ -904,10 +898,12 @@ i2b_PVK(unsigned char **out, EVP_PKEY*pk, int enclevel, pem_password_cb *cb,
                        goto error;
        }
        EVP_CIPHER_CTX_cleanup(&cctx);
+       *out = p;
        return outlen;
 
 error:
        EVP_CIPHER_CTX_cleanup(&cctx);
+       free(p);
        return -1;
 }