Reset the HKDF state between operations
[openssl.git] / crypto / kdf / hkdf.c
index 25a173826edb2b1faa24682a48ca544205fbd963..ae46fad609ac994cc732a64bc11b5075cb8ddeb4 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -48,9 +48,10 @@ static int pkey_hkdf_init(EVP_PKEY_CTX *ctx)
 {
     HKDF_PKEY_CTX *kctx;
 
-    kctx = OPENSSL_zalloc(sizeof(*kctx));
-    if (kctx == NULL)
+    if ((kctx = OPENSSL_zalloc(sizeof(*kctx))) == NULL) {
+        KDFerr(KDF_F_PKEY_HKDF_INIT, ERR_R_MALLOC_FAILURE);
         return 0;
+    }
 
     ctx->data = kctx;
 
@@ -150,7 +151,7 @@ static int pkey_hkdf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type,
 
     if (strcmp(type, "md") == 0)
         return EVP_PKEY_CTX_md(ctx, EVP_PKEY_OP_DERIVE,
-                EVP_PKEY_CTRL_HKDF_MD, value);
+                               EVP_PKEY_CTRL_HKDF_MD, value);
 
     if (strcmp(type, "salt") == 0)
         return EVP_PKEY_CTX_str2ctrl(ctx, EVP_PKEY_CTRL_HKDF_SALT, value);
@@ -174,6 +175,18 @@ static int pkey_hkdf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type,
     return -2;
 }
 
+static int pkey_hkdf_derive_init(EVP_PKEY_CTX *ctx)
+{
+    HKDF_PKEY_CTX *kctx = ctx->data;
+
+    OPENSSL_clear_free(kctx->key, kctx->key_len);
+    OPENSSL_clear_free(kctx->salt, kctx->salt_len);
+    OPENSSL_cleanse(kctx->info, kctx->info_len);
+    memset(kctx, 0, sizeof(*kctx));
+
+    return 1;
+}
+
 static int pkey_hkdf_derive(EVP_PKEY_CTX *ctx, unsigned char *key,
                             size_t *keylen)
 {
@@ -235,7 +248,7 @@ const EVP_PKEY_METHOD hkdf_pkey_meth = {
 
     0, 0,
 
-    0,
+    pkey_hkdf_derive_init,
     pkey_hkdf_derive,
     pkey_hkdf_ctrl,
     pkey_hkdf_ctrl_str
@@ -280,6 +293,7 @@ static unsigned char *HKDF_Expand(const EVP_MD *evp_md,
                                   unsigned char *okm, size_t okm_len)
 {
     HMAC_CTX *hmac;
+    unsigned char *ret = NULL;
 
     unsigned int i;
 
@@ -329,11 +343,10 @@ static unsigned char *HKDF_Expand(const EVP_MD *evp_md,
 
         done_len += copy_len;
     }
-
-    HMAC_CTX_free(hmac);
-    return okm;
+    ret = okm;
 
  err:
+    OPENSSL_cleanse(prev, sizeof(prev));
     HMAC_CTX_free(hmac);
-    return NULL;
+    return ret;
 }