Move KDFs to the provider.
authorPauli <paul.dale@oracle.com>
Tue, 20 Aug 2019 22:00:12 +0000 (08:00 +1000)
committerPauli <paul.dale@oracle.com>
Fri, 6 Sep 2019 09:27:57 +0000 (19:27 +1000)
Reviewed-by: Richard Levitte <levitte@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/9662)

15 files changed:
crypto/kdf/hkdf.c [deleted file]
crypto/kdf/pbkdf2.c [deleted file]
crypto/kdf/scrypt.c [deleted file]
crypto/kdf/sshkdf.c [deleted file]
crypto/kdf/sskdf.c [deleted file]
crypto/kdf/tls1_prf.c [deleted file]
crypto/kdf/x942kdf.c [deleted file]
providers/common/kdfs/build.info [new file with mode: 0644]
providers/common/kdfs/hkdf.c [new file with mode: 0644]
providers/common/kdfs/pbkdf2.c [new file with mode: 0644]
providers/common/kdfs/scrypt.c [new file with mode: 0644]
providers/common/kdfs/sshkdf.c [new file with mode: 0644]
providers/common/kdfs/sskdf.c [new file with mode: 0644]
providers/common/kdfs/tls1_prf.c [new file with mode: 0644]
providers/common/kdfs/x942kdf.c [new file with mode: 0644]

