EVP: fix memleak in evp_pkey_downgrade()
[openssl.git] / crypto / evp / p_open.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "internal/cryptlib.h"
11 #ifdef OPENSSL_NO_RSA
12 NON_EMPTY_TRANSLATION_UNIT
13 #else
14
15 # include <stdio.h>
16 # include <openssl/evp.h>
17 # include <openssl/objects.h>
18 # include <openssl/x509.h>
19 # include <openssl/rsa.h>
20
21 int EVP_OpenInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
22                  const unsigned char *ek, int ekl, const unsigned char *iv,
23                  EVP_PKEY *priv)
24 {
25     unsigned char *key = NULL;
26     size_t keylen = 0;
27     int ret = 0;
28     EVP_PKEY_CTX *pctx = NULL;
29
30     if (type) {
31         EVP_CIPHER_CTX_reset(ctx);
32         if (!EVP_DecryptInit_ex(ctx, type, NULL, NULL, NULL))
33             goto err;
34     }
35
36     if (priv == NULL)
37         return 1;
38
39     if ((pctx = EVP_PKEY_CTX_new(priv, NULL)) == NULL) {
40         ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
41         goto err;
42     }
43
44     if (EVP_PKEY_decrypt_init(pctx) <= 0
45         || EVP_PKEY_decrypt(pctx, NULL, &keylen, ek, ekl) <= 0)
46         goto err;
47
48     if ((key = OPENSSL_malloc(keylen)) == NULL) {
49         ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
50         goto err;
51     }
52
53     if (EVP_PKEY_decrypt(pctx, key, &keylen, ek, ekl) <= 0)
54         goto err;
55
56     if (!EVP_CIPHER_CTX_set_key_length(ctx, keylen)
57         || !EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv))
58         goto err;
59
60     ret = 1;
61  err:
62     EVP_PKEY_CTX_free(pctx);
63     OPENSSL_clear_free(key, keylen);
64     return ret;
65 }
66
67 int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
68 {
69     int i;
70
71     i = EVP_DecryptFinal_ex(ctx, out, outl);
72     if (i)
73         i = EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL);
74     return i;
75 }
76 #endif