diff --git a/crypto/kdf/hkdf.c b/crypto/kdf/hkdf.c
deleted file mode 100644 (file)
index 33c74da..0000000
+++ /dev/null
@@ -1,440 +0,0 @@
-/*
- * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
- *
- * Licensed under the Apache License 2.0 (the "License").  You may not use
- * this file except in compliance with the License.  You can obtain a copy
- * in the file LICENSE in the source distribution or at
- * https://www.openssl.org/source/license.html
- */
-
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <openssl/hmac.h>
-#include <openssl/evp.h>
-#include <openssl/kdf.h>
-#include "internal/cryptlib.h"
-#include "internal/numbers.h"
-#include "internal/evp_int.h"
-#include "kdf_local.h"
-
-#define HKDF_MAXBUF 1024
-
-static void kdf_hkdf_reset(EVP_KDF_IMPL *impl);
-static int HKDF(const EVP_MD *evp_md,
-                const unsigned char *salt, size_t salt_len,
-                const unsigned char *key, size_t key_len,
-                const unsigned char *info, size_t info_len,
-                unsigned char *okm, size_t okm_len);
-static int HKDF_Extract(const EVP_MD *evp_md,
-                        const unsigned char *salt, size_t salt_len,
-                        const unsigned char *ikm, size_t ikm_len,
-                        unsigned char *prk, size_t prk_len);
-static int HKDF_Expand(const EVP_MD *evp_md,
-                       const unsigned char *prk, size_t prk_len,
-                       const unsigned char *info, size_t info_len,
-                       unsigned char *okm, size_t okm_len);
-
-struct evp_kdf_impl_st {
-    int mode;
-    const EVP_MD *md;
-    unsigned char *salt;
-    size_t salt_len;
-    unsigned char *key;
-    size_t key_len;
-    unsigned char info[HKDF_MAXBUF];
-    size_t info_len;
-};
-
-static EVP_KDF_IMPL *kdf_hkdf_new(void)
-{
-    EVP_KDF_IMPL *impl;
-
-    if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
-        KDFerr(KDF_F_KDF_HKDF_NEW, ERR_R_MALLOC_FAILURE);
-    return impl;
-}
-
-static void kdf_hkdf_free(EVP_KDF_IMPL *impl)
-{
-    kdf_hkdf_reset(impl);
-    OPENSSL_free(impl);
-}
-
-static void kdf_hkdf_reset(EVP_KDF_IMPL *impl)
-{
-    OPENSSL_free(impl->salt);
-    OPENSSL_clear_free(impl->key, impl->key_len);
-    OPENSSL_cleanse(impl->info, impl->info_len);
-    memset(impl, 0, sizeof(*impl));
-}
-
-static int kdf_hkdf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
-{
-    const unsigned char *p;
-    size_t len;
-    const EVP_MD *md;
-
-    switch (cmd) {
-    case EVP_KDF_CTRL_SET_MD:
-        md = va_arg(args, const EVP_MD *);
-        if (md == NULL)
-            return 0;
-
-        impl->md = md;
-        return 1;
-
-    case EVP_KDF_CTRL_SET_HKDF_MODE:
-        impl->mode = va_arg(args, int);
-        return 1;
-
-    case EVP_KDF_CTRL_SET_SALT:
-        p = va_arg(args, const unsigned char *);
-        len = va_arg(args, size_t);
-        if (len == 0 || p == NULL)
-            return 1;
-
-        OPENSSL_free(impl->salt);
-        impl->salt = OPENSSL_memdup(p, len);
-        if (impl->salt == NULL)
-            return 0;
-
-        impl->salt_len = len;
-        return 1;
-
-    case EVP_KDF_CTRL_SET_KEY:
-        p = va_arg(args, const unsigned char *);
-        len = va_arg(args, size_t);
-        OPENSSL_clear_free(impl->key, impl->key_len);
-        impl->key = OPENSSL_memdup(p, len);
-        if (impl->key == NULL)
-            return 0;
-
-        impl->key_len  = len;
-        return 1;
-
-    case EVP_KDF_CTRL_RESET_HKDF_INFO:
-        OPENSSL_cleanse(impl->info, impl->info_len);
-        impl->info_len = 0;
-        return 1;
-
-    case EVP_KDF_CTRL_ADD_HKDF_INFO:
-        p = va_arg(args, const unsigned char *);
-        len = va_arg(args, size_t);
-        if (len == 0 || p == NULL)
-            return 1;
-
-        if (len > (HKDF_MAXBUF - impl->info_len))
-            return 0;
-
-        memcpy(impl->info + impl->info_len, p, len);
-        impl->info_len += len;
-        return 1;
-
-    default:
-        return -2;
-    }
-}
-
-static int kdf_hkdf_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
-                             const char *value)
-{
-    if (strcmp(type, "mode") == 0) {
-        int mode;
-
-        if (strcmp(value, "EXTRACT_AND_EXPAND") == 0)
-            mode = EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND;
-        else if (strcmp(value, "EXTRACT_ONLY") == 0)
-            mode = EVP_KDF_HKDF_MODE_EXTRACT_ONLY;
-        else if (strcmp(value, "EXPAND_ONLY") == 0)
-            mode = EVP_KDF_HKDF_MODE_EXPAND_ONLY;
-        else
-            return 0;
-
-        return call_ctrl(kdf_hkdf_ctrl, impl, EVP_KDF_CTRL_SET_HKDF_MODE, mode);
-    }
-
-    if (strcmp(type, "digest") == 0)
-        return kdf_md2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
-
-    if (strcmp(type, "salt") == 0)
-        return kdf_str2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
-
-    if (strcmp(type, "hexsalt") == 0)
-        return kdf_hex2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
-
-    if (strcmp(type, "key") == 0)
-        return kdf_str2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_KEY, value);
-
-    if (strcmp(type, "hexkey") == 0)
-        return kdf_hex2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_KEY, value);
-
-    if (strcmp(type, "info") == 0)
-        return kdf_str2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_ADD_HKDF_INFO,
-                            value);
-
-    if (strcmp(type, "hexinfo") == 0)
-        return kdf_hex2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_ADD_HKDF_INFO,
-                            value);
-
-    return -2;
-}
-
-static size_t kdf_hkdf_size(EVP_KDF_IMPL *impl)
-{
-    int sz;
-
-    if (impl->mode != EVP_KDF_HKDF_MODE_EXTRACT_ONLY)
-        return SIZE_MAX;
-
-    if (impl->md == NULL) {
-        KDFerr(KDF_F_KDF_HKDF_SIZE, KDF_R_MISSING_MESSAGE_DIGEST);
-        return 0;
-    }
-    sz = EVP_MD_size(impl->md);
-    if (sz < 0)
-        return 0;
-
-    return sz;
-}
-
-static int kdf_hkdf_derive(EVP_KDF_IMPL *impl, unsigned char *key,
-                           size_t keylen)
-{
-    if (impl->md == NULL) {
-        KDFerr(KDF_F_KDF_HKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
-        return 0;
-    }
-    if (impl->key == NULL) {
-        KDFerr(KDF_F_KDF_HKDF_DERIVE, KDF_R_MISSING_KEY);
-        return 0;
-    }
-
-    switch (impl->mode) {
-    case EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND:
-        return HKDF(impl->md, impl->salt, impl->salt_len, impl->key,
-                    impl->key_len, impl->info, impl->info_len, key,
-                    keylen);
-
-    case EVP_KDF_HKDF_MODE_EXTRACT_ONLY:
-        return HKDF_Extract(impl->md, impl->salt, impl->salt_len, impl->key,
-                            impl->key_len, key, keylen);
-
-    case EVP_KDF_HKDF_MODE_EXPAND_ONLY:
-        return HKDF_Expand(impl->md, impl->key, impl->key_len, impl->info,
-                           impl->info_len, key, keylen);
-
-    default:
-        return 0;
-    }
-}
-
-const EVP_KDF hkdf_kdf_meth = {
-    EVP_KDF_HKDF,
-    kdf_hkdf_new,
-    kdf_hkdf_free,
-    kdf_hkdf_reset,
-    kdf_hkdf_ctrl,
-    kdf_hkdf_ctrl_str,
-    kdf_hkdf_size,
-    kdf_hkdf_derive
-};
-
-/*
- * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
- * Section 2 (https://tools.ietf.org/html/rfc5869#section-2) and
- * "Cryptographic Extraction and Key Derivation: The HKDF Scheme"
- * Section 4.2 (https://eprint.iacr.org/2010/264.pdf).
- *
- * From the paper:
- *   The scheme HKDF is specified as:
- *     HKDF(XTS, SKM, CTXinfo, L) = K(1) | K(2) | ... | K(t)
- *
- *     where:
- *       SKM is source key material
- *       XTS is extractor salt (which may be null or constant)
- *       CTXinfo is context information (may be null)
- *       L is the number of key bits to be produced by KDF
- *       k is the output length in bits of the hash function used with HMAC
- *       t = ceil(L/k)
- *       the value K(t) is truncated to its first d = L mod k bits.
- *
- * From RFC 5869:
- *   2.2.  Step 1: Extract
- *     HKDF-Extract(salt, IKM) -> PRK
- *   2.3.  Step 2: Expand
- *     HKDF-Expand(PRK, info, L) -> OKM
- */
-static int HKDF(const EVP_MD *evp_md,
-                const unsigned char *salt, size_t salt_len,
-                const unsigned char *ikm, size_t ikm_len,
-                const unsigned char *info, size_t info_len,
-                unsigned char *okm, size_t okm_len)
-{
-    unsigned char prk[EVP_MAX_MD_SIZE];
-    int ret, sz;
-    size_t prk_len;
-
-    sz = EVP_MD_size(evp_md);
-    if (sz < 0)
-        return 0;
-    prk_len = (size_t)sz;
-
-    /* Step 1: HKDF-Extract(salt, IKM) -> PRK */
-    if (!HKDF_Extract(evp_md, salt, salt_len, ikm, ikm_len, prk, prk_len))
-        return 0;
-
-    /* Step 2: HKDF-Expand(PRK, info, L) -> OKM */
-    ret = HKDF_Expand(evp_md, prk, prk_len, info, info_len, okm, okm_len);
-    OPENSSL_cleanse(prk, sizeof(prk));
-
-    return ret;
-}
-
-/*
- * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
- * Section 2.2 (https://tools.ietf.org/html/rfc5869#section-2.2).
- *
- * 2.2.  Step 1: Extract
- *
- *   HKDF-Extract(salt, IKM) -> PRK
- *
- *   Options:
- *      Hash     a hash function; HashLen denotes the length of the
- *               hash function output in octets
- *
- *   Inputs:
- *      salt     optional salt value (a non-secret random value);
- *               if not provided, it is set to a string of HashLen zeros.
- *      IKM      input keying material
- *
- *   Output:
- *      PRK      a pseudorandom key (of HashLen octets)
- *
- *   The output PRK is calculated as follows:
- *
- *   PRK = HMAC-Hash(salt, IKM)
- */
-static int HKDF_Extract(const EVP_MD *evp_md,
-                        const unsigned char *salt, size_t salt_len,
-                        const unsigned char *ikm, size_t ikm_len,
-                        unsigned char *prk, size_t prk_len)
-{
-    int sz = EVP_MD_size(evp_md);
-
-    if (sz < 0)
-        return 0;
-    if (prk_len != (size_t)sz) {
-        KDFerr(KDF_F_HKDF_EXTRACT, KDF_R_WRONG_OUTPUT_BUFFER_SIZE);
-        return 0;
-    }
-    /* calc: PRK = HMAC-Hash(salt, IKM) */
-    return HMAC(evp_md, salt, salt_len, ikm, ikm_len, prk, NULL) != NULL;
-}
-
-/*
- * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
- * Section 2.3 (https://tools.ietf.org/html/rfc5869#section-2.3).
- *
- * 2.3.  Step 2: Expand
- *
- *   HKDF-Expand(PRK, info, L) -> OKM
- *
- *   Options:
- *      Hash     a hash function; HashLen denotes the length of the
- *               hash function output in octets
- *
- *   Inputs:
- *      PRK      a pseudorandom key of at least HashLen octets
- *               (usually, the output from the extract step)
- *      info     optional context and application specific information
- *               (can be a zero-length string)
- *      L        length of output keying material in octets
- *               (<= 255*HashLen)
- *
- *   Output:
- *      OKM      output keying material (of L octets)
- *
- *   The output OKM is calculated as follows:
- *
- *   N = ceil(L/HashLen)
- *   T = T(1) | T(2) | T(3) | ... | T(N)
- *   OKM = first L octets of T
- *
- *   where:
- *   T(0) = empty string (zero length)
- *   T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
- *   T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
- *   T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
- *   ...
- *
- *   (where the constant concatenated to the end of each T(n) is a
- *   single octet.)
- */
-static int HKDF_Expand(const EVP_MD *evp_md,
-                       const unsigned char *prk, size_t prk_len,
-                       const unsigned char *info, size_t info_len,
-                       unsigned char *okm, size_t okm_len)
-{
-    HMAC_CTX *hmac;
-    int ret = 0, sz;
-    unsigned int i;
-    unsigned char prev[EVP_MAX_MD_SIZE];
-    size_t done_len = 0, dig_len, n;
-
-    sz = EVP_MD_size(evp_md);
-    if (sz <= 0)
-        return 0;
-    dig_len = (size_t)sz;
-
-    /* calc: N = ceil(L/HashLen) */
-    n = okm_len / dig_len;
-    if (okm_len % dig_len)
-        n++;
-
-    if (n > 255 || okm == NULL)
-        return 0;
-
-    if ((hmac = HMAC_CTX_new()) == NULL)
-        return 0;
-
-    if (!HMAC_Init_ex(hmac, prk, prk_len, evp_md, NULL))
-        goto err;
-
-    for (i = 1; i <= n; i++) {
-        size_t copy_len;
-        const unsigned char ctr = i;
-
-        /* calc: T(i) = HMAC-Hash(PRK, T(i - 1) | info | i) */
-        if (i > 1) {
-            if (!HMAC_Init_ex(hmac, NULL, 0, NULL, NULL))
-                goto err;
-
-            if (!HMAC_Update(hmac, prev, dig_len))
-                goto err;
-        }
-
-        if (!HMAC_Update(hmac, info, info_len))
-            goto err;
-
-        if (!HMAC_Update(hmac, &ctr, 1))
-            goto err;
-
-        if (!HMAC_Final(hmac, prev, NULL))
-            goto err;
-
-        copy_len = (done_len + dig_len > okm_len) ?
-                       okm_len - done_len :
-                       dig_len;
-
-        memcpy(okm + done_len, prev, copy_len);
-
-        done_len += copy_len;
-    }
-    ret = 1;
-
- err:
-    OPENSSL_cleanse(prev, sizeof(prev));
-    HMAC_CTX_free(hmac);
-    return ret;
-}
diff --git a/crypto/kdf/pbkdf2.c b/crypto/kdf/pbkdf2.c
deleted file mode 100644 (file)
index d416897..0000000
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- * Copyright 2018-2019 The OpenSSL Project Authors. All Rights Reserved.
- *
- * Licensed under the Apache License 2.0 (the "License").  You may not use
- * this file except in compliance with the License.  You can obtain a copy
- * in the file LICENSE in the source distribution or at
- * https://www.openssl.org/source/license.html
- */
-
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <openssl/hmac.h>
-#include <openssl/evp.h>
-#include <openssl/kdf.h>
-#include "internal/cryptlib.h"
-#include "internal/evp_int.h"
-#include "kdf_local.h"
-
-/* Constants specified in SP800-132 */
-#define KDF_PBKDF2_MIN_KEY_LEN_BITS  112
-#define KDF_PBKDF2_MAX_KEY_LEN_DIGEST_RATIO 0xFFFFFFFF
-#define KDF_PBKDF2_MIN_ITERATIONS 1000
-#define KDF_PBKDF2_MIN_SALT_LEN   (128 / 8)
-/*
- * For backwards compatibility reasons,
- * Extra checks are done by default in fips mode only.
- */
-#ifdef FIPS_MODE
-# define KDF_PBKDF2_DEFAULT_CHECKS 1
-#else
-# define KDF_PBKDF2_DEFAULT_CHECKS 0
-#endif /* FIPS_MODE */
-
-static void kdf_pbkdf2_reset(EVP_KDF_IMPL *impl);
-static void kdf_pbkdf2_init(EVP_KDF_IMPL *impl);
-static int  pbkdf2_derive(const char *pass, size_t passlen,
-                          const unsigned char *salt, int saltlen, int iter,
-                          const EVP_MD *digest, unsigned char *key,
-                          size_t keylen, int extra_checks);
-
-struct evp_kdf_impl_st {
-    unsigned char *pass;
-    size_t pass_len;
-    unsigned char *salt;
-    size_t salt_len;
-    int iter;
-    const EVP_MD *md;
-    int lower_bound_checks;
-};
-
-static EVP_KDF_IMPL *kdf_pbkdf2_new(void)
-{
-    EVP_KDF_IMPL *impl;
-
-    impl = OPENSSL_zalloc(sizeof(*impl));
-    if (impl == NULL) {
-        KDFerr(KDF_F_KDF_PBKDF2_NEW, ERR_R_MALLOC_FAILURE);
-        return NULL;
-    }
-    kdf_pbkdf2_init(impl);
-    return impl;
-}
-
-static void kdf_pbkdf2_free(EVP_KDF_IMPL *impl)
-{
-    kdf_pbkdf2_reset(impl);
-    OPENSSL_free(impl);
-}
-
-static void kdf_pbkdf2_reset(EVP_KDF_IMPL *impl)
-{
-    OPENSSL_free(impl->salt);
-    OPENSSL_clear_free(impl->pass, impl->pass_len);
-    memset(impl, 0, sizeof(*impl));
-    kdf_pbkdf2_init(impl);
-}
-
-static void kdf_pbkdf2_init(EVP_KDF_IMPL *impl)
-{
-    impl->iter = PKCS5_DEFAULT_ITER;
-    impl->md = EVP_sha1();
-    impl->lower_bound_checks = KDF_PBKDF2_DEFAULT_CHECKS;
-}
-
-static int pbkdf2_set_membuf(unsigned char **buffer, size_t *buflen,
-                             const unsigned char *new_buffer,
-                             size_t new_buflen)
-{
-    if (new_buffer == NULL)
-        return 1;
-
-    OPENSSL_clear_free(*buffer, *buflen);
-
-    if (new_buflen > 0) {
-        *buffer = OPENSSL_memdup(new_buffer, new_buflen);
-    } else {
-        *buffer = OPENSSL_malloc(1);
-    }
-    if (*buffer == NULL) {
-        KDFerr(KDF_F_PBKDF2_SET_MEMBUF, ERR_R_MALLOC_FAILURE);
-        return 0;
-    }
-
-    *buflen = new_buflen;
-    return 1;
-}
-
-static int kdf_pbkdf2_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
-{
-    int iter, pkcs5, min_iter;
-    const unsigned char *p;
-    size_t len;
-    const EVP_MD *md;
-
-    switch (cmd) {
-    case EVP_KDF_CTRL_SET_PBKDF2_PKCS5_MODE:
-        pkcs5 = va_arg(args, int);
-        impl->lower_bound_checks = (pkcs5 == 0) ? 1 : 0;
-        return 1;
-    case EVP_KDF_CTRL_SET_PASS:
-        p = va_arg(args, const unsigned char *);
-        len = va_arg(args, size_t);
-        return pbkdf2_set_membuf(&impl->pass, &impl->pass_len, p, len);
-
-    case EVP_KDF_CTRL_SET_SALT:
-        p = va_arg(args, const unsigned char *);
-        len = va_arg(args, size_t);
-        if (impl->lower_bound_checks != 0 && len < KDF_PBKDF2_MIN_SALT_LEN) {
-            KDFerr(KDF_F_KDF_PBKDF2_CTRL, KDF_R_INVALID_SALT_LEN);
-            return 0;
-        }
-        return pbkdf2_set_membuf(&impl->salt, &impl->salt_len, p, len);
-
-    case EVP_KDF_CTRL_SET_ITER:
-        iter = va_arg(args, int);
-        min_iter = impl->lower_bound_checks != 0 ? KDF_PBKDF2_MIN_ITERATIONS : 1;
-        if (iter < min_iter) {
-            KDFerr(KDF_F_KDF_PBKDF2_CTRL, KDF_R_INVALID_ITERATION_COUNT);
-            return 0;
-        }
-        impl->iter = iter;
-        return 1;
-
-    case EVP_KDF_CTRL_SET_MD:
-        md = va_arg(args, const EVP_MD *);
-        if (md == NULL) {
-            KDFerr(KDF_F_KDF_PBKDF2_CTRL, KDF_R_VALUE_MISSING);
-            return 0;
-        }
-
-        impl->md = md;
-        return 1;
-
-    default:
-        return -2;
-    }
-}
-
-static int kdf_pbkdf2_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
-                               const char *value)
-{
-    if (value == NULL) {
-        KDFerr(KDF_F_KDF_PBKDF2_CTRL_STR, KDF_R_VALUE_MISSING);
-        return 0;
-    }
-
-    if (strcmp(type, "pass") == 0)
-        return kdf_str2ctrl(impl, kdf_pbkdf2_ctrl, EVP_KDF_CTRL_SET_PASS,
-                            value);
-
-    if (strcmp(type, "hexpass") == 0)
-        return kdf_hex2ctrl(impl, kdf_pbkdf2_ctrl, EVP_KDF_CTRL_SET_PASS,
-                            value);
-
-    if (strcmp(type, "salt") == 0)
-        return kdf_str2ctrl(impl, kdf_pbkdf2_ctrl, EVP_KDF_CTRL_SET_SALT,
-                            value);
-
-    if (strcmp(type, "hexsalt") == 0)
-        return kdf_hex2ctrl(impl, kdf_pbkdf2_ctrl, EVP_KDF_CTRL_SET_SALT,
-                            value);
-
-    if (strcmp(type, "iter") == 0)
-        return call_ctrl(kdf_pbkdf2_ctrl, impl, EVP_KDF_CTRL_SET_ITER,
-                         atoi(value));
-
-    if (strcmp(type, "digest") == 0)
-        return kdf_md2ctrl(impl, kdf_pbkdf2_ctrl, EVP_KDF_CTRL_SET_MD, value);
-
-    if (strcmp(type, "pkcs5") == 0)
-        return kdf_str2ctrl(impl, kdf_pbkdf2_ctrl,
-                            EVP_KDF_CTRL_SET_PBKDF2_PKCS5_MODE, value);
-    return -2;
-}
-
-static int kdf_pbkdf2_derive(EVP_KDF_IMPL *impl, unsigned char *key,
-                             size_t keylen)
-{
-    if (impl->pass == NULL) {
-        KDFerr(KDF_F_KDF_PBKDF2_DERIVE, KDF_R_MISSING_PASS);
-        return 0;
-    }
-
-    if (impl->salt == NULL) {
-        KDFerr(KDF_F_KDF_PBKDF2_DERIVE, KDF_R_MISSING_SALT);
-        return 0;
-    }
-
-    return pbkdf2_derive((char *)impl->pass, impl->pass_len,
-                         impl->salt, impl->salt_len, impl->iter,
-                         impl->md, key, keylen, impl->lower_bound_checks);
-}
-
-const EVP_KDF pbkdf2_kdf_meth = {
-    EVP_KDF_PBKDF2,
-    kdf_pbkdf2_new,
-    kdf_pbkdf2_free,
-    kdf_pbkdf2_reset,
-    kdf_pbkdf2_ctrl,
-    kdf_pbkdf2_ctrl_str,
-    NULL,
-    kdf_pbkdf2_derive
-};
-
-/*
- * This is an implementation of PKCS#5 v2.0 password based encryption key
- * derivation function PBKDF2. SHA1 version verified against test vectors
- * posted by Peter Gutmann to the PKCS-TNG mailing list.
- *
- * The constraints specified by SP800-132 have been added i.e.
- *  - Check the range of the key length.
- *  - Minimum iteration count of 1000.
- *  - Randomly-generated portion of the salt shall be at least 128 bits.
- */
-static int pbkdf2_derive(const char *pass, size_t passlen,
-                         const unsigned char *salt, int saltlen, int iter,
-                         const EVP_MD *digest, unsigned char *key,
-                         size_t keylen, int lower_bound_checks)
-{
-    int ret = 0;
-    unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
-    int cplen, j, k, tkeylen, mdlen;
-    unsigned long i = 1;
-    HMAC_CTX *hctx_tpl = NULL, *hctx = NULL;
-
-    mdlen = EVP_MD_size(digest);
-    if (mdlen <= 0)
-        return 0;
-
-    /*
-     * This check should always be done because keylen / mdlen >= (2^32 - 1)
-     * results in an overflow of the loop counter 'i'.
-     */
-    if ((keylen / mdlen) >= KDF_PBKDF2_MAX_KEY_LEN_DIGEST_RATIO) {
-        KDFerr(KDF_F_PBKDF2_DERIVE, KDF_R_INVALID_KEY_LEN);
-        return 0;
-    }
-
-    if (lower_bound_checks) {
-         if ((keylen * 8) < KDF_PBKDF2_MIN_KEY_LEN_BITS) {
-             KDFerr(KDF_F_PBKDF2_DERIVE, KDF_R_INVALID_KEY_LEN);
-             return 0;
-         }
-         if (saltlen < KDF_PBKDF2_MIN_SALT_LEN) {
-             KDFerr(KDF_F_PBKDF2_DERIVE, KDF_R_INVALID_SALT_LEN);
-            return 0;
-         }
-         if (iter < KDF_PBKDF2_MIN_ITERATIONS) {
-             KDFerr(KDF_F_PBKDF2_DERIVE, KDF_R_INVALID_ITERATION_COUNT);
-             return 0;
-         }
-    }
-
-    hctx_tpl = HMAC_CTX_new();
-    if (hctx_tpl == NULL)
-        return 0;
-    p = key;
-    tkeylen = keylen;
-    if (!HMAC_Init_ex(hctx_tpl, pass, passlen, digest, NULL))
-        goto err;
-    hctx = HMAC_CTX_new();
-    if (hctx == NULL)
-        goto err;
-    while (tkeylen) {
-        if (tkeylen > mdlen)
-            cplen = mdlen;
-        else
-            cplen = tkeylen;
-        /*
-         * We are unlikely to ever use more than 256 blocks (5120 bits!) but
-         * just in case...
-         */
-        itmp[0] = (unsigned char)((i >> 24) & 0xff);
-        itmp[1] = (unsigned char)((i >> 16) & 0xff);
-        itmp[2] = (unsigned char)((i >> 8) & 0xff);
-        itmp[3] = (unsigned char)(i & 0xff);
-        if (!HMAC_CTX_copy(hctx, hctx_tpl))
-            goto err;
-        if (!HMAC_Update(hctx, salt, saltlen)
-                || !HMAC_Update(hctx, itmp, 4)
-                || !HMAC_Final(hctx, digtmp, NULL))
-            goto err;
-        memcpy(p, digtmp, cplen);
-        for (j = 1; j < iter; j++) {
-            if (!HMAC_CTX_copy(hctx, hctx_tpl))
-                goto err;
-            if (!HMAC_Update(hctx, digtmp, mdlen)
-                    || !HMAC_Final(hctx, digtmp, NULL))
-                goto err;
-            for (k = 0; k < cplen; k++)
-                p[k] ^= digtmp[k];
-        }
-        tkeylen -= cplen;
-        i++;
-        p += cplen;
-    }
-    ret = 1;
-
-err:
-    HMAC_CTX_free(hctx);
-    HMAC_CTX_free(hctx_tpl);
-    return ret;
-}
diff --git a/crypto/kdf/scrypt.c b/crypto/kdf/scrypt.c
deleted file mode 100644 (file)
index 29ceeb3..0000000
+++ /dev/null
@@ -1,506 +0,0 @@
-/*
- * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
- *
- * Licensed under the Apache License 2.0 (the "License").  You may not use
- * this file except in compliance with the License.  You can obtain a copy
- * in the file LICENSE in the source distribution or at
- * https://www.openssl.org/source/license.html
- */
-
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <openssl/evp.h>
-#include <openssl/kdf.h>
-#include <openssl/err.h>
-#include "internal/evp_int.h"
-#include "internal/numbers.h"
-#include "kdf_local.h"
-
-#ifndef OPENSSL_NO_SCRYPT
-
-static void kdf_scrypt_reset(EVP_KDF_IMPL *impl);
-static void kdf_scrypt_init(EVP_KDF_IMPL *impl);
-static int atou64(const char *nptr, uint64_t *result);
-static int scrypt_alg(const char *pass, size_t passlen,
-                      const unsigned char *salt, size_t saltlen,
-                      uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
-                      unsigned char *key, size_t keylen);
-
-struct evp_kdf_impl_st {
-    unsigned char *pass;
-    size_t pass_len;
-    unsigned char *salt;
-    size_t salt_len;
-    uint64_t N;
-    uint32_t r, p;
-    uint64_t maxmem_bytes;
-};
-
-/* Custom uint64_t parser since we do not have strtoull */
-static int atou64(const char *nptr, uint64_t *result)
-{
-    uint64_t value = 0;
-
-    while (*nptr) {
-        unsigned int digit;
-        uint64_t new_value;
-
-        if ((*nptr < '0') || (*nptr > '9')) {
-            return 0;
-        }
-        digit = (unsigned int)(*nptr - '0');
-        new_value = (value * 10) + digit;
-        if ((new_value < digit) || ((new_value - digit) / 10 != value)) {
-            /* Overflow */
-            return 0;
-        }
-        value = new_value;
-        nptr++;
-    }
-    *result = value;
-    return 1;
-}
-
-static EVP_KDF_IMPL *kdf_scrypt_new(void)
-{
-    EVP_KDF_IMPL *impl;
-
-    impl = OPENSSL_zalloc(sizeof(*impl));
-    if (impl == NULL) {
-        KDFerr(KDF_F_KDF_SCRYPT_NEW, ERR_R_MALLOC_FAILURE);
-        return NULL;
-    }
-    kdf_scrypt_init(impl);
-    return impl;
-}
-
-static void kdf_scrypt_free(EVP_KDF_IMPL *impl)
-{
-    kdf_scrypt_reset(impl);
-    OPENSSL_free(impl);
-}
-
-static void kdf_scrypt_reset(EVP_KDF_IMPL *impl)
-{
-    OPENSSL_free(impl->salt);
-    OPENSSL_clear_free(impl->pass, impl->pass_len);
-    memset(impl, 0, sizeof(*impl));
-    kdf_scrypt_init(impl);
-}
-
-static void kdf_scrypt_init(EVP_KDF_IMPL *impl)
-{
-    /* Default values are the most conservative recommendation given in the
-     * original paper of C. Percival. Derivation uses roughly 1 GiB of memory
-     * for this parameter choice (approx. 128 * r * N * p bytes).
-     */
-    impl->N = 1 << 20;
-    impl->r = 8;
-    impl->p = 1;
-    impl->maxmem_bytes = 1025 * 1024 * 1024;
-}
-
-static int scrypt_set_membuf(unsigned char **buffer, size_t *buflen,
-                             const unsigned char *new_buffer,
-                             size_t new_buflen)
-{
-    if (new_buffer == NULL)
-        return 1;
-
-    OPENSSL_clear_free(*buffer, *buflen);
-
-    if (new_buflen > 0) {
-        *buffer = OPENSSL_memdup(new_buffer, new_buflen);
-    } else {
-        *buffer = OPENSSL_malloc(1);
-    }
-    if (*buffer == NULL) {
-        KDFerr(KDF_F_SCRYPT_SET_MEMBUF, ERR_R_MALLOC_FAILURE);
-        return 0;
-    }
-
-    *buflen = new_buflen;
-    return 1;
-}
-
-static int is_power_of_two(uint64_t value)
-{
-    return (value != 0) && ((value & (value - 1)) == 0);
-}
-
-static int kdf_scrypt_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
-{
-    uint64_t u64_value;
-    uint32_t value;
-    const unsigned char *p;
-    size_t len;
-
-    switch (cmd) {
-    case EVP_KDF_CTRL_SET_PASS:
-        p = va_arg(args, const unsigned char *);
-        len = va_arg(args, size_t);
-        return scrypt_set_membuf(&impl->pass, &impl->pass_len, p, len);
-
-    case EVP_KDF_CTRL_SET_SALT:
-        p = va_arg(args, const unsigned char *);
-        len = va_arg(args, size_t);
-        return scrypt_set_membuf(&impl->salt, &impl->salt_len, p, len);
-
-    case EVP_KDF_CTRL_SET_SCRYPT_N:
-        u64_value = va_arg(args, uint64_t);
-        if ((u64_value <= 1) || !is_power_of_two(u64_value))
-            return 0;
-
-        impl->N = u64_value;
-        return 1;
-
-    case EVP_KDF_CTRL_SET_SCRYPT_R:
-        value = va_arg(args, uint32_t);
-        if (value < 1)
-            return 0;
-
-        impl->r = value;
-        return 1;
-
-    case EVP_KDF_CTRL_SET_SCRYPT_P:
-        value = va_arg(args, uint32_t);
-        if (value < 1)
-            return 0;
-
-        impl->p = value;
-        return 1;
-
-    case EVP_KDF_CTRL_SET_MAXMEM_BYTES:
-        u64_value = va_arg(args, uint64_t);
-        if (u64_value < 1)
-            return 0;
-
-        impl->maxmem_bytes = u64_value;
-        return 1;
-
-    default:
-        return -2;
-    }
-}
-
-static int kdf_scrypt_ctrl_uint32(EVP_KDF_IMPL *impl, int cmd,
-                                  const char *value)
-{
-    int int_value = atoi(value);
-
-    if (int_value < 0 || (uint64_t)int_value > UINT32_MAX) {
-        KDFerr(KDF_F_KDF_SCRYPT_CTRL_UINT32, KDF_R_VALUE_ERROR);
-        return 0;
-    }
-    return call_ctrl(kdf_scrypt_ctrl, impl, cmd, (uint32_t)int_value);
-}
-
-static int kdf_scrypt_ctrl_uint64(EVP_KDF_IMPL *impl, int cmd,
-                                  const char *value)
-{
-    uint64_t u64_value;
-
-    if (!atou64(value, &u64_value)) {
-        KDFerr(KDF_F_KDF_SCRYPT_CTRL_UINT64, KDF_R_VALUE_ERROR);
-        return 0;
-    }
-    return call_ctrl(kdf_scrypt_ctrl, impl, cmd, u64_value);
-}
-
-static int kdf_scrypt_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
-                               const char *value)
-{
-    if (value == NULL) {
-        KDFerr(KDF_F_KDF_SCRYPT_CTRL_STR, KDF_R_VALUE_MISSING);
-        return 0;
-    }
-
-    if (strcmp(type, "pass") == 0)
-        return kdf_str2ctrl(impl, kdf_scrypt_ctrl, EVP_KDF_CTRL_SET_PASS,
-                            value);
-
-    if (strcmp(type, "hexpass") == 0)
-        return kdf_hex2ctrl(impl, kdf_scrypt_ctrl, EVP_KDF_CTRL_SET_PASS,
-                            value);
-
-    if (strcmp(type, "salt") == 0)
-        return kdf_str2ctrl(impl, kdf_scrypt_ctrl, EVP_KDF_CTRL_SET_SALT,
-                            value);
-
-    if (strcmp(type, "hexsalt") == 0)
-        return kdf_hex2ctrl(impl, kdf_scrypt_ctrl, EVP_KDF_CTRL_SET_SALT,
-                            value);
-
-    if (strcmp(type, "N") == 0)
-        return kdf_scrypt_ctrl_uint64(impl, EVP_KDF_CTRL_SET_SCRYPT_N, value);
-
-    if (strcmp(type, "r") == 0)
-        return kdf_scrypt_ctrl_uint32(impl, EVP_KDF_CTRL_SET_SCRYPT_R, value);
-
-    if (strcmp(type, "p") == 0)
-        return kdf_scrypt_ctrl_uint32(impl, EVP_KDF_CTRL_SET_SCRYPT_P, value);
-
-    if (strcmp(type, "maxmem_bytes") == 0)
-        return kdf_scrypt_ctrl_uint64(impl, EVP_KDF_CTRL_SET_MAXMEM_BYTES,
-                                      value);
-
-    return -2;
-}
-
-static int kdf_scrypt_derive(EVP_KDF_IMPL *impl, unsigned char *key,
-                             size_t keylen)
-{
-    if (impl->pass == NULL) {
-        KDFerr(KDF_F_KDF_SCRYPT_DERIVE, KDF_R_MISSING_PASS);
-        return 0;
-    }
-
-    if (impl->salt == NULL) {
-        KDFerr(KDF_F_KDF_SCRYPT_DERIVE, KDF_R_MISSING_SALT);
-        return 0;
-    }
-
-    return scrypt_alg((char *)impl->pass, impl->pass_len, impl->salt,
-                      impl->salt_len, impl->N, impl->r, impl->p,
-                      impl->maxmem_bytes, key, keylen);
-}
-
-const EVP_KDF scrypt_kdf_meth = {
-    EVP_KDF_SCRYPT,
-    kdf_scrypt_new,
-    kdf_scrypt_free,
-    kdf_scrypt_reset,
-    kdf_scrypt_ctrl,
-    kdf_scrypt_ctrl_str,
-    NULL,
-    kdf_scrypt_derive
-};
-
-#define R(a,b) (((a) << (b)) | ((a) >> (32 - (b))))
-static void salsa208_word_specification(uint32_t inout[16])
-{
-    int i;
-    uint32_t x[16];
-
-    memcpy(x, inout, sizeof(x));
-    for (i = 8; i > 0; i -= 2) {
-        x[4] ^= R(x[0] + x[12], 7);
-        x[8] ^= R(x[4] + x[0], 9);
-        x[12] ^= R(x[8] + x[4], 13);
-        x[0] ^= R(x[12] + x[8], 18);
-        x[9] ^= R(x[5] + x[1], 7);
-        x[13] ^= R(x[9] + x[5], 9);
-        x[1] ^= R(x[13] + x[9], 13);
-        x[5] ^= R(x[1] + x[13], 18);
-        x[14] ^= R(x[10] + x[6], 7);
-        x[2] ^= R(x[14] + x[10], 9);
-        x[6] ^= R(x[2] + x[14], 13);
-        x[10] ^= R(x[6] + x[2], 18);
-        x[3] ^= R(x[15] + x[11], 7);
-        x[7] ^= R(x[3] + x[15], 9);
-        x[11] ^= R(x[7] + x[3], 13);
-        x[15] ^= R(x[11] + x[7], 18);
-        x[1] ^= R(x[0] + x[3], 7);
-        x[2] ^= R(x[1] + x[0], 9);
-        x[3] ^= R(x[2] + x[1], 13);
-        x[0] ^= R(x[3] + x[2], 18);
-        x[6] ^= R(x[5] + x[4], 7);
-        x[7] ^= R(x[6] + x[5], 9);
-        x[4] ^= R(x[7] + x[6], 13);
-        x[5] ^= R(x[4] + x[7], 18);
-        x[11] ^= R(x[10] + x[9], 7);
-        x[8] ^= R(x[11] + x[10], 9);
-        x[9] ^= R(x[8] + x[11], 13);
-        x[10] ^= R(x[9] + x[8], 18);
-        x[12] ^= R(x[15] + x[14], 7);
-        x[13] ^= R(x[12] + x[15], 9);
-        x[14] ^= R(x[13] + x[12], 13);
-        x[15] ^= R(x[14] + x[13], 18);
-    }
-    for (i = 0; i < 16; ++i)
-        inout[i] += x[i];
-    OPENSSL_cleanse(x, sizeof(x));
-}
-
-static void scryptBlockMix(uint32_t *B_, uint32_t *B, uint64_t r)
-{
-    uint64_t i, j;
-    uint32_t X[16], *pB;
-
-    memcpy(X, B + (r * 2 - 1) * 16, sizeof(X));
-    pB = B;
-    for (i = 0; i < r * 2; i++) {
-        for (j = 0; j < 16; j++)
-            X[j] ^= *pB++;
-        salsa208_word_specification(X);
-        memcpy(B_ + (i / 2 + (i & 1) * r) * 16, X, sizeof(X));
-    }
-    OPENSSL_cleanse(X, sizeof(X));
-}
-
-static void scryptROMix(unsigned char *B, uint64_t r, uint64_t N,
-                        uint32_t *X, uint32_t *T, uint32_t *V)
-{
-    unsigned char *pB;
-    uint32_t *pV;
-    uint64_t i, k;
-
-    /* Convert from little endian input */
-    for (pV = V, i = 0, pB = B; i < 32 * r; i++, pV++) {
-        *pV = *pB++;
-        *pV |= *pB++ << 8;
-        *pV |= *pB++ << 16;
-        *pV |= (uint32_t)*pB++ << 24;
-    }
-
-    for (i = 1; i < N; i++, pV += 32 * r)
-        scryptBlockMix(pV, pV - 32 * r, r);
-
-    scryptBlockMix(X, V + (N - 1) * 32 * r, r);
-
-    for (i = 0; i < N; i++) {
-        uint32_t j;
-        j = X[16 * (2 * r - 1)] % N;
-        pV = V + 32 * r * j;
-        for (k = 0; k < 32 * r; k++)
-            T[k] = X[k] ^ *pV++;
-        scryptBlockMix(X, T, r);
-    }
-    /* Convert output to little endian */
-    for (i = 0, pB = B; i < 32 * r; i++) {
-        uint32_t xtmp = X[i];
-        *pB++ = xtmp & 0xff;
-        *pB++ = (xtmp >> 8) & 0xff;
-        *pB++ = (xtmp >> 16) & 0xff;
-        *pB++ = (xtmp >> 24) & 0xff;
-    }
-}
-
-#ifndef SIZE_MAX
-# define SIZE_MAX    ((size_t)-1)
-#endif
-
-/*
- * Maximum power of two that will fit in uint64_t: this should work on
- * most (all?) platforms.
- */
-
-#define LOG2_UINT64_MAX         (sizeof(uint64_t) * 8 - 1)
-
-/*
- * Maximum value of p * r:
- * p <= ((2^32-1) * hLen) / MFLen =>
- * p <= ((2^32-1) * 32) / (128 * r) =>
- * p * r <= (2^30-1)
- */
-
-#define SCRYPT_PR_MAX   ((1 << 30) - 1)
-
-static int scrypt_alg(const char *pass, size_t passlen,
-                      const unsigned char *salt, size_t saltlen,
-                      uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
-                      unsigned char *key, size_t keylen)
-{
-    int rv = 0;
-    unsigned char *B;
-    uint32_t *X, *V, *T;
-    uint64_t i, Blen, Vlen;
-
-    /* Sanity check parameters */
-    /* initial check, r,p must be non zero, N >= 2 and a power of 2 */
-    if (r == 0 || p == 0 || N < 2 || (N & (N - 1)))
-        return 0;
-    /* Check p * r < SCRYPT_PR_MAX avoiding overflow */
-    if (p > SCRYPT_PR_MAX / r) {
-        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
-        return 0;
-    }
-
-    /*
-     * Need to check N: if 2^(128 * r / 8) overflows limit this is
-     * automatically satisfied since N <= UINT64_MAX.
-     */
-
-    if (16 * r <= LOG2_UINT64_MAX) {
-        if (N >= (((uint64_t)1) << (16 * r))) {
-            EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
-            return 0;
-        }
-    }
-
-    /* Memory checks: check total allocated buffer size fits in uint64_t */
-
-    /*
-     * B size in section 5 step 1.S
-     * Note: we know p * 128 * r < UINT64_MAX because we already checked
-     * p * r < SCRYPT_PR_MAX
-     */
-    Blen = p * 128 * r;
-    /*
-     * Yet we pass it as integer to PKCS5_PBKDF2_HMAC... [This would
-     * have to be revised when/if PKCS5_PBKDF2_HMAC accepts size_t.]
-     */
-    if (Blen > INT_MAX) {
-        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
-        return 0;
-    }
-
-    /*
-     * Check 32 * r * (N + 2) * sizeof(uint32_t) fits in uint64_t
-     * This is combined size V, X and T (section 4)
-     */
-    i = UINT64_MAX / (32 * sizeof(uint32_t));
-    if (N + 2 > i / r) {
-        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
-        return 0;
-    }
-    Vlen = 32 * r * (N + 2) * sizeof(uint32_t);
-
-    /* check total allocated size fits in uint64_t */
-    if (Blen > UINT64_MAX - Vlen) {
-        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
-        return 0;
-    }
-
-    /* Check that the maximum memory doesn't exceed a size_t limits */
-    if (maxmem > SIZE_MAX)
-        maxmem = SIZE_MAX;
-
-    if (Blen + Vlen > maxmem) {
-        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
-        return 0;
-    }
-
-    /* If no key return to indicate parameters are OK */
-    if (key == NULL)
-        return 1;
-
-    B = OPENSSL_malloc((size_t)(Blen + Vlen));
-    if (B == NULL) {
-        EVPerr(EVP_F_SCRYPT_ALG, ERR_R_MALLOC_FAILURE);
-        return 0;
-    }
-    X = (uint32_t *)(B + Blen);
-    T = X + 32 * r;
-    V = T + 32 * r;
-    if (PKCS5_PBKDF2_HMAC(pass, passlen, salt, saltlen, 1, EVP_sha256(),
-                          (int)Blen, B) == 0)
-        goto err;
-
-    for (i = 0; i < p; i++)
-        scryptROMix(B + 128 * r * i, r, N, X, T, V);
-
-    if (PKCS5_PBKDF2_HMAC(pass, passlen, B, (int)Blen, 1, EVP_sha256(),
-                          keylen, key) == 0)
-        goto err;
-    rv = 1;
- err:
-    if (rv == 0)
-        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_PBKDF2_ERROR);
-
-    OPENSSL_clear_free(B, (size_t)(Blen + Vlen));
-    return rv;
-}
-
-#endif
diff --git a/crypto/kdf/sshkdf.c b/crypto/kdf/sshkdf.c
deleted file mode 100644 (file)
index 4701c9c..0000000
+++ /dev/null
@@ -1,292 +0,0 @@
-/*
- * Copyright 2018-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
- * in the file LICENSE in the source distribution or at
- * https://www.openssl.org/source/license.html
- */
-
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <openssl/evp.h>
-#include <openssl/kdf.h>
-#include "internal/cryptlib.h"
-#include "internal/numbers.h"
-#include "internal/evp_int.h"
-#include "kdf_local.h"
-
-/* See RFC 4253, Section 7.2 */
-
-static void kdf_sshkdf_reset(EVP_KDF_IMPL *impl);
-static int SSHKDF(const EVP_MD *evp_md,
-                  const unsigned char *key, size_t key_len,
-                  const unsigned char *xcghash, size_t xcghash_len,
-                  const unsigned char *session_id, size_t session_id_len,
-                  char type, unsigned char *okey, size_t okey_len);
-
-struct evp_kdf_impl_st {
-    const EVP_MD *md;
-    unsigned char *key; /* K */
-    size_t key_len;
-    unsigned char *xcghash; /* H */
-    size_t xcghash_len;
-    char type; /* X */
-    unsigned char *session_id;
-    size_t session_id_len;
-};
-
-static EVP_KDF_IMPL *kdf_sshkdf_new(void)
-{
-    EVP_KDF_IMPL *impl;
-
-    if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
-        KDFerr(KDF_F_KDF_SSHKDF_NEW, ERR_R_MALLOC_FAILURE);
-    return impl;
-}
-
-static void kdf_sshkdf_free(EVP_KDF_IMPL *impl)
-{
-    kdf_sshkdf_reset(impl);
-    OPENSSL_free(impl);
-}
-
-static void kdf_sshkdf_reset(EVP_KDF_IMPL *impl)
-{
-    OPENSSL_clear_free(impl->key, impl->key_len);
-    OPENSSL_clear_free(impl->xcghash, impl->xcghash_len);
-    OPENSSL_clear_free(impl->session_id, impl->session_id_len);
-    memset(impl, 0, sizeof(*impl));
-}
-
-static int kdf_sshkdf_parse_buffer_arg(unsigned char **dst, size_t *dst_len,
-                                       va_list args)
-{
-    const unsigned char *p;
-    size_t len;
-
-    p = va_arg(args, const unsigned char *);
-    len = va_arg(args, size_t);
-    OPENSSL_clear_free(*dst, *dst_len);
-    *dst = OPENSSL_memdup(p, len);
-    if (*dst == NULL)
-        return 0;
-
-    *dst_len = len;
-    return 1;
-}
-
-static int kdf_sshkdf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
-{
-    int t;
-
-    switch (cmd) {
-    case EVP_KDF_CTRL_SET_MD:
-        impl->md = va_arg(args, const EVP_MD *);
-        if (impl->md == NULL)
-            return 0;
-
-        return 1;
-
-    case EVP_KDF_CTRL_SET_KEY:
-        return kdf_sshkdf_parse_buffer_arg(&impl->key,
-                                           &impl->key_len, args);
-
-    case EVP_KDF_CTRL_SET_SSHKDF_XCGHASH:
-        return kdf_sshkdf_parse_buffer_arg(&impl->xcghash,
-                                           &impl->xcghash_len, args);
-
-    case EVP_KDF_CTRL_SET_SSHKDF_SESSION_ID:
-        return kdf_sshkdf_parse_buffer_arg(&impl->session_id,
-                                           &impl->session_id_len, args);
-
-    case EVP_KDF_CTRL_SET_SSHKDF_TYPE:
-        t = va_arg(args, int);
-        if (t < 65 || t > 70) {
-            KDFerr(KDF_F_KDF_SSHKDF_CTRL, KDF_R_VALUE_ERROR);
-            return 0;
-        }
-
-        impl->type = (char)t;
-        return 1;
-
-    default:
-        return -2;
-
-    }
-}
-
-static int kdf_sshkdf_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
-                               const char *value)
-{
-    if (value == NULL) {
-        KDFerr(KDF_F_KDF_SSHKDF_CTRL_STR, KDF_R_VALUE_MISSING);
-        return 0;
-    }
-
-    if (strcmp(type, "digest") == 0)
-        return kdf_md2ctrl(impl, kdf_sshkdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
-    /* alias, for historical reasons */
-    if (strcmp(type, "md") == 0)
-        return kdf_md2ctrl(impl, kdf_sshkdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
-
-    if (strcmp(type, "key") == 0)
-        return kdf_str2ctrl(impl, kdf_sshkdf_ctrl,
-                            EVP_KDF_CTRL_SET_KEY, value);
-
-    if (strcmp(type, "hexkey") == 0)
-        return kdf_hex2ctrl(impl, kdf_sshkdf_ctrl,
-                            EVP_KDF_CTRL_SET_KEY, value);
-
-    if (strcmp(type, "xcghash") == 0)
-        return kdf_str2ctrl(impl, kdf_sshkdf_ctrl,
-                            EVP_KDF_CTRL_SET_SSHKDF_XCGHASH, value);
-
-    if (strcmp(type, "hexxcghash") == 0)
-        return kdf_hex2ctrl(impl, kdf_sshkdf_ctrl,
-                            EVP_KDF_CTRL_SET_SSHKDF_XCGHASH, value);
-
-    if (strcmp(type, "session_id") == 0)
-        return kdf_str2ctrl(impl, kdf_sshkdf_ctrl,
-                            EVP_KDF_CTRL_SET_SSHKDF_SESSION_ID, value);
-
-    if (strcmp(type, "hexsession_id") == 0)
-        return kdf_hex2ctrl(impl, kdf_sshkdf_ctrl,
-                            EVP_KDF_CTRL_SET_SSHKDF_SESSION_ID, value);
-
-    if (strcmp(type, "type") == 0) {
-        if (strlen(value) != 1) {
-            KDFerr(KDF_F_KDF_SSHKDF_CTRL_STR, KDF_R_VALUE_ERROR);
-            return 0;
-        }
-
-        return call_ctrl(kdf_sshkdf_ctrl, impl, EVP_KDF_CTRL_SET_SSHKDF_TYPE,
-                         (int)value[0]);
-    }
-
-    KDFerr(KDF_F_KDF_SSHKDF_CTRL_STR, KDF_R_UNKNOWN_PARAMETER_TYPE);
-    return -2;
-}
-
-static size_t kdf_sshkdf_size(EVP_KDF_IMPL *impl)
-{
-    return SIZE_MAX;
-}
-
-static int kdf_sshkdf_derive(EVP_KDF_IMPL *impl, unsigned char *key,
-                             size_t keylen)
-{
-    if (impl->md == NULL) {
-        KDFerr(KDF_F_KDF_SSHKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
-        return 0;
-    }
-    if (impl->key == NULL) {
-        KDFerr(KDF_F_KDF_SSHKDF_DERIVE, KDF_R_MISSING_KEY);
-        return 0;
-    }
-    if (impl->xcghash == NULL) {
-        KDFerr(KDF_F_KDF_SSHKDF_DERIVE, KDF_R_MISSING_XCGHASH);
-        return 0;
-    }
-    if (impl->session_id == NULL) {
-        KDFerr(KDF_F_KDF_SSHKDF_DERIVE, KDF_R_MISSING_SESSION_ID);
-        return 0;
-    }
-    if (impl->type == 0) {
-        KDFerr(KDF_F_KDF_SSHKDF_DERIVE, KDF_R_MISSING_TYPE);
-        return 0;
-    }
-    return SSHKDF(impl->md, impl->key, impl->key_len,
-                  impl->xcghash, impl->xcghash_len,
-                  impl->session_id, impl->session_id_len,
-                  impl->type, key, keylen);
-}
-
-const EVP_KDF sshkdf_kdf_meth = {
-    EVP_KDF_SSHKDF,
-    kdf_sshkdf_new,
-    kdf_sshkdf_free,
-    kdf_sshkdf_reset,
-    kdf_sshkdf_ctrl,
-    kdf_sshkdf_ctrl_str,
-    kdf_sshkdf_size,
-    kdf_sshkdf_derive,
-};
-
-static int SSHKDF(const EVP_MD *evp_md,
-                  const unsigned char *key, size_t key_len,
-                  const unsigned char *xcghash, size_t xcghash_len,
-                  const unsigned char *session_id, size_t session_id_len,
-                  char type, unsigned char *okey, size_t okey_len)
-{
-    EVP_MD_CTX *md = NULL;
-    unsigned char digest[EVP_MAX_MD_SIZE];
-    unsigned int dsize = 0;
-    size_t cursize = 0;
-    int ret = 0;
-
-    md = EVP_MD_CTX_new();
-    if (md == NULL)
-        return 0;
-
-    if (!EVP_DigestInit_ex(md, evp_md, NULL))
-        goto out;
-
-    if (!EVP_DigestUpdate(md, key, key_len))
-        goto out;
-
-    if (!EVP_DigestUpdate(md, xcghash, xcghash_len))
-        goto out;
-
-    if (!EVP_DigestUpdate(md, &type, 1))
-        goto out;
-
-    if (!EVP_DigestUpdate(md, session_id, session_id_len))
-        goto out;
-
-    if (!EVP_DigestFinal_ex(md, digest, &dsize))
-        goto out;
-
-    if (okey_len < dsize) {
-        memcpy(okey, digest, okey_len);
-        ret = 1;
-        goto out;
-    }
-
-    memcpy(okey, digest, dsize);
-
-    for (cursize = dsize; cursize < okey_len; cursize += dsize) {
-
-        if (!EVP_DigestInit_ex(md, evp_md, NULL))
-            goto out;
-
-        if (!EVP_DigestUpdate(md, key, key_len))
-            goto out;
-
-        if (!EVP_DigestUpdate(md, xcghash, xcghash_len))
-            goto out;
-
-        if (!EVP_DigestUpdate(md, okey, cursize))
-            goto out;
-
-        if (!EVP_DigestFinal_ex(md, digest, &dsize))
-            goto out;
-
-        if (okey_len < cursize + dsize) {
-            memcpy(okey + cursize, digest, okey_len - cursize);
-            ret = 1;
-            goto out;
-        }
-
-        memcpy(okey + cursize, digest, dsize);
-    }
-
-    ret = 1;
-
-out:
-    EVP_MD_CTX_free(md);
-    OPENSSL_cleanse(digest, EVP_MAX_MD_SIZE);
-    return ret;
-}
-
diff --git a/crypto/kdf/sskdf.c b/crypto/kdf/sskdf.c
deleted file mode 100644 (file)
index b20eff2..0000000
+++ /dev/null
@@ -1,558 +0,0 @@
-/*
- * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
- * Copyright (c) 2019, Oracle and/or its affiliates.  All rights reserved.
- *
- * Licensed under the Apache License 2.0 (the "License").  You may not use
- * this file except in compliance with the License.  You can obtain a copy
- * in the file LICENSE in the source distribution or at
- * https://www.openssl.org/source/license.html
- */
-
-/*
- * Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
- * Section 4.1.
- *
- * The Single Step KDF algorithm is given by:
- *
- * Result(0) = empty bit string (i.e., the null string).
- * For i = 1 to reps, do the following:
- *   Increment counter by 1.
- *   Result(i) = Result(i - 1) || H(counter || Z || FixedInfo).
- * DKM = LeftmostBits(Result(reps), L))
- *
- * NOTES:
- *   Z is a shared secret required to produce the derived key material.
- *   counter is a 4 byte buffer.
- *   FixedInfo is a bit string containing context specific data.
- *   DKM is the output derived key material.
- *   L is the required size of the DKM.
- *   reps = [L / H_outputBits]
- *   H(x) is the auxiliary function that can be either a hash, HMAC or KMAC.
- *   H_outputBits is the length of the output of the auxiliary function H(x).
- *
- * Currently there is not a comprehensive list of test vectors for this
- * algorithm, especially for H(x) = HMAC and H(x) = KMAC.
- * Test vectors for H(x) = Hash are indirectly used by CAVS KAS tests.
- */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <openssl/hmac.h>
-#include <openssl/evp.h>
-#include <openssl/kdf.h>
-#include <openssl/core_names.h>
-#include <openssl/params.h>
-#include "internal/cryptlib.h"
-#include "internal/evp_int.h"
-#include "kdf_local.h"
-
-struct evp_kdf_impl_st {
-    EVP_MAC *mac;       /* H(x) = HMAC_hash OR H(x) = KMAC */
-    const EVP_MD *md;   /* H(x) = hash OR when H(x) = HMAC_hash */
-    unsigned char *secret;
-    size_t secret_len;
-    unsigned char *info;
-    size_t info_len;
-    unsigned char *salt;
-    size_t salt_len;
-    size_t out_len; /* optional KMAC parameter */
-};
-
-#define SSKDF_MAX_INLEN (1<<30)
-#define SSKDF_KMAC128_DEFAULT_SALT_SIZE (168 - 4)
-#define SSKDF_KMAC256_DEFAULT_SALT_SIZE (136 - 4)
-
-/* KMAC uses a Customisation string of 'KDF' */
-static const unsigned char kmac_custom_str[] = { 0x4B, 0x44, 0x46 };
-
-/*
- * Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
- * Section 4. One-Step Key Derivation using H(x) = hash(x)
- * Note: X9.63 also uses this code with the only difference being that the
- * counter is appended to the secret 'z'.
- * i.e.
- *   result[i] = Hash(counter || z || info) for One Step OR
- *   result[i] = Hash(z || counter || info) for X9.63.
- */
-static int SSKDF_hash_kdm(const EVP_MD *kdf_md,
-                          const unsigned char *z, size_t z_len,
-                          const unsigned char *info, size_t info_len,
-                          unsigned int append_ctr,
-                          unsigned char *derived_key, size_t derived_key_len)
-{
-    int ret = 0, hlen;
-    size_t counter, out_len, len = derived_key_len;
-    unsigned char c[4];
-    unsigned char mac[EVP_MAX_MD_SIZE];
-    unsigned char *out = derived_key;
-    EVP_MD_CTX *ctx = NULL, *ctx_init = NULL;
-
-    if (z_len > SSKDF_MAX_INLEN || info_len > SSKDF_MAX_INLEN
-            || derived_key_len > SSKDF_MAX_INLEN
-            || derived_key_len == 0)
-        return 0;
-
-    hlen = EVP_MD_size(kdf_md);
-    if (hlen <= 0)
-        return 0;
-    out_len = (size_t)hlen;
-
-    ctx = EVP_MD_CTX_create();
-    ctx_init = EVP_MD_CTX_create();
-    if (ctx == NULL || ctx_init == NULL)
-        goto end;
-
-    if (!EVP_DigestInit(ctx_init, kdf_md))
-        goto end;
-
-    for (counter = 1;; counter++) {
-        c[0] = (unsigned char)((counter >> 24) & 0xff);
-        c[1] = (unsigned char)((counter >> 16) & 0xff);
-        c[2] = (unsigned char)((counter >> 8) & 0xff);
-        c[3] = (unsigned char)(counter & 0xff);
-
-        if (!(EVP_MD_CTX_copy_ex(ctx, ctx_init)
-                && (append_ctr || EVP_DigestUpdate(ctx, c, sizeof(c)))
-                && EVP_DigestUpdate(ctx, z, z_len)
-                && (!append_ctr || EVP_DigestUpdate(ctx, c, sizeof(c)))
-                && EVP_DigestUpdate(ctx, info, info_len)))
-            goto end;
-        if (len >= out_len) {
-            if (!EVP_DigestFinal_ex(ctx, out, NULL))
-                goto end;
-            out += out_len;
-            len -= out_len;
-            if (len == 0)
-                break;
-        } else {
-            if (!EVP_DigestFinal_ex(ctx, mac, NULL))
-                goto end;
-            memcpy(out, mac, len);
-            break;
-        }
-    }
-    ret = 1;
-end:
-    EVP_MD_CTX_destroy(ctx);
-    EVP_MD_CTX_destroy(ctx_init);
-    OPENSSL_cleanse(mac, sizeof(mac));
-    return ret;
-}
-
-static int kmac_init(EVP_MAC_CTX *ctx, const unsigned char *custom,
-                     size_t custom_len, size_t kmac_out_len,
-                     size_t derived_key_len, unsigned char **out)
-{
-    OSSL_PARAM params[2];
-
-    /* Only KMAC has custom data - so return if not KMAC */
-    if (custom == NULL)
-        return 1;
-
-    params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_CUSTOM,
-                                                  (void *)custom, custom_len);
-    params[1] = OSSL_PARAM_construct_end();
-
-    if (!EVP_MAC_CTX_set_params(ctx, params))
-        return 0;
-
-    /* By default only do one iteration if kmac_out_len is not specified */
-    if (kmac_out_len == 0)
-        kmac_out_len = derived_key_len;
-    /* otherwise check the size is valid */
-    else if (!(kmac_out_len == derived_key_len
-            || kmac_out_len == 20
-            || kmac_out_len == 28
-            || kmac_out_len == 32
-            || kmac_out_len == 48
-            || kmac_out_len == 64))
-        return 0;
-
-    params[0] = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_SIZE,
-                                            &kmac_out_len);
-
-    if (EVP_MAC_CTX_set_params(ctx, params) <= 0)
-        return 0;
-
-    /*
-     * For kmac the output buffer can be larger than EVP_MAX_MD_SIZE: so
-     * alloc a buffer for this case.
-     */
-    if (kmac_out_len > EVP_MAX_MD_SIZE) {
-        *out = OPENSSL_zalloc(kmac_out_len);
-        if (*out == NULL)
-            return 0;
-    }
-    return 1;
-}
-
-/*
- * Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
- * Section 4. One-Step Key Derivation using MAC: i.e either
- *     H(x) = HMAC-hash(salt, x) OR
- *     H(x) = KMAC#(salt, x, outbits, CustomString='KDF')
- */
-static int SSKDF_mac_kdm(EVP_MAC *kdf_mac, const EVP_MD *hmac_md,
-                         const unsigned char *kmac_custom,
-                         size_t kmac_custom_len, size_t kmac_out_len,
-                         const unsigned char *salt, size_t salt_len,
-                         const unsigned char *z, size_t z_len,
-                         const unsigned char *info, size_t info_len,
-                         unsigned char *derived_key, size_t derived_key_len)
-{
-    int ret = 0;
-    size_t counter, out_len, len;
-    unsigned char c[4];
-    unsigned char mac_buf[EVP_MAX_MD_SIZE];
-    unsigned char *out = derived_key;
-    EVP_MAC_CTX *ctx = NULL, *ctx_init = NULL;
-    unsigned char *mac = mac_buf, *kmac_buffer = NULL;
-    OSSL_PARAM params[3];
-    size_t params_n = 0;
-
-    if (z_len > SSKDF_MAX_INLEN || info_len > SSKDF_MAX_INLEN
-            || derived_key_len > SSKDF_MAX_INLEN
-            || derived_key_len == 0)
-        return 0;
-
-    ctx_init = EVP_MAC_CTX_new(kdf_mac);
-    if (ctx_init == NULL)
-        goto end;
-
-    if (hmac_md != NULL) {
-        const char *mdname = EVP_MD_name(hmac_md);
-        params[params_n++] =
-            OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
-                                             (char *)mdname, 0);
-    }
-    params[params_n++] =
-        OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (void *)salt,
-                                          salt_len);
-    params[params_n] = OSSL_PARAM_construct_end();
-
-    if (!EVP_MAC_CTX_set_params(ctx_init, params))
-        goto end;
-
-    if (!kmac_init(ctx_init, kmac_custom, kmac_custom_len, kmac_out_len,
-                   derived_key_len, &kmac_buffer))
-        goto end;
-    if (kmac_buffer != NULL)
-        mac = kmac_buffer;
-
-    if (!EVP_MAC_init(ctx_init))
-        goto end;
-
-    out_len = EVP_MAC_size(ctx_init); /* output size */
-    if (out_len <= 0)
-        goto end;
-    len = derived_key_len;
-
-    for (counter = 1;; counter++) {
-        c[0] = (unsigned char)((counter >> 24) & 0xff);
-        c[1] = (unsigned char)((counter >> 16) & 0xff);
-        c[2] = (unsigned char)((counter >> 8) & 0xff);
-        c[3] = (unsigned char)(counter & 0xff);
-
-        ctx = EVP_MAC_CTX_dup(ctx_init);
-        if (!(ctx != NULL
-                && EVP_MAC_update(ctx, c, sizeof(c))
-                && EVP_MAC_update(ctx, z, z_len)
-                && EVP_MAC_update(ctx, info, info_len)))
-            goto end;
-        if (len >= out_len) {
-            if (!EVP_MAC_final(ctx, out, NULL, len))
-                goto end;
-            out += out_len;
-            len -= out_len;
-            if (len == 0)
-                break;
-        } else {
-            if (!EVP_MAC_final(ctx, mac, NULL, len))
-                goto end;
-            memcpy(out, mac, len);
-            break;
-        }
-        EVP_MAC_CTX_free(ctx);
-        ctx = NULL;
-    }
-    ret = 1;
-end:
-    if (kmac_buffer != NULL)
-        OPENSSL_clear_free(kmac_buffer, kmac_out_len);
-    else
-        OPENSSL_cleanse(mac_buf, sizeof(mac_buf));
-
-    EVP_MAC_CTX_free(ctx);
-    EVP_MAC_CTX_free(ctx_init);
-    return ret;
-}
-
-static EVP_KDF_IMPL *sskdf_new(void)
-{
-    EVP_KDF_IMPL *impl;
-
-    if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
-        KDFerr(KDF_F_SSKDF_NEW, ERR_R_MALLOC_FAILURE);
-    return impl;
-}
-
-static void sskdf_reset(EVP_KDF_IMPL *impl)
-{
-    OPENSSL_clear_free(impl->secret, impl->secret_len);
-    OPENSSL_clear_free(impl->info, impl->info_len);
-    OPENSSL_clear_free(impl->salt, impl->salt_len);
-    EVP_MAC_free(impl->mac);
-#if 0                    /* TODO(3.0) When we switch to fetched MDs */
-    EVP_MD_meth_free(impl->md);
-#endif
-    memset(impl, 0, sizeof(*impl));
-}
-
-static void sskdf_free(EVP_KDF_IMPL *impl)
-{
-    sskdf_reset(impl);
-    OPENSSL_free(impl);
-}
-
-static int sskdf_set_buffer(va_list args, unsigned char **out, size_t *out_len)
-{
-    const unsigned char *p;
-    size_t len;
-
-    p = va_arg(args, const unsigned char *);
-    len = va_arg(args, size_t);
-    if (len == 0 || p == NULL)
-        return 1;
-
-    OPENSSL_free(*out);
-    *out = OPENSSL_memdup(p, len);
-    if (*out == NULL)
-        return 0;
-
-    *out_len = len;
-    return 1;
-}
-
-static int sskdf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
-{
-    const EVP_MD *md;
-
-    switch (cmd) {
-    case EVP_KDF_CTRL_SET_KEY:
-        return sskdf_set_buffer(args, &impl->secret, &impl->secret_len);
-
-    case EVP_KDF_CTRL_SET_SSKDF_INFO:
-        return sskdf_set_buffer(args, &impl->info, &impl->info_len);
-
-    case EVP_KDF_CTRL_SET_MD:
-        md = va_arg(args, const EVP_MD *);
-        if (md == NULL)
-            return 0;
-
-#if 0                    /* TODO(3.0) When we switch to fetched MDs */
-        EVP_MD_meth_free(impl->md);
-#endif
-        impl->md = md;
-        return 1;
-
-    case EVP_KDF_CTRL_SET_MAC:
-        {
-            const char *name;
-            EVP_MAC *mac;
-
-            name = va_arg(args, const char *);
-            if (name == NULL)
-                return 0;
-
-            EVP_MAC_free(impl->mac);
-            impl->mac = NULL;
-
-            /*
-             * TODO(3.0) add support for OPENSSL_CTX and properties in KDFs
-             */
-            mac = EVP_MAC_fetch(NULL, name, NULL);
-            if (mac == NULL)
-                return 0;
-
-            impl->mac = mac;
-            return 1;
-        }
-    case EVP_KDF_CTRL_SET_SALT:
-        return sskdf_set_buffer(args, &impl->salt, &impl->salt_len);
-
-    case EVP_KDF_CTRL_SET_MAC_SIZE:
-        impl->out_len = va_arg(args, size_t);
-        return 1;
-
-    default:
-        return -2;
-    }
-}
-
-static int sskdf_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
-                          const char *value)
-{
-    if (strcmp(type, "secret") == 0 || strcmp(type, "key") == 0)
-         return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_KEY,
-                             value);
-
-    if (strcmp(type, "hexsecret") == 0 || strcmp(type, "hexkey") == 0)
-        return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_KEY,
-                            value);
-
-    if (strcmp(type, "info") == 0)
-        return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SSKDF_INFO,
-                            value);
-
-    if (strcmp(type, "hexinfo") == 0)
-        return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SSKDF_INFO,
-                            value);
-
-    if (strcmp(type, "digest") == 0)
-        return kdf_md2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
-
-    if (strcmp(type, "mac") == 0)
-        return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_MAC, value);
-
-    if (strcmp(type, "salt") == 0)
-        return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
-
-    if (strcmp(type, "hexsalt") == 0)
-        return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
-
-
-    if (strcmp(type, "maclen") == 0) {
-        int val = atoi(value);
-        if (val < 0) {
-            KDFerr(KDF_F_SSKDF_CTRL_STR, KDF_R_VALUE_ERROR);
-            return 0;
-        }
-        return call_ctrl(sskdf_ctrl, impl, EVP_KDF_CTRL_SET_MAC_SIZE,
-                         (size_t)val);
-    }
-    return -2;
-}
-
-static size_t sskdf_size(EVP_KDF_IMPL *impl)
-{
-    int len;
-
-    if (impl->md == NULL) {
-        KDFerr(KDF_F_SSKDF_SIZE, KDF_R_MISSING_MESSAGE_DIGEST);
-        return 0;
-    }
-    len = EVP_MD_size(impl->md);
-    return (len <= 0) ? 0 : (size_t)len;
-}
-
-static int sskdf_derive(EVP_KDF_IMPL *impl, unsigned char *key, size_t keylen)
-{
-    if (impl->secret == NULL) {
-        KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_SECRET);
-        return 0;
-    }
-
-    if (impl->mac != NULL) {
-        /* H(x) = KMAC or H(x) = HMAC */
-        int ret;
-        const unsigned char *custom = NULL;
-        size_t custom_len = 0;
-        const char *macname;
-        int default_salt_len;
-
-        /*
-         * TODO(3.0) investigate the necessity to have all these controls.
-         * Why does KMAC require a salt length that's shorter than the MD
-         * block size?
-         */
-        macname = EVP_MAC_name(impl->mac);
-        if (strcmp(macname, OSSL_MAC_NAME_HMAC) == 0) {
-            /* H(x) = HMAC(x, salt, hash) */
-            if (impl->md == NULL) {
-                KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
-                return 0;
-            }
-            default_salt_len = EVP_MD_block_size(impl->md);
-            if (default_salt_len <= 0)
-                return 0;
-        } else if (strcmp(macname, OSSL_MAC_NAME_KMAC128) == 0
-                   || strcmp(macname, OSSL_MAC_NAME_KMAC256) == 0) {
-            /* H(x) = KMACzzz(x, salt, custom) */
-            custom = kmac_custom_str;
-            custom_len = sizeof(kmac_custom_str);
-            if (strcmp(macname, OSSL_MAC_NAME_KMAC128) == 0)
-                default_salt_len = SSKDF_KMAC128_DEFAULT_SALT_SIZE;
-            else
-                default_salt_len = SSKDF_KMAC256_DEFAULT_SALT_SIZE;
-        } else {
-            KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_UNSUPPORTED_MAC_TYPE);
-            return 0;
-        }
-        /* If no salt is set then use a default_salt of zeros */
-        if (impl->salt == NULL || impl->salt_len <= 0) {
-            impl->salt = OPENSSL_zalloc(default_salt_len);
-            if (impl->salt == NULL) {
-                KDFerr(KDF_F_SSKDF_DERIVE, ERR_R_MALLOC_FAILURE);
-                return 0;
-            }
-            impl->salt_len = default_salt_len;
-        }
-        ret = SSKDF_mac_kdm(impl->mac, impl->md,
-                            custom, custom_len, impl->out_len,
-                            impl->salt, impl->salt_len,
-                            impl->secret, impl->secret_len,
-                            impl->info, impl->info_len, key, keylen);
-        return ret;
-    } else {
-        /* H(x) = hash */
-        if (impl->md == NULL) {
-            KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
-            return 0;
-        }
-        return SSKDF_hash_kdm(impl->md, impl->secret, impl->secret_len,
-                              impl->info, impl->info_len, 0, key, keylen);
-    }
-}
-
-static int x963kdf_derive(EVP_KDF_IMPL *impl, unsigned char *key, size_t keylen)
-{
-    if (impl->secret == NULL) {
-        KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_MISSING_SECRET);
-        return 0;
-    }
-
-    if (impl->mac != NULL) {
-        KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_NOT_SUPPORTED);
-        return 0;
-    } else {
-        /* H(x) = hash */
-        if (impl->md == NULL) {
-            KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
-            return 0;
-        }
-        return SSKDF_hash_kdm(impl->md, impl->secret, impl->secret_len,
-                              impl->info, impl->info_len, 1, key, keylen);
-    }
-}
-
-const EVP_KDF ss_kdf_meth = {
-    EVP_KDF_SS,
-    sskdf_new,
-    sskdf_free,
-    sskdf_reset,
-    sskdf_ctrl,
-    sskdf_ctrl_str,
-    sskdf_size,
-    sskdf_derive
-};
-
-const EVP_KDF x963_kdf_meth = {
-    EVP_KDF_X963,
-    sskdf_new,
-    sskdf_free,
-    sskdf_reset,
-    sskdf_ctrl,
-    sskdf_ctrl_str,
-    sskdf_size,
-    x963kdf_derive
-};
diff --git a/crypto/kdf/tls1_prf.c b/crypto/kdf/tls1_prf.c
deleted file mode 100644 (file)
index edd7f05..0000000
+++ /dev/null
@@ -1,375 +0,0 @@
-/*
- * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
- *
- * Licensed under the Apache License 2.0 (the "License").  You may not use
- * this file except in compliance with the License.  You can obtain a copy
- * in the file LICENSE in the source distribution or at
- * https://www.openssl.org/source/license.html
- */
-
-/*
- * Refer to "The TLS Protocol Version 1.0" Section 5
- * (https://tools.ietf.org/html/rfc2246#section-5) and
- * "The Transport Layer Security (TLS) Protocol Version 1.2" Section 5
- * (https://tools.ietf.org/html/rfc5246#section-5).
- *
- * For TLS v1.0 and TLS v1.1 the TLS PRF algorithm is given by:
- *
- *   PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR
- *                              P_SHA-1(S2, label + seed)
- *
- * where P_MD5 and P_SHA-1 are defined by P_<hash>, below, and S1 and S2 are
- * two halves of the secret (with the possibility of one shared byte, in the
- * case where the length of the original secret is odd).  S1 is taken from the
- * first half of the secret, S2 from the second half.
- *
- * For TLS v1.2 the TLS PRF algorithm is given by:
- *
- *   PRF(secret, label, seed) = P_<hash>(secret, label + seed)
- *
- * where hash is SHA-256 for all cipher suites defined in RFC 5246 as well as
- * those published prior to TLS v1.2 while the TLS v1.2 protocol is in effect,
- * unless defined otherwise by the cipher suite.
- *
- * P_<hash> is an expansion function that uses a single hash function to expand
- * a secret and seed into an arbitrary quantity of output:
- *
- *   P_<hash>(secret, seed) = HMAC_<hash>(secret, A(1) + seed) +
- *                            HMAC_<hash>(secret, A(2) + seed) +
- *                            HMAC_<hash>(secret, A(3) + seed) + ...
- *
- * where + indicates concatenation.  P_<hash> can be iterated as many times as
- * is necessary to produce the required quantity of data.
- *
- * A(i) is defined as:
- *     A(0) = seed
- *     A(i) = HMAC_<hash>(secret, A(i-1))
- */
-#include <stdio.h>
-#include <stdarg.h>
-#include <string.h>
-#include "internal/cryptlib.h"
-#include <openssl/evp.h>
-#include <openssl/kdf.h>
-#include <openssl/core_names.h>
-#include <openssl/params.h>
-#include "internal/evp_int.h"
-#include "kdf_local.h"
-
-static void kdf_tls1_prf_reset(EVP_KDF_IMPL *impl);
-static int tls1_prf_alg(const EVP_MD *md,
-                        const unsigned char *sec, size_t slen,
-                        const unsigned char *seed, size_t seed_len,
-                        unsigned char *out, size_t olen);
-
-#define TLS1_PRF_MAXBUF 1024
-
-/* TLS KDF kdf context structure */
-
-struct evp_kdf_impl_st {
-    /* Digest to use for PRF */
-    const EVP_MD *md;
-    /* Secret value to use for PRF */
-    unsigned char *sec;
-    size_t seclen;
-    /* Buffer of concatenated seed data */
-    unsigned char seed[TLS1_PRF_MAXBUF];
-    size_t seedlen;
-};
-
-static EVP_KDF_IMPL *kdf_tls1_prf_new(void)
-{
-    EVP_KDF_IMPL *impl;
-
-    if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
-        KDFerr(KDF_F_KDF_TLS1_PRF_NEW, ERR_R_MALLOC_FAILURE);
-    return impl;
-}
-
-static void kdf_tls1_prf_free(EVP_KDF_IMPL *impl)
-{
-    kdf_tls1_prf_reset(impl);
-    OPENSSL_free(impl);
-}
-
-static void kdf_tls1_prf_reset(EVP_KDF_IMPL *impl)
-{
-    OPENSSL_clear_free(impl->sec, impl->seclen);
-    OPENSSL_cleanse(impl->seed, impl->seedlen);
-    memset(impl, 0, sizeof(*impl));
-}
-
-static int kdf_tls1_prf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
-{
-    const unsigned char *p;
-    size_t len;
-    const EVP_MD *md;
-
-    switch (cmd) {
-    case EVP_KDF_CTRL_SET_MD:
-        md = va_arg(args, const EVP_MD *);
-        if (md == NULL)
-            return 0;
-
-        impl->md = md;
-        return 1;
-
-    case EVP_KDF_CTRL_SET_TLS_SECRET:
-        p = va_arg(args, const unsigned char *);
-        len = va_arg(args, size_t);
-        OPENSSL_clear_free(impl->sec, impl->seclen);
-        impl->sec = OPENSSL_memdup(p, len);
-        if (impl->sec == NULL)
-            return 0;
-
-        impl->seclen = len;
-        return 1;
-
-    case EVP_KDF_CTRL_RESET_TLS_SEED:
-        OPENSSL_cleanse(impl->seed, impl->seedlen);
-        impl->seedlen = 0;
-        return 1;
-
-    case EVP_KDF_CTRL_ADD_TLS_SEED:
-        p = va_arg(args, const unsigned char *);
-        len = va_arg(args, size_t);
-        if (len == 0 || p == NULL)
-            return 1;
-
-        if (len > (TLS1_PRF_MAXBUF - impl->seedlen))
-            return 0;
-
-        memcpy(impl->seed + impl->seedlen, p, len);
-        impl->seedlen += len;
-        return 1;
-
-    default:
-        return -2;
-    }
-}
-
-static int kdf_tls1_prf_ctrl_str(EVP_KDF_IMPL *impl,
-                                 const char *type, const char *value)
-{
-    if (value == NULL) {
-        KDFerr(KDF_F_KDF_TLS1_PRF_CTRL_STR, KDF_R_VALUE_MISSING);
-        return 0;
-    }
-    if (strcmp(type, "digest") == 0)
-        return kdf_md2ctrl(impl, kdf_tls1_prf_ctrl, EVP_KDF_CTRL_SET_MD, value);
-
-    if (strcmp(type, "secret") == 0)
-        return kdf_str2ctrl(impl, kdf_tls1_prf_ctrl,
-                            EVP_KDF_CTRL_SET_TLS_SECRET, value);
-
-    if (strcmp(type, "hexsecret") == 0)
-        return kdf_hex2ctrl(impl, kdf_tls1_prf_ctrl,
-                            EVP_KDF_CTRL_SET_TLS_SECRET, value);
-
-    if (strcmp(type, "seed") == 0)
-        return kdf_str2ctrl(impl, kdf_tls1_prf_ctrl, EVP_KDF_CTRL_ADD_TLS_SEED,
-                            value);
-
-    if (strcmp(type, "hexseed") == 0)
-        return kdf_hex2ctrl(impl, kdf_tls1_prf_ctrl, EVP_KDF_CTRL_ADD_TLS_SEED,
-                            value);
-
-    return -2;
-}
-
-static int kdf_tls1_prf_derive(EVP_KDF_IMPL *impl, unsigned char *key,
-                               size_t keylen)
-{
-    if (impl->md == NULL) {
-        KDFerr(KDF_F_KDF_TLS1_PRF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
-        return 0;
-    }
-    if (impl->sec == NULL) {
-        KDFerr(KDF_F_KDF_TLS1_PRF_DERIVE, KDF_R_MISSING_SECRET);
-        return 0;
-    }
-    if (impl->seedlen == 0) {
-        KDFerr(KDF_F_KDF_TLS1_PRF_DERIVE, KDF_R_MISSING_SEED);
-        return 0;
-    }
-    return tls1_prf_alg(impl->md, impl->sec, impl->seclen,
-                        impl->seed, impl->seedlen,
-                        key, keylen);
-}
-
-const EVP_KDF tls1_prf_kdf_meth = {
-    EVP_KDF_TLS1_PRF,
-    kdf_tls1_prf_new,
-    kdf_tls1_prf_free,
-    kdf_tls1_prf_reset,
-    kdf_tls1_prf_ctrl,
-    kdf_tls1_prf_ctrl_str,
-    NULL,
-    kdf_tls1_prf_derive
-};
-
-/*
- * Refer to "The TLS Protocol Version 1.0" Section 5
- * (https://tools.ietf.org/html/rfc2246#section-5) and
- * "The Transport Layer Security (TLS) Protocol Version 1.2" Section 5
- * (https://tools.ietf.org/html/rfc5246#section-5).
- *
- * P_<hash> is an expansion function that uses a single hash function to expand
- * a secret and seed into an arbitrary quantity of output:
- *
- *   P_<hash>(secret, seed) = HMAC_<hash>(secret, A(1) + seed) +
- *                            HMAC_<hash>(secret, A(2) + seed) +
- *                            HMAC_<hash>(secret, A(3) + seed) + ...
- *
- * where + indicates concatenation.  P_<hash> can be iterated as many times as
- * is necessary to produce the required quantity of data.
- *
- * A(i) is defined as:
- *     A(0) = seed
- *     A(i) = HMAC_<hash>(secret, A(i-1))
- */
-static int tls1_prf_P_hash(const EVP_MD *md,
-                           const unsigned char *sec, size_t sec_len,
-                           const unsigned char *seed, size_t seed_len,
-                           unsigned char *out, size_t olen)
-{
-    size_t chunk;
-    EVP_MAC *mac = NULL;
-    EVP_MAC_CTX *ctx = NULL, *ctx_Ai = NULL, *ctx_init = NULL;
-    unsigned char Ai[EVP_MAX_MD_SIZE];
-    size_t Ai_len;
-    int ret = 0;
-    OSSL_PARAM params[4];
-    int mac_flags;
-    const char *mdname = EVP_MD_name(md);
-
-    mac = EVP_MAC_fetch(NULL, OSSL_MAC_NAME_HMAC, NULL); /* Implicit fetch */
-    ctx_init = EVP_MAC_CTX_new(mac);
-    if (ctx_init == NULL)
-        goto err;
-
-    /* TODO(3.0) rethink "flags", also see hmac.c in providers */
-    mac_flags = EVP_MD_CTX_FLAG_NON_FIPS_ALLOW;
-    params[0] = OSSL_PARAM_construct_int(OSSL_MAC_PARAM_FLAGS, &mac_flags);
-    params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
-                                                 (char *)mdname, 0);
-    params[2] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
-                                                  (void *)sec, sec_len);
-    params[3] = OSSL_PARAM_construct_end();
-    if (!EVP_MAC_CTX_set_params(ctx_init, params))
-        goto err;
-    if (!EVP_MAC_init(ctx_init))
-        goto err;
-    chunk = EVP_MAC_size(ctx_init);
-    if (chunk == 0)
-        goto err;
-    /* A(0) = seed */
-    ctx_Ai = EVP_MAC_CTX_dup(ctx_init);
-    if (ctx_Ai == NULL)
-        goto err;
-    if (seed != NULL && !EVP_MAC_update(ctx_Ai, seed, seed_len))
-        goto err;
-
-    for (;;) {
-        /* calc: A(i) = HMAC_<hash>(secret, A(i-1)) */
-        if (!EVP_MAC_final(ctx_Ai, Ai, &Ai_len, sizeof(Ai)))
-            goto err;
-        EVP_MAC_CTX_free(ctx_Ai);
-        ctx_Ai = NULL;
-
-        /* calc next chunk: HMAC_<hash>(secret, A(i) + seed) */
-        ctx = EVP_MAC_CTX_dup(ctx_init);
-        if (ctx == NULL)
-            goto err;
-        if (!EVP_MAC_update(ctx, Ai, Ai_len))
-            goto err;
-        /* save state for calculating next A(i) value */
-        if (olen > chunk) {
-            ctx_Ai = EVP_MAC_CTX_dup(ctx);
-            if (ctx_Ai == NULL)
-                goto err;
-        }
-        if (seed != NULL && !EVP_MAC_update(ctx, seed, seed_len))
-            goto err;
-        if (olen <= chunk) {
-            /* last chunk - use Ai as temp bounce buffer */
-            if (!EVP_MAC_final(ctx, Ai, &Ai_len, sizeof(Ai)))
-                goto err;
-            memcpy(out, Ai, olen);
-            break;
-        }
-        if (!EVP_MAC_final(ctx, out, NULL, olen))
-            goto err;
-        EVP_MAC_CTX_free(ctx);
-        ctx = NULL;
-        out += chunk;
-        olen -= chunk;
-    }
-    ret = 1;
- err:
-    EVP_MAC_CTX_free(ctx);
-    EVP_MAC_CTX_free(ctx_Ai);
-    EVP_MAC_CTX_free(ctx_init);
-    EVP_MAC_free(mac);
-    OPENSSL_cleanse(Ai, sizeof(Ai));
-    return ret;
-}
-
-/*
- * Refer to "The TLS Protocol Version 1.0" Section 5
- * (https://tools.ietf.org/html/rfc2246#section-5) and
- * "The Transport Layer Security (TLS) Protocol Version 1.2" Section 5
- * (https://tools.ietf.org/html/rfc5246#section-5).
- *
- * For TLS v1.0 and TLS v1.1:
- *
- *   PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR
- *                              P_SHA-1(S2, label + seed)
- *
- * S1 is taken from the first half of the secret, S2 from the second half.
- *
- *   L_S = length in bytes of secret;
- *   L_S1 = L_S2 = ceil(L_S / 2);
- *
- * For TLS v1.2:
- *
- *   PRF(secret, label, seed) = P_<hash>(secret, label + seed)
- */
-static int tls1_prf_alg(const EVP_MD *md,
-                        const unsigned char *sec, size_t slen,
-                        const unsigned char *seed, size_t seed_len,
-                        unsigned char *out, size_t olen)
-{
-    if (EVP_MD_type(md) == NID_md5_sha1) {
-        /* TLS v1.0 and TLS v1.1 */
-        size_t i;
-        unsigned char *tmp;
-        /* calc: L_S1 = L_S2 = ceil(L_S / 2) */
-        size_t L_S1 = (slen + 1) / 2;
-        size_t L_S2 = L_S1;
-
-        if (!tls1_prf_P_hash(EVP_md5(), sec, L_S1,
-                             seed, seed_len, out, olen))
-            return 0;
-
-        if ((tmp = OPENSSL_malloc(olen)) == NULL) {
-            KDFerr(KDF_F_TLS1_PRF_ALG, ERR_R_MALLOC_FAILURE);
-            return 0;
-        }
-        if (!tls1_prf_P_hash(EVP_sha1(), sec + slen - L_S2, L_S2,
-                             seed, seed_len, tmp, olen)) {
-            OPENSSL_clear_free(tmp, olen);
-            return 0;
-        }
-        for (i = 0; i < olen; i++)
-            out[i] ^= tmp[i];
-        OPENSSL_clear_free(tmp, olen);
-        return 1;
-    }
-
-    /* TLS v1.2 */
-    if (!tls1_prf_P_hash(md, sec, slen, seed, seed_len, out, olen))
-        return 0;
-
-    return 1;
-}
diff --git a/crypto/kdf/x942kdf.c b/crypto/kdf/x942kdf.c
deleted file mode 100644 (file)
index ce9ad61..0000000
+++ /dev/null
@@ -1,407 +0,0 @@
-/*
- * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
- * Copyright (c) 2019, Oracle and/or its affiliates.  All rights reserved.
- *
- * Licensed under the Apache License 2.0 (the "License").  You may not use
- * this file except in compliance with the License.  You can obtain a copy
- * in the file LICENSE in the source distribution or at
- * https://www.openssl.org/source/license.html
- */
-
-#include "e_os.h"
-
-#ifndef OPENSSL_NO_CMS
-
-# include <stdlib.h>
-# include <stdarg.h>
-# include <string.h>
-# include <openssl/hmac.h>
-# include <openssl/cms.h>
-# include <openssl/evp.h>
-# include <openssl/kdf.h>
-# include <openssl/x509.h>
-# include <openssl/obj_mac.h>
-# include "internal/cryptlib.h"
-# include "internal/evp_int.h"
-# include "kdf_local.h"
-
-# define X942KDF_MAX_INLEN (1 << 30)
-
-struct evp_kdf_impl_st {
-    const EVP_MD *md;
-    unsigned char *secret;
-    size_t secret_len;
-    int cek_nid;
-    unsigned char *ukm;
-    size_t ukm_len;
-    size_t dkm_len;
-};
-
-/* A table of allowed wrapping algorithms and the associated output lengths */
-static const struct {
-    int nid;
-    size_t keklen; /* size in bytes */
-} kek_algs[] = {
-    { NID_id_smime_alg_CMS3DESwrap, 24 },
-    { NID_id_smime_alg_CMSRC2wrap, 16 },
-    { NID_id_aes128_wrap, 16 },
-    { NID_id_aes192_wrap, 24 },
-    { NID_id_aes256_wrap, 32 },
-    { NID_id_camellia128_wrap, 16 },
-    { NID_id_camellia192_wrap, 24 },
-    { NID_id_camellia256_wrap, 32 }
-};
-
-/* Skip past an ASN1 structure: for OBJECT skip content octets too */
-static int skip_asn1(unsigned char **pp, long *plen, int exptag)
-{
-    int i, tag, xclass;
-    long tmplen;
-    const unsigned char *q = *pp;
-
-    i = ASN1_get_object(&q, &tmplen, &tag, &xclass, *plen);
-    if ((i & 0x80) != 0 || tag != exptag || xclass != V_ASN1_UNIVERSAL)
-        return 0;
-    if (tag == V_ASN1_OBJECT)
-        q += tmplen;
-    *pp = (unsigned char *)q;
-    *plen -= q - *pp;
-    return 1;
-}
-
-/*
- * Encode the other info structure.
- *
- *  RFC2631 Section 2.1.2 Contains the following definition for otherinfo
- *
- *  OtherInfo ::= SEQUENCE {
- *      keyInfo KeySpecificInfo,
- *      partyAInfo [0] OCTET STRING OPTIONAL,
- *      suppPubInfo [2] OCTET STRING
- *  }
- *
- *  KeySpecificInfo ::= SEQUENCE {
- *      algorithm OBJECT IDENTIFIER,
- *      counter OCTET STRING SIZE (4..4)
- *  }
- *
- * |nid| is the algorithm object identifier.
- * |keylen| is the length (in bytes) of the generated KEK. It is stored into
- * suppPubInfo (in bits).
- * |ukm| is the optional user keying material that is stored into partyAInfo. It
- * can be NULL.
- * |ukmlen| is the user keying material length (in bytes).
- * |der| is the returned encoded data. It must be freed by the caller.
- * |der_len| is the returned size of the encoded data.
- * |out_ctr| returns a pointer to the counter data which is embedded inside the
- * encoded data. This allows the counter bytes to be updated without re-encoding.
- *
- * Returns: 1 if successfully encoded, or 0 otherwise.
- * Assumptions: |der|, |der_len| & |out_ctr| are not NULL.
- */
-static int x942_encode_otherinfo(int nid, size_t keylen,
-                                 const unsigned char *ukm, size_t ukmlen,
-                                 unsigned char **der, size_t *der_len,
-                                 unsigned char **out_ctr)
-{
-    unsigned char *p, *encoded = NULL;
-    int ret = 0, encoded_len;
-    long tlen;
-    /* "magic" value to check offset is sane */
-    static unsigned char ctr[4] = { 0x00, 0x00, 0x00, 0x01 };
-    X509_ALGOR *ksi = NULL;
-    ASN1_OBJECT *alg_oid = NULL;
-    ASN1_OCTET_STRING *ctr_oct = NULL, *ukm_oct = NULL;
-
-    /* set the KeySpecificInfo - which contains an algorithm oid and counter */
-    ksi = X509_ALGOR_new();
-    alg_oid = OBJ_dup(OBJ_nid2obj(nid));
-    ctr_oct = ASN1_OCTET_STRING_new();
-    if (ksi == NULL
-        || alg_oid == NULL
-        || ctr_oct == NULL
-        || !ASN1_OCTET_STRING_set(ctr_oct, ctr, sizeof(ctr))
-        || !X509_ALGOR_set0(ksi, alg_oid, V_ASN1_OCTET_STRING, ctr_oct))
-        goto err;
-    /* NULL these as they now belong to ksi */
-    alg_oid = NULL;
-    ctr_oct = NULL;
-
-    /* Set the optional partyAInfo */
-    if (ukm != NULL) {
-        ukm_oct = ASN1_OCTET_STRING_new();
-        if (ukm_oct == NULL)
-            goto err;
-        ASN1_OCTET_STRING_set(ukm_oct, (unsigned char *)ukm, ukmlen);
-    }
-    /* Generate the OtherInfo DER data */
-    encoded_len = CMS_SharedInfo_encode(&encoded, ksi, ukm_oct, keylen);
-    if (encoded_len <= 0)
-        goto err;
-
-    /* Parse the encoded data to find the offset of the counter data */
-    p = encoded;
-    tlen = (long)encoded_len;
-    if (skip_asn1(&p, &tlen, V_ASN1_SEQUENCE)
-        && skip_asn1(&p, &tlen, V_ASN1_SEQUENCE)
-        && skip_asn1(&p, &tlen, V_ASN1_OBJECT)
-        && skip_asn1(&p, &tlen, V_ASN1_OCTET_STRING)
-        && CRYPTO_memcmp(p, ctr, 4) == 0) {
-        *out_ctr = p;
-        *der = encoded;
-        *der_len = (size_t)encoded_len;
-        ret = 1;
-    }
-err:
-    if (ret != 1)
-        OPENSSL_free(encoded);
-    ASN1_OCTET_STRING_free(ctr_oct);
-    ASN1_OCTET_STRING_free(ukm_oct);
-    ASN1_OBJECT_free(alg_oid);
-    X509_ALGOR_free(ksi);
-    return ret;
-}
-
-static int x942kdf_hash_kdm(const EVP_MD *kdf_md,
-                            const unsigned char *z, size_t z_len,
-                            const unsigned char *other, size_t other_len,
-                            unsigned char *ctr,
-                            unsigned char *derived_key, size_t derived_key_len)
-{
-    int ret = 0, hlen;
-    size_t counter, out_len, len = derived_key_len;
-    unsigned char mac[EVP_MAX_MD_SIZE];
-    unsigned char *out = derived_key;
-    EVP_MD_CTX *ctx = NULL, *ctx_init = NULL;
-
-    if (z_len > X942KDF_MAX_INLEN || other_len > X942KDF_MAX_INLEN
-            || derived_key_len > X942KDF_MAX_INLEN
-            || derived_key_len == 0) {
-        KDFerr(KDF_F_X942KDF_HASH_KDM, KDF_R_BAD_LENGTH);
-        return 0;
-    }
-
-    hlen = EVP_MD_size(kdf_md);
-    if (hlen <= 0)
-        return 0;
-    out_len = (size_t)hlen;
-
-    ctx = EVP_MD_CTX_create();
-    ctx_init = EVP_MD_CTX_create();
-    if (ctx == NULL || ctx_init == NULL)
-        goto end;
-
-    if (!EVP_DigestInit(ctx_init, kdf_md))
-        goto end;
-
-    for (counter = 1;; counter++) {
-        /* updating the ctr modifies 4 bytes in the 'other' buffer */
-        ctr[0] = (unsigned char)((counter >> 24) & 0xff);
-        ctr[1] = (unsigned char)((counter >> 16) & 0xff);
-        ctr[2] = (unsigned char)((counter >> 8) & 0xff);
-        ctr[3] = (unsigned char)(counter & 0xff);
-
-        if (!EVP_MD_CTX_copy_ex(ctx, ctx_init)
-            || !EVP_DigestUpdate(ctx, z, z_len)
-            || !EVP_DigestUpdate(ctx, other, other_len))
-            goto end;
-        if (len >= out_len) {
-            if (!EVP_DigestFinal_ex(ctx, out, NULL))
-                goto end;
-            out += out_len;
-            len -= out_len;
-            if (len == 0)
-                break;
-        } else {
-            if (!EVP_DigestFinal_ex(ctx, mac, NULL))
-                goto end;
-            memcpy(out, mac, len);
-            break;
-        }
-    }
-    ret = 1;
-end:
-    EVP_MD_CTX_free(ctx);
-    EVP_MD_CTX_free(ctx_init);
-    OPENSSL_cleanse(mac, sizeof(mac));
-    return ret;
-}
-
-static EVP_KDF_IMPL *x942kdf_new(void)
-{
-    EVP_KDF_IMPL *impl;
-
-    if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
-        KDFerr(KDF_F_X942KDF_NEW, ERR_R_MALLOC_FAILURE);
-    return impl;
-}
-
-static void x942kdf_reset(EVP_KDF_IMPL *impl)
-{
-    OPENSSL_clear_free(impl->secret, impl->secret_len);
-    OPENSSL_clear_free(impl->ukm, impl->ukm_len);
-    memset(impl, 0, sizeof(*impl));
-}
-
-static void x942kdf_free(EVP_KDF_IMPL *impl)
-{
-    x942kdf_reset(impl);
-    OPENSSL_free(impl);
-}
-
-static int x942kdf_set_buffer(va_list args, unsigned char **out, size_t *out_len)
-{
-    const unsigned char *p;
-    size_t len;
-
-    p = va_arg(args, const unsigned char *);
-    len = va_arg(args, size_t);
-    if (len == 0 || p == NULL)
-        return 1;
-
-    OPENSSL_free(*out);
-    *out = OPENSSL_memdup(p, len);
-    if (*out == NULL)
-        return 0;
-
-    *out_len = len;
-    return 1;
-}
-
-static int x942kdf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
-{
-    const EVP_MD *md;
-    char *alg_str = NULL;
-    size_t i;
-
-    switch (cmd) {
-    case EVP_KDF_CTRL_SET_MD:
-        md = va_arg(args, const EVP_MD *);
-        if (md == NULL)
-            return 0;
-
-        impl->md = md;
-        return 1;
-
-    case EVP_KDF_CTRL_SET_KEY:
-        return x942kdf_set_buffer(args, &impl->secret, &impl->secret_len);
-
-    case EVP_KDF_CTRL_SET_UKM:
-        return x942kdf_set_buffer(args, &impl->ukm, &impl->ukm_len);
-
-    case EVP_KDF_CTRL_SET_CEK_ALG:
-        alg_str = va_arg(args, char *);
-        if (alg_str == NULL)
-            return 0;
-        impl->cek_nid = OBJ_sn2nid(alg_str);
-        for (i = 0; i < (size_t)OSSL_NELEM(kek_algs); ++i) {
-            if (kek_algs[i].nid == impl->cek_nid) {
-                impl->dkm_len = kek_algs[i].keklen;
-                return 1;
-            }
-        }
-        KDFerr(KDF_F_X942KDF_CTRL, KDF_R_UNSUPPORTED_CEK_ALG);
-        return 0;
-
-    default:
-        return -2;
-    }
-}
-
-static int x942kdf_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
-                            const char *value)
-{
-    if (strcmp(type, "digest") == 0)
-        return kdf_md2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
-
-    if (strcmp(type, "secret") == 0 || strcmp(type, "key") == 0)
-         return kdf_str2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_KEY,
-                             value);
-
-    if (strcmp(type, "hexsecret") == 0 || strcmp(type, "hexkey") == 0)
-        return kdf_hex2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_KEY,
-                            value);
-
-    if (strcmp(type, "ukm") == 0)
-        return kdf_str2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_UKM,
-                            value);
-
-    if (strcmp(type, "hexukm") == 0)
-        return kdf_hex2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_UKM,
-                            value);
-
-    if (strcmp(type, "cekalg") == 0)
-        return kdf_str2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_CEK_ALG,
-                            value);
-
-    return -2;
-}
-
-static size_t x942kdf_size(EVP_KDF_IMPL *impl)
-{
-    int len;
-
-    if (impl->md == NULL) {
-        KDFerr(KDF_F_X942KDF_SIZE, KDF_R_MISSING_MESSAGE_DIGEST);
-        return 0;
-    }
-    len = EVP_MD_size(impl->md);
-    return (len <= 0) ? 0 : (size_t)len;
-}
-
-static int x942kdf_derive(EVP_KDF_IMPL *impl, unsigned char *key, size_t keylen)
-{
-    int ret = 0;
-    unsigned char *ctr;
-    unsigned char *der = NULL;
-    size_t der_len = 0;
-
-    if (impl->secret == NULL) {
-        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_MISSING_SECRET);
-        return 0;
-    }
-    if (impl->md == NULL) {
-        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
-        return 0;
-    }
-    if (impl->cek_nid == NID_undef) {
-        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_MISSING_CEK_ALG);
-        return 0;
-    }
-    if (impl->ukm != NULL && impl->ukm_len >= X942KDF_MAX_INLEN) {
-        /*
-         * Note the ukm length MUST be 512 bits.
-         * For backwards compatibility the old check is being done.
-         */
-        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_INAVLID_UKM_LEN);
-        return 0;
-    }
-    if (keylen != impl->dkm_len) {
-        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_MISSING_CEK_ALG);
-        return 0;
-    }
-    /* generate the otherinfo der */
-    if (!x942_encode_otherinfo(impl->cek_nid, impl->dkm_len,
-                               impl->ukm, impl->ukm_len,
-                               &der, &der_len, &ctr)) {
-        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_BAD_ENCODING);
-        return 0;
-    }
-    ret = x942kdf_hash_kdm(impl->md, impl->secret, impl->secret_len,
-                           der, der_len, ctr, key, keylen);
-    OPENSSL_free(der);
-    return ret;
-}
-
-const EVP_KDF x942_kdf_meth = {
-    EVP_KDF_X942,
-    x942kdf_new,
-    x942kdf_free,
-    x942kdf_reset,
-    x942kdf_ctrl,
-    x942kdf_ctrl_str,
-    x942kdf_size,
-    x942kdf_derive
-};
-
-#endif /* OPENSSL_NO_CMS */
diff --git a/providers/common/kdfs/build.info b/providers/common/kdfs/build.info
new file mode 100644 (file)
index 0000000..422cf74
--- /dev/null
@@ -0,0 +1,13 @@
+$COMMON=tls1_prf.c hkdf.c scrypt.c pbkdf2.c sskdf.c
+
+LIBS=../../../libcrypto
+SOURCE[../../../libcrypto]=$COMMON sshkdf.c x942kdf.c
+INCLUDE[../../../libcrypto]=. ../../../crypto
+
+IF[{- !$disabled{fips} -}]
+  MODULES=../../fips
+  SOURCE[../../fips]=$COMMON
+  INCLUDE[../../fips]=. ../../../crypto
+ENDIF
+
+        
diff --git a/providers/common/kdfs/hkdf.c b/providers/common/kdfs/hkdf.c
new file mode 100644 (file)
index 0000000..33c74da
--- /dev/null
@@ -0,0 +1,440 @@
+/*
+ * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License").  You may not use
+ * this file except in compliance with the License.  You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <openssl/hmac.h>
+#include <openssl/evp.h>
+#include <openssl/kdf.h>
+#include "internal/cryptlib.h"
+#include "internal/numbers.h"
+#include "internal/evp_int.h"
+#include "kdf_local.h"
+
+#define HKDF_MAXBUF 1024
+
+static void kdf_hkdf_reset(EVP_KDF_IMPL *impl);
+static int HKDF(const EVP_MD *evp_md,
+                const unsigned char *salt, size_t salt_len,
+                const unsigned char *key, size_t key_len,
+                const unsigned char *info, size_t info_len,
+                unsigned char *okm, size_t okm_len);
+static int HKDF_Extract(const EVP_MD *evp_md,
+                        const unsigned char *salt, size_t salt_len,
+                        const unsigned char *ikm, size_t ikm_len,
+                        unsigned char *prk, size_t prk_len);
+static int HKDF_Expand(const EVP_MD *evp_md,
+                       const unsigned char *prk, size_t prk_len,
+                       const unsigned char *info, size_t info_len,
+                       unsigned char *okm, size_t okm_len);
+
+struct evp_kdf_impl_st {
+    int mode;
+    const EVP_MD *md;
+    unsigned char *salt;
+    size_t salt_len;
+    unsigned char *key;
+    size_t key_len;
+    unsigned char info[HKDF_MAXBUF];
+    size_t info_len;
+};
+
+static EVP_KDF_IMPL *kdf_hkdf_new(void)
+{
+    EVP_KDF_IMPL *impl;
+
+    if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
+        KDFerr(KDF_F_KDF_HKDF_NEW, ERR_R_MALLOC_FAILURE);
+    return impl;
+}
+
+static void kdf_hkdf_free(EVP_KDF_IMPL *impl)
+{
+    kdf_hkdf_reset(impl);
+    OPENSSL_free(impl);
+}
+
+static void kdf_hkdf_reset(EVP_KDF_IMPL *impl)
+{
+    OPENSSL_free(impl->salt);
+    OPENSSL_clear_free(impl->key, impl->key_len);
+    OPENSSL_cleanse(impl->info, impl->info_len);
+    memset(impl, 0, sizeof(*impl));
+}
+
+static int kdf_hkdf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
+{
+    const unsigned char *p;
+    size_t len;
+    const EVP_MD *md;
+
+    switch (cmd) {
+    case EVP_KDF_CTRL_SET_MD:
+        md = va_arg(args, const EVP_MD *);
+        if (md == NULL)
+            return 0;
+
+        impl->md = md;
+        return 1;
+
+    case EVP_KDF_CTRL_SET_HKDF_MODE:
+        impl->mode = va_arg(args, int);
+        return 1;
+
+    case EVP_KDF_CTRL_SET_SALT:
+        p = va_arg(args, const unsigned char *);
+        len = va_arg(args, size_t);
+        if (len == 0 || p == NULL)
+            return 1;
+
+        OPENSSL_free(impl->salt);
+        impl->salt = OPENSSL_memdup(p, len);
+        if (impl->salt == NULL)
+            return 0;
+
+        impl->salt_len = len;
+        return 1;
+
+    case EVP_KDF_CTRL_SET_KEY:
+        p = va_arg(args, const unsigned char *);
+        len = va_arg(args, size_t);
+        OPENSSL_clear_free(impl->key, impl->key_len);
+        impl->key = OPENSSL_memdup(p, len);
+        if (impl->key == NULL)
+            return 0;
+
+        impl->key_len  = len;
+        return 1;
+
+    case EVP_KDF_CTRL_RESET_HKDF_INFO:
+        OPENSSL_cleanse(impl->info, impl->info_len);
+        impl->info_len = 0;
+        return 1;
+
+    case EVP_KDF_CTRL_ADD_HKDF_INFO:
+        p = va_arg(args, const unsigned char *);
+        len = va_arg(args, size_t);
+        if (len == 0 || p == NULL)
+            return 1;
+
+        if (len > (HKDF_MAXBUF - impl->info_len))
+            return 0;
+
+        memcpy(impl->info + impl->info_len, p, len);
+        impl->info_len += len;
+        return 1;
+
+    default:
+        return -2;
+    }
+}
+
+static int kdf_hkdf_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
+                             const char *value)
+{
+    if (strcmp(type, "mode") == 0) {
+        int mode;
+
+        if (strcmp(value, "EXTRACT_AND_EXPAND") == 0)
+            mode = EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND;
+        else if (strcmp(value, "EXTRACT_ONLY") == 0)
+            mode = EVP_KDF_HKDF_MODE_EXTRACT_ONLY;
+        else if (strcmp(value, "EXPAND_ONLY") == 0)
+            mode = EVP_KDF_HKDF_MODE_EXPAND_ONLY;
+        else
+            return 0;
+
+        return call_ctrl(kdf_hkdf_ctrl, impl, EVP_KDF_CTRL_SET_HKDF_MODE, mode);
+    }
+
+    if (strcmp(type, "digest") == 0)
+        return kdf_md2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
+
+    if (strcmp(type, "salt") == 0)
+        return kdf_str2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
+
+    if (strcmp(type, "hexsalt") == 0)
+        return kdf_hex2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
+
+    if (strcmp(type, "key") == 0)
+        return kdf_str2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_KEY, value);
+
+    if (strcmp(type, "hexkey") == 0)
+        return kdf_hex2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_KEY, value);
+
+    if (strcmp(type, "info") == 0)
+        return kdf_str2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_ADD_HKDF_INFO,
+                            value);
+
+    if (strcmp(type, "hexinfo") == 0)
+        return kdf_hex2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_ADD_HKDF_INFO,
+                            value);
+
+    return -2;
+}
+
+static size_t kdf_hkdf_size(EVP_KDF_IMPL *impl)
+{
+    int sz;
+
+    if (impl->mode != EVP_KDF_HKDF_MODE_EXTRACT_ONLY)
+        return SIZE_MAX;
+
+    if (impl->md == NULL) {
+        KDFerr(KDF_F_KDF_HKDF_SIZE, KDF_R_MISSING_MESSAGE_DIGEST);
+        return 0;
+    }
+    sz = EVP_MD_size(impl->md);
+    if (sz < 0)
+        return 0;
+
+    return sz;
+}
+
+static int kdf_hkdf_derive(EVP_KDF_IMPL *impl, unsigned char *key,
+                           size_t keylen)
+{
+    if (impl->md == NULL) {
+        KDFerr(KDF_F_KDF_HKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
+        return 0;
+    }
+    if (impl->key == NULL) {
+        KDFerr(KDF_F_KDF_HKDF_DERIVE, KDF_R_MISSING_KEY);
+        return 0;
+    }
+
+    switch (impl->mode) {
+    case EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND:
+        return HKDF(impl->md, impl->salt, impl->salt_len, impl->key,
+                    impl->key_len, impl->info, impl->info_len, key,
+                    keylen);
+
+    case EVP_KDF_HKDF_MODE_EXTRACT_ONLY:
+        return HKDF_Extract(impl->md, impl->salt, impl->salt_len, impl->key,
+                            impl->key_len, key, keylen);
+
+    case EVP_KDF_HKDF_MODE_EXPAND_ONLY:
+        return HKDF_Expand(impl->md, impl->key, impl->key_len, impl->info,
+                           impl->info_len, key, keylen);
+
+    default:
+        return 0;
+    }
+}
+
+const EVP_KDF hkdf_kdf_meth = {
+    EVP_KDF_HKDF,
+    kdf_hkdf_new,
+    kdf_hkdf_free,
+    kdf_hkdf_reset,
+    kdf_hkdf_ctrl,
+    kdf_hkdf_ctrl_str,
+    kdf_hkdf_size,
+    kdf_hkdf_derive
+};
+
+/*
+ * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
+ * Section 2 (https://tools.ietf.org/html/rfc5869#section-2) and
+ * "Cryptographic Extraction and Key Derivation: The HKDF Scheme"
+ * Section 4.2 (https://eprint.iacr.org/2010/264.pdf).
+ *
+ * From the paper:
+ *   The scheme HKDF is specified as:
+ *     HKDF(XTS, SKM, CTXinfo, L) = K(1) | K(2) | ... | K(t)
+ *
+ *     where:
+ *       SKM is source key material
+ *       XTS is extractor salt (which may be null or constant)
+ *       CTXinfo is context information (may be null)
+ *       L is the number of key bits to be produced by KDF
+ *       k is the output length in bits of the hash function used with HMAC
+ *       t = ceil(L/k)
+ *       the value K(t) is truncated to its first d = L mod k bits.
+ *
+ * From RFC 5869:
+ *   2.2.  Step 1: Extract
+ *     HKDF-Extract(salt, IKM) -> PRK
+ *   2.3.  Step 2: Expand
+ *     HKDF-Expand(PRK, info, L) -> OKM
+ */
+static int HKDF(const EVP_MD *evp_md,
+                const unsigned char *salt, size_t salt_len,
+                const unsigned char *ikm, size_t ikm_len,
+                const unsigned char *info, size_t info_len,
+                unsigned char *okm, size_t okm_len)
+{
+    unsigned char prk[EVP_MAX_MD_SIZE];
+    int ret, sz;
+    size_t prk_len;
+
+    sz = EVP_MD_size(evp_md);
+    if (sz < 0)
+        return 0;
+    prk_len = (size_t)sz;
+
+    /* Step 1: HKDF-Extract(salt, IKM) -> PRK */
+    if (!HKDF_Extract(evp_md, salt, salt_len, ikm, ikm_len, prk, prk_len))
+        return 0;
+
+    /* Step 2: HKDF-Expand(PRK, info, L) -> OKM */
+    ret = HKDF_Expand(evp_md, prk, prk_len, info, info_len, okm, okm_len);
+    OPENSSL_cleanse(prk, sizeof(prk));
+
+    return ret;
+}
+
+/*
+ * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
+ * Section 2.2 (https://tools.ietf.org/html/rfc5869#section-2.2).
+ *
+ * 2.2.  Step 1: Extract
+ *
+ *   HKDF-Extract(salt, IKM) -> PRK
+ *
+ *   Options:
+ *      Hash     a hash function; HashLen denotes the length of the
+ *               hash function output in octets
+ *
+ *   Inputs:
+ *      salt     optional salt value (a non-secret random value);
+ *               if not provided, it is set to a string of HashLen zeros.
+ *      IKM      input keying material
+ *
+ *   Output:
+ *      PRK      a pseudorandom key (of HashLen octets)
+ *
+ *   The output PRK is calculated as follows:
+ *
+ *   PRK = HMAC-Hash(salt, IKM)
+ */
+static int HKDF_Extract(const EVP_MD *evp_md,
+                        const unsigned char *salt, size_t salt_len,
+                        const unsigned char *ikm, size_t ikm_len,
+                        unsigned char *prk, size_t prk_len)
+{
+    int sz = EVP_MD_size(evp_md);
+
+    if (sz < 0)
+        return 0;
+    if (prk_len != (size_t)sz) {
+        KDFerr(KDF_F_HKDF_EXTRACT, KDF_R_WRONG_OUTPUT_BUFFER_SIZE);
+        return 0;
+    }
+    /* calc: PRK = HMAC-Hash(salt, IKM) */
+    return HMAC(evp_md, salt, salt_len, ikm, ikm_len, prk, NULL) != NULL;
+}
+
+/*
+ * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
+ * Section 2.3 (https://tools.ietf.org/html/rfc5869#section-2.3).
+ *
+ * 2.3.  Step 2: Expand
+ *
+ *   HKDF-Expand(PRK, info, L) -> OKM
+ *
+ *   Options:
+ *      Hash     a hash function; HashLen denotes the length of the
+ *               hash function output in octets
+ *
+ *   Inputs:
+ *      PRK      a pseudorandom key of at least HashLen octets
+ *               (usually, the output from the extract step)
+ *      info     optional context and application specific information
+ *               (can be a zero-length string)
+ *      L        length of output keying material in octets
+ *               (<= 255*HashLen)
+ *
+ *   Output:
+ *      OKM      output keying material (of L octets)
+ *
+ *   The output OKM is calculated as follows:
+ *
+ *   N = ceil(L/HashLen)
+ *   T = T(1) | T(2) | T(3) | ... | T(N)
+ *   OKM = first L octets of T
+ *
+ *   where:
+ *   T(0) = empty string (zero length)
+ *   T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
+ *   T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
+ *   T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
+ *   ...
+ *
+ *   (where the constant concatenated to the end of each T(n) is a
+ *   single octet.)
+ */
+static int HKDF_Expand(const EVP_MD *evp_md,
+                       const unsigned char *prk, size_t prk_len,
+                       const unsigned char *info, size_t info_len,
+                       unsigned char *okm, size_t okm_len)
+{
+    HMAC_CTX *hmac;
+    int ret = 0, sz;
+    unsigned int i;
+    unsigned char prev[EVP_MAX_MD_SIZE];
+    size_t done_len = 0, dig_len, n;
+
+    sz = EVP_MD_size(evp_md);
+    if (sz <= 0)
+        return 0;
+    dig_len = (size_t)sz;
+
+    /* calc: N = ceil(L/HashLen) */
+    n = okm_len / dig_len;
+    if (okm_len % dig_len)
+        n++;
+
+    if (n > 255 || okm == NULL)
+        return 0;
+
+    if ((hmac = HMAC_CTX_new()) == NULL)
+        return 0;
+
+    if (!HMAC_Init_ex(hmac, prk, prk_len, evp_md, NULL))
+        goto err;
+
+    for (i = 1; i <= n; i++) {
+        size_t copy_len;
+        const unsigned char ctr = i;
+
+        /* calc: T(i) = HMAC-Hash(PRK, T(i - 1) | info | i) */
+        if (i > 1) {
+            if (!HMAC_Init_ex(hmac, NULL, 0, NULL, NULL))
+                goto err;
+
+            if (!HMAC_Update(hmac, prev, dig_len))
+                goto err;
+        }
+
+        if (!HMAC_Update(hmac, info, info_len))
+            goto err;
+
+        if (!HMAC_Update(hmac, &ctr, 1))
+            goto err;
+
+        if (!HMAC_Final(hmac, prev, NULL))
+            goto err;
+
+        copy_len = (done_len + dig_len > okm_len) ?
+                       okm_len - done_len :
+                       dig_len;
+
+        memcpy(okm + done_len, prev, copy_len);
+
+        done_len += copy_len;
+    }
+    ret = 1;
+
+ err:
+    OPENSSL_cleanse(prev, sizeof(prev));
+    HMAC_CTX_free(hmac);
+    return ret;
+}
diff --git a/providers/common/kdfs/pbkdf2.c b/providers/common/kdfs/pbkdf2.c
new file mode 100644 (file)
index 0000000..d416897
--- /dev/null
@@ -0,0 +1,324 @@
+/*
+ * Copyright 2018-2019 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License").  You may not use
+ * this file except in compliance with the License.  You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <openssl/hmac.h>
+#include <openssl/evp.h>
+#include <openssl/kdf.h>
+#include "internal/cryptlib.h"
+#include "internal/evp_int.h"
+#include "kdf_local.h"
+
+/* Constants specified in SP800-132 */
+#define KDF_PBKDF2_MIN_KEY_LEN_BITS  112
+#define KDF_PBKDF2_MAX_KEY_LEN_DIGEST_RATIO 0xFFFFFFFF
+#define KDF_PBKDF2_MIN_ITERATIONS 1000
+#define KDF_PBKDF2_MIN_SALT_LEN   (128 / 8)
+/*
+ * For backwards compatibility reasons,
+ * Extra checks are done by default in fips mode only.
+ */
+#ifdef FIPS_MODE
+# define KDF_PBKDF2_DEFAULT_CHECKS 1
+#else
+# define KDF_PBKDF2_DEFAULT_CHECKS 0
+#endif /* FIPS_MODE */
+
+static void kdf_pbkdf2_reset(EVP_KDF_IMPL *impl);
+static void kdf_pbkdf2_init(EVP_KDF_IMPL *impl);
+static int  pbkdf2_derive(const char *pass, size_t passlen,
+                          const unsigned char *salt, int saltlen, int iter,
+                          const EVP_MD *digest, unsigned char *key,
+                          size_t keylen, int extra_checks);
+
+struct evp_kdf_impl_st {
+    unsigned char *pass;
+    size_t pass_len;
+    unsigned char *salt;
+    size_t salt_len;
+    int iter;
+    const EVP_MD *md;
+    int lower_bound_checks;
+};
+
+static EVP_KDF_IMPL *kdf_pbkdf2_new(void)
+{
+    EVP_KDF_IMPL *impl;
+
+    impl = OPENSSL_zalloc(sizeof(*impl));
+    if (impl == NULL) {
+        KDFerr(KDF_F_KDF_PBKDF2_NEW, ERR_R_MALLOC_FAILURE);
+        return NULL;
+    }
+    kdf_pbkdf2_init(impl);
+    return impl;
+}
+
+static void kdf_pbkdf2_free(EVP_KDF_IMPL *impl)
+{
+    kdf_pbkdf2_reset(impl);
+    OPENSSL_free(impl);
+}
+
+static void kdf_pbkdf2_reset(EVP_KDF_IMPL *impl)
+{
+    OPENSSL_free(impl->salt);
+    OPENSSL_clear_free(impl->pass, impl->pass_len);
+    memset(impl, 0, sizeof(*impl));
+    kdf_pbkdf2_init(impl);
+}
+
+static void kdf_pbkdf2_init(EVP_KDF_IMPL *impl)
+{
+    impl->iter = PKCS5_DEFAULT_ITER;
+    impl->md = EVP_sha1();
+    impl->lower_bound_checks = KDF_PBKDF2_DEFAULT_CHECKS;
+}
+
+static int pbkdf2_set_membuf(unsigned char **buffer, size_t *buflen,
+                             const unsigned char *new_buffer,
+                             size_t new_buflen)
+{
+    if (new_buffer == NULL)
+        return 1;
+
+    OPENSSL_clear_free(*buffer, *buflen);
+
+    if (new_buflen > 0) {
+        *buffer = OPENSSL_memdup(new_buffer, new_buflen);
+    } else {
+        *buffer = OPENSSL_malloc(1);
+    }
+    if (*buffer == NULL) {
+        KDFerr(KDF_F_PBKDF2_SET_MEMBUF, ERR_R_MALLOC_FAILURE);
+        return 0;
+    }
+
+    *buflen = new_buflen;
+    return 1;
+}
+
+static int kdf_pbkdf2_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
+{
+    int iter, pkcs5, min_iter;
+    const unsigned char *p;
+    size_t len;
+    const EVP_MD *md;
+
+    switch (cmd) {
+    case EVP_KDF_CTRL_SET_PBKDF2_PKCS5_MODE:
+        pkcs5 = va_arg(args, int);
+        impl->lower_bound_checks = (pkcs5 == 0) ? 1 : 0;
+        return 1;
+    case EVP_KDF_CTRL_SET_PASS:
+        p = va_arg(args, const unsigned char *);
+        len = va_arg(args, size_t);
+        return pbkdf2_set_membuf(&impl->pass, &impl->pass_len, p, len);
+
+    case EVP_KDF_CTRL_SET_SALT:
+        p = va_arg(args, const unsigned char *);
+        len = va_arg(args, size_t);
+        if (impl->lower_bound_checks != 0 && len < KDF_PBKDF2_MIN_SALT_LEN) {
+            KDFerr(KDF_F_KDF_PBKDF2_CTRL, KDF_R_INVALID_SALT_LEN);
+            return 0;
+        }
+        return pbkdf2_set_membuf(&impl->salt, &impl->salt_len, p, len);
+
+    case EVP_KDF_CTRL_SET_ITER:
+        iter = va_arg(args, int);
+        min_iter = impl->lower_bound_checks != 0 ? KDF_PBKDF2_MIN_ITERATIONS : 1;
+        if (iter < min_iter) {
+            KDFerr(KDF_F_KDF_PBKDF2_CTRL, KDF_R_INVALID_ITERATION_COUNT);
+            return 0;
+        }
+        impl->iter = iter;
+        return 1;
+
+    case EVP_KDF_CTRL_SET_MD:
+        md = va_arg(args, const EVP_MD *);
+        if (md == NULL) {
+            KDFerr(KDF_F_KDF_PBKDF2_CTRL, KDF_R_VALUE_MISSING);
+            return 0;
+        }
+
+        impl->md = md;
+        return 1;
+
+    default:
+        return -2;
+    }
+}
+
+static int kdf_pbkdf2_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
+                               const char *value)
+{
+    if (value == NULL) {
+        KDFerr(KDF_F_KDF_PBKDF2_CTRL_STR, KDF_R_VALUE_MISSING);
+        return 0;
+    }
+
+    if (strcmp(type, "pass") == 0)
+        return kdf_str2ctrl(impl, kdf_pbkdf2_ctrl, EVP_KDF_CTRL_SET_PASS,
+                            value);
+
+    if (strcmp(type, "hexpass") == 0)
+        return kdf_hex2ctrl(impl, kdf_pbkdf2_ctrl, EVP_KDF_CTRL_SET_PASS,
+                            value);
+
+    if (strcmp(type, "salt") == 0)
+        return kdf_str2ctrl(impl, kdf_pbkdf2_ctrl, EVP_KDF_CTRL_SET_SALT,
+                            value);
+
+    if (strcmp(type, "hexsalt") == 0)
+        return kdf_hex2ctrl(impl, kdf_pbkdf2_ctrl, EVP_KDF_CTRL_SET_SALT,
+                            value);
+
+    if (strcmp(type, "iter") == 0)
+        return call_ctrl(kdf_pbkdf2_ctrl, impl, EVP_KDF_CTRL_SET_ITER,
+                         atoi(value));
+
+    if (strcmp(type, "digest") == 0)
+        return kdf_md2ctrl(impl, kdf_pbkdf2_ctrl, EVP_KDF_CTRL_SET_MD, value);
+
+    if (strcmp(type, "pkcs5") == 0)
+        return kdf_str2ctrl(impl, kdf_pbkdf2_ctrl,
+                            EVP_KDF_CTRL_SET_PBKDF2_PKCS5_MODE, value);
+    return -2;
+}
+
+static int kdf_pbkdf2_derive(EVP_KDF_IMPL *impl, unsigned char *key,
+                             size_t keylen)
+{
+    if (impl->pass == NULL) {
+        KDFerr(KDF_F_KDF_PBKDF2_DERIVE, KDF_R_MISSING_PASS);
+        return 0;
+    }
+
+    if (impl->salt == NULL) {
+        KDFerr(KDF_F_KDF_PBKDF2_DERIVE, KDF_R_MISSING_SALT);
+        return 0;
+    }
+
+    return pbkdf2_derive((char *)impl->pass, impl->pass_len,
+                         impl->salt, impl->salt_len, impl->iter,
+                         impl->md, key, keylen, impl->lower_bound_checks);
+}
+
+const EVP_KDF pbkdf2_kdf_meth = {
+    EVP_KDF_PBKDF2,
+    kdf_pbkdf2_new,
+    kdf_pbkdf2_free,
+    kdf_pbkdf2_reset,
+    kdf_pbkdf2_ctrl,
+    kdf_pbkdf2_ctrl_str,
+    NULL,
+    kdf_pbkdf2_derive
+};
+
+/*
+ * This is an implementation of PKCS#5 v2.0 password based encryption key
+ * derivation function PBKDF2. SHA1 version verified against test vectors
+ * posted by Peter Gutmann to the PKCS-TNG mailing list.
+ *
+ * The constraints specified by SP800-132 have been added i.e.
+ *  - Check the range of the key length.
+ *  - Minimum iteration count of 1000.
+ *  - Randomly-generated portion of the salt shall be at least 128 bits.
+ */
+static int pbkdf2_derive(const char *pass, size_t passlen,
+                         const unsigned char *salt, int saltlen, int iter,
+                         const EVP_MD *digest, unsigned char *key,
+                         size_t keylen, int lower_bound_checks)
+{
+    int ret = 0;
+    unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
+    int cplen, j, k, tkeylen, mdlen;
+    unsigned long i = 1;
+    HMAC_CTX *hctx_tpl = NULL, *hctx = NULL;
+
+    mdlen = EVP_MD_size(digest);
+    if (mdlen <= 0)
+        return 0;
+
+    /*
+     * This check should always be done because keylen / mdlen >= (2^32 - 1)
+     * results in an overflow of the loop counter 'i'.
+     */
+    if ((keylen / mdlen) >= KDF_PBKDF2_MAX_KEY_LEN_DIGEST_RATIO) {
+        KDFerr(KDF_F_PBKDF2_DERIVE, KDF_R_INVALID_KEY_LEN);
+        return 0;
+    }
+
+    if (lower_bound_checks) {
+         if ((keylen * 8) < KDF_PBKDF2_MIN_KEY_LEN_BITS) {
+             KDFerr(KDF_F_PBKDF2_DERIVE, KDF_R_INVALID_KEY_LEN);
+             return 0;
+         }
+         if (saltlen < KDF_PBKDF2_MIN_SALT_LEN) {
+             KDFerr(KDF_F_PBKDF2_DERIVE, KDF_R_INVALID_SALT_LEN);
+            return 0;
+         }
+         if (iter < KDF_PBKDF2_MIN_ITERATIONS) {
+             KDFerr(KDF_F_PBKDF2_DERIVE, KDF_R_INVALID_ITERATION_COUNT);
+             return 0;
+         }
+    }
+
+    hctx_tpl = HMAC_CTX_new();
+    if (hctx_tpl == NULL)
+        return 0;
+    p = key;
+    tkeylen = keylen;
+    if (!HMAC_Init_ex(hctx_tpl, pass, passlen, digest, NULL))
+        goto err;
+    hctx = HMAC_CTX_new();
+    if (hctx == NULL)
+        goto err;
+    while (tkeylen) {
+        if (tkeylen > mdlen)
+            cplen = mdlen;
+        else
+            cplen = tkeylen;
+        /*
+         * We are unlikely to ever use more than 256 blocks (5120 bits!) but
+         * just in case...
+         */
+        itmp[0] = (unsigned char)((i >> 24) & 0xff);
+        itmp[1] = (unsigned char)((i >> 16) & 0xff);
+        itmp[2] = (unsigned char)((i >> 8) & 0xff);
+        itmp[3] = (unsigned char)(i & 0xff);
+        if (!HMAC_CTX_copy(hctx, hctx_tpl))
+            goto err;
+        if (!HMAC_Update(hctx, salt, saltlen)
+                || !HMAC_Update(hctx, itmp, 4)
+                || !HMAC_Final(hctx, digtmp, NULL))
+            goto err;
+        memcpy(p, digtmp, cplen);
+        for (j = 1; j < iter; j++) {
+            if (!HMAC_CTX_copy(hctx, hctx_tpl))
+                goto err;
+            if (!HMAC_Update(hctx, digtmp, mdlen)
+                    || !HMAC_Final(hctx, digtmp, NULL))
+                goto err;
+            for (k = 0; k < cplen; k++)
+                p[k] ^= digtmp[k];
+        }
+        tkeylen -= cplen;
+        i++;
+        p += cplen;
+    }
+    ret = 1;
+
+err:
+    HMAC_CTX_free(hctx);
+    HMAC_CTX_free(hctx_tpl);
+    return ret;
+}
diff --git a/providers/common/kdfs/scrypt.c b/providers/common/kdfs/scrypt.c
new file mode 100644 (file)
index 0000000..29ceeb3
--- /dev/null
@@ -0,0 +1,506 @@
+/*
+ * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License").  You may not use
+ * this file except in compliance with the License.  You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <openssl/evp.h>
+#include <openssl/kdf.h>
+#include <openssl/err.h>
+#include "internal/evp_int.h"
+#include "internal/numbers.h"
+#include "kdf_local.h"
+
+#ifndef OPENSSL_NO_SCRYPT
+
+static void kdf_scrypt_reset(EVP_KDF_IMPL *impl);
+static void kdf_scrypt_init(EVP_KDF_IMPL *impl);
+static int atou64(const char *nptr, uint64_t *result);
+static int scrypt_alg(const char *pass, size_t passlen,
+                      const unsigned char *salt, size_t saltlen,
+                      uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
+                      unsigned char *key, size_t keylen);
+
+struct evp_kdf_impl_st {
+    unsigned char *pass;
+    size_t pass_len;
+    unsigned char *salt;
+    size_t salt_len;
+    uint64_t N;
+    uint32_t r, p;
+    uint64_t maxmem_bytes;
+};
+
+/* Custom uint64_t parser since we do not have strtoull */
+static int atou64(const char *nptr, uint64_t *result)
+{
+    uint64_t value = 0;
+
+    while (*nptr) {
+        unsigned int digit;
+        uint64_t new_value;
+
+        if ((*nptr < '0') || (*nptr > '9')) {
+            return 0;
+        }
+        digit = (unsigned int)(*nptr - '0');
+        new_value = (value * 10) + digit;
+        if ((new_value < digit) || ((new_value - digit) / 10 != value)) {
+            /* Overflow */
+            return 0;
+        }
+        value = new_value;
+        nptr++;
+    }
+    *result = value;
+    return 1;
+}
+
+static EVP_KDF_IMPL *kdf_scrypt_new(void)
+{
+    EVP_KDF_IMPL *impl;
+
+    impl = OPENSSL_zalloc(sizeof(*impl));
+    if (impl == NULL) {
+        KDFerr(KDF_F_KDF_SCRYPT_NEW, ERR_R_MALLOC_FAILURE);
+        return NULL;
+    }
+    kdf_scrypt_init(impl);
+    return impl;
+}
+
+static void kdf_scrypt_free(EVP_KDF_IMPL *impl)
+{
+    kdf_scrypt_reset(impl);
+    OPENSSL_free(impl);
+}
+
+static void kdf_scrypt_reset(EVP_KDF_IMPL *impl)
+{
+    OPENSSL_free(impl->salt);
+    OPENSSL_clear_free(impl->pass, impl->pass_len);
+    memset(impl, 0, sizeof(*impl));
+    kdf_scrypt_init(impl);
+}
+
+static void kdf_scrypt_init(EVP_KDF_IMPL *impl)
+{
+    /* Default values are the most conservative recommendation given in the
+     * original paper of C. Percival. Derivation uses roughly 1 GiB of memory
+     * for this parameter choice (approx. 128 * r * N * p bytes).
+     */
+    impl->N = 1 << 20;
+    impl->r = 8;
+    impl->p = 1;
+    impl->maxmem_bytes = 1025 * 1024 * 1024;
+}
+
+static int scrypt_set_membuf(unsigned char **buffer, size_t *buflen,
+                             const unsigned char *new_buffer,
+                             size_t new_buflen)
+{
+    if (new_buffer == NULL)
+        return 1;
+
+    OPENSSL_clear_free(*buffer, *buflen);
+
+    if (new_buflen > 0) {
+        *buffer = OPENSSL_memdup(new_buffer, new_buflen);
+    } else {
+        *buffer = OPENSSL_malloc(1);
+    }
+    if (*buffer == NULL) {
+        KDFerr(KDF_F_SCRYPT_SET_MEMBUF, ERR_R_MALLOC_FAILURE);
+        return 0;
+    }
+
+    *buflen = new_buflen;
+    return 1;
+}
+
+static int is_power_of_two(uint64_t value)
+{
+    return (value != 0) && ((value & (value - 1)) == 0);
+}
+
+static int kdf_scrypt_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
+{
+    uint64_t u64_value;
+    uint32_t value;
+    const unsigned char *p;
+    size_t len;
+
+    switch (cmd) {
+    case EVP_KDF_CTRL_SET_PASS:
+        p = va_arg(args, const unsigned char *);
+        len = va_arg(args, size_t);
+        return scrypt_set_membuf(&impl->pass, &impl->pass_len, p, len);
+
+    case EVP_KDF_CTRL_SET_SALT:
+        p = va_arg(args, const unsigned char *);
+        len = va_arg(args, size_t);
+        return scrypt_set_membuf(&impl->salt, &impl->salt_len, p, len);
+
+    case EVP_KDF_CTRL_SET_SCRYPT_N:
+        u64_value = va_arg(args, uint64_t);
+        if ((u64_value <= 1) || !is_power_of_two(u64_value))
+            return 0;
+
+        impl->N = u64_value;
+        return 1;
+
+    case EVP_KDF_CTRL_SET_SCRYPT_R:
+        value = va_arg(args, uint32_t);
+        if (value < 1)
+            return 0;
+
+        impl->r = value;
+        return 1;
+
+    case EVP_KDF_CTRL_SET_SCRYPT_P:
+        value = va_arg(args, uint32_t);
+        if (value < 1)
+            return 0;
+
+        impl->p = value;
+        return 1;
+
+    case EVP_KDF_CTRL_SET_MAXMEM_BYTES:
+        u64_value = va_arg(args, uint64_t);
+        if (u64_value < 1)
+            return 0;
+
+        impl->maxmem_bytes = u64_value;
+        return 1;
+
+    default:
+        return -2;
+    }
+}
+
+static int kdf_scrypt_ctrl_uint32(EVP_KDF_IMPL *impl, int cmd,
+                                  const char *value)
+{
+    int int_value = atoi(value);
+
+    if (int_value < 0 || (uint64_t)int_value > UINT32_MAX) {
+        KDFerr(KDF_F_KDF_SCRYPT_CTRL_UINT32, KDF_R_VALUE_ERROR);
+        return 0;
+    }
+    return call_ctrl(kdf_scrypt_ctrl, impl, cmd, (uint32_t)int_value);
+}
+
+static int kdf_scrypt_ctrl_uint64(EVP_KDF_IMPL *impl, int cmd,
+                                  const char *value)
+{
+    uint64_t u64_value;
+
+    if (!atou64(value, &u64_value)) {
+        KDFerr(KDF_F_KDF_SCRYPT_CTRL_UINT64, KDF_R_VALUE_ERROR);
+        return 0;
+    }
+    return call_ctrl(kdf_scrypt_ctrl, impl, cmd, u64_value);
+}
+
+static int kdf_scrypt_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
+                               const char *value)
+{
+    if (value == NULL) {
+        KDFerr(KDF_F_KDF_SCRYPT_CTRL_STR, KDF_R_VALUE_MISSING);
+        return 0;
+    }
+
+    if (strcmp(type, "pass") == 0)
+        return kdf_str2ctrl(impl, kdf_scrypt_ctrl, EVP_KDF_CTRL_SET_PASS,
+                            value);
+
+    if (strcmp(type, "hexpass") == 0)
+        return kdf_hex2ctrl(impl, kdf_scrypt_ctrl, EVP_KDF_CTRL_SET_PASS,
+                            value);
+
+    if (strcmp(type, "salt") == 0)
+        return kdf_str2ctrl(impl, kdf_scrypt_ctrl, EVP_KDF_CTRL_SET_SALT,
+                            value);
+
+    if (strcmp(type, "hexsalt") == 0)
+        return kdf_hex2ctrl(impl, kdf_scrypt_ctrl, EVP_KDF_CTRL_SET_SALT,
+                            value);
+
+    if (strcmp(type, "N") == 0)
+        return kdf_scrypt_ctrl_uint64(impl, EVP_KDF_CTRL_SET_SCRYPT_N, value);
+
+    if (strcmp(type, "r") == 0)
+        return kdf_scrypt_ctrl_uint32(impl, EVP_KDF_CTRL_SET_SCRYPT_R, value);
+
+    if (strcmp(type, "p") == 0)
+        return kdf_scrypt_ctrl_uint32(impl, EVP_KDF_CTRL_SET_SCRYPT_P, value);
+
+    if (strcmp(type, "maxmem_bytes") == 0)
+        return kdf_scrypt_ctrl_uint64(impl, EVP_KDF_CTRL_SET_MAXMEM_BYTES,
+                                      value);
+
+    return -2;
+}
+
+static int kdf_scrypt_derive(EVP_KDF_IMPL *impl, unsigned char *key,
+                             size_t keylen)
+{
+    if (impl->pass == NULL) {
+        KDFerr(KDF_F_KDF_SCRYPT_DERIVE, KDF_R_MISSING_PASS);
+        return 0;
+    }
+
+    if (impl->salt == NULL) {
+        KDFerr(KDF_F_KDF_SCRYPT_DERIVE, KDF_R_MISSING_SALT);
+        return 0;
+    }
+
+    return scrypt_alg((char *)impl->pass, impl->pass_len, impl->salt,
+                      impl->salt_len, impl->N, impl->r, impl->p,
+                      impl->maxmem_bytes, key, keylen);
+}
+
+const EVP_KDF scrypt_kdf_meth = {
+    EVP_KDF_SCRYPT,
+    kdf_scrypt_new,
+    kdf_scrypt_free,
+    kdf_scrypt_reset,
+    kdf_scrypt_ctrl,
+    kdf_scrypt_ctrl_str,
+    NULL,
+    kdf_scrypt_derive
+};
+
+#define R(a,b) (((a) << (b)) | ((a) >> (32 - (b))))
+static void salsa208_word_specification(uint32_t inout[16])
+{
+    int i;
+    uint32_t x[16];
+
+    memcpy(x, inout, sizeof(x));
+    for (i = 8; i > 0; i -= 2) {
+        x[4] ^= R(x[0] + x[12], 7);
+        x[8] ^= R(x[4] + x[0], 9);
+        x[12] ^= R(x[8] + x[4], 13);
+        x[0] ^= R(x[12] + x[8], 18);
+        x[9] ^= R(x[5] + x[1], 7);
+        x[13] ^= R(x[9] + x[5], 9);
+        x[1] ^= R(x[13] + x[9], 13);
+        x[5] ^= R(x[1] + x[13], 18);
+        x[14] ^= R(x[10] + x[6], 7);
+        x[2] ^= R(x[14] + x[10], 9);
+        x[6] ^= R(x[2] + x[14], 13);
+        x[10] ^= R(x[6] + x[2], 18);
+        x[3] ^= R(x[15] + x[11], 7);
+        x[7] ^= R(x[3] + x[15], 9);
+        x[11] ^= R(x[7] + x[3], 13);
+        x[15] ^= R(x[11] + x[7], 18);
+        x[1] ^= R(x[0] + x[3], 7);
+        x[2] ^= R(x[1] + x[0], 9);
+        x[3] ^= R(x[2] + x[1], 13);
+        x[0] ^= R(x[3] + x[2], 18);
+        x[6] ^= R(x[5] + x[4], 7);
+        x[7] ^= R(x[6] + x[5], 9);
+        x[4] ^= R(x[7] + x[6], 13);
+        x[5] ^= R(x[4] + x[7], 18);
+        x[11] ^= R(x[10] + x[9], 7);
+        x[8] ^= R(x[11] + x[10], 9);
+        x[9] ^= R(x[8] + x[11], 13);
+        x[10] ^= R(x[9] + x[8], 18);
+        x[12] ^= R(x[15] + x[14], 7);
+        x[13] ^= R(x[12] + x[15], 9);
+        x[14] ^= R(x[13] + x[12], 13);
+        x[15] ^= R(x[14] + x[13], 18);
+    }
+    for (i = 0; i < 16; ++i)
+        inout[i] += x[i];
+    OPENSSL_cleanse(x, sizeof(x));
+}
+
+static void scryptBlockMix(uint32_t *B_, uint32_t *B, uint64_t r)
+{
+    uint64_t i, j;
+    uint32_t X[16], *pB;
+
+    memcpy(X, B + (r * 2 - 1) * 16, sizeof(X));
+    pB = B;
+    for (i = 0; i < r * 2; i++) {
+        for (j = 0; j < 16; j++)
+            X[j] ^= *pB++;
+        salsa208_word_specification(X);
+        memcpy(B_ + (i / 2 + (i & 1) * r) * 16, X, sizeof(X));
+    }
+    OPENSSL_cleanse(X, sizeof(X));
+}
+
+static void scryptROMix(unsigned char *B, uint64_t r, uint64_t N,
+                        uint32_t *X, uint32_t *T, uint32_t *V)
+{
+    unsigned char *pB;
+    uint32_t *pV;
+    uint64_t i, k;
+
+    /* Convert from little endian input */
+    for (pV = V, i = 0, pB = B; i < 32 * r; i++, pV++) {
+        *pV = *pB++;
+        *pV |= *pB++ << 8;
+        *pV |= *pB++ << 16;
+        *pV |= (uint32_t)*pB++ << 24;
+    }
+
+    for (i = 1; i < N; i++, pV += 32 * r)
+        scryptBlockMix(pV, pV - 32 * r, r);
+
+    scryptBlockMix(X, V + (N - 1) * 32 * r, r);
+
+    for (i = 0; i < N; i++) {
+        uint32_t j;
+        j = X[16 * (2 * r - 1)] % N;
+        pV = V + 32 * r * j;
+        for (k = 0; k < 32 * r; k++)
+            T[k] = X[k] ^ *pV++;
+        scryptBlockMix(X, T, r);
+    }
+    /* Convert output to little endian */
+    for (i = 0, pB = B; i < 32 * r; i++) {
+        uint32_t xtmp = X[i];
+        *pB++ = xtmp & 0xff;
+        *pB++ = (xtmp >> 8) & 0xff;
+        *pB++ = (xtmp >> 16) & 0xff;
+        *pB++ = (xtmp >> 24) & 0xff;
+    }
+}
+
+#ifndef SIZE_MAX
+# define SIZE_MAX    ((size_t)-1)
+#endif
+
+/*
+ * Maximum power of two that will fit in uint64_t: this should work on
+ * most (all?) platforms.
+ */
+
+#define LOG2_UINT64_MAX         (sizeof(uint64_t) * 8 - 1)
+
+/*
+ * Maximum value of p * r:
+ * p <= ((2^32-1) * hLen) / MFLen =>
+ * p <= ((2^32-1) * 32) / (128 * r) =>
+ * p * r <= (2^30-1)
+ */
+
+#define SCRYPT_PR_MAX   ((1 << 30) - 1)
+
+static int scrypt_alg(const char *pass, size_t passlen,
+                      const unsigned char *salt, size_t saltlen,
+                      uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
+                      unsigned char *key, size_t keylen)
+{
+    int rv = 0;
+    unsigned char *B;
+    uint32_t *X, *V, *T;
+    uint64_t i, Blen, Vlen;
+
+    /* Sanity check parameters */
+    /* initial check, r,p must be non zero, N >= 2 and a power of 2 */
+    if (r == 0 || p == 0 || N < 2 || (N & (N - 1)))
+        return 0;
+    /* Check p * r < SCRYPT_PR_MAX avoiding overflow */
+    if (p > SCRYPT_PR_MAX / r) {
+        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
+        return 0;
+    }
+
+    /*
+     * Need to check N: if 2^(128 * r / 8) overflows limit this is
+     * automatically satisfied since N <= UINT64_MAX.
+     */
+
+    if (16 * r <= LOG2_UINT64_MAX) {
+        if (N >= (((uint64_t)1) << (16 * r))) {
+            EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
+            return 0;
+        }
+    }
+
+    /* Memory checks: check total allocated buffer size fits in uint64_t */
+
+    /*
+     * B size in section 5 step 1.S
+     * Note: we know p * 128 * r < UINT64_MAX because we already checked
+     * p * r < SCRYPT_PR_MAX
+     */
+    Blen = p * 128 * r;
+    /*
+     * Yet we pass it as integer to PKCS5_PBKDF2_HMAC... [This would
+     * have to be revised when/if PKCS5_PBKDF2_HMAC accepts size_t.]
+     */
+    if (Blen > INT_MAX) {
+        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
+        return 0;
+    }
+
+    /*
+     * Check 32 * r * (N + 2) * sizeof(uint32_t) fits in uint64_t
+     * This is combined size V, X and T (section 4)
+     */
+    i = UINT64_MAX / (32 * sizeof(uint32_t));
+    if (N + 2 > i / r) {
+        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
+        return 0;
+    }
+    Vlen = 32 * r * (N + 2) * sizeof(uint32_t);
+
+    /* check total allocated size fits in uint64_t */
+    if (Blen > UINT64_MAX - Vlen) {
+        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
+        return 0;
+    }
+
+    /* Check that the maximum memory doesn't exceed a size_t limits */
+    if (maxmem > SIZE_MAX)
+        maxmem = SIZE_MAX;
+
+    if (Blen + Vlen > maxmem) {
+        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
+        return 0;
+    }
+
+    /* If no key return to indicate parameters are OK */
+    if (key == NULL)
+        return 1;
+
+    B = OPENSSL_malloc((size_t)(Blen + Vlen));
+    if (B == NULL) {
+        EVPerr(EVP_F_SCRYPT_ALG, ERR_R_MALLOC_FAILURE);
+        return 0;
+    }
+    X = (uint32_t *)(B + Blen);
+    T = X + 32 * r;
+    V = T + 32 * r;
+    if (PKCS5_PBKDF2_HMAC(pass, passlen, salt, saltlen, 1, EVP_sha256(),
+                          (int)Blen, B) == 0)
+        goto err;
+
+    for (i = 0; i < p; i++)
+        scryptROMix(B + 128 * r * i, r, N, X, T, V);
+
+    if (PKCS5_PBKDF2_HMAC(pass, passlen, B, (int)Blen, 1, EVP_sha256(),
+                          keylen, key) == 0)
+        goto err;
+    rv = 1;
+ err:
+    if (rv == 0)
+        EVPerr(EVP_F_SCRYPT_ALG, EVP_R_PBKDF2_ERROR);
+
+    OPENSSL_clear_free(B, (size_t)(Blen + Vlen));
+    return rv;
+}
+
+#endif
diff --git a/providers/common/kdfs/sshkdf.c b/providers/common/kdfs/sshkdf.c
new file mode 100644 (file)
index 0000000..4701c9c
--- /dev/null
@@ -0,0 +1,292 @@
+/*
+ * Copyright 2018-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
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <openssl/evp.h>
+#include <openssl/kdf.h>
+#include "internal/cryptlib.h"
+#include "internal/numbers.h"
+#include "internal/evp_int.h"
+#include "kdf_local.h"
+
+/* See RFC 4253, Section 7.2 */
+
+static void kdf_sshkdf_reset(EVP_KDF_IMPL *impl);
+static int SSHKDF(const EVP_MD *evp_md,
+                  const unsigned char *key, size_t key_len,
+                  const unsigned char *xcghash, size_t xcghash_len,
+                  const unsigned char *session_id, size_t session_id_len,
+                  char type, unsigned char *okey, size_t okey_len);
+
+struct evp_kdf_impl_st {
+    const EVP_MD *md;
+    unsigned char *key; /* K */
+    size_t key_len;
+    unsigned char *xcghash; /* H */
+    size_t xcghash_len;
+    char type; /* X */
+    unsigned char *session_id;
+    size_t session_id_len;
+};
+
+static EVP_KDF_IMPL *kdf_sshkdf_new(void)
+{
+    EVP_KDF_IMPL *impl;
+
+    if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
+        KDFerr(KDF_F_KDF_SSHKDF_NEW, ERR_R_MALLOC_FAILURE);
+    return impl;
+}
+
+static void kdf_sshkdf_free(EVP_KDF_IMPL *impl)
+{
+    kdf_sshkdf_reset(impl);
+    OPENSSL_free(impl);
+}
+
+static void kdf_sshkdf_reset(EVP_KDF_IMPL *impl)
+{
+    OPENSSL_clear_free(impl->key, impl->key_len);
+    OPENSSL_clear_free(impl->xcghash, impl->xcghash_len);
+    OPENSSL_clear_free(impl->session_id, impl->session_id_len);
+    memset(impl, 0, sizeof(*impl));
+}
+
+static int kdf_sshkdf_parse_buffer_arg(unsigned char **dst, size_t *dst_len,
+                                       va_list args)
+{
+    const unsigned char *p;
+    size_t len;
+
+    p = va_arg(args, const unsigned char *);
+    len = va_arg(args, size_t);
+    OPENSSL_clear_free(*dst, *dst_len);
+    *dst = OPENSSL_memdup(p, len);
+    if (*dst == NULL)
+        return 0;
+
+    *dst_len = len;
+    return 1;
+}
+
+static int kdf_sshkdf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
+{
+    int t;
+
+    switch (cmd) {
+    case EVP_KDF_CTRL_SET_MD:
+        impl->md = va_arg(args, const EVP_MD *);
+        if (impl->md == NULL)
+            return 0;
+
+        return 1;
+
+    case EVP_KDF_CTRL_SET_KEY:
+        return kdf_sshkdf_parse_buffer_arg(&impl->key,
+                                           &impl->key_len, args);
+
+    case EVP_KDF_CTRL_SET_SSHKDF_XCGHASH:
+        return kdf_sshkdf_parse_buffer_arg(&impl->xcghash,
+                                           &impl->xcghash_len, args);
+
+    case EVP_KDF_CTRL_SET_SSHKDF_SESSION_ID:
+        return kdf_sshkdf_parse_buffer_arg(&impl->session_id,
+                                           &impl->session_id_len, args);
+
+    case EVP_KDF_CTRL_SET_SSHKDF_TYPE:
+        t = va_arg(args, int);
+        if (t < 65 || t > 70) {
+            KDFerr(KDF_F_KDF_SSHKDF_CTRL, KDF_R_VALUE_ERROR);
+            return 0;
+        }
+
+        impl->type = (char)t;
+        return 1;
+
+    default:
+        return -2;
+
+    }
+}
+
+static int kdf_sshkdf_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
+                               const char *value)
+{
+    if (value == NULL) {
+        KDFerr(KDF_F_KDF_SSHKDF_CTRL_STR, KDF_R_VALUE_MISSING);
+        return 0;
+    }
+
+    if (strcmp(type, "digest") == 0)
+        return kdf_md2ctrl(impl, kdf_sshkdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
+    /* alias, for historical reasons */
+    if (strcmp(type, "md") == 0)
+        return kdf_md2ctrl(impl, kdf_sshkdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
+
+    if (strcmp(type, "key") == 0)
+        return kdf_str2ctrl(impl, kdf_sshkdf_ctrl,
+                            EVP_KDF_CTRL_SET_KEY, value);
+
+    if (strcmp(type, "hexkey") == 0)
+        return kdf_hex2ctrl(impl, kdf_sshkdf_ctrl,
+                            EVP_KDF_CTRL_SET_KEY, value);
+
+    if (strcmp(type, "xcghash") == 0)
+        return kdf_str2ctrl(impl, kdf_sshkdf_ctrl,
+                            EVP_KDF_CTRL_SET_SSHKDF_XCGHASH, value);
+
+    if (strcmp(type, "hexxcghash") == 0)
+        return kdf_hex2ctrl(impl, kdf_sshkdf_ctrl,
+                            EVP_KDF_CTRL_SET_SSHKDF_XCGHASH, value);
+
+    if (strcmp(type, "session_id") == 0)
+        return kdf_str2ctrl(impl, kdf_sshkdf_ctrl,
+                            EVP_KDF_CTRL_SET_SSHKDF_SESSION_ID, value);
+
+    if (strcmp(type, "hexsession_id") == 0)
+        return kdf_hex2ctrl(impl, kdf_sshkdf_ctrl,
+                            EVP_KDF_CTRL_SET_SSHKDF_SESSION_ID, value);
+
+    if (strcmp(type, "type") == 0) {
+        if (strlen(value) != 1) {
+            KDFerr(KDF_F_KDF_SSHKDF_CTRL_STR, KDF_R_VALUE_ERROR);
+            return 0;
+        }
+
+        return call_ctrl(kdf_sshkdf_ctrl, impl, EVP_KDF_CTRL_SET_SSHKDF_TYPE,
+                         (int)value[0]);
+    }
+
+    KDFerr(KDF_F_KDF_SSHKDF_CTRL_STR, KDF_R_UNKNOWN_PARAMETER_TYPE);
+    return -2;
+}
+
+static size_t kdf_sshkdf_size(EVP_KDF_IMPL *impl)
+{
+    return SIZE_MAX;
+}
+
+static int kdf_sshkdf_derive(EVP_KDF_IMPL *impl, unsigned char *key,
+                             size_t keylen)
+{
+    if (impl->md == NULL) {
+        KDFerr(KDF_F_KDF_SSHKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
+        return 0;
+    }
+    if (impl->key == NULL) {
+        KDFerr(KDF_F_KDF_SSHKDF_DERIVE, KDF_R_MISSING_KEY);
+        return 0;
+    }
+    if (impl->xcghash == NULL) {
+        KDFerr(KDF_F_KDF_SSHKDF_DERIVE, KDF_R_MISSING_XCGHASH);
+        return 0;
+    }
+    if (impl->session_id == NULL) {
+        KDFerr(KDF_F_KDF_SSHKDF_DERIVE, KDF_R_MISSING_SESSION_ID);
+        return 0;
+    }
+    if (impl->type == 0) {
+        KDFerr(KDF_F_KDF_SSHKDF_DERIVE, KDF_R_MISSING_TYPE);
+        return 0;
+    }
+    return SSHKDF(impl->md, impl->key, impl->key_len,
+                  impl->xcghash, impl->xcghash_len,
+                  impl->session_id, impl->session_id_len,
+                  impl->type, key, keylen);
+}
+
+const EVP_KDF sshkdf_kdf_meth = {
+    EVP_KDF_SSHKDF,
+    kdf_sshkdf_new,
+    kdf_sshkdf_free,
+    kdf_sshkdf_reset,
+    kdf_sshkdf_ctrl,
+    kdf_sshkdf_ctrl_str,
+    kdf_sshkdf_size,
+    kdf_sshkdf_derive,
+};
+
+static int SSHKDF(const EVP_MD *evp_md,
+                  const unsigned char *key, size_t key_len,
+                  const unsigned char *xcghash, size_t xcghash_len,
+                  const unsigned char *session_id, size_t session_id_len,
+                  char type, unsigned char *okey, size_t okey_len)
+{
+    EVP_MD_CTX *md = NULL;
+    unsigned char digest[EVP_MAX_MD_SIZE];
+    unsigned int dsize = 0;
+    size_t cursize = 0;
+    int ret = 0;
+
+    md = EVP_MD_CTX_new();
+    if (md == NULL)
+        return 0;
+
+    if (!EVP_DigestInit_ex(md, evp_md, NULL))
+        goto out;
+
+    if (!EVP_DigestUpdate(md, key, key_len))
+        goto out;
+
+    if (!EVP_DigestUpdate(md, xcghash, xcghash_len))
+        goto out;
+
+    if (!EVP_DigestUpdate(md, &type, 1))
+        goto out;
+
+    if (!EVP_DigestUpdate(md, session_id, session_id_len))
+        goto out;
+
+    if (!EVP_DigestFinal_ex(md, digest, &dsize))
+        goto out;
+
+    if (okey_len < dsize) {
+        memcpy(okey, digest, okey_len);
+        ret = 1;
+        goto out;
+    }
+
+    memcpy(okey, digest, dsize);
+
+    for (cursize = dsize; cursize < okey_len; cursize += dsize) {
+
+        if (!EVP_DigestInit_ex(md, evp_md, NULL))
+            goto out;
+
+        if (!EVP_DigestUpdate(md, key, key_len))
+            goto out;
+
+        if (!EVP_DigestUpdate(md, xcghash, xcghash_len))
+            goto out;
+
+        if (!EVP_DigestUpdate(md, okey, cursize))
+            goto out;
+
+        if (!EVP_DigestFinal_ex(md, digest, &dsize))
+            goto out;
+
+        if (okey_len < cursize + dsize) {
+            memcpy(okey + cursize, digest, okey_len - cursize);
+            ret = 1;
+            goto out;
+        }
+
+        memcpy(okey + cursize, digest, dsize);
+    }
+
+    ret = 1;
+
+out:
+    EVP_MD_CTX_free(md);
+    OPENSSL_cleanse(digest, EVP_MAX_MD_SIZE);
+    return ret;
+}
+
diff --git a/providers/common/kdfs/sskdf.c b/providers/common/kdfs/sskdf.c
new file mode 100644 (file)
index 0000000..b20eff2
--- /dev/null
@@ -0,0 +1,558 @@
+/*
+ * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2019, Oracle and/or its affiliates.  All rights reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License").  You may not use
+ * this file except in compliance with the License.  You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
+ * Section 4.1.
+ *
+ * The Single Step KDF algorithm is given by:
+ *
+ * Result(0) = empty bit string (i.e., the null string).
+ * For i = 1 to reps, do the following:
+ *   Increment counter by 1.
+ *   Result(i) = Result(i - 1) || H(counter || Z || FixedInfo).
+ * DKM = LeftmostBits(Result(reps), L))
+ *
+ * NOTES:
+ *   Z is a shared secret required to produce the derived key material.
+ *   counter is a 4 byte buffer.
+ *   FixedInfo is a bit string containing context specific data.
+ *   DKM is the output derived key material.
+ *   L is the required size of the DKM.
+ *   reps = [L / H_outputBits]
+ *   H(x) is the auxiliary function that can be either a hash, HMAC or KMAC.
+ *   H_outputBits is the length of the output of the auxiliary function H(x).
+ *
+ * Currently there is not a comprehensive list of test vectors for this
+ * algorithm, especially for H(x) = HMAC and H(x) = KMAC.
+ * Test vectors for H(x) = Hash are indirectly used by CAVS KAS tests.
+ */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <openssl/hmac.h>
+#include <openssl/evp.h>
+#include <openssl/kdf.h>
+#include <openssl/core_names.h>
+#include <openssl/params.h>
+#include "internal/cryptlib.h"
+#include "internal/evp_int.h"
+#include "kdf_local.h"
+
+struct evp_kdf_impl_st {
+    EVP_MAC *mac;       /* H(x) = HMAC_hash OR H(x) = KMAC */
+    const EVP_MD *md;   /* H(x) = hash OR when H(x) = HMAC_hash */
+    unsigned char *secret;
+    size_t secret_len;
+    unsigned char *info;
+    size_t info_len;
+    unsigned char *salt;
+    size_t salt_len;
+    size_t out_len; /* optional KMAC parameter */
+};
+
+#define SSKDF_MAX_INLEN (1<<30)
+#define SSKDF_KMAC128_DEFAULT_SALT_SIZE (168 - 4)
+#define SSKDF_KMAC256_DEFAULT_SALT_SIZE (136 - 4)
+
+/* KMAC uses a Customisation string of 'KDF' */
+static const unsigned char kmac_custom_str[] = { 0x4B, 0x44, 0x46 };
+
+/*
+ * Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
+ * Section 4. One-Step Key Derivation using H(x) = hash(x)
+ * Note: X9.63 also uses this code with the only difference being that the
+ * counter is appended to the secret 'z'.
+ * i.e.
+ *   result[i] = Hash(counter || z || info) for One Step OR
+ *   result[i] = Hash(z || counter || info) for X9.63.
+ */
+static int SSKDF_hash_kdm(const EVP_MD *kdf_md,
+                          const unsigned char *z, size_t z_len,
+                          const unsigned char *info, size_t info_len,
+                          unsigned int append_ctr,
+                          unsigned char *derived_key, size_t derived_key_len)
+{
+    int ret = 0, hlen;
+    size_t counter, out_len, len = derived_key_len;
+    unsigned char c[4];
+    unsigned char mac[EVP_MAX_MD_SIZE];
+    unsigned char *out = derived_key;
+    EVP_MD_CTX *ctx = NULL, *ctx_init = NULL;
+
+    if (z_len > SSKDF_MAX_INLEN || info_len > SSKDF_MAX_INLEN
+            || derived_key_len > SSKDF_MAX_INLEN
+            || derived_key_len == 0)
+        return 0;
+
+    hlen = EVP_MD_size(kdf_md);
+    if (hlen <= 0)
+        return 0;
+    out_len = (size_t)hlen;
+
+    ctx = EVP_MD_CTX_create();
+    ctx_init = EVP_MD_CTX_create();
+    if (ctx == NULL || ctx_init == NULL)
+        goto end;
+
+    if (!EVP_DigestInit(ctx_init, kdf_md))
+        goto end;
+
+    for (counter = 1;; counter++) {
+        c[0] = (unsigned char)((counter >> 24) & 0xff);
+        c[1] = (unsigned char)((counter >> 16) & 0xff);
+        c[2] = (unsigned char)((counter >> 8) & 0xff);
+        c[3] = (unsigned char)(counter & 0xff);
+
+        if (!(EVP_MD_CTX_copy_ex(ctx, ctx_init)
+                && (append_ctr || EVP_DigestUpdate(ctx, c, sizeof(c)))
+                && EVP_DigestUpdate(ctx, z, z_len)
+                && (!append_ctr || EVP_DigestUpdate(ctx, c, sizeof(c)))
+                && EVP_DigestUpdate(ctx, info, info_len)))
+            goto end;
+        if (len >= out_len) {
+            if (!EVP_DigestFinal_ex(ctx, out, NULL))
+                goto end;
+            out += out_len;
+            len -= out_len;
+            if (len == 0)
+                break;
+        } else {
+            if (!EVP_DigestFinal_ex(ctx, mac, NULL))
+                goto end;
+            memcpy(out, mac, len);
+            break;
+        }
+    }
+    ret = 1;
+end:
+    EVP_MD_CTX_destroy(ctx);
+    EVP_MD_CTX_destroy(ctx_init);
+    OPENSSL_cleanse(mac, sizeof(mac));
+    return ret;
+}
+
+static int kmac_init(EVP_MAC_CTX *ctx, const unsigned char *custom,
+                     size_t custom_len, size_t kmac_out_len,
+                     size_t derived_key_len, unsigned char **out)
+{
+    OSSL_PARAM params[2];
+
+    /* Only KMAC has custom data - so return if not KMAC */
+    if (custom == NULL)
+        return 1;
+
+    params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_CUSTOM,
+                                                  (void *)custom, custom_len);
+    params[1] = OSSL_PARAM_construct_end();
+
+    if (!EVP_MAC_CTX_set_params(ctx, params))
+        return 0;
+
+    /* By default only do one iteration if kmac_out_len is not specified */
+    if (kmac_out_len == 0)
+        kmac_out_len = derived_key_len;
+    /* otherwise check the size is valid */
+    else if (!(kmac_out_len == derived_key_len
+            || kmac_out_len == 20
+            || kmac_out_len == 28
+            || kmac_out_len == 32
+            || kmac_out_len == 48
+            || kmac_out_len == 64))
+        return 0;
+
+    params[0] = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_SIZE,
+                                            &kmac_out_len);
+
+    if (EVP_MAC_CTX_set_params(ctx, params) <= 0)
+        return 0;
+
+    /*
+     * For kmac the output buffer can be larger than EVP_MAX_MD_SIZE: so
+     * alloc a buffer for this case.
+     */
+    if (kmac_out_len > EVP_MAX_MD_SIZE) {
+        *out = OPENSSL_zalloc(kmac_out_len);
+        if (*out == NULL)
+            return 0;
+    }
+    return 1;
+}
+
+/*
+ * Refer to https://csrc.nist.gov/publications/detail/sp/800-56c/rev-1/final
+ * Section 4. One-Step Key Derivation using MAC: i.e either
+ *     H(x) = HMAC-hash(salt, x) OR
+ *     H(x) = KMAC#(salt, x, outbits, CustomString='KDF')
+ */
+static int SSKDF_mac_kdm(EVP_MAC *kdf_mac, const EVP_MD *hmac_md,
+                         const unsigned char *kmac_custom,
+                         size_t kmac_custom_len, size_t kmac_out_len,
+                         const unsigned char *salt, size_t salt_len,
+                         const unsigned char *z, size_t z_len,
+                         const unsigned char *info, size_t info_len,
+                         unsigned char *derived_key, size_t derived_key_len)
+{
+    int ret = 0;
+    size_t counter, out_len, len;
+    unsigned char c[4];
+    unsigned char mac_buf[EVP_MAX_MD_SIZE];
+    unsigned char *out = derived_key;
+    EVP_MAC_CTX *ctx = NULL, *ctx_init = NULL;
+    unsigned char *mac = mac_buf, *kmac_buffer = NULL;
+    OSSL_PARAM params[3];
+    size_t params_n = 0;
+
+    if (z_len > SSKDF_MAX_INLEN || info_len > SSKDF_MAX_INLEN
+            || derived_key_len > SSKDF_MAX_INLEN
+            || derived_key_len == 0)
+        return 0;
+
+    ctx_init = EVP_MAC_CTX_new(kdf_mac);
+    if (ctx_init == NULL)
+        goto end;
+
+    if (hmac_md != NULL) {
+        const char *mdname = EVP_MD_name(hmac_md);
+        params[params_n++] =
+            OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
+                                             (char *)mdname, 0);
+    }
+    params[params_n++] =
+        OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (void *)salt,
+                                          salt_len);
+    params[params_n] = OSSL_PARAM_construct_end();
+
+    if (!EVP_MAC_CTX_set_params(ctx_init, params))
+        goto end;
+
+    if (!kmac_init(ctx_init, kmac_custom, kmac_custom_len, kmac_out_len,
+                   derived_key_len, &kmac_buffer))
+        goto end;
+    if (kmac_buffer != NULL)
+        mac = kmac_buffer;
+
+    if (!EVP_MAC_init(ctx_init))
+        goto end;
+
+    out_len = EVP_MAC_size(ctx_init); /* output size */
+    if (out_len <= 0)
+        goto end;
+    len = derived_key_len;
+
+    for (counter = 1;; counter++) {
+        c[0] = (unsigned char)((counter >> 24) & 0xff);
+        c[1] = (unsigned char)((counter >> 16) & 0xff);
+        c[2] = (unsigned char)((counter >> 8) & 0xff);
+        c[3] = (unsigned char)(counter & 0xff);
+
+        ctx = EVP_MAC_CTX_dup(ctx_init);
+        if (!(ctx != NULL
+                && EVP_MAC_update(ctx, c, sizeof(c))
+                && EVP_MAC_update(ctx, z, z_len)
+                && EVP_MAC_update(ctx, info, info_len)))
+            goto end;
+        if (len >= out_len) {
+            if (!EVP_MAC_final(ctx, out, NULL, len))
+                goto end;
+            out += out_len;
+            len -= out_len;
+            if (len == 0)
+                break;
+        } else {
+            if (!EVP_MAC_final(ctx, mac, NULL, len))
+                goto end;
+            memcpy(out, mac, len);
+            break;
+        }
+        EVP_MAC_CTX_free(ctx);
+        ctx = NULL;
+    }
+    ret = 1;
+end:
+    if (kmac_buffer != NULL)
+        OPENSSL_clear_free(kmac_buffer, kmac_out_len);
+    else
+        OPENSSL_cleanse(mac_buf, sizeof(mac_buf));
+
+    EVP_MAC_CTX_free(ctx);
+    EVP_MAC_CTX_free(ctx_init);
+    return ret;
+}
+
+static EVP_KDF_IMPL *sskdf_new(void)
+{
+    EVP_KDF_IMPL *impl;
+
+    if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
+        KDFerr(KDF_F_SSKDF_NEW, ERR_R_MALLOC_FAILURE);
+    return impl;
+}
+
+static void sskdf_reset(EVP_KDF_IMPL *impl)
+{
+    OPENSSL_clear_free(impl->secret, impl->secret_len);
+    OPENSSL_clear_free(impl->info, impl->info_len);
+    OPENSSL_clear_free(impl->salt, impl->salt_len);
+    EVP_MAC_free(impl->mac);
+#if 0                    /* TODO(3.0) When we switch to fetched MDs */
+    EVP_MD_meth_free(impl->md);
+#endif
+    memset(impl, 0, sizeof(*impl));
+}
+
+static void sskdf_free(EVP_KDF_IMPL *impl)
+{
+    sskdf_reset(impl);
+    OPENSSL_free(impl);
+}
+
+static int sskdf_set_buffer(va_list args, unsigned char **out, size_t *out_len)
+{
+    const unsigned char *p;
+    size_t len;
+
+    p = va_arg(args, const unsigned char *);
+    len = va_arg(args, size_t);
+    if (len == 0 || p == NULL)
+        return 1;
+
+    OPENSSL_free(*out);
+    *out = OPENSSL_memdup(p, len);
+    if (*out == NULL)
+        return 0;
+
+    *out_len = len;
+    return 1;
+}
+
+static int sskdf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
+{
+    const EVP_MD *md;
+
+    switch (cmd) {
+    case EVP_KDF_CTRL_SET_KEY:
+        return sskdf_set_buffer(args, &impl->secret, &impl->secret_len);
+
+    case EVP_KDF_CTRL_SET_SSKDF_INFO:
+        return sskdf_set_buffer(args, &impl->info, &impl->info_len);
+
+    case EVP_KDF_CTRL_SET_MD:
+        md = va_arg(args, const EVP_MD *);
+        if (md == NULL)
+            return 0;
+
+#if 0                    /* TODO(3.0) When we switch to fetched MDs */
+        EVP_MD_meth_free(impl->md);
+#endif
+        impl->md = md;
+        return 1;
+
+    case EVP_KDF_CTRL_SET_MAC:
+        {
+            const char *name;
+            EVP_MAC *mac;
+
+            name = va_arg(args, const char *);
+            if (name == NULL)
+                return 0;
+
+            EVP_MAC_free(impl->mac);
+            impl->mac = NULL;
+
+            /*
+             * TODO(3.0) add support for OPENSSL_CTX and properties in KDFs
+             */
+            mac = EVP_MAC_fetch(NULL, name, NULL);
+            if (mac == NULL)
+                return 0;
+
+            impl->mac = mac;
+            return 1;
+        }
+    case EVP_KDF_CTRL_SET_SALT:
+        return sskdf_set_buffer(args, &impl->salt, &impl->salt_len);
+
+    case EVP_KDF_CTRL_SET_MAC_SIZE:
+        impl->out_len = va_arg(args, size_t);
+        return 1;
+
+    default:
+        return -2;
+    }
+}
+
+static int sskdf_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
+                          const char *value)
+{
+    if (strcmp(type, "secret") == 0 || strcmp(type, "key") == 0)
+         return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_KEY,
+                             value);
+
+    if (strcmp(type, "hexsecret") == 0 || strcmp(type, "hexkey") == 0)
+        return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_KEY,
+                            value);
+
+    if (strcmp(type, "info") == 0)
+        return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SSKDF_INFO,
+                            value);
+
+    if (strcmp(type, "hexinfo") == 0)
+        return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SSKDF_INFO,
+                            value);
+
+    if (strcmp(type, "digest") == 0)
+        return kdf_md2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
+
+    if (strcmp(type, "mac") == 0)
+        return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_MAC, value);
+
+    if (strcmp(type, "salt") == 0)
+        return kdf_str2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
+
+    if (strcmp(type, "hexsalt") == 0)
+        return kdf_hex2ctrl(impl, sskdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
+
+
+    if (strcmp(type, "maclen") == 0) {
+        int val = atoi(value);
+        if (val < 0) {
+            KDFerr(KDF_F_SSKDF_CTRL_STR, KDF_R_VALUE_ERROR);
+            return 0;
+        }
+        return call_ctrl(sskdf_ctrl, impl, EVP_KDF_CTRL_SET_MAC_SIZE,
+                         (size_t)val);
+    }
+    return -2;
+}
+
+static size_t sskdf_size(EVP_KDF_IMPL *impl)
+{
+    int len;
+
+    if (impl->md == NULL) {
+        KDFerr(KDF_F_SSKDF_SIZE, KDF_R_MISSING_MESSAGE_DIGEST);
+        return 0;
+    }
+    len = EVP_MD_size(impl->md);
+    return (len <= 0) ? 0 : (size_t)len;
+}
+
+static int sskdf_derive(EVP_KDF_IMPL *impl, unsigned char *key, size_t keylen)
+{
+    if (impl->secret == NULL) {
+        KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_SECRET);
+        return 0;
+    }
+
+    if (impl->mac != NULL) {
+        /* H(x) = KMAC or H(x) = HMAC */
+        int ret;
+        const unsigned char *custom = NULL;
+        size_t custom_len = 0;
+        const char *macname;
+        int default_salt_len;
+
+        /*
+         * TODO(3.0) investigate the necessity to have all these controls.
+         * Why does KMAC require a salt length that's shorter than the MD
+         * block size?
+         */
+        macname = EVP_MAC_name(impl->mac);
+        if (strcmp(macname, OSSL_MAC_NAME_HMAC) == 0) {
+            /* H(x) = HMAC(x, salt, hash) */
+            if (impl->md == NULL) {
+                KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
+                return 0;
+            }
+            default_salt_len = EVP_MD_block_size(impl->md);
+            if (default_salt_len <= 0)
+                return 0;
+        } else if (strcmp(macname, OSSL_MAC_NAME_KMAC128) == 0
+                   || strcmp(macname, OSSL_MAC_NAME_KMAC256) == 0) {
+            /* H(x) = KMACzzz(x, salt, custom) */
+            custom = kmac_custom_str;
+            custom_len = sizeof(kmac_custom_str);
+            if (strcmp(macname, OSSL_MAC_NAME_KMAC128) == 0)
+                default_salt_len = SSKDF_KMAC128_DEFAULT_SALT_SIZE;
+            else
+                default_salt_len = SSKDF_KMAC256_DEFAULT_SALT_SIZE;
+        } else {
+            KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_UNSUPPORTED_MAC_TYPE);
+            return 0;
+        }
+        /* If no salt is set then use a default_salt of zeros */
+        if (impl->salt == NULL || impl->salt_len <= 0) {
+            impl->salt = OPENSSL_zalloc(default_salt_len);
+            if (impl->salt == NULL) {
+                KDFerr(KDF_F_SSKDF_DERIVE, ERR_R_MALLOC_FAILURE);
+                return 0;
+            }
+            impl->salt_len = default_salt_len;
+        }
+        ret = SSKDF_mac_kdm(impl->mac, impl->md,
+                            custom, custom_len, impl->out_len,
+                            impl->salt, impl->salt_len,
+                            impl->secret, impl->secret_len,
+                            impl->info, impl->info_len, key, keylen);
+        return ret;
+    } else {
+        /* H(x) = hash */
+        if (impl->md == NULL) {
+            KDFerr(KDF_F_SSKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
+            return 0;
+        }
+        return SSKDF_hash_kdm(impl->md, impl->secret, impl->secret_len,
+                              impl->info, impl->info_len, 0, key, keylen);
+    }
+}
+
+static int x963kdf_derive(EVP_KDF_IMPL *impl, unsigned char *key, size_t keylen)
+{
+    if (impl->secret == NULL) {
+        KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_MISSING_SECRET);
+        return 0;
+    }
+
+    if (impl->mac != NULL) {
+        KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_NOT_SUPPORTED);
+        return 0;
+    } else {
+        /* H(x) = hash */
+        if (impl->md == NULL) {
+            KDFerr(KDF_F_X963KDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
+            return 0;
+        }
+        return SSKDF_hash_kdm(impl->md, impl->secret, impl->secret_len,
+                              impl->info, impl->info_len, 1, key, keylen);
+    }
+}
+
+const EVP_KDF ss_kdf_meth = {
+    EVP_KDF_SS,
+    sskdf_new,
+    sskdf_free,
+    sskdf_reset,
+    sskdf_ctrl,
+    sskdf_ctrl_str,
+    sskdf_size,
+    sskdf_derive
+};
+
+const EVP_KDF x963_kdf_meth = {
+    EVP_KDF_X963,
+    sskdf_new,
+    sskdf_free,
+    sskdf_reset,
+    sskdf_ctrl,
+    sskdf_ctrl_str,
+    sskdf_size,
+    x963kdf_derive
+};
diff --git a/providers/common/kdfs/tls1_prf.c b/providers/common/kdfs/tls1_prf.c
new file mode 100644 (file)
index 0000000..3c553e8
--- /dev/null
@@ -0,0 +1,377 @@
+/*
+ * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License").  You may not use
+ * this file except in compliance with the License.  You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * Refer to "The TLS Protocol Version 1.0" Section 5
+ * (https://tools.ietf.org/html/rfc2246#section-5) and
+ * "The Transport Layer Security (TLS) Protocol Version 1.2" Section 5
+ * (https://tools.ietf.org/html/rfc5246#section-5).
+ *
+ * For TLS v1.0 and TLS v1.1 the TLS PRF algorithm is given by:
+ *
+ *   PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR
+ *                              P_SHA-1(S2, label + seed)
+ *
+ * where P_MD5 and P_SHA-1 are defined by P_<hash>, below, and S1 and S2 are
+ * two halves of the secret (with the possibility of one shared byte, in the
+ * case where the length of the original secret is odd).  S1 is taken from the
+ * first half of the secret, S2 from the second half.
+ *
+ * For TLS v1.2 the TLS PRF algorithm is given by:
+ *
+ *   PRF(secret, label, seed) = P_<hash>(secret, label + seed)
+ *
+ * where hash is SHA-256 for all cipher suites defined in RFC 5246 as well as
+ * those published prior to TLS v1.2 while the TLS v1.2 protocol is in effect,
+ * unless defined otherwise by the cipher suite.
+ *
+ * P_<hash> is an expansion function that uses a single hash function to expand
+ * a secret and seed into an arbitrary quantity of output:
+ *
+ *   P_<hash>(secret, seed) = HMAC_<hash>(secret, A(1) + seed) +
+ *                            HMAC_<hash>(secret, A(2) + seed) +
+ *                            HMAC_<hash>(secret, A(3) + seed) + ...
+ *
+ * where + indicates concatenation.  P_<hash> can be iterated as many times as
+ * is necessary to produce the required quantity of data.
+ *
+ * A(i) is defined as:
+ *     A(0) = seed
+ *     A(i) = HMAC_<hash>(secret, A(i-1))
+ */
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
+#include "internal/cryptlib.h"
+#include <openssl/evp.h>
+#include <openssl/kdf.h>
+#include <openssl/core_names.h>
+#include <openssl/params.h>
+#include "internal/evp_int.h"
+#include "kdf_local.h"
+
+static void kdf_tls1_prf_reset(EVP_KDF_IMPL *impl);
+static int tls1_prf_alg(const EVP_MD *md,
+                        const unsigned char *sec, size_t slen,
+                        const unsigned char *seed, size_t seed_len,
+                        unsigned char *out, size_t olen);
+
+#define TLS1_PRF_MAXBUF 1024
+
+/* TLS KDF kdf context structure */
+
+struct evp_kdf_impl_st {
+    /* Digest to use for PRF */
+    const EVP_MD *md;
+    /* Secret value to use for PRF */
+    unsigned char *sec;
+    size_t seclen;
+    /* Buffer of concatenated seed data */
+    unsigned char seed[TLS1_PRF_MAXBUF];
+    size_t seedlen;
+};
+
+static EVP_KDF_IMPL *kdf_tls1_prf_new(void)
+{
+    EVP_KDF_IMPL *impl;
+
+    if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
+        KDFerr(KDF_F_KDF_TLS1_PRF_NEW, ERR_R_MALLOC_FAILURE);
+    return impl;
+}
+
+static void kdf_tls1_prf_free(EVP_KDF_IMPL *impl)
+{
+    kdf_tls1_prf_reset(impl);
+    OPENSSL_free(impl);
+}
+
+static void kdf_tls1_prf_reset(EVP_KDF_IMPL *impl)
+{
+    OPENSSL_clear_free(impl->sec, impl->seclen);
+    OPENSSL_cleanse(impl->seed, impl->seedlen);
+    memset(impl, 0, sizeof(*impl));
+}
+
+static int kdf_tls1_prf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
+{
+    const unsigned char *p;
+    size_t len;
+    const EVP_MD *md;
+
+    switch (cmd) {
+    case EVP_KDF_CTRL_SET_MD:
+        md = va_arg(args, const EVP_MD *);
+        if (md == NULL)
+            return 0;
+
+        impl->md = md;
+        return 1;
+
+    case EVP_KDF_CTRL_SET_TLS_SECRET:
+        p = va_arg(args, const unsigned char *);
+        len = va_arg(args, size_t);
+        OPENSSL_clear_free(impl->sec, impl->seclen);
+        impl->sec = OPENSSL_memdup(p, len);
+        if (impl->sec == NULL)
+            return 0;
+
+        impl->seclen = len;
+        return 1;
+
+    /* TODO: This is only ever called from pkey_kdf and only as part of setting the TLS secret
+    consider merging the twe two?? */
+    case EVP_KDF_CTRL_RESET_TLS_SEED:
+        OPENSSL_cleanse(impl->seed, impl->seedlen);
+        impl->seedlen = 0;
+        return 1;
+
+    case EVP_KDF_CTRL_ADD_TLS_SEED:
+        p = va_arg(args, const unsigned char *);
+        len = va_arg(args, size_t);
+        if (len == 0 || p == NULL)
+            return 1;
+
+        if (len > (TLS1_PRF_MAXBUF - impl->seedlen))
+            return 0;
+
+        memcpy(impl->seed + impl->seedlen, p, len);
+        impl->seedlen += len;
+        return 1;
+
+    default:
+        return -2;
+    }
+}
+
+static int kdf_tls1_prf_ctrl_str(EVP_KDF_IMPL *impl,
+                                 const char *type, const char *value)
+{
+    if (value == NULL) {
+        KDFerr(KDF_F_KDF_TLS1_PRF_CTRL_STR, KDF_R_VALUE_MISSING);
+        return 0;
+    }
+    if (strcmp(type, "digest") == 0)
+        return kdf_md2ctrl(impl, kdf_tls1_prf_ctrl, EVP_KDF_CTRL_SET_MD, value);
+
+    if (strcmp(type, "secret") == 0)
+        return kdf_str2ctrl(impl, kdf_tls1_prf_ctrl,
+                            EVP_KDF_CTRL_SET_TLS_SECRET, value);
+
+    if (strcmp(type, "hexsecret") == 0)
+        return kdf_hex2ctrl(impl, kdf_tls1_prf_ctrl,
+                            EVP_KDF_CTRL_SET_TLS_SECRET, value);
+
+    if (strcmp(type, "seed") == 0)
+        return kdf_str2ctrl(impl, kdf_tls1_prf_ctrl, EVP_KDF_CTRL_ADD_TLS_SEED,
+                            value);
+
+    if (strcmp(type, "hexseed") == 0)
+        return kdf_hex2ctrl(impl, kdf_tls1_prf_ctrl, EVP_KDF_CTRL_ADD_TLS_SEED,
+                            value);
+
+    return -2;
+}
+
+static int kdf_tls1_prf_derive(EVP_KDF_IMPL *impl, unsigned char *key,
+                               size_t keylen)
+{
+    if (impl->md == NULL) {
+        KDFerr(KDF_F_KDF_TLS1_PRF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
+        return 0;
+    }
+    if (impl->sec == NULL) {
+        KDFerr(KDF_F_KDF_TLS1_PRF_DERIVE, KDF_R_MISSING_SECRET);
+        return 0;
+    }
+    if (impl->seedlen == 0) {
+        KDFerr(KDF_F_KDF_TLS1_PRF_DERIVE, KDF_R_MISSING_SEED);
+        return 0;
+    }
+    return tls1_prf_alg(impl->md, impl->sec, impl->seclen,
+                        impl->seed, impl->seedlen,
+                        key, keylen);
+}
+
+const EVP_KDF tls1_prf_kdf_meth = {
+    EVP_KDF_TLS1_PRF,
+    kdf_tls1_prf_new,
+    kdf_tls1_prf_free,
+    kdf_tls1_prf_reset,
+    kdf_tls1_prf_ctrl,
+    kdf_tls1_prf_ctrl_str,
+    NULL,
+    kdf_tls1_prf_derive
+};
+
+/*
+ * Refer to "The TLS Protocol Version 1.0" Section 5
+ * (https://tools.ietf.org/html/rfc2246#section-5) and
+ * "The Transport Layer Security (TLS) Protocol Version 1.2" Section 5
+ * (https://tools.ietf.org/html/rfc5246#section-5).
+ *
+ * P_<hash> is an expansion function that uses a single hash function to expand
+ * a secret and seed into an arbitrary quantity of output:
+ *
+ *   P_<hash>(secret, seed) = HMAC_<hash>(secret, A(1) + seed) +
+ *                            HMAC_<hash>(secret, A(2) + seed) +
+ *                            HMAC_<hash>(secret, A(3) + seed) + ...
+ *
+ * where + indicates concatenation.  P_<hash> can be iterated as many times as
+ * is necessary to produce the required quantity of data.
+ *
+ * A(i) is defined as:
+ *     A(0) = seed
+ *     A(i) = HMAC_<hash>(secret, A(i-1))
+ */
+static int tls1_prf_P_hash(const EVP_MD *md,
+                           const unsigned char *sec, size_t sec_len,
+                           const unsigned char *seed, size_t seed_len,
+                           unsigned char *out, size_t olen)
+{
+    size_t chunk;
+    EVP_MAC *mac = NULL;
+    EVP_MAC_CTX *ctx = NULL, *ctx_Ai = NULL, *ctx_init = NULL;
+    unsigned char Ai[EVP_MAX_MD_SIZE];
+    size_t Ai_len;
+    int ret = 0;
+    OSSL_PARAM params[4];
+    int mac_flags;
+    const char *mdname = EVP_MD_name(md);
+
+    mac = EVP_MAC_fetch(NULL, OSSL_MAC_NAME_HMAC, NULL); /* Implicit fetch */
+    ctx_init = EVP_MAC_CTX_new(mac);
+    if (ctx_init == NULL)
+        goto err;
+
+    /* TODO(3.0) rethink "flags", also see hmac.c in providers */
+    mac_flags = EVP_MD_CTX_FLAG_NON_FIPS_ALLOW;
+    params[0] = OSSL_PARAM_construct_int(OSSL_MAC_PARAM_FLAGS, &mac_flags);
+    params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
+                                                 (char *)mdname, 0);
+    params[2] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
+                                                  (void *)sec, sec_len);
+    params[3] = OSSL_PARAM_construct_end();
+    if (!EVP_MAC_CTX_set_params(ctx_init, params))
+        goto err;
+    if (!EVP_MAC_init(ctx_init))
+        goto err;
+    chunk = EVP_MAC_size(ctx_init);
+    if (chunk == 0)
+        goto err;
+    /* A(0) = seed */
+    ctx_Ai = EVP_MAC_CTX_dup(ctx_init);
+    if (ctx_Ai == NULL)
+        goto err;
+    if (seed != NULL && !EVP_MAC_update(ctx_Ai, seed, seed_len))
+        goto err;
+
+    for (;;) {
+        /* calc: A(i) = HMAC_<hash>(secret, A(i-1)) */
+        if (!EVP_MAC_final(ctx_Ai, Ai, &Ai_len, sizeof(Ai)))
+            goto err;
+        EVP_MAC_CTX_free(ctx_Ai);
+        ctx_Ai = NULL;
+
+        /* calc next chunk: HMAC_<hash>(secret, A(i) + seed) */
+        ctx = EVP_MAC_CTX_dup(ctx_init);
+        if (ctx == NULL)
+            goto err;
+        if (!EVP_MAC_update(ctx, Ai, Ai_len))
+            goto err;
+        /* save state for calculating next A(i) value */
+        if (olen > chunk) {
+            ctx_Ai = EVP_MAC_CTX_dup(ctx);
+            if (ctx_Ai == NULL)
+                goto err;
+        }
+        if (seed != NULL && !EVP_MAC_update(ctx, seed, seed_len))
+            goto err;
+        if (olen <= chunk) {
+            /* last chunk - use Ai as temp bounce buffer */
+            if (!EVP_MAC_final(ctx, Ai, &Ai_len, sizeof(Ai)))
+                goto err;
+            memcpy(out, Ai, olen);
+            break;
+        }
+        if (!EVP_MAC_final(ctx, out, NULL, olen))
+            goto err;
+        EVP_MAC_CTX_free(ctx);
+        ctx = NULL;
+        out += chunk;
+        olen -= chunk;
+    }
+    ret = 1;
+ err:
+    EVP_MAC_CTX_free(ctx);
+    EVP_MAC_CTX_free(ctx_Ai);
+    EVP_MAC_CTX_free(ctx_init);
+    EVP_MAC_free(mac);
+    OPENSSL_cleanse(Ai, sizeof(Ai));
+    return ret;
+}
+
+/*
+ * Refer to "The TLS Protocol Version 1.0" Section 5
+ * (https://tools.ietf.org/html/rfc2246#section-5) and
+ * "The Transport Layer Security (TLS) Protocol Version 1.2" Section 5
+ * (https://tools.ietf.org/html/rfc5246#section-5).
+ *
+ * For TLS v1.0 and TLS v1.1:
+ *
+ *   PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR
+ *                              P_SHA-1(S2, label + seed)
+ *
+ * S1 is taken from the first half of the secret, S2 from the second half.
+ *
+ *   L_S = length in bytes of secret;
+ *   L_S1 = L_S2 = ceil(L_S / 2);
+ *
+ * For TLS v1.2:
+ *
+ *   PRF(secret, label, seed) = P_<hash>(secret, label + seed)
+ */
+static int tls1_prf_alg(const EVP_MD *md,
+                        const unsigned char *sec, size_t slen,
+                        const unsigned char *seed, size_t seed_len,
+                        unsigned char *out, size_t olen)
+{
+    if (EVP_MD_type(md) == NID_md5_sha1) {
+        /* TLS v1.0 and TLS v1.1 */
+        size_t i;
+        unsigned char *tmp;
+        /* calc: L_S1 = L_S2 = ceil(L_S / 2) */
+        size_t L_S1 = (slen + 1) / 2;
+        size_t L_S2 = L_S1;
+
+        if (!tls1_prf_P_hash(EVP_md5(), sec, L_S1,
+                             seed, seed_len, out, olen))
+            return 0;
+
+        if ((tmp = OPENSSL_malloc(olen)) == NULL) {
+            KDFerr(KDF_F_TLS1_PRF_ALG, ERR_R_MALLOC_FAILURE);
+            return 0;
+        }
+        if (!tls1_prf_P_hash(EVP_sha1(), sec + slen - L_S2, L_S2,
+                             seed, seed_len, tmp, olen)) {
+            OPENSSL_clear_free(tmp, olen);
+            return 0;
+        }
+        for (i = 0; i < olen; i++)
+            out[i] ^= tmp[i];
+        OPENSSL_clear_free(tmp, olen);
+        return 1;
+    }
+
+    /* TLS v1.2 */
+    if (!tls1_prf_P_hash(md, sec, slen, seed, seed_len, out, olen))
+        return 0;
+
+    return 1;
+}
diff --git a/providers/common/kdfs/x942kdf.c b/providers/common/kdfs/x942kdf.c
new file mode 100644 (file)
index 0000000..ce9ad61
--- /dev/null
@@ -0,0 +1,407 @@
+/*
+ * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2019, Oracle and/or its affiliates.  All rights reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License").  You may not use
+ * this file except in compliance with the License.  You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include "e_os.h"
+
+#ifndef OPENSSL_NO_CMS
+
+# include <stdlib.h>
+# include <stdarg.h>
+# include <string.h>
+# include <openssl/hmac.h>
+# include <openssl/cms.h>
+# include <openssl/evp.h>
+# include <openssl/kdf.h>
+# include <openssl/x509.h>
+# include <openssl/obj_mac.h>
+# include "internal/cryptlib.h"
+# include "internal/evp_int.h"
+# include "kdf_local.h"
+
+# define X942KDF_MAX_INLEN (1 << 30)
+
+struct evp_kdf_impl_st {
+    const EVP_MD *md;
+    unsigned char *secret;
+    size_t secret_len;
+    int cek_nid;
+    unsigned char *ukm;
+    size_t ukm_len;
+    size_t dkm_len;
+};
+
+/* A table of allowed wrapping algorithms and the associated output lengths */
+static const struct {
+    int nid;
+    size_t keklen; /* size in bytes */
+} kek_algs[] = {
+    { NID_id_smime_alg_CMS3DESwrap, 24 },
+    { NID_id_smime_alg_CMSRC2wrap, 16 },
+    { NID_id_aes128_wrap, 16 },
+    { NID_id_aes192_wrap, 24 },
+    { NID_id_aes256_wrap, 32 },
+    { NID_id_camellia128_wrap, 16 },
+    { NID_id_camellia192_wrap, 24 },
+    { NID_id_camellia256_wrap, 32 }
+};
+
+/* Skip past an ASN1 structure: for OBJECT skip content octets too */
+static int skip_asn1(unsigned char **pp, long *plen, int exptag)
+{
+    int i, tag, xclass;
+    long tmplen;
+    const unsigned char *q = *pp;
+
+    i = ASN1_get_object(&q, &tmplen, &tag, &xclass, *plen);
+    if ((i & 0x80) != 0 || tag != exptag || xclass != V_ASN1_UNIVERSAL)
+        return 0;
+    if (tag == V_ASN1_OBJECT)
+        q += tmplen;
+    *pp = (unsigned char *)q;
+    *plen -= q - *pp;
+    return 1;
+}
+
+/*
+ * Encode the other info structure.
+ *
+ *  RFC2631 Section 2.1.2 Contains the following definition for otherinfo
+ *
+ *  OtherInfo ::= SEQUENCE {
+ *      keyInfo KeySpecificInfo,
+ *      partyAInfo [0] OCTET STRING OPTIONAL,
+ *      suppPubInfo [2] OCTET STRING
+ *  }
+ *
+ *  KeySpecificInfo ::= SEQUENCE {
+ *      algorithm OBJECT IDENTIFIER,
+ *      counter OCTET STRING SIZE (4..4)
+ *  }
+ *
+ * |nid| is the algorithm object identifier.
+ * |keylen| is the length (in bytes) of the generated KEK. It is stored into
+ * suppPubInfo (in bits).
+ * |ukm| is the optional user keying material that is stored into partyAInfo. It
+ * can be NULL.
+ * |ukmlen| is the user keying material length (in bytes).
+ * |der| is the returned encoded data. It must be freed by the caller.
+ * |der_len| is the returned size of the encoded data.
+ * |out_ctr| returns a pointer to the counter data which is embedded inside the
+ * encoded data. This allows the counter bytes to be updated without re-encoding.
+ *
+ * Returns: 1 if successfully encoded, or 0 otherwise.
+ * Assumptions: |der|, |der_len| & |out_ctr| are not NULL.
+ */
+static int x942_encode_otherinfo(int nid, size_t keylen,
+                                 const unsigned char *ukm, size_t ukmlen,
+                                 unsigned char **der, size_t *der_len,
+                                 unsigned char **out_ctr)
+{
+    unsigned char *p, *encoded = NULL;
+    int ret = 0, encoded_len;
+    long tlen;
+    /* "magic" value to check offset is sane */
+    static unsigned char ctr[4] = { 0x00, 0x00, 0x00, 0x01 };
+    X509_ALGOR *ksi = NULL;
+    ASN1_OBJECT *alg_oid = NULL;
+    ASN1_OCTET_STRING *ctr_oct = NULL, *ukm_oct = NULL;
+
+    /* set the KeySpecificInfo - which contains an algorithm oid and counter */
+    ksi = X509_ALGOR_new();
+    alg_oid = OBJ_dup(OBJ_nid2obj(nid));
+    ctr_oct = ASN1_OCTET_STRING_new();
+    if (ksi == NULL
+        || alg_oid == NULL
+        || ctr_oct == NULL
+        || !ASN1_OCTET_STRING_set(ctr_oct, ctr, sizeof(ctr))
+        || !X509_ALGOR_set0(ksi, alg_oid, V_ASN1_OCTET_STRING, ctr_oct))
+        goto err;
+    /* NULL these as they now belong to ksi */
+    alg_oid = NULL;
+    ctr_oct = NULL;
+
+    /* Set the optional partyAInfo */
+    if (ukm != NULL) {
+        ukm_oct = ASN1_OCTET_STRING_new();
+        if (ukm_oct == NULL)
+            goto err;
+        ASN1_OCTET_STRING_set(ukm_oct, (unsigned char *)ukm, ukmlen);
+    }
+    /* Generate the OtherInfo DER data */
+    encoded_len = CMS_SharedInfo_encode(&encoded, ksi, ukm_oct, keylen);
+    if (encoded_len <= 0)
+        goto err;
+
+    /* Parse the encoded data to find the offset of the counter data */
+    p = encoded;
+    tlen = (long)encoded_len;
+    if (skip_asn1(&p, &tlen, V_ASN1_SEQUENCE)
+        && skip_asn1(&p, &tlen, V_ASN1_SEQUENCE)
+        && skip_asn1(&p, &tlen, V_ASN1_OBJECT)
+        && skip_asn1(&p, &tlen, V_ASN1_OCTET_STRING)
+        && CRYPTO_memcmp(p, ctr, 4) == 0) {
+        *out_ctr = p;
+        *der = encoded;
+        *der_len = (size_t)encoded_len;
+        ret = 1;
+    }
+err:
+    if (ret != 1)
+        OPENSSL_free(encoded);
+    ASN1_OCTET_STRING_free(ctr_oct);
+    ASN1_OCTET_STRING_free(ukm_oct);
+    ASN1_OBJECT_free(alg_oid);
+    X509_ALGOR_free(ksi);
+    return ret;
+}
+
+static int x942kdf_hash_kdm(const EVP_MD *kdf_md,
+                            const unsigned char *z, size_t z_len,
+                            const unsigned char *other, size_t other_len,
+                            unsigned char *ctr,
+                            unsigned char *derived_key, size_t derived_key_len)
+{
+    int ret = 0, hlen;
+    size_t counter, out_len, len = derived_key_len;
+    unsigned char mac[EVP_MAX_MD_SIZE];
+    unsigned char *out = derived_key;
+    EVP_MD_CTX *ctx = NULL, *ctx_init = NULL;
+
+    if (z_len > X942KDF_MAX_INLEN || other_len > X942KDF_MAX_INLEN
+            || derived_key_len > X942KDF_MAX_INLEN
+            || derived_key_len == 0) {
+        KDFerr(KDF_F_X942KDF_HASH_KDM, KDF_R_BAD_LENGTH);
+        return 0;
+    }
+
+    hlen = EVP_MD_size(kdf_md);
+    if (hlen <= 0)
+        return 0;
+    out_len = (size_t)hlen;
+
+    ctx = EVP_MD_CTX_create();
+    ctx_init = EVP_MD_CTX_create();
+    if (ctx == NULL || ctx_init == NULL)
+        goto end;
+
+    if (!EVP_DigestInit(ctx_init, kdf_md))
+        goto end;
+
+    for (counter = 1;; counter++) {
+        /* updating the ctr modifies 4 bytes in the 'other' buffer */
+        ctr[0] = (unsigned char)((counter >> 24) & 0xff);
+        ctr[1] = (unsigned char)((counter >> 16) & 0xff);
+        ctr[2] = (unsigned char)((counter >> 8) & 0xff);
+        ctr[3] = (unsigned char)(counter & 0xff);
+
+        if (!EVP_MD_CTX_copy_ex(ctx, ctx_init)
+            || !EVP_DigestUpdate(ctx, z, z_len)
+            || !EVP_DigestUpdate(ctx, other, other_len))
+            goto end;
+        if (len >= out_len) {
+            if (!EVP_DigestFinal_ex(ctx, out, NULL))
+                goto end;
+            out += out_len;
+            len -= out_len;
+            if (len == 0)
+                break;
+        } else {
+            if (!EVP_DigestFinal_ex(ctx, mac, NULL))
+                goto end;
+            memcpy(out, mac, len);
+            break;
+        }
+    }
+    ret = 1;
+end:
+    EVP_MD_CTX_free(ctx);
+    EVP_MD_CTX_free(ctx_init);
+    OPENSSL_cleanse(mac, sizeof(mac));
+    return ret;
+}
+
+static EVP_KDF_IMPL *x942kdf_new(void)
+{
+    EVP_KDF_IMPL *impl;
+
+    if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
+        KDFerr(KDF_F_X942KDF_NEW, ERR_R_MALLOC_FAILURE);
+    return impl;
+}
+
+static void x942kdf_reset(EVP_KDF_IMPL *impl)
+{
+    OPENSSL_clear_free(impl->secret, impl->secret_len);
+    OPENSSL_clear_free(impl->ukm, impl->ukm_len);
+    memset(impl, 0, sizeof(*impl));
+}
+
+static void x942kdf_free(EVP_KDF_IMPL *impl)
+{
+    x942kdf_reset(impl);
+    OPENSSL_free(impl);
+}
+
+static int x942kdf_set_buffer(va_list args, unsigned char **out, size_t *out_len)
+{
+    const unsigned char *p;
+    size_t len;
+
+    p = va_arg(args, const unsigned char *);
+    len = va_arg(args, size_t);
+    if (len == 0 || p == NULL)
+        return 1;
+
+    OPENSSL_free(*out);
+    *out = OPENSSL_memdup(p, len);
+    if (*out == NULL)
+        return 0;
+
+    *out_len = len;
+    return 1;
+}
+
+static int x942kdf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
+{
+    const EVP_MD *md;
+    char *alg_str = NULL;
+    size_t i;
+
+    switch (cmd) {
+    case EVP_KDF_CTRL_SET_MD:
+        md = va_arg(args, const EVP_MD *);
+        if (md == NULL)
+            return 0;
+
+        impl->md = md;
+        return 1;
+
+    case EVP_KDF_CTRL_SET_KEY:
+        return x942kdf_set_buffer(args, &impl->secret, &impl->secret_len);
+
+    case EVP_KDF_CTRL_SET_UKM:
+        return x942kdf_set_buffer(args, &impl->ukm, &impl->ukm_len);
+
+    case EVP_KDF_CTRL_SET_CEK_ALG:
+        alg_str = va_arg(args, char *);
+        if (alg_str == NULL)
+            return 0;
+        impl->cek_nid = OBJ_sn2nid(alg_str);
+        for (i = 0; i < (size_t)OSSL_NELEM(kek_algs); ++i) {
+            if (kek_algs[i].nid == impl->cek_nid) {
+                impl->dkm_len = kek_algs[i].keklen;
+                return 1;
+            }
+        }
+        KDFerr(KDF_F_X942KDF_CTRL, KDF_R_UNSUPPORTED_CEK_ALG);
+        return 0;
+
+    default:
+        return -2;
+    }
+}
+
+static int x942kdf_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
+                            const char *value)
+{
+    if (strcmp(type, "digest") == 0)
+        return kdf_md2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
+
+    if (strcmp(type, "secret") == 0 || strcmp(type, "key") == 0)
+         return kdf_str2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_KEY,
+                             value);
+
+    if (strcmp(type, "hexsecret") == 0 || strcmp(type, "hexkey") == 0)
+        return kdf_hex2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_KEY,
+                            value);
+
+    if (strcmp(type, "ukm") == 0)
+        return kdf_str2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_UKM,
+                            value);
+
+    if (strcmp(type, "hexukm") == 0)
+        return kdf_hex2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_UKM,
+                            value);
+
+    if (strcmp(type, "cekalg") == 0)
+        return kdf_str2ctrl(impl, x942kdf_ctrl, EVP_KDF_CTRL_SET_CEK_ALG,
+                            value);
+
+    return -2;
+}
+
+static size_t x942kdf_size(EVP_KDF_IMPL *impl)
+{
+    int len;
+
+    if (impl->md == NULL) {
+        KDFerr(KDF_F_X942KDF_SIZE, KDF_R_MISSING_MESSAGE_DIGEST);
+        return 0;
+    }
+    len = EVP_MD_size(impl->md);
+    return (len <= 0) ? 0 : (size_t)len;
+}
+
+static int x942kdf_derive(EVP_KDF_IMPL *impl, unsigned char *key, size_t keylen)
+{
+    int ret = 0;
+    unsigned char *ctr;
+    unsigned char *der = NULL;
+    size_t der_len = 0;
+
+    if (impl->secret == NULL) {
+        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_MISSING_SECRET);
+        return 0;
+    }
+    if (impl->md == NULL) {
+        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
+        return 0;
+    }
+    if (impl->cek_nid == NID_undef) {
+        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_MISSING_CEK_ALG);
+        return 0;
+    }
+    if (impl->ukm != NULL && impl->ukm_len >= X942KDF_MAX_INLEN) {
+        /*
+         * Note the ukm length MUST be 512 bits.
+         * For backwards compatibility the old check is being done.
+         */
+        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_INAVLID_UKM_LEN);
+        return 0;
+    }
+    if (keylen != impl->dkm_len) {
+        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_MISSING_CEK_ALG);
+        return 0;
+    }
+    /* generate the otherinfo der */
+    if (!x942_encode_otherinfo(impl->cek_nid, impl->dkm_len,
+                               impl->ukm, impl->ukm_len,
+                               &der, &der_len, &ctr)) {
+        KDFerr(KDF_F_X942KDF_DERIVE, KDF_R_BAD_ENCODING);
+        return 0;
+    }
+    ret = x942kdf_hash_kdm(impl->md, impl->secret, impl->secret_len,
+                           der, der_len, ctr, key, keylen);
+    OPENSSL_free(der);
+    return ret;
+}
+
+const EVP_KDF x942_kdf_meth = {
+    EVP_KDF_X942,
+    x942kdf_new,
+    x942kdf_free,
+    x942kdf_reset,
+    x942kdf_ctrl,
+    x942kdf_ctrl_str,
+    x942kdf_size,
+    x942kdf_derive
+};
+
+#endif /* OPENSSL_NO_CMS */