file_path
stringlengths
19
75
code
stringlengths
279
1.37M
./openssl/crypto/ec/curve448/arch_32/arch_intrinsics.h
/* * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2016 Cryptography Research, Inc. * * 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 * * Originally written by Mike Hamburg */ #ifndef OSSL_CRYPTO_EC_CURVE448_ARCH_32_INTRINSICS_H # define OSSL_CRYPTO_EC_CURVE448_ARCH_32_INTRINSICS_H #include "internal/constant_time.h" # define ARCH_WORD_BITS 32 #define word_is_zero(a) constant_time_is_zero_32(a) static ossl_inline uint64_t widemul(uint32_t a, uint32_t b) { return ((uint64_t)a) * b; } #endif /* OSSL_CRYPTO_EC_CURVE448_ARCH_32_INTRINSICS_H */
./openssl/crypto/ec/curve448/arch_32/f_impl.h
/* * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2014-2016 Cryptography Research, Inc. * * 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 * * Originally written by Mike Hamburg */ #ifndef OSSL_CRYPTO_EC_CURVE448_ARCH_32_F_IMPL_H # define OSSL_CRYPTO_EC_CURVE448_ARCH_32_F_IMPL_H # define GF_HEADROOM 2 # define LIMB(x) ((x) & ((1 << 28) - 1)), ((x) >> 28) # define FIELD_LITERAL(a, b, c, d, e, f, g, h) \ {{LIMB(a), LIMB(b), LIMB(c), LIMB(d), LIMB(e), LIMB(f), LIMB(g), LIMB(h)}} # define LIMB_PLACE_VALUE(i) 28 void gf_add_RAW(gf out, const gf a, const gf b) { unsigned int i; for (i = 0; i < NLIMBS; i++) out->limb[i] = a->limb[i] + b->limb[i]; } void gf_sub_RAW(gf out, const gf a, const gf b) { unsigned int i; for (i = 0; i < NLIMBS; i++) out->limb[i] = a->limb[i] - b->limb[i]; } void gf_bias(gf a, int amt) { unsigned int i; uint32_t co1 = ((1 << 28) - 1) * amt, co2 = co1 - amt; for (i = 0; i < NLIMBS; i++) a->limb[i] += (i == NLIMBS / 2) ? co2 : co1; } void gf_weak_reduce(gf a) { uint32_t mask = (1 << 28) - 1; uint32_t tmp = a->limb[NLIMBS - 1] >> 28; unsigned int i; a->limb[NLIMBS / 2] += tmp; for (i = NLIMBS - 1; i > 0; i--) a->limb[i] = (a->limb[i] & mask) + (a->limb[i - 1] >> 28); a->limb[0] = (a->limb[0] & mask) + tmp; } #endif /* OSSL_CRYPTO_EC_CURVE448_ARCH_32_F_IMPL_H */
./openssl/crypto/dh/dh_lib.c
/* * Copyright 1995-2023 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 */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <openssl/bn.h> #ifndef FIPS_MODULE # include <openssl/engine.h> #endif #include <openssl/obj_mac.h> #include <openssl/core_names.h> #include "internal/cryptlib.h" #include "internal/refcount.h" #include "crypto/evp.h" #include "crypto/dh.h" #include "dh_local.h" static DH *dh_new_intern(ENGINE *engine, OSSL_LIB_CTX *libctx); #ifndef FIPS_MODULE int DH_set_method(DH *dh, const DH_METHOD *meth) { /* * NB: The caller is specifically setting a method, so it's not up to us * to deal with which ENGINE it comes from. */ const DH_METHOD *mtmp; mtmp = dh->meth; if (mtmp->finish) mtmp->finish(dh); #ifndef OPENSSL_NO_ENGINE ENGINE_finish(dh->engine); dh->engine = NULL; #endif dh->meth = meth; if (meth->init) meth->init(dh); return 1; } const DH_METHOD *ossl_dh_get_method(const DH *dh) { return dh->meth; } # ifndef OPENSSL_NO_DEPRECATED_3_0 DH *DH_new(void) { return dh_new_intern(NULL, NULL); } # endif DH *DH_new_method(ENGINE *engine) { return dh_new_intern(engine, NULL); } #endif /* !FIPS_MODULE */ DH *ossl_dh_new_ex(OSSL_LIB_CTX *libctx) { return dh_new_intern(NULL, libctx); } static DH *dh_new_intern(ENGINE *engine, OSSL_LIB_CTX *libctx) { DH *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { ERR_raise(ERR_LIB_DH, ERR_R_CRYPTO_LIB); OPENSSL_free(ret); return NULL; } if (!CRYPTO_NEW_REF(&ret->references, 1)) { CRYPTO_THREAD_lock_free(ret->lock); OPENSSL_free(ret); return NULL; } ret->libctx = libctx; ret->meth = DH_get_default_method(); #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_ENGINE) ret->flags = ret->meth->flags; /* early default init */ if (engine) { if (!ENGINE_init(engine)) { ERR_raise(ERR_LIB_DH, ERR_R_ENGINE_LIB); goto err; } ret->engine = engine; } else ret->engine = ENGINE_get_default_DH(); if (ret->engine) { ret->meth = ENGINE_get_DH(ret->engine); if (ret->meth == NULL) { ERR_raise(ERR_LIB_DH, ERR_R_ENGINE_LIB); goto err; } } #endif ret->flags = ret->meth->flags; #ifndef FIPS_MODULE if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_DH, ret, &ret->ex_data)) goto err; #endif /* FIPS_MODULE */ ossl_ffc_params_init(&ret->params); if ((ret->meth->init != NULL) && !ret->meth->init(ret)) { ERR_raise(ERR_LIB_DH, ERR_R_INIT_FAIL); goto err; } return ret; err: DH_free(ret); return NULL; } void DH_free(DH *r) { int i; if (r == NULL) return; CRYPTO_DOWN_REF(&r->references, &i); REF_PRINT_COUNT("DH", r); if (i > 0) return; REF_ASSERT_ISNT(i < 0); if (r->meth != NULL && r->meth->finish != NULL) r->meth->finish(r); #if !defined(FIPS_MODULE) # if !defined(OPENSSL_NO_ENGINE) ENGINE_finish(r->engine); # endif CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DH, r, &r->ex_data); #endif CRYPTO_THREAD_lock_free(r->lock); CRYPTO_FREE_REF(&r->references); ossl_ffc_params_cleanup(&r->params); BN_clear_free(r->pub_key); BN_clear_free(r->priv_key); OPENSSL_free(r); } int DH_up_ref(DH *r) { int i; if (CRYPTO_UP_REF(&r->references, &i) <= 0) return 0; REF_PRINT_COUNT("DH", r); REF_ASSERT_ISNT(i < 2); return ((i > 1) ? 1 : 0); } void ossl_dh_set0_libctx(DH *d, OSSL_LIB_CTX *libctx) { d->libctx = libctx; } #ifndef FIPS_MODULE int DH_set_ex_data(DH *d, int idx, void *arg) { return CRYPTO_set_ex_data(&d->ex_data, idx, arg); } void *DH_get_ex_data(const DH *d, int idx) { return CRYPTO_get_ex_data(&d->ex_data, idx); } #endif int DH_bits(const DH *dh) { if (dh->params.p != NULL) return BN_num_bits(dh->params.p); return -1; } int DH_size(const DH *dh) { if (dh->params.p != NULL) return BN_num_bytes(dh->params.p); return -1; } int DH_security_bits(const DH *dh) { int N; if (dh->params.q != NULL) N = BN_num_bits(dh->params.q); else if (dh->length) N = dh->length; else N = -1; if (dh->params.p != NULL) return BN_security_bits(BN_num_bits(dh->params.p), N); return -1; } void DH_get0_pqg(const DH *dh, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g) { ossl_ffc_params_get0_pqg(&dh->params, p, q, g); } int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g) { /* * If the fields p and g in dh are NULL, the corresponding input * parameters MUST be non-NULL. q may remain NULL. */ if ((dh->params.p == NULL && p == NULL) || (dh->params.g == NULL && g == NULL)) return 0; ossl_ffc_params_set0_pqg(&dh->params, p, q, g); ossl_dh_cache_named_group(dh); dh->dirty_cnt++; return 1; } long DH_get_length(const DH *dh) { return dh->length; } int DH_set_length(DH *dh, long length) { dh->length = length; dh->dirty_cnt++; return 1; } void DH_get0_key(const DH *dh, const BIGNUM **pub_key, const BIGNUM **priv_key) { if (pub_key != NULL) *pub_key = dh->pub_key; if (priv_key != NULL) *priv_key = dh->priv_key; } int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key) { if (pub_key != NULL) { BN_clear_free(dh->pub_key); dh->pub_key = pub_key; } if (priv_key != NULL) { BN_clear_free(dh->priv_key); dh->priv_key = priv_key; } dh->dirty_cnt++; return 1; } const BIGNUM *DH_get0_p(const DH *dh) { return dh->params.p; } const BIGNUM *DH_get0_q(const DH *dh) { return dh->params.q; } const BIGNUM *DH_get0_g(const DH *dh) { return dh->params.g; } const BIGNUM *DH_get0_priv_key(const DH *dh) { return dh->priv_key; } const BIGNUM *DH_get0_pub_key(const DH *dh) { return dh->pub_key; } void DH_clear_flags(DH *dh, int flags) { dh->flags &= ~flags; } int DH_test_flags(const DH *dh, int flags) { return dh->flags & flags; } void DH_set_flags(DH *dh, int flags) { dh->flags |= flags; } #ifndef FIPS_MODULE ENGINE *DH_get0_engine(DH *dh) { return dh->engine; } #endif /*FIPS_MODULE */ FFC_PARAMS *ossl_dh_get0_params(DH *dh) { return &dh->params; } int ossl_dh_get0_nid(const DH *dh) { return dh->params.nid; }
./openssl/crypto/dh/dh_asn1.c
/* * Copyright 2000-2021 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 */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include "dh_local.h" #include <openssl/objects.h> #include <openssl/asn1t.h> #include "crypto/dh.h" /* Override the default free and new methods */ static int dh_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_NEW_PRE) { *pval = (ASN1_VALUE *)DH_new(); if (*pval != NULL) return 2; return 0; } else if (operation == ASN1_OP_FREE_PRE) { DH_free((DH *)*pval); *pval = NULL; return 2; } else if (operation == ASN1_OP_D2I_POST) { DH *dh = (DH *)*pval; DH_clear_flags(dh, DH_FLAG_TYPE_MASK); DH_set_flags(dh, DH_FLAG_TYPE_DH); ossl_dh_cache_named_group(dh); dh->dirty_cnt++; } return 1; } ASN1_SEQUENCE_cb(DHparams, dh_cb) = { ASN1_SIMPLE(DH, params.p, BIGNUM), ASN1_SIMPLE(DH, params.g, BIGNUM), ASN1_OPT_EMBED(DH, length, ZINT32), } ASN1_SEQUENCE_END_cb(DH, DHparams) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(DH, DHparams, DHparams) /* * Internal only structures for handling X9.42 DH: this gets translated to or * from a DH structure straight away. */ typedef struct { ASN1_BIT_STRING *seed; BIGNUM *counter; } int_dhvparams; typedef struct { BIGNUM *p; BIGNUM *q; BIGNUM *g; BIGNUM *j; int_dhvparams *vparams; } int_dhx942_dh; ASN1_SEQUENCE(DHvparams) = { ASN1_SIMPLE(int_dhvparams, seed, ASN1_BIT_STRING), ASN1_SIMPLE(int_dhvparams, counter, BIGNUM) } static_ASN1_SEQUENCE_END_name(int_dhvparams, DHvparams) ASN1_SEQUENCE(DHxparams) = { ASN1_SIMPLE(int_dhx942_dh, p, BIGNUM), ASN1_SIMPLE(int_dhx942_dh, g, BIGNUM), ASN1_SIMPLE(int_dhx942_dh, q, BIGNUM), ASN1_OPT(int_dhx942_dh, j, BIGNUM), ASN1_OPT(int_dhx942_dh, vparams, DHvparams), } static_ASN1_SEQUENCE_END_name(int_dhx942_dh, DHxparams) int_dhx942_dh *d2i_int_dhx(int_dhx942_dh **a, const unsigned char **pp, long length); int i2d_int_dhx(const int_dhx942_dh *a, unsigned char **pp); IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(int_dhx942_dh, DHxparams, int_dhx) DH *d2i_DHxparams(DH **a, const unsigned char **pp, long length) { FFC_PARAMS *params; int_dhx942_dh *dhx = NULL; DH *dh = NULL; dh = DH_new(); if (dh == NULL) return NULL; dhx = d2i_int_dhx(NULL, pp, length); if (dhx == NULL) { DH_free(dh); return NULL; } if (a != NULL) { DH_free(*a); *a = dh; } params = &dh->params; DH_set0_pqg(dh, dhx->p, dhx->q, dhx->g); ossl_ffc_params_set0_j(params, dhx->j); if (dhx->vparams != NULL) { /* The counter has a maximum value of 4 * numbits(p) - 1 */ size_t counter = (size_t)BN_get_word(dhx->vparams->counter); ossl_ffc_params_set_validate_params(params, dhx->vparams->seed->data, dhx->vparams->seed->length, counter); ASN1_BIT_STRING_free(dhx->vparams->seed); BN_free(dhx->vparams->counter); OPENSSL_free(dhx->vparams); dhx->vparams = NULL; } OPENSSL_free(dhx); DH_clear_flags(dh, DH_FLAG_TYPE_MASK); DH_set_flags(dh, DH_FLAG_TYPE_DHX); return dh; } int i2d_DHxparams(const DH *dh, unsigned char **pp) { int ret = 0; int_dhx942_dh dhx; int_dhvparams dhv = { NULL, NULL }; ASN1_BIT_STRING seed; size_t seedlen = 0; const FFC_PARAMS *params = &dh->params; int counter; ossl_ffc_params_get0_pqg(params, (const BIGNUM **)&dhx.p, (const BIGNUM **)&dhx.q, (const BIGNUM **)&dhx.g); dhx.j = params->j; ossl_ffc_params_get_validate_params(params, &seed.data, &seedlen, &counter); seed.length = (int)seedlen; if (counter != -1 && seed.data != NULL && seed.length > 0) { seed.flags = ASN1_STRING_FLAG_BITS_LEFT; dhv.seed = &seed; dhv.counter = BN_new(); if (dhv.counter == NULL) return 0; if (!BN_set_word(dhv.counter, (BN_ULONG)counter)) goto err; dhx.vparams = &dhv; } else { dhx.vparams = NULL; } ret = i2d_int_dhx(&dhx, pp); err: BN_free(dhv.counter); return ret; }
./openssl/crypto/dh/dh_backend.c
/* * Copyright 2020-2023 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 */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/err.h> #include <openssl/core_names.h> #ifndef FIPS_MODULE # include <openssl/x509.h> #endif #include "internal/param_build_set.h" #include "crypto/dh.h" #include "dh_local.h" /* * The intention with the "backend" source file is to offer backend functions * for legacy backends (EVP_PKEY_ASN1_METHOD and EVP_PKEY_METHOD) and provider * implementations alike. */ static int dh_ffc_params_fromdata(DH *dh, const OSSL_PARAM params[]) { int ret; FFC_PARAMS *ffc = ossl_dh_get0_params(dh); ret = ossl_ffc_params_fromdata(ffc, params); if (ret) ossl_dh_cache_named_group(dh); /* This increments dh->dirty_cnt */ return ret; } int ossl_dh_params_fromdata(DH *dh, const OSSL_PARAM params[]) { const OSSL_PARAM *param_priv_len; long priv_len; if (!dh_ffc_params_fromdata(dh, params)) return 0; param_priv_len = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_DH_PRIV_LEN); if (param_priv_len != NULL && (!OSSL_PARAM_get_long(param_priv_len, &priv_len) || !DH_set_length(dh, priv_len))) return 0; return 1; } int ossl_dh_key_fromdata(DH *dh, const OSSL_PARAM params[], int include_private) { const OSSL_PARAM *param_priv_key, *param_pub_key; BIGNUM *priv_key = NULL, *pub_key = NULL; if (dh == NULL) return 0; param_priv_key = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY); param_pub_key = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY); if (include_private && param_priv_key != NULL && !OSSL_PARAM_get_BN(param_priv_key, &priv_key)) goto err; if (param_pub_key != NULL && !OSSL_PARAM_get_BN(param_pub_key, &pub_key)) goto err; if (!DH_set0_key(dh, pub_key, priv_key)) goto err; return 1; err: BN_clear_free(priv_key); BN_free(pub_key); return 0; } int ossl_dh_params_todata(DH *dh, OSSL_PARAM_BLD *bld, OSSL_PARAM params[]) { long l = DH_get_length(dh); if (!ossl_ffc_params_todata(ossl_dh_get0_params(dh), bld, params)) return 0; if (l > 0 && !ossl_param_build_set_long(bld, params, OSSL_PKEY_PARAM_DH_PRIV_LEN, l)) return 0; return 1; } int ossl_dh_key_todata(DH *dh, OSSL_PARAM_BLD *bld, OSSL_PARAM params[], int include_private) { const BIGNUM *priv = NULL, *pub = NULL; if (dh == NULL) return 0; DH_get0_key(dh, &pub, &priv); if (priv != NULL && include_private && !ossl_param_build_set_bn(bld, params, OSSL_PKEY_PARAM_PRIV_KEY, priv)) return 0; if (pub != NULL && !ossl_param_build_set_bn(bld, params, OSSL_PKEY_PARAM_PUB_KEY, pub)) return 0; return 1; } int ossl_dh_is_foreign(const DH *dh) { #ifndef FIPS_MODULE if (dh->engine != NULL || ossl_dh_get_method(dh) != DH_OpenSSL()) return 1; #endif return 0; } static ossl_inline int dh_bn_dup_check(BIGNUM **out, const BIGNUM *f) { if (f != NULL && (*out = BN_dup(f)) == NULL) return 0; return 1; } DH *ossl_dh_dup(const DH *dh, int selection) { DH *dupkey = NULL; /* Do not try to duplicate foreign DH keys */ if (ossl_dh_is_foreign(dh)) return NULL; if ((dupkey = ossl_dh_new_ex(dh->libctx)) == NULL) return NULL; dupkey->length = DH_get_length(dh); if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0 && !ossl_ffc_params_copy(&dupkey->params, &dh->params)) goto err; dupkey->flags = dh->flags; if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0 && ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0 || !dh_bn_dup_check(&dupkey->pub_key, dh->pub_key))) goto err; if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0 && ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0 || !dh_bn_dup_check(&dupkey->priv_key, dh->priv_key))) goto err; #ifndef FIPS_MODULE if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_DH, &dupkey->ex_data, &dh->ex_data)) goto err; #endif return dupkey; err: DH_free(dupkey); return NULL; } #ifndef FIPS_MODULE DH *ossl_dh_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *libctx, const char *propq) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; const void *pval; const ASN1_STRING *pstr; const X509_ALGOR *palg; BIGNUM *privkey_bn = NULL; ASN1_INTEGER *privkey = NULL; DH *dh = NULL; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8inf)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if (ptype != V_ASN1_SEQUENCE) goto decerr; if ((privkey = d2i_ASN1_INTEGER(NULL, &p, pklen)) == NULL) goto decerr; pstr = pval; pm = pstr->data; pmlen = pstr->length; switch (OBJ_obj2nid(palg->algorithm)) { case NID_dhKeyAgreement: dh = d2i_DHparams(NULL, &pm, pmlen); break; case NID_dhpublicnumber: dh = d2i_DHxparams(NULL, &pm, pmlen); break; default: goto decerr; } if (dh == NULL) goto decerr; /* We have parameters now set private key */ if ((privkey_bn = BN_secure_new()) == NULL || !ASN1_INTEGER_to_BN(privkey, privkey_bn)) { ERR_raise(ERR_LIB_DH, DH_R_BN_ERROR); BN_clear_free(privkey_bn); goto dherr; } if (!DH_set0_key(dh, NULL, privkey_bn)) goto dherr; /* Calculate public key, increments dirty_cnt */ if (!DH_generate_key(dh)) goto dherr; goto done; decerr: ERR_raise(ERR_LIB_DH, EVP_R_DECODE_ERROR); dherr: DH_free(dh); dh = NULL; done: ASN1_STRING_clear_free(privkey); return dh; } #endif
./openssl/crypto/dh/dh_check.c
/* * Copyright 1995-2023 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 */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include "dh_local.h" #include "crypto/dh.h" /*- * Check that p and g are suitable enough * * p is odd * 1 < g < p - 1 */ int DH_check_params_ex(const DH *dh) { int errflags = 0; if (!DH_check_params(dh, &errflags)) return 0; if ((errflags & DH_CHECK_P_NOT_PRIME) != 0) ERR_raise(ERR_LIB_DH, DH_R_CHECK_P_NOT_PRIME); if ((errflags & DH_NOT_SUITABLE_GENERATOR) != 0) ERR_raise(ERR_LIB_DH, DH_R_NOT_SUITABLE_GENERATOR); if ((errflags & DH_MODULUS_TOO_SMALL) != 0) ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_SMALL); if ((errflags & DH_MODULUS_TOO_LARGE) != 0) ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_LARGE); return errflags == 0; } #ifdef FIPS_MODULE int DH_check_params(const DH *dh, int *ret) { int nid; *ret = 0; /* * SP800-56A R3 Section 5.5.2 Assurances of Domain Parameter Validity * (1a) The domain parameters correspond to any approved safe prime group. */ nid = DH_get_nid((DH *)dh); if (nid != NID_undef) return 1; /* * OR * (2b) FFC domain params conform to FIPS-186-4 explicit domain param * validity tests. */ return ossl_ffc_params_FIPS186_4_validate(dh->libctx, &dh->params, FFC_PARAM_TYPE_DH, ret, NULL); } #else int DH_check_params(const DH *dh, int *ret) { int ok = 0; BIGNUM *tmp = NULL; BN_CTX *ctx = NULL; *ret = 0; ctx = BN_CTX_new_ex(dh->libctx); if (ctx == NULL) goto err; BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) goto err; if (!BN_is_odd(dh->params.p)) *ret |= DH_CHECK_P_NOT_PRIME; if (BN_is_negative(dh->params.g) || BN_is_zero(dh->params.g) || BN_is_one(dh->params.g)) *ret |= DH_NOT_SUITABLE_GENERATOR; if (BN_copy(tmp, dh->params.p) == NULL || !BN_sub_word(tmp, 1)) goto err; if (BN_cmp(dh->params.g, tmp) >= 0) *ret |= DH_NOT_SUITABLE_GENERATOR; if (BN_num_bits(dh->params.p) < DH_MIN_MODULUS_BITS) *ret |= DH_MODULUS_TOO_SMALL; if (BN_num_bits(dh->params.p) > OPENSSL_DH_MAX_MODULUS_BITS) *ret |= DH_MODULUS_TOO_LARGE; ok = 1; err: BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; } #endif /* FIPS_MODULE */ /*- * Check that p is a safe prime and * g is a suitable generator. */ int DH_check_ex(const DH *dh) { int errflags = 0; if (!DH_check(dh, &errflags)) return 0; if ((errflags & DH_NOT_SUITABLE_GENERATOR) != 0) ERR_raise(ERR_LIB_DH, DH_R_NOT_SUITABLE_GENERATOR); if ((errflags & DH_CHECK_Q_NOT_PRIME) != 0) ERR_raise(ERR_LIB_DH, DH_R_CHECK_Q_NOT_PRIME); if ((errflags & DH_CHECK_INVALID_Q_VALUE) != 0) ERR_raise(ERR_LIB_DH, DH_R_CHECK_INVALID_Q_VALUE); if ((errflags & DH_CHECK_INVALID_J_VALUE) != 0) ERR_raise(ERR_LIB_DH, DH_R_CHECK_INVALID_J_VALUE); if ((errflags & DH_UNABLE_TO_CHECK_GENERATOR) != 0) ERR_raise(ERR_LIB_DH, DH_R_UNABLE_TO_CHECK_GENERATOR); if ((errflags & DH_CHECK_P_NOT_PRIME) != 0) ERR_raise(ERR_LIB_DH, DH_R_CHECK_P_NOT_PRIME); if ((errflags & DH_CHECK_P_NOT_SAFE_PRIME) != 0) ERR_raise(ERR_LIB_DH, DH_R_CHECK_P_NOT_SAFE_PRIME); if ((errflags & DH_MODULUS_TOO_SMALL) != 0) ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_SMALL); if ((errflags & DH_MODULUS_TOO_LARGE) != 0) ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_LARGE); return errflags == 0; } /* Note: according to documentation - this only checks the params */ int DH_check(const DH *dh, int *ret) { #ifdef FIPS_MODULE return DH_check_params(dh, ret); #else int ok = 0, r, q_good = 0; BN_CTX *ctx = NULL; BIGNUM *t1 = NULL, *t2 = NULL; int nid = DH_get_nid((DH *)dh); *ret = 0; if (nid != NID_undef) return 1; /* Don't do any checks at all with an excessively large modulus */ if (BN_num_bits(dh->params.p) > OPENSSL_DH_CHECK_MAX_MODULUS_BITS) { ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_LARGE); *ret = DH_MODULUS_TOO_LARGE | DH_CHECK_P_NOT_PRIME; return 0; } if (!DH_check_params(dh, ret)) return 0; ctx = BN_CTX_new_ex(dh->libctx); if (ctx == NULL) goto err; BN_CTX_start(ctx); t1 = BN_CTX_get(ctx); t2 = BN_CTX_get(ctx); if (t2 == NULL) goto err; if (dh->params.q != NULL) { if (BN_ucmp(dh->params.p, dh->params.q) > 0) q_good = 1; else *ret |= DH_CHECK_INVALID_Q_VALUE; } if (q_good) { if (BN_cmp(dh->params.g, BN_value_one()) <= 0) *ret |= DH_NOT_SUITABLE_GENERATOR; else if (BN_cmp(dh->params.g, dh->params.p) >= 0) *ret |= DH_NOT_SUITABLE_GENERATOR; else { /* Check g^q == 1 mod p */ if (!BN_mod_exp(t1, dh->params.g, dh->params.q, dh->params.p, ctx)) goto err; if (!BN_is_one(t1)) *ret |= DH_NOT_SUITABLE_GENERATOR; } r = BN_check_prime(dh->params.q, ctx, NULL); if (r < 0) goto err; if (!r) *ret |= DH_CHECK_Q_NOT_PRIME; /* Check p == 1 mod q i.e. q divides p - 1 */ if (!BN_div(t1, t2, dh->params.p, dh->params.q, ctx)) goto err; if (!BN_is_one(t2)) *ret |= DH_CHECK_INVALID_Q_VALUE; if (dh->params.j != NULL && BN_cmp(dh->params.j, t1)) *ret |= DH_CHECK_INVALID_J_VALUE; } r = BN_check_prime(dh->params.p, ctx, NULL); if (r < 0) goto err; if (!r) *ret |= DH_CHECK_P_NOT_PRIME; else if (dh->params.q == NULL) { if (!BN_rshift1(t1, dh->params.p)) goto err; r = BN_check_prime(t1, ctx, NULL); if (r < 0) goto err; if (!r) *ret |= DH_CHECK_P_NOT_SAFE_PRIME; } ok = 1; err: BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; #endif /* FIPS_MODULE */ } int DH_check_pub_key_ex(const DH *dh, const BIGNUM *pub_key) { int errflags = 0; if (!DH_check_pub_key(dh, pub_key, &errflags)) return 0; if ((errflags & DH_CHECK_PUBKEY_TOO_SMALL) != 0) ERR_raise(ERR_LIB_DH, DH_R_CHECK_PUBKEY_TOO_SMALL); if ((errflags & DH_CHECK_PUBKEY_TOO_LARGE) != 0) ERR_raise(ERR_LIB_DH, DH_R_CHECK_PUBKEY_TOO_LARGE); if ((errflags & DH_CHECK_PUBKEY_INVALID) != 0) ERR_raise(ERR_LIB_DH, DH_R_CHECK_PUBKEY_INVALID); return errflags == 0; } /* * See SP800-56Ar3 Section 5.6.2.3.1 : FFC Full public key validation. */ int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *ret) { /* Don't do any checks at all with an excessively large modulus */ if (BN_num_bits(dh->params.p) > OPENSSL_DH_CHECK_MAX_MODULUS_BITS) { ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_LARGE); *ret = DH_MODULUS_TOO_LARGE | DH_CHECK_PUBKEY_INVALID; return 0; } if (dh->params.q != NULL && BN_ucmp(dh->params.p, dh->params.q) < 0) { *ret |= DH_CHECK_INVALID_Q_VALUE | DH_CHECK_PUBKEY_INVALID; return 1; } return ossl_ffc_validate_public_key(&dh->params, pub_key, ret); } /* * See SP800-56Ar3 Section 5.6.2.3.1 : FFC Partial public key validation. * To only be used with ephemeral FFC public keys generated using the approved * safe-prime groups. */ int ossl_dh_check_pub_key_partial(const DH *dh, const BIGNUM *pub_key, int *ret) { return ossl_ffc_validate_public_key_partial(&dh->params, pub_key, ret) && *ret == 0; } int ossl_dh_check_priv_key(const DH *dh, const BIGNUM *priv_key, int *ret) { int ok = 0; BIGNUM *two_powN = NULL, *upper; *ret = 0; two_powN = BN_new(); if (two_powN == NULL) return 0; if (dh->params.q != NULL) { upper = dh->params.q; #ifndef FIPS_MODULE } else if (dh->params.p != NULL) { /* * We do not have q so we just check the key is within some * reasonable range, or the number of bits is equal to dh->length. */ int length = dh->length; if (length == 0) { length = BN_num_bits(dh->params.p) - 1; if (BN_num_bits(priv_key) <= length && BN_num_bits(priv_key) > 1) ok = 1; } else if (BN_num_bits(priv_key) == length) { ok = 1; } goto end; #endif } else { goto end; } /* Is it from an approved Safe prime group ?*/ if (DH_get_nid((DH *)dh) != NID_undef && dh->length != 0) { if (!BN_lshift(two_powN, BN_value_one(), dh->length)) goto end; if (BN_cmp(two_powN, dh->params.q) < 0) upper = two_powN; } if (!ossl_ffc_validate_private_key(upper, priv_key, ret)) goto end; ok = 1; end: BN_free(two_powN); return ok; } /* * FFC pairwise check from SP800-56A R3. * Section 5.6.2.1.4 Owner Assurance of Pair-wise Consistency */ int ossl_dh_check_pairwise(const DH *dh) { int ret = 0; BN_CTX *ctx = NULL; BIGNUM *pub_key = NULL; if (dh->params.p == NULL || dh->params.g == NULL || dh->priv_key == NULL || dh->pub_key == NULL) return 0; ctx = BN_CTX_new_ex(dh->libctx); if (ctx == NULL) goto err; pub_key = BN_new(); if (pub_key == NULL) goto err; /* recalculate the public key = (g ^ priv) mod p */ if (!ossl_dh_generate_public_key(ctx, dh, dh->priv_key, pub_key)) goto err; /* check it matches the existing pubic_key */ ret = BN_cmp(pub_key, dh->pub_key) == 0; err: BN_free(pub_key); BN_CTX_free(ctx); return ret; }
./openssl/crypto/dh/dh_depr.c
/* * Copyright 2002-2020 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 */ /* This file contains deprecated functions as wrappers to the new ones */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/opensslconf.h> #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/dh.h> DH *DH_generate_parameters(int prime_len, int generator, void (*callback) (int, int, void *), void *cb_arg) { BN_GENCB *cb; DH *ret = NULL; if ((ret = DH_new()) == NULL) return NULL; cb = BN_GENCB_new(); if (cb == NULL) { DH_free(ret); return NULL; } BN_GENCB_set_old(cb, callback, cb_arg); if (DH_generate_parameters_ex(ret, prime_len, generator, cb)) { BN_GENCB_free(cb); return ret; } BN_GENCB_free(cb); DH_free(ret); return NULL; }
./openssl/crypto/dh/dh_pmeth.c
/* * Copyright 2006-2021 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 */ /* * DH & DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> #include <openssl/evp.h> #include "dh_local.h" #include <openssl/bn.h> #include <openssl/dsa.h> #include <openssl/objects.h> #include "crypto/evp.h" /* DH pkey context structure */ typedef struct { /* Parameter gen parameters */ int prime_len; int generator; int paramgen_type; int subprime_len; int pad; /* message digest used for parameter generation */ const EVP_MD *md; int param_nid; /* Keygen callback info */ int gentmp[2]; /* KDF (if any) to use for DH */ char kdf_type; /* OID to use for KDF */ ASN1_OBJECT *kdf_oid; /* Message digest to use for key derivation */ const EVP_MD *kdf_md; /* User key material */ unsigned char *kdf_ukm; size_t kdf_ukmlen; /* KDF output length */ size_t kdf_outlen; } DH_PKEY_CTX; static int pkey_dh_init(EVP_PKEY_CTX *ctx) { DH_PKEY_CTX *dctx; if ((dctx = OPENSSL_zalloc(sizeof(*dctx))) == NULL) return 0; dctx->prime_len = 2048; dctx->subprime_len = -1; dctx->generator = 2; dctx->kdf_type = EVP_PKEY_DH_KDF_NONE; ctx->data = dctx; ctx->keygen_info = dctx->gentmp; ctx->keygen_info_count = 2; return 1; } static void pkey_dh_cleanup(EVP_PKEY_CTX *ctx) { DH_PKEY_CTX *dctx = ctx->data; if (dctx != NULL) { OPENSSL_free(dctx->kdf_ukm); ASN1_OBJECT_free(dctx->kdf_oid); OPENSSL_free(dctx); } } static int pkey_dh_copy(EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src) { DH_PKEY_CTX *dctx, *sctx; if (!pkey_dh_init(dst)) return 0; sctx = src->data; dctx = dst->data; dctx->prime_len = sctx->prime_len; dctx->subprime_len = sctx->subprime_len; dctx->generator = sctx->generator; dctx->paramgen_type = sctx->paramgen_type; dctx->pad = sctx->pad; dctx->md = sctx->md; dctx->param_nid = sctx->param_nid; dctx->kdf_type = sctx->kdf_type; dctx->kdf_oid = OBJ_dup(sctx->kdf_oid); if (dctx->kdf_oid == NULL) return 0; dctx->kdf_md = sctx->kdf_md; if (sctx->kdf_ukm != NULL) { dctx->kdf_ukm = OPENSSL_memdup(sctx->kdf_ukm, sctx->kdf_ukmlen); if (dctx->kdf_ukm == NULL) return 0; dctx->kdf_ukmlen = sctx->kdf_ukmlen; } dctx->kdf_outlen = sctx->kdf_outlen; return 1; } static int pkey_dh_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { DH_PKEY_CTX *dctx = ctx->data; switch (type) { case EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN: if (p1 < 256) return -2; dctx->prime_len = p1; return 1; case EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN: if (dctx->paramgen_type == DH_PARAMGEN_TYPE_GENERATOR) return -2; dctx->subprime_len = p1; return 1; case EVP_PKEY_CTRL_DH_PAD: dctx->pad = p1; return 1; case EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR: if (dctx->paramgen_type != DH_PARAMGEN_TYPE_GENERATOR) return -2; dctx->generator = p1; return 1; case EVP_PKEY_CTRL_DH_PARAMGEN_TYPE: #ifdef OPENSSL_NO_DSA if (p1 != DH_PARAMGEN_TYPE_GENERATOR) return -2; #else if (p1 < 0 || p1 > 2) return -2; #endif dctx->paramgen_type = p1; return 1; case EVP_PKEY_CTRL_DH_RFC5114: if (p1 < 1 || p1 > 3 || dctx->param_nid != NID_undef) return -2; dctx->param_nid = p1; return 1; case EVP_PKEY_CTRL_DH_NID: if (p1 <= 0 || dctx->param_nid != NID_undef) return -2; dctx->param_nid = p1; return 1; case EVP_PKEY_CTRL_PEER_KEY: /* Default behaviour is OK */ return 1; case EVP_PKEY_CTRL_DH_KDF_TYPE: if (p1 == -2) return dctx->kdf_type; if (p1 != EVP_PKEY_DH_KDF_NONE && p1 != EVP_PKEY_DH_KDF_X9_42) return -2; dctx->kdf_type = p1; return 1; case EVP_PKEY_CTRL_DH_KDF_MD: dctx->kdf_md = p2; return 1; case EVP_PKEY_CTRL_GET_DH_KDF_MD: *(const EVP_MD **)p2 = dctx->kdf_md; return 1; case EVP_PKEY_CTRL_DH_KDF_OUTLEN: if (p1 <= 0) return -2; dctx->kdf_outlen = (size_t)p1; return 1; case EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN: *(int *)p2 = dctx->kdf_outlen; return 1; case EVP_PKEY_CTRL_DH_KDF_UKM: OPENSSL_free(dctx->kdf_ukm); dctx->kdf_ukm = p2; if (p2) dctx->kdf_ukmlen = p1; else dctx->kdf_ukmlen = 0; return 1; case EVP_PKEY_CTRL_GET_DH_KDF_UKM: *(unsigned char **)p2 = dctx->kdf_ukm; return dctx->kdf_ukmlen; case EVP_PKEY_CTRL_DH_KDF_OID: ASN1_OBJECT_free(dctx->kdf_oid); dctx->kdf_oid = p2; return 1; case EVP_PKEY_CTRL_GET_DH_KDF_OID: *(ASN1_OBJECT **)p2 = dctx->kdf_oid; return 1; default: return -2; } } static int pkey_dh_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { if (strcmp(type, "dh_paramgen_prime_len") == 0) { int len; len = atoi(value); return EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, len); } if (strcmp(type, "dh_rfc5114") == 0) { DH_PKEY_CTX *dctx = ctx->data; int id; id = atoi(value); if (id < 0 || id > 3) return -2; dctx->param_nid = id; return 1; } if (strcmp(type, "dh_param") == 0) { DH_PKEY_CTX *dctx = ctx->data; int nid = OBJ_sn2nid(value); if (nid == NID_undef) { ERR_raise(ERR_LIB_DH, DH_R_INVALID_PARAMETER_NAME); return -2; } dctx->param_nid = nid; return 1; } if (strcmp(type, "dh_paramgen_generator") == 0) { int len; len = atoi(value); return EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, len); } if (strcmp(type, "dh_paramgen_subprime_len") == 0) { int len; len = atoi(value); return EVP_PKEY_CTX_set_dh_paramgen_subprime_len(ctx, len); } if (strcmp(type, "dh_paramgen_type") == 0) { int typ; typ = atoi(value); return EVP_PKEY_CTX_set_dh_paramgen_type(ctx, typ); } if (strcmp(type, "dh_pad") == 0) { int pad; pad = atoi(value); return EVP_PKEY_CTX_set_dh_pad(ctx, pad); } return -2; } static DH *ffc_params_generate(OSSL_LIB_CTX *libctx, DH_PKEY_CTX *dctx, BN_GENCB *pcb) { DH *ret; int rv = 0; int res; int prime_len = dctx->prime_len; int subprime_len = dctx->subprime_len; if (dctx->paramgen_type > DH_PARAMGEN_TYPE_FIPS_186_4) return NULL; ret = DH_new(); if (ret == NULL) return NULL; if (subprime_len == -1) { if (prime_len >= 2048) subprime_len = 256; else subprime_len = 160; } if (dctx->md != NULL) ossl_ffc_set_digest(&ret->params, EVP_MD_get0_name(dctx->md), NULL); # ifndef FIPS_MODULE if (dctx->paramgen_type == DH_PARAMGEN_TYPE_FIPS_186_2) rv = ossl_ffc_params_FIPS186_2_generate(libctx, &ret->params, FFC_PARAM_TYPE_DH, prime_len, subprime_len, &res, pcb); else # endif /* For FIPS we always use the DH_PARAMGEN_TYPE_FIPS_186_4 generator */ if (dctx->paramgen_type >= DH_PARAMGEN_TYPE_FIPS_186_2) rv = ossl_ffc_params_FIPS186_4_generate(libctx, &ret->params, FFC_PARAM_TYPE_DH, prime_len, subprime_len, &res, pcb); if (rv <= 0) { DH_free(ret); return NULL; } return ret; } static int pkey_dh_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { DH *dh = NULL; DH_PKEY_CTX *dctx = ctx->data; BN_GENCB *pcb = NULL; int ret; /* * Look for a safe prime group for key establishment. Which uses * either RFC_3526 (modp_XXXX) or RFC_7919 (ffdheXXXX). * RFC_5114 is also handled here for param_nid = (1..3) */ if (dctx->param_nid != NID_undef) { int type = dctx->param_nid <= 3 ? EVP_PKEY_DHX : EVP_PKEY_DH; if ((dh = DH_new_by_nid(dctx->param_nid)) == NULL) return 0; EVP_PKEY_assign(pkey, type, dh); return 1; } if (ctx->pkey_gencb != NULL) { pcb = BN_GENCB_new(); if (pcb == NULL) return 0; evp_pkey_set_cb_translate(pcb, ctx); } # ifdef FIPS_MODULE dctx->paramgen_type = DH_PARAMGEN_TYPE_FIPS_186_4; # endif /* FIPS_MODULE */ if (dctx->paramgen_type >= DH_PARAMGEN_TYPE_FIPS_186_2) { dh = ffc_params_generate(NULL, dctx, pcb); BN_GENCB_free(pcb); if (dh == NULL) return 0; EVP_PKEY_assign(pkey, EVP_PKEY_DHX, dh); return 1; } dh = DH_new(); if (dh == NULL) { BN_GENCB_free(pcb); return 0; } ret = DH_generate_parameters_ex(dh, dctx->prime_len, dctx->generator, pcb); BN_GENCB_free(pcb); if (ret) EVP_PKEY_assign_DH(pkey, dh); else DH_free(dh); return ret; } static int pkey_dh_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { DH_PKEY_CTX *dctx = ctx->data; DH *dh = NULL; if (ctx->pkey == NULL && dctx->param_nid == NID_undef) { ERR_raise(ERR_LIB_DH, DH_R_NO_PARAMETERS_SET); return 0; } if (dctx->param_nid != NID_undef) dh = DH_new_by_nid(dctx->param_nid); else dh = DH_new(); if (dh == NULL) return 0; EVP_PKEY_assign(pkey, ctx->pmeth->pkey_id, dh); /* Note: if error return, pkey is freed by parent routine */ if (ctx->pkey != NULL && !EVP_PKEY_copy_parameters(pkey, ctx->pkey)) return 0; return DH_generate_key((DH *)EVP_PKEY_get0_DH(pkey)); } static int pkey_dh_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen) { int ret; DH *dh; const DH *dhpub; DH_PKEY_CTX *dctx = ctx->data; BIGNUM *dhpubbn; if (ctx->pkey == NULL || ctx->peerkey == NULL) { ERR_raise(ERR_LIB_DH, DH_R_KEYS_NOT_SET); return 0; } dh = (DH *)EVP_PKEY_get0_DH(ctx->pkey); dhpub = EVP_PKEY_get0_DH(ctx->peerkey); if (dhpub == NULL) { ERR_raise(ERR_LIB_DH, DH_R_KEYS_NOT_SET); return 0; } dhpubbn = dhpub->pub_key; if (dctx->kdf_type == EVP_PKEY_DH_KDF_NONE) { if (key == NULL) { *keylen = DH_size(dh); return 1; } if (dctx->pad) ret = DH_compute_key_padded(key, dhpubbn, dh); else ret = DH_compute_key(key, dhpubbn, dh); if (ret < 0) return ret; *keylen = ret; return 1; } else if (dctx->kdf_type == EVP_PKEY_DH_KDF_X9_42) { unsigned char *Z = NULL; int Zlen = 0; if (!dctx->kdf_outlen || !dctx->kdf_oid) return 0; if (key == NULL) { *keylen = dctx->kdf_outlen; return 1; } if (*keylen != dctx->kdf_outlen) return 0; ret = 0; if ((Zlen = DH_size(dh)) <= 0) return 0; if ((Z = OPENSSL_malloc(Zlen)) == NULL) return 0; if (DH_compute_key_padded(Z, dhpubbn, dh) <= 0) goto err; if (!DH_KDF_X9_42(key, *keylen, Z, Zlen, dctx->kdf_oid, dctx->kdf_ukm, dctx->kdf_ukmlen, dctx->kdf_md)) goto err; *keylen = dctx->kdf_outlen; ret = 1; err: OPENSSL_clear_free(Z, Zlen); return ret; } return 0; } static const EVP_PKEY_METHOD dh_pkey_meth = { EVP_PKEY_DH, 0, pkey_dh_init, pkey_dh_copy, pkey_dh_cleanup, 0, pkey_dh_paramgen, 0, pkey_dh_keygen, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, pkey_dh_derive, pkey_dh_ctrl, pkey_dh_ctrl_str }; const EVP_PKEY_METHOD *ossl_dh_pkey_method(void) { return &dh_pkey_meth; } static const EVP_PKEY_METHOD dhx_pkey_meth = { EVP_PKEY_DHX, 0, pkey_dh_init, pkey_dh_copy, pkey_dh_cleanup, 0, pkey_dh_paramgen, 0, pkey_dh_keygen, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, pkey_dh_derive, pkey_dh_ctrl, pkey_dh_ctrl_str }; const EVP_PKEY_METHOD *ossl_dhx_pkey_method(void) { return &dhx_pkey_meth; }
./openssl/crypto/dh/dh_key.c
/* * Copyright 1995-2023 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 */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include "dh_local.h" #include "crypto/bn.h" #include "crypto/dh.h" #include "crypto/security_bits.h" #ifdef FIPS_MODULE # define MIN_STRENGTH 112 #else # define MIN_STRENGTH 80 #endif static int generate_key(DH *dh); static int dh_bn_mod_exp(const DH *dh, BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); static int dh_init(DH *dh); static int dh_finish(DH *dh); /* * See SP800-56Ar3 Section 5.7.1.1 * Finite Field Cryptography Diffie-Hellman (FFC DH) Primitive */ int ossl_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh) { BN_CTX *ctx = NULL; BN_MONT_CTX *mont = NULL; BIGNUM *z = NULL, *pminus1; int ret = -1; if (BN_num_bits(dh->params.p) > OPENSSL_DH_MAX_MODULUS_BITS) { ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_LARGE); goto err; } if (dh->params.q != NULL && BN_num_bits(dh->params.q) > OPENSSL_DH_MAX_MODULUS_BITS) { ERR_raise(ERR_LIB_DH, DH_R_Q_TOO_LARGE); goto err; } if (BN_num_bits(dh->params.p) < DH_MIN_MODULUS_BITS) { ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_SMALL); return 0; } ctx = BN_CTX_new_ex(dh->libctx); if (ctx == NULL) goto err; BN_CTX_start(ctx); pminus1 = BN_CTX_get(ctx); z = BN_CTX_get(ctx); if (z == NULL) goto err; if (dh->priv_key == NULL) { ERR_raise(ERR_LIB_DH, DH_R_NO_PRIVATE_VALUE); goto err; } if (dh->flags & DH_FLAG_CACHE_MONT_P) { mont = BN_MONT_CTX_set_locked(&dh->method_mont_p, dh->lock, dh->params.p, ctx); BN_set_flags(dh->priv_key, BN_FLG_CONSTTIME); if (!mont) goto err; } /* (Step 1) Z = pub_key^priv_key mod p */ if (!dh->meth->bn_mod_exp(dh, z, pub_key, dh->priv_key, dh->params.p, ctx, mont)) { ERR_raise(ERR_LIB_DH, ERR_R_BN_LIB); goto err; } /* (Step 2) Error if z <= 1 or z = p - 1 */ if (BN_copy(pminus1, dh->params.p) == NULL || !BN_sub_word(pminus1, 1) || BN_cmp(z, BN_value_one()) <= 0 || BN_cmp(z, pminus1) == 0) { ERR_raise(ERR_LIB_DH, DH_R_INVALID_SECRET); goto err; } /* return the padded key, i.e. same number of bytes as the modulus */ ret = BN_bn2binpad(z, key, BN_num_bytes(dh->params.p)); err: BN_clear(z); /* (Step 2) destroy intermediate values */ BN_CTX_end(ctx); BN_CTX_free(ctx); return ret; } /*- * NB: This function is inherently not constant time due to the * RFC 5246 (8.1.2) padding style that strips leading zero bytes. */ int DH_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh) { int ret = 0, i; volatile size_t npad = 0, mask = 1; /* compute the key; ret is constant unless compute_key is external */ #ifdef FIPS_MODULE ret = ossl_dh_compute_key(key, pub_key, dh); #else ret = dh->meth->compute_key(key, pub_key, dh); #endif if (ret <= 0) return ret; /* count leading zero bytes, yet still touch all bytes */ for (i = 0; i < ret; i++) { mask &= !key[i]; npad += mask; } /* unpad key */ ret -= npad; /* key-dependent memory access, potentially leaking npad / ret */ memmove(key, key + npad, ret); /* key-dependent memory access, potentially leaking npad / ret */ memset(key + ret, 0, npad); return ret; } int DH_compute_key_padded(unsigned char *key, const BIGNUM *pub_key, DH *dh) { int rv, pad; /* rv is constant unless compute_key is external */ #ifdef FIPS_MODULE rv = ossl_dh_compute_key(key, pub_key, dh); #else rv = dh->meth->compute_key(key, pub_key, dh); #endif if (rv <= 0) return rv; pad = BN_num_bytes(dh->params.p) - rv; /* pad is constant (zero) unless compute_key is external */ if (pad > 0) { memmove(key + pad, key, rv); memset(key, 0, pad); } return rv + pad; } static DH_METHOD dh_ossl = { "OpenSSL DH Method", generate_key, ossl_dh_compute_key, dh_bn_mod_exp, dh_init, dh_finish, DH_FLAG_FIPS_METHOD, NULL, NULL }; static const DH_METHOD *default_DH_method = &dh_ossl; const DH_METHOD *DH_OpenSSL(void) { return &dh_ossl; } const DH_METHOD *DH_get_default_method(void) { return default_DH_method; } static int dh_bn_mod_exp(const DH *dh, BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { #ifdef S390X_MOD_EXP return s390x_mod_exp(r, a, p, m, ctx, m_ctx); #else return BN_mod_exp_mont(r, a, p, m, ctx, m_ctx); #endif } static int dh_init(DH *dh) { dh->flags |= DH_FLAG_CACHE_MONT_P; dh->dirty_cnt++; return 1; } static int dh_finish(DH *dh) { BN_MONT_CTX_free(dh->method_mont_p); return 1; } #ifndef FIPS_MODULE void DH_set_default_method(const DH_METHOD *meth) { default_DH_method = meth; } #endif /* FIPS_MODULE */ int DH_generate_key(DH *dh) { #ifdef FIPS_MODULE return generate_key(dh); #else return dh->meth->generate_key(dh); #endif } int ossl_dh_generate_public_key(BN_CTX *ctx, const DH *dh, const BIGNUM *priv_key, BIGNUM *pub_key) { int ret = 0; BIGNUM *prk = BN_new(); BN_MONT_CTX *mont = NULL; if (prk == NULL) return 0; if (dh->flags & DH_FLAG_CACHE_MONT_P) { /* * We take the input DH as const, but we lie, because in some cases we * want to get a hold of its Montgomery context. * * We cast to remove the const qualifier in this case, it should be * fine... */ BN_MONT_CTX **pmont = (BN_MONT_CTX **)&dh->method_mont_p; mont = BN_MONT_CTX_set_locked(pmont, dh->lock, dh->params.p, ctx); if (mont == NULL) goto err; } BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME); /* pub_key = g^priv_key mod p */ if (!dh->meth->bn_mod_exp(dh, pub_key, dh->params.g, prk, dh->params.p, ctx, mont)) goto err; ret = 1; err: BN_clear_free(prk); return ret; } static int generate_key(DH *dh) { int ok = 0; int generate_new_key = 0; #ifndef FIPS_MODULE unsigned l; #endif BN_CTX *ctx = NULL; BIGNUM *pub_key = NULL, *priv_key = NULL; if (BN_num_bits(dh->params.p) > OPENSSL_DH_MAX_MODULUS_BITS) { ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_LARGE); return 0; } if (dh->params.q != NULL && BN_num_bits(dh->params.q) > OPENSSL_DH_MAX_MODULUS_BITS) { ERR_raise(ERR_LIB_DH, DH_R_Q_TOO_LARGE); return 0; } if (BN_num_bits(dh->params.p) < DH_MIN_MODULUS_BITS) { ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_SMALL); return 0; } ctx = BN_CTX_new_ex(dh->libctx); if (ctx == NULL) goto err; if (dh->priv_key == NULL) { priv_key = BN_secure_new(); if (priv_key == NULL) goto err; generate_new_key = 1; } else { priv_key = dh->priv_key; } if (dh->pub_key == NULL) { pub_key = BN_new(); if (pub_key == NULL) goto err; } else { pub_key = dh->pub_key; } if (generate_new_key) { /* Is it an approved safe prime ?*/ if (DH_get_nid(dh) != NID_undef) { int max_strength = ossl_ifc_ffc_compute_security_bits(BN_num_bits(dh->params.p)); if (dh->params.q == NULL || dh->length > BN_num_bits(dh->params.q)) goto err; /* dh->length = maximum bit length of generated private key */ if (!ossl_ffc_generate_private_key(ctx, &dh->params, dh->length, max_strength, priv_key)) goto err; } else { #ifdef FIPS_MODULE if (dh->params.q == NULL) goto err; #else if (dh->params.q == NULL) { /* secret exponent length, must satisfy 2^(l-1) <= p */ if (dh->length != 0 && dh->length >= BN_num_bits(dh->params.p)) goto err; l = dh->length ? dh->length : BN_num_bits(dh->params.p) - 1; if (!BN_priv_rand_ex(priv_key, l, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY, 0, ctx)) goto err; /* * We handle just one known case where g is a quadratic non-residue: * for g = 2: p % 8 == 3 */ if (BN_is_word(dh->params.g, DH_GENERATOR_2) && !BN_is_bit_set(dh->params.p, 2)) { /* clear bit 0, since it won't be a secret anyway */ if (!BN_clear_bit(priv_key, 0)) goto err; } } else #endif { /* Do a partial check for invalid p, q, g */ if (!ossl_ffc_params_simple_validate(dh->libctx, &dh->params, FFC_PARAM_TYPE_DH, NULL)) goto err; /* * For FFC FIPS 186-4 keygen * security strength s = 112, * Max Private key size N = len(q) */ if (!ossl_ffc_generate_private_key(ctx, &dh->params, BN_num_bits(dh->params.q), MIN_STRENGTH, priv_key)) goto err; } } } if (!ossl_dh_generate_public_key(ctx, dh, priv_key, pub_key)) goto err; dh->pub_key = pub_key; dh->priv_key = priv_key; dh->dirty_cnt++; ok = 1; err: if (ok != 1) ERR_raise(ERR_LIB_DH, ERR_R_BN_LIB); if (pub_key != dh->pub_key) BN_free(pub_key); if (priv_key != dh->priv_key) BN_free(priv_key); BN_CTX_free(ctx); return ok; } int ossl_dh_buf2key(DH *dh, const unsigned char *buf, size_t len) { int err_reason = DH_R_BN_ERROR; BIGNUM *pubkey = NULL; const BIGNUM *p; int ret; if ((pubkey = BN_bin2bn(buf, len, NULL)) == NULL) goto err; DH_get0_pqg(dh, &p, NULL, NULL); if (p == NULL || BN_num_bytes(p) == 0) { err_reason = DH_R_NO_PARAMETERS_SET; goto err; } /* Prevent small subgroup attacks per RFC 8446 Section 4.2.8.1 */ if (!ossl_dh_check_pub_key_partial(dh, pubkey, &ret)) { err_reason = DH_R_INVALID_PUBKEY; goto err; } if (DH_set0_key(dh, pubkey, NULL) != 1) goto err; return 1; err: ERR_raise(ERR_LIB_DH, err_reason); BN_free(pubkey); return 0; } size_t ossl_dh_key2buf(const DH *dh, unsigned char **pbuf_out, size_t size, int alloc) { const BIGNUM *pubkey; unsigned char *pbuf = NULL; const BIGNUM *p; int p_size; DH_get0_pqg(dh, &p, NULL, NULL); DH_get0_key(dh, &pubkey, NULL); if (p == NULL || pubkey == NULL || (p_size = BN_num_bytes(p)) == 0 || BN_num_bytes(pubkey) == 0) { ERR_raise(ERR_LIB_DH, DH_R_INVALID_PUBKEY); return 0; } if (pbuf_out != NULL && (alloc || *pbuf_out != NULL)) { if (!alloc) { if (size >= (size_t)p_size) pbuf = *pbuf_out; if (pbuf == NULL) ERR_raise(ERR_LIB_DH, DH_R_INVALID_SIZE); } else { pbuf = OPENSSL_malloc(p_size); } /* Errors raised above */ if (pbuf == NULL) return 0; /* * As per Section 4.2.8.1 of RFC 8446 left pad public * key with zeros to the size of p */ if (BN_bn2binpad(pubkey, pbuf, p_size) < 0) { if (alloc) OPENSSL_free(pbuf); ERR_raise(ERR_LIB_DH, DH_R_BN_ERROR); return 0; } *pbuf_out = pbuf; } return p_size; }
./openssl/crypto/dh/dh_rfc5114.c
/* * Copyright 2011-2021 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 */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include "dh_local.h" #include <openssl/bn.h> #include "crypto/bn_dh.h" /* * Macro to make a DH structure from BIGNUM data. NB: although just copying * the BIGNUM static pointers would be more efficient, we can't do that * because they get wiped using BN_clear_free() when DH_free() is called. */ #define make_dh(x) \ DH *DH_get_##x(void) \ { \ DH *dh = DH_new(); \ \ if (dh == NULL) \ return NULL; \ dh->params.p = BN_dup(&ossl_bignum_dh##x##_p); \ dh->params.g = BN_dup(&ossl_bignum_dh##x##_g); \ dh->params.q = BN_dup(&ossl_bignum_dh##x##_q); \ if (dh->params.p == NULL || dh->params.q == NULL || dh->params.g == NULL) {\ DH_free(dh); \ return NULL; \ } \ return dh; \ } make_dh(1024_160) make_dh(2048_224) make_dh(2048_256)
./openssl/crypto/dh/dh_local.h
/* * Copyright 2016-2020 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 <openssl/dh.h> #include "internal/refcount.h" #include "internal/ffc.h" #define DH_MIN_MODULUS_BITS 512 struct dh_st { /* * This first argument is used to pick up errors when a DH is passed * instead of a EVP_PKEY */ int pad; int version; FFC_PARAMS params; /* max generated private key length (can be less than len(q)) */ int32_t length; BIGNUM *pub_key; /* g^x % p */ BIGNUM *priv_key; /* x */ int flags; BN_MONT_CTX *method_mont_p; CRYPTO_REF_COUNT references; #ifndef FIPS_MODULE CRYPTO_EX_DATA ex_data; ENGINE *engine; #endif OSSL_LIB_CTX *libctx; const DH_METHOD *meth; CRYPTO_RWLOCK *lock; /* Provider data */ size_t dirty_cnt; /* If any key material changes, increment this */ }; struct dh_method { char *name; /* Methods here */ int (*generate_key) (DH *dh); int (*compute_key) (unsigned char *key, const BIGNUM *pub_key, DH *dh); /* Can be null */ int (*bn_mod_exp) (const DH *dh, BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); int (*init) (DH *dh); int (*finish) (DH *dh); int flags; char *app_data; /* If this is non-NULL, it will be used to generate parameters */ int (*generate_params) (DH *dh, int prime_len, int generator, BN_GENCB *cb); };
./openssl/crypto/dh/dh_meth.c
/* * Copyright 2016-2020 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 */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "dh_local.h" #include <string.h> #include <openssl/err.h> DH_METHOD *DH_meth_new(const char *name, int flags) { DH_METHOD *dhm = OPENSSL_zalloc(sizeof(*dhm)); if (dhm != NULL) { dhm->flags = flags; dhm->name = OPENSSL_strdup(name); if (dhm->name != NULL) return dhm; OPENSSL_free(dhm); } return NULL; } void DH_meth_free(DH_METHOD *dhm) { if (dhm != NULL) { OPENSSL_free(dhm->name); OPENSSL_free(dhm); } } DH_METHOD *DH_meth_dup(const DH_METHOD *dhm) { DH_METHOD *ret = OPENSSL_malloc(sizeof(*ret)); if (ret != NULL) { memcpy(ret, dhm, sizeof(*dhm)); ret->name = OPENSSL_strdup(dhm->name); if (ret->name != NULL) return ret; OPENSSL_free(ret); } return NULL; } const char *DH_meth_get0_name(const DH_METHOD *dhm) { return dhm->name; } int DH_meth_set1_name(DH_METHOD *dhm, const char *name) { char *tmpname = OPENSSL_strdup(name); if (tmpname == NULL) return 0; OPENSSL_free(dhm->name); dhm->name = tmpname; return 1; } int DH_meth_get_flags(const DH_METHOD *dhm) { return dhm->flags; } int DH_meth_set_flags(DH_METHOD *dhm, int flags) { dhm->flags = flags; return 1; } void *DH_meth_get0_app_data(const DH_METHOD *dhm) { return dhm->app_data; } int DH_meth_set0_app_data(DH_METHOD *dhm, void *app_data) { dhm->app_data = app_data; return 1; } int (*DH_meth_get_generate_key(const DH_METHOD *dhm)) (DH *) { return dhm->generate_key; } int DH_meth_set_generate_key(DH_METHOD *dhm, int (*generate_key) (DH *)) { dhm->generate_key = generate_key; return 1; } int (*DH_meth_get_compute_key(const DH_METHOD *dhm)) (unsigned char *key, const BIGNUM *pub_key, DH *dh) { return dhm->compute_key; } int DH_meth_set_compute_key(DH_METHOD *dhm, int (*compute_key) (unsigned char *key, const BIGNUM *pub_key, DH *dh)) { dhm->compute_key = compute_key; return 1; } int (*DH_meth_get_bn_mod_exp(const DH_METHOD *dhm)) (const DH *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *) { return dhm->bn_mod_exp; } int DH_meth_set_bn_mod_exp(DH_METHOD *dhm, int (*bn_mod_exp) (const DH *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *)) { dhm->bn_mod_exp = bn_mod_exp; return 1; } int (*DH_meth_get_init(const DH_METHOD *dhm))(DH *) { return dhm->init; } int DH_meth_set_init(DH_METHOD *dhm, int (*init)(DH *)) { dhm->init = init; return 1; } int (*DH_meth_get_finish(const DH_METHOD *dhm)) (DH *) { return dhm->finish; } int DH_meth_set_finish(DH_METHOD *dhm, int (*finish) (DH *)) { dhm->finish = finish; return 1; } int (*DH_meth_get_generate_params(const DH_METHOD *dhm)) (DH *, int, int, BN_GENCB *) { return dhm->generate_params; } int DH_meth_set_generate_params(DH_METHOD *dhm, int (*generate_params) (DH *, int, int, BN_GENCB *)) { dhm->generate_params = generate_params; return 1; }
./openssl/crypto/dh/dh_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2023 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 <openssl/err.h> #include <openssl/dherr.h> #include "crypto/dherr.h" #ifndef OPENSSL_NO_DH # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA DH_str_reasons[] = { {ERR_PACK(ERR_LIB_DH, 0, DH_R_BAD_FFC_PARAMETERS), "bad ffc parameters"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR), "bad generator"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_BN_DECODE_ERROR), "bn decode error"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_BN_ERROR), "bn error"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_INVALID_J_VALUE), "check invalid j value"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_INVALID_Q_VALUE), "check invalid q value"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_PUBKEY_INVALID), "check pubkey invalid"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_PUBKEY_TOO_LARGE), "check pubkey too large"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_PUBKEY_TOO_SMALL), "check pubkey too small"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_P_NOT_PRIME), "check p not prime"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_P_NOT_SAFE_PRIME), "check p not safe prime"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_Q_NOT_PRIME), "check q not prime"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_DECODE_ERROR), "decode error"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_INVALID_PARAMETER_NAME), "invalid parameter name"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_INVALID_PARAMETER_NID), "invalid parameter nid"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_INVALID_PUBKEY), "invalid public key"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_INVALID_SECRET), "invalid secret"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_INVALID_SIZE), "invalid size"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_KDF_PARAMETER_ERROR), "kdf parameter error"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_KEYS_NOT_SET), "keys not set"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_MISSING_PUBKEY), "missing pubkey"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_MODULUS_TOO_LARGE), "modulus too large"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_MODULUS_TOO_SMALL), "modulus too small"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_NOT_SUITABLE_GENERATOR), "not suitable generator"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_NO_PARAMETERS_SET), "no parameters set"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_NO_PRIVATE_VALUE), "no private value"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_PARAMETER_ENCODING_ERROR), "parameter encoding error"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_PEER_KEY_ERROR), "peer key error"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_Q_TOO_LARGE), "q too large"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_SHARED_INFO_ERROR), "shared info error"}, {ERR_PACK(ERR_LIB_DH, 0, DH_R_UNABLE_TO_CHECK_GENERATOR), "unable to check generator"}, {0, NULL} }; # endif int ossl_err_load_DH_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(DH_str_reasons[0].error) == NULL) ERR_load_strings_const(DH_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
./openssl/crypto/dh/dh_kdf.c
/* * Copyright 2013-2022 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 */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "internal/e_os.h" #include <string.h> #include <openssl/core_names.h> #include <openssl/dh.h> #include <openssl/evp.h> #include <openssl/asn1.h> #include <openssl/kdf.h> #include "internal/provider.h" #include "crypto/dh.h" /* Key derivation function from X9.63/SECG */ int ossl_dh_kdf_X9_42_asn1(unsigned char *out, size_t outlen, const unsigned char *Z, size_t Zlen, const char *cek_alg, const unsigned char *ukm, size_t ukmlen, const EVP_MD *md, OSSL_LIB_CTX *libctx, const char *propq) { int ret = 0; EVP_KDF_CTX *kctx = NULL; EVP_KDF *kdf = NULL; OSSL_PARAM params[5], *p = params; const char *mdname = EVP_MD_get0_name(md); kdf = EVP_KDF_fetch(libctx, OSSL_KDF_NAME_X942KDF_ASN1, propq); if (kdf == NULL) return 0; kctx = EVP_KDF_CTX_new(kdf); if (kctx == NULL) goto err; *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, (char *)mdname, 0); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY, (unsigned char *)Z, Zlen); if (ukm != NULL) *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_UKM, (unsigned char *)ukm, ukmlen); *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_CEK_ALG, (char *)cek_alg, 0); *p = OSSL_PARAM_construct_end(); ret = EVP_KDF_derive(kctx, out, outlen, params) > 0; err: EVP_KDF_CTX_free(kctx); EVP_KDF_free(kdf); return ret; } #if !defined(FIPS_MODULE) int DH_KDF_X9_42(unsigned char *out, size_t outlen, const unsigned char *Z, size_t Zlen, ASN1_OBJECT *key_oid, const unsigned char *ukm, size_t ukmlen, const EVP_MD *md) { char key_alg[OSSL_MAX_NAME_SIZE]; const OSSL_PROVIDER *prov = EVP_MD_get0_provider(md); OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); if (OBJ_obj2txt(key_alg, sizeof(key_alg), key_oid, 0) <= 0) return 0; return ossl_dh_kdf_X9_42_asn1(out, outlen, Z, Zlen, key_alg, ukm, ukmlen, md, libctx, NULL); } #endif /* !defined(FIPS_MODULE) */
./openssl/crypto/dh/dh_prn.c
/* * Copyright 1995-2020 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 */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/dh.h> #ifndef OPENSSL_NO_STDIO int DHparams_print_fp(FILE *fp, const DH *x) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_DH, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = DHparams_print(b, x); BIO_free(b); return ret; } #endif
./openssl/crypto/dh/dh_group_params.c
/* * Copyright 2017-2022 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 */ /* DH parameters from RFC7919 and RFC3526 */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include "internal/ffc.h" #include "dh_local.h" #include <openssl/bn.h> #include <openssl/objects.h> #include "internal/nelem.h" #include "crypto/dh.h" static DH *dh_param_init(OSSL_LIB_CTX *libctx, const DH_NAMED_GROUP *group) { DH *dh = ossl_dh_new_ex(libctx); if (dh == NULL) return NULL; ossl_ffc_named_group_set(&dh->params, group); dh->params.nid = ossl_ffc_named_group_get_uid(group); dh->dirty_cnt++; return dh; } DH *ossl_dh_new_by_nid_ex(OSSL_LIB_CTX *libctx, int nid) { const DH_NAMED_GROUP *group; if ((group = ossl_ffc_uid_to_dh_named_group(nid)) != NULL) return dh_param_init(libctx, group); ERR_raise(ERR_LIB_DH, DH_R_INVALID_PARAMETER_NID); return NULL; } DH *DH_new_by_nid(int nid) { return ossl_dh_new_by_nid_ex(NULL, nid); } void ossl_dh_cache_named_group(DH *dh) { const DH_NAMED_GROUP *group; if (dh == NULL) return; dh->params.nid = NID_undef; /* flush cached value */ /* Exit if p or g is not set */ if (dh->params.p == NULL || dh->params.g == NULL) return; if ((group = ossl_ffc_numbers_to_dh_named_group(dh->params.p, dh->params.q, dh->params.g)) != NULL) { if (dh->params.q == NULL) dh->params.q = (BIGNUM *)ossl_ffc_named_group_get_q(group); /* cache the nid and default key length */ dh->params.nid = ossl_ffc_named_group_get_uid(group); dh->params.keylength = ossl_ffc_named_group_get_keylength(group); dh->dirty_cnt++; } } int ossl_dh_is_named_safe_prime_group(const DH *dh) { int id = DH_get_nid(dh); /* * Exclude RFC5114 groups (id = 1..3) since they do not have * q = (p - 1) / 2 */ return (id > 3); } int DH_get_nid(const DH *dh) { if (dh == NULL) return NID_undef; return dh->params.nid; }
./openssl/crypto/dh/dh_gen.c
/* * Copyright 1995-2021 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 */ /* * NB: These functions have been upgraded - the previous prototypes are in * dh_depr.c as wrappers to these ones. - Geoff */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. * * NOTE: When generating keys for key-agreement schemes - FIPS 140-2 IG 9.9 * states that no additional pairwise tests are required (apart from the tests * specified in SP800-56A) when generating keys. Hence DH pairwise tests are * omitted here. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/sha.h> #include "crypto/dh.h" #include "crypto/security_bits.h" #include "dh_local.h" #ifndef FIPS_MODULE static int dh_builtin_genparams(DH *ret, int prime_len, int generator, BN_GENCB *cb); #endif /* FIPS_MODULE */ int ossl_dh_generate_ffc_parameters(DH *dh, int type, int pbits, int qbits, BN_GENCB *cb) { int ret, res; #ifndef FIPS_MODULE if (type == DH_PARAMGEN_TYPE_FIPS_186_2) ret = ossl_ffc_params_FIPS186_2_generate(dh->libctx, &dh->params, FFC_PARAM_TYPE_DH, pbits, qbits, &res, cb); else #endif ret = ossl_ffc_params_FIPS186_4_generate(dh->libctx, &dh->params, FFC_PARAM_TYPE_DH, pbits, qbits, &res, cb); if (ret > 0) dh->dirty_cnt++; return ret; } int ossl_dh_get_named_group_uid_from_size(int pbits) { /* * Just choose an approved safe prime group. * The alternative to this is to generate FIPS186-4 domain parameters i.e. * return dh_generate_ffc_parameters(ret, prime_len, 0, NULL, cb); * As the FIPS186-4 generated params are for backwards compatibility, * the safe prime group should be used as the default. */ int nid; switch (pbits) { case 2048: nid = NID_ffdhe2048; break; case 3072: nid = NID_ffdhe3072; break; case 4096: nid = NID_ffdhe4096; break; case 6144: nid = NID_ffdhe6144; break; case 8192: nid = NID_ffdhe8192; break; /* unsupported prime_len */ default: return NID_undef; } return nid; } #ifdef FIPS_MODULE static int dh_gen_named_group(OSSL_LIB_CTX *libctx, DH *ret, int prime_len) { DH *dh; int ok = 0; int nid = ossl_dh_get_named_group_uid_from_size(prime_len); if (nid == NID_undef) return 0; dh = ossl_dh_new_by_nid_ex(libctx, nid); if (dh != NULL && ossl_ffc_params_copy(&ret->params, &dh->params)) { ok = 1; ret->dirty_cnt++; } DH_free(dh); return ok; } #endif /* FIPS_MODULE */ int DH_generate_parameters_ex(DH *ret, int prime_len, int generator, BN_GENCB *cb) { #ifdef FIPS_MODULE if (generator != 2) return 0; return dh_gen_named_group(ret->libctx, ret, prime_len); #else if (ret->meth->generate_params) return ret->meth->generate_params(ret, prime_len, generator, cb); return dh_builtin_genparams(ret, prime_len, generator, cb); #endif /* FIPS_MODULE */ } #ifndef FIPS_MODULE /*- * We generate DH parameters as follows * find a prime p which is prime_len bits long, * where q=(p-1)/2 is also prime. * In the following we assume that g is not 0, 1 or p-1, since it * would generate only trivial subgroups. * For this case, g is a generator of the order-q subgroup if * g^q mod p == 1. * Or in terms of the Legendre symbol: (g/p) == 1. * * Having said all that, * there is another special case method for the generators 2, 3 and 5. * Using the quadratic reciprocity law it is possible to solve * (g/p) == 1 for the special values 2, 3, 5: * (2/p) == 1 if p mod 8 == 1 or 7. * (3/p) == 1 if p mod 12 == 1 or 11. * (5/p) == 1 if p mod 5 == 1 or 4. * See for instance: https://en.wikipedia.org/wiki/Legendre_symbol * * Since all safe primes > 7 must satisfy p mod 12 == 11 * and all safe primes > 11 must satisfy p mod 5 != 1 * we can further improve the condition for g = 2, 3 and 5: * for 2, p mod 24 == 23 * for 3, p mod 12 == 11 * for 5, p mod 60 == 59 */ static int dh_builtin_genparams(DH *ret, int prime_len, int generator, BN_GENCB *cb) { BIGNUM *t1, *t2; int g, ok = -1; BN_CTX *ctx = NULL; if (prime_len > OPENSSL_DH_MAX_MODULUS_BITS) { ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_LARGE); return 0; } if (prime_len < DH_MIN_MODULUS_BITS) { ERR_raise(ERR_LIB_DH, DH_R_MODULUS_TOO_SMALL); return 0; } ctx = BN_CTX_new_ex(ret->libctx); if (ctx == NULL) goto err; BN_CTX_start(ctx); t1 = BN_CTX_get(ctx); t2 = BN_CTX_get(ctx); if (t2 == NULL) goto err; /* Make sure 'ret' has the necessary elements */ if (ret->params.p == NULL && ((ret->params.p = BN_new()) == NULL)) goto err; if (ret->params.g == NULL && ((ret->params.g = BN_new()) == NULL)) goto err; if (generator <= 1) { ERR_raise(ERR_LIB_DH, DH_R_BAD_GENERATOR); goto err; } if (generator == DH_GENERATOR_2) { if (!BN_set_word(t1, 24)) goto err; if (!BN_set_word(t2, 23)) goto err; g = 2; } else if (generator == DH_GENERATOR_5) { if (!BN_set_word(t1, 60)) goto err; if (!BN_set_word(t2, 59)) goto err; g = 5; } else { /* * in the general case, don't worry if 'generator' is a generator or * not: since we are using safe primes, it will generate either an * order-q or an order-2q group, which both is OK */ if (!BN_set_word(t1, 12)) goto err; if (!BN_set_word(t2, 11)) goto err; g = generator; } if (!BN_generate_prime_ex2(ret->params.p, prime_len, 1, t1, t2, cb, ctx)) goto err; if (!BN_GENCB_call(cb, 3, 0)) goto err; if (!BN_set_word(ret->params.g, g)) goto err; /* We are using safe prime p, set key length equivalent to RFC 7919 */ ret->length = (2 * ossl_ifc_ffc_compute_security_bits(prime_len) + 24) / 25 * 25; ret->dirty_cnt++; ok = 1; err: if (ok == -1) { ERR_raise(ERR_LIB_DH, ERR_R_BN_LIB); ok = 0; } BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; } #endif /* FIPS_MODULE */
./openssl/crypto/dh/dh_ameth.c
/* * Copyright 2006-2022 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 */ /* * DH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <openssl/x509.h> #include <openssl/asn1.h> #include <openssl/bn.h> #include <openssl/core_names.h> #include <openssl/param_build.h> #include "internal/ffc.h" #include "internal/cryptlib.h" #include "crypto/asn1.h" #include "crypto/dh.h" #include "crypto/evp.h" #include "dh_local.h" /* * i2d/d2i like DH parameter functions which use the appropriate routine for * PKCS#3 DH or X9.42 DH. */ static DH *d2i_dhp(const EVP_PKEY *pkey, const unsigned char **pp, long length) { DH *dh = NULL; int is_dhx = (pkey->ameth == &ossl_dhx_asn1_meth); if (is_dhx) dh = d2i_DHxparams(NULL, pp, length); else dh = d2i_DHparams(NULL, pp, length); return dh; } static int i2d_dhp(const EVP_PKEY *pkey, const DH *a, unsigned char **pp) { if (pkey->ameth == &ossl_dhx_asn1_meth) return i2d_DHxparams(a, pp); return i2d_DHparams(a, pp); } static void int_dh_free(EVP_PKEY *pkey) { DH_free(pkey->pkey.dh); } static int dh_pub_decode(EVP_PKEY *pkey, const X509_PUBKEY *pubkey) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; const void *pval; const ASN1_STRING *pstr; X509_ALGOR *palg; ASN1_INTEGER *public_key = NULL; DH *dh = NULL; if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if (ptype != V_ASN1_SEQUENCE) { ERR_raise(ERR_LIB_DH, DH_R_PARAMETER_ENCODING_ERROR); goto err; } pstr = pval; pm = pstr->data; pmlen = pstr->length; if ((dh = d2i_dhp(pkey, &pm, pmlen)) == NULL) { ERR_raise(ERR_LIB_DH, DH_R_DECODE_ERROR); goto err; } if ((public_key = d2i_ASN1_INTEGER(NULL, &p, pklen)) == NULL) { ERR_raise(ERR_LIB_DH, DH_R_DECODE_ERROR); goto err; } /* We have parameters now set public key */ if ((dh->pub_key = ASN1_INTEGER_to_BN(public_key, NULL)) == NULL) { ERR_raise(ERR_LIB_DH, DH_R_BN_DECODE_ERROR); goto err; } ASN1_INTEGER_free(public_key); EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, dh); return 1; err: ASN1_INTEGER_free(public_key); DH_free(dh); return 0; } static int dh_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) { DH *dh; int ptype; unsigned char *penc = NULL; int penclen; ASN1_STRING *str; ASN1_INTEGER *pub_key = NULL; dh = pkey->pkey.dh; str = ASN1_STRING_new(); if (str == NULL) { ERR_raise(ERR_LIB_DH, ERR_R_ASN1_LIB); goto err; } str->length = i2d_dhp(pkey, dh, &str->data); if (str->length <= 0) { ERR_raise(ERR_LIB_DH, ERR_R_ASN1_LIB); goto err; } ptype = V_ASN1_SEQUENCE; pub_key = BN_to_ASN1_INTEGER(dh->pub_key, NULL); if (pub_key == NULL) goto err; penclen = i2d_ASN1_INTEGER(pub_key, &penc); ASN1_INTEGER_free(pub_key); if (penclen <= 0) { ERR_raise(ERR_LIB_DH, ERR_R_ASN1_LIB); goto err; } if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(pkey->ameth->pkey_id), ptype, str, penc, penclen)) return 1; err: OPENSSL_free(penc); ASN1_STRING_free(str); return 0; } /* * PKCS#8 DH is defined in PKCS#11 of all places. It is similar to DH in that * the AlgorithmIdentifier contains the parameters, the private key is * explicitly included and the pubkey must be recalculated. */ static int dh_priv_decode(EVP_PKEY *pkey, const PKCS8_PRIV_KEY_INFO *p8) { int ret = 0; DH *dh = ossl_dh_key_from_pkcs8(p8, NULL, NULL); if (dh != NULL) { ret = 1; EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, dh); } return ret; } static int dh_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey) { ASN1_STRING *params = NULL; ASN1_INTEGER *prkey = NULL; unsigned char *dp = NULL; int dplen; params = ASN1_STRING_new(); if (params == NULL) { ERR_raise(ERR_LIB_DH, ERR_R_ASN1_LIB); goto err; } params->length = i2d_dhp(pkey, pkey->pkey.dh, &params->data); if (params->length <= 0) { ERR_raise(ERR_LIB_DH, ERR_R_ASN1_LIB); goto err; } params->type = V_ASN1_SEQUENCE; /* Get private key into integer */ prkey = BN_to_ASN1_INTEGER(pkey->pkey.dh->priv_key, NULL); if (prkey == NULL) { ERR_raise(ERR_LIB_DH, DH_R_BN_ERROR); goto err; } dplen = i2d_ASN1_INTEGER(prkey, &dp); ASN1_STRING_clear_free(prkey); if (dplen <= 0) { ERR_raise(ERR_LIB_DH, DH_R_BN_ERROR); goto err; } if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(pkey->ameth->pkey_id), 0, V_ASN1_SEQUENCE, params, dp, dplen)) { OPENSSL_clear_free(dp, dplen); goto err; } return 1; err: ASN1_STRING_free(params); return 0; } static int dh_param_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { DH *dh; if ((dh = d2i_dhp(pkey, pder, derlen)) == NULL) return 0; dh->dirty_cnt++; EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, dh); return 1; } static int dh_param_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_dhp(pkey, pkey->pkey.dh, pder); } static int do_dh_print(BIO *bp, const DH *x, int indent, int ptype) { int reason = ERR_R_BUF_LIB; const char *ktype = NULL; BIGNUM *priv_key, *pub_key; if (ptype == 2) priv_key = x->priv_key; else priv_key = NULL; if (ptype > 0) pub_key = x->pub_key; else pub_key = NULL; if (x->params.p == NULL || (ptype == 2 && priv_key == NULL) || (ptype > 0 && pub_key == NULL)) { reason = ERR_R_PASSED_NULL_PARAMETER; goto err; } if (ptype == 2) ktype = "DH Private-Key"; else if (ptype == 1) ktype = "DH Public-Key"; else ktype = "DH Parameters"; if (!BIO_indent(bp, indent, 128) || BIO_printf(bp, "%s: (%d bit)\n", ktype, DH_bits(x)) <= 0) goto err; indent += 4; if (!ASN1_bn_print(bp, "private-key:", priv_key, NULL, indent)) goto err; if (!ASN1_bn_print(bp, "public-key:", pub_key, NULL, indent)) goto err; if (!ossl_ffc_params_print(bp, &x->params, indent)) goto err; if (x->length != 0) { if (!BIO_indent(bp, indent, 128) || BIO_printf(bp, "recommended-private-length: %d bits\n", (int)x->length) <= 0) goto err; } return 1; err: ERR_raise(ERR_LIB_DH, reason); return 0; } static int int_dh_size(const EVP_PKEY *pkey) { return DH_size(pkey->pkey.dh); } static int dh_bits(const EVP_PKEY *pkey) { return DH_bits(pkey->pkey.dh); } static int dh_security_bits(const EVP_PKEY *pkey) { return DH_security_bits(pkey->pkey.dh); } static int dh_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { return ossl_ffc_params_cmp(&a->pkey.dh->params, &b->pkey.dh->params, a->ameth != &ossl_dhx_asn1_meth); } static int int_dh_param_copy(DH *to, const DH *from, int is_x942) { if (is_x942 == -1) is_x942 = (from->params.q != NULL); if (!ossl_ffc_params_copy(&to->params, &from->params)) return 0; if (!is_x942) to->length = from->length; to->dirty_cnt++; return 1; } DH *DHparams_dup(const DH *dh) { DH *ret; ret = DH_new(); if (ret == NULL) return NULL; if (!int_dh_param_copy(ret, dh, -1)) { DH_free(ret); return NULL; } return ret; } static int dh_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) { if (to->pkey.dh == NULL) { to->pkey.dh = DH_new(); if (to->pkey.dh == NULL) return 0; } return int_dh_param_copy(to->pkey.dh, from->pkey.dh, from->ameth == &ossl_dhx_asn1_meth); } static int dh_missing_parameters(const EVP_PKEY *a) { return a->pkey.dh == NULL || a->pkey.dh->params.p == NULL || a->pkey.dh->params.g == NULL; } static int dh_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { if (dh_cmp_parameters(a, b) == 0) return 0; if (BN_cmp(b->pkey.dh->pub_key, a->pkey.dh->pub_key) != 0) return 0; else return 1; } static int dh_param_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dh_print(bp, pkey->pkey.dh, indent, 0); } static int dh_public_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dh_print(bp, pkey->pkey.dh, indent, 1); } static int dh_private_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dh_print(bp, pkey->pkey.dh, indent, 2); } int DHparams_print(BIO *bp, const DH *x) { return do_dh_print(bp, x, 4, 0); } static int dh_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) { DH *dh; switch (op) { case ASN1_PKEY_CTRL_SET1_TLS_ENCPT: /* We should only be here if we have a legacy key */ if (!ossl_assert(evp_pkey_is_legacy(pkey))) return 0; dh = (DH *) evp_pkey_get0_DH_int(pkey); if (dh == NULL) return 0; return ossl_dh_buf2key(dh, arg2, arg1); case ASN1_PKEY_CTRL_GET1_TLS_ENCPT: dh = (DH *) EVP_PKEY_get0_DH(pkey); if (dh == NULL) return 0; return ossl_dh_key2buf(dh, arg2, 0, 1); default: return -2; } } static int dhx_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) { switch (op) { default: return -2; } } static int dh_pkey_public_check(const EVP_PKEY *pkey) { DH *dh = pkey->pkey.dh; if (dh->pub_key == NULL) { ERR_raise(ERR_LIB_DH, DH_R_MISSING_PUBKEY); return 0; } return DH_check_pub_key_ex(dh, dh->pub_key); } static int dh_pkey_param_check(const EVP_PKEY *pkey) { DH *dh = pkey->pkey.dh; return DH_check_ex(dh); } static size_t dh_pkey_dirty_cnt(const EVP_PKEY *pkey) { return pkey->pkey.dh->dirty_cnt; } static int dh_pkey_export_to(const EVP_PKEY *from, void *to_keydata, OSSL_FUNC_keymgmt_import_fn *importer, OSSL_LIB_CTX *libctx, const char *propq) { DH *dh = from->pkey.dh; OSSL_PARAM_BLD *tmpl; const BIGNUM *p = DH_get0_p(dh), *g = DH_get0_g(dh), *q = DH_get0_q(dh); long l = DH_get_length(dh); const BIGNUM *pub_key = DH_get0_pub_key(dh); const BIGNUM *priv_key = DH_get0_priv_key(dh); OSSL_PARAM *params = NULL; int selection = 0; int rv = 0; if (p == NULL || g == NULL) return 0; tmpl = OSSL_PARAM_BLD_new(); if (tmpl == NULL) return 0; if (!OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)) goto err; if (q != NULL) { if (!OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_Q, q)) goto err; } selection |= OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS; if (l > 0) { if (!OSSL_PARAM_BLD_push_long(tmpl, OSSL_PKEY_PARAM_DH_PRIV_LEN, l)) goto err; selection |= OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS; } if (pub_key != NULL) { if (!OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PUB_KEY, pub_key)) goto err; selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY; } if (priv_key != NULL) { if (!OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PRIV_KEY, priv_key)) goto err; selection |= OSSL_KEYMGMT_SELECT_PRIVATE_KEY; } if ((params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) goto err; /* We export, the provider imports */ rv = importer(to_keydata, selection, params); OSSL_PARAM_free(params); err: OSSL_PARAM_BLD_free(tmpl); return rv; } static int dh_pkey_import_from_type(const OSSL_PARAM params[], void *vpctx, int type) { EVP_PKEY_CTX *pctx = vpctx; EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pctx); DH *dh = ossl_dh_new_ex(pctx->libctx); if (dh == NULL) { ERR_raise(ERR_LIB_DH, ERR_R_DH_LIB); return 0; } DH_clear_flags(dh, DH_FLAG_TYPE_MASK); DH_set_flags(dh, type == EVP_PKEY_DH ? DH_FLAG_TYPE_DH : DH_FLAG_TYPE_DHX); if (!ossl_dh_params_fromdata(dh, params) || !ossl_dh_key_fromdata(dh, params, 1) || !EVP_PKEY_assign(pkey, type, dh)) { DH_free(dh); return 0; } return 1; } static int dh_pkey_import_from(const OSSL_PARAM params[], void *vpctx) { return dh_pkey_import_from_type(params, vpctx, EVP_PKEY_DH); } static int dhx_pkey_import_from(const OSSL_PARAM params[], void *vpctx) { return dh_pkey_import_from_type(params, vpctx, EVP_PKEY_DHX); } static int dh_pkey_copy(EVP_PKEY *to, EVP_PKEY *from) { DH *dh = from->pkey.dh; DH *dupkey = NULL; int ret; if (dh != NULL) { dupkey = ossl_dh_dup(dh, OSSL_KEYMGMT_SELECT_ALL); if (dupkey == NULL) return 0; } ret = EVP_PKEY_assign(to, from->type, dupkey); if (!ret) DH_free(dupkey); return ret; } const EVP_PKEY_ASN1_METHOD ossl_dh_asn1_meth = { EVP_PKEY_DH, EVP_PKEY_DH, 0, "DH", "OpenSSL PKCS#3 DH method", dh_pub_decode, dh_pub_encode, dh_pub_cmp, dh_public_print, dh_priv_decode, dh_priv_encode, dh_private_print, int_dh_size, dh_bits, dh_security_bits, dh_param_decode, dh_param_encode, dh_missing_parameters, dh_copy_parameters, dh_cmp_parameters, dh_param_print, 0, int_dh_free, dh_pkey_ctrl, 0, 0, 0, 0, 0, 0, dh_pkey_public_check, dh_pkey_param_check, 0, 0, 0, 0, dh_pkey_dirty_cnt, dh_pkey_export_to, dh_pkey_import_from, dh_pkey_copy }; const EVP_PKEY_ASN1_METHOD ossl_dhx_asn1_meth = { EVP_PKEY_DHX, EVP_PKEY_DHX, 0, "X9.42 DH", "OpenSSL X9.42 DH method", dh_pub_decode, dh_pub_encode, dh_pub_cmp, dh_public_print, dh_priv_decode, dh_priv_encode, dh_private_print, int_dh_size, dh_bits, dh_security_bits, dh_param_decode, dh_param_encode, dh_missing_parameters, dh_copy_parameters, dh_cmp_parameters, dh_param_print, 0, int_dh_free, dhx_pkey_ctrl, 0, 0, 0, 0, 0, 0, dh_pkey_public_check, dh_pkey_param_check, 0, 0, 0, 0, dh_pkey_dirty_cnt, dh_pkey_export_to, dhx_pkey_import_from, dh_pkey_copy };
./openssl/crypto/sm3/legacy_sm3.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. 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 "crypto/evp.h" #include "../evp/legacy_meth.h" #include "internal/sm3.h" IMPLEMENT_LEGACY_EVP_MD_METH_LC(sm3_int, ossl_sm3) static const EVP_MD sm3_md = { NID_sm3, NID_sm3WithRSAEncryption, SM3_DIGEST_LENGTH, 0, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(sm3_int_init, sm3_int_update, sm3_int_final, NULL, SM3_CBLOCK), }; const EVP_MD *EVP_sm3(void) { return &sm3_md; }
./openssl/crypto/sm3/sm3.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * Ported from Ribose contributions from Botan. * * 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 <openssl/e_os2.h> #include "sm3_local.h" int ossl_sm3_init(SM3_CTX *c) { memset(c, 0, sizeof(*c)); c->A = SM3_A; c->B = SM3_B; c->C = SM3_C; c->D = SM3_D; c->E = SM3_E; c->F = SM3_F; c->G = SM3_G; c->H = SM3_H; return 1; } void ossl_sm3_block_data_order(SM3_CTX *ctx, const void *p, size_t num) { const unsigned char *data = p; register unsigned MD32_REG_T A, B, C, D, E, F, G, H; unsigned MD32_REG_T W00, W01, W02, W03, W04, W05, W06, W07, W08, W09, W10, W11, W12, W13, W14, W15; for (; num--;) { A = ctx->A; B = ctx->B; C = ctx->C; D = ctx->D; E = ctx->E; F = ctx->F; G = ctx->G; H = ctx->H; /* * We have to load all message bytes immediately since SM3 reads * them slightly out of order. */ (void)HOST_c2l(data, W00); (void)HOST_c2l(data, W01); (void)HOST_c2l(data, W02); (void)HOST_c2l(data, W03); (void)HOST_c2l(data, W04); (void)HOST_c2l(data, W05); (void)HOST_c2l(data, W06); (void)HOST_c2l(data, W07); (void)HOST_c2l(data, W08); (void)HOST_c2l(data, W09); (void)HOST_c2l(data, W10); (void)HOST_c2l(data, W11); (void)HOST_c2l(data, W12); (void)HOST_c2l(data, W13); (void)HOST_c2l(data, W14); (void)HOST_c2l(data, W15); R1(A, B, C, D, E, F, G, H, 0x79CC4519, W00, W00 ^ W04); W00 = EXPAND(W00, W07, W13, W03, W10); R1(D, A, B, C, H, E, F, G, 0xF3988A32, W01, W01 ^ W05); W01 = EXPAND(W01, W08, W14, W04, W11); R1(C, D, A, B, G, H, E, F, 0xE7311465, W02, W02 ^ W06); W02 = EXPAND(W02, W09, W15, W05, W12); R1(B, C, D, A, F, G, H, E, 0xCE6228CB, W03, W03 ^ W07); W03 = EXPAND(W03, W10, W00, W06, W13); R1(A, B, C, D, E, F, G, H, 0x9CC45197, W04, W04 ^ W08); W04 = EXPAND(W04, W11, W01, W07, W14); R1(D, A, B, C, H, E, F, G, 0x3988A32F, W05, W05 ^ W09); W05 = EXPAND(W05, W12, W02, W08, W15); R1(C, D, A, B, G, H, E, F, 0x7311465E, W06, W06 ^ W10); W06 = EXPAND(W06, W13, W03, W09, W00); R1(B, C, D, A, F, G, H, E, 0xE6228CBC, W07, W07 ^ W11); W07 = EXPAND(W07, W14, W04, W10, W01); R1(A, B, C, D, E, F, G, H, 0xCC451979, W08, W08 ^ W12); W08 = EXPAND(W08, W15, W05, W11, W02); R1(D, A, B, C, H, E, F, G, 0x988A32F3, W09, W09 ^ W13); W09 = EXPAND(W09, W00, W06, W12, W03); R1(C, D, A, B, G, H, E, F, 0x311465E7, W10, W10 ^ W14); W10 = EXPAND(W10, W01, W07, W13, W04); R1(B, C, D, A, F, G, H, E, 0x6228CBCE, W11, W11 ^ W15); W11 = EXPAND(W11, W02, W08, W14, W05); R1(A, B, C, D, E, F, G, H, 0xC451979C, W12, W12 ^ W00); W12 = EXPAND(W12, W03, W09, W15, W06); R1(D, A, B, C, H, E, F, G, 0x88A32F39, W13, W13 ^ W01); W13 = EXPAND(W13, W04, W10, W00, W07); R1(C, D, A, B, G, H, E, F, 0x11465E73, W14, W14 ^ W02); W14 = EXPAND(W14, W05, W11, W01, W08); R1(B, C, D, A, F, G, H, E, 0x228CBCE6, W15, W15 ^ W03); W15 = EXPAND(W15, W06, W12, W02, W09); R2(A, B, C, D, E, F, G, H, 0x9D8A7A87, W00, W00 ^ W04); W00 = EXPAND(W00, W07, W13, W03, W10); R2(D, A, B, C, H, E, F, G, 0x3B14F50F, W01, W01 ^ W05); W01 = EXPAND(W01, W08, W14, W04, W11); R2(C, D, A, B, G, H, E, F, 0x7629EA1E, W02, W02 ^ W06); W02 = EXPAND(W02, W09, W15, W05, W12); R2(B, C, D, A, F, G, H, E, 0xEC53D43C, W03, W03 ^ W07); W03 = EXPAND(W03, W10, W00, W06, W13); R2(A, B, C, D, E, F, G, H, 0xD8A7A879, W04, W04 ^ W08); W04 = EXPAND(W04, W11, W01, W07, W14); R2(D, A, B, C, H, E, F, G, 0xB14F50F3, W05, W05 ^ W09); W05 = EXPAND(W05, W12, W02, W08, W15); R2(C, D, A, B, G, H, E, F, 0x629EA1E7, W06, W06 ^ W10); W06 = EXPAND(W06, W13, W03, W09, W00); R2(B, C, D, A, F, G, H, E, 0xC53D43CE, W07, W07 ^ W11); W07 = EXPAND(W07, W14, W04, W10, W01); R2(A, B, C, D, E, F, G, H, 0x8A7A879D, W08, W08 ^ W12); W08 = EXPAND(W08, W15, W05, W11, W02); R2(D, A, B, C, H, E, F, G, 0x14F50F3B, W09, W09 ^ W13); W09 = EXPAND(W09, W00, W06, W12, W03); R2(C, D, A, B, G, H, E, F, 0x29EA1E76, W10, W10 ^ W14); W10 = EXPAND(W10, W01, W07, W13, W04); R2(B, C, D, A, F, G, H, E, 0x53D43CEC, W11, W11 ^ W15); W11 = EXPAND(W11, W02, W08, W14, W05); R2(A, B, C, D, E, F, G, H, 0xA7A879D8, W12, W12 ^ W00); W12 = EXPAND(W12, W03, W09, W15, W06); R2(D, A, B, C, H, E, F, G, 0x4F50F3B1, W13, W13 ^ W01); W13 = EXPAND(W13, W04, W10, W00, W07); R2(C, D, A, B, G, H, E, F, 0x9EA1E762, W14, W14 ^ W02); W14 = EXPAND(W14, W05, W11, W01, W08); R2(B, C, D, A, F, G, H, E, 0x3D43CEC5, W15, W15 ^ W03); W15 = EXPAND(W15, W06, W12, W02, W09); R2(A, B, C, D, E, F, G, H, 0x7A879D8A, W00, W00 ^ W04); W00 = EXPAND(W00, W07, W13, W03, W10); R2(D, A, B, C, H, E, F, G, 0xF50F3B14, W01, W01 ^ W05); W01 = EXPAND(W01, W08, W14, W04, W11); R2(C, D, A, B, G, H, E, F, 0xEA1E7629, W02, W02 ^ W06); W02 = EXPAND(W02, W09, W15, W05, W12); R2(B, C, D, A, F, G, H, E, 0xD43CEC53, W03, W03 ^ W07); W03 = EXPAND(W03, W10, W00, W06, W13); R2(A, B, C, D, E, F, G, H, 0xA879D8A7, W04, W04 ^ W08); W04 = EXPAND(W04, W11, W01, W07, W14); R2(D, A, B, C, H, E, F, G, 0x50F3B14F, W05, W05 ^ W09); W05 = EXPAND(W05, W12, W02, W08, W15); R2(C, D, A, B, G, H, E, F, 0xA1E7629E, W06, W06 ^ W10); W06 = EXPAND(W06, W13, W03, W09, W00); R2(B, C, D, A, F, G, H, E, 0x43CEC53D, W07, W07 ^ W11); W07 = EXPAND(W07, W14, W04, W10, W01); R2(A, B, C, D, E, F, G, H, 0x879D8A7A, W08, W08 ^ W12); W08 = EXPAND(W08, W15, W05, W11, W02); R2(D, A, B, C, H, E, F, G, 0x0F3B14F5, W09, W09 ^ W13); W09 = EXPAND(W09, W00, W06, W12, W03); R2(C, D, A, B, G, H, E, F, 0x1E7629EA, W10, W10 ^ W14); W10 = EXPAND(W10, W01, W07, W13, W04); R2(B, C, D, A, F, G, H, E, 0x3CEC53D4, W11, W11 ^ W15); W11 = EXPAND(W11, W02, W08, W14, W05); R2(A, B, C, D, E, F, G, H, 0x79D8A7A8, W12, W12 ^ W00); W12 = EXPAND(W12, W03, W09, W15, W06); R2(D, A, B, C, H, E, F, G, 0xF3B14F50, W13, W13 ^ W01); W13 = EXPAND(W13, W04, W10, W00, W07); R2(C, D, A, B, G, H, E, F, 0xE7629EA1, W14, W14 ^ W02); W14 = EXPAND(W14, W05, W11, W01, W08); R2(B, C, D, A, F, G, H, E, 0xCEC53D43, W15, W15 ^ W03); W15 = EXPAND(W15, W06, W12, W02, W09); R2(A, B, C, D, E, F, G, H, 0x9D8A7A87, W00, W00 ^ W04); W00 = EXPAND(W00, W07, W13, W03, W10); R2(D, A, B, C, H, E, F, G, 0x3B14F50F, W01, W01 ^ W05); W01 = EXPAND(W01, W08, W14, W04, W11); R2(C, D, A, B, G, H, E, F, 0x7629EA1E, W02, W02 ^ W06); W02 = EXPAND(W02, W09, W15, W05, W12); R2(B, C, D, A, F, G, H, E, 0xEC53D43C, W03, W03 ^ W07); W03 = EXPAND(W03, W10, W00, W06, W13); R2(A, B, C, D, E, F, G, H, 0xD8A7A879, W04, W04 ^ W08); R2(D, A, B, C, H, E, F, G, 0xB14F50F3, W05, W05 ^ W09); R2(C, D, A, B, G, H, E, F, 0x629EA1E7, W06, W06 ^ W10); R2(B, C, D, A, F, G, H, E, 0xC53D43CE, W07, W07 ^ W11); R2(A, B, C, D, E, F, G, H, 0x8A7A879D, W08, W08 ^ W12); R2(D, A, B, C, H, E, F, G, 0x14F50F3B, W09, W09 ^ W13); R2(C, D, A, B, G, H, E, F, 0x29EA1E76, W10, W10 ^ W14); R2(B, C, D, A, F, G, H, E, 0x53D43CEC, W11, W11 ^ W15); R2(A, B, C, D, E, F, G, H, 0xA7A879D8, W12, W12 ^ W00); R2(D, A, B, C, H, E, F, G, 0x4F50F3B1, W13, W13 ^ W01); R2(C, D, A, B, G, H, E, F, 0x9EA1E762, W14, W14 ^ W02); R2(B, C, D, A, F, G, H, E, 0x3D43CEC5, W15, W15 ^ W03); ctx->A ^= A; ctx->B ^= B; ctx->C ^= C; ctx->D ^= D; ctx->E ^= E; ctx->F ^= F; ctx->G ^= G; ctx->H ^= H; } }
./openssl/crypto/sm3/sm3_local.h
/* * Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * Ported from Ribose contributions from Botan. * * 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 <string.h> #include "internal/sm3.h" #define DATA_ORDER_IS_BIG_ENDIAN #define HASH_LONG SM3_WORD #define HASH_CTX SM3_CTX #define HASH_CBLOCK SM3_CBLOCK #define HASH_UPDATE ossl_sm3_update #define HASH_TRANSFORM ossl_sm3_transform #define HASH_FINAL ossl_sm3_final #define HASH_MAKE_STRING(c, s) \ do { \ unsigned long ll; \ ll=(c)->A; (void)HOST_l2c(ll, (s)); \ ll=(c)->B; (void)HOST_l2c(ll, (s)); \ ll=(c)->C; (void)HOST_l2c(ll, (s)); \ ll=(c)->D; (void)HOST_l2c(ll, (s)); \ ll=(c)->E; (void)HOST_l2c(ll, (s)); \ ll=(c)->F; (void)HOST_l2c(ll, (s)); \ ll=(c)->G; (void)HOST_l2c(ll, (s)); \ ll=(c)->H; (void)HOST_l2c(ll, (s)); \ } while (0) #if defined(OPENSSL_SM3_ASM) # if defined(__aarch64__) || defined(_M_ARM64) # include "crypto/arm_arch.h" # define HWSM3_CAPABLE (OPENSSL_armcap_P & ARMV8_SM3) void ossl_hwsm3_block_data_order(SM3_CTX *c, const void *p, size_t num); # endif # if defined(__riscv) && __riscv_xlen == 64 # include "crypto/riscv_arch.h" # define HWSM3_CAPABLE 1 void ossl_hwsm3_block_data_order(SM3_CTX *c, const void *p, size_t num); # endif #endif #if defined(HWSM3_CAPABLE) # define HASH_BLOCK_DATA_ORDER (HWSM3_CAPABLE ? ossl_hwsm3_block_data_order \ : ossl_sm3_block_data_order) #else # define HASH_BLOCK_DATA_ORDER ossl_sm3_block_data_order #endif void ossl_sm3_block_data_order(SM3_CTX *c, const void *p, size_t num); void ossl_sm3_transform(SM3_CTX *c, const unsigned char *data); #include "crypto/md32_common.h" #ifndef PEDANTIC # if defined(__GNUC__) && __GNUC__>=2 && \ !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) # if defined(__riscv_zksh) # define P0(x) ({ MD32_REG_T ret; \ asm ("sm3p0 %0, %1" \ : "=r"(ret) \ : "r"(x)); ret; }) # define P1(x) ({ MD32_REG_T ret; \ asm ("sm3p1 %0, %1" \ : "=r"(ret) \ : "r"(x)); ret; }) # endif # endif #endif #ifndef P0 # define P0(X) (X ^ ROTATE(X, 9) ^ ROTATE(X, 17)) #endif #ifndef P1 # define P1(X) (X ^ ROTATE(X, 15) ^ ROTATE(X, 23)) #endif #define FF0(X,Y,Z) (X ^ Y ^ Z) #define GG0(X,Y,Z) (X ^ Y ^ Z) #define FF1(X,Y,Z) ((X & Y) | ((X | Y) & Z)) #define GG1(X,Y,Z) ((Z ^ (X & (Y ^ Z)))) #define EXPAND(W0,W7,W13,W3,W10) \ (P1(W0 ^ W7 ^ ROTATE(W13, 15)) ^ ROTATE(W3, 7) ^ W10) #define RND(A, B, C, D, E, F, G, H, TJ, Wi, Wj, FF, GG) \ do { \ const SM3_WORD A12 = ROTATE(A, 12); \ const SM3_WORD A12_SM = A12 + E + TJ; \ const SM3_WORD SS1 = ROTATE(A12_SM, 7); \ const SM3_WORD TT1 = FF(A, B, C) + D + (SS1 ^ A12) + (Wj); \ const SM3_WORD TT2 = GG(E, F, G) + H + SS1 + Wi; \ B = ROTATE(B, 9); \ D = TT1; \ F = ROTATE(F, 19); \ H = P0(TT2); \ } while(0) #define R1(A,B,C,D,E,F,G,H,TJ,Wi,Wj) \ RND(A,B,C,D,E,F,G,H,TJ,Wi,Wj,FF0,GG0) #define R2(A,B,C,D,E,F,G,H,TJ,Wi,Wj) \ RND(A,B,C,D,E,F,G,H,TJ,Wi,Wj,FF1,GG1) #define SM3_A 0x7380166fUL #define SM3_B 0x4914b2b9UL #define SM3_C 0x172442d7UL #define SM3_D 0xda8a0600UL #define SM3_E 0xa96f30bcUL #define SM3_F 0x163138aaUL #define SM3_G 0xe38dee4dUL #define SM3_H 0xb0fb0e4eUL
./openssl/crypto/sm3/sm3_riscv.c
/* * Copyright 2023 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 <string.h> #include <openssl/opensslconf.h> #include "internal/sm3.h" #include "crypto/riscv_arch.h" #include <stdio.h> void ossl_hwsm3_block_data_order_zvksh(SM3_CTX *c, const void *p, size_t num); void ossl_sm3_block_data_order(SM3_CTX *c, const void *p, size_t num); void ossl_hwsm3_block_data_order(SM3_CTX *c, const void *p, size_t num); void ossl_hwsm3_block_data_order(SM3_CTX *c, const void *p, size_t num) { if (RISCV_HAS_ZVKB_AND_ZVKSH() && riscv_vlen() >= 128) { ossl_hwsm3_block_data_order_zvksh(c, p, num); } else { ossl_sm3_block_data_order(c, p, num); } }
./openssl/crypto/whrlpool/wp_block.c
/* * Copyright 2005-2021 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 */ /** * The Whirlpool hashing function. * * See * P.S.L.M. Barreto, V. Rijmen, * ``The Whirlpool hashing function,'' * NESSIE submission, 2000 (tweaked version, 2001), * <https://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/whirlpool.zip> * * Based on "@version 3.0 (2003.03.12)" by Paulo S.L.M. Barreto and * Vincent Rijmen. Lookup "reference implementations" on * <http://planeta.terra.com.br/informatica/paulobarreto/> * * ============================================================================= * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* * Whirlpool low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "internal/cryptlib.h" #include "wp_local.h" #include <string.h> typedef unsigned char u8; #if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32) typedef unsigned __int64 u64; #elif defined(__arch64__) typedef unsigned long u64; #else typedef unsigned long long u64; #endif #define ROUNDS 10 #define STRICT_ALIGNMENT #if !defined(PEDANTIC) && (defined(__i386) || defined(__i386__) || \ defined(__x86_64) || defined(__x86_64__) || \ defined(_M_IX86) || defined(_M_AMD64) || \ defined(_M_X64)) /* * Well, formally there're couple of other architectures, which permit * unaligned loads, specifically those not crossing cache lines, IA-64 and * PowerPC... */ # undef STRICT_ALIGNMENT #endif #ifndef STRICT_ALIGNMENT # ifdef __GNUC__ typedef u64 u64_a1 __attribute((__aligned__(1))); # else typedef u64 u64_a1; # endif #endif #if defined(__GNUC__) && !defined(STRICT_ALIGNMENT) typedef u64 u64_aX __attribute((__aligned__(1))); #else typedef u64 u64_aX; #endif #undef SMALL_REGISTER_BANK #if defined(__i386) || defined(__i386__) || defined(_M_IX86) # define SMALL_REGISTER_BANK # if defined(WHIRLPOOL_ASM) # ifndef OPENSSL_SMALL_FOOTPRINT /* * it appears that for elder non-MMX * CPUs this is actually faster! */ # define OPENSSL_SMALL_FOOTPRINT # endif # define GO_FOR_MMX(ctx,inp,num) do { \ void whirlpool_block_mmx(void *,const void *,size_t); \ if (!(OPENSSL_ia32cap_P[0] & (1<<23))) break; \ whirlpool_block_mmx(ctx->H.c,inp,num); return; \ } while (0) # endif #endif #undef ROTATE #ifndef PEDANTIC # if defined(_MSC_VER) # if defined(_WIN64) /* applies to both IA-64 and AMD64 */ # include <stdlib.h> # pragma intrinsic(_rotl64) # define ROTATE(a,n) _rotl64((a),n) # endif # elif defined(__GNUC__) && __GNUC__>=2 # if defined(__x86_64) || defined(__x86_64__) # if defined(L_ENDIAN) # define ROTATE(a,n) ({ u64 ret; asm ("rolq %1,%0" \ : "=r"(ret) : "J"(n),"0"(a) : "cc"); ret; }) # elif defined(B_ENDIAN) /* * Most will argue that x86_64 is always little-endian. Well, yes, but * then we have stratus.com who has modified gcc to "emulate" * big-endian on x86. Is there evidence that they [or somebody else] * won't do same for x86_64? Naturally no. And this line is waiting * ready for that brave soul:-) */ # define ROTATE(a,n) ({ u64 ret; asm ("rorq %1,%0" \ : "=r"(ret) : "J"(n),"0"(a) : "cc"); ret; }) # endif # elif defined(__ia64) || defined(__ia64__) # if defined(L_ENDIAN) # define ROTATE(a,n) ({ u64 ret; asm ("shrp %0=%1,%1,%2" \ : "=r"(ret) : "r"(a),"M"(64-(n))); ret; }) # elif defined(B_ENDIAN) # define ROTATE(a,n) ({ u64 ret; asm ("shrp %0=%1,%1,%2" \ : "=r"(ret) : "r"(a),"M"(n)); ret; }) # endif # endif # endif #endif #if defined(OPENSSL_SMALL_FOOTPRINT) # if !defined(ROTATE) # if defined(L_ENDIAN) /* little-endians have to rotate left */ # define ROTATE(i,n) ((i)<<(n) ^ (i)>>(64-n)) # elif defined(B_ENDIAN) /* big-endians have to rotate right */ # define ROTATE(i,n) ((i)>>(n) ^ (i)<<(64-n)) # endif # endif # if defined(ROTATE) && !defined(STRICT_ALIGNMENT) # define STRICT_ALIGNMENT /* ensure smallest table size */ # endif #endif /* * Table size depends on STRICT_ALIGNMENT and whether or not endian- * specific ROTATE macro is defined. If STRICT_ALIGNMENT is not * defined, which is normally the case on x86[_64] CPUs, the table is * 4KB large unconditionally. Otherwise if ROTATE is defined, the * table is 2KB large, and otherwise - 16KB. 2KB table requires a * whole bunch of additional rotations, but I'm willing to "trade," * because 16KB table certainly trashes L1 cache. I wish all CPUs * could handle unaligned load as 4KB table doesn't trash the cache, * nor does it require additional rotations. */ /* * Note that every Cn macro expands as two loads: one byte load and * one quadword load. One can argue that many single-byte loads * is too excessive, as one could load a quadword and "milk" it for * eight 8-bit values instead. Well, yes, but in order to do so *and* * avoid excessive loads you have to accommodate a handful of 64-bit * values in the register bank and issue a bunch of shifts and mask. * It's a tradeoff: loads vs. shift and mask in big register bank[!]. * On most CPUs eight single-byte loads are faster and I let other * ones to depend on smart compiler to fold byte loads if beneficial. * Hand-coded assembler would be another alternative:-) */ #ifdef STRICT_ALIGNMENT # if defined(ROTATE) # define N 1 # define LL(c0,c1,c2,c3,c4,c5,c6,c7) c0,c1,c2,c3,c4,c5,c6,c7 # define C0(K,i) (Cx.q[K.c[(i)*8+0]]) # define C1(K,i) ROTATE(Cx.q[K.c[(i)*8+1]],8) # define C2(K,i) ROTATE(Cx.q[K.c[(i)*8+2]],16) # define C3(K,i) ROTATE(Cx.q[K.c[(i)*8+3]],24) # define C4(K,i) ROTATE(Cx.q[K.c[(i)*8+4]],32) # define C5(K,i) ROTATE(Cx.q[K.c[(i)*8+5]],40) # define C6(K,i) ROTATE(Cx.q[K.c[(i)*8+6]],48) # define C7(K,i) ROTATE(Cx.q[K.c[(i)*8+7]],56) # else # define N 8 # define LL(c0,c1,c2,c3,c4,c5,c6,c7) c0,c1,c2,c3,c4,c5,c6,c7, \ c7,c0,c1,c2,c3,c4,c5,c6, \ c6,c7,c0,c1,c2,c3,c4,c5, \ c5,c6,c7,c0,c1,c2,c3,c4, \ c4,c5,c6,c7,c0,c1,c2,c3, \ c3,c4,c5,c6,c7,c0,c1,c2, \ c2,c3,c4,c5,c6,c7,c0,c1, \ c1,c2,c3,c4,c5,c6,c7,c0 # define C0(K,i) (Cx.q[0+8*K.c[(i)*8+0]]) # define C1(K,i) (Cx.q[1+8*K.c[(i)*8+1]]) # define C2(K,i) (Cx.q[2+8*K.c[(i)*8+2]]) # define C3(K,i) (Cx.q[3+8*K.c[(i)*8+3]]) # define C4(K,i) (Cx.q[4+8*K.c[(i)*8+4]]) # define C5(K,i) (Cx.q[5+8*K.c[(i)*8+5]]) # define C6(K,i) (Cx.q[6+8*K.c[(i)*8+6]]) # define C7(K,i) (Cx.q[7+8*K.c[(i)*8+7]]) # endif #else # define N 2 # define LL(c0,c1,c2,c3,c4,c5,c6,c7) c0,c1,c2,c3,c4,c5,c6,c7, \ c0,c1,c2,c3,c4,c5,c6,c7 # define C0(K,i) (((u64*)(Cx.c+0))[2*K.c[(i)*8+0]]) # define C1(K,i) (((u64_a1*)(Cx.c+7))[2*K.c[(i)*8+1]]) # define C2(K,i) (((u64_a1*)(Cx.c+6))[2*K.c[(i)*8+2]]) # define C3(K,i) (((u64_a1*)(Cx.c+5))[2*K.c[(i)*8+3]]) # define C4(K,i) (((u64_a1*)(Cx.c+4))[2*K.c[(i)*8+4]]) # define C5(K,i) (((u64_a1*)(Cx.c+3))[2*K.c[(i)*8+5]]) # define C6(K,i) (((u64_a1*)(Cx.c+2))[2*K.c[(i)*8+6]]) # define C7(K,i) (((u64_a1*)(Cx.c+1))[2*K.c[(i)*8+7]]) #endif static const union { u8 c[(256 * N + ROUNDS) * sizeof(u64)]; u64 q[(256 * N + ROUNDS)]; } Cx = { { /* Note endian-neutral representation:-) */ LL(0x18, 0x18, 0x60, 0x18, 0xc0, 0x78, 0x30, 0xd8), LL(0x23, 0x23, 0x8c, 0x23, 0x05, 0xaf, 0x46, 0x26), LL(0xc6, 0xc6, 0x3f, 0xc6, 0x7e, 0xf9, 0x91, 0xb8), LL(0xe8, 0xe8, 0x87, 0xe8, 0x13, 0x6f, 0xcd, 0xfb), LL(0x87, 0x87, 0x26, 0x87, 0x4c, 0xa1, 0x13, 0xcb), LL(0xb8, 0xb8, 0xda, 0xb8, 0xa9, 0x62, 0x6d, 0x11), LL(0x01, 0x01, 0x04, 0x01, 0x08, 0x05, 0x02, 0x09), LL(0x4f, 0x4f, 0x21, 0x4f, 0x42, 0x6e, 0x9e, 0x0d), LL(0x36, 0x36, 0xd8, 0x36, 0xad, 0xee, 0x6c, 0x9b), LL(0xa6, 0xa6, 0xa2, 0xa6, 0x59, 0x04, 0x51, 0xff), LL(0xd2, 0xd2, 0x6f, 0xd2, 0xde, 0xbd, 0xb9, 0x0c), LL(0xf5, 0xf5, 0xf3, 0xf5, 0xfb, 0x06, 0xf7, 0x0e), LL(0x79, 0x79, 0xf9, 0x79, 0xef, 0x80, 0xf2, 0x96), LL(0x6f, 0x6f, 0xa1, 0x6f, 0x5f, 0xce, 0xde, 0x30), LL(0x91, 0x91, 0x7e, 0x91, 0xfc, 0xef, 0x3f, 0x6d), LL(0x52, 0x52, 0x55, 0x52, 0xaa, 0x07, 0xa4, 0xf8), LL(0x60, 0x60, 0x9d, 0x60, 0x27, 0xfd, 0xc0, 0x47), LL(0xbc, 0xbc, 0xca, 0xbc, 0x89, 0x76, 0x65, 0x35), LL(0x9b, 0x9b, 0x56, 0x9b, 0xac, 0xcd, 0x2b, 0x37), LL(0x8e, 0x8e, 0x02, 0x8e, 0x04, 0x8c, 0x01, 0x8a), LL(0xa3, 0xa3, 0xb6, 0xa3, 0x71, 0x15, 0x5b, 0xd2), LL(0x0c, 0x0c, 0x30, 0x0c, 0x60, 0x3c, 0x18, 0x6c), LL(0x7b, 0x7b, 0xf1, 0x7b, 0xff, 0x8a, 0xf6, 0x84), LL(0x35, 0x35, 0xd4, 0x35, 0xb5, 0xe1, 0x6a, 0x80), LL(0x1d, 0x1d, 0x74, 0x1d, 0xe8, 0x69, 0x3a, 0xf5), LL(0xe0, 0xe0, 0xa7, 0xe0, 0x53, 0x47, 0xdd, 0xb3), LL(0xd7, 0xd7, 0x7b, 0xd7, 0xf6, 0xac, 0xb3, 0x21), LL(0xc2, 0xc2, 0x2f, 0xc2, 0x5e, 0xed, 0x99, 0x9c), LL(0x2e, 0x2e, 0xb8, 0x2e, 0x6d, 0x96, 0x5c, 0x43), LL(0x4b, 0x4b, 0x31, 0x4b, 0x62, 0x7a, 0x96, 0x29), LL(0xfe, 0xfe, 0xdf, 0xfe, 0xa3, 0x21, 0xe1, 0x5d), LL(0x57, 0x57, 0x41, 0x57, 0x82, 0x16, 0xae, 0xd5), LL(0x15, 0x15, 0x54, 0x15, 0xa8, 0x41, 0x2a, 0xbd), LL(0x77, 0x77, 0xc1, 0x77, 0x9f, 0xb6, 0xee, 0xe8), LL(0x37, 0x37, 0xdc, 0x37, 0xa5, 0xeb, 0x6e, 0x92), LL(0xe5, 0xe5, 0xb3, 0xe5, 0x7b, 0x56, 0xd7, 0x9e), LL(0x9f, 0x9f, 0x46, 0x9f, 0x8c, 0xd9, 0x23, 0x13), LL(0xf0, 0xf0, 0xe7, 0xf0, 0xd3, 0x17, 0xfd, 0x23), LL(0x4a, 0x4a, 0x35, 0x4a, 0x6a, 0x7f, 0x94, 0x20), LL(0xda, 0xda, 0x4f, 0xda, 0x9e, 0x95, 0xa9, 0x44), LL(0x58, 0x58, 0x7d, 0x58, 0xfa, 0x25, 0xb0, 0xa2), LL(0xc9, 0xc9, 0x03, 0xc9, 0x06, 0xca, 0x8f, 0xcf), LL(0x29, 0x29, 0xa4, 0x29, 0x55, 0x8d, 0x52, 0x7c), LL(0x0a, 0x0a, 0x28, 0x0a, 0x50, 0x22, 0x14, 0x5a), LL(0xb1, 0xb1, 0xfe, 0xb1, 0xe1, 0x4f, 0x7f, 0x50), LL(0xa0, 0xa0, 0xba, 0xa0, 0x69, 0x1a, 0x5d, 0xc9), LL(0x6b, 0x6b, 0xb1, 0x6b, 0x7f, 0xda, 0xd6, 0x14), LL(0x85, 0x85, 0x2e, 0x85, 0x5c, 0xab, 0x17, 0xd9), LL(0xbd, 0xbd, 0xce, 0xbd, 0x81, 0x73, 0x67, 0x3c), LL(0x5d, 0x5d, 0x69, 0x5d, 0xd2, 0x34, 0xba, 0x8f), LL(0x10, 0x10, 0x40, 0x10, 0x80, 0x50, 0x20, 0x90), LL(0xf4, 0xf4, 0xf7, 0xf4, 0xf3, 0x03, 0xf5, 0x07), LL(0xcb, 0xcb, 0x0b, 0xcb, 0x16, 0xc0, 0x8b, 0xdd), LL(0x3e, 0x3e, 0xf8, 0x3e, 0xed, 0xc6, 0x7c, 0xd3), LL(0x05, 0x05, 0x14, 0x05, 0x28, 0x11, 0x0a, 0x2d), LL(0x67, 0x67, 0x81, 0x67, 0x1f, 0xe6, 0xce, 0x78), LL(0xe4, 0xe4, 0xb7, 0xe4, 0x73, 0x53, 0xd5, 0x97), LL(0x27, 0x27, 0x9c, 0x27, 0x25, 0xbb, 0x4e, 0x02), LL(0x41, 0x41, 0x19, 0x41, 0x32, 0x58, 0x82, 0x73), LL(0x8b, 0x8b, 0x16, 0x8b, 0x2c, 0x9d, 0x0b, 0xa7), LL(0xa7, 0xa7, 0xa6, 0xa7, 0x51, 0x01, 0x53, 0xf6), LL(0x7d, 0x7d, 0xe9, 0x7d, 0xcf, 0x94, 0xfa, 0xb2), LL(0x95, 0x95, 0x6e, 0x95, 0xdc, 0xfb, 0x37, 0x49), LL(0xd8, 0xd8, 0x47, 0xd8, 0x8e, 0x9f, 0xad, 0x56), LL(0xfb, 0xfb, 0xcb, 0xfb, 0x8b, 0x30, 0xeb, 0x70), LL(0xee, 0xee, 0x9f, 0xee, 0x23, 0x71, 0xc1, 0xcd), LL(0x7c, 0x7c, 0xed, 0x7c, 0xc7, 0x91, 0xf8, 0xbb), LL(0x66, 0x66, 0x85, 0x66, 0x17, 0xe3, 0xcc, 0x71), LL(0xdd, 0xdd, 0x53, 0xdd, 0xa6, 0x8e, 0xa7, 0x7b), LL(0x17, 0x17, 0x5c, 0x17, 0xb8, 0x4b, 0x2e, 0xaf), LL(0x47, 0x47, 0x01, 0x47, 0x02, 0x46, 0x8e, 0x45), LL(0x9e, 0x9e, 0x42, 0x9e, 0x84, 0xdc, 0x21, 0x1a), LL(0xca, 0xca, 0x0f, 0xca, 0x1e, 0xc5, 0x89, 0xd4), LL(0x2d, 0x2d, 0xb4, 0x2d, 0x75, 0x99, 0x5a, 0x58), LL(0xbf, 0xbf, 0xc6, 0xbf, 0x91, 0x79, 0x63, 0x2e), LL(0x07, 0x07, 0x1c, 0x07, 0x38, 0x1b, 0x0e, 0x3f), LL(0xad, 0xad, 0x8e, 0xad, 0x01, 0x23, 0x47, 0xac), LL(0x5a, 0x5a, 0x75, 0x5a, 0xea, 0x2f, 0xb4, 0xb0), LL(0x83, 0x83, 0x36, 0x83, 0x6c, 0xb5, 0x1b, 0xef), LL(0x33, 0x33, 0xcc, 0x33, 0x85, 0xff, 0x66, 0xb6), LL(0x63, 0x63, 0x91, 0x63, 0x3f, 0xf2, 0xc6, 0x5c), LL(0x02, 0x02, 0x08, 0x02, 0x10, 0x0a, 0x04, 0x12), LL(0xaa, 0xaa, 0x92, 0xaa, 0x39, 0x38, 0x49, 0x93), LL(0x71, 0x71, 0xd9, 0x71, 0xaf, 0xa8, 0xe2, 0xde), LL(0xc8, 0xc8, 0x07, 0xc8, 0x0e, 0xcf, 0x8d, 0xc6), LL(0x19, 0x19, 0x64, 0x19, 0xc8, 0x7d, 0x32, 0xd1), LL(0x49, 0x49, 0x39, 0x49, 0x72, 0x70, 0x92, 0x3b), LL(0xd9, 0xd9, 0x43, 0xd9, 0x86, 0x9a, 0xaf, 0x5f), LL(0xf2, 0xf2, 0xef, 0xf2, 0xc3, 0x1d, 0xf9, 0x31), LL(0xe3, 0xe3, 0xab, 0xe3, 0x4b, 0x48, 0xdb, 0xa8), LL(0x5b, 0x5b, 0x71, 0x5b, 0xe2, 0x2a, 0xb6, 0xb9), LL(0x88, 0x88, 0x1a, 0x88, 0x34, 0x92, 0x0d, 0xbc), LL(0x9a, 0x9a, 0x52, 0x9a, 0xa4, 0xc8, 0x29, 0x3e), LL(0x26, 0x26, 0x98, 0x26, 0x2d, 0xbe, 0x4c, 0x0b), LL(0x32, 0x32, 0xc8, 0x32, 0x8d, 0xfa, 0x64, 0xbf), LL(0xb0, 0xb0, 0xfa, 0xb0, 0xe9, 0x4a, 0x7d, 0x59), LL(0xe9, 0xe9, 0x83, 0xe9, 0x1b, 0x6a, 0xcf, 0xf2), LL(0x0f, 0x0f, 0x3c, 0x0f, 0x78, 0x33, 0x1e, 0x77), LL(0xd5, 0xd5, 0x73, 0xd5, 0xe6, 0xa6, 0xb7, 0x33), LL(0x80, 0x80, 0x3a, 0x80, 0x74, 0xba, 0x1d, 0xf4), LL(0xbe, 0xbe, 0xc2, 0xbe, 0x99, 0x7c, 0x61, 0x27), LL(0xcd, 0xcd, 0x13, 0xcd, 0x26, 0xde, 0x87, 0xeb), LL(0x34, 0x34, 0xd0, 0x34, 0xbd, 0xe4, 0x68, 0x89), LL(0x48, 0x48, 0x3d, 0x48, 0x7a, 0x75, 0x90, 0x32), LL(0xff, 0xff, 0xdb, 0xff, 0xab, 0x24, 0xe3, 0x54), LL(0x7a, 0x7a, 0xf5, 0x7a, 0xf7, 0x8f, 0xf4, 0x8d), LL(0x90, 0x90, 0x7a, 0x90, 0xf4, 0xea, 0x3d, 0x64), LL(0x5f, 0x5f, 0x61, 0x5f, 0xc2, 0x3e, 0xbe, 0x9d), LL(0x20, 0x20, 0x80, 0x20, 0x1d, 0xa0, 0x40, 0x3d), LL(0x68, 0x68, 0xbd, 0x68, 0x67, 0xd5, 0xd0, 0x0f), LL(0x1a, 0x1a, 0x68, 0x1a, 0xd0, 0x72, 0x34, 0xca), LL(0xae, 0xae, 0x82, 0xae, 0x19, 0x2c, 0x41, 0xb7), LL(0xb4, 0xb4, 0xea, 0xb4, 0xc9, 0x5e, 0x75, 0x7d), LL(0x54, 0x54, 0x4d, 0x54, 0x9a, 0x19, 0xa8, 0xce), LL(0x93, 0x93, 0x76, 0x93, 0xec, 0xe5, 0x3b, 0x7f), LL(0x22, 0x22, 0x88, 0x22, 0x0d, 0xaa, 0x44, 0x2f), LL(0x64, 0x64, 0x8d, 0x64, 0x07, 0xe9, 0xc8, 0x63), LL(0xf1, 0xf1, 0xe3, 0xf1, 0xdb, 0x12, 0xff, 0x2a), LL(0x73, 0x73, 0xd1, 0x73, 0xbf, 0xa2, 0xe6, 0xcc), LL(0x12, 0x12, 0x48, 0x12, 0x90, 0x5a, 0x24, 0x82), LL(0x40, 0x40, 0x1d, 0x40, 0x3a, 0x5d, 0x80, 0x7a), LL(0x08, 0x08, 0x20, 0x08, 0x40, 0x28, 0x10, 0x48), LL(0xc3, 0xc3, 0x2b, 0xc3, 0x56, 0xe8, 0x9b, 0x95), LL(0xec, 0xec, 0x97, 0xec, 0x33, 0x7b, 0xc5, 0xdf), LL(0xdb, 0xdb, 0x4b, 0xdb, 0x96, 0x90, 0xab, 0x4d), LL(0xa1, 0xa1, 0xbe, 0xa1, 0x61, 0x1f, 0x5f, 0xc0), LL(0x8d, 0x8d, 0x0e, 0x8d, 0x1c, 0x83, 0x07, 0x91), LL(0x3d, 0x3d, 0xf4, 0x3d, 0xf5, 0xc9, 0x7a, 0xc8), LL(0x97, 0x97, 0x66, 0x97, 0xcc, 0xf1, 0x33, 0x5b), LL(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), LL(0xcf, 0xcf, 0x1b, 0xcf, 0x36, 0xd4, 0x83, 0xf9), LL(0x2b, 0x2b, 0xac, 0x2b, 0x45, 0x87, 0x56, 0x6e), LL(0x76, 0x76, 0xc5, 0x76, 0x97, 0xb3, 0xec, 0xe1), LL(0x82, 0x82, 0x32, 0x82, 0x64, 0xb0, 0x19, 0xe6), LL(0xd6, 0xd6, 0x7f, 0xd6, 0xfe, 0xa9, 0xb1, 0x28), LL(0x1b, 0x1b, 0x6c, 0x1b, 0xd8, 0x77, 0x36, 0xc3), LL(0xb5, 0xb5, 0xee, 0xb5, 0xc1, 0x5b, 0x77, 0x74), LL(0xaf, 0xaf, 0x86, 0xaf, 0x11, 0x29, 0x43, 0xbe), LL(0x6a, 0x6a, 0xb5, 0x6a, 0x77, 0xdf, 0xd4, 0x1d), LL(0x50, 0x50, 0x5d, 0x50, 0xba, 0x0d, 0xa0, 0xea), LL(0x45, 0x45, 0x09, 0x45, 0x12, 0x4c, 0x8a, 0x57), LL(0xf3, 0xf3, 0xeb, 0xf3, 0xcb, 0x18, 0xfb, 0x38), LL(0x30, 0x30, 0xc0, 0x30, 0x9d, 0xf0, 0x60, 0xad), LL(0xef, 0xef, 0x9b, 0xef, 0x2b, 0x74, 0xc3, 0xc4), LL(0x3f, 0x3f, 0xfc, 0x3f, 0xe5, 0xc3, 0x7e, 0xda), LL(0x55, 0x55, 0x49, 0x55, 0x92, 0x1c, 0xaa, 0xc7), LL(0xa2, 0xa2, 0xb2, 0xa2, 0x79, 0x10, 0x59, 0xdb), LL(0xea, 0xea, 0x8f, 0xea, 0x03, 0x65, 0xc9, 0xe9), LL(0x65, 0x65, 0x89, 0x65, 0x0f, 0xec, 0xca, 0x6a), LL(0xba, 0xba, 0xd2, 0xba, 0xb9, 0x68, 0x69, 0x03), LL(0x2f, 0x2f, 0xbc, 0x2f, 0x65, 0x93, 0x5e, 0x4a), LL(0xc0, 0xc0, 0x27, 0xc0, 0x4e, 0xe7, 0x9d, 0x8e), LL(0xde, 0xde, 0x5f, 0xde, 0xbe, 0x81, 0xa1, 0x60), LL(0x1c, 0x1c, 0x70, 0x1c, 0xe0, 0x6c, 0x38, 0xfc), LL(0xfd, 0xfd, 0xd3, 0xfd, 0xbb, 0x2e, 0xe7, 0x46), LL(0x4d, 0x4d, 0x29, 0x4d, 0x52, 0x64, 0x9a, 0x1f), LL(0x92, 0x92, 0x72, 0x92, 0xe4, 0xe0, 0x39, 0x76), LL(0x75, 0x75, 0xc9, 0x75, 0x8f, 0xbc, 0xea, 0xfa), LL(0x06, 0x06, 0x18, 0x06, 0x30, 0x1e, 0x0c, 0x36), LL(0x8a, 0x8a, 0x12, 0x8a, 0x24, 0x98, 0x09, 0xae), LL(0xb2, 0xb2, 0xf2, 0xb2, 0xf9, 0x40, 0x79, 0x4b), LL(0xe6, 0xe6, 0xbf, 0xe6, 0x63, 0x59, 0xd1, 0x85), LL(0x0e, 0x0e, 0x38, 0x0e, 0x70, 0x36, 0x1c, 0x7e), LL(0x1f, 0x1f, 0x7c, 0x1f, 0xf8, 0x63, 0x3e, 0xe7), LL(0x62, 0x62, 0x95, 0x62, 0x37, 0xf7, 0xc4, 0x55), LL(0xd4, 0xd4, 0x77, 0xd4, 0xee, 0xa3, 0xb5, 0x3a), LL(0xa8, 0xa8, 0x9a, 0xa8, 0x29, 0x32, 0x4d, 0x81), LL(0x96, 0x96, 0x62, 0x96, 0xc4, 0xf4, 0x31, 0x52), LL(0xf9, 0xf9, 0xc3, 0xf9, 0x9b, 0x3a, 0xef, 0x62), LL(0xc5, 0xc5, 0x33, 0xc5, 0x66, 0xf6, 0x97, 0xa3), LL(0x25, 0x25, 0x94, 0x25, 0x35, 0xb1, 0x4a, 0x10), LL(0x59, 0x59, 0x79, 0x59, 0xf2, 0x20, 0xb2, 0xab), LL(0x84, 0x84, 0x2a, 0x84, 0x54, 0xae, 0x15, 0xd0), LL(0x72, 0x72, 0xd5, 0x72, 0xb7, 0xa7, 0xe4, 0xc5), LL(0x39, 0x39, 0xe4, 0x39, 0xd5, 0xdd, 0x72, 0xec), LL(0x4c, 0x4c, 0x2d, 0x4c, 0x5a, 0x61, 0x98, 0x16), LL(0x5e, 0x5e, 0x65, 0x5e, 0xca, 0x3b, 0xbc, 0x94), LL(0x78, 0x78, 0xfd, 0x78, 0xe7, 0x85, 0xf0, 0x9f), LL(0x38, 0x38, 0xe0, 0x38, 0xdd, 0xd8, 0x70, 0xe5), LL(0x8c, 0x8c, 0x0a, 0x8c, 0x14, 0x86, 0x05, 0x98), LL(0xd1, 0xd1, 0x63, 0xd1, 0xc6, 0xb2, 0xbf, 0x17), LL(0xa5, 0xa5, 0xae, 0xa5, 0x41, 0x0b, 0x57, 0xe4), LL(0xe2, 0xe2, 0xaf, 0xe2, 0x43, 0x4d, 0xd9, 0xa1), LL(0x61, 0x61, 0x99, 0x61, 0x2f, 0xf8, 0xc2, 0x4e), LL(0xb3, 0xb3, 0xf6, 0xb3, 0xf1, 0x45, 0x7b, 0x42), LL(0x21, 0x21, 0x84, 0x21, 0x15, 0xa5, 0x42, 0x34), LL(0x9c, 0x9c, 0x4a, 0x9c, 0x94, 0xd6, 0x25, 0x08), LL(0x1e, 0x1e, 0x78, 0x1e, 0xf0, 0x66, 0x3c, 0xee), LL(0x43, 0x43, 0x11, 0x43, 0x22, 0x52, 0x86, 0x61), LL(0xc7, 0xc7, 0x3b, 0xc7, 0x76, 0xfc, 0x93, 0xb1), LL(0xfc, 0xfc, 0xd7, 0xfc, 0xb3, 0x2b, 0xe5, 0x4f), LL(0x04, 0x04, 0x10, 0x04, 0x20, 0x14, 0x08, 0x24), LL(0x51, 0x51, 0x59, 0x51, 0xb2, 0x08, 0xa2, 0xe3), LL(0x99, 0x99, 0x5e, 0x99, 0xbc, 0xc7, 0x2f, 0x25), LL(0x6d, 0x6d, 0xa9, 0x6d, 0x4f, 0xc4, 0xda, 0x22), LL(0x0d, 0x0d, 0x34, 0x0d, 0x68, 0x39, 0x1a, 0x65), LL(0xfa, 0xfa, 0xcf, 0xfa, 0x83, 0x35, 0xe9, 0x79), LL(0xdf, 0xdf, 0x5b, 0xdf, 0xb6, 0x84, 0xa3, 0x69), LL(0x7e, 0x7e, 0xe5, 0x7e, 0xd7, 0x9b, 0xfc, 0xa9), LL(0x24, 0x24, 0x90, 0x24, 0x3d, 0xb4, 0x48, 0x19), LL(0x3b, 0x3b, 0xec, 0x3b, 0xc5, 0xd7, 0x76, 0xfe), LL(0xab, 0xab, 0x96, 0xab, 0x31, 0x3d, 0x4b, 0x9a), LL(0xce, 0xce, 0x1f, 0xce, 0x3e, 0xd1, 0x81, 0xf0), LL(0x11, 0x11, 0x44, 0x11, 0x88, 0x55, 0x22, 0x99), LL(0x8f, 0x8f, 0x06, 0x8f, 0x0c, 0x89, 0x03, 0x83), LL(0x4e, 0x4e, 0x25, 0x4e, 0x4a, 0x6b, 0x9c, 0x04), LL(0xb7, 0xb7, 0xe6, 0xb7, 0xd1, 0x51, 0x73, 0x66), LL(0xeb, 0xeb, 0x8b, 0xeb, 0x0b, 0x60, 0xcb, 0xe0), LL(0x3c, 0x3c, 0xf0, 0x3c, 0xfd, 0xcc, 0x78, 0xc1), LL(0x81, 0x81, 0x3e, 0x81, 0x7c, 0xbf, 0x1f, 0xfd), LL(0x94, 0x94, 0x6a, 0x94, 0xd4, 0xfe, 0x35, 0x40), LL(0xf7, 0xf7, 0xfb, 0xf7, 0xeb, 0x0c, 0xf3, 0x1c), LL(0xb9, 0xb9, 0xde, 0xb9, 0xa1, 0x67, 0x6f, 0x18), LL(0x13, 0x13, 0x4c, 0x13, 0x98, 0x5f, 0x26, 0x8b), LL(0x2c, 0x2c, 0xb0, 0x2c, 0x7d, 0x9c, 0x58, 0x51), LL(0xd3, 0xd3, 0x6b, 0xd3, 0xd6, 0xb8, 0xbb, 0x05), LL(0xe7, 0xe7, 0xbb, 0xe7, 0x6b, 0x5c, 0xd3, 0x8c), LL(0x6e, 0x6e, 0xa5, 0x6e, 0x57, 0xcb, 0xdc, 0x39), LL(0xc4, 0xc4, 0x37, 0xc4, 0x6e, 0xf3, 0x95, 0xaa), LL(0x03, 0x03, 0x0c, 0x03, 0x18, 0x0f, 0x06, 0x1b), LL(0x56, 0x56, 0x45, 0x56, 0x8a, 0x13, 0xac, 0xdc), LL(0x44, 0x44, 0x0d, 0x44, 0x1a, 0x49, 0x88, 0x5e), LL(0x7f, 0x7f, 0xe1, 0x7f, 0xdf, 0x9e, 0xfe, 0xa0), LL(0xa9, 0xa9, 0x9e, 0xa9, 0x21, 0x37, 0x4f, 0x88), LL(0x2a, 0x2a, 0xa8, 0x2a, 0x4d, 0x82, 0x54, 0x67), LL(0xbb, 0xbb, 0xd6, 0xbb, 0xb1, 0x6d, 0x6b, 0x0a), LL(0xc1, 0xc1, 0x23, 0xc1, 0x46, 0xe2, 0x9f, 0x87), LL(0x53, 0x53, 0x51, 0x53, 0xa2, 0x02, 0xa6, 0xf1), LL(0xdc, 0xdc, 0x57, 0xdc, 0xae, 0x8b, 0xa5, 0x72), LL(0x0b, 0x0b, 0x2c, 0x0b, 0x58, 0x27, 0x16, 0x53), LL(0x9d, 0x9d, 0x4e, 0x9d, 0x9c, 0xd3, 0x27, 0x01), LL(0x6c, 0x6c, 0xad, 0x6c, 0x47, 0xc1, 0xd8, 0x2b), LL(0x31, 0x31, 0xc4, 0x31, 0x95, 0xf5, 0x62, 0xa4), LL(0x74, 0x74, 0xcd, 0x74, 0x87, 0xb9, 0xe8, 0xf3), LL(0xf6, 0xf6, 0xff, 0xf6, 0xe3, 0x09, 0xf1, 0x15), LL(0x46, 0x46, 0x05, 0x46, 0x0a, 0x43, 0x8c, 0x4c), LL(0xac, 0xac, 0x8a, 0xac, 0x09, 0x26, 0x45, 0xa5), LL(0x89, 0x89, 0x1e, 0x89, 0x3c, 0x97, 0x0f, 0xb5), LL(0x14, 0x14, 0x50, 0x14, 0xa0, 0x44, 0x28, 0xb4), LL(0xe1, 0xe1, 0xa3, 0xe1, 0x5b, 0x42, 0xdf, 0xba), LL(0x16, 0x16, 0x58, 0x16, 0xb0, 0x4e, 0x2c, 0xa6), LL(0x3a, 0x3a, 0xe8, 0x3a, 0xcd, 0xd2, 0x74, 0xf7), LL(0x69, 0x69, 0xb9, 0x69, 0x6f, 0xd0, 0xd2, 0x06), LL(0x09, 0x09, 0x24, 0x09, 0x48, 0x2d, 0x12, 0x41), LL(0x70, 0x70, 0xdd, 0x70, 0xa7, 0xad, 0xe0, 0xd7), LL(0xb6, 0xb6, 0xe2, 0xb6, 0xd9, 0x54, 0x71, 0x6f), LL(0xd0, 0xd0, 0x67, 0xd0, 0xce, 0xb7, 0xbd, 0x1e), LL(0xed, 0xed, 0x93, 0xed, 0x3b, 0x7e, 0xc7, 0xd6), LL(0xcc, 0xcc, 0x17, 0xcc, 0x2e, 0xdb, 0x85, 0xe2), LL(0x42, 0x42, 0x15, 0x42, 0x2a, 0x57, 0x84, 0x68), LL(0x98, 0x98, 0x5a, 0x98, 0xb4, 0xc2, 0x2d, 0x2c), LL(0xa4, 0xa4, 0xaa, 0xa4, 0x49, 0x0e, 0x55, 0xed), LL(0x28, 0x28, 0xa0, 0x28, 0x5d, 0x88, 0x50, 0x75), LL(0x5c, 0x5c, 0x6d, 0x5c, 0xda, 0x31, 0xb8, 0x86), LL(0xf8, 0xf8, 0xc7, 0xf8, 0x93, 0x3f, 0xed, 0x6b), LL(0x86, 0x86, 0x22, 0x86, 0x44, 0xa4, 0x11, 0xc2), #define RC (&(Cx.q[256*N])) 0x18, 0x23, 0xc6, 0xe8, 0x87, 0xb8, 0x01, 0x4f, /* rc[ROUNDS] */ 0x36, 0xa6, 0xd2, 0xf5, 0x79, 0x6f, 0x91, 0x52, 0x60, 0xbc, 0x9b, 0x8e, 0xa3, 0x0c, 0x7b, 0x35, 0x1d, 0xe0, 0xd7, 0xc2, 0x2e, 0x4b, 0xfe, 0x57, 0x15, 0x77, 0x37, 0xe5, 0x9f, 0xf0, 0x4a, 0xda, 0x58, 0xc9, 0x29, 0x0a, 0xb1, 0xa0, 0x6b, 0x85, 0xbd, 0x5d, 0x10, 0xf4, 0xcb, 0x3e, 0x05, 0x67, 0xe4, 0x27, 0x41, 0x8b, 0xa7, 0x7d, 0x95, 0xd8, 0xfb, 0xee, 0x7c, 0x66, 0xdd, 0x17, 0x47, 0x9e, 0xca, 0x2d, 0xbf, 0x07, 0xad, 0x5a, 0x83, 0x33 } }; void whirlpool_block(WHIRLPOOL_CTX *ctx, const void *inp, size_t n) { int r; const u8 *p = inp; union { u64 q[8]; u8 c[64]; } S, K, *H = (void *)ctx->H.q; #ifdef GO_FOR_MMX GO_FOR_MMX(ctx, inp, n); #endif do { #ifdef OPENSSL_SMALL_FOOTPRINT u64 L[8]; int i; for (i = 0; i < 64; i++) S.c[i] = (K.c[i] = H->c[i]) ^ p[i]; for (r = 0; r < ROUNDS; r++) { for (i = 0; i < 8; i++) { L[i] = i ? 0 : RC[r]; L[i] ^= C0(K, i) ^ C1(K, (i - 1) & 7) ^ C2(K, (i - 2) & 7) ^ C3(K, (i - 3) & 7) ^ C4(K, (i - 4) & 7) ^ C5(K, (i - 5) & 7) ^ C6(K, (i - 6) & 7) ^ C7(K, (i - 7) & 7); } memcpy(K.q, L, 64); for (i = 0; i < 8; i++) { L[i] ^= C0(S, i) ^ C1(S, (i - 1) & 7) ^ C2(S, (i - 2) & 7) ^ C3(S, (i - 3) & 7) ^ C4(S, (i - 4) & 7) ^ C5(S, (i - 5) & 7) ^ C6(S, (i - 6) & 7) ^ C7(S, (i - 7) & 7); } memcpy(S.q, L, 64); } for (i = 0; i < 64; i++) H->c[i] ^= S.c[i] ^ p[i]; #else u64 L0, L1, L2, L3, L4, L5, L6, L7; # ifdef STRICT_ALIGNMENT if ((size_t)p & 7) { memcpy(S.c, p, 64); S.q[0] ^= (K.q[0] = H->q[0]); S.q[1] ^= (K.q[1] = H->q[1]); S.q[2] ^= (K.q[2] = H->q[2]); S.q[3] ^= (K.q[3] = H->q[3]); S.q[4] ^= (K.q[4] = H->q[4]); S.q[5] ^= (K.q[5] = H->q[5]); S.q[6] ^= (K.q[6] = H->q[6]); S.q[7] ^= (K.q[7] = H->q[7]); } else # endif { const u64_aX *pa = (const u64_aX *)p; S.q[0] = (K.q[0] = H->q[0]) ^ pa[0]; S.q[1] = (K.q[1] = H->q[1]) ^ pa[1]; S.q[2] = (K.q[2] = H->q[2]) ^ pa[2]; S.q[3] = (K.q[3] = H->q[3]) ^ pa[3]; S.q[4] = (K.q[4] = H->q[4]) ^ pa[4]; S.q[5] = (K.q[5] = H->q[5]) ^ pa[5]; S.q[6] = (K.q[6] = H->q[6]) ^ pa[6]; S.q[7] = (K.q[7] = H->q[7]) ^ pa[7]; } for (r = 0; r < ROUNDS; r++) { # ifdef SMALL_REGISTER_BANK L0 = C0(K, 0) ^ C1(K, 7) ^ C2(K, 6) ^ C3(K, 5) ^ C4(K, 4) ^ C5(K, 3) ^ C6(K, 2) ^ C7(K, 1) ^ RC[r]; L1 = C0(K, 1) ^ C1(K, 0) ^ C2(K, 7) ^ C3(K, 6) ^ C4(K, 5) ^ C5(K, 4) ^ C6(K, 3) ^ C7(K, 2); L2 = C0(K, 2) ^ C1(K, 1) ^ C2(K, 0) ^ C3(K, 7) ^ C4(K, 6) ^ C5(K, 5) ^ C6(K, 4) ^ C7(K, 3); L3 = C0(K, 3) ^ C1(K, 2) ^ C2(K, 1) ^ C3(K, 0) ^ C4(K, 7) ^ C5(K, 6) ^ C6(K, 5) ^ C7(K, 4); L4 = C0(K, 4) ^ C1(K, 3) ^ C2(K, 2) ^ C3(K, 1) ^ C4(K, 0) ^ C5(K, 7) ^ C6(K, 6) ^ C7(K, 5); L5 = C0(K, 5) ^ C1(K, 4) ^ C2(K, 3) ^ C3(K, 2) ^ C4(K, 1) ^ C5(K, 0) ^ C6(K, 7) ^ C7(K, 6); L6 = C0(K, 6) ^ C1(K, 5) ^ C2(K, 4) ^ C3(K, 3) ^ C4(K, 2) ^ C5(K, 1) ^ C6(K, 0) ^ C7(K, 7); L7 = C0(K, 7) ^ C1(K, 6) ^ C2(K, 5) ^ C3(K, 4) ^ C4(K, 3) ^ C5(K, 2) ^ C6(K, 1) ^ C7(K, 0); K.q[0] = L0; K.q[1] = L1; K.q[2] = L2; K.q[3] = L3; K.q[4] = L4; K.q[5] = L5; K.q[6] = L6; K.q[7] = L7; L0 ^= C0(S, 0) ^ C1(S, 7) ^ C2(S, 6) ^ C3(S, 5) ^ C4(S, 4) ^ C5(S, 3) ^ C6(S, 2) ^ C7(S, 1); L1 ^= C0(S, 1) ^ C1(S, 0) ^ C2(S, 7) ^ C3(S, 6) ^ C4(S, 5) ^ C5(S, 4) ^ C6(S, 3) ^ C7(S, 2); L2 ^= C0(S, 2) ^ C1(S, 1) ^ C2(S, 0) ^ C3(S, 7) ^ C4(S, 6) ^ C5(S, 5) ^ C6(S, 4) ^ C7(S, 3); L3 ^= C0(S, 3) ^ C1(S, 2) ^ C2(S, 1) ^ C3(S, 0) ^ C4(S, 7) ^ C5(S, 6) ^ C6(S, 5) ^ C7(S, 4); L4 ^= C0(S, 4) ^ C1(S, 3) ^ C2(S, 2) ^ C3(S, 1) ^ C4(S, 0) ^ C5(S, 7) ^ C6(S, 6) ^ C7(S, 5); L5 ^= C0(S, 5) ^ C1(S, 4) ^ C2(S, 3) ^ C3(S, 2) ^ C4(S, 1) ^ C5(S, 0) ^ C6(S, 7) ^ C7(S, 6); L6 ^= C0(S, 6) ^ C1(S, 5) ^ C2(S, 4) ^ C3(S, 3) ^ C4(S, 2) ^ C5(S, 1) ^ C6(S, 0) ^ C7(S, 7); L7 ^= C0(S, 7) ^ C1(S, 6) ^ C2(S, 5) ^ C3(S, 4) ^ C4(S, 3) ^ C5(S, 2) ^ C6(S, 1) ^ C7(S, 0); S.q[0] = L0; S.q[1] = L1; S.q[2] = L2; S.q[3] = L3; S.q[4] = L4; S.q[5] = L5; S.q[6] = L6; S.q[7] = L7; # else L0 = C0(K, 0); L1 = C1(K, 0); L2 = C2(K, 0); L3 = C3(K, 0); L4 = C4(K, 0); L5 = C5(K, 0); L6 = C6(K, 0); L7 = C7(K, 0); L0 ^= RC[r]; L1 ^= C0(K, 1); L2 ^= C1(K, 1); L3 ^= C2(K, 1); L4 ^= C3(K, 1); L5 ^= C4(K, 1); L6 ^= C5(K, 1); L7 ^= C6(K, 1); L0 ^= C7(K, 1); L2 ^= C0(K, 2); L3 ^= C1(K, 2); L4 ^= C2(K, 2); L5 ^= C3(K, 2); L6 ^= C4(K, 2); L7 ^= C5(K, 2); L0 ^= C6(K, 2); L1 ^= C7(K, 2); L3 ^= C0(K, 3); L4 ^= C1(K, 3); L5 ^= C2(K, 3); L6 ^= C3(K, 3); L7 ^= C4(K, 3); L0 ^= C5(K, 3); L1 ^= C6(K, 3); L2 ^= C7(K, 3); L4 ^= C0(K, 4); L5 ^= C1(K, 4); L6 ^= C2(K, 4); L7 ^= C3(K, 4); L0 ^= C4(K, 4); L1 ^= C5(K, 4); L2 ^= C6(K, 4); L3 ^= C7(K, 4); L5 ^= C0(K, 5); L6 ^= C1(K, 5); L7 ^= C2(K, 5); L0 ^= C3(K, 5); L1 ^= C4(K, 5); L2 ^= C5(K, 5); L3 ^= C6(K, 5); L4 ^= C7(K, 5); L6 ^= C0(K, 6); L7 ^= C1(K, 6); L0 ^= C2(K, 6); L1 ^= C3(K, 6); L2 ^= C4(K, 6); L3 ^= C5(K, 6); L4 ^= C6(K, 6); L5 ^= C7(K, 6); L7 ^= C0(K, 7); L0 ^= C1(K, 7); L1 ^= C2(K, 7); L2 ^= C3(K, 7); L3 ^= C4(K, 7); L4 ^= C5(K, 7); L5 ^= C6(K, 7); L6 ^= C7(K, 7); K.q[0] = L0; K.q[1] = L1; K.q[2] = L2; K.q[3] = L3; K.q[4] = L4; K.q[5] = L5; K.q[6] = L6; K.q[7] = L7; L0 ^= C0(S, 0); L1 ^= C1(S, 0); L2 ^= C2(S, 0); L3 ^= C3(S, 0); L4 ^= C4(S, 0); L5 ^= C5(S, 0); L6 ^= C6(S, 0); L7 ^= C7(S, 0); L1 ^= C0(S, 1); L2 ^= C1(S, 1); L3 ^= C2(S, 1); L4 ^= C3(S, 1); L5 ^= C4(S, 1); L6 ^= C5(S, 1); L7 ^= C6(S, 1); L0 ^= C7(S, 1); L2 ^= C0(S, 2); L3 ^= C1(S, 2); L4 ^= C2(S, 2); L5 ^= C3(S, 2); L6 ^= C4(S, 2); L7 ^= C5(S, 2); L0 ^= C6(S, 2); L1 ^= C7(S, 2); L3 ^= C0(S, 3); L4 ^= C1(S, 3); L5 ^= C2(S, 3); L6 ^= C3(S, 3); L7 ^= C4(S, 3); L0 ^= C5(S, 3); L1 ^= C6(S, 3); L2 ^= C7(S, 3); L4 ^= C0(S, 4); L5 ^= C1(S, 4); L6 ^= C2(S, 4); L7 ^= C3(S, 4); L0 ^= C4(S, 4); L1 ^= C5(S, 4); L2 ^= C6(S, 4); L3 ^= C7(S, 4); L5 ^= C0(S, 5); L6 ^= C1(S, 5); L7 ^= C2(S, 5); L0 ^= C3(S, 5); L1 ^= C4(S, 5); L2 ^= C5(S, 5); L3 ^= C6(S, 5); L4 ^= C7(S, 5); L6 ^= C0(S, 6); L7 ^= C1(S, 6); L0 ^= C2(S, 6); L1 ^= C3(S, 6); L2 ^= C4(S, 6); L3 ^= C5(S, 6); L4 ^= C6(S, 6); L5 ^= C7(S, 6); L7 ^= C0(S, 7); L0 ^= C1(S, 7); L1 ^= C2(S, 7); L2 ^= C3(S, 7); L3 ^= C4(S, 7); L4 ^= C5(S, 7); L5 ^= C6(S, 7); L6 ^= C7(S, 7); S.q[0] = L0; S.q[1] = L1; S.q[2] = L2; S.q[3] = L3; S.q[4] = L4; S.q[5] = L5; S.q[6] = L6; S.q[7] = L7; # endif } # ifdef STRICT_ALIGNMENT if ((size_t)p & 7) { int i; for (i = 0; i < 64; i++) H->c[i] ^= S.c[i] ^ p[i]; } else # endif { const u64_aX *pa = (const u64_aX *)p; H->q[0] ^= S.q[0] ^ pa[0]; H->q[1] ^= S.q[1] ^ pa[1]; H->q[2] ^= S.q[2] ^ pa[2]; H->q[3] ^= S.q[3] ^ pa[3]; H->q[4] ^= S.q[4] ^ pa[4]; H->q[5] ^= S.q[5] ^ pa[5]; H->q[6] ^= S.q[6] ^ pa[6]; H->q[7] ^= S.q[7] ^ pa[7]; } #endif p += 64; } while (--n); }
./openssl/crypto/whrlpool/wp_dgst.c
/* * Copyright 2005-2023 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 */ /** * The Whirlpool hashing function. * * See * P.S.L.M. Barreto, V. Rijmen, * ``The Whirlpool hashing function,'' * NESSIE submission, 2000 (tweaked version, 2001), * <https://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/whirlpool.zip> * * Based on "@version 3.0 (2003.03.12)" by Paulo S.L.M. Barreto and * Vincent Rijmen. Lookup "reference implementations" on * <http://planeta.terra.com.br/informatica/paulobarreto/> * * ============================================================================= * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* * OpenSSL-specific implementation notes. * * WHIRLPOOL_Update as well as one-stroke WHIRLPOOL both expect * number of *bytes* as input length argument. Bit-oriented routine * as specified by authors is called WHIRLPOOL_BitUpdate[!] and * does not have one-stroke counterpart. * * WHIRLPOOL_BitUpdate implements byte-oriented loop, essentially * to serve WHIRLPOOL_Update. This is done for performance. * * Unlike authors' reference implementation, block processing * routine whirlpool_block is designed to operate on multi-block * input. This is done for performance. */ /* * Whirlpool low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/crypto.h> #include "wp_local.h" #include <string.h> int WHIRLPOOL_Init(WHIRLPOOL_CTX *c) { memset(c, 0, sizeof(*c)); return 1; } int WHIRLPOOL_Update(WHIRLPOOL_CTX *c, const void *_inp, size_t bytes) { /* * Well, largest suitable chunk size actually is * (1<<(sizeof(size_t)*8-3))-64, but below number is large enough for not * to care about excessive calls to WHIRLPOOL_BitUpdate... */ size_t chunk = ((size_t)1) << (sizeof(size_t) * 8 - 4); const unsigned char *inp = _inp; while (bytes >= chunk) { WHIRLPOOL_BitUpdate(c, inp, chunk * 8); bytes -= chunk; inp += chunk; } if (bytes) WHIRLPOOL_BitUpdate(c, inp, bytes * 8); return 1; } void WHIRLPOOL_BitUpdate(WHIRLPOOL_CTX *c, const void *_inp, size_t bits) { size_t n; unsigned int bitoff = c->bitoff, bitrem = bitoff % 8, inpgap = (8 - (unsigned int)bits % 8) & 7; const unsigned char *inp = _inp; /* * This 256-bit increment procedure relies on the size_t being natural * size of CPU register, so that we don't have to mask the value in order * to detect overflows. */ c->bitlen[0] += bits; if (c->bitlen[0] < bits) { /* overflow */ n = 1; do { c->bitlen[n]++; } while (c->bitlen[n] == 0 && ++n < (WHIRLPOOL_COUNTER / sizeof(size_t))); } #ifndef OPENSSL_SMALL_FOOTPRINT reconsider: if (inpgap == 0 && bitrem == 0) { /* byte-oriented loop */ while (bits) { if (bitoff == 0 && (n = bits / WHIRLPOOL_BBLOCK)) { whirlpool_block(c, inp, n); inp += n * WHIRLPOOL_BBLOCK / 8; bits %= WHIRLPOOL_BBLOCK; } else { unsigned int byteoff = bitoff / 8; bitrem = WHIRLPOOL_BBLOCK - bitoff; /* reuse bitrem */ if (bits >= bitrem) { bits -= bitrem; bitrem /= 8; memcpy(c->data + byteoff, inp, bitrem); inp += bitrem; whirlpool_block(c, c->data, 1); bitoff = 0; } else { memcpy(c->data + byteoff, inp, bits / 8); bitoff += (unsigned int)bits; bits = 0; } c->bitoff = bitoff; } } } else /* bit-oriented loop */ #endif { /*- inp | +-------+-------+------- ||||||||||||||||||||| +-------+-------+------- +-------+-------+-------+-------+------- |||||||||||||| c->data +-------+-------+-------+-------+------- | c->bitoff/8 */ while (bits) { unsigned int byteoff = bitoff / 8; unsigned char b; #ifndef OPENSSL_SMALL_FOOTPRINT if (bitrem == inpgap) { c->data[byteoff++] |= inp[0] & (0xff >> inpgap); inpgap = 8 - inpgap; bitoff += inpgap; bitrem = 0; /* bitoff%8 */ bits -= inpgap; inpgap = 0; /* bits%8 */ inp++; if (bitoff == WHIRLPOOL_BBLOCK) { whirlpool_block(c, c->data, 1); bitoff = 0; } c->bitoff = bitoff; goto reconsider; } else #endif if (bits > 8) { b = ((inp[0] << inpgap) | (inp[1] >> (8 - inpgap))); b &= 0xff; if (bitrem) c->data[byteoff++] |= b >> bitrem; else c->data[byteoff++] = b; bitoff += 8; bits -= 8; inp++; if (bitoff >= WHIRLPOOL_BBLOCK) { whirlpool_block(c, c->data, 1); byteoff = 0; bitoff %= WHIRLPOOL_BBLOCK; } if (bitrem) c->data[byteoff] = b << (8 - bitrem); } else { /* remaining less than or equal to 8 bits */ b = (inp[0] << inpgap) & 0xff; if (bitrem) c->data[byteoff++] |= b >> bitrem; else c->data[byteoff++] = b; bitoff += (unsigned int)bits; if (bitoff == WHIRLPOOL_BBLOCK) { whirlpool_block(c, c->data, 1); byteoff = 0; bitoff %= WHIRLPOOL_BBLOCK; } if (bitrem) c->data[byteoff] = b << (8 - bitrem); bits = 0; } c->bitoff = bitoff; } } } int WHIRLPOOL_Final(unsigned char *md, WHIRLPOOL_CTX *c) { unsigned int bitoff = c->bitoff, byteoff = bitoff / 8; size_t i, j, v; unsigned char *p; bitoff %= 8; if (bitoff) c->data[byteoff] |= 0x80 >> bitoff; else c->data[byteoff] = 0x80; byteoff++; /* pad with zeros */ if (byteoff > (WHIRLPOOL_BBLOCK / 8 - WHIRLPOOL_COUNTER)) { if (byteoff < WHIRLPOOL_BBLOCK / 8) memset(&c->data[byteoff], 0, WHIRLPOOL_BBLOCK / 8 - byteoff); whirlpool_block(c, c->data, 1); byteoff = 0; } if (byteoff < (WHIRLPOOL_BBLOCK / 8 - WHIRLPOOL_COUNTER)) memset(&c->data[byteoff], 0, (WHIRLPOOL_BBLOCK / 8 - WHIRLPOOL_COUNTER) - byteoff); /* smash 256-bit c->bitlen in big-endian order */ p = &c->data[WHIRLPOOL_BBLOCK / 8 - 1]; /* last byte in c->data */ for (i = 0; i < WHIRLPOOL_COUNTER / sizeof(size_t); i++) for (v = c->bitlen[i], j = 0; j < sizeof(size_t); j++, v >>= 8) *p-- = (unsigned char)(v & 0xff); whirlpool_block(c, c->data, 1); if (md) { memcpy(md, c->H.c, WHIRLPOOL_DIGEST_LENGTH); OPENSSL_cleanse(c, sizeof(*c)); return 1; } return 0; } unsigned char *WHIRLPOOL(const void *inp, size_t bytes, unsigned char *md) { WHIRLPOOL_CTX ctx; static unsigned char m[WHIRLPOOL_DIGEST_LENGTH]; if (md == NULL) md = m; WHIRLPOOL_Init(&ctx); WHIRLPOOL_Update(&ctx, inp, bytes); WHIRLPOOL_Final(md, &ctx); return md; }
./openssl/crypto/whrlpool/wp_local.h
/* * Copyright 2005-2016 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 <openssl/whrlpool.h> void whirlpool_block(WHIRLPOOL_CTX *, const void *, size_t);
./openssl/crypto/evp/e_des.c
/* * Copyright 1995-2021 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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_DES # include <openssl/evp.h> # include <openssl/objects.h> # include "crypto/evp.h" # include <openssl/des.h> # include <openssl/rand.h> # include "evp_local.h" typedef struct { union { OSSL_UNION_ALIGN; DES_key_schedule ks; } ks; union { void (*cbc) (const void *, void *, size_t, const DES_key_schedule *, unsigned char *); } stream; } EVP_DES_KEY; # if defined(AES_ASM) && (defined(__sparc) || defined(__sparc__)) /* ----------^^^ this is not a typo, just a way to detect that * assembler support was in general requested... */ # include "crypto/sparc_arch.h" # define SPARC_DES_CAPABLE (OPENSSL_sparcv9cap_P[1] & CFR_DES) void des_t4_key_expand(const void *key, DES_key_schedule *ks); void des_t4_cbc_encrypt(const void *inp, void *out, size_t len, const DES_key_schedule *ks, unsigned char iv[8]); void des_t4_cbc_decrypt(const void *inp, void *out, size_t len, const DES_key_schedule *ks, unsigned char iv[8]); # endif static int des_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); static int des_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr); /* * Because of various casts and different names can't use * IMPLEMENT_BLOCK_CIPHER */ static int des_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { BLOCK_CIPHER_ecb_loop() DES_ecb_encrypt((DES_cblock *)(in + i), (DES_cblock *)(out + i), EVP_CIPHER_CTX_get_cipher_data(ctx), EVP_CIPHER_CTX_is_encrypting(ctx)); return 1; } static int des_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { while (inl >= EVP_MAXCHUNK) { int num = EVP_CIPHER_CTX_get_num(ctx); DES_ofb64_encrypt(in, out, (long)EVP_MAXCHUNK, EVP_CIPHER_CTX_get_cipher_data(ctx), (DES_cblock *)ctx->iv, &num); EVP_CIPHER_CTX_set_num(ctx, num); inl -= EVP_MAXCHUNK; in += EVP_MAXCHUNK; out += EVP_MAXCHUNK; } if (inl) { int num = EVP_CIPHER_CTX_get_num(ctx); DES_ofb64_encrypt(in, out, (long)inl, EVP_CIPHER_CTX_get_cipher_data(ctx), (DES_cblock *)ctx->iv, &num); EVP_CIPHER_CTX_set_num(ctx, num); } return 1; } static int des_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { EVP_DES_KEY *dat = (EVP_DES_KEY *) EVP_CIPHER_CTX_get_cipher_data(ctx); if (dat->stream.cbc != NULL) { (*dat->stream.cbc) (in, out, inl, &dat->ks.ks, ctx->iv); return 1; } while (inl >= EVP_MAXCHUNK) { DES_ncbc_encrypt(in, out, (long)EVP_MAXCHUNK, EVP_CIPHER_CTX_get_cipher_data(ctx), (DES_cblock *)ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); inl -= EVP_MAXCHUNK; in += EVP_MAXCHUNK; out += EVP_MAXCHUNK; } if (inl) DES_ncbc_encrypt(in, out, (long)inl, EVP_CIPHER_CTX_get_cipher_data(ctx), (DES_cblock *)ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); return 1; } static int des_cfb64_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { while (inl >= EVP_MAXCHUNK) { int num = EVP_CIPHER_CTX_get_num(ctx); DES_cfb64_encrypt(in, out, (long)EVP_MAXCHUNK, EVP_CIPHER_CTX_get_cipher_data(ctx), (DES_cblock *)ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx)); EVP_CIPHER_CTX_set_num(ctx, num); inl -= EVP_MAXCHUNK; in += EVP_MAXCHUNK; out += EVP_MAXCHUNK; } if (inl) { int num = EVP_CIPHER_CTX_get_num(ctx); DES_cfb64_encrypt(in, out, (long)inl, EVP_CIPHER_CTX_get_cipher_data(ctx), (DES_cblock *)ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx)); EVP_CIPHER_CTX_set_num(ctx, num); } return 1; } /* * Although we have a CFB-r implementation for DES, it doesn't pack the right * way, so wrap it here */ static int des_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { size_t n, chunk = EVP_MAXCHUNK / 8; unsigned char c[1]; unsigned char d[1] = { 0 }; /* Appease Coverity */ if (inl < chunk) chunk = inl; while (inl && inl >= chunk) { for (n = 0; n < chunk * 8; ++n) { c[0] = (in[n / 8] & (1 << (7 - n % 8))) ? 0x80 : 0; DES_cfb_encrypt(c, d, 1, 1, EVP_CIPHER_CTX_get_cipher_data(ctx), (DES_cblock *)ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); out[n / 8] = (out[n / 8] & ~(0x80 >> (unsigned int)(n % 8))) | ((d[0] & 0x80) >> (unsigned int)(n % 8)); } inl -= chunk; in += chunk; out += chunk; if (inl < chunk) chunk = inl; } return 1; } static int des_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { while (inl >= EVP_MAXCHUNK) { DES_cfb_encrypt(in, out, 8, (long)EVP_MAXCHUNK, EVP_CIPHER_CTX_get_cipher_data(ctx), (DES_cblock *)ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); inl -= EVP_MAXCHUNK; in += EVP_MAXCHUNK; out += EVP_MAXCHUNK; } if (inl) DES_cfb_encrypt(in, out, 8, (long)inl, EVP_CIPHER_CTX_get_cipher_data(ctx), (DES_cblock *)ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); return 1; } BLOCK_CIPHER_defs(des, EVP_DES_KEY, NID_des, 8, 8, 8, 64, EVP_CIPH_RAND_KEY, des_init_key, NULL, EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, des_ctrl) BLOCK_CIPHER_def_cfb(des, EVP_DES_KEY, NID_des, 8, 8, 1, EVP_CIPH_RAND_KEY, des_init_key, NULL, EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, des_ctrl) BLOCK_CIPHER_def_cfb(des, EVP_DES_KEY, NID_des, 8, 8, 8, EVP_CIPH_RAND_KEY, des_init_key, NULL, EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, des_ctrl) static int des_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { DES_cblock *deskey = (DES_cblock *)key; EVP_DES_KEY *dat = (EVP_DES_KEY *) EVP_CIPHER_CTX_get_cipher_data(ctx); dat->stream.cbc = NULL; # if defined(SPARC_DES_CAPABLE) if (SPARC_DES_CAPABLE) { int mode = EVP_CIPHER_CTX_get_mode(ctx); if (mode == EVP_CIPH_CBC_MODE) { des_t4_key_expand(key, &dat->ks.ks); dat->stream.cbc = enc ? des_t4_cbc_encrypt : des_t4_cbc_decrypt; return 1; } } # endif DES_set_key_unchecked(deskey, EVP_CIPHER_CTX_get_cipher_data(ctx)); return 1; } static int des_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { switch (type) { case EVP_CTRL_RAND_KEY: if (RAND_priv_bytes(ptr, 8) <= 0) return 0; DES_set_odd_parity((DES_cblock *)ptr); return 1; default: return -1; } } #endif
./openssl/crypto/evp/bio_enc.c
/* * Copyright 1995-2023 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 */ #define OPENSSL_SUPPRESS_DEPRECATED /* for BIO_get_callback */ #include <stdio.h> #include <errno.h> #include "internal/cryptlib.h" #include <openssl/buffer.h> #include <openssl/evp.h> #include "internal/bio.h" static int enc_write(BIO *h, const char *buf, int num); static int enc_read(BIO *h, char *buf, int size); static long enc_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int enc_new(BIO *h); static int enc_free(BIO *data); static long enc_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fps); #define ENC_BLOCK_SIZE (1024*4) #define ENC_MIN_CHUNK (256) #define BUF_OFFSET (ENC_MIN_CHUNK + EVP_MAX_BLOCK_LENGTH) typedef struct enc_struct { int buf_len; int buf_off; int cont; /* <= 0 when finished */ int finished; int ok; /* bad decrypt */ EVP_CIPHER_CTX *cipher; unsigned char *read_start, *read_end; /* * buf is larger than ENC_BLOCK_SIZE because EVP_DecryptUpdate can return * up to a block more data than is presented to it */ unsigned char buf[BUF_OFFSET + ENC_BLOCK_SIZE]; } BIO_ENC_CTX; static const BIO_METHOD methods_enc = { BIO_TYPE_CIPHER, "cipher", bwrite_conv, enc_write, bread_conv, enc_read, NULL, /* enc_puts, */ NULL, /* enc_gets, */ enc_ctrl, enc_new, enc_free, enc_callback_ctrl, }; const BIO_METHOD *BIO_f_cipher(void) { return &methods_enc; } static int enc_new(BIO *bi) { BIO_ENC_CTX *ctx; if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) return 0; ctx->cipher = EVP_CIPHER_CTX_new(); if (ctx->cipher == NULL) { OPENSSL_free(ctx); return 0; } ctx->cont = 1; ctx->ok = 1; ctx->read_end = ctx->read_start = &(ctx->buf[BUF_OFFSET]); BIO_set_data(bi, ctx); BIO_set_init(bi, 1); return 1; } static int enc_free(BIO *a) { BIO_ENC_CTX *b; if (a == NULL) return 0; b = BIO_get_data(a); if (b == NULL) return 0; EVP_CIPHER_CTX_free(b->cipher); OPENSSL_clear_free(b, sizeof(BIO_ENC_CTX)); BIO_set_data(a, NULL); BIO_set_init(a, 0); return 1; } static int enc_read(BIO *b, char *out, int outl) { int ret = 0, i, blocksize; BIO_ENC_CTX *ctx; BIO *next; if (out == NULL) return 0; ctx = BIO_get_data(b); next = BIO_next(b); if ((ctx == NULL) || (next == NULL)) return 0; /* First check if there are bytes decoded/encoded */ if (ctx->buf_len > 0) { i = ctx->buf_len - ctx->buf_off; if (i > outl) i = outl; memcpy(out, &(ctx->buf[ctx->buf_off]), i); ret = i; out += i; outl -= i; ctx->buf_off += i; if (ctx->buf_len == ctx->buf_off) { ctx->buf_len = 0; ctx->buf_off = 0; } } blocksize = EVP_CIPHER_CTX_get_block_size(ctx->cipher); if (blocksize == 1) blocksize = 0; /* * At this point, we have room of outl bytes and an empty buffer, so we * should read in some more. */ while (outl > 0) { if (ctx->cont <= 0) break; if (ctx->read_start == ctx->read_end) { /* time to read more data */ ctx->read_end = ctx->read_start = &(ctx->buf[BUF_OFFSET]); i = BIO_read(next, ctx->read_start, ENC_BLOCK_SIZE); if (i > 0) ctx->read_end += i; } else { i = ctx->read_end - ctx->read_start; } if (i <= 0) { /* Should be continue next time we are called? */ if (!BIO_should_retry(next)) { ctx->cont = i; i = EVP_CipherFinal_ex(ctx->cipher, ctx->buf, &(ctx->buf_len)); ctx->ok = i; ctx->buf_off = 0; } else { ret = (ret == 0) ? i : ret; break; } } else { if (outl > ENC_MIN_CHUNK) { /* * Depending on flags block cipher decrypt can write * one extra block and then back off, i.e. output buffer * has to accommodate extra block... */ int j = outl - blocksize, buf_len; if (!EVP_CipherUpdate(ctx->cipher, (unsigned char *)out, &buf_len, ctx->read_start, i > j ? j : i)) { BIO_clear_retry_flags(b); return 0; } ret += buf_len; out += buf_len; outl -= buf_len; if ((i -= j) <= 0) { ctx->read_start = ctx->read_end; continue; } ctx->read_start += j; } if (i > ENC_MIN_CHUNK) i = ENC_MIN_CHUNK; if (!EVP_CipherUpdate(ctx->cipher, ctx->buf, &ctx->buf_len, ctx->read_start, i)) { BIO_clear_retry_flags(b); ctx->ok = 0; return 0; } ctx->read_start += i; ctx->cont = 1; /* * Note: it is possible for EVP_CipherUpdate to decrypt zero * bytes because this is or looks like the final block: if this * happens we should retry and either read more data or decrypt * the final block */ if (ctx->buf_len == 0) continue; } if (ctx->buf_len <= outl) i = ctx->buf_len; else i = outl; if (i <= 0) break; memcpy(out, ctx->buf, i); ret += i; ctx->buf_off = i; outl -= i; out += i; } BIO_clear_retry_flags(b); BIO_copy_next_retry(b); return ((ret == 0) ? ctx->cont : ret); } static int enc_write(BIO *b, const char *in, int inl) { int ret = 0, n, i; BIO_ENC_CTX *ctx; BIO *next; ctx = BIO_get_data(b); next = BIO_next(b); if ((ctx == NULL) || (next == NULL)) return 0; ret = inl; BIO_clear_retry_flags(b); n = ctx->buf_len - ctx->buf_off; while (n > 0) { i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n); if (i <= 0) { BIO_copy_next_retry(b); return i; } ctx->buf_off += i; n -= i; } /* at this point all pending data has been written */ if ((in == NULL) || (inl <= 0)) return 0; ctx->buf_off = 0; while (inl > 0) { n = (inl > ENC_BLOCK_SIZE) ? ENC_BLOCK_SIZE : inl; if (!EVP_CipherUpdate(ctx->cipher, ctx->buf, &ctx->buf_len, (const unsigned char *)in, n)) { BIO_clear_retry_flags(b); ctx->ok = 0; return 0; } inl -= n; in += n; ctx->buf_off = 0; n = ctx->buf_len; while (n > 0) { i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n); if (i <= 0) { BIO_copy_next_retry(b); return (ret == inl) ? i : ret - inl; } n -= i; ctx->buf_off += i; } ctx->buf_len = 0; ctx->buf_off = 0; } BIO_copy_next_retry(b); return ret; } static long enc_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO *dbio; BIO_ENC_CTX *ctx, *dctx; long ret = 1; int i; EVP_CIPHER_CTX **c_ctx; BIO *next; int pend; ctx = BIO_get_data(b); next = BIO_next(b); if (ctx == NULL) return 0; switch (cmd) { case BIO_CTRL_RESET: ctx->ok = 1; ctx->finished = 0; if (!EVP_CipherInit_ex(ctx->cipher, NULL, NULL, NULL, NULL, EVP_CIPHER_CTX_is_encrypting(ctx->cipher))) return 0; ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_EOF: /* More to read */ if (ctx->cont <= 0) ret = 1; else ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_WPENDING: ret = ctx->buf_len - ctx->buf_off; if (ret <= 0) ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_PENDING: /* More to read in buffer */ ret = ctx->buf_len - ctx->buf_off; if (ret <= 0) ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_FLUSH: /* do a final write */ again: while (ctx->buf_len != ctx->buf_off) { pend = ctx->buf_len - ctx->buf_off; i = enc_write(b, NULL, 0); /* * i should never be > 0 here because we didn't ask to write any * new data. We stop if we get an error or we failed to make any * progress writing pending data. */ if (i < 0 || (ctx->buf_len - ctx->buf_off) == pend) return i; } if (!ctx->finished) { ctx->finished = 1; ctx->buf_off = 0; ret = EVP_CipherFinal_ex(ctx->cipher, (unsigned char *)ctx->buf, &(ctx->buf_len)); ctx->ok = (int)ret; if (ret <= 0) break; /* push out the bytes */ goto again; } /* Finally flush the underlying BIO */ ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_C_GET_CIPHER_STATUS: ret = (long)ctx->ok; break; case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_C_GET_CIPHER_CTX: c_ctx = (EVP_CIPHER_CTX **)ptr; *c_ctx = ctx->cipher; BIO_set_init(b, 1); break; case BIO_CTRL_DUP: dbio = (BIO *)ptr; dctx = BIO_get_data(dbio); dctx->cipher = EVP_CIPHER_CTX_new(); if (dctx->cipher == NULL) return 0; ret = EVP_CIPHER_CTX_copy(dctx->cipher, ctx->cipher); if (ret) BIO_set_init(dbio, 1); break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static long enc_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } int BIO_set_cipher(BIO *b, const EVP_CIPHER *c, const unsigned char *k, const unsigned char *i, int e) { BIO_ENC_CTX *ctx; BIO_callback_fn_ex callback_ex; #ifndef OPENSSL_NO_DEPRECATED_3_0 long (*callback) (struct bio_st *, int, const char *, int, long, long) = NULL; #endif ctx = BIO_get_data(b); if (ctx == NULL) return 0; if ((callback_ex = BIO_get_callback_ex(b)) != NULL) { if (callback_ex(b, BIO_CB_CTRL, (const char *)c, 0, BIO_CTRL_SET, e, 1, NULL) <= 0) return 0; } #ifndef OPENSSL_NO_DEPRECATED_3_0 else { callback = BIO_get_callback(b); if ((callback != NULL) && (callback(b, BIO_CB_CTRL, (const char *)c, BIO_CTRL_SET, e, 0L) <= 0)) return 0; } #endif BIO_set_init(b, 1); if (!EVP_CipherInit_ex(ctx->cipher, c, NULL, k, i, e)) return 0; if (callback_ex != NULL) return callback_ex(b, BIO_CB_CTRL | BIO_CB_RETURN, (const char *)c, 0, BIO_CTRL_SET, e, 1, NULL); #ifndef OPENSSL_NO_DEPRECATED_3_0 else if (callback != NULL) return callback(b, BIO_CB_CTRL, (const char *)c, BIO_CTRL_SET, e, 1L); #endif return 1; }
./openssl/crypto/evp/e_rc5.c
/* * Copyright 1995-2021 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 */ /* * RC5 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_RC5 # include <openssl/evp.h> # include "crypto/evp.h" # include <openssl/objects.h> # include "evp_local.h" # include <openssl/rc5.h> static int r_32_12_16_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); static int rc5_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr); typedef struct { int rounds; /* number of rounds */ RC5_32_KEY ks; /* key schedule */ } EVP_RC5_KEY; # define data(ctx) EVP_C_DATA(EVP_RC5_KEY,ctx) IMPLEMENT_BLOCK_CIPHER(rc5_32_12_16, ks, RC5_32, EVP_RC5_KEY, NID_rc5, 8, RC5_32_KEY_LENGTH, 8, 64, EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CTRL_INIT, r_32_12_16_init_key, NULL, NULL, NULL, rc5_ctrl) static int rc5_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { switch (type) { case EVP_CTRL_INIT: data(c)->rounds = RC5_12_ROUNDS; return 1; case EVP_CTRL_GET_RC5_ROUNDS: *(int *)ptr = data(c)->rounds; return 1; case EVP_CTRL_SET_RC5_ROUNDS: switch (arg) { case RC5_8_ROUNDS: case RC5_12_ROUNDS: case RC5_16_ROUNDS: data(c)->rounds = arg; return 1; default: ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_NUMBER_OF_ROUNDS); return 0; } default: return -1; } } static int r_32_12_16_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { const int key_len = EVP_CIPHER_CTX_get_key_length(ctx); if (key_len > 255 || key_len < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_BAD_KEY_LENGTH); return 0; } return RC5_32_set_key(&data(ctx)->ks, key_len, key, data(ctx)->rounds); } #endif
./openssl/crypto/evp/p_dec.c
/* * Copyright 1995-2021 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 */ /* We need to use the deprecated RSA low level calls */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include "crypto/evp.h" int EVP_PKEY_decrypt_old(unsigned char *key, const unsigned char *ek, int ekl, EVP_PKEY *priv) { int ret = -1; RSA *rsa = NULL; if (EVP_PKEY_get_id(priv) != EVP_PKEY_RSA) { ERR_raise(ERR_LIB_EVP, EVP_R_PUBLIC_KEY_NOT_RSA); goto err; } rsa = evp_pkey_get0_RSA_int(priv); if (rsa == NULL) goto err; ret = RSA_private_decrypt(ekl, ek, key, rsa, RSA_PKCS1_PADDING); err: return ret; }
./openssl/crypto/evp/ec_ctrl.c
/* * Copyright 2020-2023 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 "internal/deprecated.h" #include <openssl/core_names.h> #include <openssl/err.h> #include <openssl/ec.h> #include "crypto/evp.h" #include "crypto/ec.h" /* * This file is meant to contain functions to provide EVP_PKEY support for EC * keys. */ static ossl_inline int evp_pkey_ctx_getset_ecdh_param_checks(const EVP_PKEY_CTX *ctx) { if (ctx == NULL || !EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* If key type not EC return error */ if (evp_pkey_ctx_is_legacy(ctx) && ctx->pmeth != NULL && ctx->pmeth->pkey_id != EVP_PKEY_EC) return -1; return 1; } int EVP_PKEY_CTX_set_ecdh_cofactor_mode(EVP_PKEY_CTX *ctx, int cofactor_mode) { int ret; OSSL_PARAM params[2], *p = params; ret = evp_pkey_ctx_getset_ecdh_param_checks(ctx); if (ret != 1) return ret; /* * Valid input values are: * * 0 for disable * * 1 for enable * * -1 for reset to default for associated priv key */ if (cofactor_mode < -1 || cofactor_mode > 1) { /* Uses the same return value of pkey_ec_ctrl() */ return -2; } *p++ = OSSL_PARAM_construct_int(OSSL_EXCHANGE_PARAM_EC_ECDH_COFACTOR_MODE, &cofactor_mode); *p++ = OSSL_PARAM_construct_end(); ret = evp_pkey_ctx_set_params_strict(ctx, params); if (ret == -2) ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return ret; } int EVP_PKEY_CTX_get_ecdh_cofactor_mode(EVP_PKEY_CTX *ctx) { int ret, mode; OSSL_PARAM params[2], *p = params; ret = evp_pkey_ctx_getset_ecdh_param_checks(ctx); if (ret != 1) return ret; *p++ = OSSL_PARAM_construct_int(OSSL_EXCHANGE_PARAM_EC_ECDH_COFACTOR_MODE, &mode); *p++ = OSSL_PARAM_construct_end(); ret = evp_pkey_ctx_get_params_strict(ctx, params); switch (ret) { case -2: ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); break; case 1: ret = mode; if (mode < 0 || mode > 1) { /* * The provider should return either 0 or 1, any other value is a * provider error. */ ret = -1; } break; default: ret = -1; break; } return ret; } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_ecdh_kdf_type(EVP_PKEY_CTX *ctx, int kdf) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_TYPE, kdf, NULL); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_get_ecdh_kdf_type(EVP_PKEY_CTX *ctx) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_TYPE, -2, NULL); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_ecdh_kdf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_MD, 0, (void *)(md)); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_get_ecdh_kdf_md(EVP_PKEY_CTX *ctx, const EVP_MD **pmd) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_MD, 0, (void *)(pmd)); } int EVP_PKEY_CTX_set_ecdh_kdf_outlen(EVP_PKEY_CTX *ctx, int outlen) { int ret; size_t len = outlen; OSSL_PARAM params[2], *p = params; ret = evp_pkey_ctx_getset_ecdh_param_checks(ctx); if (ret != 1) return ret; if (outlen <= 0) { /* * This would ideally be -1 or 0, but we have to retain compatibility * with legacy behaviour of EVP_PKEY_CTX_ctrl() which returned -2 if * in <= 0 */ return -2; } *p++ = OSSL_PARAM_construct_size_t(OSSL_EXCHANGE_PARAM_KDF_OUTLEN, &len); *p++ = OSSL_PARAM_construct_end(); ret = evp_pkey_ctx_set_params_strict(ctx, params); if (ret == -2) ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return ret; } int EVP_PKEY_CTX_get_ecdh_kdf_outlen(EVP_PKEY_CTX *ctx, int *plen) { size_t len = UINT_MAX; int ret; OSSL_PARAM params[2], *p = params; ret = evp_pkey_ctx_getset_ecdh_param_checks(ctx); if (ret != 1) return ret; *p++ = OSSL_PARAM_construct_size_t(OSSL_EXCHANGE_PARAM_KDF_OUTLEN, &len); *p++ = OSSL_PARAM_construct_end(); ret = evp_pkey_ctx_get_params_strict(ctx, params); switch (ret) { case -2: ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); break; case 1: if (len <= INT_MAX) *plen = (int)len; else ret = -1; break; default: ret = -1; break; } return ret; } int EVP_PKEY_CTX_set0_ecdh_kdf_ukm(EVP_PKEY_CTX *ctx, unsigned char *ukm, int len) { int ret; OSSL_PARAM params[2], *p = params; ret = evp_pkey_ctx_getset_ecdh_param_checks(ctx); if (ret != 1) return ret; *p++ = OSSL_PARAM_construct_octet_string(OSSL_EXCHANGE_PARAM_KDF_UKM, /* * Cast away the const. This is read * only so should be safe */ (void *)ukm, (size_t)len); *p++ = OSSL_PARAM_construct_end(); ret = evp_pkey_ctx_set_params_strict(ctx, params); switch (ret) { case -2: ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); break; case 1: OPENSSL_free(ukm); break; } return ret; } #ifndef OPENSSL_NO_DEPRECATED_3_0 int EVP_PKEY_CTX_get0_ecdh_kdf_ukm(EVP_PKEY_CTX *ctx, unsigned char **pukm) { size_t ukmlen; int ret; OSSL_PARAM params[2], *p = params; ret = evp_pkey_ctx_getset_ecdh_param_checks(ctx); if (ret != 1) return ret; *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_EXCHANGE_PARAM_KDF_UKM, (void **)pukm, 0); *p++ = OSSL_PARAM_construct_end(); ret = evp_pkey_ctx_get_params_strict(ctx, params); switch (ret) { case -2: ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); break; case 1: ret = -1; ukmlen = params[0].return_size; if (ukmlen <= INT_MAX) ret = (int)ukmlen; break; default: ret = -1; break; } return ret; } #endif #ifndef FIPS_MODULE /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. * ASN1_OBJECT (which would be converted to text internally)? */ int EVP_PKEY_CTX_set_ec_paramgen_curve_nid(EVP_PKEY_CTX *ctx, int nid) { int keytype = nid == EVP_PKEY_SM2 ? EVP_PKEY_SM2 : EVP_PKEY_EC; return EVP_PKEY_CTX_ctrl(ctx, keytype, EVP_PKEY_OP_TYPE_GEN, EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, nid, NULL); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_ec_param_enc(EVP_PKEY_CTX *ctx, int param_enc) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, EVP_PKEY_OP_TYPE_GEN, EVP_PKEY_CTRL_EC_PARAM_ENC, param_enc, NULL); } #endif
./openssl/crypto/evp/dh_support.c
/* * Copyright 2020-2021 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 <string.h> /* strcmp */ #include <openssl/dh.h> #include "internal/nelem.h" #include "crypto/dh.h" typedef struct dh_name2id_st{ const char *name; int id; int type; } DH_GENTYPE_NAME2ID; /* Indicates that the paramgen_type can be used for either DH or DHX */ #define TYPE_ANY -1 #ifndef OPENSSL_NO_DH # define TYPE_DH DH_FLAG_TYPE_DH # define TYPE_DHX DH_FLAG_TYPE_DHX #else # define TYPE_DH 0 # define TYPE_DHX 0 #endif static const DH_GENTYPE_NAME2ID dhtype2id[] = { { "group", DH_PARAMGEN_TYPE_GROUP, TYPE_ANY }, { "generator", DH_PARAMGEN_TYPE_GENERATOR, TYPE_DH }, { "fips186_4", DH_PARAMGEN_TYPE_FIPS_186_4, TYPE_DHX }, { "fips186_2", DH_PARAMGEN_TYPE_FIPS_186_2, TYPE_DHX }, }; const char *ossl_dh_gen_type_id2name(int id) { size_t i; for (i = 0; i < OSSL_NELEM(dhtype2id); ++i) { if (dhtype2id[i].id == id) return dhtype2id[i].name; } return NULL; } #ifndef OPENSSL_NO_DH int ossl_dh_gen_type_name2id(const char *name, int type) { size_t i; for (i = 0; i < OSSL_NELEM(dhtype2id); ++i) { if ((dhtype2id[i].type == TYPE_ANY || type == dhtype2id[i].type) && strcmp(dhtype2id[i].name, name) == 0) return dhtype2id[i].id; } return -1; } #endif
./openssl/crypto/evp/p_verify.c
/* * Copyright 1995-2023 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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include "crypto/evp.h" int EVP_VerifyFinal_ex(EVP_MD_CTX *ctx, const unsigned char *sigbuf, unsigned int siglen, EVP_PKEY *pkey, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char m[EVP_MAX_MD_SIZE]; unsigned int m_len = 0; int i = 0; EVP_PKEY_CTX *pkctx = NULL; if (EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_FINALISE)) { if (!EVP_DigestFinal_ex(ctx, m, &m_len)) goto err; } else { int rv = 0; EVP_MD_CTX *tmp_ctx = EVP_MD_CTX_new(); if (tmp_ctx == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return 0; } rv = EVP_MD_CTX_copy_ex(tmp_ctx, ctx); if (rv) rv = EVP_DigestFinal_ex(tmp_ctx, m, &m_len); else rv = EVP_DigestFinal_ex(ctx, m, &m_len); EVP_MD_CTX_free(tmp_ctx); if (!rv) return 0; } i = -1; pkctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (pkctx == NULL) goto err; if (EVP_PKEY_verify_init(pkctx) <= 0) goto err; if (EVP_PKEY_CTX_set_signature_md(pkctx, EVP_MD_CTX_get0_md(ctx)) <= 0) goto err; i = EVP_PKEY_verify(pkctx, sigbuf, siglen, m, m_len); err: EVP_PKEY_CTX_free(pkctx); return i; } int EVP_VerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sigbuf, unsigned int siglen, EVP_PKEY *pkey) { return EVP_VerifyFinal_ex(ctx, sigbuf, siglen, pkey, NULL, NULL); }
./openssl/crypto/evp/m_sigver.c
/* * Copyright 2006-2023 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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/objects.h> #include "crypto/evp.h" #include "internal/provider.h" #include "internal/numbers.h" /* includes SIZE_MAX */ #include "evp_local.h" #ifndef FIPS_MODULE static int update(EVP_MD_CTX *ctx, const void *data, size_t datalen) { ERR_raise(ERR_LIB_EVP, EVP_R_ONLY_ONESHOT_SUPPORTED); return 0; } /* * If we get the "NULL" md then the name comes back as "UNDEF". We want to use * NULL for this. */ static const char *canon_mdname(const char *mdname) { if (mdname != NULL && strcmp(mdname, "UNDEF") == 0) return NULL; return mdname; } static int do_sigver_init(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const EVP_MD *type, const char *mdname, OSSL_LIB_CTX *libctx, const char *props, ENGINE *e, EVP_PKEY *pkey, int ver, const OSSL_PARAM params[]) { EVP_PKEY_CTX *locpctx = NULL; EVP_SIGNATURE *signature = NULL; EVP_KEYMGMT *tmp_keymgmt = NULL; const OSSL_PROVIDER *tmp_prov = NULL; const char *supported_sig = NULL; char locmdname[80] = ""; /* 80 chars should be enough */ void *provkey = NULL; int ret, iter, reinit = 1; if (!evp_md_ctx_free_algctx(ctx)) return 0; if (ctx->pctx == NULL) { reinit = 0; if (e == NULL) ctx->pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, props); else ctx->pctx = EVP_PKEY_CTX_new(pkey, e); } if (ctx->pctx == NULL) return 0; EVP_MD_CTX_clear_flags(ctx, EVP_MD_CTX_FLAG_FINALISED); locpctx = ctx->pctx; ERR_set_mark(); if (evp_pkey_ctx_is_legacy(locpctx)) goto legacy; /* do not reinitialize if pkey is set or operation is different */ if (reinit && (pkey != NULL || locpctx->operation != (ver ? EVP_PKEY_OP_VERIFYCTX : EVP_PKEY_OP_SIGNCTX) || (signature = locpctx->op.sig.signature) == NULL || locpctx->op.sig.algctx == NULL)) reinit = 0; if (props == NULL) props = locpctx->propquery; if (locpctx->pkey == NULL) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_NO_KEY_SET); goto err; } if (!reinit) { evp_pkey_ctx_free_old_ops(locpctx); } else { if (mdname == NULL && type == NULL) mdname = canon_mdname(EVP_MD_get0_name(ctx->reqdigest)); goto reinitialize; } /* * Try to derive the supported signature from |locpctx->keymgmt|. */ if (!ossl_assert(locpctx->pkey->keymgmt == NULL || locpctx->pkey->keymgmt == locpctx->keymgmt)) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); goto err; } supported_sig = evp_keymgmt_util_query_operation_name(locpctx->keymgmt, OSSL_OP_SIGNATURE); if (supported_sig == NULL) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } /* * We perform two iterations: * * 1. Do the normal signature fetch, using the fetching data given by * the EVP_PKEY_CTX. * 2. Do the provider specific signature fetch, from the same provider * as |ctx->keymgmt| * * We then try to fetch the keymgmt from the same provider as the * signature, and try to export |ctx->pkey| to that keymgmt (when * this keymgmt happens to be the same as |ctx->keymgmt|, the export * is a no-op, but we call it anyway to not complicate the code even * more). * If the export call succeeds (returns a non-NULL provider key pointer), * we're done and can perform the operation itself. If not, we perform * the second iteration, or jump to legacy. */ for (iter = 1, provkey = NULL; iter < 3 && provkey == NULL; iter++) { EVP_KEYMGMT *tmp_keymgmt_tofree = NULL; /* * If we're on the second iteration, free the results from the first. * They are NULL on the first iteration, so no need to check what * iteration we're on. */ EVP_SIGNATURE_free(signature); EVP_KEYMGMT_free(tmp_keymgmt); switch (iter) { case 1: signature = EVP_SIGNATURE_fetch(locpctx->libctx, supported_sig, locpctx->propquery); if (signature != NULL) tmp_prov = EVP_SIGNATURE_get0_provider(signature); break; case 2: tmp_prov = EVP_KEYMGMT_get0_provider(locpctx->keymgmt); signature = evp_signature_fetch_from_prov((OSSL_PROVIDER *)tmp_prov, supported_sig, locpctx->propquery); if (signature == NULL) goto legacy; break; } if (signature == NULL) continue; /* * Ensure that the key is provided, either natively, or as a cached * export. We start by fetching the keymgmt with the same name as * |locpctx->pkey|, but from the provider of the signature method, using * the same property query as when fetching the signature method. * With the keymgmt we found (if we did), we try to export |locpctx->pkey| * to it (evp_pkey_export_to_provider() is smart enough to only actually * export it if |tmp_keymgmt| is different from |locpctx->pkey|'s keymgmt) */ tmp_keymgmt_tofree = tmp_keymgmt = evp_keymgmt_fetch_from_prov((OSSL_PROVIDER *)tmp_prov, EVP_KEYMGMT_get0_name(locpctx->keymgmt), locpctx->propquery); if (tmp_keymgmt != NULL) provkey = evp_pkey_export_to_provider(locpctx->pkey, locpctx->libctx, &tmp_keymgmt, locpctx->propquery); if (tmp_keymgmt == NULL) EVP_KEYMGMT_free(tmp_keymgmt_tofree); } if (provkey == NULL) { EVP_SIGNATURE_free(signature); ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } ERR_pop_to_mark(); /* No more legacy from here down to legacy: */ locpctx->op.sig.signature = signature; locpctx->operation = ver ? EVP_PKEY_OP_VERIFYCTX : EVP_PKEY_OP_SIGNCTX; locpctx->op.sig.algctx = signature->newctx(ossl_provider_ctx(signature->prov), props); if (locpctx->op.sig.algctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } reinitialize: if (pctx != NULL) *pctx = locpctx; if (type != NULL) { ctx->reqdigest = type; if (mdname == NULL) mdname = canon_mdname(EVP_MD_get0_name(type)); } else { if (mdname == NULL && !reinit) { if (evp_keymgmt_util_get_deflt_digest_name(tmp_keymgmt, provkey, locmdname, sizeof(locmdname)) > 0) { mdname = canon_mdname(locmdname); } } if (mdname != NULL) { /* * We're about to get a new digest so clear anything associated with * an old digest. */ evp_md_ctx_clear_digest(ctx, 1, 0); /* legacy code support for engines */ ERR_set_mark(); /* * This might be requested by a later call to EVP_MD_CTX_get0_md(). * In that case the "explicit fetch" rules apply for that * function (as per man pages), i.e. the ref count is not updated * so the EVP_MD should not be used beyond the lifetime of the * EVP_MD_CTX. */ ctx->fetched_digest = EVP_MD_fetch(locpctx->libctx, mdname, props); if (ctx->fetched_digest != NULL) { ctx->digest = ctx->reqdigest = ctx->fetched_digest; } else { /* legacy engine support : remove the mark when this is deleted */ ctx->reqdigest = ctx->digest = EVP_get_digestbyname(mdname); if (ctx->digest == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } } (void)ERR_pop_to_mark(); } } if (ver) { if (signature->digest_verify_init == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } ret = signature->digest_verify_init(locpctx->op.sig.algctx, mdname, provkey, params); } else { if (signature->digest_sign_init == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } ret = signature->digest_sign_init(locpctx->op.sig.algctx, mdname, provkey, params); } /* * If the operation was not a success and no digest was found, an error * needs to be raised. */ if (ret > 0 || mdname != NULL) goto end; if (type == NULL) /* This check is redundant but clarifies matters */ ERR_raise(ERR_LIB_EVP, EVP_R_NO_DEFAULT_DIGEST); err: evp_pkey_ctx_free_old_ops(locpctx); locpctx->operation = EVP_PKEY_OP_UNDEFINED; EVP_KEYMGMT_free(tmp_keymgmt); return 0; legacy: /* * If we don't have the full support we need with provided methods, * let's go see if legacy does. */ ERR_pop_to_mark(); EVP_KEYMGMT_free(tmp_keymgmt); tmp_keymgmt = NULL; if (type == NULL && mdname != NULL) type = evp_get_digestbyname_ex(locpctx->libctx, mdname); if (ctx->pctx->pmeth == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } if (!(ctx->pctx->pmeth->flags & EVP_PKEY_FLAG_SIGCTX_CUSTOM)) { if (type == NULL) { int def_nid; if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) > 0) type = EVP_get_digestbynid(def_nid); } if (type == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_DEFAULT_DIGEST); return 0; } } if (ver) { if (ctx->pctx->pmeth->verifyctx_init) { if (ctx->pctx->pmeth->verifyctx_init(ctx->pctx, ctx) <= 0) return 0; ctx->pctx->operation = EVP_PKEY_OP_VERIFYCTX; } else if (ctx->pctx->pmeth->digestverify != 0) { ctx->pctx->operation = EVP_PKEY_OP_VERIFY; ctx->update = update; } else if (EVP_PKEY_verify_init(ctx->pctx) <= 0) { return 0; } } else { if (ctx->pctx->pmeth->signctx_init) { if (ctx->pctx->pmeth->signctx_init(ctx->pctx, ctx) <= 0) return 0; ctx->pctx->operation = EVP_PKEY_OP_SIGNCTX; } else if (ctx->pctx->pmeth->digestsign != 0) { ctx->pctx->operation = EVP_PKEY_OP_SIGN; ctx->update = update; } else if (EVP_PKEY_sign_init(ctx->pctx) <= 0) { return 0; } } if (EVP_PKEY_CTX_set_signature_md(ctx->pctx, type) <= 0) return 0; if (pctx) *pctx = ctx->pctx; if (ctx->pctx->pmeth->flags & EVP_PKEY_FLAG_SIGCTX_CUSTOM) return 1; if (!EVP_DigestInit_ex(ctx, type, e)) return 0; /* * This indicates the current algorithm requires * special treatment before hashing the tbs-message. */ ctx->pctx->flag_call_digest_custom = 0; if (ctx->pctx->pmeth->digest_custom != NULL) ctx->pctx->flag_call_digest_custom = 1; ret = 1; end: #ifndef FIPS_MODULE if (ret > 0) ret = evp_pkey_ctx_use_cached_data(locpctx); #endif EVP_KEYMGMT_free(tmp_keymgmt); return ret > 0 ? 1 : 0; } int EVP_DigestSignInit_ex(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const char *mdname, OSSL_LIB_CTX *libctx, const char *props, EVP_PKEY *pkey, const OSSL_PARAM params[]) { return do_sigver_init(ctx, pctx, NULL, mdname, libctx, props, NULL, pkey, 0, params); } int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey) { return do_sigver_init(ctx, pctx, type, NULL, NULL, NULL, e, pkey, 0, NULL); } int EVP_DigestVerifyInit_ex(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const char *mdname, OSSL_LIB_CTX *libctx, const char *props, EVP_PKEY *pkey, const OSSL_PARAM params[]) { return do_sigver_init(ctx, pctx, NULL, mdname, libctx, props, NULL, pkey, 1, params); } int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey) { return do_sigver_init(ctx, pctx, type, NULL, NULL, NULL, e, pkey, 1, NULL); } #endif /* FIPS_MDOE */ int EVP_DigestSignUpdate(EVP_MD_CTX *ctx, const void *data, size_t dsize) { EVP_PKEY_CTX *pctx = ctx->pctx; if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISED) != 0) { ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR); return 0; } if (pctx == NULL || pctx->operation != EVP_PKEY_OP_SIGNCTX || pctx->op.sig.algctx == NULL || pctx->op.sig.signature == NULL) goto legacy; if (pctx->op.sig.signature->digest_sign_update == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } return pctx->op.sig.signature->digest_sign_update(pctx->op.sig.algctx, data, dsize); legacy: if (pctx != NULL) { /* do_sigver_init() checked that |digest_custom| is non-NULL */ if (pctx->flag_call_digest_custom && !ctx->pctx->pmeth->digest_custom(ctx->pctx, ctx)) return 0; pctx->flag_call_digest_custom = 0; } return EVP_DigestUpdate(ctx, data, dsize); } int EVP_DigestVerifyUpdate(EVP_MD_CTX *ctx, const void *data, size_t dsize) { EVP_PKEY_CTX *pctx = ctx->pctx; if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISED) != 0) { ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR); return 0; } if (pctx == NULL || pctx->operation != EVP_PKEY_OP_VERIFYCTX || pctx->op.sig.algctx == NULL || pctx->op.sig.signature == NULL) goto legacy; if (pctx->op.sig.signature->digest_verify_update == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } return pctx->op.sig.signature->digest_verify_update(pctx->op.sig.algctx, data, dsize); legacy: if (pctx != NULL) { /* do_sigver_init() checked that |digest_custom| is non-NULL */ if (pctx->flag_call_digest_custom && !ctx->pctx->pmeth->digest_custom(ctx->pctx, ctx)) return 0; pctx->flag_call_digest_custom = 0; } return EVP_DigestUpdate(ctx, data, dsize); } #ifndef FIPS_MODULE int EVP_DigestSignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, size_t *siglen) { int sctx = 0, r = 0; EVP_PKEY_CTX *dctx = NULL, *pctx = ctx->pctx; if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISED) != 0) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } if (pctx == NULL || pctx->operation != EVP_PKEY_OP_SIGNCTX || pctx->op.sig.algctx == NULL || pctx->op.sig.signature == NULL) goto legacy; if (sigret != NULL && (ctx->flags & EVP_MD_CTX_FLAG_FINALISE) == 0) { /* try dup */ dctx = EVP_PKEY_CTX_dup(pctx); if (dctx != NULL) pctx = dctx; } r = pctx->op.sig.signature->digest_sign_final(pctx->op.sig.algctx, sigret, siglen, sigret == NULL ? 0 : *siglen); if (dctx == NULL && sigret != NULL) ctx->flags |= EVP_MD_CTX_FLAG_FINALISED; else EVP_PKEY_CTX_free(dctx); return r; legacy: if (pctx == NULL || pctx->pmeth == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } /* do_sigver_init() checked that |digest_custom| is non-NULL */ if (pctx->flag_call_digest_custom && !ctx->pctx->pmeth->digest_custom(ctx->pctx, ctx)) return 0; pctx->flag_call_digest_custom = 0; if (pctx->pmeth->flags & EVP_PKEY_FLAG_SIGCTX_CUSTOM) { if (sigret == NULL) return pctx->pmeth->signctx(pctx, sigret, siglen, ctx); if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISE) != 0) { r = pctx->pmeth->signctx(pctx, sigret, siglen, ctx); ctx->flags |= EVP_MD_CTX_FLAG_FINALISED; } else { dctx = EVP_PKEY_CTX_dup(pctx); if (dctx == NULL) return 0; r = dctx->pmeth->signctx(dctx, sigret, siglen, ctx); EVP_PKEY_CTX_free(dctx); } return r; } if (pctx->pmeth->signctx != NULL) sctx = 1; else sctx = 0; if (sigret != NULL) { unsigned char md[EVP_MAX_MD_SIZE]; unsigned int mdlen = 0; if (ctx->flags & EVP_MD_CTX_FLAG_FINALISE) { if (sctx) r = pctx->pmeth->signctx(pctx, sigret, siglen, ctx); else r = EVP_DigestFinal_ex(ctx, md, &mdlen); } else { EVP_MD_CTX *tmp_ctx = EVP_MD_CTX_new(); if (tmp_ctx == NULL) return 0; if (!EVP_MD_CTX_copy_ex(tmp_ctx, ctx)) { EVP_MD_CTX_free(tmp_ctx); return 0; } if (sctx) r = tmp_ctx->pctx->pmeth->signctx(tmp_ctx->pctx, sigret, siglen, tmp_ctx); else r = EVP_DigestFinal_ex(tmp_ctx, md, &mdlen); EVP_MD_CTX_free(tmp_ctx); } if (sctx || !r) return r; if (EVP_PKEY_sign(pctx, sigret, siglen, md, mdlen) <= 0) return 0; } else { if (sctx) { if (pctx->pmeth->signctx(pctx, sigret, siglen, ctx) <= 0) return 0; } else { int s = EVP_MD_get_size(ctx->digest); if (s < 0 || EVP_PKEY_sign(pctx, sigret, siglen, NULL, s) <= 0) return 0; } } return 1; } int EVP_DigestSign(EVP_MD_CTX *ctx, unsigned char *sigret, size_t *siglen, const unsigned char *tbs, size_t tbslen) { EVP_PKEY_CTX *pctx = ctx->pctx; if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISED) != 0) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } if (pctx != NULL && pctx->operation == EVP_PKEY_OP_SIGNCTX && pctx->op.sig.algctx != NULL && pctx->op.sig.signature != NULL) { if (pctx->op.sig.signature->digest_sign != NULL) { if (sigret != NULL) ctx->flags |= EVP_MD_CTX_FLAG_FINALISED; return pctx->op.sig.signature->digest_sign(pctx->op.sig.algctx, sigret, siglen, sigret == NULL ? 0 : *siglen, tbs, tbslen); } } else { /* legacy */ if (ctx->pctx->pmeth != NULL && ctx->pctx->pmeth->digestsign != NULL) return ctx->pctx->pmeth->digestsign(ctx, sigret, siglen, tbs, tbslen); } if (sigret != NULL && EVP_DigestSignUpdate(ctx, tbs, tbslen) <= 0) return 0; return EVP_DigestSignFinal(ctx, sigret, siglen); } int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sig, size_t siglen) { unsigned char md[EVP_MAX_MD_SIZE]; int r = 0; unsigned int mdlen = 0; int vctx = 0; EVP_PKEY_CTX *dctx = NULL, *pctx = ctx->pctx; if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISED) != 0) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } if (pctx == NULL || pctx->operation != EVP_PKEY_OP_VERIFYCTX || pctx->op.sig.algctx == NULL || pctx->op.sig.signature == NULL) goto legacy; if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISE) == 0) { /* try dup */ dctx = EVP_PKEY_CTX_dup(pctx); if (dctx != NULL) pctx = dctx; } r = pctx->op.sig.signature->digest_verify_final(pctx->op.sig.algctx, sig, siglen); if (dctx == NULL) ctx->flags |= EVP_MD_CTX_FLAG_FINALISED; else EVP_PKEY_CTX_free(dctx); return r; legacy: if (pctx == NULL || pctx->pmeth == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } /* do_sigver_init() checked that |digest_custom| is non-NULL */ if (pctx->flag_call_digest_custom && !ctx->pctx->pmeth->digest_custom(ctx->pctx, ctx)) return 0; pctx->flag_call_digest_custom = 0; if (pctx->pmeth->verifyctx != NULL) vctx = 1; else vctx = 0; if (ctx->flags & EVP_MD_CTX_FLAG_FINALISE) { if (vctx) { r = pctx->pmeth->verifyctx(pctx, sig, siglen, ctx); ctx->flags |= EVP_MD_CTX_FLAG_FINALISED; } else r = EVP_DigestFinal_ex(ctx, md, &mdlen); } else { EVP_MD_CTX *tmp_ctx = EVP_MD_CTX_new(); if (tmp_ctx == NULL) return -1; if (!EVP_MD_CTX_copy_ex(tmp_ctx, ctx)) { EVP_MD_CTX_free(tmp_ctx); return -1; } if (vctx) r = tmp_ctx->pctx->pmeth->verifyctx(tmp_ctx->pctx, sig, siglen, tmp_ctx); else r = EVP_DigestFinal_ex(tmp_ctx, md, &mdlen); EVP_MD_CTX_free(tmp_ctx); } if (vctx || !r) return r; return EVP_PKEY_verify(pctx, sig, siglen, md, mdlen); } int EVP_DigestVerify(EVP_MD_CTX *ctx, const unsigned char *sigret, size_t siglen, const unsigned char *tbs, size_t tbslen) { EVP_PKEY_CTX *pctx = ctx->pctx; if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISED) != 0) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } if (pctx != NULL && pctx->operation == EVP_PKEY_OP_VERIFYCTX && pctx->op.sig.algctx != NULL && pctx->op.sig.signature != NULL) { if (pctx->op.sig.signature->digest_verify != NULL) { ctx->flags |= EVP_MD_CTX_FLAG_FINALISED; return pctx->op.sig.signature->digest_verify(pctx->op.sig.algctx, sigret, siglen, tbs, tbslen); } } else { /* legacy */ if (ctx->pctx->pmeth != NULL && ctx->pctx->pmeth->digestverify != NULL) return ctx->pctx->pmeth->digestverify(ctx, sigret, siglen, tbs, tbslen); } if (EVP_DigestVerifyUpdate(ctx, tbs, tbslen) <= 0) return -1; return EVP_DigestVerifyFinal(ctx, sigret, siglen); } #endif /* FIPS_MODULE */
./openssl/crypto/evp/bio_b64.c
/* * Copyright 1995-2023 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 <stdio.h> #include <errno.h> #include "internal/cryptlib.h" #include <openssl/buffer.h> #include <openssl/evp.h> #include "internal/bio.h" static int b64_write(BIO *h, const char *buf, int num); static int b64_read(BIO *h, char *buf, int size); static int b64_puts(BIO *h, const char *str); static long b64_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int b64_new(BIO *h); static int b64_free(BIO *data); static long b64_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); #define B64_BLOCK_SIZE 1024 #define B64_BLOCK_SIZE2 768 #define B64_NONE 0 #define B64_ENCODE 1 #define B64_DECODE 2 typedef struct b64_struct { /* * BIO *bio; moved to the BIO structure */ int buf_len; int buf_off; int tmp_len; /* used to find the start when decoding */ int tmp_nl; /* If true, scan until '\n' */ int encode; int start; /* have we started decoding yet? */ int cont; /* <= 0 when finished */ EVP_ENCODE_CTX *base64; unsigned char buf[EVP_ENCODE_LENGTH(B64_BLOCK_SIZE) + 10]; unsigned char tmp[B64_BLOCK_SIZE]; } BIO_B64_CTX; static const BIO_METHOD methods_b64 = { BIO_TYPE_BASE64, "base64 encoding", bwrite_conv, b64_write, bread_conv, b64_read, b64_puts, NULL, /* b64_gets, */ b64_ctrl, b64_new, b64_free, b64_callback_ctrl, }; const BIO_METHOD *BIO_f_base64(void) { return &methods_b64; } static int b64_new(BIO *bi) { BIO_B64_CTX *ctx; if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) return 0; ctx->cont = 1; ctx->start = 1; ctx->base64 = EVP_ENCODE_CTX_new(); if (ctx->base64 == NULL) { OPENSSL_free(ctx); return 0; } BIO_set_data(bi, ctx); BIO_set_init(bi, 1); return 1; } static int b64_free(BIO *a) { BIO_B64_CTX *ctx; if (a == NULL) return 0; ctx = BIO_get_data(a); if (ctx == NULL) return 0; EVP_ENCODE_CTX_free(ctx->base64); OPENSSL_free(ctx); BIO_set_data(a, NULL); BIO_set_init(a, 0); return 1; } static int b64_read(BIO *b, char *out, int outl) { int ret = 0, i, ii, j, k, x, n, num, ret_code = 0; BIO_B64_CTX *ctx; unsigned char *p, *q; BIO *next; if (out == NULL) return 0; ctx = (BIO_B64_CTX *)BIO_get_data(b); next = BIO_next(b); if (ctx == NULL || next == NULL) return 0; BIO_clear_retry_flags(b); if (ctx->encode != B64_DECODE) { ctx->encode = B64_DECODE; ctx->buf_len = 0; ctx->buf_off = 0; ctx->tmp_len = 0; EVP_DecodeInit(ctx->base64); } /* First check if there are bytes decoded/encoded */ if (ctx->buf_len > 0) { OPENSSL_assert(ctx->buf_len >= ctx->buf_off); i = ctx->buf_len - ctx->buf_off; if (i > outl) i = outl; OPENSSL_assert(ctx->buf_off + i < (int)sizeof(ctx->buf)); memcpy(out, &(ctx->buf[ctx->buf_off]), i); ret = i; out += i; outl -= i; ctx->buf_off += i; if (ctx->buf_len == ctx->buf_off) { ctx->buf_len = 0; ctx->buf_off = 0; } } /* * At this point, we have room of outl bytes and an empty buffer, so we * should read in some more. */ ret_code = 0; while (outl > 0) { if (ctx->cont <= 0) break; i = BIO_read(next, &(ctx->tmp[ctx->tmp_len]), B64_BLOCK_SIZE - ctx->tmp_len); if (i <= 0) { ret_code = i; /* Should we continue next time we are called? */ if (!BIO_should_retry(next)) { ctx->cont = i; /* If buffer empty break */ if (ctx->tmp_len == 0) break; /* Fall through and process what we have */ else i = 0; } /* else we retry and add more data to buffer */ else break; } i += ctx->tmp_len; ctx->tmp_len = i; /* * We need to scan, a line at a time until we have a valid line if we * are starting. */ if (ctx->start && (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) != 0) { ctx->tmp_len = 0; } else if (ctx->start) { q = p = ctx->tmp; num = 0; for (j = 0; j < i; j++) { if (*(q++) != '\n') continue; /* * due to a previous very long line, we need to keep on * scanning for a '\n' before we even start looking for * base64 encoded stuff. */ if (ctx->tmp_nl) { p = q; ctx->tmp_nl = 0; continue; } k = EVP_DecodeUpdate(ctx->base64, ctx->buf, &num, p, q - p); if (k <= 0 && num == 0 && ctx->start) { EVP_DecodeInit(ctx->base64); } else { if (p != ctx->tmp) { i -= p - ctx->tmp; for (x = 0; x < i; x++) ctx->tmp[x] = p[x]; } EVP_DecodeInit(ctx->base64); ctx->start = 0; break; } p = q; } /* we fell off the end without starting */ if (j == i && num == 0) { /* * Is this is one long chunk?, if so, keep on reading until a * new line. */ if (p == ctx->tmp) { /* Check buffer full */ if (i == B64_BLOCK_SIZE) { ctx->tmp_nl = 1; ctx->tmp_len = 0; } } else if (p != q) { /* finished on a '\n' */ n = q - p; for (ii = 0; ii < n; ii++) ctx->tmp[ii] = p[ii]; ctx->tmp_len = n; } /* else finished on a '\n' */ continue; } else { ctx->tmp_len = 0; } } else if (i < B64_BLOCK_SIZE && ctx->cont > 0) { /* * If buffer isn't full and we can retry then restart to read in * more data. */ continue; } if ((BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) != 0) { int z, jj; jj = i & ~3; /* process per 4 */ z = EVP_DecodeBlock(ctx->buf, ctx->tmp, jj); if (jj > 2) { if (ctx->tmp[jj - 1] == '=') { z--; if (ctx->tmp[jj - 2] == '=') z--; } } /* * z is now number of output bytes and jj is the number consumed */ if (jj != i) { memmove(ctx->tmp, &ctx->tmp[jj], i - jj); ctx->tmp_len = i - jj; } ctx->buf_len = 0; if (z > 0) { ctx->buf_len = z; } i = z; } else { i = EVP_DecodeUpdate(ctx->base64, ctx->buf, &ctx->buf_len, ctx->tmp, i); ctx->tmp_len = 0; } /* * If eof or an error was signalled, then the condition * 'ctx->cont <= 0' will prevent b64_read() from reading * more data on subsequent calls. This assignment was * deleted accidentally in commit 5562cfaca4f3. */ ctx->cont = i; ctx->buf_off = 0; if (i < 0) { ret_code = 0; ctx->buf_len = 0; break; } if (ctx->buf_len <= outl) i = ctx->buf_len; else i = outl; memcpy(out, ctx->buf, i); ret += i; ctx->buf_off = i; if (ctx->buf_off == ctx->buf_len) { ctx->buf_len = 0; ctx->buf_off = 0; } outl -= i; out += i; } /* BIO_clear_retry_flags(b); */ BIO_copy_next_retry(b); return ret == 0 ? ret_code : ret; } static int b64_write(BIO *b, const char *in, int inl) { int ret = 0; int n; int i; BIO_B64_CTX *ctx; BIO *next; ctx = (BIO_B64_CTX *)BIO_get_data(b); next = BIO_next(b); if (ctx == NULL || next == NULL) return 0; BIO_clear_retry_flags(b); if (ctx->encode != B64_ENCODE) { ctx->encode = B64_ENCODE; ctx->buf_len = 0; ctx->buf_off = 0; ctx->tmp_len = 0; EVP_EncodeInit(ctx->base64); } OPENSSL_assert(ctx->buf_off < (int)sizeof(ctx->buf)); OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf)); OPENSSL_assert(ctx->buf_len >= ctx->buf_off); n = ctx->buf_len - ctx->buf_off; while (n > 0) { i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n); if (i <= 0) { BIO_copy_next_retry(b); return i; } OPENSSL_assert(i <= n); ctx->buf_off += i; OPENSSL_assert(ctx->buf_off <= (int)sizeof(ctx->buf)); OPENSSL_assert(ctx->buf_len >= ctx->buf_off); n -= i; } /* at this point all pending data has been written */ ctx->buf_off = 0; ctx->buf_len = 0; if (in == NULL || inl <= 0) return 0; while (inl > 0) { n = inl > B64_BLOCK_SIZE ? B64_BLOCK_SIZE : inl; if ((BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) != 0) { if (ctx->tmp_len > 0) { OPENSSL_assert(ctx->tmp_len <= 3); n = 3 - ctx->tmp_len; /* * There's a theoretical possibility for this */ if (n > inl) n = inl; memcpy(&(ctx->tmp[ctx->tmp_len]), in, n); ctx->tmp_len += n; ret += n; if (ctx->tmp_len < 3) break; ctx->buf_len = EVP_EncodeBlock(ctx->buf, ctx->tmp, ctx->tmp_len); OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf)); OPENSSL_assert(ctx->buf_len >= ctx->buf_off); /* * Since we're now done using the temporary buffer, the * length should be 0'd */ ctx->tmp_len = 0; } else { if (n < 3) { memcpy(ctx->tmp, in, n); ctx->tmp_len = n; ret += n; break; } n -= n % 3; ctx->buf_len = EVP_EncodeBlock(ctx->buf, (unsigned char *)in, n); OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf)); OPENSSL_assert(ctx->buf_len >= ctx->buf_off); ret += n; } } else { if (!EVP_EncodeUpdate(ctx->base64, ctx->buf, &ctx->buf_len, (unsigned char *)in, n)) return ret == 0 ? -1 : ret; OPENSSL_assert(ctx->buf_len <= (int)sizeof(ctx->buf)); OPENSSL_assert(ctx->buf_len >= ctx->buf_off); ret += n; } inl -= n; in += n; ctx->buf_off = 0; n = ctx->buf_len; while (n > 0) { i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n); if (i <= 0) { BIO_copy_next_retry(b); return ret == 0 ? i : ret; } OPENSSL_assert(i <= n); n -= i; ctx->buf_off += i; OPENSSL_assert(ctx->buf_off <= (int)sizeof(ctx->buf)); OPENSSL_assert(ctx->buf_len >= ctx->buf_off); } ctx->buf_len = 0; ctx->buf_off = 0; } return ret; } static long b64_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO_B64_CTX *ctx; long ret = 1; int i; BIO *next; ctx = (BIO_B64_CTX *)BIO_get_data(b); next = BIO_next(b); if (ctx == NULL || next == NULL) return 0; switch (cmd) { case BIO_CTRL_RESET: ctx->cont = 1; ctx->start = 1; ctx->encode = B64_NONE; ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_EOF: /* More to read */ if (ctx->cont <= 0) ret = 1; else ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_WPENDING: /* More to write in buffer */ OPENSSL_assert(ctx->buf_len >= ctx->buf_off); ret = ctx->buf_len - ctx->buf_off; if (ret == 0 && ctx->encode != B64_NONE && EVP_ENCODE_CTX_num(ctx->base64) != 0) ret = 1; else if (ret <= 0) ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_PENDING: /* More to read in buffer */ OPENSSL_assert(ctx->buf_len >= ctx->buf_off); ret = ctx->buf_len - ctx->buf_off; if (ret <= 0) ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_FLUSH: /* do a final write */ again: while (ctx->buf_len != ctx->buf_off) { i = b64_write(b, NULL, 0); if (i < 0) return i; } if (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) { if (ctx->tmp_len != 0) { ctx->buf_len = EVP_EncodeBlock(ctx->buf, ctx->tmp, ctx->tmp_len); ctx->buf_off = 0; ctx->tmp_len = 0; goto again; } } else if (ctx->encode != B64_NONE && EVP_ENCODE_CTX_num(ctx->base64) != 0) { ctx->buf_off = 0; EVP_EncodeFinal(ctx->base64, ctx->buf, &(ctx->buf_len)); /* push out the bytes */ goto again; } /* Finally flush the underlying BIO */ ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_DUP: break; case BIO_CTRL_INFO: case BIO_CTRL_GET: case BIO_CTRL_SET: default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static long b64_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } static int b64_puts(BIO *b, const char *str) { return b64_write(b, str, strlen(str)); }
./openssl/crypto/evp/asymcipher.c
/* * Copyright 2006-2023 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 <stdio.h> #include <stdlib.h> #include <openssl/objects.h> #include <openssl/evp.h> #include "internal/cryptlib.h" #include "internal/provider.h" #include "internal/core.h" #include "crypto/evp.h" #include "evp_local.h" static int evp_pkey_asym_cipher_init(EVP_PKEY_CTX *ctx, int operation, const OSSL_PARAM params[]) { int ret = 0; void *provkey = NULL; EVP_ASYM_CIPHER *cipher = NULL; EVP_KEYMGMT *tmp_keymgmt = NULL; const OSSL_PROVIDER *tmp_prov = NULL; const char *supported_ciph = NULL; int iter; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } evp_pkey_ctx_free_old_ops(ctx); ctx->operation = operation; ERR_set_mark(); if (evp_pkey_ctx_is_legacy(ctx)) goto legacy; if (ctx->pkey == NULL) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_NO_KEY_SET); goto err; } /* * Try to derive the supported asym cipher from |ctx->keymgmt|. */ if (!ossl_assert(ctx->pkey->keymgmt == NULL || ctx->pkey->keymgmt == ctx->keymgmt)) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); goto err; } supported_ciph = evp_keymgmt_util_query_operation_name(ctx->keymgmt, OSSL_OP_ASYM_CIPHER); if (supported_ciph == NULL) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } /* * We perform two iterations: * * 1. Do the normal asym cipher fetch, using the fetching data given by * the EVP_PKEY_CTX. * 2. Do the provider specific asym cipher fetch, from the same provider * as |ctx->keymgmt| * * We then try to fetch the keymgmt from the same provider as the * asym cipher, and try to export |ctx->pkey| to that keymgmt (when * this keymgmt happens to be the same as |ctx->keymgmt|, the export * is a no-op, but we call it anyway to not complicate the code even * more). * If the export call succeeds (returns a non-NULL provider key pointer), * we're done and can perform the operation itself. If not, we perform * the second iteration, or jump to legacy. */ for (iter = 1, provkey = NULL; iter < 3 && provkey == NULL; iter++) { EVP_KEYMGMT *tmp_keymgmt_tofree; /* * If we're on the second iteration, free the results from the first. * They are NULL on the first iteration, so no need to check what * iteration we're on. */ EVP_ASYM_CIPHER_free(cipher); EVP_KEYMGMT_free(tmp_keymgmt); switch (iter) { case 1: cipher = EVP_ASYM_CIPHER_fetch(ctx->libctx, supported_ciph, ctx->propquery); if (cipher != NULL) tmp_prov = EVP_ASYM_CIPHER_get0_provider(cipher); break; case 2: tmp_prov = EVP_KEYMGMT_get0_provider(ctx->keymgmt); cipher = evp_asym_cipher_fetch_from_prov((OSSL_PROVIDER *)tmp_prov, supported_ciph, ctx->propquery); if (cipher == NULL) goto legacy; break; } if (cipher == NULL) continue; /* * Ensure that the key is provided, either natively, or as a cached * export. We start by fetching the keymgmt with the same name as * |ctx->pkey|, but from the provider of the asym cipher method, using * the same property query as when fetching the asym cipher method. * With the keymgmt we found (if we did), we try to export |ctx->pkey| * to it (evp_pkey_export_to_provider() is smart enough to only actually * export it if |tmp_keymgmt| is different from |ctx->pkey|'s keymgmt) */ tmp_keymgmt_tofree = tmp_keymgmt = evp_keymgmt_fetch_from_prov((OSSL_PROVIDER *)tmp_prov, EVP_KEYMGMT_get0_name(ctx->keymgmt), ctx->propquery); if (tmp_keymgmt != NULL) provkey = evp_pkey_export_to_provider(ctx->pkey, ctx->libctx, &tmp_keymgmt, ctx->propquery); if (tmp_keymgmt == NULL) EVP_KEYMGMT_free(tmp_keymgmt_tofree); } if (provkey == NULL) { EVP_ASYM_CIPHER_free(cipher); goto legacy; } ERR_pop_to_mark(); /* No more legacy from here down to legacy: */ ctx->op.ciph.cipher = cipher; ctx->op.ciph.algctx = cipher->newctx(ossl_provider_ctx(cipher->prov)); if (ctx->op.ciph.algctx == NULL) { /* The provider key can stay in the cache */ ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } switch (operation) { case EVP_PKEY_OP_ENCRYPT: if (cipher->encrypt_init == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); ret = -2; goto err; } ret = cipher->encrypt_init(ctx->op.ciph.algctx, provkey, params); break; case EVP_PKEY_OP_DECRYPT: if (cipher->decrypt_init == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); ret = -2; goto err; } ret = cipher->decrypt_init(ctx->op.ciph.algctx, provkey, params); break; default: ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } if (ret <= 0) goto err; EVP_KEYMGMT_free(tmp_keymgmt); return 1; legacy: /* * If we don't have the full support we need with provided methods, * let's go see if legacy does. */ ERR_pop_to_mark(); EVP_KEYMGMT_free(tmp_keymgmt); tmp_keymgmt = NULL; if (ctx->pmeth == NULL || ctx->pmeth->encrypt == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } switch (ctx->operation) { case EVP_PKEY_OP_ENCRYPT: if (ctx->pmeth->encrypt_init == NULL) return 1; ret = ctx->pmeth->encrypt_init(ctx); break; case EVP_PKEY_OP_DECRYPT: if (ctx->pmeth->decrypt_init == NULL) return 1; ret = ctx->pmeth->decrypt_init(ctx); break; default: ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); ret = -1; } err: if (ret <= 0) { evp_pkey_ctx_free_old_ops(ctx); ctx->operation = EVP_PKEY_OP_UNDEFINED; } EVP_KEYMGMT_free(tmp_keymgmt); return ret; } int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx) { return evp_pkey_asym_cipher_init(ctx, EVP_PKEY_OP_ENCRYPT, NULL); } int EVP_PKEY_encrypt_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]) { return evp_pkey_asym_cipher_init(ctx, EVP_PKEY_OP_ENCRYPT, params); } int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen) { int ret; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } if (ctx->operation != EVP_PKEY_OP_ENCRYPT) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); return -1; } if (ctx->op.ciph.algctx == NULL) goto legacy; ret = ctx->op.ciph.cipher->encrypt(ctx->op.ciph.algctx, out, outlen, (out == NULL ? 0 : *outlen), in, inlen); return ret; legacy: if (ctx->pmeth == NULL || ctx->pmeth->encrypt == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } M_check_autoarg(ctx, out, outlen, EVP_F_EVP_PKEY_ENCRYPT) return ctx->pmeth->encrypt(ctx, out, outlen, in, inlen); } int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx) { return evp_pkey_asym_cipher_init(ctx, EVP_PKEY_OP_DECRYPT, NULL); } int EVP_PKEY_decrypt_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]) { return evp_pkey_asym_cipher_init(ctx, EVP_PKEY_OP_DECRYPT, params); } int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen) { int ret; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } if (ctx->operation != EVP_PKEY_OP_DECRYPT) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); return -1; } if (ctx->op.ciph.algctx == NULL) goto legacy; ret = ctx->op.ciph.cipher->decrypt(ctx->op.ciph.algctx, out, outlen, (out == NULL ? 0 : *outlen), in, inlen); return ret; legacy: if (ctx->pmeth == NULL || ctx->pmeth->decrypt == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } M_check_autoarg(ctx, out, outlen, EVP_F_EVP_PKEY_DECRYPT) return ctx->pmeth->decrypt(ctx, out, outlen, in, inlen); } /* decrypt to new buffer of dynamic size, checking any pre-determined size */ int evp_pkey_decrypt_alloc(EVP_PKEY_CTX *ctx, unsigned char **outp, size_t *outlenp, size_t expected_outlen, const unsigned char *in, size_t inlen) { if (EVP_PKEY_decrypt(ctx, NULL, outlenp, in, inlen) <= 0 || (*outp = OPENSSL_malloc(*outlenp)) == NULL) return -1; if (EVP_PKEY_decrypt(ctx, *outp, outlenp, in, inlen) <= 0 || *outlenp == 0 || (expected_outlen != 0 && *outlenp != expected_outlen)) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); OPENSSL_clear_free(*outp, *outlenp); *outp = NULL; return 0; } return 1; } static EVP_ASYM_CIPHER *evp_asym_cipher_new(OSSL_PROVIDER *prov) { EVP_ASYM_CIPHER *cipher = OPENSSL_zalloc(sizeof(EVP_ASYM_CIPHER)); if (cipher == NULL) return NULL; if (!CRYPTO_NEW_REF(&cipher->refcnt, 1)) { OPENSSL_free(cipher); return NULL; } cipher->prov = prov; ossl_provider_up_ref(prov); return cipher; } static void *evp_asym_cipher_from_algorithm(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { const OSSL_DISPATCH *fns = algodef->implementation; EVP_ASYM_CIPHER *cipher = NULL; int ctxfncnt = 0, encfncnt = 0, decfncnt = 0; int gparamfncnt = 0, sparamfncnt = 0; if ((cipher = evp_asym_cipher_new(prov)) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); goto err; } cipher->name_id = name_id; if ((cipher->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) goto err; cipher->description = algodef->algorithm_description; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_ASYM_CIPHER_NEWCTX: if (cipher->newctx != NULL) break; cipher->newctx = OSSL_FUNC_asym_cipher_newctx(fns); ctxfncnt++; break; case OSSL_FUNC_ASYM_CIPHER_ENCRYPT_INIT: if (cipher->encrypt_init != NULL) break; cipher->encrypt_init = OSSL_FUNC_asym_cipher_encrypt_init(fns); encfncnt++; break; case OSSL_FUNC_ASYM_CIPHER_ENCRYPT: if (cipher->encrypt != NULL) break; cipher->encrypt = OSSL_FUNC_asym_cipher_encrypt(fns); encfncnt++; break; case OSSL_FUNC_ASYM_CIPHER_DECRYPT_INIT: if (cipher->decrypt_init != NULL) break; cipher->decrypt_init = OSSL_FUNC_asym_cipher_decrypt_init(fns); decfncnt++; break; case OSSL_FUNC_ASYM_CIPHER_DECRYPT: if (cipher->decrypt != NULL) break; cipher->decrypt = OSSL_FUNC_asym_cipher_decrypt(fns); decfncnt++; break; case OSSL_FUNC_ASYM_CIPHER_FREECTX: if (cipher->freectx != NULL) break; cipher->freectx = OSSL_FUNC_asym_cipher_freectx(fns); ctxfncnt++; break; case OSSL_FUNC_ASYM_CIPHER_DUPCTX: if (cipher->dupctx != NULL) break; cipher->dupctx = OSSL_FUNC_asym_cipher_dupctx(fns); break; case OSSL_FUNC_ASYM_CIPHER_GET_CTX_PARAMS: if (cipher->get_ctx_params != NULL) break; cipher->get_ctx_params = OSSL_FUNC_asym_cipher_get_ctx_params(fns); gparamfncnt++; break; case OSSL_FUNC_ASYM_CIPHER_GETTABLE_CTX_PARAMS: if (cipher->gettable_ctx_params != NULL) break; cipher->gettable_ctx_params = OSSL_FUNC_asym_cipher_gettable_ctx_params(fns); gparamfncnt++; break; case OSSL_FUNC_ASYM_CIPHER_SET_CTX_PARAMS: if (cipher->set_ctx_params != NULL) break; cipher->set_ctx_params = OSSL_FUNC_asym_cipher_set_ctx_params(fns); sparamfncnt++; break; case OSSL_FUNC_ASYM_CIPHER_SETTABLE_CTX_PARAMS: if (cipher->settable_ctx_params != NULL) break; cipher->settable_ctx_params = OSSL_FUNC_asym_cipher_settable_ctx_params(fns); sparamfncnt++; break; } } if (ctxfncnt != 2 || (encfncnt != 0 && encfncnt != 2) || (decfncnt != 0 && decfncnt != 2) || (encfncnt != 2 && decfncnt != 2) || (gparamfncnt != 0 && gparamfncnt != 2) || (sparamfncnt != 0 && sparamfncnt != 2)) { /* * In order to be a consistent set of functions we must have at least * a set of context functions (newctx and freectx) as well as a pair of * "cipher" functions: (encrypt_init, encrypt) or * (decrypt_init decrypt). set_ctx_params and settable_ctx_params are * optional, but if one of them is present then the other one must also * be present. The same applies to get_ctx_params and * gettable_ctx_params. The dupctx function is optional. */ ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS); goto err; } return cipher; err: EVP_ASYM_CIPHER_free(cipher); return NULL; } void EVP_ASYM_CIPHER_free(EVP_ASYM_CIPHER *cipher) { int i; if (cipher == NULL) return; CRYPTO_DOWN_REF(&cipher->refcnt, &i); if (i > 0) return; OPENSSL_free(cipher->type_name); ossl_provider_free(cipher->prov); CRYPTO_FREE_REF(&cipher->refcnt); OPENSSL_free(cipher); } int EVP_ASYM_CIPHER_up_ref(EVP_ASYM_CIPHER *cipher) { int ref = 0; CRYPTO_UP_REF(&cipher->refcnt, &ref); return 1; } OSSL_PROVIDER *EVP_ASYM_CIPHER_get0_provider(const EVP_ASYM_CIPHER *cipher) { return cipher->prov; } EVP_ASYM_CIPHER *EVP_ASYM_CIPHER_fetch(OSSL_LIB_CTX *ctx, const char *algorithm, const char *properties) { return evp_generic_fetch(ctx, OSSL_OP_ASYM_CIPHER, algorithm, properties, evp_asym_cipher_from_algorithm, (int (*)(void *))EVP_ASYM_CIPHER_up_ref, (void (*)(void *))EVP_ASYM_CIPHER_free); } EVP_ASYM_CIPHER *evp_asym_cipher_fetch_from_prov(OSSL_PROVIDER *prov, const char *algorithm, const char *properties) { return evp_generic_fetch_from_prov(prov, OSSL_OP_ASYM_CIPHER, algorithm, properties, evp_asym_cipher_from_algorithm, (int (*)(void *))EVP_ASYM_CIPHER_up_ref, (void (*)(void *))EVP_ASYM_CIPHER_free); } int EVP_ASYM_CIPHER_is_a(const EVP_ASYM_CIPHER *cipher, const char *name) { return evp_is_a(cipher->prov, cipher->name_id, NULL, name); } int evp_asym_cipher_get_number(const EVP_ASYM_CIPHER *cipher) { return cipher->name_id; } const char *EVP_ASYM_CIPHER_get0_name(const EVP_ASYM_CIPHER *cipher) { return cipher->type_name; } const char *EVP_ASYM_CIPHER_get0_description(const EVP_ASYM_CIPHER *cipher) { return cipher->description; } void EVP_ASYM_CIPHER_do_all_provided(OSSL_LIB_CTX *libctx, void (*fn)(EVP_ASYM_CIPHER *cipher, void *arg), void *arg) { evp_generic_do_all(libctx, OSSL_OP_ASYM_CIPHER, (void (*)(void *, void *))fn, arg, evp_asym_cipher_from_algorithm, (int (*)(void *))EVP_ASYM_CIPHER_up_ref, (void (*)(void *))EVP_ASYM_CIPHER_free); } int EVP_ASYM_CIPHER_names_do_all(const EVP_ASYM_CIPHER *cipher, void (*fn)(const char *name, void *data), void *data) { if (cipher->prov != NULL) return evp_names_do_all(cipher->prov, cipher->name_id, fn, data); return 1; } const OSSL_PARAM *EVP_ASYM_CIPHER_gettable_ctx_params(const EVP_ASYM_CIPHER *cip) { void *provctx; if (cip == NULL || cip->gettable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_ASYM_CIPHER_get0_provider(cip)); return cip->gettable_ctx_params(NULL, provctx); } const OSSL_PARAM *EVP_ASYM_CIPHER_settable_ctx_params(const EVP_ASYM_CIPHER *cip) { void *provctx; if (cip == NULL || cip->settable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_ASYM_CIPHER_get0_provider(cip)); return cip->settable_ctx_params(NULL, provctx); }
./openssl/crypto/evp/pmeth_gn.c
/* * Copyright 2006-2023 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 <stdio.h> #include <stdlib.h> #include <openssl/core.h> #include <openssl/core_names.h> #include "internal/cryptlib.h" #include "internal/core.h" #include <openssl/objects.h> #include <openssl/evp.h> #include "crypto/bn.h" #ifndef FIPS_MODULE # include "crypto/asn1.h" #endif #include "crypto/evp.h" #include "evp_local.h" static int gen_init(EVP_PKEY_CTX *ctx, int operation) { int ret = 0; if (ctx == NULL) goto not_supported; evp_pkey_ctx_free_old_ops(ctx); ctx->operation = operation; if (ctx->keymgmt == NULL || ctx->keymgmt->gen_init == NULL) goto legacy; switch (operation) { case EVP_PKEY_OP_PARAMGEN: ctx->op.keymgmt.genctx = evp_keymgmt_gen_init(ctx->keymgmt, OSSL_KEYMGMT_SELECT_ALL_PARAMETERS, NULL); break; case EVP_PKEY_OP_KEYGEN: ctx->op.keymgmt.genctx = evp_keymgmt_gen_init(ctx->keymgmt, OSSL_KEYMGMT_SELECT_KEYPAIR, NULL); break; } if (ctx->op.keymgmt.genctx == NULL) ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); else ret = 1; goto end; legacy: #ifdef FIPS_MODULE goto not_supported; #else if (ctx->pmeth == NULL || (operation == EVP_PKEY_OP_PARAMGEN && ctx->pmeth->paramgen == NULL) || (operation == EVP_PKEY_OP_KEYGEN && ctx->pmeth->keygen == NULL)) goto not_supported; ret = 1; switch (operation) { case EVP_PKEY_OP_PARAMGEN: if (ctx->pmeth->paramgen_init != NULL) ret = ctx->pmeth->paramgen_init(ctx); break; case EVP_PKEY_OP_KEYGEN: if (ctx->pmeth->keygen_init != NULL) ret = ctx->pmeth->keygen_init(ctx); break; } #endif end: if (ret <= 0 && ctx != NULL) { evp_pkey_ctx_free_old_ops(ctx); ctx->operation = EVP_PKEY_OP_UNDEFINED; } return ret; not_supported: ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); ret = -2; goto end; } int EVP_PKEY_paramgen_init(EVP_PKEY_CTX *ctx) { return gen_init(ctx, EVP_PKEY_OP_PARAMGEN); } int EVP_PKEY_keygen_init(EVP_PKEY_CTX *ctx) { return gen_init(ctx, EVP_PKEY_OP_KEYGEN); } static int ossl_callback_to_pkey_gencb(const OSSL_PARAM params[], void *arg) { EVP_PKEY_CTX *ctx = arg; const OSSL_PARAM *param = NULL; int p = -1, n = -1; if (ctx->pkey_gencb == NULL) return 1; /* No callback? That's fine */ if ((param = OSSL_PARAM_locate_const(params, OSSL_GEN_PARAM_POTENTIAL)) == NULL || !OSSL_PARAM_get_int(param, &p)) return 0; if ((param = OSSL_PARAM_locate_const(params, OSSL_GEN_PARAM_ITERATION)) == NULL || !OSSL_PARAM_get_int(param, &n)) return 0; ctx->keygen_info[0] = p; ctx->keygen_info[1] = n; return ctx->pkey_gencb(ctx); } int EVP_PKEY_generate(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey) { int ret = 0; EVP_PKEY *allocated_pkey = NULL; /* Legacy compatible keygen callback info, only used with provider impls */ int gentmp[2]; if (ppkey == NULL) return -1; if (ctx == NULL) goto not_supported; if ((ctx->operation & EVP_PKEY_OP_TYPE_GEN) == 0) goto not_initialized; if (*ppkey == NULL) *ppkey = allocated_pkey = EVP_PKEY_new(); if (*ppkey == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return -1; } if (ctx->op.keymgmt.genctx == NULL) goto legacy; /* * Assigning gentmp to ctx->keygen_info is something our legacy * implementations do. Because the provider implementations aren't * allowed to reach into our EVP_PKEY_CTX, we need to provide similar * space for backward compatibility. It's ok that we attach a local * variable, as it should only be useful in the calls down from here. * This is cleared as soon as it isn't useful any more, i.e. directly * after the evp_keymgmt_util_gen() call. */ ctx->keygen_info = gentmp; ctx->keygen_info_count = 2; ret = 1; if (ctx->pkey != NULL) { EVP_KEYMGMT *tmp_keymgmt = ctx->keymgmt; void *keydata = evp_pkey_export_to_provider(ctx->pkey, ctx->libctx, &tmp_keymgmt, ctx->propquery); if (tmp_keymgmt == NULL) goto not_supported; /* * It's ok if keydata is NULL here. The backend is expected to deal * with that as it sees fit. */ ret = evp_keymgmt_gen_set_template(ctx->keymgmt, ctx->op.keymgmt.genctx, keydata); } /* * the returned value from evp_keymgmt_util_gen() is cached in *ppkey, * so we do not need to save it, just check it. */ ret = ret && (evp_keymgmt_util_gen(*ppkey, ctx->keymgmt, ctx->op.keymgmt.genctx, ossl_callback_to_pkey_gencb, ctx) != NULL); ctx->keygen_info = NULL; #ifndef FIPS_MODULE /* In case |*ppkey| was originally a legacy key */ if (ret) evp_pkey_free_legacy(*ppkey); #endif /* * Because we still have legacy keys */ (*ppkey)->type = ctx->legacy_keytype; goto end; legacy: #ifdef FIPS_MODULE goto not_supported; #else /* * If we get here then we're using legacy paramgen/keygen. In that case * the pkey in ctx (if there is one) had better not be provided (because the * legacy methods may not know how to handle it). However we can only get * here if ctx->op.keymgmt.genctx == NULL, but that should never be the case * if ctx->pkey is provided because we don't allow this when we initialise * the ctx. */ if (ctx->pkey != NULL && !ossl_assert(!evp_pkey_is_provided(ctx->pkey))) goto not_accessible; switch (ctx->operation) { case EVP_PKEY_OP_PARAMGEN: ret = ctx->pmeth->paramgen(ctx, *ppkey); break; case EVP_PKEY_OP_KEYGEN: ret = ctx->pmeth->keygen(ctx, *ppkey); break; default: goto not_supported; } #endif end: if (ret <= 0) { if (allocated_pkey != NULL) *ppkey = NULL; EVP_PKEY_free(allocated_pkey); } return ret; not_supported: ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); ret = -2; goto end; not_initialized: ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); ret = -1; goto end; #ifndef FIPS_MODULE not_accessible: ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_DOMAIN_PARAMETERS); ret = -1; goto end; #endif } int EVP_PKEY_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey) { if (ctx->operation != EVP_PKEY_OP_PARAMGEN) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); return -1; } return EVP_PKEY_generate(ctx, ppkey); } int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey) { if (ctx->operation != EVP_PKEY_OP_KEYGEN) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); return -1; } return EVP_PKEY_generate(ctx, ppkey); } void EVP_PKEY_CTX_set_cb(EVP_PKEY_CTX *ctx, EVP_PKEY_gen_cb *cb) { ctx->pkey_gencb = cb; } EVP_PKEY_gen_cb *EVP_PKEY_CTX_get_cb(EVP_PKEY_CTX *ctx) { return ctx->pkey_gencb; } /* * "translation callback" to call EVP_PKEY_CTX callbacks using BN_GENCB style * callbacks. */ static int trans_cb(int a, int b, BN_GENCB *gcb) { EVP_PKEY_CTX *ctx = BN_GENCB_get_arg(gcb); ctx->keygen_info[0] = a; ctx->keygen_info[1] = b; return ctx->pkey_gencb(ctx); } void evp_pkey_set_cb_translate(BN_GENCB *cb, EVP_PKEY_CTX *ctx) { BN_GENCB_set(cb, trans_cb, ctx); } int EVP_PKEY_CTX_get_keygen_info(EVP_PKEY_CTX *ctx, int idx) { if (idx == -1) return ctx->keygen_info_count; if (idx < 0 || idx > ctx->keygen_info_count) return 0; return ctx->keygen_info[idx]; } #ifndef FIPS_MODULE EVP_PKEY *EVP_PKEY_new_mac_key(int type, ENGINE *e, const unsigned char *key, int keylen) { EVP_PKEY_CTX *mac_ctx = NULL; EVP_PKEY *mac_key = NULL; mac_ctx = EVP_PKEY_CTX_new_id(type, e); if (!mac_ctx) return NULL; if (EVP_PKEY_keygen_init(mac_ctx) <= 0) goto merr; if (EVP_PKEY_CTX_set_mac_key(mac_ctx, key, keylen) <= 0) goto merr; if (EVP_PKEY_keygen(mac_ctx, &mac_key) <= 0) goto merr; merr: EVP_PKEY_CTX_free(mac_ctx); return mac_key; } #endif /* FIPS_MODULE */ /*- All methods below can also be used in FIPS_MODULE */ static int fromdata_init(EVP_PKEY_CTX *ctx, int operation) { if (ctx == NULL || ctx->keytype == NULL) goto not_supported; evp_pkey_ctx_free_old_ops(ctx); if (ctx->keymgmt == NULL) goto not_supported; ctx->operation = operation; return 1; not_supported: if (ctx != NULL) ctx->operation = EVP_PKEY_OP_UNDEFINED; ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } int EVP_PKEY_fromdata_init(EVP_PKEY_CTX *ctx) { return fromdata_init(ctx, EVP_PKEY_OP_FROMDATA); } int EVP_PKEY_fromdata(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey, int selection, OSSL_PARAM params[]) { void *keydata = NULL; EVP_PKEY *allocated_pkey = NULL; if (ctx == NULL || (ctx->operation & EVP_PKEY_OP_FROMDATA) == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } if (ppkey == NULL) return -1; if (*ppkey == NULL) allocated_pkey = *ppkey = EVP_PKEY_new(); if (*ppkey == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return -1; } keydata = evp_keymgmt_util_fromdata(*ppkey, ctx->keymgmt, selection, params); if (keydata == NULL) { if (allocated_pkey != NULL) { *ppkey = NULL; EVP_PKEY_free(allocated_pkey); } return 0; } /* keydata is cached in *ppkey, so we need not bother with it further */ return 1; } const OSSL_PARAM *EVP_PKEY_fromdata_settable(EVP_PKEY_CTX *ctx, int selection) { /* We call fromdata_init to get ctx->keymgmt populated */ if (fromdata_init(ctx, EVP_PKEY_OP_UNDEFINED) == 1) return evp_keymgmt_import_types(ctx->keymgmt, selection); return NULL; } static OSSL_CALLBACK ossl_pkey_todata_cb; static int ossl_pkey_todata_cb(const OSSL_PARAM params[], void *arg) { OSSL_PARAM **ret = arg; *ret = OSSL_PARAM_dup(params); return 1; } int EVP_PKEY_todata(const EVP_PKEY *pkey, int selection, OSSL_PARAM **params) { if (params == NULL) return 0; return EVP_PKEY_export(pkey, selection, ossl_pkey_todata_cb, params); } #ifndef FIPS_MODULE struct fake_import_data_st { OSSL_CALLBACK *export_cb; void *export_cbarg; }; static OSSL_FUNC_keymgmt_import_fn pkey_fake_import; static int pkey_fake_import(void *fake_keydata, int ignored_selection, const OSSL_PARAM params[]) { struct fake_import_data_st *data = fake_keydata; return data->export_cb(params, data->export_cbarg); } #endif int EVP_PKEY_export(const EVP_PKEY *pkey, int selection, OSSL_CALLBACK *export_cb, void *export_cbarg) { if (pkey == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return 0; } #ifndef FIPS_MODULE if (evp_pkey_is_legacy(pkey)) { struct fake_import_data_st data; data.export_cb = export_cb; data.export_cbarg = export_cbarg; /* * We don't need to care about libctx or propq here, as we're only * interested in the resulting OSSL_PARAM array. */ return pkey->ameth->export_to(pkey, &data, pkey_fake_import, NULL, NULL); } #endif return evp_keymgmt_util_export(pkey, selection, export_cb, export_cbarg); }
./openssl/crypto/evp/bio_ok.c
/* * Copyright 1995-2023 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 */ /*- From: Arne Ansper Why BIO_f_reliable? I wrote function which took BIO* as argument, read data from it and processed it. Then I wanted to store the input file in encrypted form. OK I pushed BIO_f_cipher to the BIO stack and everything was OK. BUT if user types wrong password BIO_f_cipher outputs only garbage and my function crashes. Yes I can and I should fix my function, but BIO_f_cipher is easy way to add encryption support to many existing applications and it's hard to debug and fix them all. So I wanted another BIO which would catch the incorrect passwords and file damages which cause garbage on BIO_f_cipher's output. The easy way is to push the BIO_f_md and save the checksum at the end of the file. However there are several problems with this approach: 1) you must somehow separate checksum from actual data. 2) you need lot's of memory when reading the file, because you must read to the end of the file and verify the checksum before letting the application to read the data. BIO_f_reliable tries to solve both problems, so that you can read and write arbitrary long streams using only fixed amount of memory. BIO_f_reliable splits data stream into blocks. Each block is prefixed with its length and suffixed with its digest. So you need only several Kbytes of memory to buffer single block before verifying its digest. BIO_f_reliable goes further and adds several important capabilities: 1) the digest of the block is computed over the whole stream -- so nobody can rearrange the blocks or remove or replace them. 2) to detect invalid passwords right at the start BIO_f_reliable adds special prefix to the stream. In order to avoid known plain-text attacks this prefix is generated as follows: *) digest is initialized with random seed instead of standardized one. *) same seed is written to output *) well-known text is then hashed and the output of the digest is also written to output. reader can now read the seed from stream, hash the same string and then compare the digest output. Bad things: BIO_f_reliable knows what's going on in EVP_Digest. I initially wrote and tested this code on x86 machine and wrote the digests out in machine-dependent order :( There are people using this code and I cannot change this easily without making existing data files unreadable. */ #include <stdio.h> #include <errno.h> #include <assert.h> #include "internal/cryptlib.h" #include <openssl/buffer.h> #include "internal/bio.h" #include <openssl/evp.h> #include <openssl/rand.h> #include "internal/endian.h" #include "crypto/evp.h" static int ok_write(BIO *h, const char *buf, int num); static int ok_read(BIO *h, char *buf, int size); static long ok_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int ok_new(BIO *h); static int ok_free(BIO *data); static long ok_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); static __owur int sig_out(BIO *b); static __owur int sig_in(BIO *b); static __owur int block_out(BIO *b); static __owur int block_in(BIO *b); #define OK_BLOCK_SIZE (1024*4) #define OK_BLOCK_BLOCK 4 #define IOBS (OK_BLOCK_SIZE+ OK_BLOCK_BLOCK+ 3*EVP_MAX_MD_SIZE) #define WELLKNOWN "The quick brown fox jumped over the lazy dog's back." typedef struct ok_struct { size_t buf_len; size_t buf_off; size_t buf_len_save; size_t buf_off_save; int cont; /* <= 0 when finished */ int finished; EVP_MD_CTX *md; int blockout; /* output block is ready */ int sigio; /* must process signature */ unsigned char buf[IOBS]; } BIO_OK_CTX; static const BIO_METHOD methods_ok = { BIO_TYPE_CIPHER, "reliable", bwrite_conv, ok_write, bread_conv, ok_read, NULL, /* ok_puts, */ NULL, /* ok_gets, */ ok_ctrl, ok_new, ok_free, ok_callback_ctrl, }; const BIO_METHOD *BIO_f_reliable(void) { return &methods_ok; } static int ok_new(BIO *bi) { BIO_OK_CTX *ctx; if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) return 0; ctx->cont = 1; ctx->sigio = 1; ctx->md = EVP_MD_CTX_new(); if (ctx->md == NULL) { OPENSSL_free(ctx); return 0; } BIO_set_init(bi, 0); BIO_set_data(bi, ctx); return 1; } static int ok_free(BIO *a) { BIO_OK_CTX *ctx; if (a == NULL) return 0; ctx = BIO_get_data(a); EVP_MD_CTX_free(ctx->md); OPENSSL_clear_free(ctx, sizeof(BIO_OK_CTX)); BIO_set_data(a, NULL); BIO_set_init(a, 0); return 1; } static int ok_read(BIO *b, char *out, int outl) { int ret = 0, i, n; BIO_OK_CTX *ctx; BIO *next; if (out == NULL) return 0; ctx = BIO_get_data(b); next = BIO_next(b); if ((ctx == NULL) || (next == NULL) || (BIO_get_init(b) == 0)) return 0; while (outl > 0) { /* copy clean bytes to output buffer */ if (ctx->blockout) { i = ctx->buf_len - ctx->buf_off; if (i > outl) i = outl; memcpy(out, &(ctx->buf[ctx->buf_off]), i); ret += i; out += i; outl -= i; ctx->buf_off += i; /* all clean bytes are out */ if (ctx->buf_len == ctx->buf_off) { ctx->buf_off = 0; /* * copy start of the next block into proper place */ if (ctx->buf_len_save > ctx->buf_off_save) { ctx->buf_len = ctx->buf_len_save - ctx->buf_off_save; memmove(ctx->buf, &(ctx->buf[ctx->buf_off_save]), ctx->buf_len); } else { ctx->buf_len = 0; } ctx->blockout = 0; } } /* output buffer full -- cancel */ if (outl == 0) break; /* no clean bytes in buffer -- fill it */ n = IOBS - ctx->buf_len; i = BIO_read(next, &(ctx->buf[ctx->buf_len]), n); if (i <= 0) break; /* nothing new */ ctx->buf_len += i; /* no signature yet -- check if we got one */ if (ctx->sigio == 1) { if (!sig_in(b)) { BIO_clear_retry_flags(b); return 0; } } /* signature ok -- check if we got block */ if (ctx->sigio == 0) { if (!block_in(b)) { BIO_clear_retry_flags(b); return 0; } } /* invalid block -- cancel */ if (ctx->cont <= 0) break; } BIO_clear_retry_flags(b); BIO_copy_next_retry(b); return ret; } static int ok_write(BIO *b, const char *in, int inl) { int ret = 0, n, i; BIO_OK_CTX *ctx; BIO *next; if (inl <= 0) return inl; ctx = BIO_get_data(b); next = BIO_next(b); ret = inl; if ((ctx == NULL) || (next == NULL) || (BIO_get_init(b) == 0)) return 0; if (ctx->sigio && !sig_out(b)) return 0; do { BIO_clear_retry_flags(b); n = ctx->buf_len - ctx->buf_off; while (ctx->blockout && n > 0) { i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n); if (i <= 0) { BIO_copy_next_retry(b); if (!BIO_should_retry(b)) ctx->cont = 0; return i; } ctx->buf_off += i; n -= i; } /* at this point all pending data has been written */ ctx->blockout = 0; if (ctx->buf_len == ctx->buf_off) { ctx->buf_len = OK_BLOCK_BLOCK; ctx->buf_off = 0; } if ((in == NULL) || (inl <= 0)) return 0; n = (inl + ctx->buf_len > OK_BLOCK_SIZE + OK_BLOCK_BLOCK) ? (int)(OK_BLOCK_SIZE + OK_BLOCK_BLOCK - ctx->buf_len) : inl; memcpy(&ctx->buf[ctx->buf_len], in, n); ctx->buf_len += n; inl -= n; in += n; if (ctx->buf_len >= OK_BLOCK_SIZE + OK_BLOCK_BLOCK) { if (!block_out(b)) { BIO_clear_retry_flags(b); return 0; } } } while (inl > 0); BIO_clear_retry_flags(b); BIO_copy_next_retry(b); return ret; } static long ok_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO_OK_CTX *ctx; EVP_MD *md; const EVP_MD **ppmd; long ret = 1; int i; BIO *next; ctx = BIO_get_data(b); next = BIO_next(b); switch (cmd) { case BIO_CTRL_RESET: ctx->buf_len = 0; ctx->buf_off = 0; ctx->buf_len_save = 0; ctx->buf_off_save = 0; ctx->cont = 1; ctx->finished = 0; ctx->blockout = 0; ctx->sigio = 1; ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_EOF: /* More to read */ if (ctx->cont <= 0) ret = 1; else ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_PENDING: /* More to read in buffer */ case BIO_CTRL_WPENDING: /* More to read in buffer */ ret = ctx->blockout ? ctx->buf_len - ctx->buf_off : 0; if (ret <= 0) ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_FLUSH: /* do a final write */ if (ctx->blockout == 0) if (!block_out(b)) return 0; while (ctx->blockout) { i = ok_write(b, NULL, 0); if (i < 0) { ret = i; break; } } ctx->finished = 1; ctx->buf_off = ctx->buf_len = 0; ctx->cont = (int)ret; /* Finally flush the underlying BIO */ ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_INFO: ret = (long)ctx->cont; break; case BIO_C_SET_MD: md = ptr; if (!EVP_DigestInit_ex(ctx->md, md, NULL)) return 0; BIO_set_init(b, 1); break; case BIO_C_GET_MD: if (BIO_get_init(b)) { ppmd = ptr; *ppmd = EVP_MD_CTX_get0_md(ctx->md); } else ret = 0; break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static long ok_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next; next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } static void longswap(void *_ptr, size_t len) { DECLARE_IS_ENDIAN; if (IS_LITTLE_ENDIAN) { size_t i; unsigned char *p = _ptr, c; for (i = 0; i < len; i += 4) { c = p[0], p[0] = p[3], p[3] = c; c = p[1], p[1] = p[2], p[2] = c; } } } static int sig_out(BIO *b) { BIO_OK_CTX *ctx; EVP_MD_CTX *md; const EVP_MD *digest; int md_size; void *md_data; ctx = BIO_get_data(b); md = ctx->md; digest = EVP_MD_CTX_get0_md(md); md_size = EVP_MD_get_size(digest); md_data = EVP_MD_CTX_get0_md_data(md); if (ctx->buf_len + 2 * md_size > OK_BLOCK_SIZE) return 1; if (!EVP_DigestInit_ex(md, digest, NULL)) goto berr; /* * FIXME: there's absolutely no guarantee this makes any sense at all, * particularly now EVP_MD_CTX has been restructured. */ if (RAND_bytes(md_data, md_size) <= 0) goto berr; memcpy(&(ctx->buf[ctx->buf_len]), md_data, md_size); longswap(&(ctx->buf[ctx->buf_len]), md_size); ctx->buf_len += md_size; if (!EVP_DigestUpdate(md, WELLKNOWN, strlen(WELLKNOWN))) goto berr; if (!EVP_DigestFinal_ex(md, &(ctx->buf[ctx->buf_len]), NULL)) goto berr; ctx->buf_len += md_size; ctx->blockout = 1; ctx->sigio = 0; return 1; berr: BIO_clear_retry_flags(b); return 0; } static int sig_in(BIO *b) { BIO_OK_CTX *ctx; EVP_MD_CTX *md; unsigned char tmp[EVP_MAX_MD_SIZE]; int ret = 0; const EVP_MD *digest; int md_size; void *md_data; ctx = BIO_get_data(b); if ((md = ctx->md) == NULL) goto berr; digest = EVP_MD_CTX_get0_md(md); if ((md_size = EVP_MD_get_size(digest)) < 0) goto berr; md_data = EVP_MD_CTX_get0_md_data(md); if ((int)(ctx->buf_len - ctx->buf_off) < 2 * md_size) return 1; if (!EVP_DigestInit_ex(md, digest, NULL)) goto berr; memcpy(md_data, &(ctx->buf[ctx->buf_off]), md_size); longswap(md_data, md_size); ctx->buf_off += md_size; if (!EVP_DigestUpdate(md, WELLKNOWN, strlen(WELLKNOWN))) goto berr; if (!EVP_DigestFinal_ex(md, tmp, NULL)) goto berr; ret = memcmp(&(ctx->buf[ctx->buf_off]), tmp, md_size) == 0; ctx->buf_off += md_size; if (ret == 1) { ctx->sigio = 0; if (ctx->buf_len != ctx->buf_off) { memmove(ctx->buf, &(ctx->buf[ctx->buf_off]), ctx->buf_len - ctx->buf_off); } ctx->buf_len -= ctx->buf_off; ctx->buf_off = 0; } else { ctx->cont = 0; } return 1; berr: BIO_clear_retry_flags(b); return 0; } static int block_out(BIO *b) { BIO_OK_CTX *ctx; EVP_MD_CTX *md; unsigned long tl; const EVP_MD *digest; int md_size; ctx = BIO_get_data(b); md = ctx->md; digest = EVP_MD_CTX_get0_md(md); md_size = EVP_MD_get_size(digest); tl = ctx->buf_len - OK_BLOCK_BLOCK; ctx->buf[0] = (unsigned char)(tl >> 24); ctx->buf[1] = (unsigned char)(tl >> 16); ctx->buf[2] = (unsigned char)(tl >> 8); ctx->buf[3] = (unsigned char)(tl); if (!EVP_DigestUpdate(md, (unsigned char *)&(ctx->buf[OK_BLOCK_BLOCK]), tl)) goto berr; if (!EVP_DigestFinal_ex(md, &(ctx->buf[ctx->buf_len]), NULL)) goto berr; ctx->buf_len += md_size; ctx->blockout = 1; return 1; berr: BIO_clear_retry_flags(b); return 0; } static int block_in(BIO *b) { BIO_OK_CTX *ctx; EVP_MD_CTX *md; unsigned long tl = 0; unsigned char tmp[EVP_MAX_MD_SIZE]; int md_size; ctx = BIO_get_data(b); md = ctx->md; md_size = EVP_MD_get_size(EVP_MD_CTX_get0_md(md)); if (md_size < 0) goto berr; assert(sizeof(tl) >= OK_BLOCK_BLOCK); /* always true */ tl = ctx->buf[0]; tl <<= 8; tl |= ctx->buf[1]; tl <<= 8; tl |= ctx->buf[2]; tl <<= 8; tl |= ctx->buf[3]; if (ctx->buf_len < tl + OK_BLOCK_BLOCK + md_size) return 1; if (!EVP_DigestUpdate(md, (unsigned char *)&(ctx->buf[OK_BLOCK_BLOCK]), tl)) goto berr; if (!EVP_DigestFinal_ex(md, tmp, NULL)) goto berr; if (memcmp(&(ctx->buf[tl + OK_BLOCK_BLOCK]), tmp, md_size) == 0) { /* there might be parts from next block lurking around ! */ ctx->buf_off_save = tl + OK_BLOCK_BLOCK + md_size; ctx->buf_len_save = ctx->buf_len; ctx->buf_off = OK_BLOCK_BLOCK; ctx->buf_len = tl + OK_BLOCK_BLOCK; ctx->blockout = 1; } else { ctx->cont = 0; } return 1; berr: BIO_clear_retry_flags(b); return 0; }
./openssl/crypto/evp/legacy_md4.c
/* * Copyright 2015-2021 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 */ /* * MD4 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/md4.h> #include "crypto/evp.h" #include "legacy_meth.h" IMPLEMENT_LEGACY_EVP_MD_METH(md4, MD4) static const EVP_MD md4_md = { NID_md4, NID_md4WithRSAEncryption, MD4_DIGEST_LENGTH, 0, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(md4_init, md4_update, md4_final, NULL, MD4_CBLOCK), }; const EVP_MD *EVP_md4(void) { return &md4_md; }
./openssl/crypto/evp/evp_pkey.c
/* * Copyright 1999-2023 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 <stdio.h> #include <stdlib.h> #include "internal/cryptlib.h" #include <openssl/x509.h> #include <openssl/rand.h> #include <openssl/encoder.h> #include <openssl/decoder.h> #include "internal/provider.h" #include "internal/sizes.h" #include "crypto/asn1.h" #include "crypto/evp.h" #include "crypto/x509.h" /* Extract a private key from a PKCS8 structure */ EVP_PKEY *evp_pkcs82pkey_legacy(const PKCS8_PRIV_KEY_INFO *p8, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pkey = NULL; const ASN1_OBJECT *algoid; char obj_tmp[80]; if (!PKCS8_pkey_get0(&algoid, NULL, NULL, NULL, p8)) return NULL; if ((pkey = EVP_PKEY_new()) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return NULL; } if (!EVP_PKEY_set_type(pkey, OBJ_obj2nid(algoid))) { i2t_ASN1_OBJECT(obj_tmp, 80, algoid); ERR_raise_data(ERR_LIB_EVP, EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM, "TYPE=%s", obj_tmp); goto error; } if (pkey->ameth->priv_decode_ex != NULL) { if (!pkey->ameth->priv_decode_ex(pkey, p8, libctx, propq)) goto error; } else if (pkey->ameth->priv_decode != NULL) { if (!pkey->ameth->priv_decode(pkey, p8)) { ERR_raise(ERR_LIB_EVP, EVP_R_PRIVATE_KEY_DECODE_ERROR); goto error; } } else { ERR_raise(ERR_LIB_EVP, EVP_R_METHOD_NOT_SUPPORTED); goto error; } return pkey; error: EVP_PKEY_free(pkey); return NULL; } EVP_PKEY *EVP_PKCS82PKEY_ex(const PKCS8_PRIV_KEY_INFO *p8, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pkey = NULL; const unsigned char *p8_data = NULL; unsigned char *encoded_data = NULL; int encoded_len; int selection; size_t len; OSSL_DECODER_CTX *dctx = NULL; const ASN1_OBJECT *algoid = NULL; char keytype[OSSL_MAX_NAME_SIZE]; if (p8 == NULL || !PKCS8_pkey_get0(&algoid, NULL, NULL, NULL, p8) || !OBJ_obj2txt(keytype, sizeof(keytype), algoid, 0)) return NULL; if ((encoded_len = i2d_PKCS8_PRIV_KEY_INFO(p8, &encoded_data)) <= 0 || encoded_data == NULL) return NULL; p8_data = encoded_data; len = encoded_len; selection = EVP_PKEY_KEYPAIR | EVP_PKEY_KEY_PARAMETERS; dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", "PrivateKeyInfo", keytype, selection, libctx, propq); if (dctx != NULL && OSSL_DECODER_CTX_get_num_decoders(dctx) == 0) { OSSL_DECODER_CTX_free(dctx); /* * This could happen if OBJ_obj2txt() returned a text OID and the * decoder has not got that OID as an alias. We fall back to a NULL * keytype */ dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", "PrivateKeyInfo", NULL, selection, libctx, propq); } if (dctx == NULL || !OSSL_DECODER_from_data(dctx, &p8_data, &len)) /* try legacy */ pkey = evp_pkcs82pkey_legacy(p8, libctx, propq); OPENSSL_clear_free(encoded_data, encoded_len); OSSL_DECODER_CTX_free(dctx); return pkey; } EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8) { return EVP_PKCS82PKEY_ex(p8, NULL, NULL); } /* Turn a private key into a PKCS8 structure */ PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey) { PKCS8_PRIV_KEY_INFO *p8 = NULL; OSSL_ENCODER_CTX *ctx = NULL; /* * The implementation for provider-native keys is to encode the * key to a DER encoded PKCS#8 structure, then convert it to a * PKCS8_PRIV_KEY_INFO with good old d2i functions. */ if (evp_pkey_is_provided(pkey)) { int selection = OSSL_KEYMGMT_SELECT_ALL; unsigned char *der = NULL; size_t derlen = 0; const unsigned char *pp; if ((ctx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, "DER", "PrivateKeyInfo", NULL)) == NULL || !OSSL_ENCODER_to_data(ctx, &der, &derlen)) goto error; pp = der; p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &pp, (long)derlen); OPENSSL_free(der); if (p8 == NULL) goto error; } else { p8 = PKCS8_PRIV_KEY_INFO_new(); if (p8 == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_ASN1_LIB); return NULL; } if (pkey->ameth != NULL) { if (pkey->ameth->priv_encode != NULL) { if (!pkey->ameth->priv_encode(p8, pkey)) { ERR_raise(ERR_LIB_EVP, EVP_R_PRIVATE_KEY_ENCODE_ERROR); goto error; } } else { ERR_raise(ERR_LIB_EVP, EVP_R_METHOD_NOT_SUPPORTED); goto error; } } else { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM); goto error; } } goto end; error: PKCS8_PRIV_KEY_INFO_free(p8); p8 = NULL; end: OSSL_ENCODER_CTX_free(ctx); return p8; } /* EVP_PKEY attribute functions */ int EVP_PKEY_get_attr_count(const EVP_PKEY *key) { return X509at_get_attr_count(key->attributes); } int EVP_PKEY_get_attr_by_NID(const EVP_PKEY *key, int nid, int lastpos) { return X509at_get_attr_by_NID(key->attributes, nid, lastpos); } int EVP_PKEY_get_attr_by_OBJ(const EVP_PKEY *key, const ASN1_OBJECT *obj, int lastpos) { return X509at_get_attr_by_OBJ(key->attributes, obj, lastpos); } X509_ATTRIBUTE *EVP_PKEY_get_attr(const EVP_PKEY *key, int loc) { return X509at_get_attr(key->attributes, loc); } X509_ATTRIBUTE *EVP_PKEY_delete_attr(EVP_PKEY *key, int loc) { return X509at_delete_attr(key->attributes, loc); } int EVP_PKEY_add1_attr(EVP_PKEY *key, X509_ATTRIBUTE *attr) { if (X509at_add1_attr(&key->attributes, attr)) return 1; return 0; } int EVP_PKEY_add1_attr_by_OBJ(EVP_PKEY *key, const ASN1_OBJECT *obj, int type, const unsigned char *bytes, int len) { if (X509at_add1_attr_by_OBJ(&key->attributes, obj, type, bytes, len)) return 1; return 0; } int EVP_PKEY_add1_attr_by_NID(EVP_PKEY *key, int nid, int type, const unsigned char *bytes, int len) { if (X509at_add1_attr_by_NID(&key->attributes, nid, type, bytes, len)) return 1; return 0; } int EVP_PKEY_add1_attr_by_txt(EVP_PKEY *key, const char *attrname, int type, const unsigned char *bytes, int len) { if (X509at_add1_attr_by_txt(&key->attributes, attrname, type, bytes, len)) return 1; return 0; } const char *EVP_PKEY_get0_type_name(const EVP_PKEY *key) { const EVP_PKEY_ASN1_METHOD *ameth; const char *name = NULL; if (key->keymgmt != NULL) return EVP_KEYMGMT_get0_name(key->keymgmt); /* Otherwise fallback to legacy */ ameth = EVP_PKEY_get0_asn1(key); if (ameth != NULL) EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &name, ameth); return name; } const OSSL_PROVIDER *EVP_PKEY_get0_provider(const EVP_PKEY *key) { if (evp_pkey_is_provided(key)) return EVP_KEYMGMT_get0_provider(key->keymgmt); return NULL; }
./openssl/crypto/evp/dsa_ctrl.c
/* * Copyright 2020-2021 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 <openssl/core_names.h> #include <openssl/err.h> #include <openssl/dsa.h> #include <openssl/evp.h> #include "crypto/evp.h" static int dsa_paramgen_check(EVP_PKEY_CTX *ctx) { if (ctx == NULL || !EVP_PKEY_CTX_IS_GEN_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* If key type not DSA return error */ if (ctx->pmeth != NULL && ctx->pmeth->pkey_id != EVP_PKEY_DSA) return -1; return 1; } int EVP_PKEY_CTX_set_dsa_paramgen_type(EVP_PKEY_CTX *ctx, const char *name) { int ret; OSSL_PARAM params[2], *p = params; if ((ret = dsa_paramgen_check(ctx)) <= 0) return ret; *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_TYPE, (char *)name, 0); *p++ = OSSL_PARAM_construct_end(); return EVP_PKEY_CTX_set_params(ctx, params); } int EVP_PKEY_CTX_set_dsa_paramgen_gindex(EVP_PKEY_CTX *ctx, int gindex) { int ret; OSSL_PARAM params[2], *p = params; if ((ret = dsa_paramgen_check(ctx)) <= 0) return ret; *p++ = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_GINDEX, &gindex); *p++ = OSSL_PARAM_construct_end(); return EVP_PKEY_CTX_set_params(ctx, params); } int EVP_PKEY_CTX_set_dsa_paramgen_seed(EVP_PKEY_CTX *ctx, const unsigned char *seed, size_t seedlen) { int ret; OSSL_PARAM params[2], *p = params; if ((ret = dsa_paramgen_check(ctx)) <= 0) return ret; *p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_FFC_SEED, (void *)seed, seedlen); *p++ = OSSL_PARAM_construct_end(); return EVP_PKEY_CTX_set_params(ctx, params); } int EVP_PKEY_CTX_set_dsa_paramgen_bits(EVP_PKEY_CTX *ctx, int nbits) { int ret; OSSL_PARAM params[2], *p = params; size_t bits = nbits; if ((ret = dsa_paramgen_check(ctx)) <= 0) return ret; *p++ = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_FFC_PBITS, &bits); *p++ = OSSL_PARAM_construct_end(); return EVP_PKEY_CTX_set_params(ctx, params); } int EVP_PKEY_CTX_set_dsa_paramgen_q_bits(EVP_PKEY_CTX *ctx, int qbits) { int ret; OSSL_PARAM params[2], *p = params; size_t bits2 = qbits; if ((ret = dsa_paramgen_check(ctx)) <= 0) return ret; *p++ = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_FFC_QBITS, &bits2); *p++ = OSSL_PARAM_construct_end(); return EVP_PKEY_CTX_set_params(ctx, params); } int EVP_PKEY_CTX_set_dsa_paramgen_md_props(EVP_PKEY_CTX *ctx, const char *md_name, const char *md_properties) { int ret; OSSL_PARAM params[3], *p = params; if ((ret = dsa_paramgen_check(ctx)) <= 0) return ret; *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST, (char *)md_name, 0); if (md_properties != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST_PROPS, (char *)md_properties, 0); *p++ = OSSL_PARAM_construct_end(); return EVP_PKEY_CTX_set_params(ctx, params); } #if !defined(FIPS_MODULE) int EVP_PKEY_CTX_set_dsa_paramgen_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DSA, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DSA_PARAMGEN_MD, 0, (void *)(md)); } #endif
./openssl/crypto/evp/e_aria.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2017, 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 "internal/deprecated.h" #include "internal/cryptlib.h" #ifndef OPENSSL_NO_ARIA # include <openssl/evp.h> # include <openssl/modes.h> # include <openssl/rand.h> # include "crypto/aria.h" # include "crypto/evp.h" # include "crypto/modes.h" # include "evp_local.h" /* ARIA subkey Structure */ typedef struct { ARIA_KEY ks; } EVP_ARIA_KEY; /* ARIA GCM context */ typedef struct { union { OSSL_UNION_ALIGN; ARIA_KEY ks; } ks; /* ARIA subkey to use */ int key_set; /* Set if key initialised */ int iv_set; /* Set if an iv is set */ GCM128_CONTEXT gcm; unsigned char *iv; /* Temporary IV store */ int ivlen; /* IV length */ int taglen; int iv_gen; /* It is OK to generate IVs */ int tls_aad_len; /* TLS AAD length */ } EVP_ARIA_GCM_CTX; /* ARIA CCM context */ typedef struct { union { OSSL_UNION_ALIGN; ARIA_KEY ks; } ks; /* ARIA key schedule to use */ int key_set; /* Set if key initialised */ int iv_set; /* Set if an iv is set */ int tag_set; /* Set if tag is valid */ int len_set; /* Set if message length set */ int L, M; /* L and M parameters from RFC3610 */ int tls_aad_len; /* TLS AAD length */ CCM128_CONTEXT ccm; ccm128_f str; } EVP_ARIA_CCM_CTX; /* The subkey for ARIA is generated. */ static int aria_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int ret; int mode = EVP_CIPHER_CTX_get_mode(ctx); if (enc || (mode != EVP_CIPH_ECB_MODE && mode != EVP_CIPH_CBC_MODE)) ret = ossl_aria_set_encrypt_key(key, EVP_CIPHER_CTX_get_key_length(ctx) * 8, EVP_CIPHER_CTX_get_cipher_data(ctx)); else ret = ossl_aria_set_decrypt_key(key, EVP_CIPHER_CTX_get_key_length(ctx) * 8, EVP_CIPHER_CTX_get_cipher_data(ctx)); if (ret < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_ARIA_KEY_SETUP_FAILED); return 0; } return 1; } static void aria_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len, const ARIA_KEY *key, unsigned char *ivec, const int enc) { if (enc) CRYPTO_cbc128_encrypt(in, out, len, key, ivec, (block128_f) ossl_aria_encrypt); else CRYPTO_cbc128_decrypt(in, out, len, key, ivec, (block128_f) ossl_aria_encrypt); } static void aria_cfb128_encrypt(const unsigned char *in, unsigned char *out, size_t length, const ARIA_KEY *key, unsigned char *ivec, int *num, const int enc) { CRYPTO_cfb128_encrypt(in, out, length, key, ivec, num, enc, (block128_f) ossl_aria_encrypt); } static void aria_cfb1_encrypt(const unsigned char *in, unsigned char *out, size_t length, const ARIA_KEY *key, unsigned char *ivec, int *num, const int enc) { CRYPTO_cfb128_1_encrypt(in, out, length, key, ivec, num, enc, (block128_f) ossl_aria_encrypt); } static void aria_cfb8_encrypt(const unsigned char *in, unsigned char *out, size_t length, const ARIA_KEY *key, unsigned char *ivec, int *num, const int enc) { CRYPTO_cfb128_8_encrypt(in, out, length, key, ivec, num, enc, (block128_f) ossl_aria_encrypt); } static void aria_ecb_encrypt(const unsigned char *in, unsigned char *out, const ARIA_KEY *key, const int enc) { ossl_aria_encrypt(in, out, key); } static void aria_ofb128_encrypt(const unsigned char *in, unsigned char *out, size_t length, const ARIA_KEY *key, unsigned char *ivec, int *num) { CRYPTO_ofb128_encrypt(in, out, length, key, ivec, num, (block128_f) ossl_aria_encrypt); } IMPLEMENT_BLOCK_CIPHER(aria_128, ks, aria, EVP_ARIA_KEY, NID_aria_128, 16, 16, 16, 128, 0, aria_init_key, NULL, EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL) IMPLEMENT_BLOCK_CIPHER(aria_192, ks, aria, EVP_ARIA_KEY, NID_aria_192, 16, 24, 16, 128, 0, aria_init_key, NULL, EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL) IMPLEMENT_BLOCK_CIPHER(aria_256, ks, aria, EVP_ARIA_KEY, NID_aria_256, 16, 32, 16, 128, 0, aria_init_key, NULL, EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL) # define IMPLEMENT_ARIA_CFBR(ksize,cbits) \ IMPLEMENT_CFBR(aria,aria,EVP_ARIA_KEY,ks,ksize,cbits,16,0) IMPLEMENT_ARIA_CFBR(128,1) IMPLEMENT_ARIA_CFBR(192,1) IMPLEMENT_ARIA_CFBR(256,1) IMPLEMENT_ARIA_CFBR(128,8) IMPLEMENT_ARIA_CFBR(192,8) IMPLEMENT_ARIA_CFBR(256,8) # define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ static const EVP_CIPHER aria_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aria_init_key, \ aria_##mode##_cipher, \ NULL, \ sizeof(EVP_ARIA_KEY), \ NULL,NULL,NULL,NULL }; \ const EVP_CIPHER *EVP_aria_##keylen##_##mode(void) \ { return &aria_##keylen##_##mode; } static int aria_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { int n = EVP_CIPHER_CTX_get_num(ctx); unsigned int num; EVP_ARIA_KEY *dat = EVP_C_DATA(EVP_ARIA_KEY, ctx); if (n < 0) return 0; num = (unsigned int)n; CRYPTO_ctr128_encrypt(in, out, len, &dat->ks, ctx->iv, EVP_CIPHER_CTX_buf_noconst(ctx), &num, (block128_f) ossl_aria_encrypt); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } BLOCK_CIPHER_generic(NID_aria, 128, 1, 16, ctr, ctr, CTR, 0) BLOCK_CIPHER_generic(NID_aria, 192, 1, 16, ctr, ctr, CTR, 0) BLOCK_CIPHER_generic(NID_aria, 256, 1, 16, ctr, ctr, CTR, 0) /* Authenticated cipher modes (GCM/CCM) */ /* increment counter (64-bit int) by 1 */ static void ctr64_inc(unsigned char *counter) { int n = 8; unsigned char c; do { --n; c = counter[n]; ++c; counter[n] = c; if (c) return; } while (n); } static int aria_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int ret; EVP_ARIA_GCM_CTX *gctx = EVP_C_DATA(EVP_ARIA_GCM_CTX, ctx); if (!iv && !key) return 1; if (key) { ret = ossl_aria_set_encrypt_key(key, EVP_CIPHER_CTX_get_key_length(ctx) * 8, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) ossl_aria_encrypt); if (ret < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_ARIA_KEY_SETUP_FAILED); return 0; } /* * If we have an iv can set it directly, otherwise use saved IV. */ if (iv == NULL && gctx->iv_set) iv = gctx->iv; if (iv) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); gctx->iv_set = 1; } gctx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (gctx->key_set) CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); else memcpy(gctx->iv, iv, gctx->ivlen); gctx->iv_set = 1; gctx->iv_gen = 0; } return 1; } static int aria_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_ARIA_GCM_CTX *gctx = EVP_C_DATA(EVP_ARIA_GCM_CTX, c); switch (type) { case EVP_CTRL_INIT: gctx->key_set = 0; gctx->iv_set = 0; gctx->ivlen = EVP_CIPHER_get_iv_length(c->cipher); gctx->iv = c->iv; gctx->taglen = -1; gctx->iv_gen = 0; gctx->tls_aad_len = -1; return 1; case EVP_CTRL_GET_IVLEN: *(int *)ptr = gctx->ivlen; return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0) return 0; /* Allocate memory for IV if needed */ if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) { if (gctx->iv != c->iv) OPENSSL_free(gctx->iv); if ((gctx->iv = OPENSSL_malloc(arg)) == NULL) return 0; } gctx->ivlen = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > 16 || EVP_CIPHER_CTX_is_encrypting(c)) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->taglen = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > 16 || !EVP_CIPHER_CTX_is_encrypting(c) || gctx->taglen < 0) return 0; memcpy(ptr, EVP_CIPHER_CTX_buf_noconst(c), arg); return 1; case EVP_CTRL_GCM_SET_IV_FIXED: /* Special case: -1 length restores whole IV */ if (arg == -1) { memcpy(gctx->iv, ptr, gctx->ivlen); gctx->iv_gen = 1; return 1; } /* * Fixed field must be at least 4 bytes and invocation field at least * 8. */ if ((arg < 4) || (gctx->ivlen - arg) < 8) return 0; if (arg) memcpy(gctx->iv, ptr, arg); if (EVP_CIPHER_CTX_is_encrypting(c) && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0) return 0; gctx->iv_gen = 1; return 1; case EVP_CTRL_GCM_IV_GEN: if (gctx->iv_gen == 0 || gctx->key_set == 0) return 0; CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); if (arg <= 0 || arg > gctx->ivlen) arg = gctx->ivlen; memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg); /* * Invocation field will be at least 8 bytes in size and so no need * to check wrap around or increment more than last 8 bytes. */ ctr64_inc(gctx->iv + gctx->ivlen - 8); gctx->iv_set = 1; return 1; case EVP_CTRL_GCM_SET_IV_INV: if (gctx->iv_gen == 0 || gctx->key_set == 0 || EVP_CIPHER_CTX_is_encrypting(c)) return 0; memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); gctx->iv_set = 1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->tls_aad_len = arg; { unsigned int len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ if (len < EVP_GCM_TLS_EXPLICIT_IV_LEN) return 0; len -= EVP_GCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_is_encrypting(c)) { if (len < EVP_GCM_TLS_TAG_LEN) return 0; len -= EVP_GCM_TLS_TAG_LEN; } EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return EVP_GCM_TLS_TAG_LEN; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_ARIA_GCM_CTX *gctx_out = EVP_C_DATA(EVP_ARIA_GCM_CTX, out); if (gctx->gcm.key) { if (gctx->gcm.key != &gctx->ks) return 0; gctx_out->gcm.key = &gctx_out->ks; } if (gctx->iv == c->iv) gctx_out->iv = out->iv; else { if ((gctx_out->iv = OPENSSL_malloc(gctx->ivlen)) == NULL) return 0; memcpy(gctx_out->iv, gctx->iv, gctx->ivlen); } return 1; } default: return -1; } } static int aria_gcm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_ARIA_GCM_CTX *gctx = EVP_C_DATA(EVP_ARIA_GCM_CTX, ctx); int rv = -1; /* Encrypt/decrypt must be performed in place */ if (out != in || len < (EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN)) return -1; /* * Set IV from start of buffer or generate IV and write to start of * buffer. */ if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CIPHER_CTX_is_encrypting(ctx) ? EVP_CTRL_GCM_IV_GEN : EVP_CTRL_GCM_SET_IV_INV, EVP_GCM_TLS_EXPLICIT_IV_LEN, out) <= 0) goto err; /* Use saved AAD */ if (CRYPTO_gcm128_aad(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), gctx->tls_aad_len)) goto err; /* Fix buffer and length to point to payload */ in += EVP_GCM_TLS_EXPLICIT_IV_LEN; out += EVP_GCM_TLS_EXPLICIT_IV_LEN; len -= EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { /* Encrypt payload */ if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, len)) goto err; out += len; /* Finally write tag */ CRYPTO_gcm128_tag(&gctx->gcm, out, EVP_GCM_TLS_TAG_LEN); rv = len + EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN; } else { /* Decrypt */ if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, len)) goto err; /* Retrieve tag */ CRYPTO_gcm128_tag(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), EVP_GCM_TLS_TAG_LEN); /* If tag mismatch wipe buffer */ if (CRYPTO_memcmp(EVP_CIPHER_CTX_buf_noconst(ctx), in + len, EVP_GCM_TLS_TAG_LEN)) { OPENSSL_cleanse(out, len); goto err; } rv = len; } err: gctx->iv_set = 0; gctx->tls_aad_len = -1; return rv; } static int aria_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_ARIA_GCM_CTX *gctx = EVP_C_DATA(EVP_ARIA_GCM_CTX, ctx); /* If not set up, return error */ if (!gctx->key_set) return -1; if (gctx->tls_aad_len >= 0) return aria_gcm_tls_cipher(ctx, out, in, len); if (!gctx->iv_set) return -1; if (in) { if (out == NULL) { if (CRYPTO_gcm128_aad(&gctx->gcm, in, len)) return -1; } else if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, len)) return -1; } else { if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, len)) return -1; } return len; } if (!EVP_CIPHER_CTX_is_encrypting(ctx)) { if (gctx->taglen < 0) return -1; if (CRYPTO_gcm128_finish(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), gctx->taglen) != 0) return -1; gctx->iv_set = 0; return 0; } CRYPTO_gcm128_tag(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), 16); gctx->taglen = 16; /* Don't reuse the IV */ gctx->iv_set = 0; return 0; } static int aria_gcm_cleanup(EVP_CIPHER_CTX *ctx) { EVP_ARIA_GCM_CTX *gctx = EVP_C_DATA(EVP_ARIA_GCM_CTX, ctx); if (gctx->iv != ctx->iv) OPENSSL_free(gctx->iv); return 1; } static int aria_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int ret; EVP_ARIA_CCM_CTX *cctx = EVP_C_DATA(EVP_ARIA_CCM_CTX, ctx); if (!iv && !key) return 1; if (key) { ret = ossl_aria_set_encrypt_key(key, EVP_CIPHER_CTX_get_key_length(ctx) * 8, &cctx->ks.ks); CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, &cctx->ks, (block128_f) ossl_aria_encrypt); if (ret < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_ARIA_KEY_SETUP_FAILED); return 0; } cctx->str = NULL; cctx->key_set = 1; } if (iv) { memcpy(ctx->iv, iv, 15 - cctx->L); cctx->iv_set = 1; } return 1; } static int aria_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_ARIA_CCM_CTX *cctx = EVP_C_DATA(EVP_ARIA_CCM_CTX, c); switch (type) { case EVP_CTRL_INIT: cctx->key_set = 0; cctx->iv_set = 0; cctx->L = 8; cctx->M = 12; cctx->tag_set = 0; cctx->len_set = 0; cctx->tls_aad_len = -1; return 1; case EVP_CTRL_GET_IVLEN: *(int *)ptr = 15 - cctx->L; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); cctx->tls_aad_len = arg; { uint16_t len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ if (len < EVP_CCM_TLS_EXPLICIT_IV_LEN) return 0; len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_is_encrypting(c)) { if (len < cctx->M) return 0; len -= cctx->M; } EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return cctx->M; case EVP_CTRL_CCM_SET_IV_FIXED: /* Sanity check length */ if (arg != EVP_CCM_TLS_FIXED_IV_LEN) return 0; /* Just copy to first part of IV */ memcpy(c->iv, ptr, arg); return 1; case EVP_CTRL_AEAD_SET_IVLEN: arg = 15 - arg; /* fall through */ case EVP_CTRL_CCM_SET_L: if (arg < 2 || arg > 8) return 0; cctx->L = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if ((arg & 1) || arg < 4 || arg > 16) return 0; if (EVP_CIPHER_CTX_is_encrypting(c) && ptr) return 0; if (ptr) { cctx->tag_set = 1; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); } cctx->M = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (!EVP_CIPHER_CTX_is_encrypting(c) || !cctx->tag_set) return 0; if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg)) return 0; cctx->tag_set = 0; cctx->iv_set = 0; cctx->len_set = 0; return 1; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_ARIA_CCM_CTX *cctx_out = EVP_C_DATA(EVP_ARIA_CCM_CTX, out); if (cctx->ccm.key) { if (cctx->ccm.key != &cctx->ks) return 0; cctx_out->ccm.key = &cctx_out->ks; } return 1; } default: return -1; } } static int aria_ccm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_ARIA_CCM_CTX *cctx = EVP_C_DATA(EVP_ARIA_CCM_CTX, ctx); CCM128_CONTEXT *ccm = &cctx->ccm; /* Encrypt/decrypt must be performed in place */ if (out != in || len < (EVP_CCM_TLS_EXPLICIT_IV_LEN + (size_t)cctx->M)) return -1; /* If encrypting set explicit IV from sequence number (start of AAD) */ if (EVP_CIPHER_CTX_is_encrypting(ctx)) memcpy(out, EVP_CIPHER_CTX_buf_noconst(ctx), EVP_CCM_TLS_EXPLICIT_IV_LEN); /* Get rest of IV from explicit IV */ memcpy(ctx->iv + EVP_CCM_TLS_FIXED_IV_LEN, in, EVP_CCM_TLS_EXPLICIT_IV_LEN); /* Correct length value */ len -= EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->M; if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len)) return -1; /* Use saved AAD */ CRYPTO_ccm128_aad(ccm, EVP_CIPHER_CTX_buf_noconst(ctx), cctx->tls_aad_len); /* Fix buffer to point to payload */ in += EVP_CCM_TLS_EXPLICIT_IV_LEN; out += EVP_CCM_TLS_EXPLICIT_IV_LEN; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (cctx->str ? CRYPTO_ccm128_encrypt_ccm64(ccm, in, out, len, cctx->str) : CRYPTO_ccm128_encrypt(ccm, in, out, len)) return -1; if (!CRYPTO_ccm128_tag(ccm, out + len, cctx->M)) return -1; return len + EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->M; } else { if (cctx->str ? !CRYPTO_ccm128_decrypt_ccm64(ccm, in, out, len, cctx->str) : !CRYPTO_ccm128_decrypt(ccm, in, out, len)) { unsigned char tag[16]; if (CRYPTO_ccm128_tag(ccm, tag, cctx->M)) { if (!CRYPTO_memcmp(tag, in + len, cctx->M)) return len; } } OPENSSL_cleanse(out, len); return -1; } } static int aria_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_ARIA_CCM_CTX *cctx = EVP_C_DATA(EVP_ARIA_CCM_CTX, ctx); CCM128_CONTEXT *ccm = &cctx->ccm; /* If not set up, return error */ if (!cctx->key_set) return -1; if (cctx->tls_aad_len >= 0) return aria_ccm_tls_cipher(ctx, out, in, len); /* EVP_*Final() doesn't return any data */ if (in == NULL && out != NULL) return 0; if (!cctx->iv_set) return -1; if (!out) { if (!in) { if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len)) return -1; cctx->len_set = 1; return len; } /* If have AAD need message length */ if (!cctx->len_set && len) return -1; CRYPTO_ccm128_aad(ccm, in, len); return len; } /* The tag must be set before actually decrypting data */ if (!EVP_CIPHER_CTX_is_encrypting(ctx) && !cctx->tag_set) return -1; /* If not set length yet do it */ if (!cctx->len_set) { if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len)) return -1; cctx->len_set = 1; } if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (cctx->str ? CRYPTO_ccm128_encrypt_ccm64(ccm, in, out, len, cctx->str) : CRYPTO_ccm128_encrypt(ccm, in, out, len)) return -1; cctx->tag_set = 1; return len; } else { int rv = -1; if (cctx->str ? !CRYPTO_ccm128_decrypt_ccm64(ccm, in, out, len, cctx->str) : !CRYPTO_ccm128_decrypt(ccm, in, out, len)) { unsigned char tag[16]; if (CRYPTO_ccm128_tag(ccm, tag, cctx->M)) { if (!CRYPTO_memcmp(tag, EVP_CIPHER_CTX_buf_noconst(ctx), cctx->M)) rv = len; } } if (rv == -1) OPENSSL_cleanse(out, len); cctx->iv_set = 0; cctx->tag_set = 0; cctx->len_set = 0; return rv; } } #define aria_ccm_cleanup NULL #define ARIA_AUTH_FLAGS (EVP_CIPH_FLAG_DEFAULT_ASN1 \ | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \ | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \ | EVP_CIPH_CUSTOM_COPY | EVP_CIPH_FLAG_AEAD_CIPHER \ | EVP_CIPH_CUSTOM_IV_LENGTH) #define BLOCK_CIPHER_aead(keylen,mode,MODE) \ static const EVP_CIPHER aria_##keylen##_##mode = { \ NID_aria_##keylen##_##mode, \ 1, keylen/8, 12, \ ARIA_AUTH_FLAGS|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aria_##mode##_init_key, \ aria_##mode##_cipher, \ aria_##mode##_cleanup, \ sizeof(EVP_ARIA_##MODE##_CTX), \ NULL,NULL,aria_##mode##_ctrl,NULL }; \ const EVP_CIPHER *EVP_aria_##keylen##_##mode(void) \ { return (EVP_CIPHER*)&aria_##keylen##_##mode; } BLOCK_CIPHER_aead(128, gcm, GCM) BLOCK_CIPHER_aead(192, gcm, GCM) BLOCK_CIPHER_aead(256, gcm, GCM) BLOCK_CIPHER_aead(128, ccm, CCM) BLOCK_CIPHER_aead(192, ccm, CCM) BLOCK_CIPHER_aead(256, ccm, CCM) #endif
./openssl/crypto/evp/p_legacy.c
/* * Copyright 1995-2021 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 */ /* * Legacy EVP_PKEY assign/set/get APIs are deprecated for public use, but * still ok for internal use, particularly in providers. */ #include "internal/deprecated.h" #include <openssl/types.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/rsa.h> #include <openssl/ec.h> #include "crypto/types.h" #include "crypto/evp.h" #include "evp_local.h" int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key) { int ret = EVP_PKEY_assign_RSA(pkey, key); if (ret) RSA_up_ref(key); return ret; } RSA *evp_pkey_get0_RSA_int(const EVP_PKEY *pkey) { if (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_RSA_PSS) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_AN_RSA_KEY); return NULL; } return evp_pkey_get_legacy((EVP_PKEY *)pkey); } const RSA *EVP_PKEY_get0_RSA(const EVP_PKEY *pkey) { return evp_pkey_get0_RSA_int(pkey); } RSA *EVP_PKEY_get1_RSA(EVP_PKEY *pkey) { RSA *ret = evp_pkey_get0_RSA_int(pkey); if (ret != NULL) RSA_up_ref(ret); return ret; } #ifndef OPENSSL_NO_EC int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, EC_KEY *key) { if (!EC_KEY_up_ref(key)) return 0; if (!EVP_PKEY_assign_EC_KEY(pkey, key)) { EC_KEY_free(key); return 0; } return 1; } EC_KEY *evp_pkey_get0_EC_KEY_int(const EVP_PKEY *pkey) { if (EVP_PKEY_get_base_id(pkey) != EVP_PKEY_EC) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_EC_KEY); return NULL; } return evp_pkey_get_legacy((EVP_PKEY *)pkey); } const EC_KEY *EVP_PKEY_get0_EC_KEY(const EVP_PKEY *pkey) { return evp_pkey_get0_EC_KEY_int(pkey); } EC_KEY *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey) { EC_KEY *ret = evp_pkey_get0_EC_KEY_int(pkey); if (ret != NULL && !EC_KEY_up_ref(ret)) ret = NULL; return ret; } #endif /* OPENSSL_NO_EC */
./openssl/crypto/evp/evp_pbe.c
/* * Copyright 1999-2023 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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/core.h> #include <openssl/core_names.h> #include <openssl/pkcs12.h> #include <openssl/x509.h> #include "crypto/evp.h" #include "evp_local.h" /* Password based encryption (PBE) functions */ /* Setup a cipher context from a PBE algorithm */ struct evp_pbe_st { int pbe_type; int pbe_nid; int cipher_nid; int md_nid; EVP_PBE_KEYGEN *keygen; EVP_PBE_KEYGEN_EX *keygen_ex; }; static STACK_OF(EVP_PBE_CTL) *pbe_algs; static const EVP_PBE_CTL builtin_pbe[] = { {EVP_PBE_TYPE_OUTER, NID_pbeWithMD2AndDES_CBC, NID_des_cbc, NID_md2, PKCS5_PBE_keyivgen, PKCS5_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_pbeWithMD5AndDES_CBC, NID_des_cbc, NID_md5, PKCS5_PBE_keyivgen, PKCS5_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_pbeWithSHA1AndRC2_CBC, NID_rc2_64_cbc, NID_sha1, PKCS5_PBE_keyivgen, PKCS5_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_id_pbkdf2, -1, -1, PKCS5_v2_PBKDF2_keyivgen}, {EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And128BitRC4, NID_rc4, NID_sha1, PKCS12_PBE_keyivgen, &PKCS12_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And40BitRC4, NID_rc4_40, NID_sha1, PKCS12_PBE_keyivgen, &PKCS12_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, NID_des_ede3_cbc, NID_sha1, PKCS12_PBE_keyivgen, &PKCS12_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And2_Key_TripleDES_CBC, NID_des_ede_cbc, NID_sha1, PKCS12_PBE_keyivgen, &PKCS12_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And128BitRC2_CBC, NID_rc2_cbc, NID_sha1, PKCS12_PBE_keyivgen, &PKCS12_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And40BitRC2_CBC, NID_rc2_40_cbc, NID_sha1, PKCS12_PBE_keyivgen, &PKCS12_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_pbes2, -1, -1, PKCS5_v2_PBE_keyivgen, &PKCS5_v2_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_pbeWithMD2AndRC2_CBC, NID_rc2_64_cbc, NID_md2, PKCS5_PBE_keyivgen, PKCS5_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_pbeWithMD5AndRC2_CBC, NID_rc2_64_cbc, NID_md5, PKCS5_PBE_keyivgen, PKCS5_PBE_keyivgen_ex}, {EVP_PBE_TYPE_OUTER, NID_pbeWithSHA1AndDES_CBC, NID_des_cbc, NID_sha1, PKCS5_PBE_keyivgen, PKCS5_PBE_keyivgen_ex}, {EVP_PBE_TYPE_PRF, NID_hmacWithSHA1, -1, NID_sha1, 0}, {EVP_PBE_TYPE_PRF, NID_hmac_md5, -1, NID_md5, 0}, {EVP_PBE_TYPE_PRF, NID_hmac_sha1, -1, NID_sha1, 0}, {EVP_PBE_TYPE_PRF, NID_hmacWithMD5, -1, NID_md5, 0}, {EVP_PBE_TYPE_PRF, NID_hmacWithSHA224, -1, NID_sha224, 0}, {EVP_PBE_TYPE_PRF, NID_hmacWithSHA256, -1, NID_sha256, 0}, {EVP_PBE_TYPE_PRF, NID_hmacWithSHA384, -1, NID_sha384, 0}, {EVP_PBE_TYPE_PRF, NID_hmacWithSHA512, -1, NID_sha512, 0}, {EVP_PBE_TYPE_PRF, NID_id_HMACGostR3411_94, -1, NID_id_GostR3411_94, 0}, {EVP_PBE_TYPE_PRF, NID_id_tc26_hmac_gost_3411_2012_256, -1, NID_id_GostR3411_2012_256, 0}, {EVP_PBE_TYPE_PRF, NID_id_tc26_hmac_gost_3411_2012_512, -1, NID_id_GostR3411_2012_512, 0}, {EVP_PBE_TYPE_PRF, NID_hmac_sha3_224, -1, NID_sha3_224, 0}, {EVP_PBE_TYPE_PRF, NID_hmac_sha3_256, -1, NID_sha3_256, 0}, {EVP_PBE_TYPE_PRF, NID_hmac_sha3_384, -1, NID_sha3_384, 0}, {EVP_PBE_TYPE_PRF, NID_hmac_sha3_512, -1, NID_sha3_512, 0}, {EVP_PBE_TYPE_PRF, NID_hmacWithSHA512_224, -1, NID_sha512_224, 0}, {EVP_PBE_TYPE_PRF, NID_hmacWithSHA512_256, -1, NID_sha512_256, 0}, #ifndef OPENSSL_NO_SM3 {EVP_PBE_TYPE_PRF, NID_hmacWithSM3, -1, NID_sm3, 0}, #endif {EVP_PBE_TYPE_KDF, NID_id_pbkdf2, -1, -1, PKCS5_v2_PBKDF2_keyivgen, &PKCS5_v2_PBKDF2_keyivgen_ex}, #ifndef OPENSSL_NO_SCRYPT {EVP_PBE_TYPE_KDF, NID_id_scrypt, -1, -1, PKCS5_v2_scrypt_keyivgen, &PKCS5_v2_scrypt_keyivgen_ex} #endif }; int EVP_PBE_CipherInit_ex(ASN1_OBJECT *pbe_obj, const char *pass, int passlen, ASN1_TYPE *param, EVP_CIPHER_CTX *ctx, int en_de, OSSL_LIB_CTX *libctx, const char *propq) { const EVP_CIPHER *cipher = NULL; EVP_CIPHER *cipher_fetch = NULL; const EVP_MD *md = NULL; EVP_MD *md_fetch = NULL; int ret = 0, cipher_nid, md_nid; EVP_PBE_KEYGEN_EX *keygen_ex; EVP_PBE_KEYGEN *keygen; if (!EVP_PBE_find_ex(EVP_PBE_TYPE_OUTER, OBJ_obj2nid(pbe_obj), &cipher_nid, &md_nid, &keygen, &keygen_ex)) { char obj_tmp[80]; if (pbe_obj == NULL) OPENSSL_strlcpy(obj_tmp, "NULL", sizeof(obj_tmp)); else i2t_ASN1_OBJECT(obj_tmp, sizeof(obj_tmp), pbe_obj); ERR_raise_data(ERR_LIB_EVP, EVP_R_UNKNOWN_PBE_ALGORITHM, "TYPE=%s", obj_tmp); goto err; } if (pass == NULL) passlen = 0; else if (passlen == -1) passlen = strlen(pass); if (cipher_nid != -1) { (void)ERR_set_mark(); cipher = cipher_fetch = EVP_CIPHER_fetch(libctx, OBJ_nid2sn(cipher_nid), propq); /* Fallback to legacy method */ if (cipher == NULL) cipher = EVP_get_cipherbynid(cipher_nid); if (cipher == NULL) { (void)ERR_clear_last_mark(); ERR_raise_data(ERR_LIB_EVP, EVP_R_UNKNOWN_CIPHER, OBJ_nid2sn(cipher_nid)); goto err; } (void)ERR_pop_to_mark(); } if (md_nid != -1) { (void)ERR_set_mark(); md = md_fetch = EVP_MD_fetch(libctx, OBJ_nid2sn(md_nid), propq); /* Fallback to legacy method */ if (md == NULL) md = EVP_get_digestbynid(md_nid); if (md == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_UNKNOWN_DIGEST); goto err; } (void)ERR_pop_to_mark(); } /* Try extended keygen with libctx/propq first, fall back to legacy keygen */ if (keygen_ex != NULL) ret = keygen_ex(ctx, pass, passlen, param, cipher, md, en_de, libctx, propq); else ret = keygen(ctx, pass, passlen, param, cipher, md, en_de); err: EVP_CIPHER_free(cipher_fetch); EVP_MD_free(md_fetch); return ret; } int EVP_PBE_CipherInit(ASN1_OBJECT *pbe_obj, const char *pass, int passlen, ASN1_TYPE *param, EVP_CIPHER_CTX *ctx, int en_de) { return EVP_PBE_CipherInit_ex(pbe_obj, pass, passlen, param, ctx, en_de, NULL, NULL); } DECLARE_OBJ_BSEARCH_CMP_FN(EVP_PBE_CTL, EVP_PBE_CTL, pbe2); static int pbe2_cmp(const EVP_PBE_CTL *pbe1, const EVP_PBE_CTL *pbe2) { int ret = pbe1->pbe_type - pbe2->pbe_type; if (ret) return ret; else return pbe1->pbe_nid - pbe2->pbe_nid; } IMPLEMENT_OBJ_BSEARCH_CMP_FN(EVP_PBE_CTL, EVP_PBE_CTL, pbe2); static int pbe_cmp(const EVP_PBE_CTL *const *a, const EVP_PBE_CTL *const *b) { int ret = (*a)->pbe_type - (*b)->pbe_type; if (ret) return ret; else return (*a)->pbe_nid - (*b)->pbe_nid; } /* Add a PBE algorithm */ int EVP_PBE_alg_add_type(int pbe_type, int pbe_nid, int cipher_nid, int md_nid, EVP_PBE_KEYGEN *keygen) { EVP_PBE_CTL *pbe_tmp = NULL; if (pbe_algs == NULL) { pbe_algs = sk_EVP_PBE_CTL_new(pbe_cmp); if (pbe_algs == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_CRYPTO_LIB); goto err; } } if ((pbe_tmp = OPENSSL_zalloc(sizeof(*pbe_tmp))) == NULL) goto err; pbe_tmp->pbe_type = pbe_type; pbe_tmp->pbe_nid = pbe_nid; pbe_tmp->cipher_nid = cipher_nid; pbe_tmp->md_nid = md_nid; pbe_tmp->keygen = keygen; if (!sk_EVP_PBE_CTL_push(pbe_algs, pbe_tmp)) { ERR_raise(ERR_LIB_EVP, ERR_R_CRYPTO_LIB); goto err; } return 1; err: OPENSSL_free(pbe_tmp); return 0; } int EVP_PBE_alg_add(int nid, const EVP_CIPHER *cipher, const EVP_MD *md, EVP_PBE_KEYGEN *keygen) { int cipher_nid, md_nid; if (cipher) cipher_nid = EVP_CIPHER_get_nid(cipher); else cipher_nid = -1; if (md) md_nid = EVP_MD_get_type(md); else md_nid = -1; return EVP_PBE_alg_add_type(EVP_PBE_TYPE_OUTER, nid, cipher_nid, md_nid, keygen); } int EVP_PBE_find_ex(int type, int pbe_nid, int *pcnid, int *pmnid, EVP_PBE_KEYGEN **pkeygen, EVP_PBE_KEYGEN_EX **pkeygen_ex) { EVP_PBE_CTL *pbetmp = NULL, pbelu; int i; if (pbe_nid == NID_undef) return 0; pbelu.pbe_type = type; pbelu.pbe_nid = pbe_nid; if (pbe_algs != NULL) { /* Ideally, this would be done under lock */ sk_EVP_PBE_CTL_sort(pbe_algs); i = sk_EVP_PBE_CTL_find(pbe_algs, &pbelu); pbetmp = sk_EVP_PBE_CTL_value(pbe_algs, i); } if (pbetmp == NULL) { pbetmp = OBJ_bsearch_pbe2(&pbelu, builtin_pbe, OSSL_NELEM(builtin_pbe)); } if (pbetmp == NULL) return 0; if (pcnid != NULL) *pcnid = pbetmp->cipher_nid; if (pmnid != NULL) *pmnid = pbetmp->md_nid; if (pkeygen != NULL) *pkeygen = pbetmp->keygen; if (pkeygen_ex != NULL) *pkeygen_ex = pbetmp->keygen_ex; return 1; } int EVP_PBE_find(int type, int pbe_nid, int *pcnid, int *pmnid, EVP_PBE_KEYGEN **pkeygen) { return EVP_PBE_find_ex(type, pbe_nid, pcnid, pmnid, pkeygen, NULL); } static void free_evp_pbe_ctl(EVP_PBE_CTL *pbe) { OPENSSL_free(pbe); } void EVP_PBE_cleanup(void) { sk_EVP_PBE_CTL_pop_free(pbe_algs, free_evp_pbe_ctl); pbe_algs = NULL; } int EVP_PBE_get(int *ptype, int *ppbe_nid, size_t num) { const EVP_PBE_CTL *tpbe; if (num >= OSSL_NELEM(builtin_pbe)) return 0; tpbe = builtin_pbe + num; if (ptype) *ptype = tpbe->pbe_type; if (ppbe_nid) *ppbe_nid = tpbe->pbe_nid; return 1; }
./openssl/crypto/evp/mac_meth.c
/* * Copyright 2022-2023 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 <openssl/evp.h> #include <openssl/err.h> #include <openssl/core.h> #include <openssl/core_dispatch.h> #include "internal/provider.h" #include "internal/core.h" #include "crypto/evp.h" #include "evp_local.h" static int evp_mac_up_ref(void *vmac) { EVP_MAC *mac = vmac; int ref = 0; CRYPTO_UP_REF(&mac->refcnt, &ref); return 1; } static void evp_mac_free(void *vmac) { EVP_MAC *mac = vmac; int ref = 0; if (mac == NULL) return; CRYPTO_DOWN_REF(&mac->refcnt, &ref); if (ref > 0) return; OPENSSL_free(mac->type_name); ossl_provider_free(mac->prov); CRYPTO_FREE_REF(&mac->refcnt); OPENSSL_free(mac); } static void *evp_mac_new(void) { EVP_MAC *mac = NULL; if ((mac = OPENSSL_zalloc(sizeof(*mac))) == NULL || !CRYPTO_NEW_REF(&mac->refcnt, 1)) { evp_mac_free(mac); return NULL; } return mac; } static void *evp_mac_from_algorithm(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { const OSSL_DISPATCH *fns = algodef->implementation; EVP_MAC *mac = NULL; int fnmaccnt = 0, fnctxcnt = 0; if ((mac = evp_mac_new()) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return NULL; } mac->name_id = name_id; if ((mac->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) { evp_mac_free(mac); return NULL; } mac->description = algodef->algorithm_description; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_MAC_NEWCTX: if (mac->newctx != NULL) break; mac->newctx = OSSL_FUNC_mac_newctx(fns); fnctxcnt++; break; case OSSL_FUNC_MAC_DUPCTX: if (mac->dupctx != NULL) break; mac->dupctx = OSSL_FUNC_mac_dupctx(fns); break; case OSSL_FUNC_MAC_FREECTX: if (mac->freectx != NULL) break; mac->freectx = OSSL_FUNC_mac_freectx(fns); fnctxcnt++; break; case OSSL_FUNC_MAC_INIT: if (mac->init != NULL) break; mac->init = OSSL_FUNC_mac_init(fns); fnmaccnt++; break; case OSSL_FUNC_MAC_UPDATE: if (mac->update != NULL) break; mac->update = OSSL_FUNC_mac_update(fns); fnmaccnt++; break; case OSSL_FUNC_MAC_FINAL: if (mac->final != NULL) break; mac->final = OSSL_FUNC_mac_final(fns); fnmaccnt++; break; case OSSL_FUNC_MAC_GETTABLE_PARAMS: if (mac->gettable_params != NULL) break; mac->gettable_params = OSSL_FUNC_mac_gettable_params(fns); break; case OSSL_FUNC_MAC_GETTABLE_CTX_PARAMS: if (mac->gettable_ctx_params != NULL) break; mac->gettable_ctx_params = OSSL_FUNC_mac_gettable_ctx_params(fns); break; case OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS: if (mac->settable_ctx_params != NULL) break; mac->settable_ctx_params = OSSL_FUNC_mac_settable_ctx_params(fns); break; case OSSL_FUNC_MAC_GET_PARAMS: if (mac->get_params != NULL) break; mac->get_params = OSSL_FUNC_mac_get_params(fns); break; case OSSL_FUNC_MAC_GET_CTX_PARAMS: if (mac->get_ctx_params != NULL) break; mac->get_ctx_params = OSSL_FUNC_mac_get_ctx_params(fns); break; case OSSL_FUNC_MAC_SET_CTX_PARAMS: if (mac->set_ctx_params != NULL) break; mac->set_ctx_params = OSSL_FUNC_mac_set_ctx_params(fns); break; } } if (fnmaccnt != 3 || fnctxcnt != 2) { /* * In order to be a consistent set of functions we must have at least * a complete set of "mac" functions, and a complete set of context * management functions, as well as the size function. */ evp_mac_free(mac); ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS); return NULL; } mac->prov = prov; if (prov != NULL) ossl_provider_up_ref(prov); return mac; } EVP_MAC *EVP_MAC_fetch(OSSL_LIB_CTX *libctx, const char *algorithm, const char *properties) { return evp_generic_fetch(libctx, OSSL_OP_MAC, algorithm, properties, evp_mac_from_algorithm, evp_mac_up_ref, evp_mac_free); } int EVP_MAC_up_ref(EVP_MAC *mac) { return evp_mac_up_ref(mac); } void EVP_MAC_free(EVP_MAC *mac) { evp_mac_free(mac); } const OSSL_PROVIDER *EVP_MAC_get0_provider(const EVP_MAC *mac) { return mac->prov; } const OSSL_PARAM *EVP_MAC_gettable_params(const EVP_MAC *mac) { if (mac->gettable_params == NULL) return NULL; return mac->gettable_params(ossl_provider_ctx(EVP_MAC_get0_provider(mac))); } const OSSL_PARAM *EVP_MAC_gettable_ctx_params(const EVP_MAC *mac) { void *alg; if (mac->gettable_ctx_params == NULL) return NULL; alg = ossl_provider_ctx(EVP_MAC_get0_provider(mac)); return mac->gettable_ctx_params(NULL, alg); } const OSSL_PARAM *EVP_MAC_settable_ctx_params(const EVP_MAC *mac) { void *alg; if (mac->settable_ctx_params == NULL) return NULL; alg = ossl_provider_ctx(EVP_MAC_get0_provider(mac)); return mac->settable_ctx_params(NULL, alg); } const OSSL_PARAM *EVP_MAC_CTX_gettable_params(EVP_MAC_CTX *ctx) { void *alg; if (ctx->meth->gettable_ctx_params == NULL) return NULL; alg = ossl_provider_ctx(EVP_MAC_get0_provider(ctx->meth)); return ctx->meth->gettable_ctx_params(ctx->algctx, alg); } const OSSL_PARAM *EVP_MAC_CTX_settable_params(EVP_MAC_CTX *ctx) { void *alg; if (ctx->meth->settable_ctx_params == NULL) return NULL; alg = ossl_provider_ctx(EVP_MAC_get0_provider(ctx->meth)); return ctx->meth->settable_ctx_params(ctx->algctx, alg); } void EVP_MAC_do_all_provided(OSSL_LIB_CTX *libctx, void (*fn)(EVP_MAC *mac, void *arg), void *arg) { evp_generic_do_all(libctx, OSSL_OP_MAC, (void (*)(void *, void *))fn, arg, evp_mac_from_algorithm, evp_mac_up_ref, evp_mac_free); }
./openssl/crypto/evp/dh_ctrl.c
/* * Copyright 2020-2021 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 "internal/deprecated.h" #include <openssl/core_names.h> #include <openssl/params.h> #include <openssl/err.h> #include <openssl/dh.h> #include "crypto/dh.h" #include "crypto/evp.h" static int dh_paramgen_check(EVP_PKEY_CTX *ctx) { if (ctx == NULL || !EVP_PKEY_CTX_IS_GEN_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* If key type not DH return error */ if (evp_pkey_ctx_is_legacy(ctx) && ctx->pmeth->pkey_id != EVP_PKEY_DH && ctx->pmeth->pkey_id != EVP_PKEY_DHX) return -1; return 1; } static int dh_param_derive_check(EVP_PKEY_CTX *ctx) { if (ctx == NULL || !EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* If key type not DH return error */ if (evp_pkey_ctx_is_legacy(ctx) && ctx->pmeth->pkey_id != EVP_PKEY_DH && ctx->pmeth->pkey_id != EVP_PKEY_DHX) return -1; return 1; } int EVP_PKEY_CTX_set_dh_paramgen_gindex(EVP_PKEY_CTX *ctx, int gindex) { int ret; OSSL_PARAM params[2], *p = params; if ((ret = dh_paramgen_check(ctx)) <= 0) return ret; *p++ = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_GINDEX, &gindex); *p = OSSL_PARAM_construct_end(); return evp_pkey_ctx_set_params_strict(ctx, params); } int EVP_PKEY_CTX_set_dh_paramgen_seed(EVP_PKEY_CTX *ctx, const unsigned char *seed, size_t seedlen) { int ret; OSSL_PARAM params[2], *p = params; if ((ret = dh_paramgen_check(ctx)) <= 0) return ret; *p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_FFC_SEED, (void *)seed, seedlen); *p = OSSL_PARAM_construct_end(); return evp_pkey_ctx_set_params_strict(ctx, params); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_dh_paramgen_type(EVP_PKEY_CTX *ctx, int typ) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_TYPE, typ, NULL); } int EVP_PKEY_CTX_set_dh_paramgen_prime_len(EVP_PKEY_CTX *ctx, int pbits) { int ret; OSSL_PARAM params[2], *p = params; size_t bits = pbits; if ((ret = dh_paramgen_check(ctx)) <= 0) return ret; *p++ = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_FFC_PBITS, &bits); *p = OSSL_PARAM_construct_end(); return evp_pkey_ctx_set_params_strict(ctx, params); } int EVP_PKEY_CTX_set_dh_paramgen_subprime_len(EVP_PKEY_CTX *ctx, int qbits) { int ret; OSSL_PARAM params[2], *p = params; size_t bits2 = qbits; if ((ret = dh_paramgen_check(ctx)) <= 0) return ret; *p++ = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_FFC_QBITS, &bits2); *p = OSSL_PARAM_construct_end(); return evp_pkey_ctx_set_params_strict(ctx, params); } int EVP_PKEY_CTX_set_dh_paramgen_generator(EVP_PKEY_CTX *ctx, int gen) { int ret; OSSL_PARAM params[2], *p = params; if ((ret = dh_paramgen_check(ctx)) <= 0) return ret; *p++ = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_DH_GENERATOR, &gen); *p = OSSL_PARAM_construct_end(); return evp_pkey_ctx_set_params_strict(ctx, params); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_dh_rfc5114(EVP_PKEY_CTX *ctx, int gen) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_RFC5114, gen, NULL); } int EVP_PKEY_CTX_set_dhx_rfc5114(EVP_PKEY_CTX *ctx, int gen) { return EVP_PKEY_CTX_set_dh_rfc5114(ctx, gen); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_dh_nid(EVP_PKEY_CTX *ctx, int nid) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_DH_NID, nid, NULL); } int EVP_PKEY_CTX_set_dh_pad(EVP_PKEY_CTX *ctx, int pad) { OSSL_PARAM dh_pad_params[2]; unsigned int upad = pad; /* We use EVP_PKEY_CTX_ctrl return values */ if (ctx == NULL || !EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } dh_pad_params[0] = OSSL_PARAM_construct_uint(OSSL_EXCHANGE_PARAM_PAD, &upad); dh_pad_params[1] = OSSL_PARAM_construct_end(); return evp_pkey_ctx_set_params_strict(ctx, dh_pad_params); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_dh_kdf_type(EVP_PKEY_CTX *ctx, int kdf) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_TYPE, kdf, NULL); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_get_dh_kdf_type(EVP_PKEY_CTX *ctx) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_TYPE, -2, NULL); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set0_dh_kdf_oid(EVP_PKEY_CTX *ctx, ASN1_OBJECT *oid) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_OID, 0, (void *)(oid)); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_get0_dh_kdf_oid(EVP_PKEY_CTX *ctx, ASN1_OBJECT **oid) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_DH_KDF_OID, 0, (void *)(oid)); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_dh_kdf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_MD, 0, (void *)(md)); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_get_dh_kdf_md(EVP_PKEY_CTX *ctx, const EVP_MD **pmd) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_DH_KDF_MD, 0, (void *)(pmd)); } int EVP_PKEY_CTX_set_dh_kdf_outlen(EVP_PKEY_CTX *ctx, int outlen) { int ret; size_t len = outlen; OSSL_PARAM params[2], *p = params; ret = dh_param_derive_check(ctx); if (ret != 1) return ret; if (outlen <= 0) { /* * This would ideally be -1 or 0, but we have to retain compatibility * with legacy behaviour of EVP_PKEY_CTX_ctrl() which returned -2 if * inlen <= 0 */ return -2; } *p++ = OSSL_PARAM_construct_size_t(OSSL_EXCHANGE_PARAM_KDF_OUTLEN, &len); *p = OSSL_PARAM_construct_end(); ret = evp_pkey_ctx_set_params_strict(ctx, params); if (ret == -2) ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return ret; } int EVP_PKEY_CTX_get_dh_kdf_outlen(EVP_PKEY_CTX *ctx, int *plen) { int ret; size_t len = UINT_MAX; OSSL_PARAM params[2], *p = params; ret = dh_param_derive_check(ctx); if (ret != 1) return ret; *p++ = OSSL_PARAM_construct_size_t(OSSL_EXCHANGE_PARAM_KDF_OUTLEN, &len); *p = OSSL_PARAM_construct_end(); ret = evp_pkey_ctx_get_params_strict(ctx, params); if (ret == -2) ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); if (ret != 1 || len > INT_MAX) return -1; *plen = (int)len; return 1; } int EVP_PKEY_CTX_set0_dh_kdf_ukm(EVP_PKEY_CTX *ctx, unsigned char *ukm, int len) { int ret; OSSL_PARAM params[2], *p = params; if (len < 0) return -1; ret = dh_param_derive_check(ctx); if (ret != 1) return ret; *p++ = OSSL_PARAM_construct_octet_string(OSSL_EXCHANGE_PARAM_KDF_UKM, /* * Cast away the const. This is read * only so should be safe */ (void *)ukm, (size_t)len); *p = OSSL_PARAM_construct_end(); ret = evp_pkey_ctx_set_params_strict(ctx, params); if (ret == -2) ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); if (ret == 1) OPENSSL_free(ukm); return ret; } #ifndef OPENSSL_NO_DEPRECATED_3_0 int EVP_PKEY_CTX_get0_dh_kdf_ukm(EVP_PKEY_CTX *ctx, unsigned char **pukm) { int ret; size_t ukmlen; OSSL_PARAM params[2], *p = params; ret = dh_param_derive_check(ctx); if (ret != 1) return ret; *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_EXCHANGE_PARAM_KDF_UKM, (void **)pukm, 0); *p = OSSL_PARAM_construct_end(); ret = evp_pkey_ctx_get_params_strict(ctx, params); if (ret == -2) ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); if (ret != 1) return -1; ukmlen = params[0].return_size; if (ukmlen > INT_MAX) return -1; return (int)ukmlen; } #endif
./openssl/crypto/evp/bio_md.c
/* * Copyright 1995-2021 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 <stdio.h> #include <errno.h> #include <openssl/buffer.h> #include <openssl/evp.h> #include "internal/bio.h" /* * BIO_put and BIO_get both add to the digest, BIO_gets returns the digest */ static int md_write(BIO *h, char const *buf, int num); static int md_read(BIO *h, char *buf, int size); static int md_gets(BIO *h, char *str, int size); static long md_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int md_new(BIO *h); static int md_free(BIO *data); static long md_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); static const BIO_METHOD methods_md = { BIO_TYPE_MD, "message digest", bwrite_conv, md_write, bread_conv, md_read, NULL, /* md_puts, */ md_gets, md_ctrl, md_new, md_free, md_callback_ctrl, }; const BIO_METHOD *BIO_f_md(void) { return &methods_md; } static int md_new(BIO *bi) { EVP_MD_CTX *ctx; ctx = EVP_MD_CTX_new(); if (ctx == NULL) return 0; BIO_set_init(bi, 1); BIO_set_data(bi, ctx); return 1; } static int md_free(BIO *a) { if (a == NULL) return 0; EVP_MD_CTX_free(BIO_get_data(a)); BIO_set_data(a, NULL); BIO_set_init(a, 0); return 1; } static int md_read(BIO *b, char *out, int outl) { int ret = 0; EVP_MD_CTX *ctx; BIO *next; if (out == NULL) return 0; ctx = BIO_get_data(b); next = BIO_next(b); if ((ctx == NULL) || (next == NULL)) return 0; ret = BIO_read(next, out, outl); if (BIO_get_init(b)) { if (ret > 0) { if (EVP_DigestUpdate(ctx, (unsigned char *)out, (unsigned int)ret) <= 0) return -1; } } BIO_clear_retry_flags(b); BIO_copy_next_retry(b); return ret; } static int md_write(BIO *b, const char *in, int inl) { int ret = 0; EVP_MD_CTX *ctx; BIO *next; if ((in == NULL) || (inl <= 0)) return 0; ctx = BIO_get_data(b); next = BIO_next(b); if ((ctx != NULL) && (next != NULL)) ret = BIO_write(next, in, inl); if (BIO_get_init(b)) { if (ret > 0) { if (!EVP_DigestUpdate(ctx, (const unsigned char *)in, (unsigned int)ret)) { BIO_clear_retry_flags(b); return 0; } } } if (next != NULL) { BIO_clear_retry_flags(b); BIO_copy_next_retry(b); } return ret; } static long md_ctrl(BIO *b, int cmd, long num, void *ptr) { EVP_MD_CTX *ctx, *dctx, **pctx; const EVP_MD **ppmd; EVP_MD *md; long ret = 1; BIO *dbio, *next; ctx = BIO_get_data(b); next = BIO_next(b); switch (cmd) { case BIO_CTRL_RESET: if (BIO_get_init(b)) ret = EVP_DigestInit_ex(ctx, EVP_MD_CTX_get0_md(ctx), NULL); else ret = 0; if (ret > 0) ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_C_GET_MD: if (BIO_get_init(b)) { ppmd = ptr; *ppmd = EVP_MD_CTX_get0_md(ctx); } else ret = 0; break; case BIO_C_GET_MD_CTX: pctx = ptr; *pctx = ctx; BIO_set_init(b, 1); break; case BIO_C_SET_MD_CTX: if (BIO_get_init(b)) BIO_set_data(b, ptr); else ret = 0; break; case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_C_SET_MD: md = ptr; ret = EVP_DigestInit_ex(ctx, md, NULL); if (ret > 0) BIO_set_init(b, 1); break; case BIO_CTRL_DUP: dbio = ptr; dctx = BIO_get_data(dbio); if (!EVP_MD_CTX_copy_ex(dctx, ctx)) return 0; BIO_set_init(b, 1); break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static long md_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next; next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } static int md_gets(BIO *bp, char *buf, int size) { EVP_MD_CTX *ctx; unsigned int ret; ctx = BIO_get_data(bp); if (size < EVP_MD_CTX_get_size(ctx)) return 0; if (EVP_DigestFinal_ex(ctx, (unsigned char *)buf, &ret) <= 0) return -1; return (int)ret; }
./openssl/crypto/evp/e_aes_cbc_hmac_sha1.c
/* * Copyright 2011-2022 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 */ /* * AES low level APIs are deprecated for public use, but still ok for internal * use where we're using them to implement the higher level EVP interface, as is * the case here. */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/aes.h> #include <openssl/sha.h> #include <openssl/rand.h> #include "internal/cryptlib.h" #include "crypto/modes.h" #include "crypto/evp.h" #include "internal/constant_time.h" #include "evp_local.h" typedef struct { AES_KEY ks; SHA_CTX head, tail, md; size_t payload_length; /* AAD length in decrypt case */ union { unsigned int tls_ver; unsigned char tls_aad[16]; /* 13 used */ } aux; } EVP_AES_HMAC_SHA1; #define NO_PAYLOAD_LENGTH ((size_t)-1) #if defined(AES_ASM) && ( \ defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64) ) # define AESNI_CAPABLE (1<<(57-32)) int aesni_set_encrypt_key(const unsigned char *userKey, int bits, AES_KEY *key); int aesni_set_decrypt_key(const unsigned char *userKey, int bits, AES_KEY *key); void aesni_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t length, const AES_KEY *key, unsigned char *ivec, int enc); void aesni_cbc_sha1_enc(const void *inp, void *out, size_t blocks, const AES_KEY *key, unsigned char iv[16], SHA_CTX *ctx, const void *in0); void aesni256_cbc_sha1_dec(const void *inp, void *out, size_t blocks, const AES_KEY *key, unsigned char iv[16], SHA_CTX *ctx, const void *in0); # define data(ctx) ((EVP_AES_HMAC_SHA1 *)EVP_CIPHER_CTX_get_cipher_data(ctx)) static int aesni_cbc_hmac_sha1_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *inkey, const unsigned char *iv, int enc) { EVP_AES_HMAC_SHA1 *key = data(ctx); int ret; const int keylen = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } if (enc) ret = aesni_set_encrypt_key(inkey, keylen, &key->ks); else ret = aesni_set_decrypt_key(inkey, keylen, &key->ks); SHA1_Init(&key->head); /* handy when benchmarking */ key->tail = key->head; key->md = key->head; key->payload_length = NO_PAYLOAD_LENGTH; return ret < 0 ? 0 : 1; } # define STITCHED_CALL # undef STITCHED_DECRYPT_CALL # if !defined(STITCHED_CALL) # define aes_off 0 # endif void sha1_block_data_order(void *c, const void *p, size_t len); static void sha1_update(SHA_CTX *c, const void *data, size_t len) { const unsigned char *ptr = data; size_t res; if ((res = c->num)) { res = SHA_CBLOCK - res; if (len < res) res = len; SHA1_Update(c, ptr, res); ptr += res; len -= res; } res = len % SHA_CBLOCK; len -= res; if (len) { sha1_block_data_order(c, ptr, len / SHA_CBLOCK); ptr += len; c->Nh += len >> 29; c->Nl += len <<= 3; if (c->Nl < (unsigned int)len) c->Nh++; } if (res) SHA1_Update(c, ptr, res); } # ifdef SHA1_Update # undef SHA1_Update # endif # define SHA1_Update sha1_update # if !defined(OPENSSL_NO_MULTIBLOCK) typedef struct { unsigned int A[8], B[8], C[8], D[8], E[8]; } SHA1_MB_CTX; typedef struct { const unsigned char *ptr; int blocks; } HASH_DESC; void sha1_multi_block(SHA1_MB_CTX *, const HASH_DESC *, int); typedef struct { const unsigned char *inp; unsigned char *out; int blocks; u64 iv[2]; } CIPH_DESC; void aesni_multi_cbc_encrypt(CIPH_DESC *, void *, int); static size_t tls1_1_multi_block_encrypt(EVP_AES_HMAC_SHA1 *key, unsigned char *out, const unsigned char *inp, size_t inp_len, int n4x) { /* n4x is 1 or 2 */ HASH_DESC hash_d[8], edges[8]; CIPH_DESC ciph_d[8]; unsigned char storage[sizeof(SHA1_MB_CTX) + 32]; union { u64 q[16]; u32 d[32]; u8 c[128]; } blocks[8]; SHA1_MB_CTX *ctx; unsigned int frag, last, packlen, i, x4 = 4 * n4x, minblocks, processed = 0; size_t ret = 0; u8 *IVs; # if defined(BSWAP8) u64 seqnum; # endif /* ask for IVs in bulk */ if (RAND_bytes((IVs = blocks[0].c), 16 * x4) <= 0) return 0; ctx = (SHA1_MB_CTX *) (storage + 32 - ((size_t)storage % 32)); /* align */ frag = (unsigned int)inp_len >> (1 + n4x); last = (unsigned int)inp_len + frag - (frag << (1 + n4x)); if (last > frag && ((last + 13 + 9) % 64) < (x4 - 1)) { frag++; last -= x4 - 1; } packlen = 5 + 16 + ((frag + 20 + 16) & -16); /* populate descriptors with pointers and IVs */ hash_d[0].ptr = inp; ciph_d[0].inp = inp; /* 5+16 is place for header and explicit IV */ ciph_d[0].out = out + 5 + 16; memcpy(ciph_d[0].out - 16, IVs, 16); memcpy(ciph_d[0].iv, IVs, 16); IVs += 16; for (i = 1; i < x4; i++) { ciph_d[i].inp = hash_d[i].ptr = hash_d[i - 1].ptr + frag; ciph_d[i].out = ciph_d[i - 1].out + packlen; memcpy(ciph_d[i].out - 16, IVs, 16); memcpy(ciph_d[i].iv, IVs, 16); IVs += 16; } # if defined(BSWAP8) memcpy(blocks[0].c, key->md.data, 8); seqnum = BSWAP8(blocks[0].q[0]); # endif for (i = 0; i < x4; i++) { unsigned int len = (i == (x4 - 1) ? last : frag); # if !defined(BSWAP8) unsigned int carry, j; # endif ctx->A[i] = key->md.h0; ctx->B[i] = key->md.h1; ctx->C[i] = key->md.h2; ctx->D[i] = key->md.h3; ctx->E[i] = key->md.h4; /* fix seqnum */ # if defined(BSWAP8) blocks[i].q[0] = BSWAP8(seqnum + i); # else for (carry = i, j = 8; j--;) { blocks[i].c[j] = ((u8 *)key->md.data)[j] + carry; carry = (blocks[i].c[j] - carry) >> (sizeof(carry) * 8 - 1); } # endif blocks[i].c[8] = ((u8 *)key->md.data)[8]; blocks[i].c[9] = ((u8 *)key->md.data)[9]; blocks[i].c[10] = ((u8 *)key->md.data)[10]; /* fix length */ blocks[i].c[11] = (u8)(len >> 8); blocks[i].c[12] = (u8)(len); memcpy(blocks[i].c + 13, hash_d[i].ptr, 64 - 13); hash_d[i].ptr += 64 - 13; hash_d[i].blocks = (len - (64 - 13)) / 64; edges[i].ptr = blocks[i].c; edges[i].blocks = 1; } /* hash 13-byte headers and first 64-13 bytes of inputs */ sha1_multi_block(ctx, edges, n4x); /* hash bulk inputs */ # define MAXCHUNKSIZE 2048 # if MAXCHUNKSIZE%64 # error "MAXCHUNKSIZE is not divisible by 64" # elif MAXCHUNKSIZE /* * goal is to minimize pressure on L1 cache by moving in shorter steps, * so that hashed data is still in the cache by the time we encrypt it */ minblocks = ((frag <= last ? frag : last) - (64 - 13)) / 64; if (minblocks > MAXCHUNKSIZE / 64) { for (i = 0; i < x4; i++) { edges[i].ptr = hash_d[i].ptr; edges[i].blocks = MAXCHUNKSIZE / 64; ciph_d[i].blocks = MAXCHUNKSIZE / 16; } do { sha1_multi_block(ctx, edges, n4x); aesni_multi_cbc_encrypt(ciph_d, &key->ks, n4x); for (i = 0; i < x4; i++) { edges[i].ptr = hash_d[i].ptr += MAXCHUNKSIZE; hash_d[i].blocks -= MAXCHUNKSIZE / 64; edges[i].blocks = MAXCHUNKSIZE / 64; ciph_d[i].inp += MAXCHUNKSIZE; ciph_d[i].out += MAXCHUNKSIZE; ciph_d[i].blocks = MAXCHUNKSIZE / 16; memcpy(ciph_d[i].iv, ciph_d[i].out - 16, 16); } processed += MAXCHUNKSIZE; minblocks -= MAXCHUNKSIZE / 64; } while (minblocks > MAXCHUNKSIZE / 64); } # endif # undef MAXCHUNKSIZE sha1_multi_block(ctx, hash_d, n4x); memset(blocks, 0, sizeof(blocks)); for (i = 0; i < x4; i++) { unsigned int len = (i == (x4 - 1) ? last : frag), off = hash_d[i].blocks * 64; const unsigned char *ptr = hash_d[i].ptr + off; off = (len - processed) - (64 - 13) - off; /* remainder actually */ memcpy(blocks[i].c, ptr, off); blocks[i].c[off] = 0x80; len += 64 + 13; /* 64 is HMAC header */ len *= 8; /* convert to bits */ if (off < (64 - 8)) { # ifdef BSWAP4 blocks[i].d[15] = BSWAP4(len); # else PUTU32(blocks[i].c + 60, len); # endif edges[i].blocks = 1; } else { # ifdef BSWAP4 blocks[i].d[31] = BSWAP4(len); # else PUTU32(blocks[i].c + 124, len); # endif edges[i].blocks = 2; } edges[i].ptr = blocks[i].c; } /* hash input tails and finalize */ sha1_multi_block(ctx, edges, n4x); memset(blocks, 0, sizeof(blocks)); for (i = 0; i < x4; i++) { # ifdef BSWAP4 blocks[i].d[0] = BSWAP4(ctx->A[i]); ctx->A[i] = key->tail.h0; blocks[i].d[1] = BSWAP4(ctx->B[i]); ctx->B[i] = key->tail.h1; blocks[i].d[2] = BSWAP4(ctx->C[i]); ctx->C[i] = key->tail.h2; blocks[i].d[3] = BSWAP4(ctx->D[i]); ctx->D[i] = key->tail.h3; blocks[i].d[4] = BSWAP4(ctx->E[i]); ctx->E[i] = key->tail.h4; blocks[i].c[20] = 0x80; blocks[i].d[15] = BSWAP4((64 + 20) * 8); # else PUTU32(blocks[i].c + 0, ctx->A[i]); ctx->A[i] = key->tail.h0; PUTU32(blocks[i].c + 4, ctx->B[i]); ctx->B[i] = key->tail.h1; PUTU32(blocks[i].c + 8, ctx->C[i]); ctx->C[i] = key->tail.h2; PUTU32(blocks[i].c + 12, ctx->D[i]); ctx->D[i] = key->tail.h3; PUTU32(blocks[i].c + 16, ctx->E[i]); ctx->E[i] = key->tail.h4; blocks[i].c[20] = 0x80; PUTU32(blocks[i].c + 60, (64 + 20) * 8); # endif edges[i].ptr = blocks[i].c; edges[i].blocks = 1; } /* finalize MACs */ sha1_multi_block(ctx, edges, n4x); for (i = 0; i < x4; i++) { unsigned int len = (i == (x4 - 1) ? last : frag), pad, j; unsigned char *out0 = out; memcpy(ciph_d[i].out, ciph_d[i].inp, len - processed); ciph_d[i].inp = ciph_d[i].out; out += 5 + 16 + len; /* write MAC */ PUTU32(out + 0, ctx->A[i]); PUTU32(out + 4, ctx->B[i]); PUTU32(out + 8, ctx->C[i]); PUTU32(out + 12, ctx->D[i]); PUTU32(out + 16, ctx->E[i]); out += 20; len += 20; /* pad */ pad = 15 - len % 16; for (j = 0; j <= pad; j++) *(out++) = pad; len += pad + 1; ciph_d[i].blocks = (len - processed) / 16; len += 16; /* account for explicit iv */ /* arrange header */ out0[0] = ((u8 *)key->md.data)[8]; out0[1] = ((u8 *)key->md.data)[9]; out0[2] = ((u8 *)key->md.data)[10]; out0[3] = (u8)(len >> 8); out0[4] = (u8)(len); ret += len + 5; inp += frag; } aesni_multi_cbc_encrypt(ciph_d, &key->ks, n4x); OPENSSL_cleanse(blocks, sizeof(blocks)); OPENSSL_cleanse(ctx, sizeof(*ctx)); return ret; } # endif static int aesni_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_HMAC_SHA1 *key = data(ctx); unsigned int l; size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and * later */ sha_off = 0; # if defined(STITCHED_CALL) size_t aes_off = 0, blocks; sha_off = SHA_CBLOCK - key->md.num; # endif key->payload_length = NO_PAYLOAD_LENGTH; if (len % AES_BLOCK_SIZE) return 0; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (plen == NO_PAYLOAD_LENGTH) plen = len; else if (len != ((plen + SHA_DIGEST_LENGTH + AES_BLOCK_SIZE) & -AES_BLOCK_SIZE)) return 0; else if (key->aux.tls_ver >= TLS1_1_VERSION) iv = AES_BLOCK_SIZE; # if defined(STITCHED_CALL) if (plen > (sha_off + iv) && (blocks = (plen - (sha_off + iv)) / SHA_CBLOCK)) { SHA1_Update(&key->md, in + iv, sha_off); aesni_cbc_sha1_enc(in, out, blocks, &key->ks, ctx->iv, &key->md, in + iv + sha_off); blocks *= SHA_CBLOCK; aes_off += blocks; sha_off += blocks; key->md.Nh += blocks >> 29; key->md.Nl += blocks <<= 3; if (key->md.Nl < (unsigned int)blocks) key->md.Nh++; } else { sha_off = 0; } # endif sha_off += iv; SHA1_Update(&key->md, in + sha_off, plen - sha_off); if (plen != len) { /* "TLS" mode of operation */ if (in != out) memcpy(out + aes_off, in + aes_off, plen - aes_off); /* calculate HMAC and append it to payload */ SHA1_Final(out + plen, &key->md); key->md = key->tail; SHA1_Update(&key->md, out + plen, SHA_DIGEST_LENGTH); SHA1_Final(out + plen, &key->md); /* pad the payload|hmac */ plen += SHA_DIGEST_LENGTH; for (l = len - plen - 1; plen < len; plen++) out[plen] = l; /* encrypt HMAC|padding at once */ aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } else { aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } } else { union { unsigned int u[SHA_DIGEST_LENGTH / sizeof(unsigned int)]; unsigned char c[32 + SHA_DIGEST_LENGTH]; } mac, *pmac; /* arrange cache line alignment */ pmac = (void *)(((size_t)mac.c + 31) & ((size_t)0 - 32)); if (plen != NO_PAYLOAD_LENGTH) { /* "TLS" mode of operation */ size_t inp_len, mask, j, i; unsigned int res, maxpad, pad, bitlen; int ret = 1; union { unsigned int u[SHA_LBLOCK]; unsigned char c[SHA_CBLOCK]; } *data = (void *)key->md.data; # if defined(STITCHED_DECRYPT_CALL) unsigned char tail_iv[AES_BLOCK_SIZE]; int stitch = 0; const int keylen = EVP_CIPHER_CTX_get_key_length(ctx); if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } # endif if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3]) >= TLS1_1_VERSION) { if (len < (AES_BLOCK_SIZE + SHA_DIGEST_LENGTH + 1)) return 0; /* omit explicit iv */ memcpy(ctx->iv, in, AES_BLOCK_SIZE); in += AES_BLOCK_SIZE; out += AES_BLOCK_SIZE; len -= AES_BLOCK_SIZE; } else if (len < (SHA_DIGEST_LENGTH + 1)) return 0; # if defined(STITCHED_DECRYPT_CALL) if (len >= 1024 && keylen == 32) { /* decrypt last block */ memcpy(tail_iv, in + len - 2 * AES_BLOCK_SIZE, AES_BLOCK_SIZE); aesni_cbc_encrypt(in + len - AES_BLOCK_SIZE, out + len - AES_BLOCK_SIZE, AES_BLOCK_SIZE, &key->ks, tail_iv, 0); stitch = 1; } else # endif /* decrypt HMAC|padding at once */ aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0); /* figure out payload length */ pad = out[len - 1]; maxpad = len - (SHA_DIGEST_LENGTH + 1); maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8); maxpad &= 255; mask = constant_time_ge(maxpad, pad); ret &= mask; /* * If pad is invalid then we will fail the above test but we must * continue anyway because we are in constant time code. However, * we'll use the maxpad value instead of the supplied pad to make * sure we perform well defined pointer arithmetic. */ pad = constant_time_select(mask, pad, maxpad); inp_len = len - (SHA_DIGEST_LENGTH + pad + 1); key->aux.tls_aad[plen - 2] = inp_len >> 8; key->aux.tls_aad[plen - 1] = inp_len; /* calculate HMAC */ key->md = key->head; SHA1_Update(&key->md, key->aux.tls_aad, plen); # if defined(STITCHED_DECRYPT_CALL) if (stitch) { blocks = (len - (256 + 32 + SHA_CBLOCK)) / SHA_CBLOCK; aes_off = len - AES_BLOCK_SIZE - blocks * SHA_CBLOCK; sha_off = SHA_CBLOCK - plen; aesni_cbc_encrypt(in, out, aes_off, &key->ks, ctx->iv, 0); SHA1_Update(&key->md, out, sha_off); aesni256_cbc_sha1_dec(in + aes_off, out + aes_off, blocks, &key->ks, ctx->iv, &key->md, out + sha_off); sha_off += blocks *= SHA_CBLOCK; out += sha_off; len -= sha_off; inp_len -= sha_off; key->md.Nl += (blocks << 3); /* at most 18 bits */ memcpy(ctx->iv, tail_iv, AES_BLOCK_SIZE); } # endif # if 1 /* see original reference version in #else */ len -= SHA_DIGEST_LENGTH; /* amend mac */ if (len >= (256 + SHA_CBLOCK)) { j = (len - (256 + SHA_CBLOCK)) & (0 - SHA_CBLOCK); j += SHA_CBLOCK - key->md.num; SHA1_Update(&key->md, out, j); out += j; len -= j; inp_len -= j; } /* but pretend as if we hashed padded payload */ bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */ # ifdef BSWAP4 bitlen = BSWAP4(bitlen); # else mac.c[0] = 0; mac.c[1] = (unsigned char)(bitlen >> 16); mac.c[2] = (unsigned char)(bitlen >> 8); mac.c[3] = (unsigned char)bitlen; bitlen = mac.u[0]; # endif pmac->u[0] = 0; pmac->u[1] = 0; pmac->u[2] = 0; pmac->u[3] = 0; pmac->u[4] = 0; for (res = key->md.num, j = 0; j < len; j++) { size_t c = out[j]; mask = (j - inp_len) >> (sizeof(j) * 8 - 8); c &= mask; c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8)); data->c[res++] = (unsigned char)c; if (res != SHA_CBLOCK) continue; /* j is not incremented yet */ mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha1_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h0 & mask; pmac->u[1] |= key->md.h1 & mask; pmac->u[2] |= key->md.h2 & mask; pmac->u[3] |= key->md.h3 & mask; pmac->u[4] |= key->md.h4 & mask; res = 0; } for (i = res; i < SHA_CBLOCK; i++, j++) data->c[i] = 0; if (res > SHA_CBLOCK - 8) { mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha1_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h0 & mask; pmac->u[1] |= key->md.h1 & mask; pmac->u[2] |= key->md.h2 & mask; pmac->u[3] |= key->md.h3 & mask; pmac->u[4] |= key->md.h4 & mask; memset(data, 0, SHA_CBLOCK); j += 64; } data->u[SHA_LBLOCK - 1] = bitlen; sha1_block_data_order(&key->md, data, 1); mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h0 & mask; pmac->u[1] |= key->md.h1 & mask; pmac->u[2] |= key->md.h2 & mask; pmac->u[3] |= key->md.h3 & mask; pmac->u[4] |= key->md.h4 & mask; # ifdef BSWAP4 pmac->u[0] = BSWAP4(pmac->u[0]); pmac->u[1] = BSWAP4(pmac->u[1]); pmac->u[2] = BSWAP4(pmac->u[2]); pmac->u[3] = BSWAP4(pmac->u[3]); pmac->u[4] = BSWAP4(pmac->u[4]); # else for (i = 0; i < 5; i++) { res = pmac->u[i]; pmac->c[4 * i + 0] = (unsigned char)(res >> 24); pmac->c[4 * i + 1] = (unsigned char)(res >> 16); pmac->c[4 * i + 2] = (unsigned char)(res >> 8); pmac->c[4 * i + 3] = (unsigned char)res; } # endif len += SHA_DIGEST_LENGTH; # else /* pre-lucky-13 reference version of above */ SHA1_Update(&key->md, out, inp_len); res = key->md.num; SHA1_Final(pmac->c, &key->md); { unsigned int inp_blocks, pad_blocks; /* but pretend as if we hashed padded payload */ inp_blocks = 1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); res += (unsigned int)(len - inp_len); pad_blocks = res / SHA_CBLOCK; res %= SHA_CBLOCK; pad_blocks += 1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); for (; inp_blocks < pad_blocks; inp_blocks++) sha1_block_data_order(&key->md, data, 1); } # endif key->md = key->tail; SHA1_Update(&key->md, pmac->c, SHA_DIGEST_LENGTH); SHA1_Final(pmac->c, &key->md); /* verify HMAC */ out += inp_len; len -= inp_len; # if 1 /* see original reference version in #else */ { unsigned char *p = out + len - 1 - maxpad - SHA_DIGEST_LENGTH; size_t off = out - p; unsigned int c, cmask; for (res = 0, i = 0, j = 0; j < maxpad + SHA_DIGEST_LENGTH; j++) { c = p[j]; cmask = ((int)(j - off - SHA_DIGEST_LENGTH)) >> (sizeof(int) * 8 - 1); res |= (c ^ pad) & ~cmask; /* ... and padding */ cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1); res |= (c ^ pmac->c[i]) & cmask; i += 1 & cmask; } res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; } # else /* pre-lucky-13 reference version of above */ for (res = 0, i = 0; i < SHA_DIGEST_LENGTH; i++) res |= out[i] ^ pmac->c[i]; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; /* verify padding */ pad = (pad & ~res) | (maxpad & res); out = out + len - 1 - pad; for (res = 0, i = 0; i < pad; i++) res |= out[i] ^ pad; res = (0 - res) >> (sizeof(res) * 8 - 1); ret &= (int)~res; # endif return ret; } else { # if defined(STITCHED_DECRYPT_CALL) if (len >= 1024 && keylen == 32) { if (sha_off %= SHA_CBLOCK) blocks = (len - 3 * SHA_CBLOCK) / SHA_CBLOCK; else blocks = (len - 2 * SHA_CBLOCK) / SHA_CBLOCK; aes_off = len - blocks * SHA_CBLOCK; aesni_cbc_encrypt(in, out, aes_off, &key->ks, ctx->iv, 0); SHA1_Update(&key->md, out, sha_off); aesni256_cbc_sha1_dec(in + aes_off, out + aes_off, blocks, &key->ks, ctx->iv, &key->md, out + sha_off); sha_off += blocks *= SHA_CBLOCK; out += sha_off; len -= sha_off; key->md.Nh += blocks >> 29; key->md.Nl += blocks <<= 3; if (key->md.Nl < (unsigned int)blocks) key->md.Nh++; } else # endif /* decrypt HMAC|padding at once */ aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0); SHA1_Update(&key->md, out, len); } } return 1; } static int aesni_cbc_hmac_sha1_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { EVP_AES_HMAC_SHA1 *key = data(ctx); switch (type) { case EVP_CTRL_AEAD_SET_MAC_KEY: { unsigned int i; unsigned char hmac_key[64]; memset(hmac_key, 0, sizeof(hmac_key)); if (arg > (int)sizeof(hmac_key)) { SHA1_Init(&key->head); SHA1_Update(&key->head, ptr, arg); SHA1_Final(hmac_key, &key->head); } else { memcpy(hmac_key, ptr, arg); } for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36; /* ipad */ SHA1_Init(&key->head); SHA1_Update(&key->head, hmac_key, sizeof(hmac_key)); for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36 ^ 0x5c; /* opad */ SHA1_Init(&key->tail); SHA1_Update(&key->tail, hmac_key, sizeof(hmac_key)); OPENSSL_cleanse(hmac_key, sizeof(hmac_key)); return 1; } case EVP_CTRL_AEAD_TLS1_AAD: { unsigned char *p = ptr; unsigned int len; if (arg != EVP_AEAD_TLS1_AAD_LEN) return -1; len = p[arg - 2] << 8 | p[arg - 1]; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { key->payload_length = len; if ((key->aux.tls_ver = p[arg - 4] << 8 | p[arg - 3]) >= TLS1_1_VERSION) { if (len < AES_BLOCK_SIZE) return 0; len -= AES_BLOCK_SIZE; p[arg - 2] = len >> 8; p[arg - 1] = len; } key->md = key->head; SHA1_Update(&key->md, p, arg); return (int)(((len + SHA_DIGEST_LENGTH + AES_BLOCK_SIZE) & -AES_BLOCK_SIZE) - len); } else { memcpy(key->aux.tls_aad, ptr, arg); key->payload_length = arg; return SHA_DIGEST_LENGTH; } } # if !defined(OPENSSL_NO_MULTIBLOCK) case EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE: return (int)(5 + 16 + ((arg + 20 + 16) & -16)); case EVP_CTRL_TLS1_1_MULTIBLOCK_AAD: { EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param = (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr; unsigned int n4x = 1, x4; unsigned int frag, last, packlen, inp_len; if (arg < (int)sizeof(EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM)) return -1; inp_len = param->inp[11] << 8 | param->inp[12]; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if ((param->inp[9] << 8 | param->inp[10]) < TLS1_1_VERSION) return -1; if (inp_len) { if (inp_len < 4096) return 0; /* too short */ if (inp_len >= 8192 && OPENSSL_ia32cap_P[2] & (1 << 5)) n4x = 2; /* AVX2 */ } else if ((n4x = param->interleave / 4) && n4x <= 2) inp_len = param->len; else return -1; key->md = key->head; SHA1_Update(&key->md, param->inp, 13); x4 = 4 * n4x; n4x += 1; frag = inp_len >> n4x; last = inp_len + frag - (frag << n4x); if (last > frag && ((last + 13 + 9) % 64 < (x4 - 1))) { frag++; last -= x4 - 1; } packlen = 5 + 16 + ((frag + 20 + 16) & -16); packlen = (packlen << n4x) - packlen; packlen += 5 + 16 + ((last + 20 + 16) & -16); param->interleave = x4; return (int)packlen; } else return -1; /* not yet */ } case EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT: { EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param = (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr; return (int)tls1_1_multi_block_encrypt(key, param->out, param->inp, param->len, param->interleave / 4); } case EVP_CTRL_TLS1_1_MULTIBLOCK_DECRYPT: # endif default: return -1; } } static EVP_CIPHER aesni_128_cbc_hmac_sha1_cipher = { # ifdef NID_aes_128_cbc_hmac_sha1 NID_aes_128_cbc_hmac_sha1, # else NID_undef, # endif AES_BLOCK_SIZE, 16, AES_BLOCK_SIZE, EVP_CIPH_CBC_MODE | EVP_CIPH_FLAG_DEFAULT_ASN1 | EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK, EVP_ORIG_GLOBAL, aesni_cbc_hmac_sha1_init_key, aesni_cbc_hmac_sha1_cipher, NULL, sizeof(EVP_AES_HMAC_SHA1), EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_set_asn1_iv, EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_get_asn1_iv, aesni_cbc_hmac_sha1_ctrl, NULL }; static EVP_CIPHER aesni_256_cbc_hmac_sha1_cipher = { # ifdef NID_aes_256_cbc_hmac_sha1 NID_aes_256_cbc_hmac_sha1, # else NID_undef, # endif AES_BLOCK_SIZE, 32, AES_BLOCK_SIZE, EVP_CIPH_CBC_MODE | EVP_CIPH_FLAG_DEFAULT_ASN1 | EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK, EVP_ORIG_GLOBAL, aesni_cbc_hmac_sha1_init_key, aesni_cbc_hmac_sha1_cipher, NULL, sizeof(EVP_AES_HMAC_SHA1), EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_set_asn1_iv, EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_get_asn1_iv, aesni_cbc_hmac_sha1_ctrl, NULL }; const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha1(void) { return (OPENSSL_ia32cap_P[1] & AESNI_CAPABLE ? &aesni_128_cbc_hmac_sha1_cipher : NULL); } const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void) { return (OPENSSL_ia32cap_P[1] & AESNI_CAPABLE ? &aesni_256_cbc_hmac_sha1_cipher : NULL); } #else const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha1(void) { return NULL; } const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void) { return NULL; } #endif
./openssl/crypto/evp/c_allc.c
/* * Copyright 1995-2022 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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include "crypto/evp.h" #include <openssl/pkcs12.h> #include <openssl/objects.h> void openssl_add_all_ciphers_int(void) { #ifndef OPENSSL_NO_DES EVP_add_cipher(EVP_des_cfb()); EVP_add_cipher(EVP_des_cfb1()); EVP_add_cipher(EVP_des_cfb8()); EVP_add_cipher(EVP_des_ede_cfb()); EVP_add_cipher(EVP_des_ede3_cfb()); EVP_add_cipher(EVP_des_ede3_cfb1()); EVP_add_cipher(EVP_des_ede3_cfb8()); EVP_add_cipher(EVP_des_ofb()); EVP_add_cipher(EVP_des_ede_ofb()); EVP_add_cipher(EVP_des_ede3_ofb()); EVP_add_cipher(EVP_desx_cbc()); EVP_add_cipher_alias(SN_desx_cbc, "DESX"); EVP_add_cipher_alias(SN_desx_cbc, "desx"); EVP_add_cipher(EVP_des_cbc()); EVP_add_cipher_alias(SN_des_cbc, "DES"); EVP_add_cipher_alias(SN_des_cbc, "des"); EVP_add_cipher(EVP_des_ede_cbc()); EVP_add_cipher(EVP_des_ede3_cbc()); EVP_add_cipher_alias(SN_des_ede3_cbc, "DES3"); EVP_add_cipher_alias(SN_des_ede3_cbc, "des3"); EVP_add_cipher(EVP_des_ecb()); EVP_add_cipher(EVP_des_ede()); EVP_add_cipher_alias(SN_des_ede_ecb, "DES-EDE-ECB"); EVP_add_cipher_alias(SN_des_ede_ecb, "des-ede-ecb"); EVP_add_cipher(EVP_des_ede3()); EVP_add_cipher_alias(SN_des_ede3_ecb, "DES-EDE3-ECB"); EVP_add_cipher_alias(SN_des_ede3_ecb, "des-ede3-ecb"); EVP_add_cipher(EVP_des_ede3_wrap()); EVP_add_cipher_alias(SN_id_smime_alg_CMS3DESwrap, "des3-wrap"); #endif #ifndef OPENSSL_NO_RC4 EVP_add_cipher(EVP_rc4()); EVP_add_cipher(EVP_rc4_40()); # ifndef OPENSSL_NO_MD5 EVP_add_cipher(EVP_rc4_hmac_md5()); # endif #endif #ifndef OPENSSL_NO_IDEA EVP_add_cipher(EVP_idea_ecb()); EVP_add_cipher(EVP_idea_cfb()); EVP_add_cipher(EVP_idea_ofb()); EVP_add_cipher(EVP_idea_cbc()); EVP_add_cipher_alias(SN_idea_cbc, "IDEA"); EVP_add_cipher_alias(SN_idea_cbc, "idea"); #endif #ifndef OPENSSL_NO_SEED EVP_add_cipher(EVP_seed_ecb()); EVP_add_cipher(EVP_seed_cfb()); EVP_add_cipher(EVP_seed_ofb()); EVP_add_cipher(EVP_seed_cbc()); EVP_add_cipher_alias(SN_seed_cbc, "SEED"); EVP_add_cipher_alias(SN_seed_cbc, "seed"); #endif #ifndef OPENSSL_NO_SM4 EVP_add_cipher(EVP_sm4_ecb()); EVP_add_cipher(EVP_sm4_cbc()); EVP_add_cipher(EVP_sm4_cfb()); EVP_add_cipher(EVP_sm4_ofb()); EVP_add_cipher(EVP_sm4_ctr()); EVP_add_cipher_alias(SN_sm4_cbc, "SM4"); EVP_add_cipher_alias(SN_sm4_cbc, "sm4"); #endif #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_ecb()); EVP_add_cipher(EVP_rc2_cfb()); EVP_add_cipher(EVP_rc2_ofb()); EVP_add_cipher(EVP_rc2_cbc()); EVP_add_cipher(EVP_rc2_40_cbc()); EVP_add_cipher(EVP_rc2_64_cbc()); EVP_add_cipher_alias(SN_rc2_cbc, "RC2"); EVP_add_cipher_alias(SN_rc2_cbc, "rc2"); EVP_add_cipher_alias(SN_rc2_cbc, "rc2-128"); EVP_add_cipher_alias(SN_rc2_64_cbc, "rc2-64"); EVP_add_cipher_alias(SN_rc2_40_cbc, "rc2-40"); #endif #ifndef OPENSSL_NO_BF EVP_add_cipher(EVP_bf_ecb()); EVP_add_cipher(EVP_bf_cfb()); EVP_add_cipher(EVP_bf_ofb()); EVP_add_cipher(EVP_bf_cbc()); EVP_add_cipher_alias(SN_bf_cbc, "BF"); EVP_add_cipher_alias(SN_bf_cbc, "bf"); EVP_add_cipher_alias(SN_bf_cbc, "blowfish"); #endif #ifndef OPENSSL_NO_CAST EVP_add_cipher(EVP_cast5_ecb()); EVP_add_cipher(EVP_cast5_cfb()); EVP_add_cipher(EVP_cast5_ofb()); EVP_add_cipher(EVP_cast5_cbc()); EVP_add_cipher_alias(SN_cast5_cbc, "CAST"); EVP_add_cipher_alias(SN_cast5_cbc, "cast"); EVP_add_cipher_alias(SN_cast5_cbc, "CAST-cbc"); EVP_add_cipher_alias(SN_cast5_cbc, "cast-cbc"); #endif #ifndef OPENSSL_NO_RC5 EVP_add_cipher(EVP_rc5_32_12_16_ecb()); EVP_add_cipher(EVP_rc5_32_12_16_cfb()); EVP_add_cipher(EVP_rc5_32_12_16_ofb()); EVP_add_cipher(EVP_rc5_32_12_16_cbc()); EVP_add_cipher_alias(SN_rc5_cbc, "rc5"); EVP_add_cipher_alias(SN_rc5_cbc, "RC5"); #endif EVP_add_cipher(EVP_aes_128_ecb()); EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_128_cfb()); EVP_add_cipher(EVP_aes_128_cfb1()); EVP_add_cipher(EVP_aes_128_cfb8()); EVP_add_cipher(EVP_aes_128_ofb()); EVP_add_cipher(EVP_aes_128_ctr()); EVP_add_cipher(EVP_aes_128_gcm()); #ifndef OPENSSL_NO_OCB EVP_add_cipher(EVP_aes_128_ocb()); #endif EVP_add_cipher(EVP_aes_128_xts()); EVP_add_cipher(EVP_aes_128_ccm()); EVP_add_cipher(EVP_aes_128_wrap()); EVP_add_cipher_alias(SN_id_aes128_wrap, "aes128-wrap"); EVP_add_cipher(EVP_aes_128_wrap_pad()); EVP_add_cipher_alias(SN_id_aes128_wrap_pad, "aes128-wrap-pad"); EVP_add_cipher_alias(SN_aes_128_cbc, "AES128"); EVP_add_cipher_alias(SN_aes_128_cbc, "aes128"); EVP_add_cipher(EVP_aes_192_ecb()); EVP_add_cipher(EVP_aes_192_cbc()); EVP_add_cipher(EVP_aes_192_cfb()); EVP_add_cipher(EVP_aes_192_cfb1()); EVP_add_cipher(EVP_aes_192_cfb8()); EVP_add_cipher(EVP_aes_192_ofb()); EVP_add_cipher(EVP_aes_192_ctr()); EVP_add_cipher(EVP_aes_192_gcm()); #ifndef OPENSSL_NO_OCB EVP_add_cipher(EVP_aes_192_ocb()); #endif EVP_add_cipher(EVP_aes_192_ccm()); EVP_add_cipher(EVP_aes_192_wrap()); EVP_add_cipher_alias(SN_id_aes192_wrap, "aes192-wrap"); EVP_add_cipher(EVP_aes_192_wrap_pad()); EVP_add_cipher_alias(SN_id_aes192_wrap_pad, "aes192-wrap-pad"); EVP_add_cipher_alias(SN_aes_192_cbc, "AES192"); EVP_add_cipher_alias(SN_aes_192_cbc, "aes192"); EVP_add_cipher(EVP_aes_256_ecb()); EVP_add_cipher(EVP_aes_256_cbc()); EVP_add_cipher(EVP_aes_256_cfb()); EVP_add_cipher(EVP_aes_256_cfb1()); EVP_add_cipher(EVP_aes_256_cfb8()); EVP_add_cipher(EVP_aes_256_ofb()); EVP_add_cipher(EVP_aes_256_ctr()); EVP_add_cipher(EVP_aes_256_gcm()); #ifndef OPENSSL_NO_OCB EVP_add_cipher(EVP_aes_256_ocb()); #endif EVP_add_cipher(EVP_aes_256_xts()); EVP_add_cipher(EVP_aes_256_ccm()); EVP_add_cipher(EVP_aes_256_wrap()); EVP_add_cipher_alias(SN_id_aes256_wrap, "aes256-wrap"); EVP_add_cipher(EVP_aes_256_wrap_pad()); EVP_add_cipher_alias(SN_id_aes256_wrap_pad, "aes256-wrap-pad"); EVP_add_cipher_alias(SN_aes_256_cbc, "AES256"); EVP_add_cipher_alias(SN_aes_256_cbc, "aes256"); EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1()); EVP_add_cipher(EVP_aes_128_cbc_hmac_sha256()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha256()); #ifndef OPENSSL_NO_ARIA EVP_add_cipher(EVP_aria_128_ecb()); EVP_add_cipher(EVP_aria_128_cbc()); EVP_add_cipher(EVP_aria_128_cfb()); EVP_add_cipher(EVP_aria_128_cfb1()); EVP_add_cipher(EVP_aria_128_cfb8()); EVP_add_cipher(EVP_aria_128_ctr()); EVP_add_cipher(EVP_aria_128_ofb()); EVP_add_cipher(EVP_aria_128_gcm()); EVP_add_cipher(EVP_aria_128_ccm()); EVP_add_cipher_alias(SN_aria_128_cbc, "ARIA128"); EVP_add_cipher_alias(SN_aria_128_cbc, "aria128"); EVP_add_cipher(EVP_aria_192_ecb()); EVP_add_cipher(EVP_aria_192_cbc()); EVP_add_cipher(EVP_aria_192_cfb()); EVP_add_cipher(EVP_aria_192_cfb1()); EVP_add_cipher(EVP_aria_192_cfb8()); EVP_add_cipher(EVP_aria_192_ctr()); EVP_add_cipher(EVP_aria_192_ofb()); EVP_add_cipher(EVP_aria_192_gcm()); EVP_add_cipher(EVP_aria_192_ccm()); EVP_add_cipher_alias(SN_aria_192_cbc, "ARIA192"); EVP_add_cipher_alias(SN_aria_192_cbc, "aria192"); EVP_add_cipher(EVP_aria_256_ecb()); EVP_add_cipher(EVP_aria_256_cbc()); EVP_add_cipher(EVP_aria_256_cfb()); EVP_add_cipher(EVP_aria_256_cfb1()); EVP_add_cipher(EVP_aria_256_cfb8()); EVP_add_cipher(EVP_aria_256_ctr()); EVP_add_cipher(EVP_aria_256_ofb()); EVP_add_cipher(EVP_aria_256_gcm()); EVP_add_cipher(EVP_aria_256_ccm()); EVP_add_cipher_alias(SN_aria_256_cbc, "ARIA256"); EVP_add_cipher_alias(SN_aria_256_cbc, "aria256"); #endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_ecb()); EVP_add_cipher(EVP_camellia_128_cbc()); EVP_add_cipher(EVP_camellia_128_cfb()); EVP_add_cipher(EVP_camellia_128_cfb1()); EVP_add_cipher(EVP_camellia_128_cfb8()); EVP_add_cipher(EVP_camellia_128_ofb()); EVP_add_cipher_alias(SN_camellia_128_cbc, "CAMELLIA128"); EVP_add_cipher_alias(SN_camellia_128_cbc, "camellia128"); EVP_add_cipher(EVP_camellia_192_ecb()); EVP_add_cipher(EVP_camellia_192_cbc()); EVP_add_cipher(EVP_camellia_192_cfb()); EVP_add_cipher(EVP_camellia_192_cfb1()); EVP_add_cipher(EVP_camellia_192_cfb8()); EVP_add_cipher(EVP_camellia_192_ofb()); EVP_add_cipher_alias(SN_camellia_192_cbc, "CAMELLIA192"); EVP_add_cipher_alias(SN_camellia_192_cbc, "camellia192"); EVP_add_cipher(EVP_camellia_256_ecb()); EVP_add_cipher(EVP_camellia_256_cbc()); EVP_add_cipher(EVP_camellia_256_cfb()); EVP_add_cipher(EVP_camellia_256_cfb1()); EVP_add_cipher(EVP_camellia_256_cfb8()); EVP_add_cipher(EVP_camellia_256_ofb()); EVP_add_cipher_alias(SN_camellia_256_cbc, "CAMELLIA256"); EVP_add_cipher_alias(SN_camellia_256_cbc, "camellia256"); EVP_add_cipher(EVP_camellia_128_ctr()); EVP_add_cipher(EVP_camellia_192_ctr()); EVP_add_cipher(EVP_camellia_256_ctr()); #endif #ifndef OPENSSL_NO_CHACHA EVP_add_cipher(EVP_chacha20()); # ifndef OPENSSL_NO_POLY1305 EVP_add_cipher(EVP_chacha20_poly1305()); # endif #endif }
./openssl/crypto/evp/e_rc4.c
/* * Copyright 1995-2021 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 */ /* * RC4 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_RC4 # include <openssl/evp.h> # include <openssl/objects.h> # include <openssl/rc4.h> # include "crypto/evp.h" typedef struct { RC4_KEY ks; /* working key */ } EVP_RC4_KEY; # define data(ctx) ((EVP_RC4_KEY *)EVP_CIPHER_CTX_get_cipher_data(ctx)) static int rc4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); static int rc4_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl); static const EVP_CIPHER r4_cipher = { NID_rc4, 1, EVP_RC4_KEY_SIZE, 0, EVP_CIPH_VARIABLE_LENGTH, EVP_ORIG_GLOBAL, rc4_init_key, rc4_cipher, NULL, sizeof(EVP_RC4_KEY), NULL, NULL, NULL, NULL }; static const EVP_CIPHER r4_40_cipher = { NID_rc4_40, 1, 5 /* 40 bit */ , 0, EVP_CIPH_VARIABLE_LENGTH, EVP_ORIG_GLOBAL, rc4_init_key, rc4_cipher, NULL, sizeof(EVP_RC4_KEY), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_rc4(void) { return &r4_cipher; } const EVP_CIPHER *EVP_rc4_40(void) { return &r4_40_cipher; } static int rc4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int keylen; if ((keylen = EVP_CIPHER_CTX_get_key_length(ctx)) <= 0) return 0; RC4_set_key(&data(ctx)->ks, keylen, key); return 1; } static int rc4_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { RC4(&data(ctx)->ks, inl, in, out); return 1; } #endif
./openssl/crypto/evp/evp_cnf.c
/* * Copyright 2012-2021 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 <stdio.h> #include <openssl/crypto.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/trace.h> #include "crypto/evp.h" /* Algorithm configuration module. */ static int alg_module_init(CONF_IMODULE *md, const CONF *cnf) { int i; const char *oid_section; STACK_OF(CONF_VALUE) *sktmp; CONF_VALUE *oval; OSSL_TRACE2(CONF, "Loading EVP module: name %s, value %s\n", CONF_imodule_get_name(md), CONF_imodule_get_value(md)); oid_section = CONF_imodule_get_value(md); if ((sktmp = NCONF_get_section(cnf, oid_section)) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_ERROR_LOADING_SECTION); return 0; } for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) { oval = sk_CONF_VALUE_value(sktmp, i); if (strcmp(oval->name, "fips_mode") == 0) { int m; /* Detailed error already reported. */ if (!X509V3_get_value_bool(oval, &m)) return 0; /* * fips_mode is deprecated and should not be used in new * configurations. */ if (!evp_default_properties_enable_fips_int( NCONF_get0_libctx((CONF *)cnf), m > 0, 0)) { ERR_raise(ERR_LIB_EVP, EVP_R_SET_DEFAULT_PROPERTY_FAILURE); return 0; } } else if (strcmp(oval->name, "default_properties") == 0) { if (!evp_set_default_properties_int(NCONF_get0_libctx((CONF *)cnf), oval->value, 0, 0)) { ERR_raise(ERR_LIB_EVP, EVP_R_SET_DEFAULT_PROPERTY_FAILURE); return 0; } } else { ERR_raise_data(ERR_LIB_EVP, EVP_R_UNKNOWN_OPTION, "name=%s, value=%s", oval->name, oval->value); return 0; } } return 1; } void EVP_add_alg_module(void) { OSSL_TRACE(CONF, "Adding config module 'alg_section'\n"); CONF_module_add("alg_section", alg_module_init, 0); }
./openssl/crypto/evp/e_seed.c
/* * Copyright 2007-2020 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 */ /* * SEED low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/opensslconf.h> #include <openssl/evp.h> #include <openssl/err.h> #include <string.h> #include <assert.h> #include <openssl/seed.h> #include "crypto/evp.h" #include "evp_local.h" static int seed_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); typedef struct { SEED_KEY_SCHEDULE ks; } EVP_SEED_KEY; IMPLEMENT_BLOCK_CIPHER(seed, ks, SEED, EVP_SEED_KEY, NID_seed, 16, 16, 16, 128, EVP_CIPH_FLAG_DEFAULT_ASN1, seed_init_key, 0, 0, 0, 0) static int seed_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { SEED_set_key(key, &EVP_C_DATA(EVP_SEED_KEY, ctx)->ks); return 1; }
./openssl/crypto/evp/p_enc.c
/* * Copyright 1995-2021 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 */ /* We need to use the deprecated RSA low level calls */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include "crypto/evp.h" int EVP_PKEY_encrypt_old(unsigned char *ek, const unsigned char *key, int key_len, EVP_PKEY *pubk) { int ret = 0; RSA *rsa = NULL; if (EVP_PKEY_get_id(pubk) != EVP_PKEY_RSA) { ERR_raise(ERR_LIB_EVP, EVP_R_PUBLIC_KEY_NOT_RSA); goto err; } rsa = evp_pkey_get0_RSA_int(pubk); if (rsa == NULL) goto err; ret = RSA_public_encrypt(key_len, key, ek, rsa, RSA_PKCS1_PADDING); err: return ret; }
./openssl/crypto/evp/m_null.c
/* * Copyright 1995-2021 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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include "crypto/evp.h" static int init(EVP_MD_CTX *ctx) { return 1; } static int update(EVP_MD_CTX *ctx, const void *data, size_t count) { return 1; } static int final(EVP_MD_CTX *ctx, unsigned char *md) { return 1; } static const EVP_MD null_md = { NID_undef, NID_undef, 0, 0, EVP_ORIG_GLOBAL, init, update, final, NULL, NULL, 0, sizeof(EVP_MD *), }; const EVP_MD *EVP_md_null(void) { return &null_md; }
./openssl/crypto/evp/evp_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2023 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 <openssl/err.h> #include <openssl/evperr.h> #include "crypto/evperr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA EVP_str_reasons[] = { {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_AES_KEY_SETUP_FAILED), "aes key setup failed"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_ARIA_KEY_SETUP_FAILED), "aria key setup failed"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_BAD_ALGORITHM_NAME), "bad algorithm name"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_BAD_DECRYPT), "bad decrypt"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_BAD_KEY_LENGTH), "bad key length"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_BUFFER_TOO_SMALL), "buffer too small"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CACHE_CONSTANTS_FAILED), "cache constants failed"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CAMELLIA_KEY_SETUP_FAILED), "camellia key setup failed"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CANNOT_GET_PARAMETERS), "cannot get parameters"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CANNOT_SET_PARAMETERS), "cannot set parameters"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CIPHER_NOT_GCM_MODE), "cipher not gcm mode"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CIPHER_PARAMETER_ERROR), "cipher parameter error"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_COMMAND_NOT_SUPPORTED), "command not supported"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CONFLICTING_ALGORITHM_NAME), "conflicting algorithm name"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_COPY_ERROR), "copy error"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CTRL_NOT_IMPLEMENTED), "ctrl not implemented"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED), "ctrl operation not implemented"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH), "data not multiple of block length"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_DECODE_ERROR), "decode error"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_DEFAULT_QUERY_PARSE_ERROR), "default query parse error"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_DIFFERENT_KEY_TYPES), "different key types"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_DIFFERENT_PARAMETERS), "different parameters"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_ERROR_LOADING_SECTION), "error loading section"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_AN_HMAC_KEY), "expecting an hmac key"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_AN_RSA_KEY), "expecting an rsa key"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_A_DH_KEY), "expecting a dh key"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_A_DSA_KEY), "expecting a dsa key"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_A_ECX_KEY), "expecting an ecx key"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_A_EC_KEY), "expecting an ec key"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_A_POLY1305_KEY), "expecting a poly1305 key"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_A_SIPHASH_KEY), "expecting a siphash key"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_FINAL_ERROR), "final error"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_GENERATE_ERROR), "generate error"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_GET_RAW_KEY_FAILED), "get raw key failed"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_ILLEGAL_SCRYPT_PARAMETERS), "illegal scrypt parameters"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INACCESSIBLE_DOMAIN_PARAMETERS), "inaccessible domain parameters"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INACCESSIBLE_KEY), "inaccessible key"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INITIALIZATION_ERROR), "initialization error"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INPUT_NOT_INITIALIZED), "input not initialized"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_CUSTOM_LENGTH), "invalid custom length"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_DIGEST), "invalid digest"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_IV_LENGTH), "invalid iv length"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_KEY), "invalid key"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_KEY_LENGTH), "invalid key length"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_LENGTH), "invalid length"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_NULL_ALGORITHM), "invalid null algorithm"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_OPERATION), "invalid operation"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_PROVIDER_FUNCTIONS), "invalid provider functions"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_SALT_LENGTH), "invalid salt length"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_SECRET_LENGTH), "invalid secret length"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_SEED_LENGTH), "invalid seed length"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_VALUE), "invalid value"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_KEYMGMT_EXPORT_FAILURE), "keymgmt export failure"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_KEY_SETUP_FAILED), "key setup failed"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_LOCKING_NOT_SUPPORTED), "locking not supported"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_MEMORY_LIMIT_EXCEEDED), "memory limit exceeded"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_MESSAGE_DIGEST_IS_NULL), "message digest is null"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_METHOD_NOT_SUPPORTED), "method not supported"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_MISSING_PARAMETERS), "missing parameters"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NOT_ABLE_TO_COPY_CTX), "not able to copy ctx"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NOT_XOF_OR_INVALID_LENGTH), "not XOF or invalid length"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_CIPHER_SET), "no cipher set"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_DEFAULT_DIGEST), "no default digest"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_DIGEST_SET), "no digest set"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_IMPORT_FUNCTION), "no import function"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_KEYMGMT_AVAILABLE), "no keymgmt available"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_KEYMGMT_PRESENT), "no keymgmt present"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_KEY_SET), "no key set"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_OPERATION_SET), "no operation set"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NULL_MAC_PKEY_CTX), "null mac pkey ctx"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_ONLY_ONESHOT_SUPPORTED), "only oneshot supported"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_OPERATION_NOT_INITIALIZED), "operation not initialized"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE), "operation not supported for this keytype"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_OUTPUT_WOULD_OVERFLOW), "output would overflow"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PARAMETER_TOO_LARGE), "parameter too large"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PARTIALLY_OVERLAPPING), "partially overlapping buffers"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PBKDF2_ERROR), "pbkdf2 error"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PKEY_APPLICATION_ASN1_METHOD_ALREADY_REGISTERED), "pkey application asn1 method already registered"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PRIVATE_KEY_DECODE_ERROR), "private key decode error"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PRIVATE_KEY_ENCODE_ERROR), "private key encode error"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PUBLIC_KEY_NOT_RSA), "public key not rsa"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_SETTING_XOF_FAILED), "setting xof failed"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_SET_DEFAULT_PROPERTY_FAILURE), "set default property failure"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_TOO_MANY_RECORDS), "too many records"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNABLE_TO_ENABLE_LOCKING), "unable to enable locking"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNABLE_TO_GET_MAXIMUM_REQUEST_SIZE), "unable to get maximum request size"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNABLE_TO_GET_RANDOM_STRENGTH), "unable to get random strength"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNABLE_TO_LOCK_CONTEXT), "unable to lock context"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNABLE_TO_SET_CALLBACKS), "unable to set callbacks"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_BITS), "unknown bits"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_CIPHER), "unknown cipher"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_DIGEST), "unknown digest"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_KEY_TYPE), "unknown key type"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_MAX_SIZE), "unknown max size"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_OPTION), "unknown option"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_PBE_ALGORITHM), "unknown pbe algorithm"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_SECURITY_BITS), "unknown security bits"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_ALGORITHM), "unsupported algorithm"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_CIPHER), "unsupported cipher"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_KEYLENGTH), "unsupported keylength"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION), "unsupported key derivation function"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_KEY_SIZE), "unsupported key size"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_KEY_TYPE), "unsupported key type"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_NUMBER_OF_ROUNDS), "unsupported number of rounds"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_PRF), "unsupported prf"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM), "unsupported private key algorithm"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_SALT_TYPE), "unsupported salt type"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UPDATE_ERROR), "update error"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_WRAP_MODE_NOT_ALLOWED), "wrap mode not allowed"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_WRONG_FINAL_BLOCK_LENGTH), "wrong final block length"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_XTS_DATA_UNIT_IS_TOO_LARGE), "xts data unit is too large"}, {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_XTS_DUPLICATED_KEYS), "xts duplicated keys"}, {0, NULL} }; #endif int ossl_err_load_EVP_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(EVP_str_reasons[0].error) == NULL) ERR_load_strings_const(EVP_str_reasons); #endif return 1; }
./openssl/crypto/evp/e_des3.c
/* * Copyright 1995-2021 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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_DES # include <openssl/objects.h> # include "crypto/evp.h" # include "crypto/sha.h" # include <openssl/des.h> # include <openssl/rand.h> # include "evp_local.h" typedef struct { union { OSSL_UNION_ALIGN; DES_key_schedule ks[3]; } ks; union { void (*cbc) (const void *, void *, size_t, const DES_key_schedule *, unsigned char *); } stream; } DES_EDE_KEY; # define ks1 ks.ks[0] # define ks2 ks.ks[1] # define ks3 ks.ks[2] # if defined(AES_ASM) && (defined(__sparc) || defined(__sparc__)) /* ---------^^^ this is not a typo, just a way to detect that * assembler support was in general requested... */ # include "crypto/sparc_arch.h" # define SPARC_DES_CAPABLE (OPENSSL_sparcv9cap_P[1] & CFR_DES) void des_t4_key_expand(const void *key, DES_key_schedule *ks); void des_t4_ede3_cbc_encrypt(const void *inp, void *out, size_t len, const DES_key_schedule ks[3], unsigned char iv[8]); void des_t4_ede3_cbc_decrypt(const void *inp, void *out, size_t len, const DES_key_schedule ks[3], unsigned char iv[8]); # endif static int des_ede_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); static int des_ede3_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); static int des3_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr); # define data(ctx) EVP_C_DATA(DES_EDE_KEY,ctx) /* * Because of various casts and different args can't use * IMPLEMENT_BLOCK_CIPHER */ static int des_ede_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { BLOCK_CIPHER_ecb_loop() DES_ecb3_encrypt((const_DES_cblock *)(in + i), (DES_cblock *)(out + i), &data(ctx)->ks1, &data(ctx)->ks2, &data(ctx)->ks3, EVP_CIPHER_CTX_is_encrypting(ctx)); return 1; } static int des_ede_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { while (inl >= EVP_MAXCHUNK) { int num = EVP_CIPHER_CTX_get_num(ctx); DES_ede3_ofb64_encrypt(in, out, (long)EVP_MAXCHUNK, &data(ctx)->ks1, &data(ctx)->ks2, &data(ctx)->ks3, (DES_cblock *)ctx->iv, &num); EVP_CIPHER_CTX_set_num(ctx, num); inl -= EVP_MAXCHUNK; in += EVP_MAXCHUNK; out += EVP_MAXCHUNK; } if (inl) { int num = EVP_CIPHER_CTX_get_num(ctx); DES_ede3_ofb64_encrypt(in, out, (long)inl, &data(ctx)->ks1, &data(ctx)->ks2, &data(ctx)->ks3, (DES_cblock *)ctx->iv, &num); EVP_CIPHER_CTX_set_num(ctx, num); } return 1; } static int des_ede_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { DES_EDE_KEY *dat = data(ctx); if (dat->stream.cbc != NULL) { (*dat->stream.cbc) (in, out, inl, dat->ks.ks, ctx->iv); return 1; } while (inl >= EVP_MAXCHUNK) { DES_ede3_cbc_encrypt(in, out, (long)EVP_MAXCHUNK, &dat->ks1, &dat->ks2, &dat->ks3, (DES_cblock *)ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); inl -= EVP_MAXCHUNK; in += EVP_MAXCHUNK; out += EVP_MAXCHUNK; } if (inl) DES_ede3_cbc_encrypt(in, out, (long)inl, &dat->ks1, &dat->ks2, &dat->ks3, (DES_cblock *)ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); return 1; } static int des_ede_cfb64_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { while (inl >= EVP_MAXCHUNK) { int num = EVP_CIPHER_CTX_get_num(ctx); DES_ede3_cfb64_encrypt(in, out, (long)EVP_MAXCHUNK, &data(ctx)->ks1, &data(ctx)->ks2, &data(ctx)->ks3, (DES_cblock *)ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx)); EVP_CIPHER_CTX_set_num(ctx, num); inl -= EVP_MAXCHUNK; in += EVP_MAXCHUNK; out += EVP_MAXCHUNK; } if (inl) { int num = EVP_CIPHER_CTX_get_num(ctx); DES_ede3_cfb64_encrypt(in, out, (long)inl, &data(ctx)->ks1, &data(ctx)->ks2, &data(ctx)->ks3, (DES_cblock *)ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx)); EVP_CIPHER_CTX_set_num(ctx, num); } return 1; } /* * Although we have a CFB-r implementation for 3-DES, it doesn't pack the * right way, so wrap it here */ static int des_ede3_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { size_t n; unsigned char c[1]; unsigned char d[1] = { 0 }; /* Appease Coverity */ if (!EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS)) inl *= 8; for (n = 0; n < inl; ++n) { c[0] = (in[n / 8] & (1 << (7 - n % 8))) ? 0x80 : 0; DES_ede3_cfb_encrypt(c, d, 1, 1, &data(ctx)->ks1, &data(ctx)->ks2, &data(ctx)->ks3, (DES_cblock *)ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); out[n / 8] = (out[n / 8] & ~(0x80 >> (unsigned int)(n % 8))) | ((d[0] & 0x80) >> (unsigned int)(n % 8)); } return 1; } static int des_ede3_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { while (inl >= EVP_MAXCHUNK) { DES_ede3_cfb_encrypt(in, out, 8, (long)EVP_MAXCHUNK, &data(ctx)->ks1, &data(ctx)->ks2, &data(ctx)->ks3, (DES_cblock *)ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); inl -= EVP_MAXCHUNK; in += EVP_MAXCHUNK; out += EVP_MAXCHUNK; } if (inl) DES_ede3_cfb_encrypt(in, out, 8, (long)inl, &data(ctx)->ks1, &data(ctx)->ks2, &data(ctx)->ks3, (DES_cblock *)ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); return 1; } BLOCK_CIPHER_defs(des_ede, DES_EDE_KEY, NID_des_ede, 8, 16, 8, 64, EVP_CIPH_RAND_KEY | EVP_CIPH_FLAG_DEFAULT_ASN1, des_ede_init_key, NULL, NULL, NULL, des3_ctrl) # define des_ede3_cfb64_cipher des_ede_cfb64_cipher # define des_ede3_ofb_cipher des_ede_ofb_cipher # define des_ede3_cbc_cipher des_ede_cbc_cipher # define des_ede3_ecb_cipher des_ede_ecb_cipher BLOCK_CIPHER_defs(des_ede3, DES_EDE_KEY, NID_des_ede3, 8, 24, 8, 64, EVP_CIPH_RAND_KEY | EVP_CIPH_FLAG_DEFAULT_ASN1, des_ede3_init_key, NULL, NULL, NULL, des3_ctrl) BLOCK_CIPHER_def_cfb(des_ede3, DES_EDE_KEY, NID_des_ede3, 24, 8, 1, EVP_CIPH_RAND_KEY | EVP_CIPH_FLAG_DEFAULT_ASN1, des_ede3_init_key, NULL, NULL, NULL, des3_ctrl) BLOCK_CIPHER_def_cfb(des_ede3, DES_EDE_KEY, NID_des_ede3, 24, 8, 8, EVP_CIPH_RAND_KEY | EVP_CIPH_FLAG_DEFAULT_ASN1, des_ede3_init_key, NULL, NULL, NULL, des3_ctrl) static int des_ede_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { DES_cblock *deskey = (DES_cblock *)key; DES_EDE_KEY *dat = data(ctx); dat->stream.cbc = NULL; # if defined(SPARC_DES_CAPABLE) if (SPARC_DES_CAPABLE) { int mode = EVP_CIPHER_CTX_get_mode(ctx); if (mode == EVP_CIPH_CBC_MODE) { des_t4_key_expand(&deskey[0], &dat->ks1); des_t4_key_expand(&deskey[1], &dat->ks2); memcpy(&dat->ks3, &dat->ks1, sizeof(dat->ks1)); dat->stream.cbc = enc ? des_t4_ede3_cbc_encrypt : des_t4_ede3_cbc_decrypt; return 1; } } # endif DES_set_key_unchecked(&deskey[0], &dat->ks1); DES_set_key_unchecked(&deskey[1], &dat->ks2); memcpy(&dat->ks3, &dat->ks1, sizeof(dat->ks1)); return 1; } static int des_ede3_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { DES_cblock *deskey = (DES_cblock *)key; DES_EDE_KEY *dat = data(ctx); dat->stream.cbc = NULL; # if defined(SPARC_DES_CAPABLE) if (SPARC_DES_CAPABLE) { int mode = EVP_CIPHER_CTX_get_mode(ctx); if (mode == EVP_CIPH_CBC_MODE) { des_t4_key_expand(&deskey[0], &dat->ks1); des_t4_key_expand(&deskey[1], &dat->ks2); des_t4_key_expand(&deskey[2], &dat->ks3); dat->stream.cbc = enc ? des_t4_ede3_cbc_encrypt : des_t4_ede3_cbc_decrypt; return 1; } } # endif DES_set_key_unchecked(&deskey[0], &dat->ks1); DES_set_key_unchecked(&deskey[1], &dat->ks2); DES_set_key_unchecked(&deskey[2], &dat->ks3); return 1; } static int des3_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { DES_cblock *deskey = ptr; int kl; switch (type) { case EVP_CTRL_RAND_KEY: kl = EVP_CIPHER_CTX_get_key_length(ctx); if (kl < 0 || RAND_priv_bytes(ptr, kl) <= 0) return 0; DES_set_odd_parity(deskey); if (kl >= 16) DES_set_odd_parity(deskey + 1); if (kl >= 24) DES_set_odd_parity(deskey + 2); return 1; default: return -1; } } const EVP_CIPHER *EVP_des_ede(void) { return &des_ede_ecb; } const EVP_CIPHER *EVP_des_ede3(void) { return &des_ede3_ecb; } # include <openssl/sha.h> static const unsigned char wrap_iv[8] = { 0x4a, 0xdd, 0xa2, 0x2c, 0x79, 0xe8, 0x21, 0x05 }; static int des_ede3_unwrap(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { unsigned char icv[8], iv[8], sha1tmp[SHA_DIGEST_LENGTH]; int rv = -1; if (inl < 24) return -1; if (out == NULL) return inl - 16; memcpy(ctx->iv, wrap_iv, 8); /* Decrypt first block which will end up as icv */ des_ede_cbc_cipher(ctx, icv, in, 8); /* Decrypt central blocks */ /* * If decrypting in place move whole output along a block so the next * des_ede_cbc_cipher is in place. */ if (out == in) { memmove(out, out + 8, inl - 8); in -= 8; } des_ede_cbc_cipher(ctx, out, in + 8, inl - 16); /* Decrypt final block which will be IV */ des_ede_cbc_cipher(ctx, iv, in + inl - 8, 8); /* Reverse order of everything */ BUF_reverse(icv, NULL, 8); BUF_reverse(out, NULL, inl - 16); BUF_reverse(ctx->iv, iv, 8); /* Decrypt again using new IV */ des_ede_cbc_cipher(ctx, out, out, inl - 16); des_ede_cbc_cipher(ctx, icv, icv, 8); if (ossl_sha1(out, inl - 16, sha1tmp) /* Work out hash of first portion */ && CRYPTO_memcmp(sha1tmp, icv, 8) == 0) rv = inl - 16; OPENSSL_cleanse(icv, 8); OPENSSL_cleanse(sha1tmp, SHA_DIGEST_LENGTH); OPENSSL_cleanse(iv, 8); OPENSSL_cleanse(ctx->iv, 8); if (rv == -1) OPENSSL_cleanse(out, inl - 16); return rv; } static int des_ede3_wrap(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { unsigned char sha1tmp[SHA_DIGEST_LENGTH]; if (out == NULL) return inl + 16; /* Copy input to output buffer + 8 so we have space for IV */ memmove(out + 8, in, inl); /* Work out ICV */ if (!ossl_sha1(in, inl, sha1tmp)) return -1; memcpy(out + inl + 8, sha1tmp, 8); OPENSSL_cleanse(sha1tmp, SHA_DIGEST_LENGTH); /* Generate random IV */ if (RAND_bytes(ctx->iv, 8) <= 0) return -1; memcpy(out, ctx->iv, 8); /* Encrypt everything after IV in place */ des_ede_cbc_cipher(ctx, out + 8, out + 8, inl + 8); BUF_reverse(out, NULL, inl + 16); memcpy(ctx->iv, wrap_iv, 8); des_ede_cbc_cipher(ctx, out, out, inl + 16); return inl + 16; } static int des_ede3_wrap_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { /* * Sanity check input length: we typically only wrap keys so EVP_MAXCHUNK * is more than will ever be needed. Also input length must be a multiple * of 8 bits. */ if (inl >= EVP_MAXCHUNK || inl % 8) return -1; if (ossl_is_partially_overlapping(out, in, inl)) { ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING); return 0; } if (EVP_CIPHER_CTX_is_encrypting(ctx)) return des_ede3_wrap(ctx, out, in, inl); else return des_ede3_unwrap(ctx, out, in, inl); } static const EVP_CIPHER des3_wrap = { NID_id_smime_alg_CMS3DESwrap, 8, 24, 0, EVP_CIPH_WRAP_MODE | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER | EVP_CIPH_FLAG_DEFAULT_ASN1, EVP_ORIG_GLOBAL, des_ede3_init_key, des_ede3_wrap_cipher, NULL, sizeof(DES_EDE_KEY), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_des_ede3_wrap(void) { return &des3_wrap; } #endif
./openssl/crypto/evp/cmeth_lib.c
/* * Copyright 2015-2023 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 */ /* * EVP _meth_ APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <string.h> #include <openssl/evp.h> #include "crypto/evp.h" #include "internal/provider.h" #include "evp_local.h" EVP_CIPHER *EVP_CIPHER_meth_new(int cipher_type, int block_size, int key_len) { EVP_CIPHER *cipher = evp_cipher_new(); if (cipher != NULL) { cipher->nid = cipher_type; cipher->block_size = block_size; cipher->key_len = key_len; cipher->origin = EVP_ORIG_METH; } return cipher; } EVP_CIPHER *EVP_CIPHER_meth_dup(const EVP_CIPHER *cipher) { EVP_CIPHER *to = NULL; /* * Non-legacy EVP_CIPHERs can't be duplicated like this. * Use EVP_CIPHER_up_ref() instead. */ if (cipher->prov != NULL) return NULL; if ((to = EVP_CIPHER_meth_new(cipher->nid, cipher->block_size, cipher->key_len)) != NULL) { CRYPTO_REF_COUNT refcnt = to->refcnt; memcpy(to, cipher, sizeof(*to)); to->refcnt = refcnt; to->origin = EVP_ORIG_METH; } return to; } void EVP_CIPHER_meth_free(EVP_CIPHER *cipher) { if (cipher == NULL || cipher->origin != EVP_ORIG_METH) return; evp_cipher_free_int(cipher); } int EVP_CIPHER_meth_set_iv_length(EVP_CIPHER *cipher, int iv_len) { if (cipher->iv_len != 0) return 0; cipher->iv_len = iv_len; return 1; } int EVP_CIPHER_meth_set_flags(EVP_CIPHER *cipher, unsigned long flags) { if (cipher->flags != 0) return 0; cipher->flags = flags; return 1; } int EVP_CIPHER_meth_set_impl_ctx_size(EVP_CIPHER *cipher, int ctx_size) { if (cipher->ctx_size != 0) return 0; cipher->ctx_size = ctx_size; return 1; } int EVP_CIPHER_meth_set_init(EVP_CIPHER *cipher, int (*init) (EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc)) { if (cipher->init != NULL) return 0; cipher->init = init; return 1; } int EVP_CIPHER_meth_set_do_cipher(EVP_CIPHER *cipher, int (*do_cipher) (EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl)) { if (cipher->do_cipher != NULL) return 0; cipher->do_cipher = do_cipher; return 1; } int EVP_CIPHER_meth_set_cleanup(EVP_CIPHER *cipher, int (*cleanup) (EVP_CIPHER_CTX *)) { if (cipher->cleanup != NULL) return 0; cipher->cleanup = cleanup; return 1; } int EVP_CIPHER_meth_set_set_asn1_params(EVP_CIPHER *cipher, int (*set_asn1_parameters) (EVP_CIPHER_CTX *, ASN1_TYPE *)) { if (cipher->set_asn1_parameters != NULL) return 0; cipher->set_asn1_parameters = set_asn1_parameters; return 1; } int EVP_CIPHER_meth_set_get_asn1_params(EVP_CIPHER *cipher, int (*get_asn1_parameters) (EVP_CIPHER_CTX *, ASN1_TYPE *)) { if (cipher->get_asn1_parameters != NULL) return 0; cipher->get_asn1_parameters = get_asn1_parameters; return 1; } int EVP_CIPHER_meth_set_ctrl(EVP_CIPHER *cipher, int (*ctrl) (EVP_CIPHER_CTX *, int type, int arg, void *ptr)) { if (cipher->ctrl != NULL) return 0; cipher->ctrl = ctrl; return 1; } int (*EVP_CIPHER_meth_get_init(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { return cipher->init; } int (*EVP_CIPHER_meth_get_do_cipher(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { return cipher->do_cipher; } int (*EVP_CIPHER_meth_get_cleanup(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *) { return cipher->cleanup; } int (*EVP_CIPHER_meth_get_set_asn1_params(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, ASN1_TYPE *) { return cipher->set_asn1_parameters; } int (*EVP_CIPHER_meth_get_get_asn1_params(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, ASN1_TYPE *) { return cipher->get_asn1_parameters; } int (*EVP_CIPHER_meth_get_ctrl(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, int type, int arg, void *ptr) { return cipher->ctrl; }
./openssl/crypto/evp/e_aes.c
/* * Copyright 2001-2022 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 */ /* * This file uses the low-level AES functions (which are deprecated for * non-internal use) in order to implement the EVP AES ciphers. */ #include "internal/deprecated.h" #include <string.h> #include <assert.h> #include <openssl/opensslconf.h> #include <openssl/crypto.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/aes.h> #include <openssl/rand.h> #include <openssl/cmac.h> #include "crypto/evp.h" #include "internal/cryptlib.h" #include "crypto/modes.h" #include "crypto/siv.h" #include "crypto/aes_platform.h" #include "evp_local.h" typedef struct { union { OSSL_UNION_ALIGN; AES_KEY ks; } ks; block128_f block; union { cbc128_f cbc; ctr128_f ctr; } stream; } EVP_AES_KEY; typedef struct { union { OSSL_UNION_ALIGN; AES_KEY ks; } ks; /* AES key schedule to use */ int key_set; /* Set if key initialised */ int iv_set; /* Set if an iv is set */ GCM128_CONTEXT gcm; unsigned char *iv; /* Temporary IV store */ int ivlen; /* IV length */ int taglen; int iv_gen; /* It is OK to generate IVs */ int iv_gen_rand; /* No IV was specified, so generate a rand IV */ int tls_aad_len; /* TLS AAD length */ uint64_t tls_enc_records; /* Number of TLS records encrypted */ ctr128_f ctr; } EVP_AES_GCM_CTX; typedef struct { union { OSSL_UNION_ALIGN; AES_KEY ks; } ks1, ks2; /* AES key schedules to use */ XTS128_CONTEXT xts; void (*stream) (const unsigned char *in, unsigned char *out, size_t length, const AES_KEY *key1, const AES_KEY *key2, const unsigned char iv[16]); } EVP_AES_XTS_CTX; #ifdef FIPS_MODULE static const int allow_insecure_decrypt = 0; #else static const int allow_insecure_decrypt = 1; #endif typedef struct { union { OSSL_UNION_ALIGN; AES_KEY ks; } ks; /* AES key schedule to use */ int key_set; /* Set if key initialised */ int iv_set; /* Set if an iv is set */ int tag_set; /* Set if tag is valid */ int len_set; /* Set if message length set */ int L, M; /* L and M parameters from RFC3610 */ int tls_aad_len; /* TLS AAD length */ CCM128_CONTEXT ccm; ccm128_f str; } EVP_AES_CCM_CTX; #ifndef OPENSSL_NO_OCB typedef struct { union { OSSL_UNION_ALIGN; AES_KEY ks; } ksenc; /* AES key schedule to use for encryption */ union { OSSL_UNION_ALIGN; AES_KEY ks; } ksdec; /* AES key schedule to use for decryption */ int key_set; /* Set if key initialised */ int iv_set; /* Set if an iv is set */ OCB128_CONTEXT ocb; unsigned char *iv; /* Temporary IV store */ unsigned char tag[16]; unsigned char data_buf[16]; /* Store partial data blocks */ unsigned char aad_buf[16]; /* Store partial AAD blocks */ int data_buf_len; int aad_buf_len; int ivlen; /* IV length */ int taglen; } EVP_AES_OCB_CTX; #endif #define MAXBITCHUNK ((size_t)1<<(sizeof(size_t)*8-4)) /* increment counter (64-bit int) by 1 */ static void ctr64_inc(unsigned char *counter) { int n = 8; unsigned char c; do { --n; c = counter[n]; ++c; counter[n] = c; if (c) return; } while (n); } #if defined(AESNI_CAPABLE) # if defined(__x86_64) || defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64) # define AES_GCM_ASM2(gctx) (gctx->gcm.block==(block128_f)aesni_encrypt && \ gctx->gcm.ghash==gcm_ghash_avx) # undef AES_GCM_ASM2 /* minor size optimization */ # endif static int aesni_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int ret, mode; EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); const int keylen = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } mode = EVP_CIPHER_CTX_get_mode(ctx); if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE) && !enc) { ret = aesni_set_decrypt_key(key, keylen, &dat->ks.ks); dat->block = (block128_f) aesni_decrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) aesni_cbc_encrypt : NULL; } else { ret = aesni_set_encrypt_key(key, keylen, &dat->ks.ks); dat->block = (block128_f) aesni_encrypt; if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) aesni_cbc_encrypt; else if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) aesni_ctr32_encrypt_blocks; else dat->stream.cbc = NULL; } if (ret < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_AES_KEY_SETUP_FAILED); return 0; } return 1; } static int aesni_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { aesni_cbc_encrypt(in, out, len, &EVP_C_DATA(EVP_AES_KEY,ctx)->ks.ks, ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); return 1; } static int aesni_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { size_t bl = EVP_CIPHER_CTX_get_block_size(ctx); if (len < bl) return 1; aesni_ecb_encrypt(in, out, len, &EVP_C_DATA(EVP_AES_KEY,ctx)->ks.ks, EVP_CIPHER_CTX_is_encrypting(ctx)); return 1; } # define aesni_ofb_cipher aes_ofb_cipher static int aesni_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aesni_cfb_cipher aes_cfb_cipher static int aesni_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aesni_cfb8_cipher aes_cfb8_cipher static int aesni_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aesni_cfb1_cipher aes_cfb1_cipher static int aesni_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aesni_ctr_cipher aes_ctr_cipher static int aesni_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aesni_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX, ctx); if (iv == NULL && key == NULL) return 1; if (key) { const int keylen = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } aesni_set_encrypt_key(key, keylen, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) aesni_encrypt); gctx->ctr = (ctr128_f) aesni_ctr32_encrypt_blocks; /* * If we have an iv can set it directly, otherwise use saved IV. */ if (iv == NULL && gctx->iv_set) iv = gctx->iv; if (iv) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); gctx->iv_set = 1; } gctx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (gctx->key_set) CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); else memcpy(gctx->iv, iv, gctx->ivlen); gctx->iv_set = 1; gctx->iv_gen = 0; } return 1; } # define aesni_gcm_cipher aes_gcm_cipher static int aesni_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aesni_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_XTS_CTX *xctx = EVP_C_DATA(EVP_AES_XTS_CTX,ctx); if (iv == NULL && key == NULL) return 1; if (key) { /* The key is two half length keys in reality */ const int keylen = EVP_CIPHER_CTX_get_key_length(ctx); const int bytes = keylen / 2; const int bits = bytes * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } /* * Verify that the two keys are different. * * This addresses Rogaway's vulnerability. * See comment in aes_xts_init_key() below. */ if ((!allow_insecure_decrypt || enc) && CRYPTO_memcmp(key, key + bytes, bytes) == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_XTS_DUPLICATED_KEYS); return 0; } /* key_len is two AES keys */ if (enc) { aesni_set_encrypt_key(key, bits, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) aesni_encrypt; xctx->stream = aesni_xts_encrypt; } else { aesni_set_decrypt_key(key, bits, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) aesni_decrypt; xctx->stream = aesni_xts_decrypt; } aesni_set_encrypt_key(key + bytes, bits, &xctx->ks2.ks); xctx->xts.block2 = (block128_f) aesni_encrypt; xctx->xts.key1 = &xctx->ks1; } if (iv) { xctx->xts.key2 = &xctx->ks2; memcpy(ctx->iv, iv, 16); } return 1; } # define aesni_xts_cipher aes_xts_cipher static int aesni_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aesni_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,ctx); if (iv == NULL && key == NULL) return 1; if (key != NULL) { const int keylen = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } aesni_set_encrypt_key(key, keylen, &cctx->ks.ks); CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, &cctx->ks, (block128_f) aesni_encrypt); cctx->str = enc ? (ccm128_f) aesni_ccm64_encrypt_blocks : (ccm128_f) aesni_ccm64_decrypt_blocks; cctx->key_set = 1; } if (iv) { memcpy(ctx->iv, iv, 15 - cctx->L); cctx->iv_set = 1; } return 1; } # define aesni_ccm_cipher aes_ccm_cipher static int aesni_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # ifndef OPENSSL_NO_OCB static int aesni_ocb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,ctx); if (iv == NULL && key == NULL) return 1; if (key != NULL) { const int keylen = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } do { /* * We set both the encrypt and decrypt key here because decrypt * needs both. We could possibly optimise to remove setting the * decrypt for an encryption operation. */ aesni_set_encrypt_key(key, keylen, &octx->ksenc.ks); aesni_set_decrypt_key(key, keylen, &octx->ksdec.ks); if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc.ks, &octx->ksdec.ks, (block128_f) aesni_encrypt, (block128_f) aesni_decrypt, enc ? aesni_ocb_encrypt : aesni_ocb_decrypt)) return 0; } while (0); /* * If we have an iv we can set it directly, otherwise use saved IV. */ if (iv == NULL && octx->iv_set) iv = octx->iv; if (iv) { if (CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen) != 1) return 0; octx->iv_set = 1; } octx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (octx->key_set) CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen); else memcpy(octx->iv, iv, octx->ivlen); octx->iv_set = 1; } return 1; } # define aesni_ocb_cipher aes_ocb_cipher static int aesni_ocb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # endif /* OPENSSL_NO_OCB */ # define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ static const EVP_CIPHER aesni_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aesni_init_key, \ aesni_##mode##_cipher, \ NULL, \ sizeof(EVP_AES_KEY), \ NULL,NULL,NULL,NULL }; \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize, \ keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aes_init_key, \ aes_##mode##_cipher, \ NULL, \ sizeof(EVP_AES_KEY), \ NULL,NULL,NULL,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return AESNI_CAPABLE?&aesni_##keylen##_##mode:&aes_##keylen##_##mode; } # define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \ static const EVP_CIPHER aesni_##keylen##_##mode = { \ nid##_##keylen##_##mode,blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE||EVP_CIPH_##MODE##_MODE==EVP_CIPH_SIV_MODE?2:1)*keylen/8, \ ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aesni_##mode##_init_key, \ aesni_##mode##_cipher, \ aes_##mode##_cleanup, \ sizeof(EVP_AES_##MODE##_CTX), \ NULL,NULL,aes_##mode##_ctrl,NULL }; \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##mode,blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE||EVP_CIPH_##MODE##_MODE==EVP_CIPH_SIV_MODE?2:1)*keylen/8, \ ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aes_##mode##_init_key, \ aes_##mode##_cipher, \ aes_##mode##_cleanup, \ sizeof(EVP_AES_##MODE##_CTX), \ NULL,NULL,aes_##mode##_ctrl,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return AESNI_CAPABLE?&aesni_##keylen##_##mode:&aes_##keylen##_##mode; } #elif defined(SPARC_AES_CAPABLE) static int aes_t4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int ret, mode, bits; EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); mode = EVP_CIPHER_CTX_get_mode(ctx); bits = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (bits <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE) && !enc) { ret = 0; aes_t4_set_decrypt_key(key, bits, &dat->ks.ks); dat->block = (block128_f) aes_t4_decrypt; switch (bits) { case 128: dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) aes128_t4_cbc_decrypt : NULL; break; case 192: dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) aes192_t4_cbc_decrypt : NULL; break; case 256: dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) aes256_t4_cbc_decrypt : NULL; break; default: ret = -1; } } else { ret = 0; aes_t4_set_encrypt_key(key, bits, &dat->ks.ks); dat->block = (block128_f) aes_t4_encrypt; switch (bits) { case 128: if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) aes128_t4_cbc_encrypt; else if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) aes128_t4_ctr32_encrypt; else dat->stream.cbc = NULL; break; case 192: if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) aes192_t4_cbc_encrypt; else if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) aes192_t4_ctr32_encrypt; else dat->stream.cbc = NULL; break; case 256: if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) aes256_t4_cbc_encrypt; else if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) aes256_t4_ctr32_encrypt; else dat->stream.cbc = NULL; break; default: ret = -1; } } if (ret < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_AES_KEY_SETUP_FAILED); return 0; } return 1; } # define aes_t4_cbc_cipher aes_cbc_cipher static int aes_t4_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_ecb_cipher aes_ecb_cipher static int aes_t4_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_ofb_cipher aes_ofb_cipher static int aes_t4_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_cfb_cipher aes_cfb_cipher static int aes_t4_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_cfb8_cipher aes_cfb8_cipher static int aes_t4_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_cfb1_cipher aes_cfb1_cipher static int aes_t4_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_ctr_cipher aes_ctr_cipher static int aes_t4_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aes_t4_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,ctx); if (iv == NULL && key == NULL) return 1; if (key) { const int bits = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (bits <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } aes_t4_set_encrypt_key(key, bits, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) aes_t4_encrypt); switch (bits) { case 128: gctx->ctr = (ctr128_f) aes128_t4_ctr32_encrypt; break; case 192: gctx->ctr = (ctr128_f) aes192_t4_ctr32_encrypt; break; case 256: gctx->ctr = (ctr128_f) aes256_t4_ctr32_encrypt; break; default: return 0; } /* * If we have an iv can set it directly, otherwise use saved IV. */ if (iv == NULL && gctx->iv_set) iv = gctx->iv; if (iv) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); gctx->iv_set = 1; } gctx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (gctx->key_set) CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); else memcpy(gctx->iv, iv, gctx->ivlen); gctx->iv_set = 1; gctx->iv_gen = 0; } return 1; } # define aes_t4_gcm_cipher aes_gcm_cipher static int aes_t4_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aes_t4_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_XTS_CTX *xctx = EVP_C_DATA(EVP_AES_XTS_CTX,ctx); if (!iv && !key) return 1; if (key) { /* The key is two half length keys in reality */ const int keylen = EVP_CIPHER_CTX_get_key_length(ctx); const int bytes = keylen / 2; const int bits = bytes * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } /* * Verify that the two keys are different. * * This addresses Rogaway's vulnerability. * See comment in aes_xts_init_key() below. */ if ((!allow_insecure_decrypt || enc) && CRYPTO_memcmp(key, key + bytes, bytes) == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_XTS_DUPLICATED_KEYS); return 0; } xctx->stream = NULL; /* key_len is two AES keys */ if (enc) { aes_t4_set_encrypt_key(key, bits, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) aes_t4_encrypt; switch (bits) { case 128: xctx->stream = aes128_t4_xts_encrypt; break; case 256: xctx->stream = aes256_t4_xts_encrypt; break; default: return 0; } } else { aes_t4_set_decrypt_key(key, bits, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) aes_t4_decrypt; switch (bits) { case 128: xctx->stream = aes128_t4_xts_decrypt; break; case 256: xctx->stream = aes256_t4_xts_decrypt; break; default: return 0; } } aes_t4_set_encrypt_key(key + bytes, bits, &xctx->ks2.ks); xctx->xts.block2 = (block128_f) aes_t4_encrypt; xctx->xts.key1 = &xctx->ks1; } if (iv) { xctx->xts.key2 = &xctx->ks2; memcpy(ctx->iv, iv, 16); } return 1; } # define aes_t4_xts_cipher aes_xts_cipher static int aes_t4_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aes_t4_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,ctx); if (iv == NULL && key == NULL) return 1; if (key != NULL) { const int bits = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (bits <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } aes_t4_set_encrypt_key(key, bits, &cctx->ks.ks); CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, &cctx->ks, (block128_f) aes_t4_encrypt); cctx->str = NULL; cctx->key_set = 1; } if (iv) { memcpy(ctx->iv, iv, 15 - cctx->L); cctx->iv_set = 1; } return 1; } # define aes_t4_ccm_cipher aes_ccm_cipher static int aes_t4_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # ifndef OPENSSL_NO_OCB static int aes_t4_ocb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,ctx); if (iv == NULL && key == NULL) return 1; if (key != NULL) { const int keylen = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } do { /* * We set both the encrypt and decrypt key here because decrypt * needs both. We could possibly optimise to remove setting the * decrypt for an encryption operation. */ aes_t4_set_encrypt_key(key, keylen, &octx->ksenc.ks); aes_t4_set_decrypt_key(key, keylen, &octx->ksdec.ks); if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc.ks, &octx->ksdec.ks, (block128_f) aes_t4_encrypt, (block128_f) aes_t4_decrypt, NULL)) return 0; } while (0); /* * If we have an iv we can set it directly, otherwise use saved IV. */ if (iv == NULL && octx->iv_set) iv = octx->iv; if (iv) { if (CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen) != 1) return 0; octx->iv_set = 1; } octx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (octx->key_set) CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen); else memcpy(octx->iv, iv, octx->ivlen); octx->iv_set = 1; } return 1; } # define aes_t4_ocb_cipher aes_ocb_cipher static int aes_t4_ocb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # endif /* OPENSSL_NO_OCB */ # ifndef OPENSSL_NO_SIV # define aes_t4_siv_init_key aes_siv_init_key # define aes_t4_siv_cipher aes_siv_cipher # endif /* OPENSSL_NO_SIV */ # define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ static const EVP_CIPHER aes_t4_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aes_t4_init_key, \ aes_t4_##mode##_cipher, \ NULL, \ sizeof(EVP_AES_KEY), \ NULL,NULL,NULL,NULL }; \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize, \ keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aes_init_key, \ aes_##mode##_cipher, \ NULL, \ sizeof(EVP_AES_KEY), \ NULL,NULL,NULL,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return SPARC_AES_CAPABLE?&aes_t4_##keylen##_##mode:&aes_##keylen##_##mode; } # define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \ static const EVP_CIPHER aes_t4_##keylen##_##mode = { \ nid##_##keylen##_##mode,blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE||EVP_CIPH_##MODE##_MODE==EVP_CIPH_SIV_MODE?2:1)*keylen/8, \ ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aes_t4_##mode##_init_key, \ aes_t4_##mode##_cipher, \ aes_##mode##_cleanup, \ sizeof(EVP_AES_##MODE##_CTX), \ NULL,NULL,aes_##mode##_ctrl,NULL }; \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##mode,blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE||EVP_CIPH_##MODE##_MODE==EVP_CIPH_SIV_MODE?2:1)*keylen/8, \ ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aes_##mode##_init_key, \ aes_##mode##_cipher, \ aes_##mode##_cleanup, \ sizeof(EVP_AES_##MODE##_CTX), \ NULL,NULL,aes_##mode##_ctrl,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return SPARC_AES_CAPABLE?&aes_t4_##keylen##_##mode:&aes_##keylen##_##mode; } #elif defined(S390X_aes_128_CAPABLE) /* IBM S390X support */ typedef struct { union { OSSL_UNION_ALIGN; /*- * KM-AES parameter block - begin * (see z/Architecture Principles of Operation >= SA22-7832-06) */ struct { unsigned char k[32]; } param; /* KM-AES parameter block - end */ } km; unsigned int fc; } S390X_AES_ECB_CTX; typedef struct { union { OSSL_UNION_ALIGN; /*- * KMO-AES parameter block - begin * (see z/Architecture Principles of Operation >= SA22-7832-08) */ struct { unsigned char cv[16]; unsigned char k[32]; } param; /* KMO-AES parameter block - end */ } kmo; unsigned int fc; } S390X_AES_OFB_CTX; typedef struct { union { OSSL_UNION_ALIGN; /*- * KMF-AES parameter block - begin * (see z/Architecture Principles of Operation >= SA22-7832-08) */ struct { unsigned char cv[16]; unsigned char k[32]; } param; /* KMF-AES parameter block - end */ } kmf; unsigned int fc; } S390X_AES_CFB_CTX; typedef struct { union { OSSL_UNION_ALIGN; /*- * KMA-GCM-AES parameter block - begin * (see z/Architecture Principles of Operation >= SA22-7832-11) */ struct { unsigned char reserved[12]; union { unsigned int w; unsigned char b[4]; } cv; union { unsigned long long g[2]; unsigned char b[16]; } t; unsigned char h[16]; unsigned long long taadl; unsigned long long tpcl; union { unsigned long long g[2]; unsigned int w[4]; } j0; unsigned char k[32]; } param; /* KMA-GCM-AES parameter block - end */ } kma; unsigned int fc; int key_set; unsigned char *iv; int ivlen; int iv_set; int iv_gen; int taglen; unsigned char ares[16]; unsigned char mres[16]; unsigned char kres[16]; int areslen; int mreslen; int kreslen; int tls_aad_len; uint64_t tls_enc_records; /* Number of TLS records encrypted */ } S390X_AES_GCM_CTX; typedef struct { union { OSSL_UNION_ALIGN; /*- * Padding is chosen so that ccm.kmac_param.k overlaps with key.k and * ccm.fc with key.k.rounds. Remember that on s390x, an AES_KEY's * rounds field is used to store the function code and that the key * schedule is not stored (if aes hardware support is detected). */ struct { unsigned char pad[16]; AES_KEY k; } key; struct { /*- * KMAC-AES parameter block - begin * (see z/Architecture Principles of Operation >= SA22-7832-08) */ struct { union { unsigned long long g[2]; unsigned char b[16]; } icv; unsigned char k[32]; } kmac_param; /* KMAC-AES parameter block - end */ union { unsigned long long g[2]; unsigned char b[16]; } nonce; union { unsigned long long g[2]; unsigned char b[16]; } buf; unsigned long long blocks; int l; int m; int tls_aad_len; int iv_set; int tag_set; int len_set; int key_set; unsigned char pad[140]; unsigned int fc; } ccm; } aes; } S390X_AES_CCM_CTX; # define s390x_aes_init_key aes_init_key static int s390x_aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); # define S390X_AES_CBC_CTX EVP_AES_KEY # define s390x_aes_cbc_init_key aes_init_key # define s390x_aes_cbc_cipher aes_cbc_cipher static int s390x_aes_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int s390x_aes_ecb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { S390X_AES_ECB_CTX *cctx = EVP_C_DATA(S390X_AES_ECB_CTX, ctx); const int keylen = EVP_CIPHER_CTX_get_key_length(ctx); if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } cctx->fc = S390X_AES_FC(keylen); if (!enc) cctx->fc |= S390X_DECRYPT; memcpy(cctx->km.param.k, key, keylen); return 1; } static int s390x_aes_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { S390X_AES_ECB_CTX *cctx = EVP_C_DATA(S390X_AES_ECB_CTX, ctx); s390x_km(in, len, out, cctx->fc, &cctx->km.param); return 1; } static int s390x_aes_ofb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *ivec, int enc) { S390X_AES_OFB_CTX *cctx = EVP_C_DATA(S390X_AES_OFB_CTX, ctx); const unsigned char *iv = ctx->oiv; const int keylen = EVP_CIPHER_CTX_get_key_length(ctx); const int ivlen = EVP_CIPHER_CTX_get_iv_length(ctx); if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } if (ivlen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_IV_LENGTH); return 0; } memcpy(cctx->kmo.param.cv, iv, ivlen); memcpy(cctx->kmo.param.k, key, keylen); cctx->fc = S390X_AES_FC(keylen); return 1; } static int s390x_aes_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { S390X_AES_OFB_CTX *cctx = EVP_C_DATA(S390X_AES_OFB_CTX, ctx); const int ivlen = EVP_CIPHER_CTX_get_iv_length(ctx); unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx); int n = ctx->num; int rem; memcpy(cctx->kmo.param.cv, iv, ivlen); while (n && len) { *out = *in ^ cctx->kmo.param.cv[n]; n = (n + 1) & 0xf; --len; ++in; ++out; } rem = len & 0xf; len &= ~(size_t)0xf; if (len) { s390x_kmo(in, len, out, cctx->fc, &cctx->kmo.param); out += len; in += len; } if (rem) { s390x_km(cctx->kmo.param.cv, 16, cctx->kmo.param.cv, cctx->fc, cctx->kmo.param.k); while (rem--) { out[n] = in[n] ^ cctx->kmo.param.cv[n]; ++n; } } memcpy(iv, cctx->kmo.param.cv, ivlen); ctx->num = n; return 1; } static int s390x_aes_cfb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *ivec, int enc) { S390X_AES_CFB_CTX *cctx = EVP_C_DATA(S390X_AES_CFB_CTX, ctx); const unsigned char *iv = ctx->oiv; const int keylen = EVP_CIPHER_CTX_get_key_length(ctx); const int ivlen = EVP_CIPHER_CTX_get_iv_length(ctx); if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } if (ivlen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_IV_LENGTH); return 0; } cctx->fc = S390X_AES_FC(keylen); cctx->fc |= 16 << 24; /* 16 bytes cipher feedback */ if (!enc) cctx->fc |= S390X_DECRYPT; memcpy(cctx->kmf.param.cv, iv, ivlen); memcpy(cctx->kmf.param.k, key, keylen); return 1; } static int s390x_aes_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { S390X_AES_CFB_CTX *cctx = EVP_C_DATA(S390X_AES_CFB_CTX, ctx); const int keylen = EVP_CIPHER_CTX_get_key_length(ctx); const int enc = EVP_CIPHER_CTX_is_encrypting(ctx); const int ivlen = EVP_CIPHER_CTX_get_iv_length(ctx); unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx); int n = ctx->num; int rem; unsigned char tmp; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } if (ivlen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_IV_LENGTH); return 0; } memcpy(cctx->kmf.param.cv, iv, ivlen); while (n && len) { tmp = *in; *out = cctx->kmf.param.cv[n] ^ tmp; cctx->kmf.param.cv[n] = enc ? *out : tmp; n = (n + 1) & 0xf; --len; ++in; ++out; } rem = len & 0xf; len &= ~(size_t)0xf; if (len) { s390x_kmf(in, len, out, cctx->fc, &cctx->kmf.param); out += len; in += len; } if (rem) { s390x_km(cctx->kmf.param.cv, 16, cctx->kmf.param.cv, S390X_AES_FC(keylen), cctx->kmf.param.k); while (rem--) { tmp = in[n]; out[n] = cctx->kmf.param.cv[n] ^ tmp; cctx->kmf.param.cv[n] = enc ? out[n] : tmp; ++n; } } memcpy(iv, cctx->kmf.param.cv, ivlen); ctx->num = n; return 1; } static int s390x_aes_cfb8_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *ivec, int enc) { S390X_AES_CFB_CTX *cctx = EVP_C_DATA(S390X_AES_CFB_CTX, ctx); const unsigned char *iv = ctx->oiv; const int keylen = EVP_CIPHER_CTX_get_key_length(ctx); const int ivlen = EVP_CIPHER_CTX_get_iv_length(ctx); if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } if (ivlen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_IV_LENGTH); return 0; } cctx->fc = S390X_AES_FC(keylen); cctx->fc |= 1 << 24; /* 1 byte cipher feedback */ if (!enc) cctx->fc |= S390X_DECRYPT; memcpy(cctx->kmf.param.cv, iv, ivlen); memcpy(cctx->kmf.param.k, key, keylen); return 1; } static int s390x_aes_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { S390X_AES_CFB_CTX *cctx = EVP_C_DATA(S390X_AES_CFB_CTX, ctx); const int ivlen = EVP_CIPHER_CTX_get_iv_length(ctx); unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx); memcpy(cctx->kmf.param.cv, iv, ivlen); s390x_kmf(in, len, out, cctx->fc, &cctx->kmf.param); memcpy(iv, cctx->kmf.param.cv, ivlen); return 1; } # define s390x_aes_cfb1_init_key aes_init_key # define s390x_aes_cfb1_cipher aes_cfb1_cipher static int s390x_aes_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define S390X_AES_CTR_CTX EVP_AES_KEY # define s390x_aes_ctr_init_key aes_init_key # define s390x_aes_ctr_cipher aes_ctr_cipher static int s390x_aes_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); /* iv + padding length for iv lengths != 12 */ # define S390X_gcm_ivpadlen(i) ((((i) + 15) >> 4 << 4) + 16) /*- * Process additional authenticated data. Returns 0 on success. Code is * big-endian. */ static int s390x_aes_gcm_aad(S390X_AES_GCM_CTX *ctx, const unsigned char *aad, size_t len) { unsigned long long alen; int n, rem; if (ctx->kma.param.tpcl) return -2; alen = ctx->kma.param.taadl + len; if (alen > (U64(1) << 61) || (sizeof(len) == 8 && alen < len)) return -1; ctx->kma.param.taadl = alen; n = ctx->areslen; if (n) { while (n && len) { ctx->ares[n] = *aad; n = (n + 1) & 0xf; ++aad; --len; } /* ctx->ares contains a complete block if offset has wrapped around */ if (!n) { s390x_kma(ctx->ares, 16, NULL, 0, NULL, ctx->fc, &ctx->kma.param); ctx->fc |= S390X_KMA_HS; } ctx->areslen = n; } rem = len & 0xf; len &= ~(size_t)0xf; if (len) { s390x_kma(aad, len, NULL, 0, NULL, ctx->fc, &ctx->kma.param); aad += len; ctx->fc |= S390X_KMA_HS; } if (rem) { ctx->areslen = rem; do { --rem; ctx->ares[rem] = aad[rem]; } while (rem); } return 0; } /*- * En/de-crypt plain/cipher-text and authenticate ciphertext. Returns 0 for * success. Code is big-endian. */ static int s390x_aes_gcm(S390X_AES_GCM_CTX *ctx, const unsigned char *in, unsigned char *out, size_t len) { const unsigned char *inptr; unsigned long long mlen; union { unsigned int w[4]; unsigned char b[16]; } buf; size_t inlen; int n, rem, i; mlen = ctx->kma.param.tpcl + len; if (mlen > ((U64(1) << 36) - 32) || (sizeof(len) == 8 && mlen < len)) return -1; ctx->kma.param.tpcl = mlen; n = ctx->mreslen; if (n) { inptr = in; inlen = len; while (n && inlen) { ctx->mres[n] = *inptr; n = (n + 1) & 0xf; ++inptr; --inlen; } /* ctx->mres contains a complete block if offset has wrapped around */ if (!n) { s390x_kma(ctx->ares, ctx->areslen, ctx->mres, 16, buf.b, ctx->fc | S390X_KMA_LAAD, &ctx->kma.param); ctx->fc |= S390X_KMA_HS; ctx->areslen = 0; /* previous call already encrypted/decrypted its remainder, * see comment below */ n = ctx->mreslen; while (n) { *out = buf.b[n]; n = (n + 1) & 0xf; ++out; ++in; --len; } ctx->mreslen = 0; } } rem = len & 0xf; len &= ~(size_t)0xf; if (len) { s390x_kma(ctx->ares, ctx->areslen, in, len, out, ctx->fc | S390X_KMA_LAAD, &ctx->kma.param); in += len; out += len; ctx->fc |= S390X_KMA_HS; ctx->areslen = 0; } /*- * If there is a remainder, it has to be saved such that it can be * processed by kma later. However, we also have to do the for-now * unauthenticated encryption/decryption part here and now... */ if (rem) { if (!ctx->mreslen) { buf.w[0] = ctx->kma.param.j0.w[0]; buf.w[1] = ctx->kma.param.j0.w[1]; buf.w[2] = ctx->kma.param.j0.w[2]; buf.w[3] = ctx->kma.param.cv.w + 1; s390x_km(buf.b, 16, ctx->kres, ctx->fc & 0x1f, &ctx->kma.param.k); } n = ctx->mreslen; for (i = 0; i < rem; i++) { ctx->mres[n + i] = in[i]; out[i] = in[i] ^ ctx->kres[n + i]; } ctx->mreslen += rem; } return 0; } /*- * Initialize context structure. Code is big-endian. */ static void s390x_aes_gcm_setiv(S390X_AES_GCM_CTX *ctx, const unsigned char *iv) { ctx->kma.param.t.g[0] = 0; ctx->kma.param.t.g[1] = 0; ctx->kma.param.tpcl = 0; ctx->kma.param.taadl = 0; ctx->mreslen = 0; ctx->areslen = 0; ctx->kreslen = 0; if (ctx->ivlen == 12) { memcpy(&ctx->kma.param.j0, iv, ctx->ivlen); ctx->kma.param.j0.w[3] = 1; ctx->kma.param.cv.w = 1; } else { /* ctx->iv has the right size and is already padded. */ memcpy(ctx->iv, iv, ctx->ivlen); s390x_kma(ctx->iv, S390X_gcm_ivpadlen(ctx->ivlen), NULL, 0, NULL, ctx->fc, &ctx->kma.param); ctx->fc |= S390X_KMA_HS; ctx->kma.param.j0.g[0] = ctx->kma.param.t.g[0]; ctx->kma.param.j0.g[1] = ctx->kma.param.t.g[1]; ctx->kma.param.cv.w = ctx->kma.param.j0.w[3]; ctx->kma.param.t.g[0] = 0; ctx->kma.param.t.g[1] = 0; } } /*- * Performs various operations on the context structure depending on control * type. Returns 1 for success, 0 for failure and -1 for unknown control type. * Code is big-endian. */ static int s390x_aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { S390X_AES_GCM_CTX *gctx = EVP_C_DATA(S390X_AES_GCM_CTX, c); S390X_AES_GCM_CTX *gctx_out; EVP_CIPHER_CTX *out; unsigned char *buf; int ivlen, enc, len; switch (type) { case EVP_CTRL_INIT: ivlen = EVP_CIPHER_get_iv_length(c->cipher); gctx->key_set = 0; gctx->iv_set = 0; gctx->ivlen = ivlen; gctx->iv = c->iv; gctx->taglen = -1; gctx->iv_gen = 0; gctx->tls_aad_len = -1; return 1; case EVP_CTRL_GET_IVLEN: *(int *)ptr = gctx->ivlen; return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0) return 0; if (arg != 12) { len = S390X_gcm_ivpadlen(arg); /* Allocate memory for iv if needed. */ if (gctx->ivlen == 12 || len > S390X_gcm_ivpadlen(gctx->ivlen)) { if (gctx->iv != c->iv) OPENSSL_free(gctx->iv); if ((gctx->iv = OPENSSL_malloc(len)) == NULL) return 0; } /* Add padding. */ memset(gctx->iv + arg, 0, len - arg - 8); *((unsigned long long *)(gctx->iv + len - 8)) = arg << 3; } gctx->ivlen = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: buf = EVP_CIPHER_CTX_buf_noconst(c); enc = EVP_CIPHER_CTX_is_encrypting(c); if (arg <= 0 || arg > 16 || enc) return 0; memcpy(buf, ptr, arg); gctx->taglen = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: enc = EVP_CIPHER_CTX_is_encrypting(c); if (arg <= 0 || arg > 16 || !enc || gctx->taglen < 0) return 0; memcpy(ptr, gctx->kma.param.t.b, arg); return 1; case EVP_CTRL_GCM_SET_IV_FIXED: /* Special case: -1 length restores whole iv */ if (arg == -1) { memcpy(gctx->iv, ptr, gctx->ivlen); gctx->iv_gen = 1; return 1; } /* * Fixed field must be at least 4 bytes and invocation field at least * 8. */ if ((arg < 4) || (gctx->ivlen - arg) < 8) return 0; if (arg) memcpy(gctx->iv, ptr, arg); enc = EVP_CIPHER_CTX_is_encrypting(c); if (enc && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0) return 0; gctx->iv_gen = 1; return 1; case EVP_CTRL_GCM_IV_GEN: if (gctx->iv_gen == 0 || gctx->key_set == 0) return 0; s390x_aes_gcm_setiv(gctx, gctx->iv); if (arg <= 0 || arg > gctx->ivlen) arg = gctx->ivlen; memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg); /* * Invocation field will be at least 8 bytes in size and so no need * to check wrap around or increment more than last 8 bytes. */ ctr64_inc(gctx->iv + gctx->ivlen - 8); gctx->iv_set = 1; return 1; case EVP_CTRL_GCM_SET_IV_INV: enc = EVP_CIPHER_CTX_is_encrypting(c); if (gctx->iv_gen == 0 || gctx->key_set == 0 || enc) return 0; memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); s390x_aes_gcm_setiv(gctx, gctx->iv); gctx->iv_set = 1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the aad for later use. */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; buf = EVP_CIPHER_CTX_buf_noconst(c); memcpy(buf, ptr, arg); gctx->tls_aad_len = arg; gctx->tls_enc_records = 0; len = buf[arg - 2] << 8 | buf[arg - 1]; /* Correct length for explicit iv. */ if (len < EVP_GCM_TLS_EXPLICIT_IV_LEN) return 0; len -= EVP_GCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too. */ enc = EVP_CIPHER_CTX_is_encrypting(c); if (!enc) { if (len < EVP_GCM_TLS_TAG_LEN) return 0; len -= EVP_GCM_TLS_TAG_LEN; } buf[arg - 2] = len >> 8; buf[arg - 1] = len & 0xff; /* Extra padding: tag appended to record. */ return EVP_GCM_TLS_TAG_LEN; case EVP_CTRL_COPY: out = ptr; gctx_out = EVP_C_DATA(S390X_AES_GCM_CTX, out); if (gctx->iv == c->iv) { gctx_out->iv = out->iv; } else { len = S390X_gcm_ivpadlen(gctx->ivlen); if ((gctx_out->iv = OPENSSL_malloc(len)) == NULL) return 0; memcpy(gctx_out->iv, gctx->iv, len); } return 1; default: return -1; } } /*- * Set key and/or iv. Returns 1 on success. Otherwise 0 is returned. */ static int s390x_aes_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { S390X_AES_GCM_CTX *gctx = EVP_C_DATA(S390X_AES_GCM_CTX, ctx); int keylen; if (iv == NULL && key == NULL) return 1; if (key != NULL) { keylen = EVP_CIPHER_CTX_get_key_length(ctx); if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } memcpy(&gctx->kma.param.k, key, keylen); gctx->fc = S390X_AES_FC(keylen); if (!enc) gctx->fc |= S390X_DECRYPT; if (iv == NULL && gctx->iv_set) iv = gctx->iv; if (iv != NULL) { s390x_aes_gcm_setiv(gctx, iv); gctx->iv_set = 1; } gctx->key_set = 1; } else { if (gctx->key_set) s390x_aes_gcm_setiv(gctx, iv); else memcpy(gctx->iv, iv, gctx->ivlen); gctx->iv_set = 1; gctx->iv_gen = 0; } return 1; } /*- * En/de-crypt and authenticate TLS packet. Returns the number of bytes written * if successful. Otherwise -1 is returned. Code is big-endian. */ static int s390x_aes_gcm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { S390X_AES_GCM_CTX *gctx = EVP_C_DATA(S390X_AES_GCM_CTX, ctx); const unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx); const int enc = EVP_CIPHER_CTX_is_encrypting(ctx); int rv = -1; if (out != in || len < (EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN)) return -1; /* * Check for too many keys as per FIPS 140-2 IG A.5 "Key/IV Pair Uniqueness * Requirements from SP 800-38D". The requirements is for one party to the * communication to fail after 2^64 - 1 keys. We do this on the encrypting * side only. */ if (enc && ++gctx->tls_enc_records == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_TOO_MANY_RECORDS); goto err; } if (EVP_CIPHER_CTX_ctrl(ctx, enc ? EVP_CTRL_GCM_IV_GEN : EVP_CTRL_GCM_SET_IV_INV, EVP_GCM_TLS_EXPLICIT_IV_LEN, out) <= 0) goto err; in += EVP_GCM_TLS_EXPLICIT_IV_LEN; out += EVP_GCM_TLS_EXPLICIT_IV_LEN; len -= EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN; gctx->kma.param.taadl = gctx->tls_aad_len << 3; gctx->kma.param.tpcl = len << 3; s390x_kma(buf, gctx->tls_aad_len, in, len, out, gctx->fc | S390X_KMA_LAAD | S390X_KMA_LPC, &gctx->kma.param); if (enc) { memcpy(out + len, gctx->kma.param.t.b, EVP_GCM_TLS_TAG_LEN); rv = len + EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN; } else { if (CRYPTO_memcmp(gctx->kma.param.t.b, in + len, EVP_GCM_TLS_TAG_LEN)) { OPENSSL_cleanse(out, len); goto err; } rv = len; } err: gctx->iv_set = 0; gctx->tls_aad_len = -1; return rv; } /*- * Called from EVP layer to initialize context, process additional * authenticated data, en/de-crypt plain/cipher-text and authenticate * ciphertext or process a TLS packet, depending on context. Returns bytes * written on success. Otherwise -1 is returned. Code is big-endian. */ static int s390x_aes_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { S390X_AES_GCM_CTX *gctx = EVP_C_DATA(S390X_AES_GCM_CTX, ctx); unsigned char *buf, tmp[16]; int enc; if (!gctx->key_set) return -1; if (gctx->tls_aad_len >= 0) return s390x_aes_gcm_tls_cipher(ctx, out, in, len); if (!gctx->iv_set) return -1; if (in != NULL) { if (out == NULL) { if (s390x_aes_gcm_aad(gctx, in, len)) return -1; } else { if (s390x_aes_gcm(gctx, in, out, len)) return -1; } return len; } else { gctx->kma.param.taadl <<= 3; gctx->kma.param.tpcl <<= 3; s390x_kma(gctx->ares, gctx->areslen, gctx->mres, gctx->mreslen, tmp, gctx->fc | S390X_KMA_LAAD | S390X_KMA_LPC, &gctx->kma.param); /* recall that we already did en-/decrypt gctx->mres * and returned it to caller... */ OPENSSL_cleanse(tmp, gctx->mreslen); gctx->iv_set = 0; enc = EVP_CIPHER_CTX_is_encrypting(ctx); if (enc) { gctx->taglen = 16; } else { if (gctx->taglen < 0) return -1; buf = EVP_CIPHER_CTX_buf_noconst(ctx); if (CRYPTO_memcmp(buf, gctx->kma.param.t.b, gctx->taglen)) return -1; } return 0; } } static int s390x_aes_gcm_cleanup(EVP_CIPHER_CTX *c) { S390X_AES_GCM_CTX *gctx = EVP_C_DATA(S390X_AES_GCM_CTX, c); if (gctx == NULL) return 0; if (gctx->iv != c->iv) OPENSSL_free(gctx->iv); OPENSSL_cleanse(gctx, sizeof(*gctx)); return 1; } # define S390X_AES_XTS_CTX EVP_AES_XTS_CTX # define s390x_aes_xts_init_key aes_xts_init_key static int s390x_aes_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); # define s390x_aes_xts_cipher aes_xts_cipher static int s390x_aes_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define s390x_aes_xts_ctrl aes_xts_ctrl static int s390x_aes_xts_ctrl(EVP_CIPHER_CTX *, int type, int arg, void *ptr); # define s390x_aes_xts_cleanup aes_xts_cleanup /*- * Set nonce and length fields. Code is big-endian. */ static inline void s390x_aes_ccm_setiv(S390X_AES_CCM_CTX *ctx, const unsigned char *nonce, size_t mlen) { ctx->aes.ccm.nonce.b[0] &= ~S390X_CCM_AAD_FLAG; ctx->aes.ccm.nonce.g[1] = mlen; memcpy(ctx->aes.ccm.nonce.b + 1, nonce, 15 - ctx->aes.ccm.l); } /*- * Process additional authenticated data. Code is big-endian. */ static void s390x_aes_ccm_aad(S390X_AES_CCM_CTX *ctx, const unsigned char *aad, size_t alen) { unsigned char *ptr; int i, rem; if (!alen) return; ctx->aes.ccm.nonce.b[0] |= S390X_CCM_AAD_FLAG; /* Suppress 'type-punned pointer dereference' warning. */ ptr = ctx->aes.ccm.buf.b; if (alen < ((1 << 16) - (1 << 8))) { *(uint16_t *)ptr = alen; i = 2; } else if (sizeof(alen) == 8 && alen >= (size_t)1 << (32 % (sizeof(alen) * 8))) { *(uint16_t *)ptr = 0xffff; *(uint64_t *)(ptr + 2) = alen; i = 10; } else { *(uint16_t *)ptr = 0xfffe; *(uint32_t *)(ptr + 2) = alen; i = 6; } while (i < 16 && alen) { ctx->aes.ccm.buf.b[i] = *aad; ++aad; --alen; ++i; } while (i < 16) { ctx->aes.ccm.buf.b[i] = 0; ++i; } ctx->aes.ccm.kmac_param.icv.g[0] = 0; ctx->aes.ccm.kmac_param.icv.g[1] = 0; s390x_kmac(ctx->aes.ccm.nonce.b, 32, ctx->aes.ccm.fc, &ctx->aes.ccm.kmac_param); ctx->aes.ccm.blocks += 2; rem = alen & 0xf; alen &= ~(size_t)0xf; if (alen) { s390x_kmac(aad, alen, ctx->aes.ccm.fc, &ctx->aes.ccm.kmac_param); ctx->aes.ccm.blocks += alen >> 4; aad += alen; } if (rem) { for (i = 0; i < rem; i++) ctx->aes.ccm.kmac_param.icv.b[i] ^= aad[i]; s390x_km(ctx->aes.ccm.kmac_param.icv.b, 16, ctx->aes.ccm.kmac_param.icv.b, ctx->aes.ccm.fc, ctx->aes.ccm.kmac_param.k); ctx->aes.ccm.blocks++; } } /*- * En/de-crypt plain/cipher-text. Compute tag from plaintext. Returns 0 for * success. */ static int s390x_aes_ccm(S390X_AES_CCM_CTX *ctx, const unsigned char *in, unsigned char *out, size_t len, int enc) { size_t n, rem; unsigned int i, l, num; unsigned char flags; flags = ctx->aes.ccm.nonce.b[0]; if (!(flags & S390X_CCM_AAD_FLAG)) { s390x_km(ctx->aes.ccm.nonce.b, 16, ctx->aes.ccm.kmac_param.icv.b, ctx->aes.ccm.fc, ctx->aes.ccm.kmac_param.k); ctx->aes.ccm.blocks++; } l = flags & 0x7; ctx->aes.ccm.nonce.b[0] = l; /*- * Reconstruct length from encoded length field * and initialize it with counter value. */ n = 0; for (i = 15 - l; i < 15; i++) { n |= ctx->aes.ccm.nonce.b[i]; ctx->aes.ccm.nonce.b[i] = 0; n <<= 8; } n |= ctx->aes.ccm.nonce.b[15]; ctx->aes.ccm.nonce.b[15] = 1; if (n != len) return -1; /* length mismatch */ if (enc) { /* Two operations per block plus one for tag encryption */ ctx->aes.ccm.blocks += (((len + 15) >> 4) << 1) + 1; if (ctx->aes.ccm.blocks > (1ULL << 61)) return -2; /* too much data */ } num = 0; rem = len & 0xf; len &= ~(size_t)0xf; if (enc) { /* mac-then-encrypt */ if (len) s390x_kmac(in, len, ctx->aes.ccm.fc, &ctx->aes.ccm.kmac_param); if (rem) { for (i = 0; i < rem; i++) ctx->aes.ccm.kmac_param.icv.b[i] ^= in[len + i]; s390x_km(ctx->aes.ccm.kmac_param.icv.b, 16, ctx->aes.ccm.kmac_param.icv.b, ctx->aes.ccm.fc, ctx->aes.ccm.kmac_param.k); } CRYPTO_ctr128_encrypt_ctr32(in, out, len + rem, &ctx->aes.key.k, ctx->aes.ccm.nonce.b, ctx->aes.ccm.buf.b, &num, (ctr128_f)AES_ctr32_encrypt); } else { /* decrypt-then-mac */ CRYPTO_ctr128_encrypt_ctr32(in, out, len + rem, &ctx->aes.key.k, ctx->aes.ccm.nonce.b, ctx->aes.ccm.buf.b, &num, (ctr128_f)AES_ctr32_encrypt); if (len) s390x_kmac(out, len, ctx->aes.ccm.fc, &ctx->aes.ccm.kmac_param); if (rem) { for (i = 0; i < rem; i++) ctx->aes.ccm.kmac_param.icv.b[i] ^= out[len + i]; s390x_km(ctx->aes.ccm.kmac_param.icv.b, 16, ctx->aes.ccm.kmac_param.icv.b, ctx->aes.ccm.fc, ctx->aes.ccm.kmac_param.k); } } /* encrypt tag */ for (i = 15 - l; i < 16; i++) ctx->aes.ccm.nonce.b[i] = 0; s390x_km(ctx->aes.ccm.nonce.b, 16, ctx->aes.ccm.buf.b, ctx->aes.ccm.fc, ctx->aes.ccm.kmac_param.k); ctx->aes.ccm.kmac_param.icv.g[0] ^= ctx->aes.ccm.buf.g[0]; ctx->aes.ccm.kmac_param.icv.g[1] ^= ctx->aes.ccm.buf.g[1]; ctx->aes.ccm.nonce.b[0] = flags; /* restore flags field */ return 0; } /*- * En/de-crypt and authenticate TLS packet. Returns the number of bytes written * if successful. Otherwise -1 is returned. */ static int s390x_aes_ccm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { S390X_AES_CCM_CTX *cctx = EVP_C_DATA(S390X_AES_CCM_CTX, ctx); unsigned char *ivec = ctx->iv; unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx); const int enc = EVP_CIPHER_CTX_is_encrypting(ctx); if (out != in || len < (EVP_CCM_TLS_EXPLICIT_IV_LEN + (size_t)cctx->aes.ccm.m)) return -1; if (enc) { /* Set explicit iv (sequence number). */ memcpy(out, buf, EVP_CCM_TLS_EXPLICIT_IV_LEN); } len -= EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->aes.ccm.m; /*- * Get explicit iv (sequence number). We already have fixed iv * (server/client_write_iv) here. */ memcpy(ivec + EVP_CCM_TLS_FIXED_IV_LEN, in, EVP_CCM_TLS_EXPLICIT_IV_LEN); s390x_aes_ccm_setiv(cctx, ivec, len); /* Process aad (sequence number|type|version|length) */ s390x_aes_ccm_aad(cctx, buf, cctx->aes.ccm.tls_aad_len); in += EVP_CCM_TLS_EXPLICIT_IV_LEN; out += EVP_CCM_TLS_EXPLICIT_IV_LEN; if (enc) { if (s390x_aes_ccm(cctx, in, out, len, enc)) return -1; memcpy(out + len, cctx->aes.ccm.kmac_param.icv.b, cctx->aes.ccm.m); return len + EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->aes.ccm.m; } else { if (!s390x_aes_ccm(cctx, in, out, len, enc)) { if (!CRYPTO_memcmp(cctx->aes.ccm.kmac_param.icv.b, in + len, cctx->aes.ccm.m)) return len; } OPENSSL_cleanse(out, len); return -1; } } /*- * Set key and flag field and/or iv. Returns 1 if successful. Otherwise 0 is * returned. */ static int s390x_aes_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { S390X_AES_CCM_CTX *cctx = EVP_C_DATA(S390X_AES_CCM_CTX, ctx); int keylen; if (iv == NULL && key == NULL) return 1; if (key != NULL) { keylen = EVP_CIPHER_CTX_get_key_length(ctx); if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } cctx->aes.ccm.fc = S390X_AES_FC(keylen); memcpy(cctx->aes.ccm.kmac_param.k, key, keylen); /* Store encoded m and l. */ cctx->aes.ccm.nonce.b[0] = ((cctx->aes.ccm.l - 1) & 0x7) | (((cctx->aes.ccm.m - 2) >> 1) & 0x7) << 3; memset(cctx->aes.ccm.nonce.b + 1, 0, sizeof(cctx->aes.ccm.nonce.b)); cctx->aes.ccm.blocks = 0; cctx->aes.ccm.key_set = 1; } if (iv != NULL) { memcpy(ctx->iv, iv, 15 - cctx->aes.ccm.l); cctx->aes.ccm.iv_set = 1; } return 1; } /*- * Called from EVP layer to initialize context, process additional * authenticated data, en/de-crypt plain/cipher-text and authenticate * plaintext or process a TLS packet, depending on context. Returns bytes * written on success. Otherwise -1 is returned. */ static int s390x_aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { S390X_AES_CCM_CTX *cctx = EVP_C_DATA(S390X_AES_CCM_CTX, ctx); const int enc = EVP_CIPHER_CTX_is_encrypting(ctx); int rv; unsigned char *buf; if (!cctx->aes.ccm.key_set) return -1; if (cctx->aes.ccm.tls_aad_len >= 0) return s390x_aes_ccm_tls_cipher(ctx, out, in, len); /*- * Final(): Does not return any data. Recall that ccm is mac-then-encrypt * so integrity must be checked already at Update() i.e., before * potentially corrupted data is output. */ if (in == NULL && out != NULL) return 0; if (!cctx->aes.ccm.iv_set) return -1; if (out == NULL) { /* Update(): Pass message length. */ if (in == NULL) { s390x_aes_ccm_setiv(cctx, ctx->iv, len); cctx->aes.ccm.len_set = 1; return len; } /* Update(): Process aad. */ if (!cctx->aes.ccm.len_set && len) return -1; s390x_aes_ccm_aad(cctx, in, len); return len; } /* The tag must be set before actually decrypting data */ if (!enc && !cctx->aes.ccm.tag_set) return -1; /* Update(): Process message. */ if (!cctx->aes.ccm.len_set) { /*- * In case message length was not previously set explicitly via * Update(), set it now. */ s390x_aes_ccm_setiv(cctx, ctx->iv, len); cctx->aes.ccm.len_set = 1; } if (enc) { if (s390x_aes_ccm(cctx, in, out, len, enc)) return -1; cctx->aes.ccm.tag_set = 1; return len; } else { rv = -1; if (!s390x_aes_ccm(cctx, in, out, len, enc)) { buf = EVP_CIPHER_CTX_buf_noconst(ctx); if (!CRYPTO_memcmp(cctx->aes.ccm.kmac_param.icv.b, buf, cctx->aes.ccm.m)) rv = len; } if (rv == -1) OPENSSL_cleanse(out, len); cctx->aes.ccm.iv_set = 0; cctx->aes.ccm.tag_set = 0; cctx->aes.ccm.len_set = 0; return rv; } } /*- * Performs various operations on the context structure depending on control * type. Returns 1 for success, 0 for failure and -1 for unknown control type. * Code is big-endian. */ static int s390x_aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { S390X_AES_CCM_CTX *cctx = EVP_C_DATA(S390X_AES_CCM_CTX, c); unsigned char *buf; int enc, len; switch (type) { case EVP_CTRL_INIT: cctx->aes.ccm.key_set = 0; cctx->aes.ccm.iv_set = 0; cctx->aes.ccm.l = 8; cctx->aes.ccm.m = 12; cctx->aes.ccm.tag_set = 0; cctx->aes.ccm.len_set = 0; cctx->aes.ccm.tls_aad_len = -1; return 1; case EVP_CTRL_GET_IVLEN: *(int *)ptr = 15 - cctx->aes.ccm.l; return 1; case EVP_CTRL_AEAD_TLS1_AAD: if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; /* Save the aad for later use. */ buf = EVP_CIPHER_CTX_buf_noconst(c); memcpy(buf, ptr, arg); cctx->aes.ccm.tls_aad_len = arg; len = buf[arg - 2] << 8 | buf[arg - 1]; if (len < EVP_CCM_TLS_EXPLICIT_IV_LEN) return 0; /* Correct length for explicit iv. */ len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; enc = EVP_CIPHER_CTX_is_encrypting(c); if (!enc) { if (len < cctx->aes.ccm.m) return 0; /* Correct length for tag. */ len -= cctx->aes.ccm.m; } buf[arg - 2] = len >> 8; buf[arg - 1] = len & 0xff; /* Extra padding: tag appended to record. */ return cctx->aes.ccm.m; case EVP_CTRL_CCM_SET_IV_FIXED: if (arg != EVP_CCM_TLS_FIXED_IV_LEN) return 0; /* Copy to first part of the iv. */ memcpy(c->iv, ptr, arg); return 1; case EVP_CTRL_AEAD_SET_IVLEN: arg = 15 - arg; /* fall-through */ case EVP_CTRL_CCM_SET_L: if (arg < 2 || arg > 8) return 0; cctx->aes.ccm.l = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if ((arg & 1) || arg < 4 || arg > 16) return 0; enc = EVP_CIPHER_CTX_is_encrypting(c); if (enc && ptr) return 0; if (ptr) { cctx->aes.ccm.tag_set = 1; buf = EVP_CIPHER_CTX_buf_noconst(c); memcpy(buf, ptr, arg); } cctx->aes.ccm.m = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: enc = EVP_CIPHER_CTX_is_encrypting(c); if (!enc || !cctx->aes.ccm.tag_set) return 0; if (arg < cctx->aes.ccm.m) return 0; memcpy(ptr, cctx->aes.ccm.kmac_param.icv.b, cctx->aes.ccm.m); cctx->aes.ccm.tag_set = 0; cctx->aes.ccm.iv_set = 0; cctx->aes.ccm.len_set = 0; return 1; case EVP_CTRL_COPY: return 1; default: return -1; } } # define s390x_aes_ccm_cleanup aes_ccm_cleanup # ifndef OPENSSL_NO_OCB # define S390X_AES_OCB_CTX EVP_AES_OCB_CTX # define s390x_aes_ocb_init_key aes_ocb_init_key static int s390x_aes_ocb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); # define s390x_aes_ocb_cipher aes_ocb_cipher static int s390x_aes_ocb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define s390x_aes_ocb_cleanup aes_ocb_cleanup static int s390x_aes_ocb_cleanup(EVP_CIPHER_CTX *); # define s390x_aes_ocb_ctrl aes_ocb_ctrl static int s390x_aes_ocb_ctrl(EVP_CIPHER_CTX *, int type, int arg, void *ptr); # endif # ifndef OPENSSL_NO_SIV # define S390X_AES_SIV_CTX EVP_AES_SIV_CTX # define s390x_aes_siv_init_key aes_siv_init_key # define s390x_aes_siv_cipher aes_siv_cipher # define s390x_aes_siv_cleanup aes_siv_cleanup # define s390x_aes_siv_ctrl aes_siv_ctrl # endif # define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode, \ MODE,flags) \ static const EVP_CIPHER s390x_aes_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize, \ keylen / 8, \ ivlen, \ flags | EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ s390x_aes_##mode##_init_key, \ s390x_aes_##mode##_cipher, \ NULL, \ sizeof(S390X_AES_##MODE##_CTX), \ NULL, \ NULL, \ NULL, \ NULL \ }; \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##nmode, \ blocksize, \ keylen / 8, \ ivlen, \ flags | EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aes_init_key, \ aes_##mode##_cipher, \ NULL, \ sizeof(EVP_AES_KEY), \ NULL, \ NULL, \ NULL, \ NULL \ }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { \ return S390X_aes_##keylen##_##mode##_CAPABLE ? \ &s390x_aes_##keylen##_##mode : &aes_##keylen##_##mode; \ } # define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags)\ static const EVP_CIPHER s390x_aes_##keylen##_##mode = { \ nid##_##keylen##_##mode, \ blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE||EVP_CIPH_##MODE##_MODE==EVP_CIPH_SIV_MODE ? 2 : 1) * keylen / 8, \ ivlen, \ flags | EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ s390x_aes_##mode##_init_key, \ s390x_aes_##mode##_cipher, \ s390x_aes_##mode##_cleanup, \ sizeof(S390X_AES_##MODE##_CTX), \ NULL, \ NULL, \ s390x_aes_##mode##_ctrl, \ NULL \ }; \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##mode,blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE||EVP_CIPH_##MODE##_MODE==EVP_CIPH_SIV_MODE ? 2 : 1) * keylen / 8, \ ivlen, \ flags | EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aes_##mode##_init_key, \ aes_##mode##_cipher, \ aes_##mode##_cleanup, \ sizeof(EVP_AES_##MODE##_CTX), \ NULL, \ NULL, \ aes_##mode##_ctrl, \ NULL \ }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { \ return S390X_aes_##keylen##_##mode##_CAPABLE ? \ &s390x_aes_##keylen##_##mode : &aes_##keylen##_##mode; \ } #else # define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aes_init_key, \ aes_##mode##_cipher, \ NULL, \ sizeof(EVP_AES_KEY), \ NULL,NULL,NULL,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return &aes_##keylen##_##mode; } # define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##mode,blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE||EVP_CIPH_##MODE##_MODE==EVP_CIPH_SIV_MODE?2:1)*keylen/8, \ ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ aes_##mode##_init_key, \ aes_##mode##_cipher, \ aes_##mode##_cleanup, \ sizeof(EVP_AES_##MODE##_CTX), \ NULL,NULL,aes_##mode##_ctrl,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return &aes_##keylen##_##mode; } #endif #define BLOCK_CIPHER_generic_pack(nid,keylen,flags) \ BLOCK_CIPHER_generic(nid,keylen,16,16,cbc,cbc,CBC,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,16,0,ecb,ecb,ECB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,1,16,ofb128,ofb,OFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,1,16,cfb128,cfb,CFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,1,16,cfb1,cfb1,CFB,flags) \ BLOCK_CIPHER_generic(nid,keylen,1,16,cfb8,cfb8,CFB,flags) \ BLOCK_CIPHER_generic(nid,keylen,1,16,ctr,ctr,CTR,flags) static int aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int ret, mode; EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); const int keylen = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } mode = EVP_CIPHER_CTX_get_mode(ctx); if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE) && !enc) { #ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { ret = HWAES_set_decrypt_key(key, keylen, &dat->ks.ks); dat->block = (block128_f) HWAES_decrypt; dat->stream.cbc = NULL; # ifdef HWAES_cbc_encrypt if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) HWAES_cbc_encrypt; # endif } else #endif #ifdef BSAES_CAPABLE if (BSAES_CAPABLE && mode == EVP_CIPH_CBC_MODE) { ret = AES_set_decrypt_key(key, keylen, &dat->ks.ks); dat->block = (block128_f) AES_decrypt; dat->stream.cbc = (cbc128_f) ossl_bsaes_cbc_encrypt; } else #endif #ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { ret = vpaes_set_decrypt_key(key, keylen, &dat->ks.ks); dat->block = (block128_f) vpaes_decrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) vpaes_cbc_encrypt : NULL; } else #endif { ret = AES_set_decrypt_key(key, keylen, &dat->ks.ks); dat->block = (block128_f) AES_decrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) AES_cbc_encrypt : NULL; } } else #ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { ret = HWAES_set_encrypt_key(key, keylen, &dat->ks.ks); dat->block = (block128_f) HWAES_encrypt; dat->stream.cbc = NULL; # ifdef HWAES_cbc_encrypt if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) HWAES_cbc_encrypt; else # endif # ifdef HWAES_ctr32_encrypt_blocks if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) HWAES_ctr32_encrypt_blocks; else # endif (void)0; /* terminate potentially open 'else' */ } else #endif #ifdef BSAES_CAPABLE if (BSAES_CAPABLE && mode == EVP_CIPH_CTR_MODE) { ret = AES_set_encrypt_key(key, keylen, &dat->ks.ks); dat->block = (block128_f) AES_encrypt; dat->stream.ctr = (ctr128_f) ossl_bsaes_ctr32_encrypt_blocks; } else #endif #ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { ret = vpaes_set_encrypt_key(key, keylen, &dat->ks.ks); dat->block = (block128_f) vpaes_encrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) vpaes_cbc_encrypt : NULL; } else #endif { ret = AES_set_encrypt_key(key, keylen, &dat->ks.ks); dat->block = (block128_f) AES_encrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) AES_cbc_encrypt : NULL; #ifdef AES_CTR_ASM if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) AES_ctr32_encrypt; #endif } if (ret < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_AES_KEY_SETUP_FAILED); return 0; } return 1; } static int aes_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); if (dat->stream.cbc) (*dat->stream.cbc) (in, out, len, &dat->ks, ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); else if (EVP_CIPHER_CTX_is_encrypting(ctx)) CRYPTO_cbc128_encrypt(in, out, len, &dat->ks, ctx->iv, dat->block); else CRYPTO_cbc128_decrypt(in, out, len, &dat->ks, ctx->iv, dat->block); return 1; } static int aes_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { size_t bl = EVP_CIPHER_CTX_get_block_size(ctx); size_t i; EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); if (len < bl) return 1; for (i = 0, len -= bl; i <= len; i += bl) (*dat->block) (in + i, out + i, &dat->ks); return 1; } static int aes_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_ofb128_encrypt(in, out, len, &dat->ks, ctx->iv, &num, dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } static int aes_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_cfb128_encrypt(in, out, len, &dat->ks, ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } static int aes_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_cfb128_8_encrypt(in, out, len, &dat->ks, ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } static int aes_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS)) { int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_cfb128_1_encrypt(in, out, len, &dat->ks, ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } while (len >= MAXBITCHUNK) { int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_cfb128_1_encrypt(in, out, MAXBITCHUNK * 8, &dat->ks, ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); len -= MAXBITCHUNK; out += MAXBITCHUNK; in += MAXBITCHUNK; } if (len) { int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_cfb128_1_encrypt(in, out, len * 8, &dat->ks, ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); } return 1; } static int aes_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { int n = EVP_CIPHER_CTX_get_num(ctx); unsigned int num; EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); if (n < 0) return 0; num = (unsigned int)n; if (dat->stream.ctr) CRYPTO_ctr128_encrypt_ctr32(in, out, len, &dat->ks, ctx->iv, EVP_CIPHER_CTX_buf_noconst(ctx), &num, dat->stream.ctr); else CRYPTO_ctr128_encrypt(in, out, len, &dat->ks, ctx->iv, EVP_CIPHER_CTX_buf_noconst(ctx), &num, dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } BLOCK_CIPHER_generic_pack(NID_aes, 128, 0) BLOCK_CIPHER_generic_pack(NID_aes, 192, 0) BLOCK_CIPHER_generic_pack(NID_aes, 256, 0) static int aes_gcm_cleanup(EVP_CIPHER_CTX *c) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c); if (gctx == NULL) return 0; OPENSSL_cleanse(&gctx->gcm, sizeof(gctx->gcm)); if (gctx->iv != c->iv) OPENSSL_free(gctx->iv); return 1; } static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c); switch (type) { case EVP_CTRL_INIT: gctx->key_set = 0; gctx->iv_set = 0; gctx->ivlen = EVP_CIPHER_get_iv_length(c->cipher); gctx->iv = c->iv; gctx->taglen = -1; gctx->iv_gen = 0; gctx->tls_aad_len = -1; return 1; case EVP_CTRL_GET_IVLEN: *(int *)ptr = gctx->ivlen; return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0) return 0; /* Allocate memory for IV if needed */ if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) { if (gctx->iv != c->iv) OPENSSL_free(gctx->iv); if ((gctx->iv = OPENSSL_malloc(arg)) == NULL) return 0; } gctx->ivlen = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > 16 || c->encrypt) return 0; memcpy(c->buf, ptr, arg); gctx->taglen = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > 16 || !c->encrypt || gctx->taglen < 0) return 0; memcpy(ptr, c->buf, arg); return 1; case EVP_CTRL_GCM_SET_IV_FIXED: /* Special case: -1 length restores whole IV */ if (arg == -1) { memcpy(gctx->iv, ptr, gctx->ivlen); gctx->iv_gen = 1; return 1; } /* * Fixed field must be at least 4 bytes and invocation field at least * 8. */ if ((arg < 4) || (gctx->ivlen - arg) < 8) return 0; if (arg) memcpy(gctx->iv, ptr, arg); if (c->encrypt && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0) return 0; gctx->iv_gen = 1; return 1; case EVP_CTRL_GCM_IV_GEN: if (gctx->iv_gen == 0 || gctx->key_set == 0) return 0; CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); if (arg <= 0 || arg > gctx->ivlen) arg = gctx->ivlen; memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg); /* * Invocation field will be at least 8 bytes in size and so no need * to check wrap around or increment more than last 8 bytes. */ ctr64_inc(gctx->iv + gctx->ivlen - 8); gctx->iv_set = 1; return 1; case EVP_CTRL_GCM_SET_IV_INV: if (gctx->iv_gen == 0 || gctx->key_set == 0 || c->encrypt) return 0; memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); gctx->iv_set = 1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(c->buf, ptr, arg); gctx->tls_aad_len = arg; gctx->tls_enc_records = 0; { unsigned int len = c->buf[arg - 2] << 8 | c->buf[arg - 1]; /* Correct length for explicit IV */ if (len < EVP_GCM_TLS_EXPLICIT_IV_LEN) return 0; len -= EVP_GCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!c->encrypt) { if (len < EVP_GCM_TLS_TAG_LEN) return 0; len -= EVP_GCM_TLS_TAG_LEN; } c->buf[arg - 2] = len >> 8; c->buf[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return EVP_GCM_TLS_TAG_LEN; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_GCM_CTX *gctx_out = EVP_C_DATA(EVP_AES_GCM_CTX,out); if (gctx->gcm.key) { if (gctx->gcm.key != &gctx->ks) return 0; gctx_out->gcm.key = &gctx_out->ks; } if (gctx->iv == c->iv) gctx_out->iv = out->iv; else { if ((gctx_out->iv = OPENSSL_malloc(gctx->ivlen)) == NULL) return 0; memcpy(gctx_out->iv, gctx->iv, gctx->ivlen); } return 1; } default: return -1; } } static int aes_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,ctx); if (iv == NULL && key == NULL) return 1; if (key != NULL) { const int keylen = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } do { #ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { HWAES_set_encrypt_key(key, keylen, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) HWAES_encrypt); # ifdef HWAES_ctr32_encrypt_blocks gctx->ctr = (ctr128_f) HWAES_ctr32_encrypt_blocks; # else gctx->ctr = NULL; # endif break; } else #endif #ifdef BSAES_CAPABLE if (BSAES_CAPABLE) { AES_set_encrypt_key(key, keylen, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) AES_encrypt); gctx->ctr = (ctr128_f) ossl_bsaes_ctr32_encrypt_blocks; break; } else #endif #ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { vpaes_set_encrypt_key(key, keylen, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) vpaes_encrypt); gctx->ctr = NULL; break; } else #endif (void)0; /* terminate potentially open 'else' */ AES_set_encrypt_key(key, keylen, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) AES_encrypt); #ifdef AES_CTR_ASM gctx->ctr = (ctr128_f) AES_ctr32_encrypt; #else gctx->ctr = NULL; #endif } while (0); /* * If we have an iv can set it directly, otherwise use saved IV. */ if (iv == NULL && gctx->iv_set) iv = gctx->iv; if (iv) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); gctx->iv_set = 1; } gctx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (gctx->key_set) CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); else memcpy(gctx->iv, iv, gctx->ivlen); gctx->iv_set = 1; gctx->iv_gen = 0; } return 1; } /* * Handle TLS GCM packet format. This consists of the last portion of the IV * followed by the payload and finally the tag. On encrypt generate IV, * encrypt payload and write the tag. On verify retrieve IV, decrypt payload * and verify tag. */ static int aes_gcm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,ctx); int rv = -1; /* Encrypt/decrypt must be performed in place */ if (out != in || len < (EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN)) return -1; /* * Check for too many keys as per FIPS 140-2 IG A.5 "Key/IV Pair Uniqueness * Requirements from SP 800-38D". The requirements is for one party to the * communication to fail after 2^64 - 1 keys. We do this on the encrypting * side only. */ if (EVP_CIPHER_CTX_is_encrypting(ctx) && ++gctx->tls_enc_records == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_TOO_MANY_RECORDS); goto err; } /* * Set IV from start of buffer or generate IV and write to start of * buffer. */ if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CIPHER_CTX_is_encrypting(ctx) ? EVP_CTRL_GCM_IV_GEN : EVP_CTRL_GCM_SET_IV_INV, EVP_GCM_TLS_EXPLICIT_IV_LEN, out) <= 0) goto err; /* Use saved AAD */ if (CRYPTO_gcm128_aad(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), gctx->tls_aad_len)) goto err; /* Fix buffer and length to point to payload */ in += EVP_GCM_TLS_EXPLICIT_IV_LEN; out += EVP_GCM_TLS_EXPLICIT_IV_LEN; len -= EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { /* Encrypt payload */ if (gctx->ctr) { size_t bulk = 0; #if defined(AES_GCM_ASM) if (len >= 32 && AES_GCM_ASM(gctx)) { if (CRYPTO_gcm128_encrypt(&gctx->gcm, NULL, NULL, 0)) return -1; bulk = AES_gcm_encrypt(in, out, len, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; } #endif if (CRYPTO_gcm128_encrypt_ctr32(&gctx->gcm, in + bulk, out + bulk, len - bulk, gctx->ctr)) goto err; } else { size_t bulk = 0; #if defined(AES_GCM_ASM2) if (len >= 32 && AES_GCM_ASM2(gctx)) { if (CRYPTO_gcm128_encrypt(&gctx->gcm, NULL, NULL, 0)) return -1; bulk = AES_gcm_encrypt(in, out, len, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; } #endif if (CRYPTO_gcm128_encrypt(&gctx->gcm, in + bulk, out + bulk, len - bulk)) goto err; } out += len; /* Finally write tag */ CRYPTO_gcm128_tag(&gctx->gcm, out, EVP_GCM_TLS_TAG_LEN); rv = len + EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN; } else { /* Decrypt */ if (gctx->ctr) { size_t bulk = 0; #if defined(AES_GCM_ASM) if (len >= 16 && AES_GCM_ASM(gctx)) { if (CRYPTO_gcm128_decrypt(&gctx->gcm, NULL, NULL, 0)) return -1; bulk = AES_gcm_decrypt(in, out, len, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; } #endif if (CRYPTO_gcm128_decrypt_ctr32(&gctx->gcm, in + bulk, out + bulk, len - bulk, gctx->ctr)) goto err; } else { size_t bulk = 0; #if defined(AES_GCM_ASM2) if (len >= 16 && AES_GCM_ASM2(gctx)) { if (CRYPTO_gcm128_decrypt(&gctx->gcm, NULL, NULL, 0)) return -1; bulk = AES_gcm_decrypt(in, out, len, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; } #endif if (CRYPTO_gcm128_decrypt(&gctx->gcm, in + bulk, out + bulk, len - bulk)) goto err; } /* Retrieve tag */ CRYPTO_gcm128_tag(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), EVP_GCM_TLS_TAG_LEN); /* If tag mismatch wipe buffer */ if (CRYPTO_memcmp(EVP_CIPHER_CTX_buf_noconst(ctx), in + len, EVP_GCM_TLS_TAG_LEN)) { OPENSSL_cleanse(out, len); goto err; } rv = len; } err: gctx->iv_set = 0; gctx->tls_aad_len = -1; return rv; } #ifdef FIPS_MODULE /* * See SP800-38D (GCM) Section 8 "Uniqueness requirement on IVS and keys" * * See also 8.2.2 RBG-based construction. * Random construction consists of a free field (which can be NULL) and a * random field which will use a DRBG that can return at least 96 bits of * entropy strength. (The DRBG must be seeded by the FIPS module). */ static int aes_gcm_iv_generate(EVP_AES_GCM_CTX *gctx, int offset) { int sz = gctx->ivlen - offset; /* Must be at least 96 bits */ if (sz <= 0 || gctx->ivlen < 12) return 0; /* Use DRBG to generate random iv */ if (RAND_bytes(gctx->iv + offset, sz) <= 0) return 0; return 1; } #endif /* FIPS_MODULE */ static int aes_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,ctx); /* If not set up, return error */ if (!gctx->key_set) return -1; if (gctx->tls_aad_len >= 0) return aes_gcm_tls_cipher(ctx, out, in, len); #ifdef FIPS_MODULE /* * FIPS requires generation of AES-GCM IV's inside the FIPS module. * The IV can still be set externally (the security policy will state that * this is not FIPS compliant). There are some applications * where setting the IV externally is the only option available. */ if (!gctx->iv_set) { if (!EVP_CIPHER_CTX_is_encrypting(ctx) || !aes_gcm_iv_generate(gctx, 0)) return -1; CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); gctx->iv_set = 1; gctx->iv_gen_rand = 1; } #else if (!gctx->iv_set) return -1; #endif /* FIPS_MODULE */ if (in) { if (out == NULL) { if (CRYPTO_gcm128_aad(&gctx->gcm, in, len)) return -1; } else if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (gctx->ctr) { size_t bulk = 0; #if defined(AES_GCM_ASM) if (len >= 32 && AES_GCM_ASM(gctx)) { size_t res = (16 - gctx->gcm.mres) % 16; if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, res)) return -1; bulk = AES_gcm_encrypt(in + res, out + res, len - res, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; bulk += res; } #endif if (CRYPTO_gcm128_encrypt_ctr32(&gctx->gcm, in + bulk, out + bulk, len - bulk, gctx->ctr)) return -1; } else { size_t bulk = 0; #if defined(AES_GCM_ASM2) if (len >= 32 && AES_GCM_ASM2(gctx)) { size_t res = (16 - gctx->gcm.mres) % 16; if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, res)) return -1; bulk = AES_gcm_encrypt(in + res, out + res, len - res, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; bulk += res; } #endif if (CRYPTO_gcm128_encrypt(&gctx->gcm, in + bulk, out + bulk, len - bulk)) return -1; } } else { if (gctx->ctr) { size_t bulk = 0; #if defined(AES_GCM_ASM) if (len >= 16 && AES_GCM_ASM(gctx)) { size_t res = (16 - gctx->gcm.mres) % 16; if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, res)) return -1; bulk = AES_gcm_decrypt(in + res, out + res, len - res, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; bulk += res; } #endif if (CRYPTO_gcm128_decrypt_ctr32(&gctx->gcm, in + bulk, out + bulk, len - bulk, gctx->ctr)) return -1; } else { size_t bulk = 0; #if defined(AES_GCM_ASM2) if (len >= 16 && AES_GCM_ASM2(gctx)) { size_t res = (16 - gctx->gcm.mres) % 16; if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, res)) return -1; bulk = AES_gcm_decrypt(in + res, out + res, len - res, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; bulk += res; } #endif if (CRYPTO_gcm128_decrypt(&gctx->gcm, in + bulk, out + bulk, len - bulk)) return -1; } } return len; } else { if (!EVP_CIPHER_CTX_is_encrypting(ctx)) { if (gctx->taglen < 0) return -1; if (CRYPTO_gcm128_finish(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), gctx->taglen) != 0) return -1; gctx->iv_set = 0; return 0; } CRYPTO_gcm128_tag(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), 16); gctx->taglen = 16; /* Don't reuse the IV */ gctx->iv_set = 0; return 0; } } #define CUSTOM_FLAGS (EVP_CIPH_FLAG_DEFAULT_ASN1 \ | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \ | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \ | EVP_CIPH_CUSTOM_COPY | EVP_CIPH_CUSTOM_IV_LENGTH) BLOCK_CIPHER_custom(NID_aes, 128, 1, 12, gcm, GCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 192, 1, 12, gcm, GCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 256, 1, 12, gcm, GCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) static int aes_xts_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_XTS_CTX *xctx = EVP_C_DATA(EVP_AES_XTS_CTX, c); if (type == EVP_CTRL_COPY) { EVP_CIPHER_CTX *out = ptr; EVP_AES_XTS_CTX *xctx_out = EVP_C_DATA(EVP_AES_XTS_CTX,out); if (xctx->xts.key1) { if (xctx->xts.key1 != &xctx->ks1) return 0; xctx_out->xts.key1 = &xctx_out->ks1; } if (xctx->xts.key2) { if (xctx->xts.key2 != &xctx->ks2) return 0; xctx_out->xts.key2 = &xctx_out->ks2; } return 1; } else if (type != EVP_CTRL_INIT) return -1; /* key1 and key2 are used as an indicator both key and IV are set */ xctx->xts.key1 = NULL; xctx->xts.key2 = NULL; return 1; } static int aes_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_XTS_CTX *xctx = EVP_C_DATA(EVP_AES_XTS_CTX,ctx); if (iv == NULL && key == NULL) return 1; if (key != NULL) { do { /* The key is two half length keys in reality */ const int keylen = EVP_CIPHER_CTX_get_key_length(ctx); const int bytes = keylen / 2; const int bits = bytes * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } /* * Verify that the two keys are different. * * This addresses the vulnerability described in Rogaway's * September 2004 paper: * * "Efficient Instantiations of Tweakable Blockciphers and * Refinements to Modes OCB and PMAC". * (http://web.cs.ucdavis.edu/~rogaway/papers/offsets.pdf) * * FIPS 140-2 IG A.9 XTS-AES Key Generation Requirements states * that: * "The check for Key_1 != Key_2 shall be done at any place * BEFORE using the keys in the XTS-AES algorithm to process * data with them." */ if ((!allow_insecure_decrypt || enc) && CRYPTO_memcmp(key, key + bytes, bytes) == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_XTS_DUPLICATED_KEYS); return 0; } #ifdef AES_XTS_ASM xctx->stream = enc ? AES_xts_encrypt : AES_xts_decrypt; #else xctx->stream = NULL; #endif /* key_len is two AES keys */ #ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { if (enc) { HWAES_set_encrypt_key(key, bits, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) HWAES_encrypt; # ifdef HWAES_xts_encrypt xctx->stream = HWAES_xts_encrypt; # endif } else { HWAES_set_decrypt_key(key, bits, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) HWAES_decrypt; # ifdef HWAES_xts_decrypt xctx->stream = HWAES_xts_decrypt; #endif } HWAES_set_encrypt_key(key + bytes, bits, &xctx->ks2.ks); xctx->xts.block2 = (block128_f) HWAES_encrypt; xctx->xts.key1 = &xctx->ks1; break; } else #endif #ifdef BSAES_CAPABLE if (BSAES_CAPABLE) xctx->stream = enc ? ossl_bsaes_xts_encrypt : ossl_bsaes_xts_decrypt; else #endif #ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { if (enc) { vpaes_set_encrypt_key(key, bits, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) vpaes_encrypt; } else { vpaes_set_decrypt_key(key, bits, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) vpaes_decrypt; } vpaes_set_encrypt_key(key + bytes, bits, &xctx->ks2.ks); xctx->xts.block2 = (block128_f) vpaes_encrypt; xctx->xts.key1 = &xctx->ks1; break; } else #endif (void)0; /* terminate potentially open 'else' */ if (enc) { AES_set_encrypt_key(key, bits, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) AES_encrypt; } else { AES_set_decrypt_key(key, bits, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) AES_decrypt; } AES_set_encrypt_key(key + bytes, bits, &xctx->ks2.ks); xctx->xts.block2 = (block128_f) AES_encrypt; xctx->xts.key1 = &xctx->ks1; } while (0); } if (iv) { xctx->xts.key2 = &xctx->ks2; memcpy(ctx->iv, iv, 16); } return 1; } static int aes_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_XTS_CTX *xctx = EVP_C_DATA(EVP_AES_XTS_CTX,ctx); if (xctx->xts.key1 == NULL || xctx->xts.key2 == NULL || out == NULL || in == NULL || len < AES_BLOCK_SIZE) return 0; /* * Impose a limit of 2^20 blocks per data unit as specified by * IEEE Std 1619-2018. The earlier and obsolete IEEE Std 1619-2007 * indicated that this was a SHOULD NOT rather than a MUST NOT. * NIST SP 800-38E mandates the same limit. */ if (len > XTS_MAX_BLOCKS_PER_DATA_UNIT * AES_BLOCK_SIZE) { ERR_raise(ERR_LIB_EVP, EVP_R_XTS_DATA_UNIT_IS_TOO_LARGE); return 0; } if (xctx->stream) (*xctx->stream) (in, out, len, xctx->xts.key1, xctx->xts.key2, ctx->iv); else if (CRYPTO_xts128_encrypt(&xctx->xts, ctx->iv, in, out, len, EVP_CIPHER_CTX_is_encrypting(ctx))) return 0; return 1; } #define aes_xts_cleanup NULL #define XTS_FLAGS (EVP_CIPH_FLAG_DEFAULT_ASN1 | EVP_CIPH_CUSTOM_IV \ | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \ | EVP_CIPH_CUSTOM_COPY) BLOCK_CIPHER_custom(NID_aes, 128, 1, 16, xts, XTS, XTS_FLAGS) BLOCK_CIPHER_custom(NID_aes, 256, 1, 16, xts, XTS, XTS_FLAGS) static int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c); switch (type) { case EVP_CTRL_INIT: cctx->key_set = 0; cctx->iv_set = 0; cctx->L = 8; cctx->M = 12; cctx->tag_set = 0; cctx->len_set = 0; cctx->tls_aad_len = -1; return 1; case EVP_CTRL_GET_IVLEN: *(int *)ptr = 15 - cctx->L; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); cctx->tls_aad_len = arg; { uint16_t len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ if (len < EVP_CCM_TLS_EXPLICIT_IV_LEN) return 0; len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_is_encrypting(c)) { if (len < cctx->M) return 0; len -= cctx->M; } EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return cctx->M; case EVP_CTRL_CCM_SET_IV_FIXED: /* Sanity check length */ if (arg != EVP_CCM_TLS_FIXED_IV_LEN) return 0; /* Just copy to first part of IV */ memcpy(c->iv, ptr, arg); return 1; case EVP_CTRL_AEAD_SET_IVLEN: arg = 15 - arg; /* fall through */ case EVP_CTRL_CCM_SET_L: if (arg < 2 || arg > 8) return 0; cctx->L = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if ((arg & 1) || arg < 4 || arg > 16) return 0; if (EVP_CIPHER_CTX_is_encrypting(c) && ptr) return 0; if (ptr) { cctx->tag_set = 1; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); } cctx->M = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (!EVP_CIPHER_CTX_is_encrypting(c) || !cctx->tag_set) return 0; if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg)) return 0; cctx->tag_set = 0; cctx->iv_set = 0; cctx->len_set = 0; return 1; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out); if (cctx->ccm.key) { if (cctx->ccm.key != &cctx->ks) return 0; cctx_out->ccm.key = &cctx_out->ks; } return 1; } default: return -1; } } static int aes_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,ctx); if (iv == NULL && key == NULL) return 1; if (key != NULL) { const int keylen = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } do { #ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { HWAES_set_encrypt_key(key, keylen, &cctx->ks.ks); CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, &cctx->ks, (block128_f) HWAES_encrypt); cctx->str = NULL; cctx->key_set = 1; break; } else #endif #ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { vpaes_set_encrypt_key(key, keylen, &cctx->ks.ks); CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, &cctx->ks, (block128_f) vpaes_encrypt); cctx->str = NULL; cctx->key_set = 1; break; } #endif AES_set_encrypt_key(key, keylen, &cctx->ks.ks); CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, &cctx->ks, (block128_f) AES_encrypt); cctx->str = NULL; cctx->key_set = 1; } while (0); } if (iv != NULL) { memcpy(ctx->iv, iv, 15 - cctx->L); cctx->iv_set = 1; } return 1; } static int aes_ccm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,ctx); CCM128_CONTEXT *ccm = &cctx->ccm; /* Encrypt/decrypt must be performed in place */ if (out != in || len < (EVP_CCM_TLS_EXPLICIT_IV_LEN + (size_t)cctx->M)) return -1; /* If encrypting set explicit IV from sequence number (start of AAD) */ if (EVP_CIPHER_CTX_is_encrypting(ctx)) memcpy(out, EVP_CIPHER_CTX_buf_noconst(ctx), EVP_CCM_TLS_EXPLICIT_IV_LEN); /* Get rest of IV from explicit IV */ memcpy(ctx->iv + EVP_CCM_TLS_FIXED_IV_LEN, in, EVP_CCM_TLS_EXPLICIT_IV_LEN); /* Correct length value */ len -= EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->M; if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len)) return -1; /* Use saved AAD */ CRYPTO_ccm128_aad(ccm, EVP_CIPHER_CTX_buf_noconst(ctx), cctx->tls_aad_len); /* Fix buffer to point to payload */ in += EVP_CCM_TLS_EXPLICIT_IV_LEN; out += EVP_CCM_TLS_EXPLICIT_IV_LEN; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (cctx->str ? CRYPTO_ccm128_encrypt_ccm64(ccm, in, out, len, cctx->str) : CRYPTO_ccm128_encrypt(ccm, in, out, len)) return -1; if (!CRYPTO_ccm128_tag(ccm, out + len, cctx->M)) return -1; return len + EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->M; } else { if (cctx->str ? !CRYPTO_ccm128_decrypt_ccm64(ccm, in, out, len, cctx->str) : !CRYPTO_ccm128_decrypt(ccm, in, out, len)) { unsigned char tag[16]; if (CRYPTO_ccm128_tag(ccm, tag, cctx->M)) { if (!CRYPTO_memcmp(tag, in + len, cctx->M)) return len; } } OPENSSL_cleanse(out, len); return -1; } } static int aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,ctx); CCM128_CONTEXT *ccm = &cctx->ccm; /* If not set up, return error */ if (!cctx->key_set) return -1; if (cctx->tls_aad_len >= 0) return aes_ccm_tls_cipher(ctx, out, in, len); /* EVP_*Final() doesn't return any data */ if (in == NULL && out != NULL) return 0; if (!cctx->iv_set) return -1; if (!out) { if (!in) { if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len)) return -1; cctx->len_set = 1; return len; } /* If have AAD need message length */ if (!cctx->len_set && len) return -1; CRYPTO_ccm128_aad(ccm, in, len); return len; } /* The tag must be set before actually decrypting data */ if (!EVP_CIPHER_CTX_is_encrypting(ctx) && !cctx->tag_set) return -1; /* If not set length yet do it */ if (!cctx->len_set) { if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len)) return -1; cctx->len_set = 1; } if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (cctx->str ? CRYPTO_ccm128_encrypt_ccm64(ccm, in, out, len, cctx->str) : CRYPTO_ccm128_encrypt(ccm, in, out, len)) return -1; cctx->tag_set = 1; return len; } else { int rv = -1; if (cctx->str ? !CRYPTO_ccm128_decrypt_ccm64(ccm, in, out, len, cctx->str) : !CRYPTO_ccm128_decrypt(ccm, in, out, len)) { unsigned char tag[16]; if (CRYPTO_ccm128_tag(ccm, tag, cctx->M)) { if (!CRYPTO_memcmp(tag, EVP_CIPHER_CTX_buf_noconst(ctx), cctx->M)) rv = len; } } if (rv == -1) OPENSSL_cleanse(out, len); cctx->iv_set = 0; cctx->tag_set = 0; cctx->len_set = 0; return rv; } } #define aes_ccm_cleanup NULL BLOCK_CIPHER_custom(NID_aes, 128, 1, 12, ccm, CCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 192, 1, 12, ccm, CCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 256, 1, 12, ccm, CCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) typedef struct { union { OSSL_UNION_ALIGN; AES_KEY ks; } ks; /* Indicates if IV has been set */ unsigned char *iv; } EVP_AES_WRAP_CTX; static int aes_wrap_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int len; EVP_AES_WRAP_CTX *wctx = EVP_C_DATA(EVP_AES_WRAP_CTX,ctx); if (iv == NULL && key == NULL) return 1; if (key != NULL) { const int keylen = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } if (EVP_CIPHER_CTX_is_encrypting(ctx)) AES_set_encrypt_key(key, keylen, &wctx->ks.ks); else AES_set_decrypt_key(key, keylen, &wctx->ks.ks); if (iv == NULL) wctx->iv = NULL; } if (iv != NULL) { if ((len = EVP_CIPHER_CTX_get_iv_length(ctx)) < 0) return 0; memcpy(ctx->iv, iv, len); wctx->iv = ctx->iv; } return 1; } static int aes_wrap_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inlen) { EVP_AES_WRAP_CTX *wctx = EVP_C_DATA(EVP_AES_WRAP_CTX,ctx); size_t rv; /* AES wrap with padding has IV length of 4, without padding 8 */ int pad = EVP_CIPHER_CTX_get_iv_length(ctx) == 4; /* No final operation so always return zero length */ if (!in) return 0; /* Input length must always be non-zero */ if (!inlen) return -1; /* If decrypting need at least 16 bytes and multiple of 8 */ if (!EVP_CIPHER_CTX_is_encrypting(ctx) && (inlen < 16 || inlen & 0x7)) return -1; /* If not padding input must be multiple of 8 */ if (!pad && inlen & 0x7) return -1; if (ossl_is_partially_overlapping(out, in, inlen)) { ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING); return 0; } if (!out) { if (EVP_CIPHER_CTX_is_encrypting(ctx)) { /* If padding round up to multiple of 8 */ if (pad) inlen = (inlen + 7) / 8 * 8; /* 8 byte prefix */ return inlen + 8; } else { /* * If not padding output will be exactly 8 bytes smaller than * input. If padding it will be at least 8 bytes smaller but we * don't know how much. */ return inlen - 8; } } if (pad) { if (EVP_CIPHER_CTX_is_encrypting(ctx)) rv = CRYPTO_128_wrap_pad(&wctx->ks.ks, wctx->iv, out, in, inlen, (block128_f) AES_encrypt); else rv = CRYPTO_128_unwrap_pad(&wctx->ks.ks, wctx->iv, out, in, inlen, (block128_f) AES_decrypt); } else { if (EVP_CIPHER_CTX_is_encrypting(ctx)) rv = CRYPTO_128_wrap(&wctx->ks.ks, wctx->iv, out, in, inlen, (block128_f) AES_encrypt); else rv = CRYPTO_128_unwrap(&wctx->ks.ks, wctx->iv, out, in, inlen, (block128_f) AES_decrypt); } return rv ? (int)rv : -1; } #define WRAP_FLAGS (EVP_CIPH_WRAP_MODE \ | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \ | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_FLAG_DEFAULT_ASN1) static const EVP_CIPHER aes_128_wrap = { NID_id_aes128_wrap, 8, 16, 8, WRAP_FLAGS, EVP_ORIG_GLOBAL, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_128_wrap(void) { return &aes_128_wrap; } static const EVP_CIPHER aes_192_wrap = { NID_id_aes192_wrap, 8, 24, 8, WRAP_FLAGS, EVP_ORIG_GLOBAL, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_192_wrap(void) { return &aes_192_wrap; } static const EVP_CIPHER aes_256_wrap = { NID_id_aes256_wrap, 8, 32, 8, WRAP_FLAGS, EVP_ORIG_GLOBAL, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_256_wrap(void) { return &aes_256_wrap; } static const EVP_CIPHER aes_128_wrap_pad = { NID_id_aes128_wrap_pad, 8, 16, 4, WRAP_FLAGS, EVP_ORIG_GLOBAL, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_128_wrap_pad(void) { return &aes_128_wrap_pad; } static const EVP_CIPHER aes_192_wrap_pad = { NID_id_aes192_wrap_pad, 8, 24, 4, WRAP_FLAGS, EVP_ORIG_GLOBAL, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_192_wrap_pad(void) { return &aes_192_wrap_pad; } static const EVP_CIPHER aes_256_wrap_pad = { NID_id_aes256_wrap_pad, 8, 32, 4, WRAP_FLAGS, EVP_ORIG_GLOBAL, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_256_wrap_pad(void) { return &aes_256_wrap_pad; } #ifndef OPENSSL_NO_OCB static int aes_ocb_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,c); EVP_CIPHER_CTX *newc; EVP_AES_OCB_CTX *new_octx; switch (type) { case EVP_CTRL_INIT: octx->key_set = 0; octx->iv_set = 0; octx->ivlen = EVP_CIPHER_get_iv_length(c->cipher); octx->iv = c->iv; octx->taglen = 16; octx->data_buf_len = 0; octx->aad_buf_len = 0; return 1; case EVP_CTRL_GET_IVLEN: *(int *)ptr = octx->ivlen; return 1; case EVP_CTRL_AEAD_SET_IVLEN: /* IV len must be 1 to 15 */ if (arg <= 0 || arg > 15) return 0; octx->ivlen = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if (ptr == NULL) { /* Tag len must be 0 to 16 */ if (arg < 0 || arg > 16) return 0; octx->taglen = arg; return 1; } if (arg != octx->taglen || EVP_CIPHER_CTX_is_encrypting(c)) return 0; memcpy(octx->tag, ptr, arg); return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg != octx->taglen || !EVP_CIPHER_CTX_is_encrypting(c)) return 0; memcpy(ptr, octx->tag, arg); return 1; case EVP_CTRL_COPY: newc = (EVP_CIPHER_CTX *)ptr; new_octx = EVP_C_DATA(EVP_AES_OCB_CTX,newc); return CRYPTO_ocb128_copy_ctx(&new_octx->ocb, &octx->ocb, &new_octx->ksenc.ks, &new_octx->ksdec.ks); default: return -1; } } static int aes_ocb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,ctx); if (iv == NULL && key == NULL) return 1; if (key != NULL) { const int keylen = EVP_CIPHER_CTX_get_key_length(ctx) * 8; if (keylen <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } do { /* * We set both the encrypt and decrypt key here because decrypt * needs both. We could possibly optimise to remove setting the * decrypt for an encryption operation. */ # ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { HWAES_set_encrypt_key(key, keylen, &octx->ksenc.ks); HWAES_set_decrypt_key(key, keylen, &octx->ksdec.ks); if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc.ks, &octx->ksdec.ks, (block128_f) HWAES_encrypt, (block128_f) HWAES_decrypt, enc ? HWAES_ocb_encrypt : HWAES_ocb_decrypt)) return 0; break; } # endif # ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { vpaes_set_encrypt_key(key, keylen, &octx->ksenc.ks); vpaes_set_decrypt_key(key, keylen, &octx->ksdec.ks); if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc.ks, &octx->ksdec.ks, (block128_f) vpaes_encrypt, (block128_f) vpaes_decrypt, NULL)) return 0; break; } # endif AES_set_encrypt_key(key, keylen, &octx->ksenc.ks); AES_set_decrypt_key(key, keylen, &octx->ksdec.ks); if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc.ks, &octx->ksdec.ks, (block128_f) AES_encrypt, (block128_f) AES_decrypt, NULL)) return 0; } while (0); /* * If we have an iv we can set it directly, otherwise use saved IV. */ if (iv == NULL && octx->iv_set) iv = octx->iv; if (iv) { if (CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen) != 1) return 0; octx->iv_set = 1; } octx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (octx->key_set) CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen); else memcpy(octx->iv, iv, octx->ivlen); octx->iv_set = 1; } return 1; } static int aes_ocb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { unsigned char *buf; int *buf_len; int written_len = 0; size_t trailing_len; EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,ctx); /* If IV or Key not set then return error */ if (!octx->iv_set) return -1; if (!octx->key_set) return -1; if (in != NULL) { /* * Need to ensure we are only passing full blocks to low-level OCB * routines. We do it here rather than in EVP_EncryptUpdate/ * EVP_DecryptUpdate because we need to pass full blocks of AAD too * and those routines don't support that */ /* Are we dealing with AAD or normal data here? */ if (out == NULL) { buf = octx->aad_buf; buf_len = &(octx->aad_buf_len); } else { buf = octx->data_buf; buf_len = &(octx->data_buf_len); if (ossl_is_partially_overlapping(out + *buf_len, in, len)) { ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING); return 0; } } /* * If we've got a partially filled buffer from a previous call then * use that data first */ if (*buf_len > 0) { unsigned int remaining; remaining = AES_BLOCK_SIZE - (*buf_len); if (remaining > len) { memcpy(buf + (*buf_len), in, len); *(buf_len) += len; return 0; } memcpy(buf + (*buf_len), in, remaining); /* * If we get here we've filled the buffer, so process it */ len -= remaining; in += remaining; if (out == NULL) { if (!CRYPTO_ocb128_aad(&octx->ocb, buf, AES_BLOCK_SIZE)) return -1; } else if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (!CRYPTO_ocb128_encrypt(&octx->ocb, buf, out, AES_BLOCK_SIZE)) return -1; } else { if (!CRYPTO_ocb128_decrypt(&octx->ocb, buf, out, AES_BLOCK_SIZE)) return -1; } written_len = AES_BLOCK_SIZE; *buf_len = 0; if (out != NULL) out += AES_BLOCK_SIZE; } /* Do we have a partial block to handle at the end? */ trailing_len = len % AES_BLOCK_SIZE; /* * If we've got some full blocks to handle, then process these first */ if (len != trailing_len) { if (out == NULL) { if (!CRYPTO_ocb128_aad(&octx->ocb, in, len - trailing_len)) return -1; } else if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (!CRYPTO_ocb128_encrypt (&octx->ocb, in, out, len - trailing_len)) return -1; } else { if (!CRYPTO_ocb128_decrypt (&octx->ocb, in, out, len - trailing_len)) return -1; } written_len += len - trailing_len; in += len - trailing_len; } /* Handle any trailing partial block */ if (trailing_len > 0) { memcpy(buf, in, trailing_len); *buf_len = trailing_len; } return written_len; } else { /* * First of all empty the buffer of any partial block that we might * have been provided - both for data and AAD */ if (octx->data_buf_len > 0) { if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (!CRYPTO_ocb128_encrypt(&octx->ocb, octx->data_buf, out, octx->data_buf_len)) return -1; } else { if (!CRYPTO_ocb128_decrypt(&octx->ocb, octx->data_buf, out, octx->data_buf_len)) return -1; } written_len = octx->data_buf_len; octx->data_buf_len = 0; } if (octx->aad_buf_len > 0) { if (!CRYPTO_ocb128_aad (&octx->ocb, octx->aad_buf, octx->aad_buf_len)) return -1; octx->aad_buf_len = 0; } /* If decrypting then verify */ if (!EVP_CIPHER_CTX_is_encrypting(ctx)) { if (octx->taglen < 0) return -1; if (CRYPTO_ocb128_finish(&octx->ocb, octx->tag, octx->taglen) != 0) return -1; octx->iv_set = 0; return written_len; } /* If encrypting then just get the tag */ if (CRYPTO_ocb128_tag(&octx->ocb, octx->tag, 16) != 1) return -1; /* Don't reuse the IV */ octx->iv_set = 0; return written_len; } } static int aes_ocb_cleanup(EVP_CIPHER_CTX *c) { EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,c); CRYPTO_ocb128_cleanup(&octx->ocb); return 1; } BLOCK_CIPHER_custom(NID_aes, 128, 16, 12, ocb, OCB, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 192, 16, 12, ocb, OCB, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 256, 16, 12, ocb, OCB, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) #endif /* OPENSSL_NO_OCB */
./openssl/crypto/evp/mac_lib.c
/* * Copyright 2018-2021 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 <string.h> #include <stdarg.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/core.h> #include <openssl/core_names.h> #include <openssl/types.h> #include "internal/nelem.h" #include "crypto/evp.h" #include "internal/provider.h" #include "evp_local.h" EVP_MAC_CTX *EVP_MAC_CTX_new(EVP_MAC *mac) { EVP_MAC_CTX *ctx = OPENSSL_zalloc(sizeof(EVP_MAC_CTX)); if (ctx != NULL) { ctx->meth = mac; if ((ctx->algctx = mac->newctx(ossl_provider_ctx(mac->prov))) == NULL || !EVP_MAC_up_ref(mac)) { mac->freectx(ctx->algctx); ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); OPENSSL_free(ctx); ctx = NULL; } } return ctx; } void EVP_MAC_CTX_free(EVP_MAC_CTX *ctx) { if (ctx == NULL) return; ctx->meth->freectx(ctx->algctx); ctx->algctx = NULL; /* refcnt-- */ EVP_MAC_free(ctx->meth); OPENSSL_free(ctx); } EVP_MAC_CTX *EVP_MAC_CTX_dup(const EVP_MAC_CTX *src) { EVP_MAC_CTX *dst; if (src->algctx == NULL) return NULL; dst = OPENSSL_malloc(sizeof(*dst)); if (dst == NULL) return NULL; *dst = *src; if (!EVP_MAC_up_ref(dst->meth)) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); OPENSSL_free(dst); return NULL; } dst->algctx = src->meth->dupctx(src->algctx); if (dst->algctx == NULL) { EVP_MAC_CTX_free(dst); return NULL; } return dst; } EVP_MAC *EVP_MAC_CTX_get0_mac(EVP_MAC_CTX *ctx) { return ctx->meth; } static size_t get_size_t_ctx_param(EVP_MAC_CTX *ctx, const char *name) { size_t sz = 0; if (ctx->algctx != NULL) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_size_t(name, &sz); if (ctx->meth->get_ctx_params != NULL) { if (ctx->meth->get_ctx_params(ctx->algctx, params)) return sz; } else if (ctx->meth->get_params != NULL) { if (ctx->meth->get_params(params)) return sz; } } /* * If the MAC hasn't been initialized yet, or there is no size to get, * we return zero */ return 0; } size_t EVP_MAC_CTX_get_mac_size(EVP_MAC_CTX *ctx) { return get_size_t_ctx_param(ctx, OSSL_MAC_PARAM_SIZE); } size_t EVP_MAC_CTX_get_block_size(EVP_MAC_CTX *ctx) { return get_size_t_ctx_param(ctx, OSSL_MAC_PARAM_BLOCK_SIZE); } int EVP_MAC_init(EVP_MAC_CTX *ctx, const unsigned char *key, size_t keylen, const OSSL_PARAM params[]) { return ctx->meth->init(ctx->algctx, key, keylen, params); } int EVP_MAC_update(EVP_MAC_CTX *ctx, const unsigned char *data, size_t datalen) { return ctx->meth->update(ctx->algctx, data, datalen); } static int evp_mac_final(EVP_MAC_CTX *ctx, int xof, unsigned char *out, size_t *outl, size_t outsize) { size_t l; int res; OSSL_PARAM params[2]; size_t macsize; if (ctx == NULL || ctx->meth == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_NULL_ALGORITHM); return 0; } if (ctx->meth->final == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } macsize = EVP_MAC_CTX_get_mac_size(ctx); if (out == NULL) { if (outl == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return 0; } *outl = macsize; return 1; } if (outsize < macsize) { ERR_raise(ERR_LIB_EVP, EVP_R_BUFFER_TOO_SMALL); return 0; } if (xof) { params[0] = OSSL_PARAM_construct_int(OSSL_MAC_PARAM_XOF, &xof); params[1] = OSSL_PARAM_construct_end(); if (EVP_MAC_CTX_set_params(ctx, params) <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_SETTING_XOF_FAILED); return 0; } } res = ctx->meth->final(ctx->algctx, out, &l, outsize); if (outl != NULL) *outl = l; return res; } int EVP_MAC_final(EVP_MAC_CTX *ctx, unsigned char *out, size_t *outl, size_t outsize) { return evp_mac_final(ctx, 0, out, outl, outsize); } int EVP_MAC_finalXOF(EVP_MAC_CTX *ctx, unsigned char *out, size_t outsize) { return evp_mac_final(ctx, 1, out, NULL, outsize); } /* * The {get,set}_params functions return 1 if there is no corresponding * function in the implementation. This is the same as if there was one, * but it didn't recognise any of the given params, i.e. nothing in the * bag of parameters was useful. */ int EVP_MAC_get_params(EVP_MAC *mac, OSSL_PARAM params[]) { if (mac->get_params != NULL) return mac->get_params(params); return 1; } int EVP_MAC_CTX_get_params(EVP_MAC_CTX *ctx, OSSL_PARAM params[]) { if (ctx->meth->get_ctx_params != NULL) return ctx->meth->get_ctx_params(ctx->algctx, params); return 1; } int EVP_MAC_CTX_set_params(EVP_MAC_CTX *ctx, const OSSL_PARAM params[]) { if (ctx->meth->set_ctx_params != NULL) return ctx->meth->set_ctx_params(ctx->algctx, params); return 1; } int evp_mac_get_number(const EVP_MAC *mac) { return mac->name_id; } const char *EVP_MAC_get0_name(const EVP_MAC *mac) { return mac->type_name; } const char *EVP_MAC_get0_description(const EVP_MAC *mac) { return mac->description; } int EVP_MAC_is_a(const EVP_MAC *mac, const char *name) { return mac != NULL && evp_is_a(mac->prov, mac->name_id, NULL, name); } int EVP_MAC_names_do_all(const EVP_MAC *mac, void (*fn)(const char *name, void *data), void *data) { if (mac->prov != NULL) return evp_names_do_all(mac->prov, mac->name_id, fn, data); return 1; } unsigned char *EVP_Q_mac(OSSL_LIB_CTX *libctx, const char *name, const char *propq, const char *subalg, const OSSL_PARAM *params, const void *key, size_t keylen, const unsigned char *data, size_t datalen, unsigned char *out, size_t outsize, size_t *outlen) { EVP_MAC *mac = EVP_MAC_fetch(libctx, name, propq); OSSL_PARAM subalg_param[] = { OSSL_PARAM_END, OSSL_PARAM_END }; EVP_MAC_CTX *ctx = NULL; size_t len = 0; unsigned char *res = NULL; if (outlen != NULL) *outlen = 0; if (mac == NULL) return NULL; if (subalg != NULL) { const OSSL_PARAM *defined_params = EVP_MAC_settable_ctx_params(mac); const char *param_name = OSSL_MAC_PARAM_DIGEST; /* * The underlying algorithm may be a cipher or a digest. * We don't know which it is, but we can ask the MAC what it * should be and bet on that. */ if (OSSL_PARAM_locate_const(defined_params, param_name) == NULL) { param_name = OSSL_MAC_PARAM_CIPHER; if (OSSL_PARAM_locate_const(defined_params, param_name) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_INVALID_ARGUMENT); goto err; } } subalg_param[0] = OSSL_PARAM_construct_utf8_string(param_name, (char *)subalg, 0); } /* Single-shot - on NULL key input, set dummy key value for EVP_MAC_Init. */ if (key == NULL && keylen == 0) key = data; if ((ctx = EVP_MAC_CTX_new(mac)) != NULL && EVP_MAC_CTX_set_params(ctx, subalg_param) && EVP_MAC_CTX_set_params(ctx, params) && EVP_MAC_init(ctx, key, keylen, params) && EVP_MAC_update(ctx, data, datalen) && EVP_MAC_final(ctx, out, &len, outsize)) { if (out == NULL) { out = OPENSSL_malloc(len); if (out != NULL && !EVP_MAC_final(ctx, out, NULL, len)) { OPENSSL_free(out); out = NULL; } } res = out; if (res != NULL && outlen != NULL) *outlen = len; } err: EVP_MAC_CTX_free(ctx); EVP_MAC_free(mac); return res; }
./openssl/crypto/evp/evp_key.c
/* * Copyright 1995-2021 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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/x509.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/ui.h> #ifndef BUFSIZ # define BUFSIZ 256 #endif /* should be init to zeros. */ static char prompt_string[80]; void EVP_set_pw_prompt(const char *prompt) { if (prompt == NULL) prompt_string[0] = '\0'; else { strncpy(prompt_string, prompt, 79); prompt_string[79] = '\0'; } } char *EVP_get_pw_prompt(void) { if (prompt_string[0] == '\0') return NULL; else return prompt_string; } /* * For historical reasons, the standard function for reading passwords is in * the DES library -- if someone ever wants to disable DES, this function * will fail */ int EVP_read_pw_string(char *buf, int len, const char *prompt, int verify) { return EVP_read_pw_string_min(buf, 0, len, prompt, verify); } int EVP_read_pw_string_min(char *buf, int min, int len, const char *prompt, int verify) { int ret = -1; char buff[BUFSIZ]; UI *ui; if ((prompt == NULL) && (prompt_string[0] != '\0')) prompt = prompt_string; ui = UI_new(); if (ui == NULL) return ret; if (UI_add_input_string(ui, prompt, 0, buf, min, (len >= BUFSIZ) ? BUFSIZ - 1 : len) < 0 || (verify && UI_add_verify_string(ui, prompt, 0, buff, min, (len >= BUFSIZ) ? BUFSIZ - 1 : len, buf) < 0)) goto end; ret = UI_process(ui); OPENSSL_cleanse(buff, BUFSIZ); end: UI_free(ui); return ret; } int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, const unsigned char *salt, const unsigned char *data, int datal, int count, unsigned char *key, unsigned char *iv) { EVP_MD_CTX *c; unsigned char md_buf[EVP_MAX_MD_SIZE]; int niv, nkey, addmd = 0; unsigned int mds = 0, i; int rv = 0; nkey = EVP_CIPHER_get_key_length(type); niv = EVP_CIPHER_get_iv_length(type); OPENSSL_assert(nkey <= EVP_MAX_KEY_LENGTH); OPENSSL_assert(niv <= EVP_MAX_IV_LENGTH); if (data == NULL) return nkey; c = EVP_MD_CTX_new(); if (c == NULL) goto err; for (;;) { if (!EVP_DigestInit_ex(c, md, NULL)) goto err; if (addmd++) if (!EVP_DigestUpdate(c, &(md_buf[0]), mds)) goto err; if (!EVP_DigestUpdate(c, data, datal)) goto err; if (salt != NULL) if (!EVP_DigestUpdate(c, salt, PKCS5_SALT_LEN)) goto err; if (!EVP_DigestFinal_ex(c, &(md_buf[0]), &mds)) goto err; for (i = 1; i < (unsigned int)count; i++) { if (!EVP_DigestInit_ex(c, md, NULL)) goto err; if (!EVP_DigestUpdate(c, &(md_buf[0]), mds)) goto err; if (!EVP_DigestFinal_ex(c, &(md_buf[0]), &mds)) goto err; } i = 0; if (nkey) { for (;;) { if (nkey == 0) break; if (i == mds) break; if (key != NULL) *(key++) = md_buf[i]; nkey--; i++; } } if (niv && (i != mds)) { for (;;) { if (niv == 0) break; if (i == mds) break; if (iv != NULL) *(iv++) = md_buf[i]; niv--; i++; } } if ((nkey == 0) && (niv == 0)) break; } rv = EVP_CIPHER_get_key_length(type); err: EVP_MD_CTX_free(c); OPENSSL_cleanse(md_buf, sizeof(md_buf)); return rv; }
./openssl/crypto/evp/p_seal.c
/* * Copyright 1995-2021 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 <stdio.h> #include "internal/cryptlib.h" #include "internal/provider.h" #include <openssl/rand.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, unsigned char **ek, int *ekl, unsigned char *iv, EVP_PKEY **pubk, int npubk) { unsigned char key[EVP_MAX_KEY_LENGTH]; const OSSL_PROVIDER *prov; OSSL_LIB_CTX *libctx = NULL; EVP_PKEY_CTX *pctx = NULL; const EVP_CIPHER *cipher; int i, len; int rv = 0; if (type != NULL) { EVP_CIPHER_CTX_reset(ctx); if (!EVP_EncryptInit_ex(ctx, type, NULL, NULL, NULL)) return 0; } if ((cipher = EVP_CIPHER_CTX_get0_cipher(ctx)) != NULL && (prov = EVP_CIPHER_get0_provider(cipher)) != NULL) libctx = ossl_provider_libctx(prov); if ((npubk <= 0) || !pubk) return 1; if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0) return 0; len = EVP_CIPHER_CTX_get_iv_length(ctx); if (len < 0 || RAND_priv_bytes_ex(libctx, iv, len, 0) <= 0) goto err; len = EVP_CIPHER_CTX_get_key_length(ctx); if (len < 0) goto err; if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) goto err; for (i = 0; i < npubk; i++) { size_t keylen = len; pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pubk[i], NULL); if (pctx == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); goto err; } if (EVP_PKEY_encrypt_init(pctx) <= 0 || EVP_PKEY_encrypt(pctx, ek[i], &keylen, key, keylen) <= 0) goto err; ekl[i] = (int)keylen; EVP_PKEY_CTX_free(pctx); } pctx = NULL; rv = npubk; err: EVP_PKEY_CTX_free(pctx); OPENSSL_cleanse(key, sizeof(key)); return rv; } int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { int i; i = EVP_EncryptFinal_ex(ctx, out, outl); if (i) i = EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL); return i; }
./openssl/crypto/evp/names.c
/* * Copyright 1995-2021 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 <stdio.h> #include <openssl/evp.h> #include <openssl/kdf.h> #include <openssl/x509.h> #include "internal/cryptlib.h" #include "internal/namemap.h" #include "crypto/objects.h" #include "crypto/evp.h" int EVP_add_cipher(const EVP_CIPHER *c) { int r; if (c == NULL) return 0; r = OBJ_NAME_add(OBJ_nid2sn(c->nid), OBJ_NAME_TYPE_CIPHER_METH, (const char *)c); if (r == 0) return 0; r = OBJ_NAME_add(OBJ_nid2ln(c->nid), OBJ_NAME_TYPE_CIPHER_METH, (const char *)c); return r; } int EVP_add_digest(const EVP_MD *md) { int r; const char *name; name = OBJ_nid2sn(md->type); r = OBJ_NAME_add(name, OBJ_NAME_TYPE_MD_METH, (const char *)md); if (r == 0) return 0; r = OBJ_NAME_add(OBJ_nid2ln(md->type), OBJ_NAME_TYPE_MD_METH, (const char *)md); if (r == 0) return 0; if (md->pkey_type && md->type != md->pkey_type) { r = OBJ_NAME_add(OBJ_nid2sn(md->pkey_type), OBJ_NAME_TYPE_MD_METH | OBJ_NAME_ALIAS, name); if (r == 0) return 0; r = OBJ_NAME_add(OBJ_nid2ln(md->pkey_type), OBJ_NAME_TYPE_MD_METH | OBJ_NAME_ALIAS, name); } return r; } static void cipher_from_name(const char *name, void *data) { const EVP_CIPHER **cipher = data; if (*cipher != NULL) return; *cipher = (const EVP_CIPHER *)OBJ_NAME_get(name, OBJ_NAME_TYPE_CIPHER_METH); } const EVP_CIPHER *EVP_get_cipherbyname(const char *name) { return evp_get_cipherbyname_ex(NULL, name); } const EVP_CIPHER *evp_get_cipherbyname_ex(OSSL_LIB_CTX *libctx, const char *name) { const EVP_CIPHER *cp; OSSL_NAMEMAP *namemap; int id; if (!OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS, NULL)) return NULL; cp = (const EVP_CIPHER *)OBJ_NAME_get(name, OBJ_NAME_TYPE_CIPHER_METH); if (cp != NULL) return cp; /* * It's not in the method database, but it might be there under a different * name. So we check for aliases in the EVP namemap and try all of those * in turn. */ namemap = ossl_namemap_stored(libctx); id = ossl_namemap_name2num(namemap, name); if (id == 0) return NULL; if (!ossl_namemap_doall_names(namemap, id, cipher_from_name, &cp)) return NULL; return cp; } static void digest_from_name(const char *name, void *data) { const EVP_MD **md = data; if (*md != NULL) return; *md = (const EVP_MD *)OBJ_NAME_get(name, OBJ_NAME_TYPE_MD_METH); } const EVP_MD *EVP_get_digestbyname(const char *name) { return evp_get_digestbyname_ex(NULL, name); } const EVP_MD *evp_get_digestbyname_ex(OSSL_LIB_CTX *libctx, const char *name) { const EVP_MD *dp; OSSL_NAMEMAP *namemap; int id; if (!OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_DIGESTS, NULL)) return NULL; dp = (const EVP_MD *)OBJ_NAME_get(name, OBJ_NAME_TYPE_MD_METH); if (dp != NULL) return dp; /* * It's not in the method database, but it might be there under a different * name. So we check for aliases in the EVP namemap and try all of those * in turn. */ namemap = ossl_namemap_stored(libctx); id = ossl_namemap_name2num(namemap, name); if (id == 0) return NULL; if (!ossl_namemap_doall_names(namemap, id, digest_from_name, &dp)) return NULL; return dp; } void evp_cleanup_int(void) { OBJ_NAME_cleanup(OBJ_NAME_TYPE_KDF_METH); OBJ_NAME_cleanup(OBJ_NAME_TYPE_CIPHER_METH); OBJ_NAME_cleanup(OBJ_NAME_TYPE_MD_METH); /* * The above calls will only clean out the contents of the name hash * table, but not the hash table itself. The following line does that * part. -- Richard Levitte */ OBJ_NAME_cleanup(-1); EVP_PBE_cleanup(); OBJ_sigid_free(); evp_app_cleanup_int(); } struct doall_cipher { void *arg; void (*fn) (const EVP_CIPHER *ciph, const char *from, const char *to, void *arg); }; static void do_all_cipher_fn(const OBJ_NAME *nm, void *arg) { struct doall_cipher *dc = arg; if (nm->alias) dc->fn(NULL, nm->name, nm->data, dc->arg); else dc->fn((const EVP_CIPHER *)nm->data, nm->name, NULL, dc->arg); } void EVP_CIPHER_do_all(void (*fn) (const EVP_CIPHER *ciph, const char *from, const char *to, void *x), void *arg) { struct doall_cipher dc; /* Ignore errors */ OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS, NULL); dc.fn = fn; dc.arg = arg; OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH, do_all_cipher_fn, &dc); } void EVP_CIPHER_do_all_sorted(void (*fn) (const EVP_CIPHER *ciph, const char *from, const char *to, void *x), void *arg) { struct doall_cipher dc; /* Ignore errors */ OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS, NULL); dc.fn = fn; dc.arg = arg; OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, do_all_cipher_fn, &dc); } struct doall_md { void *arg; void (*fn) (const EVP_MD *ciph, const char *from, const char *to, void *arg); }; static void do_all_md_fn(const OBJ_NAME *nm, void *arg) { struct doall_md *dc = arg; if (nm->alias) dc->fn(NULL, nm->name, nm->data, dc->arg); else dc->fn((const EVP_MD *)nm->data, nm->name, NULL, dc->arg); } void EVP_MD_do_all(void (*fn) (const EVP_MD *md, const char *from, const char *to, void *x), void *arg) { struct doall_md dc; /* Ignore errors */ OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_DIGESTS, NULL); dc.fn = fn; dc.arg = arg; OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH, do_all_md_fn, &dc); } void EVP_MD_do_all_sorted(void (*fn) (const EVP_MD *md, const char *from, const char *to, void *x), void *arg) { struct doall_md dc; OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_DIGESTS, NULL); dc.fn = fn; dc.arg = arg; OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH, do_all_md_fn, &dc); }
./openssl/crypto/evp/digest.c
/* * Copyright 1995-2023 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 */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/ec.h> #ifndef FIPS_MODULE # include <openssl/engine.h> #endif #include <openssl/params.h> #include <openssl/core_names.h> #include "internal/cryptlib.h" #include "internal/provider.h" #include "internal/core.h" #include "crypto/evp.h" #include "evp_local.h" static void cleanup_old_md_data(EVP_MD_CTX *ctx, int force) { if (ctx->digest != NULL) { if (ctx->digest->cleanup != NULL && !EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_CLEANED)) ctx->digest->cleanup(ctx); if (ctx->md_data != NULL && ctx->digest->ctx_size > 0 && (!EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_REUSE) || force)) { OPENSSL_clear_free(ctx->md_data, ctx->digest->ctx_size); ctx->md_data = NULL; } } } void evp_md_ctx_clear_digest(EVP_MD_CTX *ctx, int force, int keep_fetched) { if (ctx->algctx != NULL) { if (ctx->digest != NULL && ctx->digest->freectx != NULL) ctx->digest->freectx(ctx->algctx); ctx->algctx = NULL; EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_CLEANED); } /* Code below to be removed when legacy support is dropped. */ /* * Don't assume ctx->md_data was cleaned in EVP_Digest_Final, because * sometimes only copies of the context are ever finalised. */ cleanup_old_md_data(ctx, force); if (force) ctx->digest = NULL; #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_ENGINE) ENGINE_finish(ctx->engine); ctx->engine = NULL; #endif /* Non legacy code, this has to be later than the ctx->digest cleaning */ if (!keep_fetched) { EVP_MD_free(ctx->fetched_digest); ctx->fetched_digest = NULL; ctx->reqdigest = NULL; } } static int evp_md_ctx_reset_ex(EVP_MD_CTX *ctx, int keep_fetched) { if (ctx == NULL) return 1; #ifndef FIPS_MODULE /* * pctx should be freed by the user of EVP_MD_CTX * if EVP_MD_CTX_FLAG_KEEP_PKEY_CTX is set */ if (!EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX)) { EVP_PKEY_CTX_free(ctx->pctx); ctx->pctx = NULL; } #endif evp_md_ctx_clear_digest(ctx, 0, keep_fetched); if (!keep_fetched) OPENSSL_cleanse(ctx, sizeof(*ctx)); return 1; } /* This call frees resources associated with the context */ int EVP_MD_CTX_reset(EVP_MD_CTX *ctx) { return evp_md_ctx_reset_ex(ctx, 0); } #ifndef FIPS_MODULE EVP_MD_CTX *evp_md_ctx_new_ex(EVP_PKEY *pkey, const ASN1_OCTET_STRING *id, OSSL_LIB_CTX *libctx, const char *propq) { EVP_MD_CTX *ctx; EVP_PKEY_CTX *pctx = NULL; if ((ctx = EVP_MD_CTX_new()) == NULL || (pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq)) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB); goto err; } if (id != NULL && EVP_PKEY_CTX_set1_id(pctx, id->data, id->length) <= 0) goto err; EVP_MD_CTX_set_pkey_ctx(ctx, pctx); return ctx; err: EVP_PKEY_CTX_free(pctx); EVP_MD_CTX_free(ctx); return NULL; } #endif EVP_MD_CTX *EVP_MD_CTX_new(void) { return OPENSSL_zalloc(sizeof(EVP_MD_CTX)); } void EVP_MD_CTX_free(EVP_MD_CTX *ctx) { if (ctx == NULL) return; EVP_MD_CTX_reset(ctx); OPENSSL_free(ctx); } int evp_md_ctx_free_algctx(EVP_MD_CTX *ctx) { if (ctx->algctx != NULL) { if (!ossl_assert(ctx->digest != NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } if (ctx->digest->freectx != NULL) ctx->digest->freectx(ctx->algctx); ctx->algctx = NULL; } return 1; } static int evp_md_init_internal(EVP_MD_CTX *ctx, const EVP_MD *type, const OSSL_PARAM params[], ENGINE *impl) { #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) ENGINE *tmpimpl = NULL; #endif #if !defined(FIPS_MODULE) if (ctx->pctx != NULL && EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx) && ctx->pctx->op.sig.algctx != NULL) { /* * Prior to OpenSSL 3.0 calling EVP_DigestInit_ex() on an mdctx * previously initialised with EVP_DigestSignInit() would retain * information about the key, and re-initialise for another sign * operation. So in that case we redirect to EVP_DigestSignInit() */ if (ctx->pctx->operation == EVP_PKEY_OP_SIGNCTX) return EVP_DigestSignInit(ctx, NULL, type, impl, NULL); if (ctx->pctx->operation == EVP_PKEY_OP_VERIFYCTX) return EVP_DigestVerifyInit(ctx, NULL, type, impl, NULL); ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR); return 0; } #endif EVP_MD_CTX_clear_flags(ctx, EVP_MD_CTX_FLAG_CLEANED | EVP_MD_CTX_FLAG_FINALISED); if (type != NULL) { ctx->reqdigest = type; } else { if (ctx->digest == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_DIGEST_SET); return 0; } type = ctx->digest; } /* Code below to be removed when legacy support is dropped. */ #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) /* * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so * this context may already have an ENGINE! Try to avoid releasing the * previous handle, re-querying for an ENGINE, and having a * reinitialisation, when it may all be unnecessary. */ if (ctx->engine != NULL && ctx->digest != NULL && type->type == ctx->digest->type) goto skip_to_init; /* * Ensure an ENGINE left lying around from last time is cleared (the * previous check attempted to avoid this if the same ENGINE and * EVP_MD could be used). */ ENGINE_finish(ctx->engine); ctx->engine = NULL; if (impl == NULL) tmpimpl = ENGINE_get_digest_engine(type->type); #endif /* * If there are engines involved or EVP_MD_CTX_FLAG_NO_INIT is set then we * should use legacy handling for now. */ if (impl != NULL #if !defined(OPENSSL_NO_ENGINE) || ctx->engine != NULL # if !defined(FIPS_MODULE) || tmpimpl != NULL # endif #endif || (ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) != 0 || (type != NULL && type->origin == EVP_ORIG_METH) || (type == NULL && ctx->digest != NULL && ctx->digest->origin == EVP_ORIG_METH)) { /* If we were using provided hash before, cleanup algctx */ if (!evp_md_ctx_free_algctx(ctx)) return 0; if (ctx->digest == ctx->fetched_digest) ctx->digest = NULL; EVP_MD_free(ctx->fetched_digest); ctx->fetched_digest = NULL; goto legacy; } cleanup_old_md_data(ctx, 1); /* Start of non-legacy code below */ if (ctx->digest == type) { if (!ossl_assert(type->prov != NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } } else { if (!evp_md_ctx_free_algctx(ctx)) return 0; } if (type->prov == NULL) { #ifdef FIPS_MODULE /* We only do explicit fetches inside the FIPS module */ ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; #else /* The NULL digest is a special case */ EVP_MD *provmd = EVP_MD_fetch(NULL, type->type != NID_undef ? OBJ_nid2sn(type->type) : "NULL", ""); if (provmd == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } type = provmd; EVP_MD_free(ctx->fetched_digest); ctx->fetched_digest = provmd; #endif } if (type->prov != NULL && ctx->fetched_digest != type) { if (!EVP_MD_up_ref((EVP_MD *)type)) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } EVP_MD_free(ctx->fetched_digest); ctx->fetched_digest = (EVP_MD *)type; } ctx->digest = type; if (ctx->algctx == NULL) { ctx->algctx = ctx->digest->newctx(ossl_provider_ctx(type->prov)); if (ctx->algctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } } if (ctx->digest->dinit == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } return ctx->digest->dinit(ctx->algctx, params); /* Code below to be removed when legacy support is dropped. */ legacy: #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) if (type) { if (impl != NULL) { if (!ENGINE_init(impl)) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } } else { /* Ask if an ENGINE is reserved for this job */ impl = tmpimpl; } if (impl != NULL) { /* There's an ENGINE for this job ... (apparently) */ const EVP_MD *d = ENGINE_get_digest(impl, type->type); if (d == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); ENGINE_finish(impl); return 0; } /* We'll use the ENGINE's private digest definition */ type = d; /* * Store the ENGINE functional reference so we know 'type' came * from an ENGINE and we need to release it when done. */ ctx->engine = impl; } else ctx->engine = NULL; } #endif if (ctx->digest != type) { cleanup_old_md_data(ctx, 1); ctx->digest = type; if (!(ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) && type->ctx_size) { ctx->update = type->update; ctx->md_data = OPENSSL_zalloc(type->ctx_size); if (ctx->md_data == NULL) return 0; } } #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) skip_to_init: #endif #ifndef FIPS_MODULE if (ctx->pctx != NULL && (!EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx) || ctx->pctx->op.sig.signature == NULL)) { int r; r = EVP_PKEY_CTX_ctrl(ctx->pctx, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_DIGESTINIT, 0, ctx); if (r <= 0 && (r != -2)) return 0; } #endif if (ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) return 1; return ctx->digest->init(ctx); } int EVP_DigestInit_ex2(EVP_MD_CTX *ctx, const EVP_MD *type, const OSSL_PARAM params[]) { return evp_md_init_internal(ctx, type, params, NULL); } int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type) { EVP_MD_CTX_reset(ctx); return evp_md_init_internal(ctx, type, NULL, NULL); } int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl) { return evp_md_init_internal(ctx, type, NULL, impl); } int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t count) { if (count == 0) return 1; if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISED) != 0) { ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR); return 0; } if (ctx->pctx != NULL && EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx) && ctx->pctx->op.sig.algctx != NULL) { /* * Prior to OpenSSL 3.0 EVP_DigestSignUpdate() and * EVP_DigestVerifyUpdate() were just macros for EVP_DigestUpdate(). * Some code calls EVP_DigestUpdate() directly even when initialised * with EVP_DigestSignInit_ex() or * EVP_DigestVerifyInit_ex(), so we detect that and redirect to * the correct EVP_Digest*Update() function */ if (ctx->pctx->operation == EVP_PKEY_OP_SIGNCTX) return EVP_DigestSignUpdate(ctx, data, count); if (ctx->pctx->operation == EVP_PKEY_OP_VERIFYCTX) return EVP_DigestVerifyUpdate(ctx, data, count); ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR); return 0; } if (ctx->digest == NULL || ctx->digest->prov == NULL || (ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) != 0) goto legacy; if (ctx->digest->dupdate == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR); return 0; } return ctx->digest->dupdate(ctx->algctx, data, count); /* Code below to be removed when legacy support is dropped. */ legacy: return ctx->update(ctx, data, count); } /* The caller can assume that this removes any secret data from the context */ int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *size) { int ret; ret = EVP_DigestFinal_ex(ctx, md, size); EVP_MD_CTX_reset(ctx); return ret; } /* The caller can assume that this removes any secret data from the context */ int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *isize) { int ret, sz; size_t size = 0; size_t mdsize = 0; if (ctx->digest == NULL) return 0; sz = EVP_MD_get_size(ctx->digest); if (sz < 0) return 0; mdsize = sz; if (ctx->digest->prov == NULL) goto legacy; if (ctx->digest->gettable_ctx_params != NULL) { OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_SIZE, &mdsize); if (!EVP_MD_CTX_get_params(ctx, params)) return 0; } if (ctx->digest->dfinal == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISED) != 0) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } ret = ctx->digest->dfinal(ctx->algctx, md, &size, mdsize); ctx->flags |= EVP_MD_CTX_FLAG_FINALISED; if (isize != NULL) { if (size <= UINT_MAX) { *isize = (unsigned int)size; } else { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); ret = 0; } } return ret; /* Code below to be removed when legacy support is dropped. */ legacy: OPENSSL_assert(mdsize <= EVP_MAX_MD_SIZE); ret = ctx->digest->final(ctx, md); if (isize != NULL) *isize = mdsize; if (ctx->digest->cleanup) { ctx->digest->cleanup(ctx); EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_CLEANED); } OPENSSL_cleanse(ctx->md_data, ctx->digest->ctx_size); return ret; } /* This is a one shot operation */ int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, unsigned char *md, size_t size) { int ret = 0; OSSL_PARAM params[2]; size_t i = 0; if (ctx->digest == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_NULL_ALGORITHM); return 0; } if (ctx->digest->prov == NULL) goto legacy; if (ctx->digest->dfinal == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISED) != 0) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } /* * For backward compatibility we pass the XOFLEN via a param here so that * older providers can use the supplied value. Ideally we should have just * used the size passed into ctx->digest->dfinal(). */ params[i++] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_XOFLEN, &size); params[i++] = OSSL_PARAM_construct_end(); if (EVP_MD_CTX_set_params(ctx, params) >= 0) ret = ctx->digest->dfinal(ctx->algctx, md, &size, size); ctx->flags |= EVP_MD_CTX_FLAG_FINALISED; return ret; legacy: if (ctx->digest->flags & EVP_MD_FLAG_XOF && size <= INT_MAX && ctx->digest->md_ctrl(ctx, EVP_MD_CTRL_XOF_LEN, (int)size, NULL)) { ret = ctx->digest->final(ctx, md); if (ctx->digest->cleanup != NULL) { ctx->digest->cleanup(ctx); EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_CLEANED); } OPENSSL_cleanse(ctx->md_data, ctx->digest->ctx_size); } else { ERR_raise(ERR_LIB_EVP, EVP_R_NOT_XOF_OR_INVALID_LENGTH); } return ret; } /* EVP_DigestSqueeze() can be called multiple times */ int EVP_DigestSqueeze(EVP_MD_CTX *ctx, unsigned char *md, size_t size) { if (ctx->digest == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_NULL_ALGORITHM); return 0; } if (ctx->digest->prov == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION); return 0; } if (ctx->digest->dsqueeze == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_METHOD_NOT_SUPPORTED); return 0; } return ctx->digest->dsqueeze(ctx->algctx, md, &size, size); } EVP_MD_CTX *EVP_MD_CTX_dup(const EVP_MD_CTX *in) { EVP_MD_CTX *out = EVP_MD_CTX_new(); if (out != NULL && !EVP_MD_CTX_copy_ex(out, in)) { EVP_MD_CTX_free(out); out = NULL; } return out; } int EVP_MD_CTX_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in) { EVP_MD_CTX_reset(out); return EVP_MD_CTX_copy_ex(out, in); } int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in) { int digest_change = 0; unsigned char *tmp_buf; if (in == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (in->digest == NULL) { /* copying uninitialized digest context */ EVP_MD_CTX_reset(out); if (out->fetched_digest != NULL) EVP_MD_free(out->fetched_digest); *out = *in; goto clone_pkey; } if (in->digest->prov == NULL || (in->flags & EVP_MD_CTX_FLAG_NO_INIT) != 0) goto legacy; if (in->digest->dupctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX); return 0; } evp_md_ctx_reset_ex(out, 1); digest_change = (out->fetched_digest != in->fetched_digest); if (digest_change && out->fetched_digest != NULL) EVP_MD_free(out->fetched_digest); *out = *in; /* NULL out pointers in case of error */ out->pctx = NULL; out->algctx = NULL; if (digest_change && in->fetched_digest != NULL) EVP_MD_up_ref(in->fetched_digest); if (in->algctx != NULL) { out->algctx = in->digest->dupctx(in->algctx); if (out->algctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX); return 0; } } clone_pkey: /* copied EVP_MD_CTX should free the copied EVP_PKEY_CTX */ EVP_MD_CTX_clear_flags(out, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX); #ifndef FIPS_MODULE if (in->pctx != NULL) { out->pctx = EVP_PKEY_CTX_dup(in->pctx); if (out->pctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX); EVP_MD_CTX_reset(out); return 0; } } #endif return 1; /* Code below to be removed when legacy support is dropped. */ legacy: #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) /* Make sure it's safe to copy a digest context using an ENGINE */ if (in->engine && !ENGINE_init(in->engine)) { ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB); return 0; } #endif if (out->digest == in->digest) { tmp_buf = out->md_data; EVP_MD_CTX_set_flags(out, EVP_MD_CTX_FLAG_REUSE); } else tmp_buf = NULL; EVP_MD_CTX_reset(out); memcpy(out, in, sizeof(*out)); /* copied EVP_MD_CTX should free the copied EVP_PKEY_CTX */ EVP_MD_CTX_clear_flags(out, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX); /* Null these variables, since they are getting fixed up * properly below. Anything else may cause a memleak and/or * double free if any of the memory allocations below fail */ out->md_data = NULL; out->pctx = NULL; if (in->md_data && out->digest->ctx_size) { if (tmp_buf) out->md_data = tmp_buf; else { out->md_data = OPENSSL_malloc(out->digest->ctx_size); if (out->md_data == NULL) return 0; } memcpy(out->md_data, in->md_data, out->digest->ctx_size); } out->update = in->update; #ifndef FIPS_MODULE if (in->pctx) { out->pctx = EVP_PKEY_CTX_dup(in->pctx); if (!out->pctx) { EVP_MD_CTX_reset(out); return 0; } } #endif if (out->digest->copy) return out->digest->copy(out, in); return 1; } int EVP_Digest(const void *data, size_t count, unsigned char *md, unsigned int *size, const EVP_MD *type, ENGINE *impl) { EVP_MD_CTX *ctx = EVP_MD_CTX_new(); int ret; if (ctx == NULL) return 0; EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_ONESHOT); ret = EVP_DigestInit_ex(ctx, type, impl) && EVP_DigestUpdate(ctx, data, count) && EVP_DigestFinal_ex(ctx, md, size); EVP_MD_CTX_free(ctx); return ret; } int EVP_Q_digest(OSSL_LIB_CTX *libctx, const char *name, const char *propq, const void *data, size_t datalen, unsigned char *md, size_t *mdlen) { EVP_MD *digest = EVP_MD_fetch(libctx, name, propq); unsigned int temp = 0; int ret = 0; if (digest != NULL) { ret = EVP_Digest(data, datalen, md, &temp, digest, NULL); EVP_MD_free(digest); } if (mdlen != NULL) *mdlen = temp; return ret; } int EVP_MD_get_params(const EVP_MD *digest, OSSL_PARAM params[]) { if (digest != NULL && digest->get_params != NULL) return digest->get_params(params); return 0; } const OSSL_PARAM *EVP_MD_gettable_params(const EVP_MD *digest) { if (digest != NULL && digest->gettable_params != NULL) return digest->gettable_params( ossl_provider_ctx(EVP_MD_get0_provider(digest))); return NULL; } int EVP_MD_CTX_set_params(EVP_MD_CTX *ctx, const OSSL_PARAM params[]) { EVP_PKEY_CTX *pctx = ctx->pctx; /* If we have a pctx then we should try that first */ if (pctx != NULL && (pctx->operation == EVP_PKEY_OP_VERIFYCTX || pctx->operation == EVP_PKEY_OP_SIGNCTX) && pctx->op.sig.algctx != NULL && pctx->op.sig.signature->set_ctx_md_params != NULL) return pctx->op.sig.signature->set_ctx_md_params(pctx->op.sig.algctx, params); if (ctx->digest != NULL && ctx->digest->set_ctx_params != NULL) return ctx->digest->set_ctx_params(ctx->algctx, params); return 0; } const OSSL_PARAM *EVP_MD_settable_ctx_params(const EVP_MD *md) { void *provctx; if (md != NULL && md->settable_ctx_params != NULL) { provctx = ossl_provider_ctx(EVP_MD_get0_provider(md)); return md->settable_ctx_params(NULL, provctx); } return NULL; } const OSSL_PARAM *EVP_MD_CTX_settable_params(EVP_MD_CTX *ctx) { EVP_PKEY_CTX *pctx; void *alg; if (ctx == NULL) return NULL; /* If we have a pctx then we should try that first */ pctx = ctx->pctx; if (pctx != NULL && (pctx->operation == EVP_PKEY_OP_VERIFYCTX || pctx->operation == EVP_PKEY_OP_SIGNCTX) && pctx->op.sig.algctx != NULL && pctx->op.sig.signature->settable_ctx_md_params != NULL) return pctx->op.sig.signature->settable_ctx_md_params( pctx->op.sig.algctx); if (ctx->digest != NULL && ctx->digest->settable_ctx_params != NULL) { alg = ossl_provider_ctx(EVP_MD_get0_provider(ctx->digest)); return ctx->digest->settable_ctx_params(ctx->algctx, alg); } return NULL; } int EVP_MD_CTX_get_params(EVP_MD_CTX *ctx, OSSL_PARAM params[]) { EVP_PKEY_CTX *pctx = ctx->pctx; /* If we have a pctx then we should try that first */ if (pctx != NULL && (pctx->operation == EVP_PKEY_OP_VERIFYCTX || pctx->operation == EVP_PKEY_OP_SIGNCTX) && pctx->op.sig.algctx != NULL && pctx->op.sig.signature->get_ctx_md_params != NULL) return pctx->op.sig.signature->get_ctx_md_params(pctx->op.sig.algctx, params); if (ctx->digest != NULL && ctx->digest->get_ctx_params != NULL) return ctx->digest->get_ctx_params(ctx->algctx, params); return 0; } const OSSL_PARAM *EVP_MD_gettable_ctx_params(const EVP_MD *md) { void *provctx; if (md != NULL && md->gettable_ctx_params != NULL) { provctx = ossl_provider_ctx(EVP_MD_get0_provider(md)); return md->gettable_ctx_params(NULL, provctx); } return NULL; } const OSSL_PARAM *EVP_MD_CTX_gettable_params(EVP_MD_CTX *ctx) { EVP_PKEY_CTX *pctx; void *provctx; if (ctx == NULL) return NULL; /* If we have a pctx then we should try that first */ pctx = ctx->pctx; if (pctx != NULL && (pctx->operation == EVP_PKEY_OP_VERIFYCTX || pctx->operation == EVP_PKEY_OP_SIGNCTX) && pctx->op.sig.algctx != NULL && pctx->op.sig.signature->gettable_ctx_md_params != NULL) return pctx->op.sig.signature->gettable_ctx_md_params( pctx->op.sig.algctx); if (ctx->digest != NULL && ctx->digest->gettable_ctx_params != NULL) { provctx = ossl_provider_ctx(EVP_MD_get0_provider(ctx->digest)); return ctx->digest->gettable_ctx_params(ctx->algctx, provctx); } return NULL; } int EVP_MD_CTX_ctrl(EVP_MD_CTX *ctx, int cmd, int p1, void *p2) { int ret = EVP_CTRL_RET_UNSUPPORTED; int set_params = 1; size_t sz; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ctx->digest != NULL && ctx->digest->prov == NULL) goto legacy; switch (cmd) { case EVP_MD_CTRL_XOF_LEN: sz = (size_t)p1; params[0] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_XOFLEN, &sz); break; case EVP_MD_CTRL_MICALG: set_params = 0; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_DIGEST_PARAM_MICALG, p2, p1 ? p1 : 9999); break; case EVP_CTRL_SSL3_MASTER_SECRET: params[0] = OSSL_PARAM_construct_octet_string(OSSL_DIGEST_PARAM_SSL3_MS, p2, p1); break; default: goto conclude; } if (set_params) ret = EVP_MD_CTX_set_params(ctx, params); else ret = EVP_MD_CTX_get_params(ctx, params); goto conclude; /* Code below to be removed when legacy support is dropped. */ legacy: if (ctx->digest->md_ctrl == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_CTRL_NOT_IMPLEMENTED); return 0; } ret = ctx->digest->md_ctrl(ctx, cmd, p1, p2); conclude: if (ret <= 0) return 0; return ret; } EVP_MD *evp_md_new(void) { EVP_MD *md = OPENSSL_zalloc(sizeof(*md)); if (md != NULL && !CRYPTO_NEW_REF(&md->refcnt, 1)) { OPENSSL_free(md); return NULL; } return md; } /* * FIPS module note: since internal fetches will be entirely * provider based, we know that none of its code depends on legacy * NIDs or any functionality that use them. */ #ifndef FIPS_MODULE static void set_legacy_nid(const char *name, void *vlegacy_nid) { int nid; int *legacy_nid = vlegacy_nid; /* * We use lowest level function to get the associated method, because * higher level functions such as EVP_get_digestbyname() have changed * to look at providers too. */ const void *legacy_method = OBJ_NAME_get(name, OBJ_NAME_TYPE_MD_METH); if (*legacy_nid == -1) /* We found a clash already */ return; if (legacy_method == NULL) return; nid = EVP_MD_nid(legacy_method); if (*legacy_nid != NID_undef && *legacy_nid != nid) { *legacy_nid = -1; return; } *legacy_nid = nid; } #endif static int evp_md_cache_constants(EVP_MD *md) { int ok, xof = 0, algid_absent = 0; size_t blksz = 0; size_t mdsize = 0; OSSL_PARAM params[5]; params[0] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_BLOCK_SIZE, &blksz); params[1] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_SIZE, &mdsize); params[2] = OSSL_PARAM_construct_int(OSSL_DIGEST_PARAM_XOF, &xof); params[3] = OSSL_PARAM_construct_int(OSSL_DIGEST_PARAM_ALGID_ABSENT, &algid_absent); params[4] = OSSL_PARAM_construct_end(); ok = evp_do_md_getparams(md, params) > 0; if (mdsize > INT_MAX || blksz > INT_MAX) ok = 0; if (ok) { md->block_size = (int)blksz; md->md_size = (int)mdsize; if (xof) md->flags |= EVP_MD_FLAG_XOF; if (algid_absent) md->flags |= EVP_MD_FLAG_DIGALGID_ABSENT; } return ok; } static void *evp_md_from_algorithm(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { const OSSL_DISPATCH *fns = algodef->implementation; EVP_MD *md = NULL; int fncnt = 0; /* EVP_MD_fetch() will set the legacy NID if available */ if ((md = evp_md_new()) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return NULL; } #ifndef FIPS_MODULE md->type = NID_undef; if (!evp_names_do_all(prov, name_id, set_legacy_nid, &md->type) || md->type == -1) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); EVP_MD_free(md); return NULL; } #endif md->name_id = name_id; if ((md->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) { EVP_MD_free(md); return NULL; } md->description = algodef->algorithm_description; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_DIGEST_NEWCTX: if (md->newctx == NULL) { md->newctx = OSSL_FUNC_digest_newctx(fns); fncnt++; } break; case OSSL_FUNC_DIGEST_INIT: if (md->dinit == NULL) { md->dinit = OSSL_FUNC_digest_init(fns); fncnt++; } break; case OSSL_FUNC_DIGEST_UPDATE: if (md->dupdate == NULL) { md->dupdate = OSSL_FUNC_digest_update(fns); fncnt++; } break; case OSSL_FUNC_DIGEST_FINAL: if (md->dfinal == NULL) { md->dfinal = OSSL_FUNC_digest_final(fns); fncnt++; } break; case OSSL_FUNC_DIGEST_SQUEEZE: if (md->dsqueeze == NULL) { md->dsqueeze = OSSL_FUNC_digest_squeeze(fns); fncnt++; } break; case OSSL_FUNC_DIGEST_DIGEST: if (md->digest == NULL) md->digest = OSSL_FUNC_digest_digest(fns); /* We don't increment fnct for this as it is stand alone */ break; case OSSL_FUNC_DIGEST_FREECTX: if (md->freectx == NULL) { md->freectx = OSSL_FUNC_digest_freectx(fns); fncnt++; } break; case OSSL_FUNC_DIGEST_DUPCTX: if (md->dupctx == NULL) md->dupctx = OSSL_FUNC_digest_dupctx(fns); break; case OSSL_FUNC_DIGEST_GET_PARAMS: if (md->get_params == NULL) md->get_params = OSSL_FUNC_digest_get_params(fns); break; case OSSL_FUNC_DIGEST_SET_CTX_PARAMS: if (md->set_ctx_params == NULL) md->set_ctx_params = OSSL_FUNC_digest_set_ctx_params(fns); break; case OSSL_FUNC_DIGEST_GET_CTX_PARAMS: if (md->get_ctx_params == NULL) md->get_ctx_params = OSSL_FUNC_digest_get_ctx_params(fns); break; case OSSL_FUNC_DIGEST_GETTABLE_PARAMS: if (md->gettable_params == NULL) md->gettable_params = OSSL_FUNC_digest_gettable_params(fns); break; case OSSL_FUNC_DIGEST_SETTABLE_CTX_PARAMS: if (md->settable_ctx_params == NULL) md->settable_ctx_params = OSSL_FUNC_digest_settable_ctx_params(fns); break; case OSSL_FUNC_DIGEST_GETTABLE_CTX_PARAMS: if (md->gettable_ctx_params == NULL) md->gettable_ctx_params = OSSL_FUNC_digest_gettable_ctx_params(fns); break; } } if ((fncnt != 0 && fncnt != 5 && fncnt != 6) || (fncnt == 0 && md->digest == NULL)) { /* * In order to be a consistent set of functions we either need the * whole set of init/update/final etc functions or none of them. * The "digest" function can standalone. We at least need one way to * generate digests. */ EVP_MD_free(md); ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS); return NULL; } md->prov = prov; if (prov != NULL) ossl_provider_up_ref(prov); if (!evp_md_cache_constants(md)) { EVP_MD_free(md); ERR_raise(ERR_LIB_EVP, EVP_R_CACHE_CONSTANTS_FAILED); md = NULL; } return md; } static int evp_md_up_ref(void *md) { return EVP_MD_up_ref(md); } static void evp_md_free(void *md) { EVP_MD_free(md); } EVP_MD *EVP_MD_fetch(OSSL_LIB_CTX *ctx, const char *algorithm, const char *properties) { EVP_MD *md = evp_generic_fetch(ctx, OSSL_OP_DIGEST, algorithm, properties, evp_md_from_algorithm, evp_md_up_ref, evp_md_free); return md; } int EVP_MD_up_ref(EVP_MD *md) { int ref = 0; if (md->origin == EVP_ORIG_DYNAMIC) CRYPTO_UP_REF(&md->refcnt, &ref); return 1; } void EVP_MD_free(EVP_MD *md) { int i; if (md == NULL || md->origin != EVP_ORIG_DYNAMIC) return; CRYPTO_DOWN_REF(&md->refcnt, &i); if (i > 0) return; evp_md_free_int(md); } void EVP_MD_do_all_provided(OSSL_LIB_CTX *libctx, void (*fn)(EVP_MD *mac, void *arg), void *arg) { evp_generic_do_all(libctx, OSSL_OP_DIGEST, (void (*)(void *, void *))fn, arg, evp_md_from_algorithm, evp_md_up_ref, evp_md_free); }
./openssl/crypto/evp/encode.c
/* * Copyright 1995-2020 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 <stdio.h> #include <limits.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include "crypto/evp.h" #include "evp_local.h" static unsigned char conv_ascii2bin(unsigned char a, const unsigned char *table); static int evp_encodeblock_int(EVP_ENCODE_CTX *ctx, unsigned char *t, const unsigned char *f, int dlen); static int evp_decodeblock_int(EVP_ENCODE_CTX *ctx, unsigned char *t, const unsigned char *f, int n); #ifndef CHARSET_EBCDIC # define conv_bin2ascii(a, table) ((table)[(a)&0x3f]) #else /* * We assume that PEM encoded files are EBCDIC files (i.e., printable text * files). Convert them here while decoding. When encoding, output is EBCDIC * (text) format again. (No need for conversion in the conv_bin2ascii macro, * as the underlying textstring data_bin2ascii[] is already EBCDIC) */ # define conv_bin2ascii(a, table) ((table)[(a)&0x3f]) #endif /*- * 64 char lines * pad input with 0 * left over chars are set to = * 1 byte => xx== * 2 bytes => xxx= * 3 bytes => xxxx */ #define BIN_PER_LINE (64/4*3) #define CHUNKS_PER_LINE (64/4) #define CHAR_PER_LINE (64+1) static const unsigned char data_bin2ascii[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /* SRP uses a different base64 alphabet */ static const unsigned char srpdata_bin2ascii[65] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./"; /*- * 0xF0 is a EOLN * 0xF1 is ignore but next needs to be 0xF0 (for \r\n processing). * 0xF2 is EOF * 0xE0 is ignore at start of line. * 0xFF is error */ #define B64_EOLN 0xF0 #define B64_CR 0xF1 #define B64_EOF 0xF2 #define B64_WS 0xE0 #define B64_ERROR 0xFF #define B64_NOT_BASE64(a) (((a)|0x13) == 0xF3) #define B64_BASE64(a) (!B64_NOT_BASE64(a)) static const unsigned char data_ascii2bin[128] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0xF0, 0xFF, 0xFF, 0xF1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3E, 0xFF, 0xF2, 0xFF, 0x3F, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; static const unsigned char srpdata_ascii2bin[128] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0xF0, 0xFF, 0xFF, 0xF1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF2, 0x3E, 0x3F, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; #ifndef CHARSET_EBCDIC static unsigned char conv_ascii2bin(unsigned char a, const unsigned char *table) { if (a & 0x80) return B64_ERROR; return table[a]; } #else static unsigned char conv_ascii2bin(unsigned char a, const unsigned char *table) { a = os_toascii[a]; if (a & 0x80) return B64_ERROR; return table[a]; } #endif EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void) { return OPENSSL_zalloc(sizeof(EVP_ENCODE_CTX)); } void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx) { OPENSSL_free(ctx); } int EVP_ENCODE_CTX_copy(EVP_ENCODE_CTX *dctx, const EVP_ENCODE_CTX *sctx) { memcpy(dctx, sctx, sizeof(EVP_ENCODE_CTX)); return 1; } int EVP_ENCODE_CTX_num(EVP_ENCODE_CTX *ctx) { return ctx->num; } void evp_encode_ctx_set_flags(EVP_ENCODE_CTX *ctx, unsigned int flags) { ctx->flags = flags; } void EVP_EncodeInit(EVP_ENCODE_CTX *ctx) { ctx->length = 48; ctx->num = 0; ctx->line_num = 0; ctx->flags = 0; } int EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int i, j; size_t total = 0; *outl = 0; if (inl <= 0) return 0; OPENSSL_assert(ctx->length <= (int)sizeof(ctx->enc_data)); if (ctx->length - ctx->num > inl) { memcpy(&(ctx->enc_data[ctx->num]), in, inl); ctx->num += inl; return 1; } if (ctx->num != 0) { i = ctx->length - ctx->num; memcpy(&(ctx->enc_data[ctx->num]), in, i); in += i; inl -= i; j = evp_encodeblock_int(ctx, out, ctx->enc_data, ctx->length); ctx->num = 0; out += j; total = j; if ((ctx->flags & EVP_ENCODE_CTX_NO_NEWLINES) == 0) { *(out++) = '\n'; total++; } *out = '\0'; } while (inl >= ctx->length && total <= INT_MAX) { j = evp_encodeblock_int(ctx, out, in, ctx->length); in += ctx->length; inl -= ctx->length; out += j; total += j; if ((ctx->flags & EVP_ENCODE_CTX_NO_NEWLINES) == 0) { *(out++) = '\n'; total++; } *out = '\0'; } if (total > INT_MAX) { /* Too much output data! */ *outl = 0; return 0; } if (inl != 0) memcpy(&(ctx->enc_data[0]), in, inl); ctx->num = inl; *outl = total; return 1; } void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl) { unsigned int ret = 0; if (ctx->num != 0) { ret = evp_encodeblock_int(ctx, out, ctx->enc_data, ctx->num); if ((ctx->flags & EVP_ENCODE_CTX_NO_NEWLINES) == 0) out[ret++] = '\n'; out[ret] = '\0'; ctx->num = 0; } *outl = ret; } static int evp_encodeblock_int(EVP_ENCODE_CTX *ctx, unsigned char *t, const unsigned char *f, int dlen) { int i, ret = 0; unsigned long l; const unsigned char *table; if (ctx != NULL && (ctx->flags & EVP_ENCODE_CTX_USE_SRP_ALPHABET) != 0) table = srpdata_bin2ascii; else table = data_bin2ascii; for (i = dlen; i > 0; i -= 3) { if (i >= 3) { l = (((unsigned long)f[0]) << 16L) | (((unsigned long)f[1]) << 8L) | f[2]; *(t++) = conv_bin2ascii(l >> 18L, table); *(t++) = conv_bin2ascii(l >> 12L, table); *(t++) = conv_bin2ascii(l >> 6L, table); *(t++) = conv_bin2ascii(l, table); } else { l = ((unsigned long)f[0]) << 16L; if (i == 2) l |= ((unsigned long)f[1] << 8L); *(t++) = conv_bin2ascii(l >> 18L, table); *(t++) = conv_bin2ascii(l >> 12L, table); *(t++) = (i == 1) ? '=' : conv_bin2ascii(l >> 6L, table); *(t++) = '='; } ret += 4; f += 3; } *t = '\0'; return ret; } int EVP_EncodeBlock(unsigned char *t, const unsigned char *f, int dlen) { return evp_encodeblock_int(NULL, t, f, dlen); } void EVP_DecodeInit(EVP_ENCODE_CTX *ctx) { /* Only ctx->num and ctx->flags are used during decoding. */ ctx->num = 0; ctx->length = 0; ctx->line_num = 0; ctx->flags = 0; } /*- * -1 for error * 0 for last line * 1 for full line * * Note: even though EVP_DecodeUpdate attempts to detect and report end of * content, the context doesn't currently remember it and will accept more data * in the next call. Therefore, the caller is responsible for checking and * rejecting a 0 return value in the middle of content. * * Note: even though EVP_DecodeUpdate has historically tried to detect end of * content based on line length, this has never worked properly. Therefore, * we now return 0 when one of the following is true: * - Padding or B64_EOF was detected and the last block is complete. * - Input has zero-length. * -1 is returned if: * - Invalid characters are detected. * - There is extra trailing padding, or data after padding. * - B64_EOF is detected after an incomplete base64 block. */ int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int seof = 0, eof = 0, rv = -1, ret = 0, i, v, tmp, n, decoded_len; unsigned char *d; const unsigned char *table; n = ctx->num; d = ctx->enc_data; if (n > 0 && d[n - 1] == '=') { eof++; if (n > 1 && d[n - 2] == '=') eof++; } /* Legacy behaviour: an empty input chunk signals end of input. */ if (inl == 0) { rv = 0; goto end; } if ((ctx->flags & EVP_ENCODE_CTX_USE_SRP_ALPHABET) != 0) table = srpdata_ascii2bin; else table = data_ascii2bin; for (i = 0; i < inl; i++) { tmp = *(in++); v = conv_ascii2bin(tmp, table); if (v == B64_ERROR) { rv = -1; goto end; } if (tmp == '=') { eof++; } else if (eof > 0 && B64_BASE64(v)) { /* More data after padding. */ rv = -1; goto end; } if (eof > 2) { rv = -1; goto end; } if (v == B64_EOF) { seof = 1; goto tail; } /* Only save valid base64 characters. */ if (B64_BASE64(v)) { if (n >= 64) { /* * We increment n once per loop, and empty the buffer as soon as * we reach 64 characters, so this can only happen if someone's * manually messed with the ctx. Refuse to write any more data. */ rv = -1; goto end; } OPENSSL_assert(n < (int)sizeof(ctx->enc_data)); d[n++] = tmp; } if (n == 64) { decoded_len = evp_decodeblock_int(ctx, out, d, n); n = 0; if (decoded_len < 0 || eof > decoded_len) { rv = -1; goto end; } ret += decoded_len - eof; out += decoded_len - eof; } } /* * Legacy behaviour: if the current line is a full base64-block (i.e., has * 0 mod 4 base64 characters), it is processed immediately. We keep this * behaviour as applications may not be calling EVP_DecodeFinal properly. */ tail: if (n > 0) { if ((n & 3) == 0) { decoded_len = evp_decodeblock_int(ctx, out, d, n); n = 0; if (decoded_len < 0 || eof > decoded_len) { rv = -1; goto end; } ret += (decoded_len - eof); } else if (seof) { /* EOF in the middle of a base64 block. */ rv = -1; goto end; } } rv = seof || (n == 0 && eof) ? 0 : 1; end: /* Legacy behaviour. This should probably rather be zeroed on error. */ *outl = ret; ctx->num = n; return rv; } static int evp_decodeblock_int(EVP_ENCODE_CTX *ctx, unsigned char *t, const unsigned char *f, int n) { int i, ret = 0, a, b, c, d; unsigned long l; const unsigned char *table; if (ctx != NULL && (ctx->flags & EVP_ENCODE_CTX_USE_SRP_ALPHABET) != 0) table = srpdata_ascii2bin; else table = data_ascii2bin; /* trim whitespace from the start of the line. */ while ((n > 0) && (conv_ascii2bin(*f, table) == B64_WS)) { f++; n--; } /* * strip off stuff at the end of the line ascii2bin values B64_WS, * B64_EOLN, B64_EOLN and B64_EOF */ while ((n > 3) && (B64_NOT_BASE64(conv_ascii2bin(f[n - 1], table)))) n--; if (n % 4 != 0) return -1; for (i = 0; i < n; i += 4) { a = conv_ascii2bin(*(f++), table); b = conv_ascii2bin(*(f++), table); c = conv_ascii2bin(*(f++), table); d = conv_ascii2bin(*(f++), table); if ((a & 0x80) || (b & 0x80) || (c & 0x80) || (d & 0x80)) return -1; l = ((((unsigned long)a) << 18L) | (((unsigned long)b) << 12L) | (((unsigned long)c) << 6L) | (((unsigned long)d))); *(t++) = (unsigned char)(l >> 16L) & 0xff; *(t++) = (unsigned char)(l >> 8L) & 0xff; *(t++) = (unsigned char)(l) & 0xff; ret += 3; } return ret; } int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n) { return evp_decodeblock_int(NULL, t, f, n); } int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl) { int i; *outl = 0; if (ctx->num != 0) { i = evp_decodeblock_int(ctx, out, ctx->enc_data, ctx->num); if (i < 0) return -1; ctx->num = 0; *outl = i; return 1; } else return 1; }
./openssl/crypto/evp/evp_rand.c
/* * Copyright 2020-2023 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 <stdio.h> #include <stdlib.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <openssl/core.h> #include <openssl/core_names.h> #include <openssl/crypto.h> #include "internal/cryptlib.h" #include "internal/numbers.h" #include "internal/provider.h" #include "internal/core.h" #include "crypto/evp.h" #include "evp_local.h" struct evp_rand_st { OSSL_PROVIDER *prov; int name_id; char *type_name; const char *description; CRYPTO_REF_COUNT refcnt; const OSSL_DISPATCH *dispatch; OSSL_FUNC_rand_newctx_fn *newctx; OSSL_FUNC_rand_freectx_fn *freectx; OSSL_FUNC_rand_instantiate_fn *instantiate; OSSL_FUNC_rand_uninstantiate_fn *uninstantiate; OSSL_FUNC_rand_generate_fn *generate; OSSL_FUNC_rand_reseed_fn *reseed; OSSL_FUNC_rand_nonce_fn *nonce; OSSL_FUNC_rand_enable_locking_fn *enable_locking; OSSL_FUNC_rand_lock_fn *lock; OSSL_FUNC_rand_unlock_fn *unlock; OSSL_FUNC_rand_gettable_params_fn *gettable_params; OSSL_FUNC_rand_gettable_ctx_params_fn *gettable_ctx_params; OSSL_FUNC_rand_settable_ctx_params_fn *settable_ctx_params; OSSL_FUNC_rand_get_params_fn *get_params; OSSL_FUNC_rand_get_ctx_params_fn *get_ctx_params; OSSL_FUNC_rand_set_ctx_params_fn *set_ctx_params; OSSL_FUNC_rand_verify_zeroization_fn *verify_zeroization; OSSL_FUNC_rand_get_seed_fn *get_seed; OSSL_FUNC_rand_clear_seed_fn *clear_seed; } /* EVP_RAND */ ; static int evp_rand_up_ref(void *vrand) { EVP_RAND *rand = (EVP_RAND *)vrand; int ref = 0; if (rand != NULL) return CRYPTO_UP_REF(&rand->refcnt, &ref); return 1; } static void evp_rand_free(void *vrand) { EVP_RAND *rand = (EVP_RAND *)vrand; int ref = 0; if (rand == NULL) return; CRYPTO_DOWN_REF(&rand->refcnt, &ref); if (ref > 0) return; OPENSSL_free(rand->type_name); ossl_provider_free(rand->prov); CRYPTO_FREE_REF(&rand->refcnt); OPENSSL_free(rand); } static void *evp_rand_new(void) { EVP_RAND *rand = OPENSSL_zalloc(sizeof(*rand)); if (rand == NULL) return NULL; if (!CRYPTO_NEW_REF(&rand->refcnt, 1)) { OPENSSL_free(rand); return NULL; } return rand; } /* Enable locking of the underlying DRBG/RAND if available */ int EVP_RAND_enable_locking(EVP_RAND_CTX *rand) { if (rand->meth->enable_locking != NULL) return rand->meth->enable_locking(rand->algctx); ERR_raise(ERR_LIB_EVP, EVP_R_LOCKING_NOT_SUPPORTED); return 0; } /* Lock the underlying DRBG/RAND if available */ static int evp_rand_lock(EVP_RAND_CTX *rand) { if (rand->meth->lock != NULL) return rand->meth->lock(rand->algctx); return 1; } /* Unlock the underlying DRBG/RAND if available */ static void evp_rand_unlock(EVP_RAND_CTX *rand) { if (rand->meth->unlock != NULL) rand->meth->unlock(rand->algctx); } static void *evp_rand_from_algorithm(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { const OSSL_DISPATCH *fns = algodef->implementation; EVP_RAND *rand = NULL; int fnrandcnt = 0, fnctxcnt = 0, fnlockcnt = 0, fnenablelockcnt = 0; #ifdef FIPS_MODULE int fnzeroizecnt = 0; #endif if ((rand = evp_rand_new()) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return NULL; } rand->name_id = name_id; if ((rand->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) { evp_rand_free(rand); return NULL; } rand->description = algodef->algorithm_description; rand->dispatch = fns; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_RAND_NEWCTX: if (rand->newctx != NULL) break; rand->newctx = OSSL_FUNC_rand_newctx(fns); fnctxcnt++; break; case OSSL_FUNC_RAND_FREECTX: if (rand->freectx != NULL) break; rand->freectx = OSSL_FUNC_rand_freectx(fns); fnctxcnt++; break; case OSSL_FUNC_RAND_INSTANTIATE: if (rand->instantiate != NULL) break; rand->instantiate = OSSL_FUNC_rand_instantiate(fns); fnrandcnt++; break; case OSSL_FUNC_RAND_UNINSTANTIATE: if (rand->uninstantiate != NULL) break; rand->uninstantiate = OSSL_FUNC_rand_uninstantiate(fns); fnrandcnt++; break; case OSSL_FUNC_RAND_GENERATE: if (rand->generate != NULL) break; rand->generate = OSSL_FUNC_rand_generate(fns); fnrandcnt++; break; case OSSL_FUNC_RAND_RESEED: if (rand->reseed != NULL) break; rand->reseed = OSSL_FUNC_rand_reseed(fns); break; case OSSL_FUNC_RAND_NONCE: if (rand->nonce != NULL) break; rand->nonce = OSSL_FUNC_rand_nonce(fns); break; case OSSL_FUNC_RAND_ENABLE_LOCKING: if (rand->enable_locking != NULL) break; rand->enable_locking = OSSL_FUNC_rand_enable_locking(fns); fnenablelockcnt++; break; case OSSL_FUNC_RAND_LOCK: if (rand->lock != NULL) break; rand->lock = OSSL_FUNC_rand_lock(fns); fnlockcnt++; break; case OSSL_FUNC_RAND_UNLOCK: if (rand->unlock != NULL) break; rand->unlock = OSSL_FUNC_rand_unlock(fns); fnlockcnt++; break; case OSSL_FUNC_RAND_GETTABLE_PARAMS: if (rand->gettable_params != NULL) break; rand->gettable_params = OSSL_FUNC_rand_gettable_params(fns); break; case OSSL_FUNC_RAND_GETTABLE_CTX_PARAMS: if (rand->gettable_ctx_params != NULL) break; rand->gettable_ctx_params = OSSL_FUNC_rand_gettable_ctx_params(fns); break; case OSSL_FUNC_RAND_SETTABLE_CTX_PARAMS: if (rand->settable_ctx_params != NULL) break; rand->settable_ctx_params = OSSL_FUNC_rand_settable_ctx_params(fns); break; case OSSL_FUNC_RAND_GET_PARAMS: if (rand->get_params != NULL) break; rand->get_params = OSSL_FUNC_rand_get_params(fns); break; case OSSL_FUNC_RAND_GET_CTX_PARAMS: if (rand->get_ctx_params != NULL) break; rand->get_ctx_params = OSSL_FUNC_rand_get_ctx_params(fns); fnctxcnt++; break; case OSSL_FUNC_RAND_SET_CTX_PARAMS: if (rand->set_ctx_params != NULL) break; rand->set_ctx_params = OSSL_FUNC_rand_set_ctx_params(fns); break; case OSSL_FUNC_RAND_VERIFY_ZEROIZATION: if (rand->verify_zeroization != NULL) break; rand->verify_zeroization = OSSL_FUNC_rand_verify_zeroization(fns); #ifdef FIPS_MODULE fnzeroizecnt++; #endif break; case OSSL_FUNC_RAND_GET_SEED: if (rand->get_seed != NULL) break; rand->get_seed = OSSL_FUNC_rand_get_seed(fns); break; case OSSL_FUNC_RAND_CLEAR_SEED: if (rand->clear_seed != NULL) break; rand->clear_seed = OSSL_FUNC_rand_clear_seed(fns); break; } } /* * In order to be a consistent set of functions we must have at least * a complete set of "rand" functions and a complete set of context * management functions. In FIPS mode, we also require the zeroization * verification function. * * In addition, if locking can be enabled, we need a complete set of * locking functions. */ if (fnrandcnt != 3 || fnctxcnt != 3 || (fnenablelockcnt != 0 && fnenablelockcnt != 1) || (fnlockcnt != 0 && fnlockcnt != 2) #ifdef FIPS_MODULE || fnzeroizecnt != 1 #endif ) { evp_rand_free(rand); ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS); return NULL; } if (prov != NULL && !ossl_provider_up_ref(prov)) { evp_rand_free(rand); ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return NULL; } rand->prov = prov; return rand; } EVP_RAND *EVP_RAND_fetch(OSSL_LIB_CTX *libctx, const char *algorithm, const char *properties) { return evp_generic_fetch(libctx, OSSL_OP_RAND, algorithm, properties, evp_rand_from_algorithm, evp_rand_up_ref, evp_rand_free); } int EVP_RAND_up_ref(EVP_RAND *rand) { return evp_rand_up_ref(rand); } void EVP_RAND_free(EVP_RAND *rand) { evp_rand_free(rand); } int evp_rand_get_number(const EVP_RAND *rand) { return rand->name_id; } const char *EVP_RAND_get0_name(const EVP_RAND *rand) { return rand->type_name; } const char *EVP_RAND_get0_description(const EVP_RAND *rand) { return rand->description; } int EVP_RAND_is_a(const EVP_RAND *rand, const char *name) { return rand != NULL && evp_is_a(rand->prov, rand->name_id, NULL, name); } const OSSL_PROVIDER *EVP_RAND_get0_provider(const EVP_RAND *rand) { return rand->prov; } int EVP_RAND_get_params(EVP_RAND *rand, OSSL_PARAM params[]) { if (rand->get_params != NULL) return rand->get_params(params); return 1; } int EVP_RAND_CTX_up_ref(EVP_RAND_CTX *ctx) { int ref = 0; return CRYPTO_UP_REF(&ctx->refcnt, &ref); } EVP_RAND_CTX *EVP_RAND_CTX_new(EVP_RAND *rand, EVP_RAND_CTX *parent) { EVP_RAND_CTX *ctx; void *parent_ctx = NULL; const OSSL_DISPATCH *parent_dispatch = NULL; if (rand == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_NULL_ALGORITHM); return NULL; } ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) return NULL; if (!CRYPTO_NEW_REF(&ctx->refcnt, 1)) { OPENSSL_free(ctx); return NULL; } if (parent != NULL) { if (!EVP_RAND_CTX_up_ref(parent)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); CRYPTO_FREE_REF(&ctx->refcnt); OPENSSL_free(ctx); return NULL; } parent_ctx = parent->algctx; parent_dispatch = parent->meth->dispatch; } if ((ctx->algctx = rand->newctx(ossl_provider_ctx(rand->prov), parent_ctx, parent_dispatch)) == NULL || !EVP_RAND_up_ref(rand)) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); rand->freectx(ctx->algctx); CRYPTO_FREE_REF(&ctx->refcnt); OPENSSL_free(ctx); EVP_RAND_CTX_free(parent); return NULL; } ctx->meth = rand; ctx->parent = parent; return ctx; } void EVP_RAND_CTX_free(EVP_RAND_CTX *ctx) { int ref = 0; EVP_RAND_CTX *parent; if (ctx == NULL) return; CRYPTO_DOWN_REF(&ctx->refcnt, &ref); if (ref > 0) return; parent = ctx->parent; ctx->meth->freectx(ctx->algctx); ctx->algctx = NULL; EVP_RAND_free(ctx->meth); CRYPTO_FREE_REF(&ctx->refcnt); OPENSSL_free(ctx); EVP_RAND_CTX_free(parent); } EVP_RAND *EVP_RAND_CTX_get0_rand(EVP_RAND_CTX *ctx) { return ctx->meth; } static int evp_rand_get_ctx_params_locked(EVP_RAND_CTX *ctx, OSSL_PARAM params[]) { return ctx->meth->get_ctx_params(ctx->algctx, params); } int EVP_RAND_CTX_get_params(EVP_RAND_CTX *ctx, OSSL_PARAM params[]) { int res; if (!evp_rand_lock(ctx)) return 0; res = evp_rand_get_ctx_params_locked(ctx, params); evp_rand_unlock(ctx); return res; } static int evp_rand_set_ctx_params_locked(EVP_RAND_CTX *ctx, const OSSL_PARAM params[]) { if (ctx->meth->set_ctx_params != NULL) return ctx->meth->set_ctx_params(ctx->algctx, params); return 1; } int EVP_RAND_CTX_set_params(EVP_RAND_CTX *ctx, const OSSL_PARAM params[]) { int res; if (!evp_rand_lock(ctx)) return 0; res = evp_rand_set_ctx_params_locked(ctx, params); evp_rand_unlock(ctx); return res; } const OSSL_PARAM *EVP_RAND_gettable_params(const EVP_RAND *rand) { if (rand->gettable_params == NULL) return NULL; return rand->gettable_params(ossl_provider_ctx(EVP_RAND_get0_provider(rand))); } const OSSL_PARAM *EVP_RAND_gettable_ctx_params(const EVP_RAND *rand) { void *provctx; if (rand->gettable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_RAND_get0_provider(rand)); return rand->gettable_ctx_params(NULL, provctx); } const OSSL_PARAM *EVP_RAND_settable_ctx_params(const EVP_RAND *rand) { void *provctx; if (rand->settable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_RAND_get0_provider(rand)); return rand->settable_ctx_params(NULL, provctx); } const OSSL_PARAM *EVP_RAND_CTX_gettable_params(EVP_RAND_CTX *ctx) { void *provctx; if (ctx->meth->gettable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_RAND_get0_provider(ctx->meth)); return ctx->meth->gettable_ctx_params(ctx->algctx, provctx); } const OSSL_PARAM *EVP_RAND_CTX_settable_params(EVP_RAND_CTX *ctx) { void *provctx; if (ctx->meth->settable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_RAND_get0_provider(ctx->meth)); return ctx->meth->settable_ctx_params(ctx->algctx, provctx); } void EVP_RAND_do_all_provided(OSSL_LIB_CTX *libctx, void (*fn)(EVP_RAND *rand, void *arg), void *arg) { evp_generic_do_all(libctx, OSSL_OP_RAND, (void (*)(void *, void *))fn, arg, evp_rand_from_algorithm, evp_rand_up_ref, evp_rand_free); } int EVP_RAND_names_do_all(const EVP_RAND *rand, void (*fn)(const char *name, void *data), void *data) { if (rand->prov != NULL) return evp_names_do_all(rand->prov, rand->name_id, fn, data); return 1; } static int evp_rand_instantiate_locked (EVP_RAND_CTX *ctx, unsigned int strength, int prediction_resistance, const unsigned char *pstr, size_t pstr_len, const OSSL_PARAM params[]) { return ctx->meth->instantiate(ctx->algctx, strength, prediction_resistance, pstr, pstr_len, params); } int EVP_RAND_instantiate(EVP_RAND_CTX *ctx, unsigned int strength, int prediction_resistance, const unsigned char *pstr, size_t pstr_len, const OSSL_PARAM params[]) { int res; if (!evp_rand_lock(ctx)) return 0; res = evp_rand_instantiate_locked(ctx, strength, prediction_resistance, pstr, pstr_len, params); evp_rand_unlock(ctx); return res; } static int evp_rand_uninstantiate_locked(EVP_RAND_CTX *ctx) { return ctx->meth->uninstantiate(ctx->algctx); } int EVP_RAND_uninstantiate(EVP_RAND_CTX *ctx) { int res; if (!evp_rand_lock(ctx)) return 0; res = evp_rand_uninstantiate_locked(ctx); evp_rand_unlock(ctx); return res; } static int evp_rand_generate_locked(EVP_RAND_CTX *ctx, unsigned char *out, size_t outlen, unsigned int strength, int prediction_resistance, const unsigned char *addin, size_t addin_len) { size_t chunk, max_request = 0; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_size_t(OSSL_RAND_PARAM_MAX_REQUEST, &max_request); if (!evp_rand_get_ctx_params_locked(ctx, params) || max_request == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_UNABLE_TO_GET_MAXIMUM_REQUEST_SIZE); return 0; } for (; outlen > 0; outlen -= chunk, out += chunk) { chunk = outlen > max_request ? max_request : outlen; if (!ctx->meth->generate(ctx->algctx, out, chunk, strength, prediction_resistance, addin, addin_len)) { ERR_raise(ERR_LIB_EVP, EVP_R_GENERATE_ERROR); return 0; } /* * Prediction resistance is only relevant the first time around, * subsequently, the DRBG has already been properly reseeded. */ prediction_resistance = 0; } return 1; } int EVP_RAND_generate(EVP_RAND_CTX *ctx, unsigned char *out, size_t outlen, unsigned int strength, int prediction_resistance, const unsigned char *addin, size_t addin_len) { int res; if (!evp_rand_lock(ctx)) return 0; res = evp_rand_generate_locked(ctx, out, outlen, strength, prediction_resistance, addin, addin_len); evp_rand_unlock(ctx); return res; } static int evp_rand_reseed_locked(EVP_RAND_CTX *ctx, int prediction_resistance, const unsigned char *ent, size_t ent_len, const unsigned char *addin, size_t addin_len) { if (ctx->meth->reseed != NULL) return ctx->meth->reseed(ctx->algctx, prediction_resistance, ent, ent_len, addin, addin_len); return 1; } int EVP_RAND_reseed(EVP_RAND_CTX *ctx, int prediction_resistance, const unsigned char *ent, size_t ent_len, const unsigned char *addin, size_t addin_len) { int res; if (!evp_rand_lock(ctx)) return 0; res = evp_rand_reseed_locked(ctx, prediction_resistance, ent, ent_len, addin, addin_len); evp_rand_unlock(ctx); return res; } static unsigned int evp_rand_strength_locked(EVP_RAND_CTX *ctx) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; unsigned int strength = 0; params[0] = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, &strength); if (!evp_rand_get_ctx_params_locked(ctx, params)) return 0; return strength; } unsigned int EVP_RAND_get_strength(EVP_RAND_CTX *ctx) { unsigned int res; if (!evp_rand_lock(ctx)) return 0; res = evp_rand_strength_locked(ctx); evp_rand_unlock(ctx); return res; } static int evp_rand_nonce_locked(EVP_RAND_CTX *ctx, unsigned char *out, size_t outlen) { unsigned int str = evp_rand_strength_locked(ctx); if (ctx->meth->nonce == NULL) return 0; if (ctx->meth->nonce(ctx->algctx, out, str, outlen, outlen)) return 1; return evp_rand_generate_locked(ctx, out, outlen, str, 0, NULL, 0); } int EVP_RAND_nonce(EVP_RAND_CTX *ctx, unsigned char *out, size_t outlen) { int res; if (!evp_rand_lock(ctx)) return 0; res = evp_rand_nonce_locked(ctx, out, outlen); evp_rand_unlock(ctx); return res; } int EVP_RAND_get_state(EVP_RAND_CTX *ctx) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; int state; params[0] = OSSL_PARAM_construct_int(OSSL_RAND_PARAM_STATE, &state); if (!EVP_RAND_CTX_get_params(ctx, params)) state = EVP_RAND_STATE_ERROR; return state; } static int evp_rand_verify_zeroization_locked(EVP_RAND_CTX *ctx) { if (ctx->meth->verify_zeroization != NULL) return ctx->meth->verify_zeroization(ctx->algctx); return 0; } int EVP_RAND_verify_zeroization(EVP_RAND_CTX *ctx) { int res; if (!evp_rand_lock(ctx)) return 0; res = evp_rand_verify_zeroization_locked(ctx); evp_rand_unlock(ctx); return res; } int evp_rand_can_seed(EVP_RAND_CTX *ctx) { return ctx->meth->get_seed != NULL; } static size_t evp_rand_get_seed_locked(EVP_RAND_CTX *ctx, unsigned char **buffer, int entropy, size_t min_len, size_t max_len, int prediction_resistance, const unsigned char *adin, size_t adin_len) { if (ctx->meth->get_seed != NULL) return ctx->meth->get_seed(ctx->algctx, buffer, entropy, min_len, max_len, prediction_resistance, adin, adin_len); return 0; } size_t evp_rand_get_seed(EVP_RAND_CTX *ctx, unsigned char **buffer, int entropy, size_t min_len, size_t max_len, int prediction_resistance, const unsigned char *adin, size_t adin_len) { int res; if (!evp_rand_lock(ctx)) return 0; res = evp_rand_get_seed_locked(ctx, buffer, entropy, min_len, max_len, prediction_resistance, adin, adin_len); evp_rand_unlock(ctx); return res; } static void evp_rand_clear_seed_locked(EVP_RAND_CTX *ctx, unsigned char *buffer, size_t b_len) { if (ctx->meth->clear_seed != NULL) ctx->meth->clear_seed(ctx->algctx, buffer, b_len); } void evp_rand_clear_seed(EVP_RAND_CTX *ctx, unsigned char *buffer, size_t b_len) { if (!evp_rand_lock(ctx)) return; evp_rand_clear_seed_locked(ctx, buffer, b_len); evp_rand_unlock(ctx); }
./openssl/crypto/evp/legacy_md5.c
/* * Copyright 2015-2021 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 */ /* * MD5 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/md5.h> #include "crypto/evp.h" #include "legacy_meth.h" IMPLEMENT_LEGACY_EVP_MD_METH(md5, MD5) static const EVP_MD md5_md = { NID_md5, NID_md5WithRSAEncryption, MD5_DIGEST_LENGTH, 0, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(md5_init, md5_update, md5_final, NULL, MD5_CBLOCK) }; const EVP_MD *EVP_md5(void) { return &md5_md; }
./openssl/crypto/evp/p_sign.c
/* * Copyright 1995-2023 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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include "crypto/evp.h" int EVP_SignFinal_ex(EVP_MD_CTX *ctx, unsigned char *sigret, unsigned int *siglen, EVP_PKEY *pkey, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char m[EVP_MAX_MD_SIZE]; unsigned int m_len = 0; int i = 0; size_t sltmp; EVP_PKEY_CTX *pkctx = NULL; *siglen = 0; if (EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_FINALISE)) { if (!EVP_DigestFinal_ex(ctx, m, &m_len)) goto err; } else { int rv = 0; EVP_MD_CTX *tmp_ctx = EVP_MD_CTX_new(); if (tmp_ctx == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return 0; } rv = EVP_MD_CTX_copy_ex(tmp_ctx, ctx); if (rv) rv = EVP_DigestFinal_ex(tmp_ctx, m, &m_len); else rv = EVP_DigestFinal_ex(ctx, m, &m_len); EVP_MD_CTX_free(tmp_ctx); if (!rv) return 0; } sltmp = (size_t)EVP_PKEY_get_size(pkey); i = 0; pkctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (pkctx == NULL) goto err; if (EVP_PKEY_sign_init(pkctx) <= 0) goto err; if (EVP_PKEY_CTX_set_signature_md(pkctx, EVP_MD_CTX_get0_md(ctx)) <= 0) goto err; if (EVP_PKEY_sign(pkctx, sigret, &sltmp, m, m_len) <= 0) goto err; *siglen = sltmp; i = 1; err: EVP_PKEY_CTX_free(pkctx); return i; } int EVP_SignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, unsigned int *siglen, EVP_PKEY *pkey) { return EVP_SignFinal_ex(ctx, sigret, siglen, pkey, NULL, NULL); }
./openssl/crypto/evp/e_sm4.c
/* * Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * Ported from Ribose contributions from Botan. * * 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 "internal/deprecated.h" #include "internal/cryptlib.h" #ifndef OPENSSL_NO_SM4 # include <openssl/evp.h> # include <openssl/modes.h> # include "crypto/sm4.h" # include "crypto/evp.h" # include "crypto/sm4_platform.h" # include "evp_local.h" typedef struct { union { OSSL_UNION_ALIGN; SM4_KEY ks; } ks; block128_f block; union { ecb128_f ecb; cbc128_f cbc; ctr128_f ctr; } stream; } EVP_SM4_KEY; # define BLOCK_CIPHER_generic(nid,blocksize,ivlen,nmode,mode,MODE,flags) \ static const EVP_CIPHER sm4_##mode = { \ nid##_##nmode,blocksize,128/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ sm4_init_key, \ sm4_##mode##_cipher, \ NULL, \ sizeof(EVP_SM4_KEY), \ NULL,NULL,NULL,NULL }; \ const EVP_CIPHER *EVP_sm4_##mode(void) \ { return &sm4_##mode; } #define DEFINE_BLOCK_CIPHERS(nid,flags) \ BLOCK_CIPHER_generic(nid,16,16,cbc,cbc,CBC,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,16,0,ecb,ecb,ECB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,1,16,ofb128,ofb,OFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,1,16,cfb128,cfb,CFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,1,16,ctr,ctr,CTR,flags) static int sm4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int mode; EVP_SM4_KEY *dat = EVP_C_DATA(EVP_SM4_KEY,ctx); mode = EVP_CIPHER_CTX_get_mode(ctx); if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE) && !enc) { #ifdef HWSM4_CAPABLE if (HWSM4_CAPABLE) { HWSM4_set_decrypt_key(key, &dat->ks.ks); dat->block = (block128_f) HWSM4_decrypt; dat->stream.cbc = NULL; # ifdef HWSM4_cbc_encrypt if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) HWSM4_cbc_encrypt; # endif # ifdef HWSM4_ecb_encrypt if (mode == EVP_CIPH_ECB_MODE) dat->stream.ecb = (ecb128_f) HWSM4_ecb_encrypt; # endif } else #endif #ifdef VPSM4_CAPABLE if (VPSM4_CAPABLE) { vpsm4_set_decrypt_key(key, &dat->ks.ks); dat->block = (block128_f) vpsm4_decrypt; dat->stream.cbc = NULL; if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) vpsm4_cbc_encrypt; else if (mode == EVP_CIPH_ECB_MODE) dat->stream.ecb = (ecb128_f) vpsm4_ecb_encrypt; } else #endif { dat->block = (block128_f) ossl_sm4_decrypt; ossl_sm4_set_key(key, EVP_CIPHER_CTX_get_cipher_data(ctx)); } } else #ifdef HWSM4_CAPABLE if (HWSM4_CAPABLE) { HWSM4_set_encrypt_key(key, &dat->ks.ks); dat->block = (block128_f) HWSM4_encrypt; dat->stream.cbc = NULL; # ifdef HWSM4_cbc_encrypt if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) HWSM4_cbc_encrypt; else # endif # ifdef HWSM4_ecb_encrypt if (mode == EVP_CIPH_ECB_MODE) dat->stream.ecb = (ecb128_f) HWSM4_ecb_encrypt; else # endif # ifdef HWSM4_ctr32_encrypt_blocks if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) HWSM4_ctr32_encrypt_blocks; else # endif (void)0; /* terminate potentially open 'else' */ } else #endif #ifdef VPSM4_CAPABLE if (VPSM4_CAPABLE) { vpsm4_set_encrypt_key(key, &dat->ks.ks); dat->block = (block128_f) vpsm4_encrypt; dat->stream.cbc = NULL; if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) vpsm4_cbc_encrypt; else if (mode == EVP_CIPH_ECB_MODE) dat->stream.ecb = (ecb128_f) vpsm4_ecb_encrypt; else if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) vpsm4_ctr32_encrypt_blocks; } else #endif { dat->block = (block128_f) ossl_sm4_encrypt; ossl_sm4_set_key(key, EVP_CIPHER_CTX_get_cipher_data(ctx)); } return 1; } static int sm4_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_SM4_KEY *dat = EVP_C_DATA(EVP_SM4_KEY,ctx); if (dat->stream.cbc) (*dat->stream.cbc) (in, out, len, &dat->ks.ks, ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); else if (EVP_CIPHER_CTX_is_encrypting(ctx)) CRYPTO_cbc128_encrypt(in, out, len, &dat->ks, ctx->iv, dat->block); else CRYPTO_cbc128_decrypt(in, out, len, &dat->ks, ctx->iv, dat->block); return 1; } static int sm4_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_SM4_KEY *dat = EVP_C_DATA(EVP_SM4_KEY,ctx); int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_cfb128_encrypt(in, out, len, &dat->ks, ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } static int sm4_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { size_t bl = EVP_CIPHER_CTX_get_block_size(ctx); size_t i; EVP_SM4_KEY *dat = EVP_C_DATA(EVP_SM4_KEY,ctx); if (len < bl) return 1; if (dat->stream.ecb != NULL) (*dat->stream.ecb) (in, out, len, &dat->ks.ks, EVP_CIPHER_CTX_is_encrypting(ctx)); else for (i = 0, len -= bl; i <= len; i += bl) (*dat->block) (in + i, out + i, &dat->ks); return 1; } static int sm4_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_SM4_KEY *dat = EVP_C_DATA(EVP_SM4_KEY,ctx); int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_ofb128_encrypt(in, out, len, &dat->ks, ctx->iv, &num, dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } static int sm4_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { int n = EVP_CIPHER_CTX_get_num(ctx); unsigned int num; EVP_SM4_KEY *dat = EVP_C_DATA(EVP_SM4_KEY,ctx); if (n < 0) return 0; num = (unsigned int)n; if (dat->stream.ctr) CRYPTO_ctr128_encrypt_ctr32(in, out, len, &dat->ks, ctx->iv, EVP_CIPHER_CTX_buf_noconst(ctx), &num, dat->stream.ctr); else CRYPTO_ctr128_encrypt(in, out, len, &dat->ks, ctx->iv, EVP_CIPHER_CTX_buf_noconst(ctx), &num, dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } DEFINE_BLOCK_CIPHERS(NID_sm4, 0) #endif
./openssl/crypto/evp/signature.c
/* * Copyright 2006-2023 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 <stdio.h> #include <stdlib.h> #include <openssl/objects.h> #include <openssl/evp.h> #include "internal/numbers.h" /* includes SIZE_MAX */ #include "internal/cryptlib.h" #include "internal/provider.h" #include "internal/core.h" #include "crypto/evp.h" #include "evp_local.h" static EVP_SIGNATURE *evp_signature_new(OSSL_PROVIDER *prov) { EVP_SIGNATURE *signature = OPENSSL_zalloc(sizeof(EVP_SIGNATURE)); if (signature == NULL) return NULL; if (!CRYPTO_NEW_REF(&signature->refcnt, 1)) { OPENSSL_free(signature); return NULL; } signature->prov = prov; ossl_provider_up_ref(prov); return signature; } static void *evp_signature_from_algorithm(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { const OSSL_DISPATCH *fns = algodef->implementation; EVP_SIGNATURE *signature = NULL; int ctxfncnt = 0, signfncnt = 0, verifyfncnt = 0, verifyrecfncnt = 0; int digsignfncnt = 0, digverifyfncnt = 0; int gparamfncnt = 0, sparamfncnt = 0, gmdparamfncnt = 0, smdparamfncnt = 0; if ((signature = evp_signature_new(prov)) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); goto err; } signature->name_id = name_id; if ((signature->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) goto err; signature->description = algodef->algorithm_description; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_SIGNATURE_NEWCTX: if (signature->newctx != NULL) break; signature->newctx = OSSL_FUNC_signature_newctx(fns); ctxfncnt++; break; case OSSL_FUNC_SIGNATURE_SIGN_INIT: if (signature->sign_init != NULL) break; signature->sign_init = OSSL_FUNC_signature_sign_init(fns); signfncnt++; break; case OSSL_FUNC_SIGNATURE_SIGN: if (signature->sign != NULL) break; signature->sign = OSSL_FUNC_signature_sign(fns); signfncnt++; break; case OSSL_FUNC_SIGNATURE_VERIFY_INIT: if (signature->verify_init != NULL) break; signature->verify_init = OSSL_FUNC_signature_verify_init(fns); verifyfncnt++; break; case OSSL_FUNC_SIGNATURE_VERIFY: if (signature->verify != NULL) break; signature->verify = OSSL_FUNC_signature_verify(fns); verifyfncnt++; break; case OSSL_FUNC_SIGNATURE_VERIFY_RECOVER_INIT: if (signature->verify_recover_init != NULL) break; signature->verify_recover_init = OSSL_FUNC_signature_verify_recover_init(fns); verifyrecfncnt++; break; case OSSL_FUNC_SIGNATURE_VERIFY_RECOVER: if (signature->verify_recover != NULL) break; signature->verify_recover = OSSL_FUNC_signature_verify_recover(fns); verifyrecfncnt++; break; case OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT: if (signature->digest_sign_init != NULL) break; signature->digest_sign_init = OSSL_FUNC_signature_digest_sign_init(fns); break; case OSSL_FUNC_SIGNATURE_DIGEST_SIGN_UPDATE: if (signature->digest_sign_update != NULL) break; signature->digest_sign_update = OSSL_FUNC_signature_digest_sign_update(fns); digsignfncnt++; break; case OSSL_FUNC_SIGNATURE_DIGEST_SIGN_FINAL: if (signature->digest_sign_final != NULL) break; signature->digest_sign_final = OSSL_FUNC_signature_digest_sign_final(fns); digsignfncnt++; break; case OSSL_FUNC_SIGNATURE_DIGEST_SIGN: if (signature->digest_sign != NULL) break; signature->digest_sign = OSSL_FUNC_signature_digest_sign(fns); break; case OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT: if (signature->digest_verify_init != NULL) break; signature->digest_verify_init = OSSL_FUNC_signature_digest_verify_init(fns); break; case OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_UPDATE: if (signature->digest_verify_update != NULL) break; signature->digest_verify_update = OSSL_FUNC_signature_digest_verify_update(fns); digverifyfncnt++; break; case OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_FINAL: if (signature->digest_verify_final != NULL) break; signature->digest_verify_final = OSSL_FUNC_signature_digest_verify_final(fns); digverifyfncnt++; break; case OSSL_FUNC_SIGNATURE_DIGEST_VERIFY: if (signature->digest_verify != NULL) break; signature->digest_verify = OSSL_FUNC_signature_digest_verify(fns); break; case OSSL_FUNC_SIGNATURE_FREECTX: if (signature->freectx != NULL) break; signature->freectx = OSSL_FUNC_signature_freectx(fns); ctxfncnt++; break; case OSSL_FUNC_SIGNATURE_DUPCTX: if (signature->dupctx != NULL) break; signature->dupctx = OSSL_FUNC_signature_dupctx(fns); break; case OSSL_FUNC_SIGNATURE_GET_CTX_PARAMS: if (signature->get_ctx_params != NULL) break; signature->get_ctx_params = OSSL_FUNC_signature_get_ctx_params(fns); gparamfncnt++; break; case OSSL_FUNC_SIGNATURE_GETTABLE_CTX_PARAMS: if (signature->gettable_ctx_params != NULL) break; signature->gettable_ctx_params = OSSL_FUNC_signature_gettable_ctx_params(fns); gparamfncnt++; break; case OSSL_FUNC_SIGNATURE_SET_CTX_PARAMS: if (signature->set_ctx_params != NULL) break; signature->set_ctx_params = OSSL_FUNC_signature_set_ctx_params(fns); sparamfncnt++; break; case OSSL_FUNC_SIGNATURE_SETTABLE_CTX_PARAMS: if (signature->settable_ctx_params != NULL) break; signature->settable_ctx_params = OSSL_FUNC_signature_settable_ctx_params(fns); sparamfncnt++; break; case OSSL_FUNC_SIGNATURE_GET_CTX_MD_PARAMS: if (signature->get_ctx_md_params != NULL) break; signature->get_ctx_md_params = OSSL_FUNC_signature_get_ctx_md_params(fns); gmdparamfncnt++; break; case OSSL_FUNC_SIGNATURE_GETTABLE_CTX_MD_PARAMS: if (signature->gettable_ctx_md_params != NULL) break; signature->gettable_ctx_md_params = OSSL_FUNC_signature_gettable_ctx_md_params(fns); gmdparamfncnt++; break; case OSSL_FUNC_SIGNATURE_SET_CTX_MD_PARAMS: if (signature->set_ctx_md_params != NULL) break; signature->set_ctx_md_params = OSSL_FUNC_signature_set_ctx_md_params(fns); smdparamfncnt++; break; case OSSL_FUNC_SIGNATURE_SETTABLE_CTX_MD_PARAMS: if (signature->settable_ctx_md_params != NULL) break; signature->settable_ctx_md_params = OSSL_FUNC_signature_settable_ctx_md_params(fns); smdparamfncnt++; break; } } if (ctxfncnt != 2 || (signfncnt == 0 && verifyfncnt == 0 && verifyrecfncnt == 0 && digsignfncnt == 0 && digverifyfncnt == 0 && signature->digest_sign == NULL && signature->digest_verify == NULL) || (signfncnt != 0 && signfncnt != 2) || (verifyfncnt != 0 && verifyfncnt != 2) || (verifyrecfncnt != 0 && verifyrecfncnt != 2) || (digsignfncnt != 0 && digsignfncnt != 2) || (digsignfncnt == 2 && signature->digest_sign_init == NULL) || (digverifyfncnt != 0 && digverifyfncnt != 2) || (digverifyfncnt == 2 && signature->digest_verify_init == NULL) || (signature->digest_sign != NULL && signature->digest_sign_init == NULL) || (signature->digest_verify != NULL && signature->digest_verify_init == NULL) || (gparamfncnt != 0 && gparamfncnt != 2) || (sparamfncnt != 0 && sparamfncnt != 2) || (gmdparamfncnt != 0 && gmdparamfncnt != 2) || (smdparamfncnt != 0 && smdparamfncnt != 2)) { /* * In order to be a consistent set of functions we must have at least * a set of context functions (newctx and freectx) as well as a set of * "signature" functions: * (sign_init, sign) or * (verify_init verify) or * (verify_recover_init, verify_recover) or * (digest_sign_init, digest_sign_update, digest_sign_final) or * (digest_verify_init, digest_verify_update, digest_verify_final) or * (digest_sign_init, digest_sign) or * (digest_verify_init, digest_verify). * * set_ctx_params and settable_ctx_params are optional, but if one of * them is present then the other one must also be present. The same * applies to get_ctx_params and gettable_ctx_params. The same rules * apply to the "md_params" functions. The dupctx function is optional. */ ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS); goto err; } return signature; err: EVP_SIGNATURE_free(signature); return NULL; } void EVP_SIGNATURE_free(EVP_SIGNATURE *signature) { int i; if (signature == NULL) return; CRYPTO_DOWN_REF(&signature->refcnt, &i); if (i > 0) return; OPENSSL_free(signature->type_name); ossl_provider_free(signature->prov); CRYPTO_FREE_REF(&signature->refcnt); OPENSSL_free(signature); } int EVP_SIGNATURE_up_ref(EVP_SIGNATURE *signature) { int ref = 0; CRYPTO_UP_REF(&signature->refcnt, &ref); return 1; } OSSL_PROVIDER *EVP_SIGNATURE_get0_provider(const EVP_SIGNATURE *signature) { return signature->prov; } EVP_SIGNATURE *EVP_SIGNATURE_fetch(OSSL_LIB_CTX *ctx, const char *algorithm, const char *properties) { return evp_generic_fetch(ctx, OSSL_OP_SIGNATURE, algorithm, properties, evp_signature_from_algorithm, (int (*)(void *))EVP_SIGNATURE_up_ref, (void (*)(void *))EVP_SIGNATURE_free); } EVP_SIGNATURE *evp_signature_fetch_from_prov(OSSL_PROVIDER *prov, const char *algorithm, const char *properties) { return evp_generic_fetch_from_prov(prov, OSSL_OP_SIGNATURE, algorithm, properties, evp_signature_from_algorithm, (int (*)(void *))EVP_SIGNATURE_up_ref, (void (*)(void *))EVP_SIGNATURE_free); } int EVP_SIGNATURE_is_a(const EVP_SIGNATURE *signature, const char *name) { return signature != NULL && evp_is_a(signature->prov, signature->name_id, NULL, name); } int evp_signature_get_number(const EVP_SIGNATURE *signature) { return signature->name_id; } const char *EVP_SIGNATURE_get0_name(const EVP_SIGNATURE *signature) { return signature->type_name; } const char *EVP_SIGNATURE_get0_description(const EVP_SIGNATURE *signature) { return signature->description; } void EVP_SIGNATURE_do_all_provided(OSSL_LIB_CTX *libctx, void (*fn)(EVP_SIGNATURE *signature, void *arg), void *arg) { evp_generic_do_all(libctx, OSSL_OP_SIGNATURE, (void (*)(void *, void *))fn, arg, evp_signature_from_algorithm, (int (*)(void *))EVP_SIGNATURE_up_ref, (void (*)(void *))EVP_SIGNATURE_free); } int EVP_SIGNATURE_names_do_all(const EVP_SIGNATURE *signature, void (*fn)(const char *name, void *data), void *data) { if (signature->prov != NULL) return evp_names_do_all(signature->prov, signature->name_id, fn, data); return 1; } const OSSL_PARAM *EVP_SIGNATURE_gettable_ctx_params(const EVP_SIGNATURE *sig) { void *provctx; if (sig == NULL || sig->gettable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_SIGNATURE_get0_provider(sig)); return sig->gettable_ctx_params(NULL, provctx); } const OSSL_PARAM *EVP_SIGNATURE_settable_ctx_params(const EVP_SIGNATURE *sig) { void *provctx; if (sig == NULL || sig->settable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_SIGNATURE_get0_provider(sig)); return sig->settable_ctx_params(NULL, provctx); } static int evp_pkey_signature_init(EVP_PKEY_CTX *ctx, int operation, const OSSL_PARAM params[]) { int ret = 0; void *provkey = NULL; EVP_SIGNATURE *signature = NULL; EVP_KEYMGMT *tmp_keymgmt = NULL; const OSSL_PROVIDER *tmp_prov = NULL; const char *supported_sig = NULL; int iter; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } evp_pkey_ctx_free_old_ops(ctx); ctx->operation = operation; ERR_set_mark(); if (evp_pkey_ctx_is_legacy(ctx)) goto legacy; if (ctx->pkey == NULL) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_NO_KEY_SET); goto err; } /* * Try to derive the supported signature from |ctx->keymgmt|. */ if (!ossl_assert(ctx->pkey->keymgmt == NULL || ctx->pkey->keymgmt == ctx->keymgmt)) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); goto err; } supported_sig = evp_keymgmt_util_query_operation_name(ctx->keymgmt, OSSL_OP_SIGNATURE); if (supported_sig == NULL) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } /* * We perform two iterations: * * 1. Do the normal signature fetch, using the fetching data given by * the EVP_PKEY_CTX. * 2. Do the provider specific signature fetch, from the same provider * as |ctx->keymgmt| * * We then try to fetch the keymgmt from the same provider as the * signature, and try to export |ctx->pkey| to that keymgmt (when * this keymgmt happens to be the same as |ctx->keymgmt|, the export * is a no-op, but we call it anyway to not complicate the code even * more). * If the export call succeeds (returns a non-NULL provider key pointer), * we're done and can perform the operation itself. If not, we perform * the second iteration, or jump to legacy. */ for (iter = 1; iter < 3 && provkey == NULL; iter++) { EVP_KEYMGMT *tmp_keymgmt_tofree = NULL; /* * If we're on the second iteration, free the results from the first. * They are NULL on the first iteration, so no need to check what * iteration we're on. */ EVP_SIGNATURE_free(signature); EVP_KEYMGMT_free(tmp_keymgmt); switch (iter) { case 1: signature = EVP_SIGNATURE_fetch(ctx->libctx, supported_sig, ctx->propquery); if (signature != NULL) tmp_prov = EVP_SIGNATURE_get0_provider(signature); break; case 2: tmp_prov = EVP_KEYMGMT_get0_provider(ctx->keymgmt); signature = evp_signature_fetch_from_prov((OSSL_PROVIDER *)tmp_prov, supported_sig, ctx->propquery); if (signature == NULL) goto legacy; break; } if (signature == NULL) continue; /* * Ensure that the key is provided, either natively, or as a cached * export. We start by fetching the keymgmt with the same name as * |ctx->pkey|, but from the provider of the signature method, using * the same property query as when fetching the signature method. * With the keymgmt we found (if we did), we try to export |ctx->pkey| * to it (evp_pkey_export_to_provider() is smart enough to only actually * export it if |tmp_keymgmt| is different from |ctx->pkey|'s keymgmt) */ tmp_keymgmt_tofree = tmp_keymgmt = evp_keymgmt_fetch_from_prov((OSSL_PROVIDER *)tmp_prov, EVP_KEYMGMT_get0_name(ctx->keymgmt), ctx->propquery); if (tmp_keymgmt != NULL) provkey = evp_pkey_export_to_provider(ctx->pkey, ctx->libctx, &tmp_keymgmt, ctx->propquery); if (tmp_keymgmt == NULL) EVP_KEYMGMT_free(tmp_keymgmt_tofree); } if (provkey == NULL) { EVP_SIGNATURE_free(signature); goto legacy; } ERR_pop_to_mark(); /* No more legacy from here down to legacy: */ ctx->op.sig.signature = signature; ctx->op.sig.algctx = signature->newctx(ossl_provider_ctx(signature->prov), ctx->propquery); if (ctx->op.sig.algctx == NULL) { /* The provider key can stay in the cache */ ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } switch (operation) { case EVP_PKEY_OP_SIGN: if (signature->sign_init == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); ret = -2; goto err; } ret = signature->sign_init(ctx->op.sig.algctx, provkey, params); break; case EVP_PKEY_OP_VERIFY: if (signature->verify_init == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); ret = -2; goto err; } ret = signature->verify_init(ctx->op.sig.algctx, provkey, params); break; case EVP_PKEY_OP_VERIFYRECOVER: if (signature->verify_recover_init == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); ret = -2; goto err; } ret = signature->verify_recover_init(ctx->op.sig.algctx, provkey, params); break; default: ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } if (ret <= 0) { signature->freectx(ctx->op.sig.algctx); ctx->op.sig.algctx = NULL; goto err; } goto end; legacy: /* * If we don't have the full support we need with provided methods, * let's go see if legacy does. */ ERR_pop_to_mark(); EVP_KEYMGMT_free(tmp_keymgmt); tmp_keymgmt = NULL; if (ctx->pmeth == NULL || (operation == EVP_PKEY_OP_SIGN && ctx->pmeth->sign == NULL) || (operation == EVP_PKEY_OP_VERIFY && ctx->pmeth->verify == NULL) || (operation == EVP_PKEY_OP_VERIFYRECOVER && ctx->pmeth->verify_recover == NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } switch (operation) { case EVP_PKEY_OP_SIGN: if (ctx->pmeth->sign_init == NULL) return 1; ret = ctx->pmeth->sign_init(ctx); break; case EVP_PKEY_OP_VERIFY: if (ctx->pmeth->verify_init == NULL) return 1; ret = ctx->pmeth->verify_init(ctx); break; case EVP_PKEY_OP_VERIFYRECOVER: if (ctx->pmeth->verify_recover_init == NULL) return 1; ret = ctx->pmeth->verify_recover_init(ctx); break; default: ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } if (ret <= 0) goto err; end: #ifndef FIPS_MODULE if (ret > 0) ret = evp_pkey_ctx_use_cached_data(ctx); #endif EVP_KEYMGMT_free(tmp_keymgmt); return ret; err: evp_pkey_ctx_free_old_ops(ctx); ctx->operation = EVP_PKEY_OP_UNDEFINED; EVP_KEYMGMT_free(tmp_keymgmt); return ret; } int EVP_PKEY_sign_init(EVP_PKEY_CTX *ctx) { return evp_pkey_signature_init(ctx, EVP_PKEY_OP_SIGN, NULL); } int EVP_PKEY_sign_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]) { return evp_pkey_signature_init(ctx, EVP_PKEY_OP_SIGN, params); } int EVP_PKEY_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen) { int ret; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } if (ctx->operation != EVP_PKEY_OP_SIGN) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); return -1; } if (ctx->op.sig.algctx == NULL) goto legacy; ret = ctx->op.sig.signature->sign(ctx->op.sig.algctx, sig, siglen, (sig == NULL) ? 0 : *siglen, tbs, tbslen); return ret; legacy: if (ctx->pmeth == NULL || ctx->pmeth->sign == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } M_check_autoarg(ctx, sig, siglen, EVP_F_EVP_PKEY_SIGN) return ctx->pmeth->sign(ctx, sig, siglen, tbs, tbslen); } int EVP_PKEY_verify_init(EVP_PKEY_CTX *ctx) { return evp_pkey_signature_init(ctx, EVP_PKEY_OP_VERIFY, NULL); } int EVP_PKEY_verify_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]) { return evp_pkey_signature_init(ctx, EVP_PKEY_OP_VERIFY, params); } int EVP_PKEY_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig, size_t siglen, const unsigned char *tbs, size_t tbslen) { int ret; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } if (ctx->operation != EVP_PKEY_OP_VERIFY) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); return -1; } if (ctx->op.sig.algctx == NULL) goto legacy; ret = ctx->op.sig.signature->verify(ctx->op.sig.algctx, sig, siglen, tbs, tbslen); return ret; legacy: if (ctx->pmeth == NULL || ctx->pmeth->verify == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } return ctx->pmeth->verify(ctx, sig, siglen, tbs, tbslen); } int EVP_PKEY_verify_recover_init(EVP_PKEY_CTX *ctx) { return evp_pkey_signature_init(ctx, EVP_PKEY_OP_VERIFYRECOVER, NULL); } int EVP_PKEY_verify_recover_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]) { return evp_pkey_signature_init(ctx, EVP_PKEY_OP_VERIFYRECOVER, params); } int EVP_PKEY_verify_recover(EVP_PKEY_CTX *ctx, unsigned char *rout, size_t *routlen, const unsigned char *sig, size_t siglen) { int ret; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } if (ctx->operation != EVP_PKEY_OP_VERIFYRECOVER) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); return -1; } if (ctx->op.sig.algctx == NULL) goto legacy; ret = ctx->op.sig.signature->verify_recover(ctx->op.sig.algctx, rout, routlen, (rout == NULL ? 0 : *routlen), sig, siglen); return ret; legacy: if (ctx->pmeth == NULL || ctx->pmeth->verify_recover == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } M_check_autoarg(ctx, rout, routlen, EVP_F_EVP_PKEY_VERIFY_RECOVER) return ctx->pmeth->verify_recover(ctx, rout, routlen, sig, siglen); }
./openssl/crypto/evp/evp_enc.c
/* * Copyright 1995-2023 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 */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <limits.h> #include <assert.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/rand.h> #ifndef FIPS_MODULE # include <openssl/engine.h> #endif #include <openssl/params.h> #include <openssl/core_names.h> #include "internal/cryptlib.h" #include "internal/provider.h" #include "internal/core.h" #include "internal/safe_math.h" #include "crypto/evp.h" #include "evp_local.h" OSSL_SAFE_MATH_SIGNED(int, int) int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *ctx) { if (ctx == NULL) return 1; if (ctx->cipher == NULL || ctx->cipher->prov == NULL) goto legacy; if (ctx->algctx != NULL) { if (ctx->cipher->freectx != NULL) ctx->cipher->freectx(ctx->algctx); ctx->algctx = NULL; } if (ctx->fetched_cipher != NULL) EVP_CIPHER_free(ctx->fetched_cipher); memset(ctx, 0, sizeof(*ctx)); ctx->iv_len = -1; return 1; /* Remove legacy code below when legacy support is removed. */ legacy: if (ctx->cipher != NULL) { if (ctx->cipher->cleanup && !ctx->cipher->cleanup(ctx)) return 0; /* Cleanse cipher context data */ if (ctx->cipher_data && ctx->cipher->ctx_size) OPENSSL_cleanse(ctx->cipher_data, ctx->cipher->ctx_size); } OPENSSL_free(ctx->cipher_data); #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) ENGINE_finish(ctx->engine); #endif memset(ctx, 0, sizeof(*ctx)); ctx->iv_len = -1; return 1; } EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void) { EVP_CIPHER_CTX *ctx; ctx = OPENSSL_zalloc(sizeof(EVP_CIPHER_CTX)); if (ctx == NULL) return NULL; ctx->iv_len = -1; return ctx; } void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx) { if (ctx == NULL) return; EVP_CIPHER_CTX_reset(ctx); OPENSSL_free(ctx); } static int evp_cipher_init_internal(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl, const unsigned char *key, const unsigned char *iv, int enc, const OSSL_PARAM params[]) { int n; #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) ENGINE *tmpimpl = NULL; #endif /* * enc == 1 means we are encrypting. * enc == 0 means we are decrypting. * enc == -1 means, use the previously initialised value for encrypt/decrypt */ if (enc == -1) { enc = ctx->encrypt; } else { if (enc) enc = 1; ctx->encrypt = enc; } if (cipher == NULL && ctx->cipher == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET); return 0; } /* Code below to be removed when legacy support is dropped. */ #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) /* * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so * this context may already have an ENGINE! Try to avoid releasing the * previous handle, re-querying for an ENGINE, and having a * reinitialisation, when it may all be unnecessary. */ if (ctx->engine && ctx->cipher && (cipher == NULL || cipher->nid == ctx->cipher->nid)) goto skip_to_init; if (cipher != NULL && impl == NULL) { /* Ask if an ENGINE is reserved for this job */ tmpimpl = ENGINE_get_cipher_engine(cipher->nid); } #endif /* * If there are engines involved then we should use legacy handling for now. */ if (ctx->engine != NULL #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) || tmpimpl != NULL #endif || impl != NULL || (cipher != NULL && cipher->origin == EVP_ORIG_METH) || (cipher == NULL && ctx->cipher != NULL && ctx->cipher->origin == EVP_ORIG_METH)) { if (ctx->cipher == ctx->fetched_cipher) ctx->cipher = NULL; EVP_CIPHER_free(ctx->fetched_cipher); ctx->fetched_cipher = NULL; goto legacy; } /* * Ensure a context left lying around from last time is cleared * (legacy code) */ if (cipher != NULL && ctx->cipher != NULL) { if (ctx->cipher->cleanup != NULL && !ctx->cipher->cleanup(ctx)) return 0; OPENSSL_clear_free(ctx->cipher_data, ctx->cipher->ctx_size); ctx->cipher_data = NULL; } /* Start of non-legacy code below */ /* Ensure a context left lying around from last time is cleared */ if (cipher != NULL && ctx->cipher != NULL) { unsigned long flags = ctx->flags; EVP_CIPHER_CTX_reset(ctx); /* Restore encrypt and flags */ ctx->encrypt = enc; ctx->flags = flags; } if (cipher == NULL) cipher = ctx->cipher; if (cipher->prov == NULL) { #ifdef FIPS_MODULE /* We only do explicit fetches inside the FIPS module */ ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; #else EVP_CIPHER *provciph = EVP_CIPHER_fetch(NULL, cipher->nid == NID_undef ? "NULL" : OBJ_nid2sn(cipher->nid), ""); if (provciph == NULL) return 0; cipher = provciph; EVP_CIPHER_free(ctx->fetched_cipher); ctx->fetched_cipher = provciph; #endif } if (!ossl_assert(cipher->prov != NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } if (cipher != ctx->fetched_cipher) { if (!EVP_CIPHER_up_ref((EVP_CIPHER *)cipher)) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } EVP_CIPHER_free(ctx->fetched_cipher); /* Coverity false positive, the reference counting is confusing it */ /* coverity[use_after_free] */ ctx->fetched_cipher = (EVP_CIPHER *)cipher; } ctx->cipher = cipher; if (ctx->algctx == NULL) { ctx->algctx = ctx->cipher->newctx(ossl_provider_ctx(cipher->prov)); if (ctx->algctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } } if ((ctx->flags & EVP_CIPH_NO_PADDING) != 0) { /* * If this ctx was already set up for no padding then we need to tell * the new cipher about it. */ if (!EVP_CIPHER_CTX_set_padding(ctx, 0)) return 0; } #ifndef FIPS_MODULE /* * Fix for CVE-2023-5363 * Passing in a size as part of the init call takes effect late * so, force such to occur before the initialisation. * * The FIPS provider's internal library context is used in a manner * such that this is not an issue. */ if (params != NULL) { OSSL_PARAM param_lens[3] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END }; OSSL_PARAM *q = param_lens; const OSSL_PARAM *p; p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_KEYLEN); if (p != NULL) memcpy(q++, p, sizeof(*q)); /* * Note that OSSL_CIPHER_PARAM_AEAD_IVLEN is a synonym for * OSSL_CIPHER_PARAM_IVLEN so both are covered here. */ p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_IVLEN); if (p != NULL) memcpy(q++, p, sizeof(*q)); if (q != param_lens) { if (!EVP_CIPHER_CTX_set_params(ctx, param_lens)) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_LENGTH); return 0; } } } #endif if (enc) { if (ctx->cipher->einit == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } return ctx->cipher->einit(ctx->algctx, key, key == NULL ? 0 : EVP_CIPHER_CTX_get_key_length(ctx), iv, iv == NULL ? 0 : EVP_CIPHER_CTX_get_iv_length(ctx), params); } if (ctx->cipher->dinit == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } return ctx->cipher->dinit(ctx->algctx, key, key == NULL ? 0 : EVP_CIPHER_CTX_get_key_length(ctx), iv, iv == NULL ? 0 : EVP_CIPHER_CTX_get_iv_length(ctx), params); /* Code below to be removed when legacy support is dropped. */ legacy: if (cipher != NULL) { /* * Ensure a context left lying around from last time is cleared (we * previously attempted to avoid this if the same ENGINE and * EVP_CIPHER could be used). */ if (ctx->cipher) { unsigned long flags = ctx->flags; EVP_CIPHER_CTX_reset(ctx); /* Restore encrypt and flags */ ctx->encrypt = enc; ctx->flags = flags; } #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) if (impl != NULL) { if (!ENGINE_init(impl)) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } } else { impl = tmpimpl; } if (impl != NULL) { /* There's an ENGINE for this job ... (apparently) */ const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid); if (c == NULL) { /* * One positive side-effect of US's export control history, * is that we should at least be able to avoid using US * misspellings of "initialisation"? */ ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } /* We'll use the ENGINE's private cipher definition */ cipher = c; /* * Store the ENGINE functional reference so we know 'cipher' came * from an ENGINE and we need to release it when done. */ ctx->engine = impl; } else { ctx->engine = NULL; } #endif ctx->cipher = cipher; if (ctx->cipher->ctx_size) { ctx->cipher_data = OPENSSL_zalloc(ctx->cipher->ctx_size); if (ctx->cipher_data == NULL) { ctx->cipher = NULL; return 0; } } else { ctx->cipher_data = NULL; } ctx->key_len = cipher->key_len; /* Preserve wrap enable flag, zero everything else */ ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW; if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) { if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL) <= 0) { ctx->cipher = NULL; ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } } } #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) skip_to_init: #endif if (ctx->cipher == NULL) return 0; /* we assume block size is a power of 2 in *cryptUpdate */ OPENSSL_assert(ctx->cipher->block_size == 1 || ctx->cipher->block_size == 8 || ctx->cipher->block_size == 16); if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW) && EVP_CIPHER_CTX_get_mode(ctx) == EVP_CIPH_WRAP_MODE) { ERR_raise(ERR_LIB_EVP, EVP_R_WRAP_MODE_NOT_ALLOWED); return 0; } if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx)) & EVP_CIPH_CUSTOM_IV) == 0) { switch (EVP_CIPHER_CTX_get_mode(ctx)) { case EVP_CIPH_STREAM_CIPHER: case EVP_CIPH_ECB_MODE: break; case EVP_CIPH_CFB_MODE: case EVP_CIPH_OFB_MODE: ctx->num = 0; /* fall-through */ case EVP_CIPH_CBC_MODE: n = EVP_CIPHER_CTX_get_iv_length(ctx); if (n < 0 || n > (int)sizeof(ctx->iv)) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_IV_LENGTH); return 0; } if (iv != NULL) memcpy(ctx->oiv, iv, n); memcpy(ctx->iv, ctx->oiv, n); break; case EVP_CIPH_CTR_MODE: ctx->num = 0; /* Don't reuse IV for CTR mode */ if (iv != NULL) { n = EVP_CIPHER_CTX_get_iv_length(ctx); if (n <= 0 || n > (int)sizeof(ctx->iv)) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_IV_LENGTH); return 0; } memcpy(ctx->iv, iv, n); } break; default: return 0; } } if (key != NULL || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) { if (!ctx->cipher->init(ctx, key, iv, enc)) return 0; } ctx->buf_len = 0; ctx->final_used = 0; ctx->block_mask = ctx->cipher->block_size - 1; return 1; } int EVP_CipherInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv, int enc, const OSSL_PARAM params[]) { return evp_cipher_init_internal(ctx, cipher, NULL, key, iv, enc, params); } int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv, int enc) { if (cipher != NULL) EVP_CIPHER_CTX_reset(ctx); return evp_cipher_init_internal(ctx, cipher, NULL, key, iv, enc, NULL); } int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl, const unsigned char *key, const unsigned char *iv, int enc) { return evp_cipher_init_internal(ctx, cipher, impl, key, iv, enc, NULL); } int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { if (ctx->encrypt) return EVP_EncryptUpdate(ctx, out, outl, in, inl); else return EVP_DecryptUpdate(ctx, out, outl, in, inl); } int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { if (ctx->encrypt) return EVP_EncryptFinal_ex(ctx, out, outl); else return EVP_DecryptFinal_ex(ctx, out, outl); } int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { if (ctx->encrypt) return EVP_EncryptFinal(ctx, out, outl); else return EVP_DecryptFinal(ctx, out, outl); } int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv) { return EVP_CipherInit(ctx, cipher, key, iv, 1); } int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl, const unsigned char *key, const unsigned char *iv) { return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1); } int EVP_EncryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv, const OSSL_PARAM params[]) { return EVP_CipherInit_ex2(ctx, cipher, key, iv, 1, params); } int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv) { return EVP_CipherInit(ctx, cipher, key, iv, 0); } int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl, const unsigned char *key, const unsigned char *iv) { return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0); } int EVP_DecryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv, const OSSL_PARAM params[]) { return EVP_CipherInit_ex2(ctx, cipher, key, iv, 0, params); } /* * According to the letter of standard difference between pointers * is specified to be valid only within same object. This makes * it formally challenging to determine if input and output buffers * are not partially overlapping with standard pointer arithmetic. */ #ifdef PTRDIFF_T # undef PTRDIFF_T #endif #if defined(OPENSSL_SYS_VMS) && __INITIAL_POINTER_SIZE==64 /* * Then we have VMS that distinguishes itself by adhering to * sizeof(size_t)==4 even in 64-bit builds, which means that * difference between two pointers might be truncated to 32 bits. * In the context one can even wonder how comparison for * equality is implemented. To be on the safe side we adhere to * PTRDIFF_T even for comparison for equality. */ # define PTRDIFF_T uint64_t #else # define PTRDIFF_T size_t #endif int ossl_is_partially_overlapping(const void *ptr1, const void *ptr2, int len) { PTRDIFF_T diff = (PTRDIFF_T)ptr1-(PTRDIFF_T)ptr2; /* * Check for partially overlapping buffers. [Binary logical * operations are used instead of boolean to minimize number * of conditional branches.] */ int overlapped = (len > 0) & (diff != 0) & ((diff < (PTRDIFF_T)len) | (diff > (0 - (PTRDIFF_T)len))); return overlapped; } static int evp_EncryptDecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int i, j, bl, cmpl = inl; if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS)) cmpl = safe_div_round_up_int(cmpl, 8, NULL); bl = ctx->cipher->block_size; if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { /* If block size > 1 then the cipher will have to do this check */ if (bl == 1 && ossl_is_partially_overlapping(out, in, cmpl)) { ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING); return 0; } i = ctx->cipher->do_cipher(ctx, out, in, inl); if (i < 0) return 0; else *outl = i; return 1; } if (inl <= 0) { *outl = 0; return inl == 0; } if (ossl_is_partially_overlapping(out + ctx->buf_len, in, cmpl)) { ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING); return 0; } if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) { if (ctx->cipher->do_cipher(ctx, out, in, inl)) { *outl = inl; return 1; } else { *outl = 0; return 0; } } i = ctx->buf_len; OPENSSL_assert(bl <= (int)sizeof(ctx->buf)); if (i != 0) { if (bl - i > inl) { memcpy(&(ctx->buf[i]), in, inl); ctx->buf_len += inl; *outl = 0; return 1; } else { j = bl - i; /* * Once we've processed the first j bytes from in, the amount of * data left that is a multiple of the block length is: * (inl - j) & ~(bl - 1) * We must ensure that this amount of data, plus the one block that * we process from ctx->buf does not exceed INT_MAX */ if (((inl - j) & ~(bl - 1)) > INT_MAX - bl) { ERR_raise(ERR_LIB_EVP, EVP_R_OUTPUT_WOULD_OVERFLOW); return 0; } memcpy(&(ctx->buf[i]), in, j); inl -= j; in += j; if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl)) return 0; out += bl; *outl = bl; } } else *outl = 0; i = inl & (bl - 1); inl -= i; if (inl > 0) { if (!ctx->cipher->do_cipher(ctx, out, in, inl)) return 0; *outl += inl; } if (i != 0) memcpy(ctx->buf, &(in[inl]), i); ctx->buf_len = i; return 1; } int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int ret; size_t soutl, inl_ = (size_t)inl; int blocksize; if (ossl_likely(outl != NULL)) { *outl = 0; } else { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* Prevent accidental use of decryption context when encrypting */ if (ossl_unlikely(!ctx->encrypt)) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION); return 0; } if (ossl_unlikely(ctx->cipher == NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET); return 0; } if (ossl_unlikely(ctx->cipher->prov == NULL)) goto legacy; blocksize = ctx->cipher->block_size; if (ossl_unlikely(ctx->cipher->cupdate == NULL || blocksize < 1)) { ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR); return 0; } ret = ctx->cipher->cupdate(ctx->algctx, out, &soutl, inl_ + (size_t)(blocksize == 1 ? 0 : blocksize), in, inl_); if (ossl_likely(ret)) { if (soutl > INT_MAX) { ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR); return 0; } *outl = soutl; } return ret; /* Code below to be removed when legacy support is dropped. */ legacy: return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl); } int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { int ret; ret = EVP_EncryptFinal_ex(ctx, out, outl); return ret; } int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { int n, ret; unsigned int i, b, bl; size_t soutl; int blocksize; if (outl != NULL) { *outl = 0; } else { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* Prevent accidental use of decryption context when encrypting */ if (!ctx->encrypt) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION); return 0; } if (ctx->cipher == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET); return 0; } if (ctx->cipher->prov == NULL) goto legacy; blocksize = EVP_CIPHER_CTX_get_block_size(ctx); if (blocksize < 1 || ctx->cipher->cfinal == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } ret = ctx->cipher->cfinal(ctx->algctx, out, &soutl, blocksize == 1 ? 0 : blocksize); if (ret) { if (soutl > INT_MAX) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } *outl = soutl; } return ret; /* Code below to be removed when legacy support is dropped. */ legacy: if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { ret = ctx->cipher->do_cipher(ctx, out, NULL, 0); if (ret < 0) return 0; else *outl = ret; return 1; } b = ctx->cipher->block_size; OPENSSL_assert(b <= sizeof(ctx->buf)); if (b == 1) { *outl = 0; return 1; } bl = ctx->buf_len; if (ctx->flags & EVP_CIPH_NO_PADDING) { if (bl) { ERR_raise(ERR_LIB_EVP, EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH); return 0; } *outl = 0; return 1; } n = b - bl; for (i = bl; i < b; i++) ctx->buf[i] = n; ret = ctx->cipher->do_cipher(ctx, out, ctx->buf, b); if (ret) *outl = b; return ret; } int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int fix_len, cmpl = inl, ret; unsigned int b; size_t soutl, inl_ = (size_t)inl; int blocksize; if (ossl_likely(outl != NULL)) { *outl = 0; } else { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* Prevent accidental use of encryption context when decrypting */ if (ossl_unlikely(ctx->encrypt)) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION); return 0; } if (ossl_unlikely(ctx->cipher == NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET); return 0; } if (ossl_unlikely(ctx->cipher->prov == NULL)) goto legacy; blocksize = EVP_CIPHER_CTX_get_block_size(ctx); if (ossl_unlikely(ctx->cipher->cupdate == NULL || blocksize < 1)) { ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR); return 0; } ret = ctx->cipher->cupdate(ctx->algctx, out, &soutl, inl_ + (size_t)(blocksize == 1 ? 0 : blocksize), in, inl_); if (ossl_likely(ret)) { if (soutl > INT_MAX) { ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR); return 0; } *outl = soutl; } return ret; /* Code below to be removed when legacy support is dropped. */ legacy: b = ctx->cipher->block_size; if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS)) cmpl = safe_div_round_up_int(cmpl, 8, NULL); if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { if (b == 1 && ossl_is_partially_overlapping(out, in, cmpl)) { ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING); return 0; } fix_len = ctx->cipher->do_cipher(ctx, out, in, inl); if (fix_len < 0) { *outl = 0; return 0; } else *outl = fix_len; return 1; } if (inl <= 0) { *outl = 0; return inl == 0; } if (ctx->flags & EVP_CIPH_NO_PADDING) return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl); OPENSSL_assert(b <= sizeof(ctx->final)); if (ctx->final_used) { /* see comment about PTRDIFF_T comparison above */ if (((PTRDIFF_T)out == (PTRDIFF_T)in) || ossl_is_partially_overlapping(out, in, b)) { ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING); return 0; } /* * final_used is only ever set if buf_len is 0. Therefore the maximum * length output we will ever see from evp_EncryptDecryptUpdate is * the maximum multiple of the block length that is <= inl, or just: * inl & ~(b - 1) * Since final_used has been set then the final output length is: * (inl & ~(b - 1)) + b * This must never exceed INT_MAX */ if ((inl & ~(b - 1)) > INT_MAX - b) { ERR_raise(ERR_LIB_EVP, EVP_R_OUTPUT_WOULD_OVERFLOW); return 0; } memcpy(out, ctx->final, b); out += b; fix_len = 1; } else fix_len = 0; if (!evp_EncryptDecryptUpdate(ctx, out, outl, in, inl)) return 0; /* * if we have 'decrypted' a multiple of block size, make sure we have a * copy of this last block */ if (b > 1 && !ctx->buf_len) { *outl -= b; ctx->final_used = 1; memcpy(ctx->final, &out[*outl], b); } else ctx->final_used = 0; if (fix_len) *outl += b; return 1; } int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { int ret; ret = EVP_DecryptFinal_ex(ctx, out, outl); return ret; } int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { int i, n; unsigned int b; size_t soutl; int ret; int blocksize; if (outl != NULL) { *outl = 0; } else { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* Prevent accidental use of encryption context when decrypting */ if (ctx->encrypt) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION); return 0; } if (ctx->cipher == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET); return 0; } if (ctx->cipher->prov == NULL) goto legacy; blocksize = EVP_CIPHER_CTX_get_block_size(ctx); if (blocksize < 1 || ctx->cipher->cfinal == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } ret = ctx->cipher->cfinal(ctx->algctx, out, &soutl, blocksize == 1 ? 0 : blocksize); if (ret) { if (soutl > INT_MAX) { ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR); return 0; } *outl = soutl; } return ret; /* Code below to be removed when legacy support is dropped. */ legacy: *outl = 0; if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { i = ctx->cipher->do_cipher(ctx, out, NULL, 0); if (i < 0) return 0; else *outl = i; return 1; } b = ctx->cipher->block_size; if (ctx->flags & EVP_CIPH_NO_PADDING) { if (ctx->buf_len) { ERR_raise(ERR_LIB_EVP, EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH); return 0; } *outl = 0; return 1; } if (b > 1) { if (ctx->buf_len || !ctx->final_used) { ERR_raise(ERR_LIB_EVP, EVP_R_WRONG_FINAL_BLOCK_LENGTH); return 0; } OPENSSL_assert(b <= sizeof(ctx->final)); /* * The following assumes that the ciphertext has been authenticated. * Otherwise it provides a padding oracle. */ n = ctx->final[b - 1]; if (n == 0 || n > (int)b) { ERR_raise(ERR_LIB_EVP, EVP_R_BAD_DECRYPT); return 0; } for (i = 0; i < n; i++) { if (ctx->final[--b] != n) { ERR_raise(ERR_LIB_EVP, EVP_R_BAD_DECRYPT); return 0; } } n = ctx->cipher->block_size - n; for (i = 0; i < n; i++) out[i] = ctx->final[i]; *outl = n; } else *outl = 0; return 1; } int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen) { if (c->cipher->prov != NULL) { int ok; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; size_t len; if (EVP_CIPHER_CTX_get_key_length(c) == keylen) return 1; /* Check the cipher actually understands this parameter */ if (OSSL_PARAM_locate_const(EVP_CIPHER_settable_ctx_params(c->cipher), OSSL_CIPHER_PARAM_KEYLEN) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &len); if (!OSSL_PARAM_set_int(params, keylen)) return 0; ok = evp_do_ciph_ctx_setparams(c->cipher, c->algctx, params); if (ok <= 0) return 0; c->key_len = keylen; return 1; } /* Code below to be removed when legacy support is dropped. */ /* * Note there have never been any built-in ciphers that define this flag * since it was first introduced. */ if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH) return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL); if (EVP_CIPHER_CTX_get_key_length(c) == keylen) return 1; if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) { c->key_len = keylen; return 1; } ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); return 0; } int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad) { int ok; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; unsigned int pd = pad; if (pad) ctx->flags &= ~EVP_CIPH_NO_PADDING; else ctx->flags |= EVP_CIPH_NO_PADDING; if (ctx->cipher != NULL && ctx->cipher->prov == NULL) return 1; params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_PADDING, &pd); ok = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params); return ok != 0; } int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { int ret = EVP_CTRL_RET_UNSUPPORTED; int set_params = 1; size_t sz = arg; unsigned int i; OSSL_PARAM params[4] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END }; if (ctx == NULL || ctx->cipher == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET); return 0; } if (ctx->cipher->prov == NULL) goto legacy; switch (type) { case EVP_CTRL_SET_KEY_LENGTH: if (arg < 0) return 0; if (ctx->key_len == arg) /* Skip calling into provider if unchanged. */ return 1; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &sz); ctx->key_len = -1; break; case EVP_CTRL_RAND_KEY: /* Used by DES */ set_params = 0; params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_RANDOM_KEY, ptr, sz); break; case EVP_CTRL_INIT: /* * EVP_CTRL_INIT is purely legacy, no provider counterpart. * As a matter of fact, this should be dead code, but some caller * might still do a direct control call with this command, so... * Legacy methods return 1 except for exceptional circumstances, so * we do the same here to not be disruptive. */ return 1; case EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS: /* Used by DASYNC */ default: goto end; case EVP_CTRL_AEAD_SET_IVLEN: if (arg < 0) return 0; if (ctx->iv_len == arg) /* Skip calling into provider if unchanged. */ return 1; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_IVLEN, &sz); ctx->iv_len = -1; break; case EVP_CTRL_CCM_SET_L: if (arg < 2 || arg > 8) return 0; sz = 15 - arg; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_IVLEN, &sz); ctx->iv_len = -1; break; case EVP_CTRL_AEAD_SET_IV_FIXED: params[0] = OSSL_PARAM_construct_octet_string( OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED, ptr, sz); break; case EVP_CTRL_GCM_IV_GEN: set_params = 0; if (arg < 0) sz = 0; /* special case that uses the iv length */ params[0] = OSSL_PARAM_construct_octet_string( OSSL_CIPHER_PARAM_AEAD_TLS1_GET_IV_GEN, ptr, sz); break; case EVP_CTRL_GCM_SET_IV_INV: if (arg < 0) return 0; params[0] = OSSL_PARAM_construct_octet_string( OSSL_CIPHER_PARAM_AEAD_TLS1_SET_IV_INV, ptr, sz); break; case EVP_CTRL_GET_RC5_ROUNDS: set_params = 0; /* Fall thru */ case EVP_CTRL_SET_RC5_ROUNDS: if (arg < 0) return 0; i = (unsigned int)arg; params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_ROUNDS, &i); break; case EVP_CTRL_SET_SPEED: if (arg < 0) return 0; i = (unsigned int)arg; params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_SPEED, &i); break; case EVP_CTRL_AEAD_GET_TAG: set_params = 0; /* Fall thru */ case EVP_CTRL_AEAD_SET_TAG: params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG, ptr, sz); break; case EVP_CTRL_AEAD_TLS1_AAD: /* This one does a set and a get - since it returns a size */ params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD, ptr, sz); ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params); if (ret <= 0) goto end; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD, &sz); ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); if (ret <= 0) goto end; return sz; #ifndef OPENSSL_NO_RC2 case EVP_CTRL_GET_RC2_KEY_BITS: set_params = 0; /* Fall thru */ case EVP_CTRL_SET_RC2_KEY_BITS: params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_RC2_KEYBITS, &sz); break; #endif /* OPENSSL_NO_RC2 */ #if !defined(OPENSSL_NO_MULTIBLOCK) case EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE: params[0] = OSSL_PARAM_construct_size_t( OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_SEND_FRAGMENT, &sz); ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params); if (ret <= 0) return 0; params[0] = OSSL_PARAM_construct_size_t( OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_BUFSIZE, &sz); params[1] = OSSL_PARAM_construct_end(); ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); if (ret <= 0) return 0; return sz; case EVP_CTRL_TLS1_1_MULTIBLOCK_AAD: { EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *p = (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *)ptr; if (arg < (int)sizeof(EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM)) return 0; params[0] = OSSL_PARAM_construct_octet_string( OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD, (void*)p->inp, p->len); params[1] = OSSL_PARAM_construct_uint( OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave); ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params); if (ret <= 0) return ret; /* Retrieve the return values changed by the set */ params[0] = OSSL_PARAM_construct_size_t( OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD_PACKLEN, &sz); params[1] = OSSL_PARAM_construct_uint( OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave); params[2] = OSSL_PARAM_construct_end(); ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); if (ret <= 0) return 0; return sz; } case EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT: { EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *p = (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *)ptr; params[0] = OSSL_PARAM_construct_octet_string( OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC, p->out, p->len); params[1] = OSSL_PARAM_construct_octet_string( OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_IN, (void*)p->inp, p->len); params[2] = OSSL_PARAM_construct_uint( OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave); ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params); if (ret <= 0) return ret; params[0] = OSSL_PARAM_construct_size_t( OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_LEN, &sz); params[1] = OSSL_PARAM_construct_end(); ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); if (ret <= 0) return 0; return sz; } #endif /* OPENSSL_NO_MULTIBLOCK */ case EVP_CTRL_AEAD_SET_MAC_KEY: if (arg < 0) return -1; params[0] = OSSL_PARAM_construct_octet_string( OSSL_CIPHER_PARAM_AEAD_MAC_KEY, ptr, sz); break; } if (set_params) ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params); else ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); goto end; /* Code below to be removed when legacy support is dropped. */ legacy: if (ctx->cipher->ctrl == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_CTRL_NOT_IMPLEMENTED); return 0; } ret = ctx->cipher->ctrl(ctx, type, arg, ptr); end: if (ret == EVP_CTRL_RET_UNSUPPORTED) { ERR_raise(ERR_LIB_EVP, EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED); return 0; } return ret; } int EVP_CIPHER_get_params(EVP_CIPHER *cipher, OSSL_PARAM params[]) { if (cipher != NULL && cipher->get_params != NULL) return cipher->get_params(params); return 0; } int EVP_CIPHER_CTX_set_params(EVP_CIPHER_CTX *ctx, const OSSL_PARAM params[]) { int r = 0; const OSSL_PARAM *p; if (ctx->cipher != NULL && ctx->cipher->set_ctx_params != NULL) { r = ctx->cipher->set_ctx_params(ctx->algctx, params); if (r > 0) { p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_KEYLEN); if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->key_len)) { r = 0; ctx->key_len = -1; } } if (r > 0) { p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_IVLEN); if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->iv_len)) { r = 0; ctx->iv_len = -1; } } } return r; } int EVP_CIPHER_CTX_get_params(EVP_CIPHER_CTX *ctx, OSSL_PARAM params[]) { if (ctx->cipher != NULL && ctx->cipher->get_ctx_params != NULL) return ctx->cipher->get_ctx_params(ctx->algctx, params); return 0; } const OSSL_PARAM *EVP_CIPHER_gettable_params(const EVP_CIPHER *cipher) { if (cipher != NULL && cipher->gettable_params != NULL) return cipher->gettable_params( ossl_provider_ctx(EVP_CIPHER_get0_provider(cipher))); return NULL; } const OSSL_PARAM *EVP_CIPHER_settable_ctx_params(const EVP_CIPHER *cipher) { void *provctx; if (cipher != NULL && cipher->settable_ctx_params != NULL) { provctx = ossl_provider_ctx(EVP_CIPHER_get0_provider(cipher)); return cipher->settable_ctx_params(NULL, provctx); } return NULL; } const OSSL_PARAM *EVP_CIPHER_gettable_ctx_params(const EVP_CIPHER *cipher) { void *provctx; if (cipher != NULL && cipher->gettable_ctx_params != NULL) { provctx = ossl_provider_ctx(EVP_CIPHER_get0_provider(cipher)); return cipher->gettable_ctx_params(NULL, provctx); } return NULL; } const OSSL_PARAM *EVP_CIPHER_CTX_settable_params(EVP_CIPHER_CTX *cctx) { void *alg; if (cctx != NULL && cctx->cipher->settable_ctx_params != NULL) { alg = ossl_provider_ctx(EVP_CIPHER_get0_provider(cctx->cipher)); return cctx->cipher->settable_ctx_params(cctx->algctx, alg); } return NULL; } const OSSL_PARAM *EVP_CIPHER_CTX_gettable_params(EVP_CIPHER_CTX *cctx) { void *provctx; if (cctx != NULL && cctx->cipher->gettable_ctx_params != NULL) { provctx = ossl_provider_ctx(EVP_CIPHER_get0_provider(cctx->cipher)); return cctx->cipher->gettable_ctx_params(cctx->algctx, provctx); } return NULL; } #ifndef FIPS_MODULE static OSSL_LIB_CTX *EVP_CIPHER_CTX_get_libctx(EVP_CIPHER_CTX *ctx) { const EVP_CIPHER *cipher = ctx->cipher; const OSSL_PROVIDER *prov; if (cipher == NULL) return NULL; prov = EVP_CIPHER_get0_provider(cipher); return ossl_provider_libctx(prov); } #endif int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key) { if (ctx->cipher->flags & EVP_CIPH_RAND_KEY) return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key); #ifdef FIPS_MODULE return 0; #else { int kl; OSSL_LIB_CTX *libctx = EVP_CIPHER_CTX_get_libctx(ctx); kl = EVP_CIPHER_CTX_get_key_length(ctx); if (kl <= 0 || RAND_priv_bytes_ex(libctx, key, kl, 0) <= 0) return 0; return 1; } #endif /* FIPS_MODULE */ } EVP_CIPHER_CTX *EVP_CIPHER_CTX_dup(const EVP_CIPHER_CTX *in) { EVP_CIPHER_CTX *out = EVP_CIPHER_CTX_new(); if (out != NULL && !EVP_CIPHER_CTX_copy(out, in)) { EVP_CIPHER_CTX_free(out); out = NULL; } return out; } int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in) { if ((in == NULL) || (in->cipher == NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_INPUT_NOT_INITIALIZED); return 0; } if (in->cipher->prov == NULL) goto legacy; if (in->cipher->dupctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX); return 0; } EVP_CIPHER_CTX_reset(out); *out = *in; out->algctx = NULL; if (in->fetched_cipher != NULL && !EVP_CIPHER_up_ref(in->fetched_cipher)) { out->fetched_cipher = NULL; return 0; } out->algctx = in->cipher->dupctx(in->algctx); if (out->algctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX); return 0; } return 1; /* Code below to be removed when legacy support is dropped. */ legacy: #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) /* Make sure it's safe to copy a cipher context using an ENGINE */ if (in->engine && !ENGINE_init(in->engine)) { ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB); return 0; } #endif EVP_CIPHER_CTX_reset(out); memcpy(out, in, sizeof(*out)); if (in->cipher_data && in->cipher->ctx_size) { out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size); if (out->cipher_data == NULL) { out->cipher = NULL; return 0; } memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size); } if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY) if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) { out->cipher = NULL; ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } return 1; } EVP_CIPHER *evp_cipher_new(void) { EVP_CIPHER *cipher = OPENSSL_zalloc(sizeof(EVP_CIPHER)); if (cipher != NULL && !CRYPTO_NEW_REF(&cipher->refcnt, 1)) { OPENSSL_free(cipher); return NULL; } return cipher; } /* * FIPS module note: since internal fetches will be entirely * provider based, we know that none of its code depends on legacy * NIDs or any functionality that use them. */ #ifndef FIPS_MODULE /* After removal of legacy support get rid of the need for legacy NIDs */ static void set_legacy_nid(const char *name, void *vlegacy_nid) { int nid; int *legacy_nid = vlegacy_nid; /* * We use lowest level function to get the associated method, because * higher level functions such as EVP_get_cipherbyname() have changed * to look at providers too. */ const void *legacy_method = OBJ_NAME_get(name, OBJ_NAME_TYPE_CIPHER_METH); if (*legacy_nid == -1) /* We found a clash already */ return; if (legacy_method == NULL) return; nid = EVP_CIPHER_get_nid(legacy_method); if (*legacy_nid != NID_undef && *legacy_nid != nid) { *legacy_nid = -1; return; } *legacy_nid = nid; } #endif static void *evp_cipher_from_algorithm(const int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { const OSSL_DISPATCH *fns = algodef->implementation; EVP_CIPHER *cipher = NULL; int fnciphcnt = 0, fnctxcnt = 0; if ((cipher = evp_cipher_new()) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return NULL; } #ifndef FIPS_MODULE cipher->nid = NID_undef; if (!evp_names_do_all(prov, name_id, set_legacy_nid, &cipher->nid) || cipher->nid == -1) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); EVP_CIPHER_free(cipher); return NULL; } #endif cipher->name_id = name_id; if ((cipher->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) { EVP_CIPHER_free(cipher); return NULL; } cipher->description = algodef->algorithm_description; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_CIPHER_NEWCTX: if (cipher->newctx != NULL) break; cipher->newctx = OSSL_FUNC_cipher_newctx(fns); fnctxcnt++; break; case OSSL_FUNC_CIPHER_ENCRYPT_INIT: if (cipher->einit != NULL) break; cipher->einit = OSSL_FUNC_cipher_encrypt_init(fns); fnciphcnt++; break; case OSSL_FUNC_CIPHER_DECRYPT_INIT: if (cipher->dinit != NULL) break; cipher->dinit = OSSL_FUNC_cipher_decrypt_init(fns); fnciphcnt++; break; case OSSL_FUNC_CIPHER_UPDATE: if (cipher->cupdate != NULL) break; cipher->cupdate = OSSL_FUNC_cipher_update(fns); fnciphcnt++; break; case OSSL_FUNC_CIPHER_FINAL: if (cipher->cfinal != NULL) break; cipher->cfinal = OSSL_FUNC_cipher_final(fns); fnciphcnt++; break; case OSSL_FUNC_CIPHER_CIPHER: if (cipher->ccipher != NULL) break; cipher->ccipher = OSSL_FUNC_cipher_cipher(fns); break; case OSSL_FUNC_CIPHER_FREECTX: if (cipher->freectx != NULL) break; cipher->freectx = OSSL_FUNC_cipher_freectx(fns); fnctxcnt++; break; case OSSL_FUNC_CIPHER_DUPCTX: if (cipher->dupctx != NULL) break; cipher->dupctx = OSSL_FUNC_cipher_dupctx(fns); break; case OSSL_FUNC_CIPHER_GET_PARAMS: if (cipher->get_params != NULL) break; cipher->get_params = OSSL_FUNC_cipher_get_params(fns); break; case OSSL_FUNC_CIPHER_GET_CTX_PARAMS: if (cipher->get_ctx_params != NULL) break; cipher->get_ctx_params = OSSL_FUNC_cipher_get_ctx_params(fns); break; case OSSL_FUNC_CIPHER_SET_CTX_PARAMS: if (cipher->set_ctx_params != NULL) break; cipher->set_ctx_params = OSSL_FUNC_cipher_set_ctx_params(fns); break; case OSSL_FUNC_CIPHER_GETTABLE_PARAMS: if (cipher->gettable_params != NULL) break; cipher->gettable_params = OSSL_FUNC_cipher_gettable_params(fns); break; case OSSL_FUNC_CIPHER_GETTABLE_CTX_PARAMS: if (cipher->gettable_ctx_params != NULL) break; cipher->gettable_ctx_params = OSSL_FUNC_cipher_gettable_ctx_params(fns); break; case OSSL_FUNC_CIPHER_SETTABLE_CTX_PARAMS: if (cipher->settable_ctx_params != NULL) break; cipher->settable_ctx_params = OSSL_FUNC_cipher_settable_ctx_params(fns); break; } } if ((fnciphcnt != 0 && fnciphcnt != 3 && fnciphcnt != 4) || (fnciphcnt == 0 && cipher->ccipher == NULL) || fnctxcnt != 2) { /* * In order to be a consistent set of functions we must have at least * a complete set of "encrypt" functions, or a complete set of "decrypt" * functions, or a single "cipher" function. In all cases we need both * the "newctx" and "freectx" functions. */ EVP_CIPHER_free(cipher); ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS); return NULL; } cipher->prov = prov; if (prov != NULL) ossl_provider_up_ref(prov); if (!evp_cipher_cache_constants(cipher)) { EVP_CIPHER_free(cipher); ERR_raise(ERR_LIB_EVP, EVP_R_CACHE_CONSTANTS_FAILED); cipher = NULL; } return cipher; } static int evp_cipher_up_ref(void *cipher) { return EVP_CIPHER_up_ref(cipher); } static void evp_cipher_free(void *cipher) { EVP_CIPHER_free(cipher); } EVP_CIPHER *EVP_CIPHER_fetch(OSSL_LIB_CTX *ctx, const char *algorithm, const char *properties) { EVP_CIPHER *cipher = evp_generic_fetch(ctx, OSSL_OP_CIPHER, algorithm, properties, evp_cipher_from_algorithm, evp_cipher_up_ref, evp_cipher_free); return cipher; } int EVP_CIPHER_up_ref(EVP_CIPHER *cipher) { int ref = 0; if (cipher->origin == EVP_ORIG_DYNAMIC) CRYPTO_UP_REF(&cipher->refcnt, &ref); return 1; } void evp_cipher_free_int(EVP_CIPHER *cipher) { OPENSSL_free(cipher->type_name); ossl_provider_free(cipher->prov); CRYPTO_FREE_REF(&cipher->refcnt); OPENSSL_free(cipher); } void EVP_CIPHER_free(EVP_CIPHER *cipher) { int i; if (cipher == NULL || cipher->origin != EVP_ORIG_DYNAMIC) return; CRYPTO_DOWN_REF(&cipher->refcnt, &i); if (i > 0) return; evp_cipher_free_int(cipher); } void EVP_CIPHER_do_all_provided(OSSL_LIB_CTX *libctx, void (*fn)(EVP_CIPHER *mac, void *arg), void *arg) { evp_generic_do_all(libctx, OSSL_OP_CIPHER, (void (*)(void *, void *))fn, arg, evp_cipher_from_algorithm, evp_cipher_up_ref, evp_cipher_free); }
./openssl/crypto/evp/kem.c
/* * Copyright 2020-2023 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 <stdio.h> #include <stdlib.h> #include <openssl/objects.h> #include <openssl/evp.h> #include "internal/cryptlib.h" #include "internal/provider.h" #include "internal/core.h" #include "crypto/evp.h" #include "evp_local.h" static int evp_kem_init(EVP_PKEY_CTX *ctx, int operation, const OSSL_PARAM params[], EVP_PKEY *authkey) { int ret = 0; EVP_KEM *kem = NULL; EVP_KEYMGMT *tmp_keymgmt = NULL; const OSSL_PROVIDER *tmp_prov = NULL; void *provkey = NULL, *provauthkey = NULL; const char *supported_kem = NULL; int iter; if (ctx == NULL || ctx->keytype == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } evp_pkey_ctx_free_old_ops(ctx); ctx->operation = operation; if (ctx->pkey == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_KEY_SET); goto err; } if (authkey != NULL && authkey->type != ctx->pkey->type) { ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES); return 0; } /* * Try to derive the supported kem from |ctx->keymgmt|. */ if (!ossl_assert(ctx->pkey->keymgmt == NULL || ctx->pkey->keymgmt == ctx->keymgmt)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); goto err; } supported_kem = evp_keymgmt_util_query_operation_name(ctx->keymgmt, OSSL_OP_KEM); if (supported_kem == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } /* * Because we cleared out old ops, we shouldn't need to worry about * checking if kem is already there. * We perform two iterations: * * 1. Do the normal kem fetch, using the fetching data given by * the EVP_PKEY_CTX. * 2. Do the provider specific kem fetch, from the same provider * as |ctx->keymgmt| * * We then try to fetch the keymgmt from the same provider as the * kem, and try to export |ctx->pkey| to that keymgmt (when this * keymgmt happens to be the same as |ctx->keymgmt|, the export is * a no-op, but we call it anyway to not complicate the code even * more). * If the export call succeeds (returns a non-NULL provider key pointer), * we're done and can perform the operation itself. If not, we perform * the second iteration, or jump to legacy. */ for (iter = 1, provkey = NULL; iter < 3 && provkey == NULL; iter++) { EVP_KEYMGMT *tmp_keymgmt_tofree = NULL; /* * If we're on the second iteration, free the results from the first. * They are NULL on the first iteration, so no need to check what * iteration we're on. */ EVP_KEM_free(kem); EVP_KEYMGMT_free(tmp_keymgmt); switch (iter) { case 1: kem = EVP_KEM_fetch(ctx->libctx, supported_kem, ctx->propquery); if (kem != NULL) tmp_prov = EVP_KEM_get0_provider(kem); break; case 2: tmp_prov = EVP_KEYMGMT_get0_provider(ctx->keymgmt); kem = evp_kem_fetch_from_prov((OSSL_PROVIDER *)tmp_prov, supported_kem, ctx->propquery); if (kem == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); ret = -2; goto err; } } if (kem == NULL) continue; /* * Ensure that the key is provided, either natively, or as a cached * export. We start by fetching the keymgmt with the same name as * |ctx->pkey|, but from the provider of the kem method, using the * same property query as when fetching the kem method. * With the keymgmt we found (if we did), we try to export |ctx->pkey| * to it (evp_pkey_export_to_provider() is smart enough to only actually * export it if |tmp_keymgmt| is different from |ctx->pkey|'s keymgmt) */ tmp_keymgmt_tofree = tmp_keymgmt = evp_keymgmt_fetch_from_prov((OSSL_PROVIDER *)tmp_prov, EVP_KEYMGMT_get0_name(ctx->keymgmt), ctx->propquery); if (tmp_keymgmt != NULL) { provkey = evp_pkey_export_to_provider(ctx->pkey, ctx->libctx, &tmp_keymgmt, ctx->propquery); if (provkey != NULL && authkey != NULL) { provauthkey = evp_pkey_export_to_provider(authkey, ctx->libctx, &tmp_keymgmt, ctx->propquery); if (provauthkey == NULL) { EVP_KEM_free(kem); ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } } } if (tmp_keymgmt == NULL) EVP_KEYMGMT_free(tmp_keymgmt_tofree); } if (provkey == NULL) { EVP_KEM_free(kem); ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } ctx->op.encap.kem = kem; ctx->op.encap.algctx = kem->newctx(ossl_provider_ctx(kem->prov)); if (ctx->op.encap.algctx == NULL) { /* The provider key can stay in the cache */ ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } switch (operation) { case EVP_PKEY_OP_ENCAPSULATE: if (provauthkey != NULL && kem->auth_encapsulate_init != NULL) { ret = kem->auth_encapsulate_init(ctx->op.encap.algctx, provkey, provauthkey, params); } else if (provauthkey == NULL && kem->encapsulate_init != NULL) { ret = kem->encapsulate_init(ctx->op.encap.algctx, provkey, params); } else { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); ret = -2; goto err; } break; case EVP_PKEY_OP_DECAPSULATE: if (provauthkey != NULL && kem->auth_decapsulate_init != NULL) { ret = kem->auth_decapsulate_init(ctx->op.encap.algctx, provkey, provauthkey, params); } else if (provauthkey == NULL && kem->encapsulate_init != NULL) { ret = kem->decapsulate_init(ctx->op.encap.algctx, provkey, params); } else { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); ret = -2; goto err; } break; default: ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } EVP_KEYMGMT_free(tmp_keymgmt); tmp_keymgmt = NULL; if (ret > 0) return 1; err: if (ret <= 0) { evp_pkey_ctx_free_old_ops(ctx); ctx->operation = EVP_PKEY_OP_UNDEFINED; } EVP_KEYMGMT_free(tmp_keymgmt); return ret; } int EVP_PKEY_auth_encapsulate_init(EVP_PKEY_CTX *ctx, EVP_PKEY *authpriv, const OSSL_PARAM params[]) { if (authpriv == NULL) return 0; return evp_kem_init(ctx, EVP_PKEY_OP_ENCAPSULATE, params, authpriv); } int EVP_PKEY_encapsulate_init(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]) { return evp_kem_init(ctx, EVP_PKEY_OP_ENCAPSULATE, params, NULL); } int EVP_PKEY_encapsulate(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, unsigned char *secret, size_t *secretlen) { if (ctx == NULL) return 0; if (ctx->operation != EVP_PKEY_OP_ENCAPSULATE) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); return -1; } if (ctx->op.encap.algctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } if (out != NULL && secret == NULL) return 0; return ctx->op.encap.kem->encapsulate(ctx->op.encap.algctx, out, outlen, secret, secretlen); } int EVP_PKEY_decapsulate_init(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]) { return evp_kem_init(ctx, EVP_PKEY_OP_DECAPSULATE, params, NULL); } int EVP_PKEY_auth_decapsulate_init(EVP_PKEY_CTX *ctx, EVP_PKEY *authpub, const OSSL_PARAM params[]) { if (authpub == NULL) return 0; return evp_kem_init(ctx, EVP_PKEY_OP_DECAPSULATE, params, authpub); } int EVP_PKEY_decapsulate(EVP_PKEY_CTX *ctx, unsigned char *secret, size_t *secretlen, const unsigned char *in, size_t inlen) { if (ctx == NULL || (in == NULL || inlen == 0) || (secret == NULL && secretlen == NULL)) return 0; if (ctx->operation != EVP_PKEY_OP_DECAPSULATE) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); return -1; } if (ctx->op.encap.algctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } return ctx->op.encap.kem->decapsulate(ctx->op.encap.algctx, secret, secretlen, in, inlen); } static EVP_KEM *evp_kem_new(OSSL_PROVIDER *prov) { EVP_KEM *kem = OPENSSL_zalloc(sizeof(EVP_KEM)); if (kem == NULL) return NULL; if (!CRYPTO_NEW_REF(&kem->refcnt, 1)) { OPENSSL_free(kem); return NULL; } kem->prov = prov; ossl_provider_up_ref(prov); return kem; } static void *evp_kem_from_algorithm(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { const OSSL_DISPATCH *fns = algodef->implementation; EVP_KEM *kem = NULL; int ctxfncnt = 0, encfncnt = 0, decfncnt = 0; int gparamfncnt = 0, sparamfncnt = 0; if ((kem = evp_kem_new(prov)) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); goto err; } kem->name_id = name_id; if ((kem->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) goto err; kem->description = algodef->algorithm_description; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_KEM_NEWCTX: if (kem->newctx != NULL) break; kem->newctx = OSSL_FUNC_kem_newctx(fns); ctxfncnt++; break; case OSSL_FUNC_KEM_ENCAPSULATE_INIT: if (kem->encapsulate_init != NULL) break; kem->encapsulate_init = OSSL_FUNC_kem_encapsulate_init(fns); encfncnt++; break; case OSSL_FUNC_KEM_AUTH_ENCAPSULATE_INIT: if (kem->auth_encapsulate_init != NULL) break; kem->auth_encapsulate_init = OSSL_FUNC_kem_auth_encapsulate_init(fns); encfncnt++; break; case OSSL_FUNC_KEM_ENCAPSULATE: if (kem->encapsulate != NULL) break; kem->encapsulate = OSSL_FUNC_kem_encapsulate(fns); encfncnt++; break; case OSSL_FUNC_KEM_DECAPSULATE_INIT: if (kem->decapsulate_init != NULL) break; kem->decapsulate_init = OSSL_FUNC_kem_decapsulate_init(fns); decfncnt++; break; case OSSL_FUNC_KEM_AUTH_DECAPSULATE_INIT: if (kem->auth_decapsulate_init != NULL) break; kem->auth_decapsulate_init = OSSL_FUNC_kem_auth_decapsulate_init(fns); decfncnt++; break; case OSSL_FUNC_KEM_DECAPSULATE: if (kem->decapsulate != NULL) break; kem->decapsulate = OSSL_FUNC_kem_decapsulate(fns); decfncnt++; break; case OSSL_FUNC_KEM_FREECTX: if (kem->freectx != NULL) break; kem->freectx = OSSL_FUNC_kem_freectx(fns); ctxfncnt++; break; case OSSL_FUNC_KEM_DUPCTX: if (kem->dupctx != NULL) break; kem->dupctx = OSSL_FUNC_kem_dupctx(fns); break; case OSSL_FUNC_KEM_GET_CTX_PARAMS: if (kem->get_ctx_params != NULL) break; kem->get_ctx_params = OSSL_FUNC_kem_get_ctx_params(fns); gparamfncnt++; break; case OSSL_FUNC_KEM_GETTABLE_CTX_PARAMS: if (kem->gettable_ctx_params != NULL) break; kem->gettable_ctx_params = OSSL_FUNC_kem_gettable_ctx_params(fns); gparamfncnt++; break; case OSSL_FUNC_KEM_SET_CTX_PARAMS: if (kem->set_ctx_params != NULL) break; kem->set_ctx_params = OSSL_FUNC_kem_set_ctx_params(fns); sparamfncnt++; break; case OSSL_FUNC_KEM_SETTABLE_CTX_PARAMS: if (kem->settable_ctx_params != NULL) break; kem->settable_ctx_params = OSSL_FUNC_kem_settable_ctx_params(fns); sparamfncnt++; break; } } if (ctxfncnt != 2 || (encfncnt != 0 && encfncnt != 2 && encfncnt != 3) || (decfncnt != 0 && decfncnt != 2 && decfncnt != 3) || (encfncnt != decfncnt) || (gparamfncnt != 0 && gparamfncnt != 2) || (sparamfncnt != 0 && sparamfncnt != 2)) { /* * In order to be a consistent set of functions we must have at least * a set of context functions (newctx and freectx) as well as a pair * (or triplet) of "kem" functions: * (encapsulate_init, (and/or auth_encapsulate_init), encapsulate) or * (decapsulate_init, (and/or auth_decapsulate_init), decapsulate). * set_ctx_params and settable_ctx_params are optional, but if one of * them is present then the other one must also be present. The same * applies to get_ctx_params and gettable_ctx_params. * The dupctx function is optional. */ ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS); goto err; } return kem; err: EVP_KEM_free(kem); return NULL; } void EVP_KEM_free(EVP_KEM *kem) { int i; if (kem == NULL) return; CRYPTO_DOWN_REF(&kem->refcnt, &i); if (i > 0) return; OPENSSL_free(kem->type_name); ossl_provider_free(kem->prov); CRYPTO_FREE_REF(&kem->refcnt); OPENSSL_free(kem); } int EVP_KEM_up_ref(EVP_KEM *kem) { int ref = 0; CRYPTO_UP_REF(&kem->refcnt, &ref); return 1; } OSSL_PROVIDER *EVP_KEM_get0_provider(const EVP_KEM *kem) { return kem->prov; } EVP_KEM *EVP_KEM_fetch(OSSL_LIB_CTX *ctx, const char *algorithm, const char *properties) { return evp_generic_fetch(ctx, OSSL_OP_KEM, algorithm, properties, evp_kem_from_algorithm, (int (*)(void *))EVP_KEM_up_ref, (void (*)(void *))EVP_KEM_free); } EVP_KEM *evp_kem_fetch_from_prov(OSSL_PROVIDER *prov, const char *algorithm, const char *properties) { return evp_generic_fetch_from_prov(prov, OSSL_OP_KEM, algorithm, properties, evp_kem_from_algorithm, (int (*)(void *))EVP_KEM_up_ref, (void (*)(void *))EVP_KEM_free); } int EVP_KEM_is_a(const EVP_KEM *kem, const char *name) { return kem != NULL && evp_is_a(kem->prov, kem->name_id, NULL, name); } int evp_kem_get_number(const EVP_KEM *kem) { return kem->name_id; } const char *EVP_KEM_get0_name(const EVP_KEM *kem) { return kem->type_name; } const char *EVP_KEM_get0_description(const EVP_KEM *kem) { return kem->description; } void EVP_KEM_do_all_provided(OSSL_LIB_CTX *libctx, void (*fn)(EVP_KEM *kem, void *arg), void *arg) { evp_generic_do_all(libctx, OSSL_OP_KEM, (void (*)(void *, void *))fn, arg, evp_kem_from_algorithm, (int (*)(void *))EVP_KEM_up_ref, (void (*)(void *))EVP_KEM_free); } int EVP_KEM_names_do_all(const EVP_KEM *kem, void (*fn)(const char *name, void *data), void *data) { if (kem->prov != NULL) return evp_names_do_all(kem->prov, kem->name_id, fn, data); return 1; } const OSSL_PARAM *EVP_KEM_gettable_ctx_params(const EVP_KEM *kem) { void *provctx; if (kem == NULL || kem->gettable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_KEM_get0_provider(kem)); return kem->gettable_ctx_params(NULL, provctx); } const OSSL_PARAM *EVP_KEM_settable_ctx_params(const EVP_KEM *kem) { void *provctx; if (kem == NULL || kem->settable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_KEM_get0_provider(kem)); return kem->settable_ctx_params(NULL, provctx); }
./openssl/crypto/evp/kdf_lib.c
/* * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2018-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 <stdio.h> #include <stdlib.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/kdf.h> #include <openssl/core.h> #include <openssl/core_names.h> #include "crypto/evp.h" #include "internal/numbers.h" #include "internal/provider.h" #include "evp_local.h" EVP_KDF_CTX *EVP_KDF_CTX_new(EVP_KDF *kdf) { EVP_KDF_CTX *ctx = NULL; if (kdf == NULL) return NULL; ctx = OPENSSL_zalloc(sizeof(EVP_KDF_CTX)); if (ctx == NULL || (ctx->algctx = kdf->newctx(ossl_provider_ctx(kdf->prov))) == NULL || !EVP_KDF_up_ref(kdf)) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); if (ctx != NULL) kdf->freectx(ctx->algctx); OPENSSL_free(ctx); ctx = NULL; } else { ctx->meth = kdf; } return ctx; } void EVP_KDF_CTX_free(EVP_KDF_CTX *ctx) { if (ctx == NULL) return; ctx->meth->freectx(ctx->algctx); ctx->algctx = NULL; EVP_KDF_free(ctx->meth); OPENSSL_free(ctx); } EVP_KDF_CTX *EVP_KDF_CTX_dup(const EVP_KDF_CTX *src) { EVP_KDF_CTX *dst; if (src == NULL || src->algctx == NULL || src->meth->dupctx == NULL) return NULL; dst = OPENSSL_malloc(sizeof(*dst)); if (dst == NULL) return NULL; memcpy(dst, src, sizeof(*dst)); if (!EVP_KDF_up_ref(dst->meth)) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); OPENSSL_free(dst); return NULL; } dst->algctx = src->meth->dupctx(src->algctx); if (dst->algctx == NULL) { EVP_KDF_CTX_free(dst); return NULL; } return dst; } int evp_kdf_get_number(const EVP_KDF *kdf) { return kdf->name_id; } const char *EVP_KDF_get0_name(const EVP_KDF *kdf) { return kdf->type_name; } const char *EVP_KDF_get0_description(const EVP_KDF *kdf) { return kdf->description; } int EVP_KDF_is_a(const EVP_KDF *kdf, const char *name) { return kdf != NULL && evp_is_a(kdf->prov, kdf->name_id, NULL, name); } const OSSL_PROVIDER *EVP_KDF_get0_provider(const EVP_KDF *kdf) { return kdf->prov; } const EVP_KDF *EVP_KDF_CTX_kdf(EVP_KDF_CTX *ctx) { return ctx->meth; } void EVP_KDF_CTX_reset(EVP_KDF_CTX *ctx) { if (ctx == NULL) return; if (ctx->meth->reset != NULL) ctx->meth->reset(ctx->algctx); } size_t EVP_KDF_CTX_get_kdf_size(EVP_KDF_CTX *ctx) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; size_t s = 0; if (ctx == NULL) return 0; *params = OSSL_PARAM_construct_size_t(OSSL_KDF_PARAM_SIZE, &s); if (ctx->meth->get_ctx_params != NULL && ctx->meth->get_ctx_params(ctx->algctx, params)) return s; if (ctx->meth->get_params != NULL && ctx->meth->get_params(params)) return s; return 0; } int EVP_KDF_derive(EVP_KDF_CTX *ctx, unsigned char *key, size_t keylen, const OSSL_PARAM params[]) { if (ctx == NULL) return 0; return ctx->meth->derive(ctx->algctx, key, keylen, params); } /* * The {get,set}_params functions return 1 if there is no corresponding * function in the implementation. This is the same as if there was one, * but it didn't recognise any of the given params, i.e. nothing in the * bag of parameters was useful. */ int EVP_KDF_get_params(EVP_KDF *kdf, OSSL_PARAM params[]) { if (kdf->get_params != NULL) return kdf->get_params(params); return 1; } int EVP_KDF_CTX_get_params(EVP_KDF_CTX *ctx, OSSL_PARAM params[]) { if (ctx->meth->get_ctx_params != NULL) return ctx->meth->get_ctx_params(ctx->algctx, params); return 1; } int EVP_KDF_CTX_set_params(EVP_KDF_CTX *ctx, const OSSL_PARAM params[]) { if (ctx->meth->set_ctx_params != NULL) return ctx->meth->set_ctx_params(ctx->algctx, params); return 1; } int EVP_KDF_names_do_all(const EVP_KDF *kdf, void (*fn)(const char *name, void *data), void *data) { if (kdf->prov != NULL) return evp_names_do_all(kdf->prov, kdf->name_id, fn, data); return 1; }
./openssl/crypto/evp/pbe_scrypt.c
/* * Copyright 2015-2021 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 <openssl/evp.h> #include <openssl/err.h> #include <openssl/kdf.h> #include <openssl/core_names.h> #include "internal/numbers.h" #ifndef OPENSSL_NO_SCRYPT /* * Maximum permitted memory allow this to be overridden with Configuration * option: e.g. -DSCRYPT_MAX_MEM=0 for maximum possible. */ #ifdef SCRYPT_MAX_MEM # if SCRYPT_MAX_MEM == 0 # undef SCRYPT_MAX_MEM /* * Although we could theoretically allocate SIZE_MAX memory that would leave * no memory available for anything else so set limit as half that. */ # define SCRYPT_MAX_MEM (SIZE_MAX/2) # endif #else /* Default memory limit: 32 MB */ # define SCRYPT_MAX_MEM (1024 * 1024 * 32) #endif int EVP_PBE_scrypt_ex(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, OSSL_LIB_CTX *ctx, const char *propq) { const char *empty = ""; int rv = 1; EVP_KDF *kdf; EVP_KDF_CTX *kctx; OSSL_PARAM params[7], *z = params; if (r > UINT32_MAX || p > UINT32_MAX) { ERR_raise(ERR_LIB_EVP, EVP_R_PARAMETER_TOO_LARGE); return 0; } /* Maintain existing behaviour. */ if (pass == NULL) { pass = empty; passlen = 0; } if (salt == NULL) { salt = (const unsigned char *)empty; saltlen = 0; } if (maxmem == 0) maxmem = SCRYPT_MAX_MEM; /* Use OSSL_LIB_CTX_set0_default() if you need a library context */ kdf = EVP_KDF_fetch(ctx, OSSL_KDF_NAME_SCRYPT, propq); kctx = EVP_KDF_CTX_new(kdf); EVP_KDF_free(kdf); if (kctx == NULL) return 0; *z++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, (unsigned char *)pass, passlen); *z++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, (unsigned char *)salt, saltlen); *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_N, &N); *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_R, &r); *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_P, &p); *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_MAXMEM, &maxmem); *z = OSSL_PARAM_construct_end(); if (EVP_KDF_derive(kctx, key, keylen, params) != 1) rv = 0; EVP_KDF_CTX_free(kctx); return rv; } int EVP_PBE_scrypt(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) { return EVP_PBE_scrypt_ex(pass, passlen, salt, saltlen, N, r, p, maxmem, key, keylen, NULL, NULL); } #endif
./openssl/crypto/evp/legacy_meth.h
/* * Copyright 2019-2021 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 */ #define IMPLEMENT_LEGACY_EVP_MD_METH(nm, fn) \ static int nm##_init(EVP_MD_CTX *ctx) \ { \ return fn##_Init(EVP_MD_CTX_get0_md_data(ctx)); \ } \ static int nm##_update(EVP_MD_CTX *ctx, const void *data, size_t count) \ { \ return fn##_Update(EVP_MD_CTX_get0_md_data(ctx), data, count); \ } \ static int nm##_final(EVP_MD_CTX *ctx, unsigned char *md) \ { \ return fn##_Final(md, EVP_MD_CTX_get0_md_data(ctx)); \ } #define IMPLEMENT_LEGACY_EVP_MD_METH_LC(nm, fn) \ static int nm##_init(EVP_MD_CTX *ctx) \ { \ return fn##_init(EVP_MD_CTX_get0_md_data(ctx)); \ } \ static int nm##_update(EVP_MD_CTX *ctx, const void *data, size_t count) \ { \ return fn##_update(EVP_MD_CTX_get0_md_data(ctx), data, count); \ } \ static int nm##_final(EVP_MD_CTX *ctx, unsigned char *md) \ { \ return fn##_final(md, EVP_MD_CTX_get0_md_data(ctx)); \ } #define LEGACY_EVP_MD_METH_TABLE(init, update, final, ctrl, blksz) \ init, update, final, NULL, NULL, blksz, 0, ctrl
./openssl/crypto/evp/e_null.c
/* * Copyright 1995-2021 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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/objects.h> #include "crypto/evp.h" static int null_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); static int null_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl); static const EVP_CIPHER n_cipher = { NID_undef, 1, 0, 0, 0, EVP_ORIG_GLOBAL, null_init_key, null_cipher, NULL, 0, NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_enc_null(void) { return &n_cipher; } static int null_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { return 1; } static int null_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { if (in != out) memcpy(out, in, inl); return 1; }
./openssl/crypto/evp/e_rc2.c
/* * Copyright 1995-2021 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 */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_RC2 # include <openssl/evp.h> # include <openssl/objects.h> # include "crypto/evp.h" # include <openssl/rc2.h> # include "evp_local.h" static int rc2_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); static int rc2_meth_to_magic(EVP_CIPHER_CTX *ctx); static int rc2_magic_to_meth(int i); static int rc2_set_asn1_type_and_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type); static int rc2_get_asn1_type_and_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type); static int rc2_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr); typedef struct { int key_bits; /* effective key bits */ RC2_KEY ks; /* key schedule */ } EVP_RC2_KEY; # define data(ctx) EVP_C_DATA(EVP_RC2_KEY,ctx) IMPLEMENT_BLOCK_CIPHER(rc2, ks, RC2, EVP_RC2_KEY, NID_rc2, 8, RC2_KEY_LENGTH, 8, 64, EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CTRL_INIT, rc2_init_key, NULL, rc2_set_asn1_type_and_iv, rc2_get_asn1_type_and_iv, rc2_ctrl) # define RC2_40_MAGIC 0xa0 # define RC2_64_MAGIC 0x78 # define RC2_128_MAGIC 0x3a static const EVP_CIPHER r2_64_cbc_cipher = { NID_rc2_64_cbc, 8, 8 /* 64 bit */ , 8, EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CTRL_INIT, EVP_ORIG_GLOBAL, rc2_init_key, rc2_cbc_cipher, NULL, sizeof(EVP_RC2_KEY), rc2_set_asn1_type_and_iv, rc2_get_asn1_type_and_iv, rc2_ctrl, NULL }; static const EVP_CIPHER r2_40_cbc_cipher = { NID_rc2_40_cbc, 8, 5 /* 40 bit */ , 8, EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_CTRL_INIT, EVP_ORIG_GLOBAL, rc2_init_key, rc2_cbc_cipher, NULL, sizeof(EVP_RC2_KEY), rc2_set_asn1_type_and_iv, rc2_get_asn1_type_and_iv, rc2_ctrl, NULL }; const EVP_CIPHER *EVP_rc2_64_cbc(void) { return &r2_64_cbc_cipher; } const EVP_CIPHER *EVP_rc2_40_cbc(void) { return &r2_40_cbc_cipher; } static int rc2_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { RC2_set_key(&data(ctx)->ks, EVP_CIPHER_CTX_get_key_length(ctx), key, data(ctx)->key_bits); return 1; } static int rc2_meth_to_magic(EVP_CIPHER_CTX *e) { int i; if (EVP_CIPHER_CTX_ctrl(e, EVP_CTRL_GET_RC2_KEY_BITS, 0, &i) <= 0) return 0; if (i == 128) return RC2_128_MAGIC; else if (i == 64) return RC2_64_MAGIC; else if (i == 40) return RC2_40_MAGIC; else return 0; } static int rc2_magic_to_meth(int i) { if (i == RC2_128_MAGIC) return 128; else if (i == RC2_64_MAGIC) return 64; else if (i == RC2_40_MAGIC) return 40; else { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_SIZE); return 0; } } static int rc2_get_asn1_type_and_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type) { long num = 0; int i = 0; int key_bits; unsigned int l; unsigned char iv[EVP_MAX_IV_LENGTH]; if (type != NULL) { l = EVP_CIPHER_CTX_get_iv_length(c); OPENSSL_assert(l <= sizeof(iv)); i = ASN1_TYPE_get_int_octetstring(type, &num, iv, l); if (i != (int)l) return -1; key_bits = rc2_magic_to_meth((int)num); if (!key_bits) return -1; if (i > 0 && !EVP_CipherInit_ex(c, NULL, NULL, NULL, iv, -1)) return -1; if (EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_RC2_KEY_BITS, key_bits, NULL) <= 0 || EVP_CIPHER_CTX_set_key_length(c, key_bits / 8) <= 0) return -1; } return i; } static int rc2_set_asn1_type_and_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type) { long num; int i = 0, j; if (type != NULL) { num = rc2_meth_to_magic(c); j = EVP_CIPHER_CTX_get_iv_length(c); i = ASN1_TYPE_set_int_octetstring(type, num, c->oiv, j); } return i; } static int rc2_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { switch (type) { case EVP_CTRL_INIT: data(c)->key_bits = EVP_CIPHER_CTX_get_key_length(c) * 8; return 1; case EVP_CTRL_GET_RC2_KEY_BITS: *(int *)ptr = data(c)->key_bits; return 1; case EVP_CTRL_SET_RC2_KEY_BITS: if (arg > 0) { data(c)->key_bits = arg; return 1; } return 0; # ifdef PBE_PRF_TEST case EVP_CTRL_PBE_PRF_NID: *(int *)ptr = NID_hmacWithMD5; return 1; # endif default: return -1; } } #endif
./openssl/crypto/evp/e_rc4_hmac_md5.c
/* * Copyright 2011-2021 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 */ /* * MD5 and RC4 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "internal/cryptlib.h" #include <openssl/opensslconf.h> #include <stdio.h> #include <string.h> #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_MD5) # include <openssl/crypto.h> # include <openssl/evp.h> # include <openssl/objects.h> # include <openssl/rc4.h> # include <openssl/md5.h> # include "crypto/evp.h" typedef struct { RC4_KEY ks; MD5_CTX head, tail, md; size_t payload_length; } EVP_RC4_HMAC_MD5; # define NO_PAYLOAD_LENGTH ((size_t)-1) void rc4_md5_enc(RC4_KEY *key, const void *in0, void *out, MD5_CTX *ctx, const void *inp, size_t blocks); # define data(ctx) ((EVP_RC4_HMAC_MD5 *)EVP_CIPHER_CTX_get_cipher_data(ctx)) static int rc4_hmac_md5_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *inkey, const unsigned char *iv, int enc) { EVP_RC4_HMAC_MD5 *key = data(ctx); const int keylen = EVP_CIPHER_CTX_get_key_length(ctx); if (keylen <= 0) return 0; RC4_set_key(&key->ks, keylen, inkey); MD5_Init(&key->head); /* handy when benchmarking */ key->tail = key->head; key->md = key->head; key->payload_length = NO_PAYLOAD_LENGTH; return 1; } # if defined(RC4_ASM) && defined(MD5_ASM) && ( \ defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64) ) # define STITCHED_CALL # endif # if !defined(STITCHED_CALL) # define rc4_off 0 # define md5_off 0 # endif static int rc4_hmac_md5_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_RC4_HMAC_MD5 *key = data(ctx); # if defined(STITCHED_CALL) size_t rc4_off = 32 - 1 - (key->ks.x & (32 - 1)), /* 32 is $MOD from * rc4_md5-x86_64.pl */ md5_off = MD5_CBLOCK - key->md.num, blocks; unsigned int l; # endif size_t plen = key->payload_length; if (plen != NO_PAYLOAD_LENGTH && len != (plen + MD5_DIGEST_LENGTH)) return 0; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (plen == NO_PAYLOAD_LENGTH) plen = len; # if defined(STITCHED_CALL) /* cipher has to "fall behind" */ if (rc4_off > md5_off) md5_off += MD5_CBLOCK; if (plen > md5_off && (blocks = (plen - md5_off) / MD5_CBLOCK) && (OPENSSL_ia32cap_P[0] & (1 << 20)) == 0) { MD5_Update(&key->md, in, md5_off); RC4(&key->ks, rc4_off, in, out); rc4_md5_enc(&key->ks, in + rc4_off, out + rc4_off, &key->md, in + md5_off, blocks); blocks *= MD5_CBLOCK; rc4_off += blocks; md5_off += blocks; key->md.Nh += blocks >> 29; key->md.Nl += blocks <<= 3; if (key->md.Nl < (unsigned int)blocks) key->md.Nh++; } else { rc4_off = 0; md5_off = 0; } # endif MD5_Update(&key->md, in + md5_off, plen - md5_off); if (plen != len) { /* "TLS" mode of operation */ if (in != out) memcpy(out + rc4_off, in + rc4_off, plen - rc4_off); /* calculate HMAC and append it to payload */ MD5_Final(out + plen, &key->md); key->md = key->tail; MD5_Update(&key->md, out + plen, MD5_DIGEST_LENGTH); MD5_Final(out + plen, &key->md); /* encrypt HMAC at once */ RC4(&key->ks, len - rc4_off, out + rc4_off, out + rc4_off); } else { RC4(&key->ks, len - rc4_off, in + rc4_off, out + rc4_off); } } else { unsigned char mac[MD5_DIGEST_LENGTH]; # if defined(STITCHED_CALL) /* digest has to "fall behind" */ if (md5_off > rc4_off) rc4_off += 2 * MD5_CBLOCK; else rc4_off += MD5_CBLOCK; if (len > rc4_off && (blocks = (len - rc4_off) / MD5_CBLOCK) && (OPENSSL_ia32cap_P[0] & (1 << 20)) == 0) { RC4(&key->ks, rc4_off, in, out); MD5_Update(&key->md, out, md5_off); rc4_md5_enc(&key->ks, in + rc4_off, out + rc4_off, &key->md, out + md5_off, blocks); blocks *= MD5_CBLOCK; rc4_off += blocks; md5_off += blocks; l = (key->md.Nl + (blocks << 3)) & 0xffffffffU; if (l < key->md.Nl) key->md.Nh++; key->md.Nl = l; key->md.Nh += blocks >> 29; } else { md5_off = 0; rc4_off = 0; } # endif /* decrypt HMAC at once */ RC4(&key->ks, len - rc4_off, in + rc4_off, out + rc4_off); if (plen != NO_PAYLOAD_LENGTH) { /* "TLS" mode of operation */ MD5_Update(&key->md, out + md5_off, plen - md5_off); /* calculate HMAC and verify it */ MD5_Final(mac, &key->md); key->md = key->tail; MD5_Update(&key->md, mac, MD5_DIGEST_LENGTH); MD5_Final(mac, &key->md); if (CRYPTO_memcmp(out + plen, mac, MD5_DIGEST_LENGTH)) return 0; } else { MD5_Update(&key->md, out + md5_off, len - md5_off); } } key->payload_length = NO_PAYLOAD_LENGTH; return 1; } static int rc4_hmac_md5_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { EVP_RC4_HMAC_MD5 *key = data(ctx); switch (type) { case EVP_CTRL_AEAD_SET_MAC_KEY: { unsigned int i; unsigned char hmac_key[64]; memset(hmac_key, 0, sizeof(hmac_key)); if (arg > (int)sizeof(hmac_key)) { MD5_Init(&key->head); MD5_Update(&key->head, ptr, arg); MD5_Final(hmac_key, &key->head); } else { memcpy(hmac_key, ptr, arg); } for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36; /* ipad */ MD5_Init(&key->head); MD5_Update(&key->head, hmac_key, sizeof(hmac_key)); for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36 ^ 0x5c; /* opad */ MD5_Init(&key->tail); MD5_Update(&key->tail, hmac_key, sizeof(hmac_key)); OPENSSL_cleanse(hmac_key, sizeof(hmac_key)); return 1; } case EVP_CTRL_AEAD_TLS1_AAD: { unsigned char *p = ptr; unsigned int len; if (arg != EVP_AEAD_TLS1_AAD_LEN) return -1; len = p[arg - 2] << 8 | p[arg - 1]; if (!EVP_CIPHER_CTX_is_encrypting(ctx)) { if (len < MD5_DIGEST_LENGTH) return -1; len -= MD5_DIGEST_LENGTH; p[arg - 2] = len >> 8; p[arg - 1] = len; } key->payload_length = len; key->md = key->head; MD5_Update(&key->md, p, arg); return MD5_DIGEST_LENGTH; } default: return -1; } } static EVP_CIPHER r4_hmac_md5_cipher = { # ifdef NID_rc4_hmac_md5 NID_rc4_hmac_md5, # else NID_undef, # endif 1, EVP_RC4_KEY_SIZE, 0, EVP_CIPH_STREAM_CIPHER | EVP_CIPH_VARIABLE_LENGTH | EVP_CIPH_FLAG_AEAD_CIPHER, EVP_ORIG_GLOBAL, rc4_hmac_md5_init_key, rc4_hmac_md5_cipher, NULL, sizeof(EVP_RC4_HMAC_MD5), NULL, NULL, rc4_hmac_md5_ctrl, NULL }; const EVP_CIPHER *EVP_rc4_hmac_md5(void) { return &r4_hmac_md5_cipher; } #endif
./openssl/crypto/evp/e_old.c
/* * Copyright 2004-2020 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 <openssl/opensslconf.h> #include <openssl/evp.h> /* * Define some deprecated functions, so older programs don't crash and burn * too quickly. On Windows and VMS, these will never be used, since * functions and variables in shared libraries are selected by entry point * location, not by name. */ #ifndef OPENSSL_NO_BF # undef EVP_bf_cfb const EVP_CIPHER *EVP_bf_cfb(void); const EVP_CIPHER *EVP_bf_cfb(void) { return EVP_bf_cfb64(); } #endif #ifndef OPENSSL_NO_DES # undef EVP_des_cfb const EVP_CIPHER *EVP_des_cfb(void); const EVP_CIPHER *EVP_des_cfb(void) { return EVP_des_cfb64(); } # undef EVP_des_ede3_cfb const EVP_CIPHER *EVP_des_ede3_cfb(void); const EVP_CIPHER *EVP_des_ede3_cfb(void) { return EVP_des_ede3_cfb64(); } # undef EVP_des_ede_cfb const EVP_CIPHER *EVP_des_ede_cfb(void); const EVP_CIPHER *EVP_des_ede_cfb(void) { return EVP_des_ede_cfb64(); } #endif #ifndef OPENSSL_NO_IDEA # undef EVP_idea_cfb const EVP_CIPHER *EVP_idea_cfb(void); const EVP_CIPHER *EVP_idea_cfb(void) { return EVP_idea_cfb64(); } #endif #ifndef OPENSSL_NO_RC2 # undef EVP_rc2_cfb const EVP_CIPHER *EVP_rc2_cfb(void); const EVP_CIPHER *EVP_rc2_cfb(void) { return EVP_rc2_cfb64(); } #endif #ifndef OPENSSL_NO_CAST # undef EVP_cast5_cfb const EVP_CIPHER *EVP_cast5_cfb(void); const EVP_CIPHER *EVP_cast5_cfb(void) { return EVP_cast5_cfb64(); } #endif #ifndef OPENSSL_NO_RC5 # undef EVP_rc5_32_12_16_cfb const EVP_CIPHER *EVP_rc5_32_12_16_cfb(void); const EVP_CIPHER *EVP_rc5_32_12_16_cfb(void) { return EVP_rc5_32_12_16_cfb64(); } #endif #undef EVP_aes_128_cfb const EVP_CIPHER *EVP_aes_128_cfb(void); const EVP_CIPHER *EVP_aes_128_cfb(void) { return EVP_aes_128_cfb128(); } #undef EVP_aes_192_cfb const EVP_CIPHER *EVP_aes_192_cfb(void); const EVP_CIPHER *EVP_aes_192_cfb(void) { return EVP_aes_192_cfb128(); } #undef EVP_aes_256_cfb const EVP_CIPHER *EVP_aes_256_cfb(void); const EVP_CIPHER *EVP_aes_256_cfb(void) { return EVP_aes_256_cfb128(); }
./openssl/crypto/evp/evp_utils.c
/* * Copyright 2019-2021 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 */ /* Internal EVP utility functions */ #include <openssl/core.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/asn1.h> /* evp_local.h needs it */ #include <openssl/safestack.h> /* evp_local.h needs it */ #include "crypto/evp.h" /* evp_local.h needs it */ #include "evp_local.h" /* * EVP_CTRL_RET_UNSUPPORTED = -1 is the returned value from any ctrl function * where the control command isn't supported, and an alternative code path * may be chosen. * Since these functions are used to implement ctrl functionality, we * use the same value, and other callers will have to compensate. */ #define PARAM_CHECK(obj, func, errfunc) \ if (obj == NULL) \ return 0; \ if (obj->prov == NULL) \ return EVP_CTRL_RET_UNSUPPORTED; \ if (obj->func == NULL) { \ errfunc(); \ return 0; \ } #define PARAM_FUNC(name, func, type, err) \ int name (const type *obj, OSSL_PARAM params[]) \ { \ PARAM_CHECK(obj, func, err) \ return obj->func(params); \ } #define PARAM_CTX_FUNC(name, func, type, err) \ int name (const type *obj, void *algctx, OSSL_PARAM params[]) \ { \ PARAM_CHECK(obj, func, err) \ return obj->func(algctx, params); \ } #define PARAM_FUNCTIONS(type, \ getname, getfunc, \ getctxname, getctxfunc, \ setctxname, setctxfunc) \ PARAM_FUNC(getname, getfunc, type, geterr) \ PARAM_CTX_FUNC(getctxname, getctxfunc, type, geterr) \ PARAM_CTX_FUNC(setctxname, setctxfunc, type, seterr) /* * These error functions are a workaround for the error scripts, which * currently require that XXXerr method appears inside a function (not a macro). */ static void geterr(void) { ERR_raise(ERR_LIB_EVP, EVP_R_CANNOT_GET_PARAMETERS); } static void seterr(void) { ERR_raise(ERR_LIB_EVP, EVP_R_CANNOT_SET_PARAMETERS); } PARAM_FUNCTIONS(EVP_CIPHER, evp_do_ciph_getparams, get_params, evp_do_ciph_ctx_getparams, get_ctx_params, evp_do_ciph_ctx_setparams, set_ctx_params) PARAM_FUNCTIONS(EVP_MD, evp_do_md_getparams, get_params, evp_do_md_ctx_getparams, get_ctx_params, evp_do_md_ctx_setparams, set_ctx_params)
./openssl/crypto/evp/legacy_md2.c
/* * Copyright 2015-2021 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 */ /* * MD2 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/md2.h> #include "crypto/evp.h" #include "legacy_meth.h" IMPLEMENT_LEGACY_EVP_MD_METH(md2, MD2) static const EVP_MD md2_md = { NID_md2, NID_md2WithRSAEncryption, MD2_DIGEST_LENGTH, 0, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(md2_init, md2_update, md2_final, NULL, MD2_BLOCK) }; const EVP_MD *EVP_md2(void) { return &md2_md; }
./openssl/crypto/evp/evp_fetch.c
/* * Copyright 2019-2023 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 <stddef.h> #include <openssl/types.h> #include <openssl/evp.h> #include <openssl/core.h> #include "internal/cryptlib.h" #include "internal/thread_once.h" #include "internal/property.h" #include "internal/core.h" #include "internal/provider.h" #include "internal/namemap.h" #include "crypto/decoder.h" #include "crypto/evp.h" /* evp_local.h needs it */ #include "evp_local.h" #define NAME_SEPARATOR ':' /* Data to be passed through ossl_method_construct() */ struct evp_method_data_st { OSSL_LIB_CTX *libctx; int operation_id; /* For get_evp_method_from_store() */ int name_id; /* For get_evp_method_from_store() */ const char *names; /* For get_evp_method_from_store() */ const char *propquery; /* For get_evp_method_from_store() */ OSSL_METHOD_STORE *tmp_store; /* For get_tmp_evp_method_store() */ unsigned int flag_construct_error_occurred : 1; void *(*method_from_algorithm)(int name_id, const OSSL_ALGORITHM *, OSSL_PROVIDER *); int (*refcnt_up_method)(void *method); void (*destruct_method)(void *method); }; /* * Generic routines to fetch / create EVP methods with ossl_method_construct() */ static void *get_tmp_evp_method_store(void *data) { struct evp_method_data_st *methdata = data; if (methdata->tmp_store == NULL) methdata->tmp_store = ossl_method_store_new(methdata->libctx); return methdata->tmp_store; } static void dealloc_tmp_evp_method_store(void *store) { if (store != NULL) ossl_method_store_free(store); } static OSSL_METHOD_STORE *get_evp_method_store(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_EVP_METHOD_STORE_INDEX); } static int reserve_evp_method_store(void *store, void *data) { struct evp_method_data_st *methdata = data; if (store == NULL && (store = get_evp_method_store(methdata->libctx)) == NULL) return 0; return ossl_method_lock_store(store); } static int unreserve_evp_method_store(void *store, void *data) { struct evp_method_data_st *methdata = data; if (store == NULL && (store = get_evp_method_store(methdata->libctx)) == NULL) return 0; return ossl_method_unlock_store(store); } /* * To identify the method in the EVP method store, we mix the name identity * with the operation identity, under the assumption that we don't have more * than 2^23 names or more than 2^8 operation types. * * The resulting identity is a 31-bit integer, composed like this: * * +---------23 bits--------+-8 bits-+ * | name identity | op id | * +------------------------+--------+ * * We limit this composite number to 31 bits, thus leaving the top uint32_t * bit always zero, to avoid negative sign extension when downshifting after * this number happens to be passed to an int (which happens as soon as it's * passed to ossl_method_store_cache_set(), and it's in that form that it * gets passed along to filter_on_operation_id(), defined further down. */ #define METHOD_ID_OPERATION_MASK 0x000000FF #define METHOD_ID_OPERATION_MAX ((1 << 8) - 1) #define METHOD_ID_NAME_MASK 0x7FFFFF00 #define METHOD_ID_NAME_OFFSET 8 #define METHOD_ID_NAME_MAX ((1 << 23) - 1) static uint32_t evp_method_id(int name_id, unsigned int operation_id) { if (!ossl_assert(name_id > 0 && name_id <= METHOD_ID_NAME_MAX) || !ossl_assert(operation_id > 0 && operation_id <= METHOD_ID_OPERATION_MAX)) return 0; return (((name_id << METHOD_ID_NAME_OFFSET) & METHOD_ID_NAME_MASK) | (operation_id & METHOD_ID_OPERATION_MASK)); } static void *get_evp_method_from_store(void *store, const OSSL_PROVIDER **prov, void *data) { struct evp_method_data_st *methdata = data; void *method = NULL; int name_id; uint32_t meth_id; /* * get_evp_method_from_store() is only called to try and get the method * that evp_generic_fetch() is asking for, and the operation id as well * as the name or name id are passed via methdata. */ if ((name_id = methdata->name_id) == 0 && methdata->names != NULL) { OSSL_NAMEMAP *namemap = ossl_namemap_stored(methdata->libctx); const char *names = methdata->names; const char *q = strchr(names, NAME_SEPARATOR); size_t l = (q == NULL ? strlen(names) : (size_t)(q - names)); if (namemap == 0) return NULL; name_id = ossl_namemap_name2num_n(namemap, names, l); } if (name_id == 0 || (meth_id = evp_method_id(name_id, methdata->operation_id)) == 0) return NULL; if (store == NULL && (store = get_evp_method_store(methdata->libctx)) == NULL) return NULL; if (!ossl_method_store_fetch(store, meth_id, methdata->propquery, prov, &method)) return NULL; return method; } static int put_evp_method_in_store(void *store, void *method, const OSSL_PROVIDER *prov, const char *names, const char *propdef, void *data) { struct evp_method_data_st *methdata = data; OSSL_NAMEMAP *namemap; int name_id; uint32_t meth_id; size_t l = 0; /* * put_evp_method_in_store() is only called with an EVP method that was * successfully created by construct_method() below, which means that * all the names should already be stored in the namemap with the same * numeric identity, so just use the first to get that identity. */ if (names != NULL) { const char *q = strchr(names, NAME_SEPARATOR); l = (q == NULL ? strlen(names) : (size_t)(q - names)); } if ((namemap = ossl_namemap_stored(methdata->libctx)) == NULL || (name_id = ossl_namemap_name2num_n(namemap, names, l)) == 0 || (meth_id = evp_method_id(name_id, methdata->operation_id)) == 0) return 0; if (store == NULL && (store = get_evp_method_store(methdata->libctx)) == NULL) return 0; return ossl_method_store_add(store, prov, meth_id, propdef, method, methdata->refcnt_up_method, methdata->destruct_method); } /* * The core fetching functionality passes the name of the implementation. * This function is responsible to getting an identity number for it. */ static void *construct_evp_method(const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov, void *data) { /* * This function is only called if get_evp_method_from_store() returned * NULL, so it's safe to say that of all the spots to create a new * namemap entry, this is it. Should the name already exist there, we * know that ossl_namemap_add_name() will return its corresponding * number. */ struct evp_method_data_st *methdata = data; OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); const char *names = algodef->algorithm_names; int name_id = ossl_namemap_add_names(namemap, 0, names, NAME_SEPARATOR); void *method; if (name_id == 0) return NULL; method = methdata->method_from_algorithm(name_id, algodef, prov); /* * Flag to indicate that there was actual construction errors. This * helps inner_evp_generic_fetch() determine what error it should * record on inaccessible algorithms. */ if (method == NULL) methdata->flag_construct_error_occurred = 1; return method; } static void destruct_evp_method(void *method, void *data) { struct evp_method_data_st *methdata = data; methdata->destruct_method(method); } static void * inner_evp_generic_fetch(struct evp_method_data_st *methdata, OSSL_PROVIDER *prov, int operation_id, const char *name, const char *properties, void *(*new_method)(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov), int (*up_ref_method)(void *), void (*free_method)(void *)) { OSSL_METHOD_STORE *store = get_evp_method_store(methdata->libctx); OSSL_NAMEMAP *namemap = ossl_namemap_stored(methdata->libctx); const char *const propq = properties != NULL ? properties : ""; uint32_t meth_id = 0; void *method = NULL; int unsupported, name_id; if (store == NULL || namemap == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } /* * If there's ever an operation_id == 0 passed, we have an internal * programming error. */ if (!ossl_assert(operation_id > 0)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return NULL; } /* If we haven't received a name id yet, try to get one for the name */ name_id = name != NULL ? ossl_namemap_name2num(namemap, name) : 0; /* * If we have a name id, calculate a method id with evp_method_id(). * * evp_method_id returns 0 if we have too many operations (more than * about 2^8) or too many names (more than about 2^24). In that case, * we can't create any new method. * For all intents and purposes, this is an internal error. */ if (name_id != 0 && (meth_id = evp_method_id(name_id, operation_id)) == 0) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return NULL; } /* * If we haven't found the name yet, chances are that the algorithm to * be fetched is unsupported. */ unsupported = name_id == 0; if (meth_id == 0 || !ossl_method_store_cache_get(store, prov, meth_id, propq, &method)) { OSSL_METHOD_CONSTRUCT_METHOD mcm = { get_tmp_evp_method_store, reserve_evp_method_store, unreserve_evp_method_store, get_evp_method_from_store, put_evp_method_in_store, construct_evp_method, destruct_evp_method }; methdata->operation_id = operation_id; methdata->name_id = name_id; methdata->names = name; methdata->propquery = propq; methdata->method_from_algorithm = new_method; methdata->refcnt_up_method = up_ref_method; methdata->destruct_method = free_method; methdata->flag_construct_error_occurred = 0; if ((method = ossl_method_construct(methdata->libctx, operation_id, &prov, 0 /* !force_cache */, &mcm, methdata)) != NULL) { /* * If construction did create a method for us, we know that * there is a correct name_id and meth_id, since those have * already been calculated in get_evp_method_from_store() and * put_evp_method_in_store() above. * Note that there is a corner case here, in which, if a user * passes a name of the form name1:name2:..., then the construction * will create a method against all names, but the lookup will fail * as ossl_namemap_name2num treats the name string as a single name * rather than introducing new features where in the EVP_<obj>_fetch * parses the string and querys for each, return an error. */ if (name_id == 0) name_id = ossl_namemap_name2num(namemap, name); if (name_id == 0) { ERR_raise_data(ERR_LIB_EVP, ERR_R_FETCH_FAILED, "Algorithm %s cannot be found", name); free_method(method); method = NULL; } else { meth_id = evp_method_id(name_id, operation_id); if (meth_id != 0) ossl_method_store_cache_set(store, prov, meth_id, propq, method, up_ref_method, free_method); } } /* * If we never were in the constructor, the algorithm to be fetched * is unsupported. */ unsupported = !methdata->flag_construct_error_occurred; } if ((name_id != 0 || name != NULL) && method == NULL) { int code = unsupported ? ERR_R_UNSUPPORTED : ERR_R_FETCH_FAILED; if (name == NULL) name = ossl_namemap_num2name(namemap, name_id, 0); ERR_raise_data(ERR_LIB_EVP, code, "%s, Algorithm (%s : %d), Properties (%s)", ossl_lib_ctx_get_descriptor(methdata->libctx), name == NULL ? "<null>" : name, name_id, properties == NULL ? "<null>" : properties); } return method; } void *evp_generic_fetch(OSSL_LIB_CTX *libctx, int operation_id, const char *name, const char *properties, void *(*new_method)(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov), int (*up_ref_method)(void *), void (*free_method)(void *)) { struct evp_method_data_st methdata; void *method; methdata.libctx = libctx; methdata.tmp_store = NULL; method = inner_evp_generic_fetch(&methdata, NULL, operation_id, name, properties, new_method, up_ref_method, free_method); dealloc_tmp_evp_method_store(methdata.tmp_store); return method; } /* * evp_generic_fetch_from_prov() is special, and only returns methods from * the given provider. * This is meant to be used when one method needs to fetch an associated * method. */ void *evp_generic_fetch_from_prov(OSSL_PROVIDER *prov, int operation_id, const char *name, const char *properties, void *(*new_method)(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov), int (*up_ref_method)(void *), void (*free_method)(void *)) { struct evp_method_data_st methdata; void *method; methdata.libctx = ossl_provider_libctx(prov); methdata.tmp_store = NULL; method = inner_evp_generic_fetch(&methdata, prov, operation_id, name, properties, new_method, up_ref_method, free_method); dealloc_tmp_evp_method_store(methdata.tmp_store); return method; } int evp_method_store_cache_flush(OSSL_LIB_CTX *libctx) { OSSL_METHOD_STORE *store = get_evp_method_store(libctx); if (store != NULL) return ossl_method_store_cache_flush_all(store); return 1; } int evp_method_store_remove_all_provided(const OSSL_PROVIDER *prov) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_METHOD_STORE *store = get_evp_method_store(libctx); if (store != NULL) return ossl_method_store_remove_all_provided(store, prov); return 1; } static int evp_set_parsed_default_properties(OSSL_LIB_CTX *libctx, OSSL_PROPERTY_LIST *def_prop, int loadconfig, int mirrored) { OSSL_METHOD_STORE *store = get_evp_method_store(libctx); OSSL_PROPERTY_LIST **plp = ossl_ctx_global_properties(libctx, loadconfig); if (plp != NULL && store != NULL) { int ret; #ifndef FIPS_MODULE char *propstr = NULL; size_t strsz; if (mirrored) { if (ossl_global_properties_no_mirrored(libctx)) return 0; } else { /* * These properties have been explicitly set on this libctx, so * don't allow any mirroring from a parent libctx. */ ossl_global_properties_stop_mirroring(libctx); } strsz = ossl_property_list_to_string(libctx, def_prop, NULL, 0); if (strsz > 0) propstr = OPENSSL_malloc(strsz); if (propstr == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } if (ossl_property_list_to_string(libctx, def_prop, propstr, strsz) == 0) { OPENSSL_free(propstr); ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } ossl_provider_default_props_update(libctx, propstr); OPENSSL_free(propstr); #endif ossl_property_free(*plp); *plp = def_prop; ret = ossl_method_store_cache_flush_all(store); #ifndef FIPS_MODULE ossl_decoder_cache_flush(libctx); #endif return ret; } ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } int evp_set_default_properties_int(OSSL_LIB_CTX *libctx, const char *propq, int loadconfig, int mirrored) { OSSL_PROPERTY_LIST *pl = NULL; if (propq != NULL && (pl = ossl_parse_query(libctx, propq, 1)) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_DEFAULT_QUERY_PARSE_ERROR); return 0; } if (!evp_set_parsed_default_properties(libctx, pl, loadconfig, mirrored)) { ossl_property_free(pl); return 0; } return 1; } int EVP_set_default_properties(OSSL_LIB_CTX *libctx, const char *propq) { return evp_set_default_properties_int(libctx, propq, 1, 0); } static int evp_default_properties_merge(OSSL_LIB_CTX *libctx, const char *propq, int loadconfig) { OSSL_PROPERTY_LIST **plp = ossl_ctx_global_properties(libctx, loadconfig); OSSL_PROPERTY_LIST *pl1, *pl2; if (propq == NULL) return 1; if (plp == NULL || *plp == NULL) return evp_set_default_properties_int(libctx, propq, 0, 0); if ((pl1 = ossl_parse_query(libctx, propq, 1)) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_DEFAULT_QUERY_PARSE_ERROR); return 0; } pl2 = ossl_property_merge(pl1, *plp); ossl_property_free(pl1); if (pl2 == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_CRYPTO_LIB); return 0; } if (!evp_set_parsed_default_properties(libctx, pl2, 0, 0)) { ossl_property_free(pl2); return 0; } return 1; } static int evp_default_property_is_enabled(OSSL_LIB_CTX *libctx, const char *prop_name) { OSSL_PROPERTY_LIST **plp = ossl_ctx_global_properties(libctx, 1); return plp != NULL && ossl_property_is_enabled(libctx, prop_name, *plp); } int EVP_default_properties_is_fips_enabled(OSSL_LIB_CTX *libctx) { return evp_default_property_is_enabled(libctx, "fips"); } int evp_default_properties_enable_fips_int(OSSL_LIB_CTX *libctx, int enable, int loadconfig) { const char *query = (enable != 0) ? "fips=yes" : "-fips"; return evp_default_properties_merge(libctx, query, loadconfig); } int EVP_default_properties_enable_fips(OSSL_LIB_CTX *libctx, int enable) { return evp_default_properties_enable_fips_int(libctx, enable, 1); } char *evp_get_global_properties_str(OSSL_LIB_CTX *libctx, int loadconfig) { OSSL_PROPERTY_LIST **plp = ossl_ctx_global_properties(libctx, loadconfig); char *propstr = NULL; size_t sz; if (plp == NULL) return OPENSSL_strdup(""); sz = ossl_property_list_to_string(libctx, *plp, NULL, 0); if (sz == 0) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return NULL; } propstr = OPENSSL_malloc(sz); if (propstr == NULL) return NULL; if (ossl_property_list_to_string(libctx, *plp, propstr, sz) == 0) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); OPENSSL_free(propstr); return NULL; } return propstr; } struct filter_data_st { int operation_id; void (*user_fn)(void *method, void *arg); void *user_arg; }; static void filter_on_operation_id(int id, void *method, void *arg) { struct filter_data_st *data = arg; if ((id & METHOD_ID_OPERATION_MASK) == data->operation_id) data->user_fn(method, data->user_arg); } void evp_generic_do_all(OSSL_LIB_CTX *libctx, int operation_id, void (*user_fn)(void *method, void *arg), void *user_arg, void *(*new_method)(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov), int (*up_ref_method)(void *), void (*free_method)(void *)) { struct evp_method_data_st methdata; struct filter_data_st data; methdata.libctx = libctx; methdata.tmp_store = NULL; (void)inner_evp_generic_fetch(&methdata, NULL, operation_id, NULL, NULL, new_method, up_ref_method, free_method); data.operation_id = operation_id; data.user_fn = user_fn; data.user_arg = user_arg; if (methdata.tmp_store != NULL) ossl_method_store_do_all(methdata.tmp_store, &filter_on_operation_id, &data); ossl_method_store_do_all(get_evp_method_store(libctx), &filter_on_operation_id, &data); dealloc_tmp_evp_method_store(methdata.tmp_store); } int evp_is_a(OSSL_PROVIDER *prov, int number, const char *legacy_name, const char *name) { /* * For a |prov| that is NULL, the library context will be NULL */ OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); if (prov == NULL) number = ossl_namemap_name2num(namemap, legacy_name); return ossl_namemap_name2num(namemap, name) == number; } int evp_names_do_all(OSSL_PROVIDER *prov, int number, void (*fn)(const char *name, void *data), void *data) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_doall_names(namemap, number, fn, data); }
./openssl/crypto/evp/evp_local.h
/* * Copyright 2000-2023 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 <openssl/core_dispatch.h> #include "internal/refcount.h" #define EVP_CTRL_RET_UNSUPPORTED -1 struct evp_md_ctx_st { const EVP_MD *reqdigest; /* The original requested digest */ const EVP_MD *digest; ENGINE *engine; /* functional reference if 'digest' is * ENGINE-provided */ unsigned long flags; void *md_data; /* Public key context for sign/verify */ EVP_PKEY_CTX *pctx; /* Update function: usually copied from EVP_MD */ int (*update) (EVP_MD_CTX *ctx, const void *data, size_t count); /* * Opaque ctx returned from a providers digest algorithm implementation * OSSL_FUNC_digest_newctx() */ void *algctx; EVP_MD *fetched_digest; } /* EVP_MD_CTX */ ; struct evp_cipher_ctx_st { const EVP_CIPHER *cipher; ENGINE *engine; /* functional reference if 'cipher' is * ENGINE-provided */ int encrypt; /* encrypt or decrypt */ int buf_len; /* number we have left */ unsigned char oiv[EVP_MAX_IV_LENGTH]; /* original iv */ unsigned char iv[EVP_MAX_IV_LENGTH]; /* working iv */ unsigned char buf[EVP_MAX_BLOCK_LENGTH]; /* saved partial block */ int num; /* used by cfb/ofb/ctr mode */ /* FIXME: Should this even exist? It appears unused */ void *app_data; /* application stuff */ int key_len; /* May change for variable length cipher */ int iv_len; /* IV length */ unsigned long flags; /* Various flags */ void *cipher_data; /* per EVP data */ int final_used; int block_mask; unsigned char final[EVP_MAX_BLOCK_LENGTH]; /* possible final block */ /* * Opaque ctx returned from a providers cipher algorithm implementation * OSSL_FUNC_cipher_newctx() */ void *algctx; EVP_CIPHER *fetched_cipher; } /* EVP_CIPHER_CTX */ ; struct evp_mac_ctx_st { EVP_MAC *meth; /* Method structure */ /* * Opaque ctx returned from a providers MAC algorithm implementation * OSSL_FUNC_mac_newctx() */ void *algctx; } /* EVP_MAC_CTX */; struct evp_kdf_ctx_st { EVP_KDF *meth; /* Method structure */ /* * Opaque ctx returned from a providers KDF algorithm implementation * OSSL_FUNC_kdf_newctx() */ void *algctx; } /* EVP_KDF_CTX */ ; struct evp_rand_ctx_st { EVP_RAND *meth; /* Method structure */ /* * Opaque ctx returned from a providers rand algorithm implementation * OSSL_FUNC_rand_newctx() */ void *algctx; EVP_RAND_CTX *parent; /* Parent EVP_RAND or NULL if none */ CRYPTO_REF_COUNT refcnt; /* Context reference count */ CRYPTO_RWLOCK *refcnt_lock; } /* EVP_RAND_CTX */ ; struct evp_keymgmt_st { int id; /* libcrypto internal */ int name_id; /* NID for the legacy alg if there is one */ int legacy_alg; char *type_name; const char *description; OSSL_PROVIDER *prov; CRYPTO_REF_COUNT refcnt; /* Constructor(s), destructor, information */ OSSL_FUNC_keymgmt_new_fn *new; OSSL_FUNC_keymgmt_free_fn *free; OSSL_FUNC_keymgmt_get_params_fn *get_params; OSSL_FUNC_keymgmt_gettable_params_fn *gettable_params; OSSL_FUNC_keymgmt_set_params_fn *set_params; OSSL_FUNC_keymgmt_settable_params_fn *settable_params; /* Generation, a complex constructor */ OSSL_FUNC_keymgmt_gen_init_fn *gen_init; OSSL_FUNC_keymgmt_gen_set_template_fn *gen_set_template; OSSL_FUNC_keymgmt_gen_set_params_fn *gen_set_params; OSSL_FUNC_keymgmt_gen_settable_params_fn *gen_settable_params; OSSL_FUNC_keymgmt_gen_fn *gen; OSSL_FUNC_keymgmt_gen_cleanup_fn *gen_cleanup; OSSL_FUNC_keymgmt_load_fn *load; /* Key object checking */ OSSL_FUNC_keymgmt_query_operation_name_fn *query_operation_name; OSSL_FUNC_keymgmt_has_fn *has; OSSL_FUNC_keymgmt_validate_fn *validate; OSSL_FUNC_keymgmt_match_fn *match; /* Import and export routines */ OSSL_FUNC_keymgmt_import_fn *import; OSSL_FUNC_keymgmt_import_types_fn *import_types; OSSL_FUNC_keymgmt_import_types_ex_fn *import_types_ex; OSSL_FUNC_keymgmt_export_fn *export; OSSL_FUNC_keymgmt_export_types_fn *export_types; OSSL_FUNC_keymgmt_export_types_ex_fn *export_types_ex; OSSL_FUNC_keymgmt_dup_fn *dup; } /* EVP_KEYMGMT */ ; struct evp_keyexch_st { int name_id; char *type_name; const char *description; OSSL_PROVIDER *prov; CRYPTO_REF_COUNT refcnt; OSSL_FUNC_keyexch_newctx_fn *newctx; OSSL_FUNC_keyexch_init_fn *init; OSSL_FUNC_keyexch_set_peer_fn *set_peer; OSSL_FUNC_keyexch_derive_fn *derive; OSSL_FUNC_keyexch_freectx_fn *freectx; OSSL_FUNC_keyexch_dupctx_fn *dupctx; OSSL_FUNC_keyexch_set_ctx_params_fn *set_ctx_params; OSSL_FUNC_keyexch_settable_ctx_params_fn *settable_ctx_params; OSSL_FUNC_keyexch_get_ctx_params_fn *get_ctx_params; OSSL_FUNC_keyexch_gettable_ctx_params_fn *gettable_ctx_params; } /* EVP_KEYEXCH */; struct evp_signature_st { int name_id; char *type_name; const char *description; OSSL_PROVIDER *prov; CRYPTO_REF_COUNT refcnt; OSSL_FUNC_signature_newctx_fn *newctx; OSSL_FUNC_signature_sign_init_fn *sign_init; OSSL_FUNC_signature_sign_fn *sign; OSSL_FUNC_signature_verify_init_fn *verify_init; OSSL_FUNC_signature_verify_fn *verify; OSSL_FUNC_signature_verify_recover_init_fn *verify_recover_init; OSSL_FUNC_signature_verify_recover_fn *verify_recover; OSSL_FUNC_signature_digest_sign_init_fn *digest_sign_init; OSSL_FUNC_signature_digest_sign_update_fn *digest_sign_update; OSSL_FUNC_signature_digest_sign_final_fn *digest_sign_final; OSSL_FUNC_signature_digest_sign_fn *digest_sign; OSSL_FUNC_signature_digest_verify_init_fn *digest_verify_init; OSSL_FUNC_signature_digest_verify_update_fn *digest_verify_update; OSSL_FUNC_signature_digest_verify_final_fn *digest_verify_final; OSSL_FUNC_signature_digest_verify_fn *digest_verify; OSSL_FUNC_signature_freectx_fn *freectx; OSSL_FUNC_signature_dupctx_fn *dupctx; OSSL_FUNC_signature_get_ctx_params_fn *get_ctx_params; OSSL_FUNC_signature_gettable_ctx_params_fn *gettable_ctx_params; OSSL_FUNC_signature_set_ctx_params_fn *set_ctx_params; OSSL_FUNC_signature_settable_ctx_params_fn *settable_ctx_params; OSSL_FUNC_signature_get_ctx_md_params_fn *get_ctx_md_params; OSSL_FUNC_signature_gettable_ctx_md_params_fn *gettable_ctx_md_params; OSSL_FUNC_signature_set_ctx_md_params_fn *set_ctx_md_params; OSSL_FUNC_signature_settable_ctx_md_params_fn *settable_ctx_md_params; } /* EVP_SIGNATURE */; struct evp_asym_cipher_st { int name_id; char *type_name; const char *description; OSSL_PROVIDER *prov; CRYPTO_REF_COUNT refcnt; OSSL_FUNC_asym_cipher_newctx_fn *newctx; OSSL_FUNC_asym_cipher_encrypt_init_fn *encrypt_init; OSSL_FUNC_asym_cipher_encrypt_fn *encrypt; OSSL_FUNC_asym_cipher_decrypt_init_fn *decrypt_init; OSSL_FUNC_asym_cipher_decrypt_fn *decrypt; OSSL_FUNC_asym_cipher_freectx_fn *freectx; OSSL_FUNC_asym_cipher_dupctx_fn *dupctx; OSSL_FUNC_asym_cipher_get_ctx_params_fn *get_ctx_params; OSSL_FUNC_asym_cipher_gettable_ctx_params_fn *gettable_ctx_params; OSSL_FUNC_asym_cipher_set_ctx_params_fn *set_ctx_params; OSSL_FUNC_asym_cipher_settable_ctx_params_fn *settable_ctx_params; } /* EVP_ASYM_CIPHER */; struct evp_kem_st { int name_id; char *type_name; const char *description; OSSL_PROVIDER *prov; CRYPTO_REF_COUNT refcnt; OSSL_FUNC_kem_newctx_fn *newctx; OSSL_FUNC_kem_encapsulate_init_fn *encapsulate_init; OSSL_FUNC_kem_encapsulate_fn *encapsulate; OSSL_FUNC_kem_decapsulate_init_fn *decapsulate_init; OSSL_FUNC_kem_decapsulate_fn *decapsulate; OSSL_FUNC_kem_freectx_fn *freectx; OSSL_FUNC_kem_dupctx_fn *dupctx; OSSL_FUNC_kem_get_ctx_params_fn *get_ctx_params; OSSL_FUNC_kem_gettable_ctx_params_fn *gettable_ctx_params; OSSL_FUNC_kem_set_ctx_params_fn *set_ctx_params; OSSL_FUNC_kem_settable_ctx_params_fn *settable_ctx_params; OSSL_FUNC_kem_auth_encapsulate_init_fn *auth_encapsulate_init; OSSL_FUNC_kem_auth_decapsulate_init_fn *auth_decapsulate_init; } /* EVP_KEM */; int PKCS5_v2_PBKDF2_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *c, const EVP_MD *md, int en_de); int PKCS5_v2_PBKDF2_keyivgen_ex(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *c, const EVP_MD *md, int en_de, OSSL_LIB_CTX *libctx, const char *propq); struct evp_Encode_Ctx_st { /* number saved in a partial encode/decode */ int num; /* * The length is either the output line length (in input bytes) or the * shortest input line length that is ok. Once decoding begins, the * length is adjusted up each time a longer line is decoded */ int length; /* data to encode */ unsigned char enc_data[80]; /* number read on current line */ int line_num; unsigned int flags; }; typedef struct evp_pbe_st EVP_PBE_CTL; DEFINE_STACK_OF(EVP_PBE_CTL) int ossl_is_partially_overlapping(const void *ptr1, const void *ptr2, int len); #include <openssl/types.h> #include <openssl/core.h> void *evp_generic_fetch(OSSL_LIB_CTX *ctx, int operation_id, const char *name, const char *properties, void *(*new_method)(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov), int (*up_ref_method)(void *), void (*free_method)(void *)); void *evp_generic_fetch_from_prov(OSSL_PROVIDER *prov, int operation_id, const char *name, const char *properties, void *(*new_method)(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov), int (*up_ref_method)(void *), void (*free_method)(void *)); void evp_generic_do_all_prefetched(OSSL_LIB_CTX *libctx, int operation_id, void (*user_fn)(void *method, void *arg), void *user_arg); void evp_generic_do_all(OSSL_LIB_CTX *libctx, int operation_id, void (*user_fn)(void *method, void *arg), void *user_arg, void *(*new_method)(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov), int (*up_ref_method)(void *), void (*free_method)(void *)); /* Internal fetchers for method types that are to be combined with others */ EVP_KEYMGMT *evp_keymgmt_fetch_by_number(OSSL_LIB_CTX *ctx, int name_id, const char *properties); EVP_SIGNATURE *evp_signature_fetch_from_prov(OSSL_PROVIDER *prov, const char *name, const char *properties); EVP_ASYM_CIPHER *evp_asym_cipher_fetch_from_prov(OSSL_PROVIDER *prov, const char *name, const char *properties); EVP_KEYEXCH *evp_keyexch_fetch_from_prov(OSSL_PROVIDER *prov, const char *name, const char *properties); EVP_KEM *evp_kem_fetch_from_prov(OSSL_PROVIDER *prov, const char *name, const char *properties); /* Internal structure constructors for fetched methods */ EVP_MD *evp_md_new(void); EVP_CIPHER *evp_cipher_new(void); int evp_cipher_get_asn1_aead_params(EVP_CIPHER_CTX *c, ASN1_TYPE *type, evp_cipher_aead_asn1_params *asn1_params); int evp_cipher_set_asn1_aead_params(EVP_CIPHER_CTX *c, ASN1_TYPE *type, evp_cipher_aead_asn1_params *asn1_params); /* Helper functions to avoid duplicating code */ /* * These methods implement different ways to pass a params array to the * provider. They will return one of these values: * * -2 if the method doesn't come from a provider * (evp_do_param will return this to the called) * -1 if the provider doesn't offer the desired function * (evp_do_param will raise an error and return 0) * or the return value from the desired function * (evp_do_param will return it to the caller) */ int evp_do_ciph_getparams(const EVP_CIPHER *ciph, OSSL_PARAM params[]); int evp_do_ciph_ctx_getparams(const EVP_CIPHER *ciph, void *provctx, OSSL_PARAM params[]); int evp_do_ciph_ctx_setparams(const EVP_CIPHER *ciph, void *provctx, OSSL_PARAM params[]); int evp_do_md_getparams(const EVP_MD *md, OSSL_PARAM params[]); int evp_do_md_ctx_getparams(const EVP_MD *md, void *provctx, OSSL_PARAM params[]); int evp_do_md_ctx_setparams(const EVP_MD *md, void *provctx, OSSL_PARAM params[]); OSSL_PARAM *evp_pkey_to_param(EVP_PKEY *pkey, size_t *sz); #define M_check_autoarg(ctx, arg, arglen, err) \ if (ctx->pmeth->flags & EVP_PKEY_FLAG_AUTOARGLEN) { \ size_t pksize = (size_t)EVP_PKEY_get_size(ctx->pkey); \ \ if (pksize == 0) { \ ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY); /*ckerr_ignore*/ \ return 0; \ } \ if (arg == NULL) { \ *arglen = pksize; \ return 1; \ } \ if (*arglen < pksize) { \ ERR_raise(ERR_LIB_EVP, EVP_R_BUFFER_TOO_SMALL); /*ckerr_ignore*/ \ return 0; \ } \ } void evp_pkey_ctx_free_old_ops(EVP_PKEY_CTX *ctx); void evp_cipher_free_int(EVP_CIPHER *md); void evp_md_free_int(EVP_MD *md); /* OSSL_PROVIDER * is only used to get the library context */ int evp_is_a(OSSL_PROVIDER *prov, int number, const char *legacy_name, const char *name); int evp_names_do_all(OSSL_PROVIDER *prov, int number, void (*fn)(const char *name, void *data), void *data); int evp_cipher_cache_constants(EVP_CIPHER *cipher);
./openssl/crypto/evp/c_alld.c
/* * Copyright 1995-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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include "crypto/evp.h" #include <openssl/pkcs12.h> #include <openssl/objects.h> void openssl_add_all_digests_int(void) { #ifndef OPENSSL_NO_MD4 EVP_add_digest(EVP_md4()); #endif #ifndef OPENSSL_NO_MD5 EVP_add_digest(EVP_md5()); EVP_add_digest_alias(SN_md5, "ssl3-md5"); EVP_add_digest(EVP_md5_sha1()); #endif EVP_add_digest(EVP_sha1()); EVP_add_digest_alias(SN_sha1, "ssl3-sha1"); EVP_add_digest_alias(SN_sha1WithRSAEncryption, SN_sha1WithRSA); #if !defined(OPENSSL_NO_MDC2) && !defined(OPENSSL_NO_DES) EVP_add_digest(EVP_mdc2()); #endif #ifndef OPENSSL_NO_RMD160 EVP_add_digest(EVP_ripemd160()); EVP_add_digest_alias(SN_ripemd160, "ripemd"); EVP_add_digest_alias(SN_ripemd160, "rmd160"); #endif EVP_add_digest(EVP_sha224()); EVP_add_digest(EVP_sha256()); EVP_add_digest(EVP_sha384()); EVP_add_digest(EVP_sha512()); EVP_add_digest(EVP_sha512_224()); EVP_add_digest(EVP_sha512_256()); #ifndef OPENSSL_NO_WHIRLPOOL EVP_add_digest(EVP_whirlpool()); #endif #ifndef OPENSSL_NO_SM3 EVP_add_digest(EVP_sm3()); #endif #ifndef OPENSSL_NO_BLAKE2 EVP_add_digest(EVP_blake2b512()); EVP_add_digest(EVP_blake2s256()); #endif EVP_add_digest(EVP_sha3_224()); EVP_add_digest(EVP_sha3_256()); EVP_add_digest(EVP_sha3_384()); EVP_add_digest(EVP_sha3_512()); EVP_add_digest(EVP_shake128()); EVP_add_digest(EVP_shake256()); }
./openssl/crypto/evp/p_open.c
/* * Copyright 1995-2020 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 "internal/cryptlib.h" #include <stdio.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/rsa.h> int EVP_OpenInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, const unsigned char *ek, int ekl, const unsigned char *iv, EVP_PKEY *priv) { unsigned char *key = NULL; size_t keylen = 0; int ret = 0; EVP_PKEY_CTX *pctx = NULL; if (type) { EVP_CIPHER_CTX_reset(ctx); if (!EVP_DecryptInit_ex(ctx, type, NULL, NULL, NULL)) goto err; } if (priv == NULL) return 1; if ((pctx = EVP_PKEY_CTX_new(priv, NULL)) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); goto err; } if (EVP_PKEY_decrypt_init(pctx) <= 0 || EVP_PKEY_decrypt(pctx, NULL, &keylen, ek, ekl) <= 0) goto err; if ((key = OPENSSL_malloc(keylen)) == NULL) goto err; if (EVP_PKEY_decrypt(pctx, key, &keylen, ek, ekl) <= 0) goto err; if (EVP_CIPHER_CTX_set_key_length(ctx, keylen) <= 0 || !EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) goto err; ret = 1; err: EVP_PKEY_CTX_free(pctx); OPENSSL_clear_free(key, keylen); return ret; } int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { int i; i = EVP_DecryptFinal_ex(ctx, out, outl); if (i) i = EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL); return i; }
./openssl/crypto/evp/pmeth_check.c
/* * Copyright 2006-2021 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 <stdio.h> #include <stdlib.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/evp.h> #include "crypto/bn.h" #ifndef FIPS_MODULE # include "crypto/asn1.h" #endif #include "crypto/evp.h" #include "evp_local.h" /* * Returns: * 1 True * 0 False * -1 Unsupported (use legacy path) */ static int try_provided_check(EVP_PKEY_CTX *ctx, int selection, int checktype) { EVP_KEYMGMT *keymgmt; void *keydata; if (evp_pkey_ctx_is_legacy(ctx)) return -1; keymgmt = ctx->keymgmt; keydata = evp_pkey_export_to_provider(ctx->pkey, ctx->libctx, &keymgmt, ctx->propquery); if (keydata == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } return evp_keymgmt_validate(keymgmt, keydata, selection, checktype); } static int evp_pkey_public_check_combined(EVP_PKEY_CTX *ctx, int checktype) { EVP_PKEY *pkey = ctx->pkey; int ok; if (pkey == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_KEY_SET); return 0; } if ((ok = try_provided_check(ctx, OSSL_KEYMGMT_SELECT_PUBLIC_KEY, checktype)) != -1) return ok; if (pkey->type == EVP_PKEY_NONE) goto not_supported; #ifndef FIPS_MODULE /* legacy */ /* call customized public key check function first */ if (ctx->pmeth->public_check != NULL) return ctx->pmeth->public_check(pkey); /* use default public key check function in ameth */ if (pkey->ameth == NULL || pkey->ameth->pkey_public_check == NULL) goto not_supported; return pkey->ameth->pkey_public_check(pkey); #endif not_supported: ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } int EVP_PKEY_public_check(EVP_PKEY_CTX *ctx) { return evp_pkey_public_check_combined(ctx, OSSL_KEYMGMT_VALIDATE_FULL_CHECK); } int EVP_PKEY_public_check_quick(EVP_PKEY_CTX *ctx) { return evp_pkey_public_check_combined(ctx, OSSL_KEYMGMT_VALIDATE_QUICK_CHECK); } static int evp_pkey_param_check_combined(EVP_PKEY_CTX *ctx, int checktype) { EVP_PKEY *pkey = ctx->pkey; int ok; if (pkey == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_KEY_SET); return 0; } if ((ok = try_provided_check(ctx, OSSL_KEYMGMT_SELECT_ALL_PARAMETERS, checktype)) != -1) return ok; if (pkey->type == EVP_PKEY_NONE) goto not_supported; #ifndef FIPS_MODULE /* legacy */ /* call customized param check function first */ if (ctx->pmeth->param_check != NULL) return ctx->pmeth->param_check(pkey); /* use default param check function in ameth */ if (pkey->ameth == NULL || pkey->ameth->pkey_param_check == NULL) goto not_supported; return pkey->ameth->pkey_param_check(pkey); #endif not_supported: ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } int EVP_PKEY_param_check(EVP_PKEY_CTX *ctx) { return evp_pkey_param_check_combined(ctx, OSSL_KEYMGMT_VALIDATE_FULL_CHECK); } int EVP_PKEY_param_check_quick(EVP_PKEY_CTX *ctx) { return evp_pkey_param_check_combined(ctx, OSSL_KEYMGMT_VALIDATE_QUICK_CHECK); } int EVP_PKEY_private_check(EVP_PKEY_CTX *ctx) { EVP_PKEY *pkey = ctx->pkey; int ok; if (pkey == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_KEY_SET); return 0; } if ((ok = try_provided_check(ctx, OSSL_KEYMGMT_SELECT_PRIVATE_KEY, OSSL_KEYMGMT_VALIDATE_FULL_CHECK)) != -1) return ok; /* not supported for legacy keys */ ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } int EVP_PKEY_check(EVP_PKEY_CTX *ctx) { return EVP_PKEY_pairwise_check(ctx); } int EVP_PKEY_pairwise_check(EVP_PKEY_CTX *ctx) { EVP_PKEY *pkey = ctx->pkey; int ok; if (pkey == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_KEY_SET); return 0; } if ((ok = try_provided_check(ctx, OSSL_KEYMGMT_SELECT_KEYPAIR, OSSL_KEYMGMT_VALIDATE_FULL_CHECK)) != -1) return ok; if (pkey->type == EVP_PKEY_NONE) goto not_supported; #ifndef FIPS_MODULE /* legacy */ /* call customized check function first */ if (ctx->pmeth->check != NULL) return ctx->pmeth->check(pkey); /* use default check function in ameth */ if (pkey->ameth == NULL || pkey->ameth->pkey_check == NULL) goto not_supported; return pkey->ameth->pkey_check(pkey); #endif not_supported: ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; }
./openssl/crypto/evp/keymgmt_meth.c
/* * Copyright 2019-2023 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 <openssl/crypto.h> #include <openssl/core_dispatch.h> #include <openssl/evp.h> #include <openssl/err.h> #include "internal/provider.h" #include "internal/refcount.h" #include "internal/core.h" #include "crypto/evp.h" #include "evp_local.h" static void *keymgmt_new(void) { EVP_KEYMGMT *keymgmt = NULL; if ((keymgmt = OPENSSL_zalloc(sizeof(*keymgmt))) == NULL) return NULL; if (!CRYPTO_NEW_REF(&keymgmt->refcnt, 1)) { EVP_KEYMGMT_free(keymgmt); return NULL; } return keymgmt; } #ifndef FIPS_MODULE static void help_get_legacy_alg_type_from_keymgmt(const char *keytype, void *arg) { int *type = arg; if (*type == NID_undef) *type = evp_pkey_name2type(keytype); } static int get_legacy_alg_type_from_keymgmt(const EVP_KEYMGMT *keymgmt) { int type = NID_undef; EVP_KEYMGMT_names_do_all(keymgmt, help_get_legacy_alg_type_from_keymgmt, &type); return type; } #endif static void *keymgmt_from_algorithm(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { const OSSL_DISPATCH *fns = algodef->implementation; EVP_KEYMGMT *keymgmt = NULL; int setparamfncnt = 0, getparamfncnt = 0; int setgenparamfncnt = 0; int importfncnt = 0, exportfncnt = 0; int importtypesfncnt = 0, exporttypesfncnt = 0; if ((keymgmt = keymgmt_new()) == NULL) return NULL; keymgmt->name_id = name_id; if ((keymgmt->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) { EVP_KEYMGMT_free(keymgmt); return NULL; } keymgmt->description = algodef->algorithm_description; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_KEYMGMT_NEW: if (keymgmt->new == NULL) keymgmt->new = OSSL_FUNC_keymgmt_new(fns); break; case OSSL_FUNC_KEYMGMT_GEN_INIT: if (keymgmt->gen_init == NULL) keymgmt->gen_init = OSSL_FUNC_keymgmt_gen_init(fns); break; case OSSL_FUNC_KEYMGMT_GEN_SET_TEMPLATE: if (keymgmt->gen_set_template == NULL) keymgmt->gen_set_template = OSSL_FUNC_keymgmt_gen_set_template(fns); break; case OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS: if (keymgmt->gen_set_params == NULL) { setgenparamfncnt++; keymgmt->gen_set_params = OSSL_FUNC_keymgmt_gen_set_params(fns); } break; case OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS: if (keymgmt->gen_settable_params == NULL) { setgenparamfncnt++; keymgmt->gen_settable_params = OSSL_FUNC_keymgmt_gen_settable_params(fns); } break; case OSSL_FUNC_KEYMGMT_GEN: if (keymgmt->gen == NULL) keymgmt->gen = OSSL_FUNC_keymgmt_gen(fns); break; case OSSL_FUNC_KEYMGMT_GEN_CLEANUP: if (keymgmt->gen_cleanup == NULL) keymgmt->gen_cleanup = OSSL_FUNC_keymgmt_gen_cleanup(fns); break; case OSSL_FUNC_KEYMGMT_FREE: if (keymgmt->free == NULL) keymgmt->free = OSSL_FUNC_keymgmt_free(fns); break; case OSSL_FUNC_KEYMGMT_LOAD: if (keymgmt->load == NULL) keymgmt->load = OSSL_FUNC_keymgmt_load(fns); break; case OSSL_FUNC_KEYMGMT_GET_PARAMS: if (keymgmt->get_params == NULL) { getparamfncnt++; keymgmt->get_params = OSSL_FUNC_keymgmt_get_params(fns); } break; case OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS: if (keymgmt->gettable_params == NULL) { getparamfncnt++; keymgmt->gettable_params = OSSL_FUNC_keymgmt_gettable_params(fns); } break; case OSSL_FUNC_KEYMGMT_SET_PARAMS: if (keymgmt->set_params == NULL) { setparamfncnt++; keymgmt->set_params = OSSL_FUNC_keymgmt_set_params(fns); } break; case OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS: if (keymgmt->settable_params == NULL) { setparamfncnt++; keymgmt->settable_params = OSSL_FUNC_keymgmt_settable_params(fns); } break; case OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME: if (keymgmt->query_operation_name == NULL) keymgmt->query_operation_name = OSSL_FUNC_keymgmt_query_operation_name(fns); break; case OSSL_FUNC_KEYMGMT_HAS: if (keymgmt->has == NULL) keymgmt->has = OSSL_FUNC_keymgmt_has(fns); break; case OSSL_FUNC_KEYMGMT_DUP: if (keymgmt->dup == NULL) keymgmt->dup = OSSL_FUNC_keymgmt_dup(fns); break; case OSSL_FUNC_KEYMGMT_VALIDATE: if (keymgmt->validate == NULL) keymgmt->validate = OSSL_FUNC_keymgmt_validate(fns); break; case OSSL_FUNC_KEYMGMT_MATCH: if (keymgmt->match == NULL) keymgmt->match = OSSL_FUNC_keymgmt_match(fns); break; case OSSL_FUNC_KEYMGMT_IMPORT: if (keymgmt->import == NULL) { importfncnt++; keymgmt->import = OSSL_FUNC_keymgmt_import(fns); } break; case OSSL_FUNC_KEYMGMT_IMPORT_TYPES: if (keymgmt->import_types == NULL) { if (importtypesfncnt == 0) importfncnt++; importtypesfncnt++; keymgmt->import_types = OSSL_FUNC_keymgmt_import_types(fns); } break; case OSSL_FUNC_KEYMGMT_IMPORT_TYPES_EX: if (keymgmt->import_types_ex == NULL) { if (importtypesfncnt == 0) importfncnt++; importtypesfncnt++; keymgmt->import_types_ex = OSSL_FUNC_keymgmt_import_types_ex(fns); } break; case OSSL_FUNC_KEYMGMT_EXPORT: if (keymgmt->export == NULL) { exportfncnt++; keymgmt->export = OSSL_FUNC_keymgmt_export(fns); } break; case OSSL_FUNC_KEYMGMT_EXPORT_TYPES: if (keymgmt->export_types == NULL) { if (exporttypesfncnt == 0) exportfncnt++; exporttypesfncnt++; keymgmt->export_types = OSSL_FUNC_keymgmt_export_types(fns); } break; case OSSL_FUNC_KEYMGMT_EXPORT_TYPES_EX: if (keymgmt->export_types_ex == NULL) { if (exporttypesfncnt == 0) exportfncnt++; exporttypesfncnt++; keymgmt->export_types_ex = OSSL_FUNC_keymgmt_export_types_ex(fns); } break; } } /* * Try to check that the method is sensible. * At least one constructor and the destructor are MANDATORY * The functions 'has' is MANDATORY * It makes no sense being able to free stuff if you can't create it. * It makes no sense providing OSSL_PARAM descriptors for import and * export if you can't import or export. */ if (keymgmt->free == NULL || (keymgmt->new == NULL && keymgmt->gen == NULL && keymgmt->load == NULL) || keymgmt->has == NULL || (getparamfncnt != 0 && getparamfncnt != 2) || (setparamfncnt != 0 && setparamfncnt != 2) || (setgenparamfncnt != 0 && setgenparamfncnt != 2) || (importfncnt != 0 && importfncnt != 2) || (exportfncnt != 0 && exportfncnt != 2) || (keymgmt->gen != NULL && (keymgmt->gen_init == NULL || keymgmt->gen_cleanup == NULL))) { EVP_KEYMGMT_free(keymgmt); ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS); return NULL; } keymgmt->prov = prov; if (prov != NULL) ossl_provider_up_ref(prov); #ifndef FIPS_MODULE keymgmt->legacy_alg = get_legacy_alg_type_from_keymgmt(keymgmt); #endif return keymgmt; } EVP_KEYMGMT *evp_keymgmt_fetch_from_prov(OSSL_PROVIDER *prov, const char *name, const char *properties) { return evp_generic_fetch_from_prov(prov, OSSL_OP_KEYMGMT, name, properties, keymgmt_from_algorithm, (int (*)(void *))EVP_KEYMGMT_up_ref, (void (*)(void *))EVP_KEYMGMT_free); } EVP_KEYMGMT *EVP_KEYMGMT_fetch(OSSL_LIB_CTX *ctx, const char *algorithm, const char *properties) { return evp_generic_fetch(ctx, OSSL_OP_KEYMGMT, algorithm, properties, keymgmt_from_algorithm, (int (*)(void *))EVP_KEYMGMT_up_ref, (void (*)(void *))EVP_KEYMGMT_free); } int EVP_KEYMGMT_up_ref(EVP_KEYMGMT *keymgmt) { int ref = 0; CRYPTO_UP_REF(&keymgmt->refcnt, &ref); return 1; } void EVP_KEYMGMT_free(EVP_KEYMGMT *keymgmt) { int ref = 0; if (keymgmt == NULL) return; CRYPTO_DOWN_REF(&keymgmt->refcnt, &ref); if (ref > 0) return; OPENSSL_free(keymgmt->type_name); ossl_provider_free(keymgmt->prov); CRYPTO_FREE_REF(&keymgmt->refcnt); OPENSSL_free(keymgmt); } const OSSL_PROVIDER *EVP_KEYMGMT_get0_provider(const EVP_KEYMGMT *keymgmt) { return keymgmt->prov; } int evp_keymgmt_get_number(const EVP_KEYMGMT *keymgmt) { return keymgmt->name_id; } int evp_keymgmt_get_legacy_alg(const EVP_KEYMGMT *keymgmt) { return keymgmt->legacy_alg; } const char *EVP_KEYMGMT_get0_description(const EVP_KEYMGMT *keymgmt) { return keymgmt->description; } const char *EVP_KEYMGMT_get0_name(const EVP_KEYMGMT *keymgmt) { return keymgmt->type_name; } int EVP_KEYMGMT_is_a(const EVP_KEYMGMT *keymgmt, const char *name) { return keymgmt != NULL && evp_is_a(keymgmt->prov, keymgmt->name_id, NULL, name); } void EVP_KEYMGMT_do_all_provided(OSSL_LIB_CTX *libctx, void (*fn)(EVP_KEYMGMT *keymgmt, void *arg), void *arg) { evp_generic_do_all(libctx, OSSL_OP_KEYMGMT, (void (*)(void *, void *))fn, arg, keymgmt_from_algorithm, (int (*)(void *))EVP_KEYMGMT_up_ref, (void (*)(void *))EVP_KEYMGMT_free); } int EVP_KEYMGMT_names_do_all(const EVP_KEYMGMT *keymgmt, void (*fn)(const char *name, void *data), void *data) { if (keymgmt->prov != NULL) return evp_names_do_all(keymgmt->prov, keymgmt->name_id, fn, data); return 1; } /* * Internal API that interfaces with the method function pointers */ void *evp_keymgmt_newdata(const EVP_KEYMGMT *keymgmt) { void *provctx = ossl_provider_ctx(EVP_KEYMGMT_get0_provider(keymgmt)); /* * 'new' is currently mandatory on its own, but when new * constructors appear, it won't be quite as mandatory, * so we have a check for future cases. */ if (keymgmt->new == NULL) return NULL; return keymgmt->new(provctx); } void evp_keymgmt_freedata(const EVP_KEYMGMT *keymgmt, void *keydata) { /* This is mandatory, no need to check for its presence */ keymgmt->free(keydata); } void *evp_keymgmt_gen_init(const EVP_KEYMGMT *keymgmt, int selection, const OSSL_PARAM params[]) { void *provctx = ossl_provider_ctx(EVP_KEYMGMT_get0_provider(keymgmt)); if (keymgmt->gen_init == NULL) return NULL; return keymgmt->gen_init(provctx, selection, params); } int evp_keymgmt_gen_set_template(const EVP_KEYMGMT *keymgmt, void *genctx, void *templ) { /* * It's arguable if we actually should return success in this case, as * it allows the caller to set a template key, which is then ignored. * However, this is how the legacy methods (EVP_PKEY_METHOD) operate, * so we do this in the interest of backward compatibility. */ if (keymgmt->gen_set_template == NULL) return 1; return keymgmt->gen_set_template(genctx, templ); } int evp_keymgmt_gen_set_params(const EVP_KEYMGMT *keymgmt, void *genctx, const OSSL_PARAM params[]) { if (keymgmt->gen_set_params == NULL) return 0; return keymgmt->gen_set_params(genctx, params); } const OSSL_PARAM *EVP_KEYMGMT_gen_settable_params(const EVP_KEYMGMT *keymgmt) { void *provctx = ossl_provider_ctx(EVP_KEYMGMT_get0_provider(keymgmt)); if (keymgmt->gen_settable_params == NULL) return NULL; return keymgmt->gen_settable_params(NULL, provctx); } void *evp_keymgmt_gen(const EVP_KEYMGMT *keymgmt, void *genctx, OSSL_CALLBACK *cb, void *cbarg) { if (keymgmt->gen == NULL) return NULL; return keymgmt->gen(genctx, cb, cbarg); } void evp_keymgmt_gen_cleanup(const EVP_KEYMGMT *keymgmt, void *genctx) { if (keymgmt->gen_cleanup != NULL) keymgmt->gen_cleanup(genctx); } int evp_keymgmt_has_load(const EVP_KEYMGMT *keymgmt) { return keymgmt != NULL && keymgmt->load != NULL; } void *evp_keymgmt_load(const EVP_KEYMGMT *keymgmt, const void *objref, size_t objref_sz) { if (evp_keymgmt_has_load(keymgmt)) return keymgmt->load(objref, objref_sz); return NULL; } int evp_keymgmt_get_params(const EVP_KEYMGMT *keymgmt, void *keydata, OSSL_PARAM params[]) { if (keymgmt->get_params == NULL) return 1; return keymgmt->get_params(keydata, params); } const OSSL_PARAM *EVP_KEYMGMT_gettable_params(const EVP_KEYMGMT *keymgmt) { void *provctx = ossl_provider_ctx(EVP_KEYMGMT_get0_provider(keymgmt)); if (keymgmt->gettable_params == NULL) return NULL; return keymgmt->gettable_params(provctx); } int evp_keymgmt_set_params(const EVP_KEYMGMT *keymgmt, void *keydata, const OSSL_PARAM params[]) { if (keymgmt->set_params == NULL) return 1; return keymgmt->set_params(keydata, params); } const OSSL_PARAM *EVP_KEYMGMT_settable_params(const EVP_KEYMGMT *keymgmt) { void *provctx = ossl_provider_ctx(EVP_KEYMGMT_get0_provider(keymgmt)); if (keymgmt->settable_params == NULL) return NULL; return keymgmt->settable_params(provctx); } int evp_keymgmt_has(const EVP_KEYMGMT *keymgmt, void *keydata, int selection) { /* This is mandatory, no need to check for its presence */ return keymgmt->has(keydata, selection); } int evp_keymgmt_validate(const EVP_KEYMGMT *keymgmt, void *keydata, int selection, int checktype) { /* We assume valid if the implementation doesn't have a function */ if (keymgmt->validate == NULL) return 1; return keymgmt->validate(keydata, selection, checktype); } int evp_keymgmt_match(const EVP_KEYMGMT *keymgmt, const void *keydata1, const void *keydata2, int selection) { /* We assume no match if the implementation doesn't have a function */ if (keymgmt->match == NULL) return 0; return keymgmt->match(keydata1, keydata2, selection); } int evp_keymgmt_import(const EVP_KEYMGMT *keymgmt, void *keydata, int selection, const OSSL_PARAM params[]) { if (keymgmt->import == NULL) return 0; return keymgmt->import(keydata, selection, params); } const OSSL_PARAM *evp_keymgmt_import_types(const EVP_KEYMGMT *keymgmt, int selection) { void *provctx = ossl_provider_ctx(EVP_KEYMGMT_get0_provider(keymgmt)); if (keymgmt->import_types_ex != NULL) return keymgmt->import_types_ex(provctx, selection); if (keymgmt->import_types == NULL) return NULL; return keymgmt->import_types(selection); } int evp_keymgmt_export(const EVP_KEYMGMT *keymgmt, void *keydata, int selection, OSSL_CALLBACK *param_cb, void *cbarg) { if (keymgmt->export == NULL) return 0; return keymgmt->export(keydata, selection, param_cb, cbarg); } const OSSL_PARAM *evp_keymgmt_export_types(const EVP_KEYMGMT *keymgmt, int selection) { void *provctx = ossl_provider_ctx(EVP_KEYMGMT_get0_provider(keymgmt)); if (keymgmt->export_types_ex != NULL) return keymgmt->export_types_ex(provctx, selection); if (keymgmt->export_types == NULL) return NULL; return keymgmt->export_types(selection); } void *evp_keymgmt_dup(const EVP_KEYMGMT *keymgmt, const void *keydata_from, int selection) { /* We assume no dup if the implementation doesn't have a function */ if (keymgmt->dup == NULL) return NULL; return keymgmt->dup(keydata_from, selection); }
./openssl/crypto/evp/e_xcbc_d.c
/* * Copyright 1995-2021 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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_DES # include <openssl/evp.h> # include <openssl/objects.h> # include "crypto/evp.h" # include <openssl/des.h> # include "evp_local.h" static int desx_cbc_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); static int desx_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl); typedef struct { DES_key_schedule ks; /* key schedule */ DES_cblock inw; DES_cblock outw; } DESX_CBC_KEY; # define data(ctx) EVP_C_DATA(DESX_CBC_KEY,ctx) static const EVP_CIPHER d_xcbc_cipher = { NID_desx_cbc, 8, 24, 8, EVP_CIPH_CBC_MODE, EVP_ORIG_GLOBAL, desx_cbc_init_key, desx_cbc_cipher, NULL, sizeof(DESX_CBC_KEY), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL, NULL }; const EVP_CIPHER *EVP_desx_cbc(void) { return &d_xcbc_cipher; } static int desx_cbc_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { DES_cblock *deskey = (DES_cblock *)key; DES_set_key_unchecked(deskey, &data(ctx)->ks); memcpy(&data(ctx)->inw[0], &key[8], 8); memcpy(&data(ctx)->outw[0], &key[16], 8); return 1; } static int desx_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { while (inl >= EVP_MAXCHUNK) { DES_xcbc_encrypt(in, out, (long)EVP_MAXCHUNK, &data(ctx)->ks, (DES_cblock *)ctx->iv, &data(ctx)->inw, &data(ctx)->outw, EVP_CIPHER_CTX_is_encrypting(ctx)); inl -= EVP_MAXCHUNK; in += EVP_MAXCHUNK; out += EVP_MAXCHUNK; } if (inl) DES_xcbc_encrypt(in, out, (long)inl, &data(ctx)->ks, (DES_cblock *)ctx->iv, &data(ctx)->inw, &data(ctx)->outw, EVP_CIPHER_CTX_is_encrypting(ctx)); return 1; } #endif
./openssl/crypto/evp/e_aes_cbc_hmac_sha256.c
/* * Copyright 2013-2021 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 */ /* * AES low level APIs are deprecated for public use, but still ok for internal * use where we're using them to implement the higher level EVP interface, as is * the case here. */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/aes.h> #include <openssl/sha.h> #include <openssl/rand.h> #include "internal/cryptlib.h" #include "crypto/modes.h" #include "internal/constant_time.h" #include "crypto/evp.h" #include "evp_local.h" typedef struct { AES_KEY ks; SHA256_CTX head, tail, md; size_t payload_length; /* AAD length in decrypt case */ union { unsigned int tls_ver; unsigned char tls_aad[16]; /* 13 used */ } aux; } EVP_AES_HMAC_SHA256; # define NO_PAYLOAD_LENGTH ((size_t)-1) #if defined(AES_ASM) && ( \ defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64) ) # define AESNI_CAPABLE (1<<(57-32)) int aesni_set_encrypt_key(const unsigned char *userKey, int bits, AES_KEY *key); int aesni_set_decrypt_key(const unsigned char *userKey, int bits, AES_KEY *key); void aesni_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t length, const AES_KEY *key, unsigned char *ivec, int enc); int aesni_cbc_sha256_enc(const void *inp, void *out, size_t blocks, const AES_KEY *key, unsigned char iv[16], SHA256_CTX *ctx, const void *in0); # define data(ctx) ((EVP_AES_HMAC_SHA256 *)EVP_CIPHER_CTX_get_cipher_data(ctx)) static int aesni_cbc_hmac_sha256_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *inkey, const unsigned char *iv, int enc) { EVP_AES_HMAC_SHA256 *key = data(ctx); int ret; if (enc) ret = aesni_set_encrypt_key(inkey, EVP_CIPHER_CTX_get_key_length(ctx) * 8, &key->ks); else ret = aesni_set_decrypt_key(inkey, EVP_CIPHER_CTX_get_key_length(ctx) * 8, &key->ks); SHA256_Init(&key->head); /* handy when benchmarking */ key->tail = key->head; key->md = key->head; key->payload_length = NO_PAYLOAD_LENGTH; return ret < 0 ? 0 : 1; } # define STITCHED_CALL # if !defined(STITCHED_CALL) # define aes_off 0 # endif void sha256_block_data_order(void *c, const void *p, size_t len); static void sha256_update(SHA256_CTX *c, const void *data, size_t len) { const unsigned char *ptr = data; size_t res; if ((res = c->num)) { res = SHA256_CBLOCK - res; if (len < res) res = len; SHA256_Update(c, ptr, res); ptr += res; len -= res; } res = len % SHA256_CBLOCK; len -= res; if (len) { sha256_block_data_order(c, ptr, len / SHA256_CBLOCK); ptr += len; c->Nh += len >> 29; c->Nl += len <<= 3; if (c->Nl < (unsigned int)len) c->Nh++; } if (res) SHA256_Update(c, ptr, res); } # ifdef SHA256_Update # undef SHA256_Update # endif # define SHA256_Update sha256_update # if !defined(OPENSSL_NO_MULTIBLOCK) typedef struct { unsigned int A[8], B[8], C[8], D[8], E[8], F[8], G[8], H[8]; } SHA256_MB_CTX; typedef struct { const unsigned char *ptr; int blocks; } HASH_DESC; void sha256_multi_block(SHA256_MB_CTX *, const HASH_DESC *, int); typedef struct { const unsigned char *inp; unsigned char *out; int blocks; u64 iv[2]; } CIPH_DESC; void aesni_multi_cbc_encrypt(CIPH_DESC *, void *, int); static size_t tls1_1_multi_block_encrypt(EVP_AES_HMAC_SHA256 *key, unsigned char *out, const unsigned char *inp, size_t inp_len, int n4x) { /* n4x is 1 or 2 */ HASH_DESC hash_d[8], edges[8]; CIPH_DESC ciph_d[8]; unsigned char storage[sizeof(SHA256_MB_CTX) + 32]; union { u64 q[16]; u32 d[32]; u8 c[128]; } blocks[8]; SHA256_MB_CTX *ctx; unsigned int frag, last, packlen, i, x4 = 4 * n4x, minblocks, processed = 0; size_t ret = 0; u8 *IVs; # if defined(BSWAP8) u64 seqnum; # endif /* ask for IVs in bulk */ if (RAND_bytes((IVs = blocks[0].c), 16 * x4) <= 0) return 0; /* align */ ctx = (SHA256_MB_CTX *) (storage + 32 - ((size_t)storage % 32)); frag = (unsigned int)inp_len >> (1 + n4x); last = (unsigned int)inp_len + frag - (frag << (1 + n4x)); if (last > frag && ((last + 13 + 9) % 64) < (x4 - 1)) { frag++; last -= x4 - 1; } packlen = 5 + 16 + ((frag + 32 + 16) & -16); /* populate descriptors with pointers and IVs */ hash_d[0].ptr = inp; ciph_d[0].inp = inp; /* 5+16 is place for header and explicit IV */ ciph_d[0].out = out + 5 + 16; memcpy(ciph_d[0].out - 16, IVs, 16); memcpy(ciph_d[0].iv, IVs, 16); IVs += 16; for (i = 1; i < x4; i++) { ciph_d[i].inp = hash_d[i].ptr = hash_d[i - 1].ptr + frag; ciph_d[i].out = ciph_d[i - 1].out + packlen; memcpy(ciph_d[i].out - 16, IVs, 16); memcpy(ciph_d[i].iv, IVs, 16); IVs += 16; } # if defined(BSWAP8) memcpy(blocks[0].c, key->md.data, 8); seqnum = BSWAP8(blocks[0].q[0]); # endif for (i = 0; i < x4; i++) { unsigned int len = (i == (x4 - 1) ? last : frag); # if !defined(BSWAP8) unsigned int carry, j; # endif ctx->A[i] = key->md.h[0]; ctx->B[i] = key->md.h[1]; ctx->C[i] = key->md.h[2]; ctx->D[i] = key->md.h[3]; ctx->E[i] = key->md.h[4]; ctx->F[i] = key->md.h[5]; ctx->G[i] = key->md.h[6]; ctx->H[i] = key->md.h[7]; /* fix seqnum */ # if defined(BSWAP8) blocks[i].q[0] = BSWAP8(seqnum + i); # else for (carry = i, j = 8; j--;) { blocks[i].c[j] = ((u8 *)key->md.data)[j] + carry; carry = (blocks[i].c[j] - carry) >> (sizeof(carry) * 8 - 1); } # endif blocks[i].c[8] = ((u8 *)key->md.data)[8]; blocks[i].c[9] = ((u8 *)key->md.data)[9]; blocks[i].c[10] = ((u8 *)key->md.data)[10]; /* fix length */ blocks[i].c[11] = (u8)(len >> 8); blocks[i].c[12] = (u8)(len); memcpy(blocks[i].c + 13, hash_d[i].ptr, 64 - 13); hash_d[i].ptr += 64 - 13; hash_d[i].blocks = (len - (64 - 13)) / 64; edges[i].ptr = blocks[i].c; edges[i].blocks = 1; } /* hash 13-byte headers and first 64-13 bytes of inputs */ sha256_multi_block(ctx, edges, n4x); /* hash bulk inputs */ # define MAXCHUNKSIZE 2048 # if MAXCHUNKSIZE%64 # error "MAXCHUNKSIZE is not divisible by 64" # elif MAXCHUNKSIZE /* * goal is to minimize pressure on L1 cache by moving in shorter steps, * so that hashed data is still in the cache by the time we encrypt it */ minblocks = ((frag <= last ? frag : last) - (64 - 13)) / 64; if (minblocks > MAXCHUNKSIZE / 64) { for (i = 0; i < x4; i++) { edges[i].ptr = hash_d[i].ptr; edges[i].blocks = MAXCHUNKSIZE / 64; ciph_d[i].blocks = MAXCHUNKSIZE / 16; } do { sha256_multi_block(ctx, edges, n4x); aesni_multi_cbc_encrypt(ciph_d, &key->ks, n4x); for (i = 0; i < x4; i++) { edges[i].ptr = hash_d[i].ptr += MAXCHUNKSIZE; hash_d[i].blocks -= MAXCHUNKSIZE / 64; edges[i].blocks = MAXCHUNKSIZE / 64; ciph_d[i].inp += MAXCHUNKSIZE; ciph_d[i].out += MAXCHUNKSIZE; ciph_d[i].blocks = MAXCHUNKSIZE / 16; memcpy(ciph_d[i].iv, ciph_d[i].out - 16, 16); } processed += MAXCHUNKSIZE; minblocks -= MAXCHUNKSIZE / 64; } while (minblocks > MAXCHUNKSIZE / 64); } # endif # undef MAXCHUNKSIZE sha256_multi_block(ctx, hash_d, n4x); memset(blocks, 0, sizeof(blocks)); for (i = 0; i < x4; i++) { unsigned int len = (i == (x4 - 1) ? last : frag), off = hash_d[i].blocks * 64; const unsigned char *ptr = hash_d[i].ptr + off; off = (len - processed) - (64 - 13) - off; /* remainder actually */ memcpy(blocks[i].c, ptr, off); blocks[i].c[off] = 0x80; len += 64 + 13; /* 64 is HMAC header */ len *= 8; /* convert to bits */ if (off < (64 - 8)) { # ifdef BSWAP4 blocks[i].d[15] = BSWAP4(len); # else PUTU32(blocks[i].c + 60, len); # endif edges[i].blocks = 1; } else { # ifdef BSWAP4 blocks[i].d[31] = BSWAP4(len); # else PUTU32(blocks[i].c + 124, len); # endif edges[i].blocks = 2; } edges[i].ptr = blocks[i].c; } /* hash input tails and finalize */ sha256_multi_block(ctx, edges, n4x); memset(blocks, 0, sizeof(blocks)); for (i = 0; i < x4; i++) { # ifdef BSWAP4 blocks[i].d[0] = BSWAP4(ctx->A[i]); ctx->A[i] = key->tail.h[0]; blocks[i].d[1] = BSWAP4(ctx->B[i]); ctx->B[i] = key->tail.h[1]; blocks[i].d[2] = BSWAP4(ctx->C[i]); ctx->C[i] = key->tail.h[2]; blocks[i].d[3] = BSWAP4(ctx->D[i]); ctx->D[i] = key->tail.h[3]; blocks[i].d[4] = BSWAP4(ctx->E[i]); ctx->E[i] = key->tail.h[4]; blocks[i].d[5] = BSWAP4(ctx->F[i]); ctx->F[i] = key->tail.h[5]; blocks[i].d[6] = BSWAP4(ctx->G[i]); ctx->G[i] = key->tail.h[6]; blocks[i].d[7] = BSWAP4(ctx->H[i]); ctx->H[i] = key->tail.h[7]; blocks[i].c[32] = 0x80; blocks[i].d[15] = BSWAP4((64 + 32) * 8); # else PUTU32(blocks[i].c + 0, ctx->A[i]); ctx->A[i] = key->tail.h[0]; PUTU32(blocks[i].c + 4, ctx->B[i]); ctx->B[i] = key->tail.h[1]; PUTU32(blocks[i].c + 8, ctx->C[i]); ctx->C[i] = key->tail.h[2]; PUTU32(blocks[i].c + 12, ctx->D[i]); ctx->D[i] = key->tail.h[3]; PUTU32(blocks[i].c + 16, ctx->E[i]); ctx->E[i] = key->tail.h[4]; PUTU32(blocks[i].c + 20, ctx->F[i]); ctx->F[i] = key->tail.h[5]; PUTU32(blocks[i].c + 24, ctx->G[i]); ctx->G[i] = key->tail.h[6]; PUTU32(blocks[i].c + 28, ctx->H[i]); ctx->H[i] = key->tail.h[7]; blocks[i].c[32] = 0x80; PUTU32(blocks[i].c + 60, (64 + 32) * 8); # endif edges[i].ptr = blocks[i].c; edges[i].blocks = 1; } /* finalize MACs */ sha256_multi_block(ctx, edges, n4x); for (i = 0; i < x4; i++) { unsigned int len = (i == (x4 - 1) ? last : frag), pad, j; unsigned char *out0 = out; memcpy(ciph_d[i].out, ciph_d[i].inp, len - processed); ciph_d[i].inp = ciph_d[i].out; out += 5 + 16 + len; /* write MAC */ PUTU32(out + 0, ctx->A[i]); PUTU32(out + 4, ctx->B[i]); PUTU32(out + 8, ctx->C[i]); PUTU32(out + 12, ctx->D[i]); PUTU32(out + 16, ctx->E[i]); PUTU32(out + 20, ctx->F[i]); PUTU32(out + 24, ctx->G[i]); PUTU32(out + 28, ctx->H[i]); out += 32; len += 32; /* pad */ pad = 15 - len % 16; for (j = 0; j <= pad; j++) *(out++) = pad; len += pad + 1; ciph_d[i].blocks = (len - processed) / 16; len += 16; /* account for explicit iv */ /* arrange header */ out0[0] = ((u8 *)key->md.data)[8]; out0[1] = ((u8 *)key->md.data)[9]; out0[2] = ((u8 *)key->md.data)[10]; out0[3] = (u8)(len >> 8); out0[4] = (u8)(len); ret += len + 5; inp += frag; } aesni_multi_cbc_encrypt(ciph_d, &key->ks, n4x); OPENSSL_cleanse(blocks, sizeof(blocks)); OPENSSL_cleanse(ctx, sizeof(*ctx)); return ret; } # endif static int aesni_cbc_hmac_sha256_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_HMAC_SHA256 *key = data(ctx); unsigned int l; size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and * later */ sha_off = 0; # if defined(STITCHED_CALL) size_t aes_off = 0, blocks; sha_off = SHA256_CBLOCK - key->md.num; # endif key->payload_length = NO_PAYLOAD_LENGTH; if (len % AES_BLOCK_SIZE) return 0; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (plen == NO_PAYLOAD_LENGTH) plen = len; else if (len != ((plen + SHA256_DIGEST_LENGTH + AES_BLOCK_SIZE) & -AES_BLOCK_SIZE)) return 0; else if (key->aux.tls_ver >= TLS1_1_VERSION) iv = AES_BLOCK_SIZE; # if defined(STITCHED_CALL) /* * Assembly stitch handles AVX-capable processors, but its * performance is not optimal on AMD Jaguar, ~40% worse, for * unknown reasons. Incidentally processor in question supports * AVX, but not AMD-specific XOP extension, which can be used * to identify it and avoid stitch invocation. So that after we * establish that current CPU supports AVX, we even see if it's * either even XOP-capable Bulldozer-based or GenuineIntel one. * But SHAEXT-capable go ahead... */ if (((OPENSSL_ia32cap_P[2] & (1 << 29)) || /* SHAEXT? */ ((OPENSSL_ia32cap_P[1] & (1 << (60 - 32))) && /* AVX? */ ((OPENSSL_ia32cap_P[1] & (1 << (43 - 32))) /* XOP? */ | (OPENSSL_ia32cap_P[0] & (1 << 30))))) && /* "Intel CPU"? */ plen > (sha_off + iv) && (blocks = (plen - (sha_off + iv)) / SHA256_CBLOCK)) { SHA256_Update(&key->md, in + iv, sha_off); (void)aesni_cbc_sha256_enc(in, out, blocks, &key->ks, ctx->iv, &key->md, in + iv + sha_off); blocks *= SHA256_CBLOCK; aes_off += blocks; sha_off += blocks; key->md.Nh += blocks >> 29; key->md.Nl += blocks <<= 3; if (key->md.Nl < (unsigned int)blocks) key->md.Nh++; } else { sha_off = 0; } # endif sha_off += iv; SHA256_Update(&key->md, in + sha_off, plen - sha_off); if (plen != len) { /* "TLS" mode of operation */ if (in != out) memcpy(out + aes_off, in + aes_off, plen - aes_off); /* calculate HMAC and append it to payload */ SHA256_Final(out + plen, &key->md); key->md = key->tail; SHA256_Update(&key->md, out + plen, SHA256_DIGEST_LENGTH); SHA256_Final(out + plen, &key->md); /* pad the payload|hmac */ plen += SHA256_DIGEST_LENGTH; for (l = len - plen - 1; plen < len; plen++) out[plen] = l; /* encrypt HMAC|padding at once */ aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } else { aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } } else { union { unsigned int u[SHA256_DIGEST_LENGTH / sizeof(unsigned int)]; unsigned char c[64 + SHA256_DIGEST_LENGTH]; } mac, *pmac; /* arrange cache line alignment */ pmac = (void *)(((size_t)mac.c + 63) & ((size_t)0 - 64)); /* decrypt HMAC|padding at once */ aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0); if (plen != NO_PAYLOAD_LENGTH) { /* "TLS" mode of operation */ size_t inp_len, mask, j, i; unsigned int res, maxpad, pad, bitlen; int ret = 1; union { unsigned int u[SHA_LBLOCK]; unsigned char c[SHA256_CBLOCK]; } *data = (void *)key->md.data; if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3]) >= TLS1_1_VERSION) iv = AES_BLOCK_SIZE; if (len < (iv + SHA256_DIGEST_LENGTH + 1)) return 0; /* omit explicit iv */ out += iv; len -= iv; /* figure out payload length */ pad = out[len - 1]; maxpad = len - (SHA256_DIGEST_LENGTH + 1); maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8); maxpad &= 255; mask = constant_time_ge(maxpad, pad); ret &= mask; /* * If pad is invalid then we will fail the above test but we must * continue anyway because we are in constant time code. However, * we'll use the maxpad value instead of the supplied pad to make * sure we perform well defined pointer arithmetic. */ pad = constant_time_select(mask, pad, maxpad); inp_len = len - (SHA256_DIGEST_LENGTH + pad + 1); key->aux.tls_aad[plen - 2] = inp_len >> 8; key->aux.tls_aad[plen - 1] = inp_len; /* calculate HMAC */ key->md = key->head; SHA256_Update(&key->md, key->aux.tls_aad, plen); # if 1 /* see original reference version in #else */ len -= SHA256_DIGEST_LENGTH; /* amend mac */ if (len >= (256 + SHA256_CBLOCK)) { j = (len - (256 + SHA256_CBLOCK)) & (0 - SHA256_CBLOCK); j += SHA256_CBLOCK - key->md.num; SHA256_Update(&key->md, out, j); out += j; len -= j; inp_len -= j; } /* but pretend as if we hashed padded payload */ bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */ # ifdef BSWAP4 bitlen = BSWAP4(bitlen); # else mac.c[0] = 0; mac.c[1] = (unsigned char)(bitlen >> 16); mac.c[2] = (unsigned char)(bitlen >> 8); mac.c[3] = (unsigned char)bitlen; bitlen = mac.u[0]; # endif pmac->u[0] = 0; pmac->u[1] = 0; pmac->u[2] = 0; pmac->u[3] = 0; pmac->u[4] = 0; pmac->u[5] = 0; pmac->u[6] = 0; pmac->u[7] = 0; for (res = key->md.num, j = 0; j < len; j++) { size_t c = out[j]; mask = (j - inp_len) >> (sizeof(j) * 8 - 8); c &= mask; c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8)); data->c[res++] = (unsigned char)c; if (res != SHA256_CBLOCK) continue; /* j is not incremented yet */ mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha256_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h[0] & mask; pmac->u[1] |= key->md.h[1] & mask; pmac->u[2] |= key->md.h[2] & mask; pmac->u[3] |= key->md.h[3] & mask; pmac->u[4] |= key->md.h[4] & mask; pmac->u[5] |= key->md.h[5] & mask; pmac->u[6] |= key->md.h[6] & mask; pmac->u[7] |= key->md.h[7] & mask; res = 0; } for (i = res; i < SHA256_CBLOCK; i++, j++) data->c[i] = 0; if (res > SHA256_CBLOCK - 8) { mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha256_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h[0] & mask; pmac->u[1] |= key->md.h[1] & mask; pmac->u[2] |= key->md.h[2] & mask; pmac->u[3] |= key->md.h[3] & mask; pmac->u[4] |= key->md.h[4] & mask; pmac->u[5] |= key->md.h[5] & mask; pmac->u[6] |= key->md.h[6] & mask; pmac->u[7] |= key->md.h[7] & mask; memset(data, 0, SHA256_CBLOCK); j += 64; } data->u[SHA_LBLOCK - 1] = bitlen; sha256_block_data_order(&key->md, data, 1); mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h[0] & mask; pmac->u[1] |= key->md.h[1] & mask; pmac->u[2] |= key->md.h[2] & mask; pmac->u[3] |= key->md.h[3] & mask; pmac->u[4] |= key->md.h[4] & mask; pmac->u[5] |= key->md.h[5] & mask; pmac->u[6] |= key->md.h[6] & mask; pmac->u[7] |= key->md.h[7] & mask; # ifdef BSWAP4 pmac->u[0] = BSWAP4(pmac->u[0]); pmac->u[1] = BSWAP4(pmac->u[1]); pmac->u[2] = BSWAP4(pmac->u[2]); pmac->u[3] = BSWAP4(pmac->u[3]); pmac->u[4] = BSWAP4(pmac->u[4]); pmac->u[5] = BSWAP4(pmac->u[5]); pmac->u[6] = BSWAP4(pmac->u[6]); pmac->u[7] = BSWAP4(pmac->u[7]); # else for (i = 0; i < 8; i++) { res = pmac->u[i]; pmac->c[4 * i + 0] = (unsigned char)(res >> 24); pmac->c[4 * i + 1] = (unsigned char)(res >> 16); pmac->c[4 * i + 2] = (unsigned char)(res >> 8); pmac->c[4 * i + 3] = (unsigned char)res; } # endif len += SHA256_DIGEST_LENGTH; # else SHA256_Update(&key->md, out, inp_len); res = key->md.num; SHA256_Final(pmac->c, &key->md); { unsigned int inp_blocks, pad_blocks; /* but pretend as if we hashed padded payload */ inp_blocks = 1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); res += (unsigned int)(len - inp_len); pad_blocks = res / SHA256_CBLOCK; res %= SHA256_CBLOCK; pad_blocks += 1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); for (; inp_blocks < pad_blocks; inp_blocks++) sha1_block_data_order(&key->md, data, 1); } # endif /* pre-lucky-13 reference version of above */ key->md = key->tail; SHA256_Update(&key->md, pmac->c, SHA256_DIGEST_LENGTH); SHA256_Final(pmac->c, &key->md); /* verify HMAC */ out += inp_len; len -= inp_len; # if 1 /* see original reference version in #else */ { unsigned char *p = out + len - 1 - maxpad - SHA256_DIGEST_LENGTH; size_t off = out - p; unsigned int c, cmask; for (res = 0, i = 0, j = 0; j < maxpad + SHA256_DIGEST_LENGTH; j++) { c = p[j]; cmask = ((int)(j - off - SHA256_DIGEST_LENGTH)) >> (sizeof(int) * 8 - 1); res |= (c ^ pad) & ~cmask; /* ... and padding */ cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1); res |= (c ^ pmac->c[i]) & cmask; i += 1 & cmask; } res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; } # else /* pre-lucky-13 reference version of above */ for (res = 0, i = 0; i < SHA256_DIGEST_LENGTH; i++) res |= out[i] ^ pmac->c[i]; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; /* verify padding */ pad = (pad & ~res) | (maxpad & res); out = out + len - 1 - pad; for (res = 0, i = 0; i < pad; i++) res |= out[i] ^ pad; res = (0 - res) >> (sizeof(res) * 8 - 1); ret &= (int)~res; # endif return ret; } else { SHA256_Update(&key->md, out, len); } } return 1; } static int aesni_cbc_hmac_sha256_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { EVP_AES_HMAC_SHA256 *key = data(ctx); unsigned int u_arg = (unsigned int)arg; switch (type) { case EVP_CTRL_AEAD_SET_MAC_KEY: { unsigned int i; unsigned char hmac_key[64]; memset(hmac_key, 0, sizeof(hmac_key)); if (arg < 0) return -1; if (u_arg > sizeof(hmac_key)) { SHA256_Init(&key->head); SHA256_Update(&key->head, ptr, arg); SHA256_Final(hmac_key, &key->head); } else { memcpy(hmac_key, ptr, arg); } for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36; /* ipad */ SHA256_Init(&key->head); SHA256_Update(&key->head, hmac_key, sizeof(hmac_key)); for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36 ^ 0x5c; /* opad */ SHA256_Init(&key->tail); SHA256_Update(&key->tail, hmac_key, sizeof(hmac_key)); OPENSSL_cleanse(hmac_key, sizeof(hmac_key)); return 1; } case EVP_CTRL_AEAD_TLS1_AAD: { unsigned char *p = ptr; unsigned int len; if (arg != EVP_AEAD_TLS1_AAD_LEN) return -1; len = p[arg - 2] << 8 | p[arg - 1]; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { key->payload_length = len; if ((key->aux.tls_ver = p[arg - 4] << 8 | p[arg - 3]) >= TLS1_1_VERSION) { if (len < AES_BLOCK_SIZE) return 0; len -= AES_BLOCK_SIZE; p[arg - 2] = len >> 8; p[arg - 1] = len; } key->md = key->head; SHA256_Update(&key->md, p, arg); return (int)(((len + SHA256_DIGEST_LENGTH + AES_BLOCK_SIZE) & -AES_BLOCK_SIZE) - len); } else { memcpy(key->aux.tls_aad, ptr, arg); key->payload_length = arg; return SHA256_DIGEST_LENGTH; } } # if !defined(OPENSSL_NO_MULTIBLOCK) case EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE: return (int)(5 + 16 + ((arg + 32 + 16) & -16)); case EVP_CTRL_TLS1_1_MULTIBLOCK_AAD: { EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param = (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr; unsigned int n4x = 1, x4; unsigned int frag, last, packlen, inp_len; if (arg < 0) return -1; if (u_arg < sizeof(EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM)) return -1; inp_len = param->inp[11] << 8 | param->inp[12]; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if ((param->inp[9] << 8 | param->inp[10]) < TLS1_1_VERSION) return -1; if (inp_len) { if (inp_len < 4096) return 0; /* too short */ if (inp_len >= 8192 && OPENSSL_ia32cap_P[2] & (1 << 5)) n4x = 2; /* AVX2 */ } else if ((n4x = param->interleave / 4) && n4x <= 2) inp_len = param->len; else return -1; key->md = key->head; SHA256_Update(&key->md, param->inp, 13); x4 = 4 * n4x; n4x += 1; frag = inp_len >> n4x; last = inp_len + frag - (frag << n4x); if (last > frag && ((last + 13 + 9) % 64 < (x4 - 1))) { frag++; last -= x4 - 1; } packlen = 5 + 16 + ((frag + 32 + 16) & -16); packlen = (packlen << n4x) - packlen; packlen += 5 + 16 + ((last + 32 + 16) & -16); param->interleave = x4; return (int)packlen; } else return -1; /* not yet */ } case EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT: { EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param = (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr; return (int)tls1_1_multi_block_encrypt(key, param->out, param->inp, param->len, param->interleave / 4); } case EVP_CTRL_TLS1_1_MULTIBLOCK_DECRYPT: # endif default: return -1; } } static EVP_CIPHER aesni_128_cbc_hmac_sha256_cipher = { # ifdef NID_aes_128_cbc_hmac_sha256 NID_aes_128_cbc_hmac_sha256, # else NID_undef, # endif AES_BLOCK_SIZE, 16, AES_BLOCK_SIZE, EVP_CIPH_CBC_MODE | EVP_CIPH_FLAG_DEFAULT_ASN1 | EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK, EVP_ORIG_GLOBAL, aesni_cbc_hmac_sha256_init_key, aesni_cbc_hmac_sha256_cipher, NULL, sizeof(EVP_AES_HMAC_SHA256), EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_set_asn1_iv, EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_get_asn1_iv, aesni_cbc_hmac_sha256_ctrl, NULL }; static EVP_CIPHER aesni_256_cbc_hmac_sha256_cipher = { # ifdef NID_aes_256_cbc_hmac_sha256 NID_aes_256_cbc_hmac_sha256, # else NID_undef, # endif AES_BLOCK_SIZE, 32, AES_BLOCK_SIZE, EVP_CIPH_CBC_MODE | EVP_CIPH_FLAG_DEFAULT_ASN1 | EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK, EVP_ORIG_GLOBAL, aesni_cbc_hmac_sha256_init_key, aesni_cbc_hmac_sha256_cipher, NULL, sizeof(EVP_AES_HMAC_SHA256), EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_set_asn1_iv, EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_get_asn1_iv, aesni_cbc_hmac_sha256_ctrl, NULL }; const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha256(void) { return ((OPENSSL_ia32cap_P[1] & AESNI_CAPABLE) && aesni_cbc_sha256_enc(NULL, NULL, 0, NULL, NULL, NULL, NULL) ? &aesni_128_cbc_hmac_sha256_cipher : NULL); } const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void) { return ((OPENSSL_ia32cap_P[1] & AESNI_CAPABLE) && aesni_cbc_sha256_enc(NULL, NULL, 0, NULL, NULL, NULL, NULL) ? &aesni_256_cbc_hmac_sha256_cipher : NULL); } #else const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha256(void) { return NULL; } const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void) { return NULL; } #endif
./openssl/crypto/evp/legacy_ripemd.c
/* * Copyright 1995-2021 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 */ /* * RIPEMD160 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/ripemd.h> #include "crypto/evp.h" #include "legacy_meth.h" IMPLEMENT_LEGACY_EVP_MD_METH(ripe, RIPEMD160) static const EVP_MD ripemd160_md = { NID_ripemd160, NID_ripemd160WithRSA, RIPEMD160_DIGEST_LENGTH, 0, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(ripe_init, ripe_update, ripe_final, NULL, RIPEMD160_CBLOCK), }; const EVP_MD *EVP_ripemd160(void) { return &ripemd160_md; }
./openssl/crypto/evp/keymgmt_lib.c
/* * Copyright 2019-2023 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 <openssl/core_names.h> #include "internal/cryptlib.h" #include "internal/nelem.h" #include "crypto/evp.h" #include "internal/core.h" #include "internal/provider.h" #include "evp_local.h" /* * match_type() checks if two EVP_KEYMGMT are matching key types. This * function assumes that the caller has made all the necessary NULL checks. */ static int match_type(const EVP_KEYMGMT *keymgmt1, const EVP_KEYMGMT *keymgmt2) { const char *name2 = EVP_KEYMGMT_get0_name(keymgmt2); return EVP_KEYMGMT_is_a(keymgmt1, name2); } int evp_keymgmt_util_try_import(const OSSL_PARAM params[], void *arg) { struct evp_keymgmt_util_try_import_data_st *data = arg; int delete_on_error = 0; /* Just in time creation of keydata */ if (data->keydata == NULL) { if ((data->keydata = evp_keymgmt_newdata(data->keymgmt)) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return 0; } delete_on_error = 1; } /* * It's fine if there was no data to transfer, we just end up with an * empty destination key. */ if (params[0].key == NULL) return 1; if (evp_keymgmt_import(data->keymgmt, data->keydata, data->selection, params)) return 1; if (delete_on_error) { evp_keymgmt_freedata(data->keymgmt, data->keydata); data->keydata = NULL; } return 0; } int evp_keymgmt_util_assign_pkey(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt, void *keydata) { if (pkey == NULL || keymgmt == NULL || keydata == NULL || !EVP_PKEY_set_type_by_keymgmt(pkey, keymgmt)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } pkey->keydata = keydata; evp_keymgmt_util_cache_keyinfo(pkey); return 1; } EVP_PKEY *evp_keymgmt_util_make_pkey(EVP_KEYMGMT *keymgmt, void *keydata) { EVP_PKEY *pkey = NULL; if (keymgmt == NULL || keydata == NULL || (pkey = EVP_PKEY_new()) == NULL || !evp_keymgmt_util_assign_pkey(pkey, keymgmt, keydata)) { EVP_PKEY_free(pkey); return NULL; } return pkey; } int evp_keymgmt_util_export(const EVP_PKEY *pk, int selection, OSSL_CALLBACK *export_cb, void *export_cbarg) { if (pk == NULL || export_cb == NULL) return 0; return evp_keymgmt_export(pk->keymgmt, pk->keydata, selection, export_cb, export_cbarg); } void *evp_keymgmt_util_export_to_provider(EVP_PKEY *pk, EVP_KEYMGMT *keymgmt, int selection) { struct evp_keymgmt_util_try_import_data_st import_data; OP_CACHE_ELEM *op; /* Export to where? */ if (keymgmt == NULL) return NULL; /* If we have an unassigned key, give up */ if (pk->keydata == NULL) return NULL; /* * If |keymgmt| matches the "origin" |keymgmt|, there is no more to do. * The "origin" is determined by the |keymgmt| pointers being identical * or when the provider and the name ID match. The latter case handles the * situation where the fetch cache is flushed and a "new" key manager is * created. */ if (pk->keymgmt == keymgmt || (pk->keymgmt->name_id == keymgmt->name_id && pk->keymgmt->prov == keymgmt->prov)) return pk->keydata; if (!CRYPTO_THREAD_read_lock(pk->lock)) return NULL; /* * If the provider native "origin" hasn't changed since last time, we * try to find our keymgmt in the operation cache. If it has changed * and our keymgmt isn't found, we will clear the cache further down. */ if (pk->dirty_cnt == pk->dirty_cnt_copy) { /* If this key is already exported to |keymgmt|, no more to do */ op = evp_keymgmt_util_find_operation_cache(pk, keymgmt, selection); if (op != NULL && op->keymgmt != NULL) { void *ret = op->keydata; CRYPTO_THREAD_unlock(pk->lock); return ret; } } CRYPTO_THREAD_unlock(pk->lock); /* If the "origin" |keymgmt| doesn't support exporting, give up */ if (pk->keymgmt->export == NULL) return NULL; /* * Make sure that the type of the keymgmt to export to matches the type * of the "origin" */ if (!ossl_assert(match_type(pk->keymgmt, keymgmt))) return NULL; /* * We look at the already cached provider keys, and import from the * first that supports it (i.e. use its export function), and export * the imported data to the new provider. */ /* Setup for the export callback */ import_data.keydata = NULL; /* evp_keymgmt_util_try_import will create it */ import_data.keymgmt = keymgmt; import_data.selection = selection; /* * The export function calls the callback (evp_keymgmt_util_try_import), * which does the import for us. If successful, we're done. */ if (!evp_keymgmt_util_export(pk, selection, &evp_keymgmt_util_try_import, &import_data)) /* If there was an error, bail out */ return NULL; if (!CRYPTO_THREAD_write_lock(pk->lock)) { evp_keymgmt_freedata(keymgmt, import_data.keydata); return NULL; } /* Check to make sure some other thread didn't get there first */ op = evp_keymgmt_util_find_operation_cache(pk, keymgmt, selection); if (op != NULL && op->keydata != NULL) { void *ret = op->keydata; CRYPTO_THREAD_unlock(pk->lock); /* * Another thread seemms to have already exported this so we abandon * all the work we just did. */ evp_keymgmt_freedata(keymgmt, import_data.keydata); return ret; } /* * If the dirty counter changed since last time, then clear the * operation cache. In that case, we know that |i| is zero. */ if (pk->dirty_cnt != pk->dirty_cnt_copy) evp_keymgmt_util_clear_operation_cache(pk); /* Add the new export to the operation cache */ if (!evp_keymgmt_util_cache_keydata(pk, keymgmt, import_data.keydata, selection)) { CRYPTO_THREAD_unlock(pk->lock); evp_keymgmt_freedata(keymgmt, import_data.keydata); return NULL; } /* Synchronize the dirty count */ pk->dirty_cnt_copy = pk->dirty_cnt; CRYPTO_THREAD_unlock(pk->lock); return import_data.keydata; } static void op_cache_free(OP_CACHE_ELEM *e) { evp_keymgmt_freedata(e->keymgmt, e->keydata); EVP_KEYMGMT_free(e->keymgmt); OPENSSL_free(e); } int evp_keymgmt_util_clear_operation_cache(EVP_PKEY *pk) { if (pk != NULL) { sk_OP_CACHE_ELEM_pop_free(pk->operation_cache, op_cache_free); pk->operation_cache = NULL; } return 1; } OP_CACHE_ELEM *evp_keymgmt_util_find_operation_cache(EVP_PKEY *pk, EVP_KEYMGMT *keymgmt, int selection) { int i, end = sk_OP_CACHE_ELEM_num(pk->operation_cache); OP_CACHE_ELEM *p; /* * A comparison and sk_P_CACHE_ELEM_find() are avoided to not cause * problems when we've only a read lock. */ for (i = 0; i < end; i++) { p = sk_OP_CACHE_ELEM_value(pk->operation_cache, i); if (keymgmt == p->keymgmt && (p->selection & selection) == selection) return p; } return NULL; } int evp_keymgmt_util_cache_keydata(EVP_PKEY *pk, EVP_KEYMGMT *keymgmt, void *keydata, int selection) { OP_CACHE_ELEM *p = NULL; if (keydata != NULL) { if (pk->operation_cache == NULL) { pk->operation_cache = sk_OP_CACHE_ELEM_new_null(); if (pk->operation_cache == NULL) return 0; } p = OPENSSL_malloc(sizeof(*p)); if (p == NULL) return 0; p->keydata = keydata; p->keymgmt = keymgmt; p->selection = selection; if (!EVP_KEYMGMT_up_ref(keymgmt)) { OPENSSL_free(p); return 0; } if (!sk_OP_CACHE_ELEM_push(pk->operation_cache, p)) { EVP_KEYMGMT_free(keymgmt); OPENSSL_free(p); return 0; } } return 1; } void evp_keymgmt_util_cache_keyinfo(EVP_PKEY *pk) { /* * Cache information about the provider "origin" key. * * This services functions like EVP_PKEY_get_size, EVP_PKEY_get_bits, etc */ if (pk->keydata != NULL) { int bits = 0; int security_bits = 0; int size = 0; OSSL_PARAM params[4]; params[0] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_BITS, &bits); params[1] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_SECURITY_BITS, &security_bits); params[2] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_MAX_SIZE, &size); params[3] = OSSL_PARAM_construct_end(); if (evp_keymgmt_get_params(pk->keymgmt, pk->keydata, params)) { pk->cache.size = size; pk->cache.bits = bits; pk->cache.security_bits = security_bits; } } } void *evp_keymgmt_util_fromdata(EVP_PKEY *target, EVP_KEYMGMT *keymgmt, int selection, const OSSL_PARAM params[]) { void *keydata = NULL; if ((keydata = evp_keymgmt_newdata(keymgmt)) == NULL || !evp_keymgmt_import(keymgmt, keydata, selection, params) || !evp_keymgmt_util_assign_pkey(target, keymgmt, keydata)) { evp_keymgmt_freedata(keymgmt, keydata); keydata = NULL; } return keydata; } int evp_keymgmt_util_has(EVP_PKEY *pk, int selection) { /* Check if key is even assigned */ if (pk->keymgmt == NULL) return 0; return evp_keymgmt_has(pk->keymgmt, pk->keydata, selection); } /* * evp_keymgmt_util_match() doesn't just look at the provider side "origin", * but also in the operation cache to see if there's any common keymgmt that * supplies OP_keymgmt_match. * * evp_keymgmt_util_match() adheres to the return values that EVP_PKEY_eq() * and EVP_PKEY_parameters_eq() return, i.e.: * * 1 same key * 0 not same key * -1 not same key type * -2 unsupported operation */ int evp_keymgmt_util_match(EVP_PKEY *pk1, EVP_PKEY *pk2, int selection) { EVP_KEYMGMT *keymgmt1 = NULL, *keymgmt2 = NULL; void *keydata1 = NULL, *keydata2 = NULL; if (pk1 == NULL || pk2 == NULL) { if (pk1 == NULL && pk2 == NULL) return 1; return 0; } keymgmt1 = pk1->keymgmt; keydata1 = pk1->keydata; keymgmt2 = pk2->keymgmt; keydata2 = pk2->keydata; if (keymgmt1 != keymgmt2) { /* * The condition for a successful cross export is that the * keydata to be exported is NULL (typed, but otherwise empty * EVP_PKEY), or that it was possible to export it with * evp_keymgmt_util_export_to_provider(). * * We use |ok| to determine if it's ok to cross export one way, * but also to determine if we should attempt a cross export * the other way. There's no point doing it both ways. */ int ok = 0; /* Complex case, where the keymgmt differ */ if (keymgmt1 != NULL && keymgmt2 != NULL && !match_type(keymgmt1, keymgmt2)) { ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES); return -1; /* Not the same type */ } /* * The key types are determined to match, so we try cross export, * but only to keymgmt's that supply a matching function. */ if (keymgmt2 != NULL && keymgmt2->match != NULL) { void *tmp_keydata = NULL; ok = 1; if (keydata1 != NULL) { tmp_keydata = evp_keymgmt_util_export_to_provider(pk1, keymgmt2, selection); ok = (tmp_keydata != NULL); } if (ok) { keymgmt1 = keymgmt2; keydata1 = tmp_keydata; } } /* * If we've successfully cross exported one way, there's no point * doing it the other way, hence the |!ok| check. */ if (!ok && keymgmt1 != NULL && keymgmt1->match != NULL) { void *tmp_keydata = NULL; ok = 1; if (keydata2 != NULL) { tmp_keydata = evp_keymgmt_util_export_to_provider(pk2, keymgmt1, selection); ok = (tmp_keydata != NULL); } if (ok) { keymgmt2 = keymgmt1; keydata2 = tmp_keydata; } } } /* If we still don't have matching keymgmt implementations, we give up */ if (keymgmt1 != keymgmt2) return -2; /* If both keydata are NULL, then they're the same key */ if (keydata1 == NULL && keydata2 == NULL) return 1; /* If only one of the keydata is NULL, then they're different keys */ if (keydata1 == NULL || keydata2 == NULL) return 0; /* If both keydata are non-NULL, we let the backend decide */ return evp_keymgmt_match(keymgmt1, keydata1, keydata2, selection); } int evp_keymgmt_util_copy(EVP_PKEY *to, EVP_PKEY *from, int selection) { /* Save copies of pointers we want to play with without affecting |to| */ EVP_KEYMGMT *to_keymgmt = to->keymgmt; void *to_keydata = to->keydata, *alloc_keydata = NULL; /* An unassigned key can't be copied */ if (from == NULL || from->keydata == NULL) return 0; /* * If |to| is unassigned, ensure it gets the same KEYMGMT as |from|, * Note that the final setting of KEYMGMT is done further down, with * EVP_PKEY_set_type_by_keymgmt(); we don't want to do that prematurely. */ if (to_keymgmt == NULL) to_keymgmt = from->keymgmt; if (to_keymgmt == from->keymgmt && to_keymgmt->dup != NULL && to_keydata == NULL) { to_keydata = alloc_keydata = evp_keymgmt_dup(to_keymgmt, from->keydata, selection); if (to_keydata == NULL) return 0; } else if (match_type(to_keymgmt, from->keymgmt)) { struct evp_keymgmt_util_try_import_data_st import_data; import_data.keymgmt = to_keymgmt; import_data.keydata = to_keydata; import_data.selection = selection; if (!evp_keymgmt_util_export(from, selection, &evp_keymgmt_util_try_import, &import_data)) return 0; /* * In case to_keydata was previously unallocated, * evp_keymgmt_util_try_import() may have created it for us. */ if (to_keydata == NULL) to_keydata = alloc_keydata = import_data.keydata; } else { ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES); return 0; } /* * We only need to set the |to| type when its |keymgmt| isn't set. * We can then just set its |keydata| to what we have, which might * be exactly what it had when entering this function. * This is a bit different from using evp_keymgmt_util_assign_pkey(), * which isn't as careful with |to|'s original |keymgmt|, since it's * meant to forcibly reassign an EVP_PKEY no matter what, which is * why we don't use that one here. */ if (to->keymgmt == NULL && !EVP_PKEY_set_type_by_keymgmt(to, to_keymgmt)) { evp_keymgmt_freedata(to_keymgmt, alloc_keydata); return 0; } to->keydata = to_keydata; evp_keymgmt_util_cache_keyinfo(to); return 1; } void *evp_keymgmt_util_gen(EVP_PKEY *target, EVP_KEYMGMT *keymgmt, void *genctx, OSSL_CALLBACK *cb, void *cbarg) { void *keydata = NULL; if ((keydata = evp_keymgmt_gen(keymgmt, genctx, cb, cbarg)) == NULL || !evp_keymgmt_util_assign_pkey(target, keymgmt, keydata)) { evp_keymgmt_freedata(keymgmt, keydata); keydata = NULL; } return keydata; } /* * Returns the same numbers as EVP_PKEY_get_default_digest_name() * When the string from the EVP_KEYMGMT implementation is "", we use * SN_undef, since that corresponds to what EVP_PKEY_get_default_nid() * returns for no digest. */ int evp_keymgmt_util_get_deflt_digest_name(EVP_KEYMGMT *keymgmt, void *keydata, char *mdname, size_t mdname_sz) { OSSL_PARAM params[3]; char mddefault[100] = ""; char mdmandatory[100] = ""; char *result = NULL; int rv = -2; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_DEFAULT_DIGEST, mddefault, sizeof(mddefault)); params[1] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_MANDATORY_DIGEST, mdmandatory, sizeof(mdmandatory)); params[2] = OSSL_PARAM_construct_end(); if (!evp_keymgmt_get_params(keymgmt, keydata, params)) return 0; if (OSSL_PARAM_modified(params + 1)) { if (params[1].return_size <= 1) /* Only a NUL byte */ result = SN_undef; else result = mdmandatory; rv = 2; } else if (OSSL_PARAM_modified(params)) { if (params[0].return_size <= 1) /* Only a NUL byte */ result = SN_undef; else result = mddefault; rv = 1; } if (rv > 0) OPENSSL_strlcpy(mdname, result, mdname_sz); return rv; } /* * If |keymgmt| has the method function |query_operation_name|, use it to get * the name of a supported operation identity. Otherwise, return the keytype, * assuming that it works as a default operation name. */ const char *evp_keymgmt_util_query_operation_name(EVP_KEYMGMT *keymgmt, int op_id) { const char *name = NULL; if (keymgmt != NULL) { if (keymgmt->query_operation_name != NULL) name = keymgmt->query_operation_name(op_id); if (name == NULL) name = EVP_KEYMGMT_get0_name(keymgmt); } return name; }
./openssl/crypto/evp/exchange.c
/* * Copyright 2019-2023 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 <openssl/crypto.h> #include <openssl/evp.h> #include <openssl/err.h> #include "internal/cryptlib.h" #include "internal/refcount.h" #include "internal/provider.h" #include "internal/core.h" #include "internal/numbers.h" /* includes SIZE_MAX */ #include "crypto/evp.h" #include "evp_local.h" static EVP_KEYEXCH *evp_keyexch_new(OSSL_PROVIDER *prov) { EVP_KEYEXCH *exchange = OPENSSL_zalloc(sizeof(EVP_KEYEXCH)); if (exchange == NULL) return NULL; if (!CRYPTO_NEW_REF(&exchange->refcnt, 1)) { OPENSSL_free(exchange); return NULL; } exchange->prov = prov; ossl_provider_up_ref(prov); return exchange; } static void *evp_keyexch_from_algorithm(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { const OSSL_DISPATCH *fns = algodef->implementation; EVP_KEYEXCH *exchange = NULL; int fncnt = 0, sparamfncnt = 0, gparamfncnt = 0; if ((exchange = evp_keyexch_new(prov)) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); goto err; } exchange->name_id = name_id; if ((exchange->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) goto err; exchange->description = algodef->algorithm_description; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_KEYEXCH_NEWCTX: if (exchange->newctx != NULL) break; exchange->newctx = OSSL_FUNC_keyexch_newctx(fns); fncnt++; break; case OSSL_FUNC_KEYEXCH_INIT: if (exchange->init != NULL) break; exchange->init = OSSL_FUNC_keyexch_init(fns); fncnt++; break; case OSSL_FUNC_KEYEXCH_SET_PEER: if (exchange->set_peer != NULL) break; exchange->set_peer = OSSL_FUNC_keyexch_set_peer(fns); break; case OSSL_FUNC_KEYEXCH_DERIVE: if (exchange->derive != NULL) break; exchange->derive = OSSL_FUNC_keyexch_derive(fns); fncnt++; break; case OSSL_FUNC_KEYEXCH_FREECTX: if (exchange->freectx != NULL) break; exchange->freectx = OSSL_FUNC_keyexch_freectx(fns); fncnt++; break; case OSSL_FUNC_KEYEXCH_DUPCTX: if (exchange->dupctx != NULL) break; exchange->dupctx = OSSL_FUNC_keyexch_dupctx(fns); break; case OSSL_FUNC_KEYEXCH_GET_CTX_PARAMS: if (exchange->get_ctx_params != NULL) break; exchange->get_ctx_params = OSSL_FUNC_keyexch_get_ctx_params(fns); gparamfncnt++; break; case OSSL_FUNC_KEYEXCH_GETTABLE_CTX_PARAMS: if (exchange->gettable_ctx_params != NULL) break; exchange->gettable_ctx_params = OSSL_FUNC_keyexch_gettable_ctx_params(fns); gparamfncnt++; break; case OSSL_FUNC_KEYEXCH_SET_CTX_PARAMS: if (exchange->set_ctx_params != NULL) break; exchange->set_ctx_params = OSSL_FUNC_keyexch_set_ctx_params(fns); sparamfncnt++; break; case OSSL_FUNC_KEYEXCH_SETTABLE_CTX_PARAMS: if (exchange->settable_ctx_params != NULL) break; exchange->settable_ctx_params = OSSL_FUNC_keyexch_settable_ctx_params(fns); sparamfncnt++; break; } } if (fncnt != 4 || (gparamfncnt != 0 && gparamfncnt != 2) || (sparamfncnt != 0 && sparamfncnt != 2)) { /* * In order to be a consistent set of functions we must have at least * a complete set of "exchange" functions: init, derive, newctx, * and freectx. The set_ctx_params and settable_ctx_params functions are * optional, but if one of them is present then the other one must also * be present. Same goes for get_ctx_params and gettable_ctx_params. * The dupctx and set_peer functions are optional. */ ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS); goto err; } return exchange; err: EVP_KEYEXCH_free(exchange); return NULL; } void EVP_KEYEXCH_free(EVP_KEYEXCH *exchange) { int i; if (exchange == NULL) return; CRYPTO_DOWN_REF(&exchange->refcnt, &i); if (i > 0) return; OPENSSL_free(exchange->type_name); ossl_provider_free(exchange->prov); CRYPTO_FREE_REF(&exchange->refcnt); OPENSSL_free(exchange); } int EVP_KEYEXCH_up_ref(EVP_KEYEXCH *exchange) { int ref = 0; CRYPTO_UP_REF(&exchange->refcnt, &ref); return 1; } OSSL_PROVIDER *EVP_KEYEXCH_get0_provider(const EVP_KEYEXCH *exchange) { return exchange->prov; } EVP_KEYEXCH *EVP_KEYEXCH_fetch(OSSL_LIB_CTX *ctx, const char *algorithm, const char *properties) { return evp_generic_fetch(ctx, OSSL_OP_KEYEXCH, algorithm, properties, evp_keyexch_from_algorithm, (int (*)(void *))EVP_KEYEXCH_up_ref, (void (*)(void *))EVP_KEYEXCH_free); } EVP_KEYEXCH *evp_keyexch_fetch_from_prov(OSSL_PROVIDER *prov, const char *algorithm, const char *properties) { return evp_generic_fetch_from_prov(prov, OSSL_OP_KEYEXCH, algorithm, properties, evp_keyexch_from_algorithm, (int (*)(void *))EVP_KEYEXCH_up_ref, (void (*)(void *))EVP_KEYEXCH_free); } int EVP_PKEY_derive_init(EVP_PKEY_CTX *ctx) { return EVP_PKEY_derive_init_ex(ctx, NULL); } int EVP_PKEY_derive_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]) { int ret; void *provkey = NULL; EVP_KEYEXCH *exchange = NULL; EVP_KEYMGMT *tmp_keymgmt = NULL; const OSSL_PROVIDER *tmp_prov = NULL; const char *supported_exch = NULL; int iter; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return -2; } evp_pkey_ctx_free_old_ops(ctx); ctx->operation = EVP_PKEY_OP_DERIVE; ERR_set_mark(); if (evp_pkey_ctx_is_legacy(ctx)) goto legacy; /* * Some algorithms (e.g. legacy KDFs) don't have a pkey - so we create * a blank one. */ if (ctx->pkey == NULL) { EVP_PKEY *pkey = EVP_PKEY_new(); if (pkey == NULL || !EVP_PKEY_set_type_by_keymgmt(pkey, ctx->keymgmt) || (pkey->keydata = evp_keymgmt_newdata(ctx->keymgmt)) == NULL) { ERR_clear_last_mark(); EVP_PKEY_free(pkey); ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } ctx->pkey = pkey; } /* * Try to derive the supported exch from |ctx->keymgmt|. */ if (!ossl_assert(ctx->pkey->keymgmt == NULL || ctx->pkey->keymgmt == ctx->keymgmt)) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); goto err; } supported_exch = evp_keymgmt_util_query_operation_name(ctx->keymgmt, OSSL_OP_KEYEXCH); if (supported_exch == NULL) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } /* * We perform two iterations: * * 1. Do the normal exchange fetch, using the fetching data given by * the EVP_PKEY_CTX. * 2. Do the provider specific exchange fetch, from the same provider * as |ctx->keymgmt| * * We then try to fetch the keymgmt from the same provider as the * exchange, and try to export |ctx->pkey| to that keymgmt (when * this keymgmt happens to be the same as |ctx->keymgmt|, the export * is a no-op, but we call it anyway to not complicate the code even * more). * If the export call succeeds (returns a non-NULL provider key pointer), * we're done and can perform the operation itself. If not, we perform * the second iteration, or jump to legacy. */ for (iter = 1, provkey = NULL; iter < 3 && provkey == NULL; iter++) { EVP_KEYMGMT *tmp_keymgmt_tofree = NULL; /* * If we're on the second iteration, free the results from the first. * They are NULL on the first iteration, so no need to check what * iteration we're on. */ EVP_KEYEXCH_free(exchange); EVP_KEYMGMT_free(tmp_keymgmt); switch (iter) { case 1: exchange = EVP_KEYEXCH_fetch(ctx->libctx, supported_exch, ctx->propquery); if (exchange != NULL) tmp_prov = EVP_KEYEXCH_get0_provider(exchange); break; case 2: tmp_prov = EVP_KEYMGMT_get0_provider(ctx->keymgmt); exchange = evp_keyexch_fetch_from_prov((OSSL_PROVIDER *)tmp_prov, supported_exch, ctx->propquery); if (exchange == NULL) goto legacy; break; } if (exchange == NULL) continue; /* * Ensure that the key is provided, either natively, or as a cached * export. We start by fetching the keymgmt with the same name as * |ctx->keymgmt|, but from the provider of the exchange method, using * the same property query as when fetching the exchange method. * With the keymgmt we found (if we did), we try to export |ctx->pkey| * to it (evp_pkey_export_to_provider() is smart enough to only actually * export it if |tmp_keymgmt| is different from |ctx->pkey|'s keymgmt) */ tmp_keymgmt_tofree = tmp_keymgmt = evp_keymgmt_fetch_from_prov((OSSL_PROVIDER *)tmp_prov, EVP_KEYMGMT_get0_name(ctx->keymgmt), ctx->propquery); if (tmp_keymgmt != NULL) provkey = evp_pkey_export_to_provider(ctx->pkey, ctx->libctx, &tmp_keymgmt, ctx->propquery); if (tmp_keymgmt == NULL) EVP_KEYMGMT_free(tmp_keymgmt_tofree); } if (provkey == NULL) { EVP_KEYEXCH_free(exchange); goto legacy; } ERR_pop_to_mark(); /* No more legacy from here down to legacy: */ /* A Coverity false positive with up_ref/down_ref and free */ /* coverity[use_after_free] */ ctx->op.kex.exchange = exchange; /* A Coverity false positive with up_ref/down_ref and free */ /* coverity[deref_arg] */ ctx->op.kex.algctx = exchange->newctx(ossl_provider_ctx(exchange->prov)); if (ctx->op.kex.algctx == NULL) { /* The provider key can stay in the cache */ ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); goto err; } ret = exchange->init(ctx->op.kex.algctx, provkey, params); EVP_KEYMGMT_free(tmp_keymgmt); return ret ? 1 : 0; err: evp_pkey_ctx_free_old_ops(ctx); ctx->operation = EVP_PKEY_OP_UNDEFINED; EVP_KEYMGMT_free(tmp_keymgmt); return 0; legacy: /* * If we don't have the full support we need with provided methods, * let's go see if legacy does. */ ERR_pop_to_mark(); #ifdef FIPS_MODULE return 0; #else if (ctx->pmeth == NULL || ctx->pmeth->derive == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } if (ctx->pmeth->derive_init == NULL) return 1; ret = ctx->pmeth->derive_init(ctx); if (ret <= 0) ctx->operation = EVP_PKEY_OP_UNDEFINED; EVP_KEYMGMT_free(tmp_keymgmt); return ret; #endif } int EVP_PKEY_derive_set_peer_ex(EVP_PKEY_CTX *ctx, EVP_PKEY *peer, int validate_peer) { int ret = 0, check; void *provkey = NULL; EVP_PKEY_CTX *check_ctx = NULL; EVP_KEYMGMT *tmp_keymgmt = NULL, *tmp_keymgmt_tofree = NULL; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return -1; } if (!EVP_PKEY_CTX_IS_DERIVE_OP(ctx) || ctx->op.kex.algctx == NULL) goto legacy; if (ctx->op.kex.exchange->set_peer == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } if (validate_peer) { check_ctx = EVP_PKEY_CTX_new_from_pkey(ctx->libctx, peer, ctx->propquery); if (check_ctx == NULL) return -1; check = EVP_PKEY_public_check(check_ctx); EVP_PKEY_CTX_free(check_ctx); if (check <= 0) return -1; } /* * Ensure that the |peer| is provided, either natively, or as a cached * export. We start by fetching the keymgmt with the same name as * |ctx->keymgmt|, but from the provider of the exchange method, using * the same property query as when fetching the exchange method. * With the keymgmt we found (if we did), we try to export |peer| * to it (evp_pkey_export_to_provider() is smart enough to only actually * export it if |tmp_keymgmt| is different from |peer|'s keymgmt) */ tmp_keymgmt_tofree = tmp_keymgmt = evp_keymgmt_fetch_from_prov((OSSL_PROVIDER *) EVP_KEYEXCH_get0_provider(ctx->op.kex.exchange), EVP_KEYMGMT_get0_name(ctx->keymgmt), ctx->propquery); if (tmp_keymgmt != NULL) /* A Coverity issue with up_ref/down_ref and free */ /* coverity[pass_freed_arg] */ provkey = evp_pkey_export_to_provider(peer, ctx->libctx, &tmp_keymgmt, ctx->propquery); EVP_KEYMGMT_free(tmp_keymgmt_tofree); /* * If making the key provided wasn't possible, legacy may be able to pick * it up */ if (provkey == NULL) goto legacy; return ctx->op.kex.exchange->set_peer(ctx->op.kex.algctx, provkey); legacy: #ifdef FIPS_MODULE return ret; #else if (ctx->pmeth == NULL || !(ctx->pmeth->derive != NULL || ctx->pmeth->encrypt != NULL || ctx->pmeth->decrypt != NULL) || ctx->pmeth->ctrl == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } if (ctx->operation != EVP_PKEY_OP_DERIVE && ctx->operation != EVP_PKEY_OP_ENCRYPT && ctx->operation != EVP_PKEY_OP_DECRYPT) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); return -1; } ret = ctx->pmeth->ctrl(ctx, EVP_PKEY_CTRL_PEER_KEY, 0, peer); if (ret <= 0) return ret; if (ret == 2) return 1; if (ctx->pkey == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_KEY_SET); return -1; } if (ctx->pkey->type != peer->type) { ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES); return -1; } /* * For clarity. The error is if parameters in peer are * present (!missing) but don't match. EVP_PKEY_parameters_eq may return * 1 (match), 0 (don't match) and -2 (comparison is not defined). -1 * (different key types) is impossible here because it is checked earlier. * -2 is OK for us here, as well as 1, so we can check for 0 only. */ if (!EVP_PKEY_missing_parameters(peer) && !EVP_PKEY_parameters_eq(ctx->pkey, peer)) { ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_PARAMETERS); return -1; } EVP_PKEY_free(ctx->peerkey); ctx->peerkey = peer; ret = ctx->pmeth->ctrl(ctx, EVP_PKEY_CTRL_PEER_KEY, 1, peer); if (ret <= 0) { ctx->peerkey = NULL; return ret; } EVP_PKEY_up_ref(peer); return 1; #endif } int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer) { return EVP_PKEY_derive_set_peer_ex(ctx, peer, 1); } int EVP_PKEY_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *pkeylen) { int ret; if (ctx == NULL || pkeylen == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return -1; } if (!EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_INITIALIZED); return -1; } if (ctx->op.kex.algctx == NULL) goto legacy; ret = ctx->op.kex.exchange->derive(ctx->op.kex.algctx, key, pkeylen, key != NULL ? *pkeylen : 0); return ret; legacy: if (ctx->pmeth == NULL || ctx->pmeth->derive == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; } M_check_autoarg(ctx, key, pkeylen, EVP_F_EVP_PKEY_DERIVE) return ctx->pmeth->derive(ctx, key, pkeylen); } int evp_keyexch_get_number(const EVP_KEYEXCH *keyexch) { return keyexch->name_id; } const char *EVP_KEYEXCH_get0_name(const EVP_KEYEXCH *keyexch) { return keyexch->type_name; } const char *EVP_KEYEXCH_get0_description(const EVP_KEYEXCH *keyexch) { return keyexch->description; } int EVP_KEYEXCH_is_a(const EVP_KEYEXCH *keyexch, const char *name) { return keyexch != NULL && evp_is_a(keyexch->prov, keyexch->name_id, NULL, name); } void EVP_KEYEXCH_do_all_provided(OSSL_LIB_CTX *libctx, void (*fn)(EVP_KEYEXCH *keyexch, void *arg), void *arg) { evp_generic_do_all(libctx, OSSL_OP_KEYEXCH, (void (*)(void *, void *))fn, arg, evp_keyexch_from_algorithm, (int (*)(void *))EVP_KEYEXCH_up_ref, (void (*)(void *))EVP_KEYEXCH_free); } int EVP_KEYEXCH_names_do_all(const EVP_KEYEXCH *keyexch, void (*fn)(const char *name, void *data), void *data) { if (keyexch->prov != NULL) return evp_names_do_all(keyexch->prov, keyexch->name_id, fn, data); return 1; } const OSSL_PARAM *EVP_KEYEXCH_gettable_ctx_params(const EVP_KEYEXCH *keyexch) { void *provctx; if (keyexch == NULL || keyexch->gettable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_KEYEXCH_get0_provider(keyexch)); return keyexch->gettable_ctx_params(NULL, provctx); } const OSSL_PARAM *EVP_KEYEXCH_settable_ctx_params(const EVP_KEYEXCH *keyexch) { void *provctx; if (keyexch == NULL || keyexch->settable_ctx_params == NULL) return NULL; provctx = ossl_provider_ctx(EVP_KEYEXCH_get0_provider(keyexch)); return keyexch->settable_ctx_params(NULL, provctx); }
./openssl/crypto/evp/p5_crpt2.c
/* * Copyright 1999-2023 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 <stdio.h> #include <stdlib.h> #include "internal/cryptlib.h" #include <openssl/x509.h> #include <openssl/evp.h> #include <openssl/kdf.h> #include <openssl/hmac.h> #include <openssl/trace.h> #include <openssl/core_names.h> #include "crypto/evp.h" #include "evp_local.h" int ossl_pkcs5_pbkdf2_hmac_ex(const char *pass, int passlen, const unsigned char *salt, int saltlen, int iter, const EVP_MD *digest, int keylen, unsigned char *out, OSSL_LIB_CTX *libctx, const char *propq) { const char *empty = ""; int rv = 1, mode = 1; EVP_KDF *kdf; EVP_KDF_CTX *kctx; const char *mdname = EVP_MD_get0_name(digest); OSSL_PARAM params[6], *p = params; /* Keep documented behaviour. */ if (pass == NULL) { pass = empty; passlen = 0; } else if (passlen == -1) { passlen = strlen(pass); } if (salt == NULL && saltlen == 0) salt = (unsigned char *)empty; kdf = EVP_KDF_fetch(libctx, OSSL_KDF_NAME_PBKDF2, propq); if (kdf == NULL) return 0; kctx = EVP_KDF_CTX_new(kdf); EVP_KDF_free(kdf); if (kctx == NULL) return 0; *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, (char *)pass, (size_t)passlen); *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_PKCS5, &mode); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, (unsigned char *)salt, saltlen); *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_ITER, &iter); *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, (char *)mdname, 0); *p = OSSL_PARAM_construct_end(); if (EVP_KDF_derive(kctx, out, keylen, params) != 1) rv = 0; EVP_KDF_CTX_free(kctx); OSSL_TRACE_BEGIN(PKCS5V2) { BIO_printf(trc_out, "Password:\n"); BIO_hex_string(trc_out, 0, passlen, pass, passlen); BIO_printf(trc_out, "\n"); BIO_printf(trc_out, "Salt:\n"); BIO_hex_string(trc_out, 0, saltlen, salt, saltlen); BIO_printf(trc_out, "\n"); BIO_printf(trc_out, "Iteration count %d\n", iter); BIO_printf(trc_out, "Key:\n"); BIO_hex_string(trc_out, 0, keylen, out, keylen); BIO_printf(trc_out, "\n"); } OSSL_TRACE_END(PKCS5V2); return rv; } int PKCS5_PBKDF2_HMAC(const char *pass, int passlen, const unsigned char *salt, int saltlen, int iter, const EVP_MD *digest, int keylen, unsigned char *out) { return ossl_pkcs5_pbkdf2_hmac_ex(pass, passlen, salt, saltlen, iter, digest, keylen, out, NULL, NULL); } int PKCS5_PBKDF2_HMAC_SHA1(const char *pass, int passlen, const unsigned char *salt, int saltlen, int iter, int keylen, unsigned char *out) { EVP_MD *digest; int r = 0; if ((digest = EVP_MD_fetch(NULL, SN_sha1, NULL)) != NULL) r = ossl_pkcs5_pbkdf2_hmac_ex(pass, passlen, salt, saltlen, iter, digest, keylen, out, NULL, NULL); EVP_MD_free(digest); return r; } /* * Now the key derivation function itself. This is a bit evil because it has * to check the ASN1 parameters are valid: and there are quite a few of * them... */ int PKCS5_v2_PBE_keyivgen_ex(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *c, const EVP_MD *md, int en_de, OSSL_LIB_CTX *libctx, const char *propq) { PBE2PARAM *pbe2 = NULL; char ciph_name[80]; const EVP_CIPHER *cipher = NULL; EVP_CIPHER *cipher_fetch = NULL; EVP_PBE_KEYGEN_EX *kdf; int rv = 0; pbe2 = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(PBE2PARAM), param); if (pbe2 == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_DECODE_ERROR); goto err; } /* See if we recognise the key derivation function */ if (!EVP_PBE_find_ex(EVP_PBE_TYPE_KDF, OBJ_obj2nid(pbe2->keyfunc->algorithm), NULL, NULL, NULL, &kdf)) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION); goto err; } /* * lets see if we recognise the encryption algorithm. */ if (OBJ_obj2txt(ciph_name, sizeof(ciph_name), pbe2->encryption->algorithm, 0) <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_CIPHER); goto err; } (void)ERR_set_mark(); cipher = cipher_fetch = EVP_CIPHER_fetch(libctx, ciph_name, propq); /* Fallback to legacy method */ if (cipher == NULL) cipher = EVP_get_cipherbyname(ciph_name); if (cipher == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_CIPHER); goto err; } (void)ERR_pop_to_mark(); /* Fixup cipher based on AlgorithmIdentifier */ if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, en_de)) goto err; if (EVP_CIPHER_asn1_to_param(ctx, pbe2->encryption->parameter) <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_CIPHER_PARAMETER_ERROR); goto err; } rv = kdf(ctx, pass, passlen, pbe2->keyfunc->parameter, NULL, NULL, en_de, libctx, propq); err: EVP_CIPHER_free(cipher_fetch); PBE2PARAM_free(pbe2); return rv; } int PKCS5_v2_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *c, const EVP_MD *md, int en_de) { return PKCS5_v2_PBE_keyivgen_ex(ctx, pass, passlen, param, c, md, en_de, NULL, NULL); } int PKCS5_v2_PBKDF2_keyivgen_ex(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *c, const EVP_MD *md, int en_de, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char *salt, key[EVP_MAX_KEY_LENGTH]; int saltlen, iter, t; int rv = 0; unsigned int keylen = 0; int prf_nid, hmac_md_nid; PBKDF2PARAM *kdf = NULL; const EVP_MD *prfmd = NULL; EVP_MD *prfmd_fetch = NULL; if (EVP_CIPHER_CTX_get0_cipher(ctx) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET); goto err; } keylen = EVP_CIPHER_CTX_get_key_length(ctx); OPENSSL_assert(keylen <= sizeof(key)); /* Decode parameter */ kdf = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(PBKDF2PARAM), param); if (kdf == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_DECODE_ERROR); goto err; } t = EVP_CIPHER_CTX_get_key_length(ctx); if (t < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); goto err; } keylen = t; /* Now check the parameters of the kdf */ if (kdf->keylength && (ASN1_INTEGER_get(kdf->keylength) != (int)keylen)) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEYLENGTH); goto err; } if (kdf->prf) prf_nid = OBJ_obj2nid(kdf->prf->algorithm); else prf_nid = NID_hmacWithSHA1; if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, prf_nid, NULL, &hmac_md_nid, 0)) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_PRF); goto err; } (void)ERR_set_mark(); prfmd = prfmd_fetch = EVP_MD_fetch(libctx, OBJ_nid2sn(hmac_md_nid), propq); if (prfmd == NULL) prfmd = EVP_get_digestbynid(hmac_md_nid); if (prfmd == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_PRF); goto err; } (void)ERR_pop_to_mark(); if (kdf->salt->type != V_ASN1_OCTET_STRING) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_SALT_TYPE); goto err; } /* it seems that its all OK */ salt = kdf->salt->value.octet_string->data; saltlen = kdf->salt->value.octet_string->length; iter = ASN1_INTEGER_get(kdf->iter); if (!ossl_pkcs5_pbkdf2_hmac_ex(pass, passlen, salt, saltlen, iter, prfmd, keylen, key, libctx, propq)) goto err; rv = EVP_CipherInit_ex(ctx, NULL, NULL, key, NULL, en_de); err: OPENSSL_cleanse(key, keylen); PBKDF2PARAM_free(kdf); EVP_MD_free(prfmd_fetch); return rv; } int PKCS5_v2_PBKDF2_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *c, const EVP_MD *md, int en_de) { return PKCS5_v2_PBKDF2_keyivgen_ex(ctx, pass, passlen, param, c, md, en_de, NULL, NULL); }
./openssl/crypto/evp/kdf_meth.c
/* * Copyright 2019-2023 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 <openssl/evp.h> #include <openssl/err.h> #include <openssl/core.h> #include <openssl/core_dispatch.h> #include <openssl/kdf.h> #include "internal/provider.h" #include "internal/core.h" #include "crypto/evp.h" #include "evp_local.h" static int evp_kdf_up_ref(void *vkdf) { EVP_KDF *kdf = (EVP_KDF *)vkdf; int ref = 0; CRYPTO_UP_REF(&kdf->refcnt, &ref); return 1; } static void evp_kdf_free(void *vkdf) { EVP_KDF *kdf = (EVP_KDF *)vkdf; int ref = 0; if (kdf == NULL) return; CRYPTO_DOWN_REF(&kdf->refcnt, &ref); if (ref > 0) return; OPENSSL_free(kdf->type_name); ossl_provider_free(kdf->prov); CRYPTO_FREE_REF(&kdf->refcnt); OPENSSL_free(kdf); } static void *evp_kdf_new(void) { EVP_KDF *kdf = NULL; if ((kdf = OPENSSL_zalloc(sizeof(*kdf))) == NULL || !CRYPTO_NEW_REF(&kdf->refcnt, 1)) { OPENSSL_free(kdf); return NULL; } return kdf; } static void *evp_kdf_from_algorithm(int name_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { const OSSL_DISPATCH *fns = algodef->implementation; EVP_KDF *kdf = NULL; int fnkdfcnt = 0, fnctxcnt = 0; if ((kdf = evp_kdf_new()) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return NULL; } kdf->name_id = name_id; if ((kdf->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) { evp_kdf_free(kdf); return NULL; } kdf->description = algodef->algorithm_description; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_KDF_NEWCTX: if (kdf->newctx != NULL) break; kdf->newctx = OSSL_FUNC_kdf_newctx(fns); fnctxcnt++; break; case OSSL_FUNC_KDF_DUPCTX: if (kdf->dupctx != NULL) break; kdf->dupctx = OSSL_FUNC_kdf_dupctx(fns); break; case OSSL_FUNC_KDF_FREECTX: if (kdf->freectx != NULL) break; kdf->freectx = OSSL_FUNC_kdf_freectx(fns); fnctxcnt++; break; case OSSL_FUNC_KDF_RESET: if (kdf->reset != NULL) break; kdf->reset = OSSL_FUNC_kdf_reset(fns); break; case OSSL_FUNC_KDF_DERIVE: if (kdf->derive != NULL) break; kdf->derive = OSSL_FUNC_kdf_derive(fns); fnkdfcnt++; break; case OSSL_FUNC_KDF_GETTABLE_PARAMS: if (kdf->gettable_params != NULL) break; kdf->gettable_params = OSSL_FUNC_kdf_gettable_params(fns); break; case OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS: if (kdf->gettable_ctx_params != NULL) break; kdf->gettable_ctx_params = OSSL_FUNC_kdf_gettable_ctx_params(fns); break; case OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS: if (kdf->settable_ctx_params != NULL) break; kdf->settable_ctx_params = OSSL_FUNC_kdf_settable_ctx_params(fns); break; case OSSL_FUNC_KDF_GET_PARAMS: if (kdf->get_params != NULL) break; kdf->get_params = OSSL_FUNC_kdf_get_params(fns); break; case OSSL_FUNC_KDF_GET_CTX_PARAMS: if (kdf->get_ctx_params != NULL) break; kdf->get_ctx_params = OSSL_FUNC_kdf_get_ctx_params(fns); break; case OSSL_FUNC_KDF_SET_CTX_PARAMS: if (kdf->set_ctx_params != NULL) break; kdf->set_ctx_params = OSSL_FUNC_kdf_set_ctx_params(fns); break; } } if (fnkdfcnt != 1 || fnctxcnt != 2) { /* * In order to be a consistent set of functions we must have at least * a derive function, and a complete set of context management * functions. */ evp_kdf_free(kdf); ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS); return NULL; } kdf->prov = prov; if (prov != NULL) ossl_provider_up_ref(prov); return kdf; } EVP_KDF *EVP_KDF_fetch(OSSL_LIB_CTX *libctx, const char *algorithm, const char *properties) { return evp_generic_fetch(libctx, OSSL_OP_KDF, algorithm, properties, evp_kdf_from_algorithm, evp_kdf_up_ref, evp_kdf_free); } int EVP_KDF_up_ref(EVP_KDF *kdf) { return evp_kdf_up_ref(kdf); } void EVP_KDF_free(EVP_KDF *kdf) { evp_kdf_free(kdf); } const OSSL_PARAM *EVP_KDF_gettable_params(const EVP_KDF *kdf) { if (kdf->gettable_params == NULL) return NULL; return kdf->gettable_params(ossl_provider_ctx(EVP_KDF_get0_provider(kdf))); } const OSSL_PARAM *EVP_KDF_gettable_ctx_params(const EVP_KDF *kdf) { void *alg; if (kdf->gettable_ctx_params == NULL) return NULL; alg = ossl_provider_ctx(EVP_KDF_get0_provider(kdf)); return kdf->gettable_ctx_params(NULL, alg); } const OSSL_PARAM *EVP_KDF_settable_ctx_params(const EVP_KDF *kdf) { void *alg; if (kdf->settable_ctx_params == NULL) return NULL; alg = ossl_provider_ctx(EVP_KDF_get0_provider(kdf)); return kdf->settable_ctx_params(NULL, alg); } const OSSL_PARAM *EVP_KDF_CTX_gettable_params(EVP_KDF_CTX *ctx) { void *alg; if (ctx->meth->gettable_ctx_params == NULL) return NULL; alg = ossl_provider_ctx(EVP_KDF_get0_provider(ctx->meth)); return ctx->meth->gettable_ctx_params(ctx->algctx, alg); } const OSSL_PARAM *EVP_KDF_CTX_settable_params(EVP_KDF_CTX *ctx) { void *alg; if (ctx->meth->settable_ctx_params == NULL) return NULL; alg = ossl_provider_ctx(EVP_KDF_get0_provider(ctx->meth)); return ctx->meth->settable_ctx_params(ctx->algctx, alg); } void EVP_KDF_do_all_provided(OSSL_LIB_CTX *libctx, void (*fn)(EVP_KDF *kdf, void *arg), void *arg) { evp_generic_do_all(libctx, OSSL_OP_KDF, (void (*)(void *, void *))fn, arg, evp_kdf_from_algorithm, evp_kdf_up_ref, evp_kdf_free); }
./openssl/crypto/evp/ctrl_params_translate.c
/* * Copyright 2021-2023 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 */ /* * Some ctrls depend on deprecated functionality. We trust that this is * functionality that remains internally even when 'no-deprecated' is * configured. When we drop #legacy EVP_PKEYs, this source should be * possible to drop as well. */ #include "internal/deprecated.h" #include <string.h> /* The following includes get us all the EVP_PKEY_CTRL macros */ #include <openssl/dh.h> #include <openssl/dsa.h> #include <openssl/ec.h> #include <openssl/rsa.h> #include <openssl/kdf.h> /* This include gets us all the OSSL_PARAM key string macros */ #include <openssl/core_names.h> #include <openssl/err.h> #include <openssl/evperr.h> #include <openssl/params.h> #include "internal/nelem.h" #include "internal/cryptlib.h" #include "internal/ffc.h" #include "crypto/evp.h" #include "crypto/dh.h" #include "crypto/ec.h" struct translation_ctx_st; /* Forwarding */ struct translation_st; /* Forwarding */ /* * The fixup_args functions are called with the following parameters: * * |state| The state we're called in, explained further at the * end of this comment. * |translation| The translation item, to be pilfered for data as * necessary. * |ctx| The translation context, which contains copies of * the following arguments, applicable according to * the caller. All of the attributes in this context * may be freely modified by the fixup_args function. * For cleanup, call cleanup_translation_ctx(). * * The |state| tells the fixup_args function something about the caller and * what they may expect: * * PKEY The fixup_args function has been called * from an EVP_PKEY payload getter / setter, * and is fully responsible for getting or * setting the requested data. With this * state, the fixup_args function is expected * to use or modify |*params|, depending on * |action_type|. * * PRE_CTRL_TO_PARAMS The fixup_args function has been called * POST_CTRL_TO_PARAMS from EVP_PKEY_CTX_ctrl(), to help with * translating the ctrl data to an OSSL_PARAM * element or back. The calling sequence is * as follows: * * 1. fixup_args(PRE_CTRL_TO_PARAMS, ...) * 2. EVP_PKEY_CTX_set_params() or * EVP_PKEY_CTX_get_params() * 3. fixup_args(POST_CTRL_TO_PARAMS, ...) * * With the PRE_CTRL_TO_PARAMS state, the * fixup_args function is expected to modify * the passed |*params| in whatever way * necessary, when |action_type == SET|. * With the POST_CTRL_TO_PARAMS state, the * fixup_args function is expected to modify * the passed |p2| in whatever way necessary, * when |action_type == GET|. * * The return value from the fixup_args call * with the POST_CTRL_TO_PARAMS state becomes * the return value back to EVP_PKEY_CTX_ctrl(). * * CLEANUP_CTRL_TO_PARAMS The cleanup_args functions has been called * from EVP_PKEY_CTX_ctrl(), to clean up what * the fixup_args function has done, if needed. * * * PRE_CTRL_STR_TO_PARAMS The fixup_args function has been called * POST_CTRL_STR_TO_PARAMS from EVP_PKEY_CTX_ctrl_str(), to help with * translating the ctrl_str data to an * OSSL_PARAM element or back. The calling * sequence is as follows: * * 1. fixup_args(PRE_CTRL_STR_TO_PARAMS, ...) * 2. EVP_PKEY_CTX_set_params() or * EVP_PKEY_CTX_get_params() * 3. fixup_args(POST_CTRL_STR_TO_PARAMS, ...) * * With the PRE_CTRL_STR_TO_PARAMS state, * the fixup_args function is expected to * modify the passed |*params| in whatever * way necessary, when |action_type == SET|. * With the POST_CTRL_STR_TO_PARAMS state, * the fixup_args function is only expected * to return a value. * * CLEANUP_CTRL_STR_TO_PARAMS The cleanup_args functions has been called * from EVP_PKEY_CTX_ctrl_str(), to clean up * what the fixup_args function has done, if * needed. * * PRE_PARAMS_TO_CTRL The fixup_args function has been called * POST_PARAMS_TO_CTRL from EVP_PKEY_CTX_get_params() or * EVP_PKEY_CTX_set_params(), to help with * translating the OSSL_PARAM data to the * corresponding EVP_PKEY_CTX_ctrl() arguments * or the other way around. The calling * sequence is as follows: * * 1. fixup_args(PRE_PARAMS_TO_CTRL, ...) * 2. EVP_PKEY_CTX_ctrl() * 3. fixup_args(POST_PARAMS_TO_CTRL, ...) * * With the PRE_PARAMS_TO_CTRL state, the * fixup_args function is expected to modify * the passed |p1| and |p2| in whatever way * necessary, when |action_type == SET|. * With the POST_PARAMS_TO_CTRL state, the * fixup_args function is expected to * modify the passed |*params| in whatever * way necessary, when |action_type == GET|. * * CLEANUP_PARAMS_TO_CTRL The cleanup_args functions has been called * from EVP_PKEY_CTX_get_params() or * EVP_PKEY_CTX_set_params(), to clean up what * the fixup_args function has done, if needed. */ enum state { PKEY, PRE_CTRL_TO_PARAMS, POST_CTRL_TO_PARAMS, CLEANUP_CTRL_TO_PARAMS, PRE_CTRL_STR_TO_PARAMS, POST_CTRL_STR_TO_PARAMS, CLEANUP_CTRL_STR_TO_PARAMS, PRE_PARAMS_TO_CTRL, POST_PARAMS_TO_CTRL, CLEANUP_PARAMS_TO_CTRL }; enum action { NONE = 0, GET = 1, SET = 2 }; typedef int fixup_args_fn(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx); typedef int cleanup_args_fn(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx); struct translation_ctx_st { /* * The EVP_PKEY_CTX, for calls on that structure, to be pilfered for data * as necessary. */ EVP_PKEY_CTX *pctx; /* * The action type (GET or SET). This may be 0 in some cases, and should * be modified by the fixup_args function in the PRE states. It should * otherwise remain untouched once set. */ enum action action_type; /* * For ctrl to params translation, the actual ctrl command number used. * For params to ctrl translation, 0. */ int ctrl_cmd; /* * For ctrl_str to params translation, the actual ctrl command string * used. In this case, the (string) value is always passed as |p2|. * For params to ctrl translation, this is NULL. Along with it is also * and indicator whether it matched |ctrl_str| or |ctrl_hexstr| in the * translation item. */ const char *ctrl_str; int ishex; /* the ctrl-style int argument. */ int p1; /* the ctrl-style void* argument. */ void *p2; /* a size, for passing back the |p2| size where applicable */ size_t sz; /* pointer to the OSSL_PARAM-style params array. */ OSSL_PARAM *params; /*- * The following are used entirely internally by the fixup_args functions * and should not be touched by the callers, at all. */ /* * Copy of the ctrl-style void* argument, if the fixup_args function * needs to manipulate |p2| but wants to remember original. */ void *orig_p2; /* Diverse types of storage for the needy. */ char name_buf[OSSL_MAX_NAME_SIZE]; void *allocated_buf; void *bufp; size_t buflen; }; struct translation_st { /*- * What this table item does. * * If the item has this set to 0, it means that both GET and SET are * supported, and |fixup_args| will determine which it is. This is to * support translations of ctrls where the action type depends on the * value of |p1| or |p2| (ctrls are really bi-directional, but are * seldom used that way). * * This can be also used in the lookup template when it looks up by * OSSL_PARAM key, to indicate if a setter or a getter called. */ enum action action_type; /*- * Conditions, for params->ctrl translations. * * In table item, |keytype1| and |keytype2| can be set to -1 to indicate * that this item supports all key types (or rather, that |fixup_args| * will check and return an error if it's not supported). * Any of these may be set to 0 to indicate that they are unset. */ int keytype1; /* The EVP_PKEY_XXX type, i.e. NIDs. #legacy */ int keytype2; /* Another EVP_PKEY_XXX type, used for aliases */ int optype; /* The operation type */ /* * Lookup and translation attributes * * |ctrl_num|, |ctrl_str|, |ctrl_hexstr| and |param_key| are lookup * attributes. * * |ctrl_num| may be 0 or that |param_key| may be NULL in the table item, * but not at the same time. If they are, they are simply not used for * lookup. * When |ctrl_num| == 0, no ctrl will be called. Likewise, when * |param_key| == NULL, no OSSL_PARAM setter/getter will be called. * In that case the treatment of the translation item relies entirely on * |fixup_args|, which is then assumed to have side effects. * * As a special case, it's possible to set |ctrl_hexstr| and assign NULL * to |ctrl_str|. That will signal to default_fixup_args() that the * value must always be interpreted as hex. */ int ctrl_num; /* EVP_PKEY_CTRL_xxx */ const char *ctrl_str; /* The corresponding ctrl string */ const char *ctrl_hexstr; /* The alternative "hex{str}" ctrl string */ const char *param_key; /* The corresponding OSSL_PARAM key */ /* * The appropriate OSSL_PARAM data type. This may be 0 to indicate that * this OSSL_PARAM may have more than one data type, depending on input * material. In this case, |fixup_args| is expected to check and handle * it. */ unsigned int param_data_type; /* * Fixer functions * * |fixup_args| is always called before (for SET) or after (for GET) * the actual ctrl / OSSL_PARAM function. */ fixup_args_fn *fixup_args; }; /*- * Fixer function implementations * ============================== */ /* * default_check isn't a fixer per se, but rather a helper function to * perform certain standard checks. */ static int default_check(enum state state, const struct translation_st *translation, const struct translation_ctx_st *ctx) { switch (state) { default: break; case PRE_CTRL_TO_PARAMS: if (!ossl_assert(translation != NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (!ossl_assert(translation->param_key != 0) || !ossl_assert(translation->param_data_type != 0)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return -1; } break; case PRE_CTRL_STR_TO_PARAMS: /* * For ctrl_str to params translation, we allow direct use of * OSSL_PARAM keys as ctrl_str keys. Therefore, it's possible that * we end up with |translation == NULL|, which is fine. The fixup * function will have to deal with it carefully. */ if (translation != NULL) { if (!ossl_assert(translation->action_type != GET)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (!ossl_assert(translation->param_key != NULL) || !ossl_assert(translation->param_data_type != 0)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } } break; case PRE_PARAMS_TO_CTRL: case POST_PARAMS_TO_CTRL: if (!ossl_assert(translation != NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (!ossl_assert(translation->ctrl_num != 0) || !ossl_assert(translation->param_data_type != 0)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return -1; } } /* Nothing else to check */ return 1; } /*- * default_fixup_args fixes up all sorts of arguments, governed by the * diverse attributes in the translation item. It covers all "standard" * base ctrl functionality, meaning it can handle basic conversion of * data between p1+p2 (SET) or return value+p2 (GET) as long as the values * don't have extra semantics (such as NIDs, OIDs, that sort of stuff). * Extra semantics must be handled via specific fixup_args functions. * * The following states and action type combinations have standard handling * done in this function: * * PRE_CTRL_TO_PARAMS, 0 - ERROR. action type must be * determined by a fixup function. * PRE_CTRL_TO_PARAMS, SET | GET - |p1| and |p2| are converted to an * OSSL_PARAM according to the data * type given in |translattion|. * For OSSL_PARAM_UNSIGNED_INTEGER, * a BIGNUM passed as |p2| is accepted. * POST_CTRL_TO_PARAMS, GET - If the OSSL_PARAM data type is a * STRING or PTR type, |p1| is set * to the OSSL_PARAM return size, and * |p2| is set to the string. * PRE_CTRL_STR_TO_PARAMS, !SET - ERROR. That combination is not * supported. * PRE_CTRL_STR_TO_PARAMS, SET - |p2| is taken as a string, and is * converted to an OSSL_PARAM in a * standard manner, guided by the * param key and data type from * |translation|. * PRE_PARAMS_TO_CTRL, SET - the OSSL_PARAM is converted to * |p1| and |p2| according to the * data type given in |translation| * For OSSL_PARAM_UNSIGNED_INTEGER, * if |p2| is non-NULL, then |*p2| * is assigned a BIGNUM, otherwise * |p1| is assigned an unsigned int. * POST_PARAMS_TO_CTRL, GET - |p1| and |p2| are converted to * an OSSL_PARAM, in the same manner * as for the combination of * PRE_CTRL_TO_PARAMS, SET. */ static int default_fixup_args(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; switch (state) { default: /* For states this function should never have been called with */ ERR_raise_data(ERR_LIB_EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, "[action:%d, state:%d]", ctx->action_type, state); return 0; /* * PRE_CTRL_TO_PARAMS and POST_CTRL_TO_PARAMS handle ctrl to params * translations. PRE_CTRL_TO_PARAMS is responsible for preparing * |*params|, and POST_CTRL_TO_PARAMS is responsible for bringing the * result back to |*p2| and the return value. */ case PRE_CTRL_TO_PARAMS: /* This is ctrl to params translation, so we need an OSSL_PARAM key */ if (ctx->action_type == NONE) { /* * No action type is an error here. That's a case for a * special fixup function. */ ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED, "[action:%d, state:%d]", ctx->action_type, state); return 0; } if (translation->optype != 0) { if ((EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx) && ctx->pctx->op.sig.algctx == NULL) || (EVP_PKEY_CTX_IS_DERIVE_OP(ctx->pctx) && ctx->pctx->op.kex.algctx == NULL) || (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx->pctx) && ctx->pctx->op.ciph.algctx == NULL) || (EVP_PKEY_CTX_IS_KEM_OP(ctx->pctx) && ctx->pctx->op.encap.algctx == NULL) /* * The following may be unnecessary, but we have them * for good measure... */ || (EVP_PKEY_CTX_IS_GEN_OP(ctx->pctx) && ctx->pctx->op.keymgmt.genctx == NULL) || (EVP_PKEY_CTX_IS_FROMDATA_OP(ctx->pctx) && ctx->pctx->op.keymgmt.genctx == NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } } /* * OSSL_PARAM_construct_TYPE() works equally well for both SET and GET. */ switch (translation->param_data_type) { case OSSL_PARAM_INTEGER: *ctx->params = OSSL_PARAM_construct_int(translation->param_key, &ctx->p1); break; case OSSL_PARAM_UNSIGNED_INTEGER: /* * BIGNUMs are passed via |p2|. For all ctrl's that just want * to pass a simple integer via |p1|, |p2| is expected to be * NULL. * * Note that this allocates a buffer, which the cleanup function * must deallocate. */ if (ctx->p2 != NULL) { if (ctx->action_type == SET) { ctx->buflen = BN_num_bytes(ctx->p2); if ((ctx->allocated_buf = OPENSSL_malloc(ctx->buflen)) == NULL) return 0; if (BN_bn2nativepad(ctx->p2, ctx->allocated_buf, ctx->buflen) < 0) { OPENSSL_free(ctx->allocated_buf); ctx->allocated_buf = NULL; return 0; } *ctx->params = OSSL_PARAM_construct_BN(translation->param_key, ctx->allocated_buf, ctx->buflen); } else { /* * No support for getting a BIGNUM by ctrl, this needs * fixup_args function support. */ ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED, "[action:%d, state:%d] trying to get a " "BIGNUM via ctrl call", ctx->action_type, state); return 0; } } else { *ctx->params = OSSL_PARAM_construct_uint(translation->param_key, (unsigned int *)&ctx->p1); } break; case OSSL_PARAM_UTF8_STRING: *ctx->params = OSSL_PARAM_construct_utf8_string(translation->param_key, ctx->p2, (size_t)ctx->p1); break; case OSSL_PARAM_UTF8_PTR: *ctx->params = OSSL_PARAM_construct_utf8_ptr(translation->param_key, ctx->p2, (size_t)ctx->p1); break; case OSSL_PARAM_OCTET_STRING: *ctx->params = OSSL_PARAM_construct_octet_string(translation->param_key, ctx->p2, (size_t)ctx->p1); break; case OSSL_PARAM_OCTET_PTR: *ctx->params = OSSL_PARAM_construct_octet_ptr(translation->param_key, ctx->p2, (size_t)ctx->p1); break; } break; case POST_CTRL_TO_PARAMS: /* * Because EVP_PKEY_CTX_ctrl() returns the length of certain objects * as its return value, we need to ensure that we do it here as well, * for the OSSL_PARAM data types where this makes sense. */ if (ctx->action_type == GET) { switch (translation->param_data_type) { case OSSL_PARAM_UTF8_STRING: case OSSL_PARAM_UTF8_PTR: case OSSL_PARAM_OCTET_STRING: case OSSL_PARAM_OCTET_PTR: ctx->p1 = (int)ctx->params[0].return_size; break; } } break; /* * PRE_CTRL_STR_TO_PARAMS and POST_CTRL_STR_TO_PARAMS handle ctrl_str to * params translations. PRE_CTRL_TO_PARAMS is responsible for preparing * |*params|, and POST_CTRL_TO_PARAMS currently has nothing to do, since * there's no support for getting data via ctrl_str calls. */ case PRE_CTRL_STR_TO_PARAMS: { /* This is ctrl_str to params translation */ const char *tmp_ctrl_str = ctx->ctrl_str; const char *orig_ctrl_str = ctx->ctrl_str; const char *orig_value = ctx->p2; const OSSL_PARAM *settable = NULL; int exists = 0; /* Only setting is supported here */ if (ctx->action_type != SET) { ERR_raise_data(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED, "[action:%d, state:%d] only setting allowed", ctx->action_type, state); return 0; } /* * If no translation exists, we simply pass the control string * unmodified. */ if (translation != NULL) { tmp_ctrl_str = ctx->ctrl_str = translation->param_key; if (ctx->ishex) { strcpy(ctx->name_buf, "hex"); if (OPENSSL_strlcat(ctx->name_buf, tmp_ctrl_str, sizeof(ctx->name_buf)) <= 3) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return -1; } tmp_ctrl_str = ctx->name_buf; } } settable = EVP_PKEY_CTX_settable_params(ctx->pctx); if (!OSSL_PARAM_allocate_from_text(ctx->params, settable, tmp_ctrl_str, ctx->p2, strlen(ctx->p2), &exists)) { if (!exists) { ERR_raise_data(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED, "[action:%d, state:%d] name=%s, value=%s", ctx->action_type, state, orig_ctrl_str, orig_value); return -2; } return 0; } ctx->allocated_buf = ctx->params->data; ctx->buflen = ctx->params->data_size; } break; case POST_CTRL_STR_TO_PARAMS: /* Nothing to be done */ break; /* * PRE_PARAMS_TO_CTRL and POST_PARAMS_TO_CTRL handle params to ctrl * translations. PRE_PARAMS_TO_CTRL is responsible for preparing * |p1| and |p2|, and POST_PARAMS_TO_CTRL is responsible for bringing * the EVP_PKEY_CTX_ctrl() return value (passed as |p1|) and |p2| back * to |*params|. * * PKEY is treated just like POST_PARAMS_TO_CTRL, making it easy * for the related fixup_args functions to just set |p1| and |p2| * appropriately and leave it to this section of code to fix up * |ctx->params| accordingly. */ case PKEY: case POST_PARAMS_TO_CTRL: ret = ctx->p1; /* FALLTHRU */ case PRE_PARAMS_TO_CTRL: { /* This is params to ctrl translation */ if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET) { /* For the PRE state, only setting needs some work to be done */ /* When setting, we populate |p1| and |p2| from |*params| */ switch (translation->param_data_type) { case OSSL_PARAM_INTEGER: return OSSL_PARAM_get_int(ctx->params, &ctx->p1); case OSSL_PARAM_UNSIGNED_INTEGER: if (ctx->p2 != NULL) { /* BIGNUM passed down with p2 */ if (!OSSL_PARAM_get_BN(ctx->params, ctx->p2)) return 0; } else { /* Normal C unsigned int passed down */ if (!OSSL_PARAM_get_uint(ctx->params, (unsigned int *)&ctx->p1)) return 0; } return 1; case OSSL_PARAM_UTF8_STRING: return OSSL_PARAM_get_utf8_string(ctx->params, ctx->p2, ctx->sz); case OSSL_PARAM_OCTET_STRING: return OSSL_PARAM_get_octet_string(ctx->params, &ctx->p2, ctx->sz, (size_t *)&ctx->p1); case OSSL_PARAM_OCTET_PTR: return OSSL_PARAM_get_octet_ptr(ctx->params, ctx->p2, &ctx->sz); default: ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED, "[action:%d, state:%d] " "unknown OSSL_PARAM data type %d", ctx->action_type, state, translation->param_data_type); return 0; } } else if ((state == POST_PARAMS_TO_CTRL || state == PKEY) && ctx->action_type == GET) { /* For the POST state, only getting needs some work to be done */ unsigned int param_data_type = translation->param_data_type; size_t size = (size_t)ctx->p1; if (state == PKEY) size = ctx->sz; if (param_data_type == 0) { /* we must have a fixup_args function to work */ if (!ossl_assert(translation->fixup_args != NULL)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } param_data_type = ctx->params->data_type; } /* When getting, we populate |*params| from |p1| and |p2| */ switch (param_data_type) { case OSSL_PARAM_INTEGER: return OSSL_PARAM_set_int(ctx->params, ctx->p1); case OSSL_PARAM_UNSIGNED_INTEGER: if (ctx->p2 != NULL) { /* BIGNUM passed back */ return OSSL_PARAM_set_BN(ctx->params, ctx->p2); } else { /* Normal C unsigned int passed back */ return OSSL_PARAM_set_uint(ctx->params, (unsigned int)ctx->p1); } return 0; case OSSL_PARAM_UTF8_STRING: return OSSL_PARAM_set_utf8_string(ctx->params, ctx->p2); case OSSL_PARAM_OCTET_STRING: return OSSL_PARAM_set_octet_string(ctx->params, ctx->p2, size); case OSSL_PARAM_OCTET_PTR: return OSSL_PARAM_set_octet_ptr(ctx->params, *(void **)ctx->p2, size); default: ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED, "[action:%d, state:%d] " "unsupported OSSL_PARAM data type %d", ctx->action_type, state, translation->param_data_type); return 0; } } else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == GET) { if (translation->param_data_type == OSSL_PARAM_OCTET_PTR) ctx->p2 = &ctx->bufp; } } /* Any other combination is simply pass-through */ break; } return ret; } static int cleanup_translation_ctx(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { if (ctx->allocated_buf != NULL) OPENSSL_free(ctx->allocated_buf); ctx->allocated_buf = NULL; return 1; } /* * fix_cipher_md fixes up an EVP_CIPHER / EVP_MD to its name on SET, * and cipher / md name to EVP_MD on GET. */ static const char *get_cipher_name(void *cipher) { return EVP_CIPHER_get0_name(cipher); } static const char *get_md_name(void *md) { return EVP_MD_get0_name(md); } static const void *get_cipher_by_name(OSSL_LIB_CTX *libctx, const char *name) { return evp_get_cipherbyname_ex(libctx, name); } static const void *get_md_by_name(OSSL_LIB_CTX *libctx, const char *name) { return evp_get_digestbyname_ex(libctx, name); } static int fix_cipher_md(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, const char *(*get_name)(void *algo), const void *(*get_algo_by_name)(OSSL_LIB_CTX *libctx, const char *name)) { int ret = 1; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == GET) { /* * |ctx->p2| contains the address to an EVP_CIPHER or EVP_MD pointer * to be filled in. We need to remember it, then make |ctx->p2| * point at a buffer to be filled in with the name, and |ctx->p1| * with its size. default_fixup_args() will take care of the rest * for us. */ ctx->orig_p2 = ctx->p2; ctx->p2 = ctx->name_buf; ctx->p1 = sizeof(ctx->name_buf); } else if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) { /* * In different parts of OpenSSL, this ctrl command is used * differently. Some calls pass a NID as p1, others pass an * EVP_CIPHER pointer as p2... */ ctx->p2 = (char *)(ctx->p2 == NULL ? OBJ_nid2sn(ctx->p1) : get_name(ctx->p2)); ctx->p1 = strlen(ctx->p2); } else if (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET) { ctx->p2 = (ctx->p2 == NULL ? "" : (char *)get_name(ctx->p2)); ctx->p1 = strlen(ctx->p2); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if (state == POST_CTRL_TO_PARAMS && ctx->action_type == GET) { /* * Here's how we reuse |ctx->orig_p2| that was set in the * PRE_CTRL_TO_PARAMS state above. */ *(void **)ctx->orig_p2 = (void *)get_algo_by_name(ctx->pctx->libctx, ctx->p2); ctx->p1 = 1; } else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET) { ctx->p2 = (void *)get_algo_by_name(ctx->pctx->libctx, ctx->p2); ctx->p1 = 0; } return ret; } static int fix_cipher(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { return fix_cipher_md(state, translation, ctx, get_cipher_name, get_cipher_by_name); } static int fix_md(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { return fix_cipher_md(state, translation, ctx, get_md_name, get_md_by_name); } static int fix_distid_len(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret = default_fixup_args(state, translation, ctx); if (ret > 0) { ret = 0; if ((state == POST_CTRL_TO_PARAMS || state == POST_CTRL_STR_TO_PARAMS) && ctx->action_type == GET) { *(size_t *)ctx->p2 = ctx->sz; ret = 1; } } return ret; } struct kdf_type_map_st { int kdf_type_num; const char *kdf_type_str; }; static int fix_kdf_type(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, const struct kdf_type_map_st *kdf_type_map) { /* * The EVP_PKEY_CTRL_DH_KDF_TYPE ctrl command is a bit special, in * that it's used both for setting a value, and for getting it, all * depending on the value if |p1|; if |p1| is -2, the backend is * supposed to place the current kdf type in |p2|, and if not, |p1| * is interpreted as the new kdf type. */ int ret = 0; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if (state == PRE_CTRL_TO_PARAMS) { /* * In |translations|, the initial value for |ctx->action_type| must * be NONE. */ if (!ossl_assert(ctx->action_type == NONE)) return 0; /* The action type depends on the value of *p1 */ if (ctx->p1 == -2) { /* * The OSSL_PARAMS getter needs space to store a copy of the kdf * type string. We use |ctx->name_buf|, which has enough space * allocated. * * (this wouldn't be needed if the OSSL_xxx_PARAM_KDF_TYPE * had the data type OSSL_PARAM_UTF8_PTR) */ ctx->p2 = ctx->name_buf; ctx->p1 = sizeof(ctx->name_buf); ctx->action_type = GET; } else { ctx->action_type = SET; } } if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if ((state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) || (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET)) { ret = -2; /* Convert KDF type numbers to strings */ for (; kdf_type_map->kdf_type_str != NULL; kdf_type_map++) if (ctx->p1 == kdf_type_map->kdf_type_num) { ctx->p2 = (char *)kdf_type_map->kdf_type_str; ret = 1; break; } if (ret <= 0) goto end; ctx->p1 = strlen(ctx->p2); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if ((state == POST_CTRL_TO_PARAMS && ctx->action_type == GET) || (state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET)) { ctx->p1 = ret = -1; /* Convert KDF type strings to numbers */ for (; kdf_type_map->kdf_type_str != NULL; kdf_type_map++) if (OPENSSL_strcasecmp(ctx->p2, kdf_type_map->kdf_type_str) == 0) { ctx->p1 = kdf_type_map->kdf_type_num; ret = 1; break; } ctx->p2 = NULL; } else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == GET) { ctx->p1 = -2; } end: return ret; } /* EVP_PKEY_CTRL_DH_KDF_TYPE */ static int fix_dh_kdf_type(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { static const struct kdf_type_map_st kdf_type_map[] = { { EVP_PKEY_DH_KDF_NONE, "" }, { EVP_PKEY_DH_KDF_X9_42, OSSL_KDF_NAME_X942KDF_ASN1 }, { 0, NULL } }; return fix_kdf_type(state, translation, ctx, kdf_type_map); } /* EVP_PKEY_CTRL_EC_KDF_TYPE */ static int fix_ec_kdf_type(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { static const struct kdf_type_map_st kdf_type_map[] = { { EVP_PKEY_ECDH_KDF_NONE, "" }, { EVP_PKEY_ECDH_KDF_X9_63, OSSL_KDF_NAME_X963KDF }, { 0, NULL } }; return fix_kdf_type(state, translation, ctx, kdf_type_map); } /* EVP_PKEY_CTRL_DH_KDF_OID, EVP_PKEY_CTRL_GET_DH_KDF_OID, ...??? */ static int fix_oid(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if ((state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) || (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET)) { /* * We're translating from ctrl to params and setting the OID, or * we're translating from params to ctrl and getting the OID. * Either way, |ctx->p2| points at an ASN1_OBJECT, and needs to have * that replaced with the corresponding name. * default_fixup_args() will then be able to convert that to the * corresponding OSSL_PARAM. */ OBJ_obj2txt(ctx->name_buf, sizeof(ctx->name_buf), ctx->p2, 0); ctx->p2 = (char *)ctx->name_buf; ctx->p1 = 0; /* let default_fixup_args() figure out the length */ } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if ((state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET) || (state == POST_CTRL_TO_PARAMS && ctx->action_type == GET)) { /* * We're translating from ctrl to params and setting the OID name, * or we're translating from params to ctrl and getting the OID * name. Either way, default_fixup_args() has placed the OID name * in |ctx->p2|, all we need to do now is to replace that with the * corresponding ASN1_OBJECT. */ ctx->p2 = (ASN1_OBJECT *)OBJ_txt2obj(ctx->p2, 0); } return ret; } /* EVP_PKEY_CTRL_DH_NID */ static int fix_dh_nid(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; /* This is only settable */ if (ctx->action_type != SET) return 0; if (state == PRE_CTRL_TO_PARAMS) { if ((ctx->p2 = (char *)ossl_ffc_named_group_get_name (ossl_ffc_uid_to_dh_named_group(ctx->p1))) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE); return 0; } ctx->p1 = 0; } return default_fixup_args(state, translation, ctx); } /* EVP_PKEY_CTRL_DH_RFC5114 */ static int fix_dh_nid5114(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; /* This is only settable */ if (ctx->action_type != SET) return 0; switch (state) { case PRE_CTRL_TO_PARAMS: if ((ctx->p2 = (char *)ossl_ffc_named_group_get_name (ossl_ffc_uid_to_dh_named_group(ctx->p1))) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE); return 0; } ctx->p1 = 0; break; case PRE_CTRL_STR_TO_PARAMS: if (ctx->p2 == NULL) return 0; if ((ctx->p2 = (char *)ossl_ffc_named_group_get_name (ossl_ffc_uid_to_dh_named_group(atoi(ctx->p2)))) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE); return 0; } ctx->p1 = 0; break; default: break; } return default_fixup_args(state, translation, ctx); } /* EVP_PKEY_CTRL_DH_PARAMGEN_TYPE */ static int fix_dh_paramgen_type(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; /* This is only settable */ if (ctx->action_type != SET) return 0; if (state == PRE_CTRL_STR_TO_PARAMS) { if ((ctx->p2 = (char *)ossl_dh_gen_type_id2name(atoi(ctx->p2))) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE); return 0; } ctx->p1 = strlen(ctx->p2); } return default_fixup_args(state, translation, ctx); } /* EVP_PKEY_CTRL_EC_PARAM_ENC */ static int fix_ec_param_enc(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; /* This is currently only settable */ if (ctx->action_type != SET) return 0; if (state == PRE_CTRL_TO_PARAMS) { switch (ctx->p1) { case OPENSSL_EC_EXPLICIT_CURVE: ctx->p2 = OSSL_PKEY_EC_ENCODING_EXPLICIT; break; case OPENSSL_EC_NAMED_CURVE: ctx->p2 = OSSL_PKEY_EC_ENCODING_GROUP; break; default: ret = -2; goto end; } ctx->p1 = 0; } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if (state == PRE_PARAMS_TO_CTRL) { if (strcmp(ctx->p2, OSSL_PKEY_EC_ENCODING_EXPLICIT) == 0) ctx->p1 = OPENSSL_EC_EXPLICIT_CURVE; else if (strcmp(ctx->p2, OSSL_PKEY_EC_ENCODING_GROUP) == 0) ctx->p1 = OPENSSL_EC_NAMED_CURVE; else ctx->p1 = ret = -2; ctx->p2 = NULL; } end: if (ret == -2) ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return ret; } /* EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID */ static int fix_ec_paramgen_curve_nid(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { char *p2 = NULL; int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; /* This is currently only settable */ if (ctx->action_type != SET) return 0; if (state == PRE_CTRL_TO_PARAMS) { ctx->p2 = (char *)OBJ_nid2sn(ctx->p1); ctx->p1 = 0; } else if (state == PRE_PARAMS_TO_CTRL) { /* * We're translating from params to ctrl and setting the curve name. * The ctrl function needs it to be a NID, but meanwhile, we need * space to get the curve name from the param. |ctx->name_buf| is * sufficient for that. * The double indirection is necessary for default_fixup_args()'s * call of OSSL_PARAM_get_utf8_string() to be done correctly. */ p2 = ctx->name_buf; ctx->p2 = &p2; ctx->sz = sizeof(ctx->name_buf); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if (state == PRE_PARAMS_TO_CTRL) { ctx->p1 = OBJ_sn2nid(p2); ctx->p2 = NULL; } return ret; } /* EVP_PKEY_CTRL_EC_ECDH_COFACTOR */ static int fix_ecdh_cofactor(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { /* * The EVP_PKEY_CTRL_EC_ECDH_COFACTOR ctrl command is a bit special, in * that it's used both for setting a value, and for getting it, all * depending on the value if |ctx->p1|; if |ctx->p1| is -2, the backend is * supposed to place the current cofactor mode in |ctx->p2|, and if not, * |ctx->p1| is interpreted as the new cofactor mode. */ int ret = 0; if (state == PRE_CTRL_TO_PARAMS) { /* * The initial value for |ctx->action_type| must be zero. * evp_pkey_ctrl_to_params() takes it from the translation item. */ if (!ossl_assert(ctx->action_type == NONE)) return 0; /* The action type depends on the value of ctx->p1 */ if (ctx->p1 == -2) ctx->action_type = GET; else ctx->action_type = SET; } else if (state == PRE_CTRL_STR_TO_PARAMS) { ctx->action_type = SET; } else if (state == PRE_PARAMS_TO_CTRL) { /* The initial value for |ctx->action_type| must not be zero. */ if (!ossl_assert(ctx->action_type != NONE)) return 0; } if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) { if (ctx->p1 < -1 || ctx->p1 > 1) { /* Uses the same return value of pkey_ec_ctrl() */ return -2; } } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if (state == POST_CTRL_TO_PARAMS && ctx->action_type == GET) { if (ctx->p1 < 0 || ctx->p1 > 1) { /* * The provider should return either 0 or 1, any other value is a * provider error. */ ctx->p1 = ret = -1; } } else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == GET) { ctx->p1 = -2; } return ret; } /* EVP_PKEY_CTRL_RSA_PADDING, EVP_PKEY_CTRL_GET_RSA_PADDING */ static int fix_rsa_padding_mode(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { static const OSSL_ITEM str_value_map[] = { { RSA_PKCS1_PADDING, "pkcs1" }, { RSA_NO_PADDING, "none" }, { RSA_PKCS1_OAEP_PADDING, "oaep" }, { RSA_PKCS1_OAEP_PADDING, "oeap" }, { RSA_X931_PADDING, "x931" }, { RSA_PKCS1_PSS_PADDING, "pss" }, /* Special case, will pass directly as an integer */ { RSA_PKCS1_WITH_TLS_PADDING, NULL } }; int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == GET) { /* * EVP_PKEY_CTRL_GET_RSA_PADDING returns the padding mode in the * weirdest way for a ctrl. Instead of doing like all other ctrls * that return a simple, i.e. just have that as a return value, * this particular ctrl treats p2 as the address for the int to be * returned. We must therefore remember |ctx->p2|, then make * |ctx->p2| point at a buffer to be filled in with the name, and * |ctx->p1| with its size. default_fixup_args() will take care * of the rest for us, along with the POST_CTRL_TO_PARAMS && GET * code section further down. */ ctx->orig_p2 = ctx->p2; ctx->p2 = ctx->name_buf; ctx->p1 = sizeof(ctx->name_buf); } else if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) { /* * Ideally, we should use utf8 strings for the diverse padding modes. * We only came here because someone called EVP_PKEY_CTX_ctrl(), * though, and since that can reasonably be seen as legacy code * that uses the diverse RSA macros for the padding mode, and we * know that at least our providers can handle the numeric modes, * we take the cheap route for now. * * The other solution would be to match |ctx->p1| against entries * in str_value_map and pass the corresponding string. However, * since we don't have a string for RSA_PKCS1_WITH_TLS_PADDING, * we have to do this same hack at least for that one. * * Since the "official" data type for the RSA padding mode is utf8 * string, we cannot count on default_fixup_args(). Instead, we * build the OSSL_PARAM item ourselves and return immediately. */ ctx->params[0] = OSSL_PARAM_construct_int(translation->param_key, &ctx->p1); return 1; } else if (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET) { size_t i; /* * The EVP_PKEY_CTX_get_params() caller may have asked for a utf8 * string, or may have asked for an integer of some sort. If they * ask for an integer, we respond directly. If not, we translate * the response from the ctrl function into a string. */ switch (ctx->params->data_type) { case OSSL_PARAM_INTEGER: return OSSL_PARAM_get_int(ctx->params, &ctx->p1); case OSSL_PARAM_UNSIGNED_INTEGER: return OSSL_PARAM_get_uint(ctx->params, (unsigned int *)&ctx->p1); default: break; } for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (ctx->p1 == (int)str_value_map[i].id) break; } if (i == OSSL_NELEM(str_value_map)) { ERR_raise_data(ERR_LIB_RSA, RSA_R_UNKNOWN_PADDING_TYPE, "[action:%d, state:%d] padding number %d", ctx->action_type, state, ctx->p1); return -2; } /* * If we don't have a string, we can't do anything. The caller * should have asked for a number... */ if (str_value_map[i].ptr == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } ctx->p2 = str_value_map[i].ptr; ctx->p1 = strlen(ctx->p2); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if ((ctx->action_type == SET && state == PRE_PARAMS_TO_CTRL) || (ctx->action_type == GET && state == POST_CTRL_TO_PARAMS)) { size_t i; for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (strcmp(ctx->p2, str_value_map[i].ptr) == 0) break; } if (i == OSSL_NELEM(str_value_map)) { ERR_raise_data(ERR_LIB_RSA, RSA_R_UNKNOWN_PADDING_TYPE, "[action:%d, state:%d] padding name %s", ctx->action_type, state, ctx->p1); ctx->p1 = ret = -2; } else if (state == POST_CTRL_TO_PARAMS) { /* EVP_PKEY_CTRL_GET_RSA_PADDING weirdness explained further up */ *(int *)ctx->orig_p2 = str_value_map[i].id; } else { ctx->p1 = str_value_map[i].id; } ctx->p2 = NULL; } return ret; } /* EVP_PKEY_CTRL_RSA_PSS_SALTLEN, EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN */ static int fix_rsa_pss_saltlen(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { static const OSSL_ITEM str_value_map[] = { { (unsigned int)RSA_PSS_SALTLEN_DIGEST, "digest" }, { (unsigned int)RSA_PSS_SALTLEN_MAX, "max" }, { (unsigned int)RSA_PSS_SALTLEN_AUTO, "auto" } }; int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == GET) { /* * EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN returns the saltlen by filling * in the int pointed at by p2. This is potentially as weird as * the way EVP_PKEY_CTRL_GET_RSA_PADDING works, except that saltlen * might be a negative value, so it wouldn't work as a legitimate * return value. * In any case, we must therefore remember |ctx->p2|, then make * |ctx->p2| point at a buffer to be filled in with the name, and * |ctx->p1| with its size. default_fixup_args() will take care * of the rest for us, along with the POST_CTRL_TO_PARAMS && GET * code section further down. */ ctx->orig_p2 = ctx->p2; ctx->p2 = ctx->name_buf; ctx->p1 = sizeof(ctx->name_buf); } else if ((ctx->action_type == SET && state == PRE_CTRL_TO_PARAMS) || (ctx->action_type == GET && state == POST_PARAMS_TO_CTRL)) { size_t i; for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (ctx->p1 == (int)str_value_map[i].id) break; } if (i == OSSL_NELEM(str_value_map)) { BIO_snprintf(ctx->name_buf, sizeof(ctx->name_buf), "%d", ctx->p1); } else { /* This won't truncate but it will quiet static analysers */ strncpy(ctx->name_buf, str_value_map[i].ptr, sizeof(ctx->name_buf) - 1); ctx->name_buf[sizeof(ctx->name_buf) - 1] = '\0'; } ctx->p2 = ctx->name_buf; ctx->p1 = strlen(ctx->p2); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if ((ctx->action_type == SET && state == PRE_PARAMS_TO_CTRL) || (ctx->action_type == GET && state == POST_CTRL_TO_PARAMS)) { size_t i; int val; for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (strcmp(ctx->p2, str_value_map[i].ptr) == 0) break; } val = i == OSSL_NELEM(str_value_map) ? atoi(ctx->p2) : (int)str_value_map[i].id; if (state == POST_CTRL_TO_PARAMS) { /* * EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN weirdness explained further * up */ *(int *)ctx->orig_p2 = val; } else { ctx->p1 = val; } ctx->p2 = NULL; } return ret; } /* EVP_PKEY_CTRL_HKDF_MODE */ static int fix_hkdf_mode(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { static const OSSL_ITEM str_value_map[] = { { EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND, "EXTRACT_AND_EXPAND" }, { EVP_KDF_HKDF_MODE_EXTRACT_ONLY, "EXTRACT_ONLY" }, { EVP_KDF_HKDF_MODE_EXPAND_ONLY, "EXPAND_ONLY" } }; int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if ((ctx->action_type == SET && state == PRE_CTRL_TO_PARAMS) || (ctx->action_type == GET && state == POST_PARAMS_TO_CTRL)) { size_t i; for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (ctx->p1 == (int)str_value_map[i].id) break; } if (i == OSSL_NELEM(str_value_map)) return 0; ctx->p2 = str_value_map[i].ptr; ctx->p1 = strlen(ctx->p2); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if ((ctx->action_type == SET && state == PRE_PARAMS_TO_CTRL) || (ctx->action_type == GET && state == POST_CTRL_TO_PARAMS)) { size_t i; for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (strcmp(ctx->p2, str_value_map[i].ptr) == 0) break; } if (i == OSSL_NELEM(str_value_map)) return 0; if (state == POST_CTRL_TO_PARAMS) ret = str_value_map[i].id; else ctx->p1 = str_value_map[i].id; ctx->p2 = NULL; } return 1; } /*- * Payload getters * =============== * * These all get the data they want, then call default_fixup_args() as * a post-ctrl GET fixup. They all get NULL ctx, ctrl_cmd, ctrl_str, * p1, sz */ /* Pilfering DH, DSA and EC_KEY */ static int get_payload_group_name(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { EVP_PKEY *pkey = ctx->p2; ctx->p2 = NULL; switch (EVP_PKEY_get_base_id(pkey)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DH: { const DH *dh = EVP_PKEY_get0_DH(pkey); int uid = DH_get_nid(dh); if (uid != NID_undef) { const DH_NAMED_GROUP *dh_group = ossl_ffc_uid_to_dh_named_group(uid); ctx->p2 = (char *)ossl_ffc_named_group_get_name(dh_group); } } break; #endif #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: { const EC_GROUP *grp = EC_KEY_get0_group(EVP_PKEY_get0_EC_KEY(pkey)); int nid = NID_undef; if (grp != NULL) nid = EC_GROUP_get_curve_name(grp); if (nid != NID_undef) ctx->p2 = (char *)OSSL_EC_curve_nid2name(nid); } break; #endif default: ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; } /* * Quietly ignoring unknown groups matches the behaviour on the provider * side. */ if (ctx->p2 == NULL) return 1; ctx->p1 = strlen(ctx->p2); return default_fixup_args(state, translation, ctx); } static int get_payload_private_key(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { EVP_PKEY *pkey = ctx->p2; ctx->p2 = NULL; if (ctx->params->data_type != OSSL_PARAM_UNSIGNED_INTEGER) return 0; switch (EVP_PKEY_get_base_id(pkey)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DH: { const DH *dh = EVP_PKEY_get0_DH(pkey); ctx->p2 = (BIGNUM *)DH_get0_priv_key(dh); } break; #endif #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: { const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey); ctx->p2 = (BIGNUM *)EC_KEY_get0_private_key(ec); } break; #endif default: ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; } return default_fixup_args(state, translation, ctx); } static int get_payload_public_key(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { EVP_PKEY *pkey = ctx->p2; unsigned char *buf = NULL; int ret; ctx->p2 = NULL; switch (EVP_PKEY_get_base_id(pkey)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DHX: case EVP_PKEY_DH: switch (ctx->params->data_type) { case OSSL_PARAM_OCTET_STRING: ctx->sz = ossl_dh_key2buf(EVP_PKEY_get0_DH(pkey), &buf, 0, 1); ctx->p2 = buf; break; case OSSL_PARAM_UNSIGNED_INTEGER: ctx->p2 = (void *)DH_get0_pub_key(EVP_PKEY_get0_DH(pkey)); break; default: return 0; } break; #endif #ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: if (ctx->params->data_type == OSSL_PARAM_UNSIGNED_INTEGER) { ctx->p2 = (void *)DSA_get0_pub_key(EVP_PKEY_get0_DSA(pkey)); break; } return 0; #endif #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: if (ctx->params->data_type == OSSL_PARAM_OCTET_STRING) { const EC_KEY *eckey = EVP_PKEY_get0_EC_KEY(pkey); BN_CTX *bnctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(eckey)); const EC_GROUP *ecg = EC_KEY_get0_group(eckey); const EC_POINT *point = EC_KEY_get0_public_key(eckey); if (bnctx == NULL) return 0; ctx->sz = EC_POINT_point2buf(ecg, point, POINT_CONVERSION_COMPRESSED, &buf, bnctx); ctx->p2 = buf; BN_CTX_free(bnctx); break; } return 0; #endif default: ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; } ret = default_fixup_args(state, translation, ctx); OPENSSL_free(buf); return ret; } static int get_payload_public_key_ec(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { #ifndef OPENSSL_NO_EC EVP_PKEY *pkey = ctx->p2; const EC_KEY *eckey = EVP_PKEY_get0_EC_KEY(pkey); BN_CTX *bnctx; const EC_POINT *point; const EC_GROUP *ecg; BIGNUM *x = NULL; BIGNUM *y = NULL; int ret = 0; ctx->p2 = NULL; if (eckey == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; } bnctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(eckey)); if (bnctx == NULL) return 0; point = EC_KEY_get0_public_key(eckey); ecg = EC_KEY_get0_group(eckey); /* Caller should have requested a BN, fail if not */ if (ctx->params->data_type != OSSL_PARAM_UNSIGNED_INTEGER) goto out; x = BN_CTX_get(bnctx); y = BN_CTX_get(bnctx); if (y == NULL) goto out; if (!EC_POINT_get_affine_coordinates(ecg, point, x, y, bnctx)) goto out; if (strncmp(ctx->params->key, OSSL_PKEY_PARAM_EC_PUB_X, 2) == 0) ctx->p2 = x; else if (strncmp(ctx->params->key, OSSL_PKEY_PARAM_EC_PUB_Y, 2) == 0) ctx->p2 = y; else goto out; /* Return the payload */ ret = default_fixup_args(state, translation, ctx); out: BN_CTX_free(bnctx); return ret; #else ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; #endif } static int get_payload_bn(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, const BIGNUM *bn) { if (bn == NULL) return 0; if (ctx->params->data_type != OSSL_PARAM_UNSIGNED_INTEGER) return 0; ctx->p2 = (BIGNUM *)bn; return default_fixup_args(state, translation, ctx); } static int get_dh_dsa_payload_p(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; EVP_PKEY *pkey = ctx->p2; switch (EVP_PKEY_get_base_id(pkey)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DH: bn = DH_get0_p(EVP_PKEY_get0_DH(pkey)); break; #endif #ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: bn = DSA_get0_p(EVP_PKEY_get0_DSA(pkey)); break; #endif default: ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); } return get_payload_bn(state, translation, ctx, bn); } static int get_dh_dsa_payload_q(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; switch (EVP_PKEY_get_base_id(ctx->p2)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DH: bn = DH_get0_q(EVP_PKEY_get0_DH(ctx->p2)); break; #endif #ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: bn = DSA_get0_q(EVP_PKEY_get0_DSA(ctx->p2)); break; #endif } return get_payload_bn(state, translation, ctx, bn); } static int get_dh_dsa_payload_g(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; switch (EVP_PKEY_get_base_id(ctx->p2)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DH: bn = DH_get0_g(EVP_PKEY_get0_DH(ctx->p2)); break; #endif #ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: bn = DSA_get0_g(EVP_PKEY_get0_DSA(ctx->p2)); break; #endif } return get_payload_bn(state, translation, ctx, bn); } static int get_payload_int(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, const int val) { if (ctx->params->data_type != OSSL_PARAM_INTEGER) return 0; ctx->p1 = val; ctx->p2 = NULL; return default_fixup_args(state, translation, ctx); } static int get_ec_decoded_from_explicit_params(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int val = 0; EVP_PKEY *pkey = ctx->p2; switch (EVP_PKEY_base_id(pkey)) { #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: val = EC_KEY_decoded_from_explicit_params(EVP_PKEY_get0_EC_KEY(pkey)); if (val < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY); return 0; } break; #endif default: ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; } return get_payload_int(state, translation, ctx, val); } static int get_rsa_payload_n(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) return 0; bn = RSA_get0_n(EVP_PKEY_get0_RSA(ctx->p2)); return get_payload_bn(state, translation, ctx, bn); } static int get_rsa_payload_e(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) return 0; bn = RSA_get0_e(EVP_PKEY_get0_RSA(ctx->p2)); return get_payload_bn(state, translation, ctx, bn); } static int get_rsa_payload_d(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) return 0; bn = RSA_get0_d(EVP_PKEY_get0_RSA(ctx->p2)); return get_payload_bn(state, translation, ctx, bn); } static int get_rsa_payload_factor(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, size_t factornum) { const RSA *r = EVP_PKEY_get0_RSA(ctx->p2); const BIGNUM *bn = NULL; switch (factornum) { case 0: bn = RSA_get0_p(r); break; case 1: bn = RSA_get0_q(r); break; default: { size_t pnum = RSA_get_multi_prime_extra_count(r); const BIGNUM *factors[10]; if (factornum - 2 < pnum && RSA_get0_multi_prime_factors(r, factors)) bn = factors[factornum - 2]; } break; } return get_payload_bn(state, translation, ctx, bn); } static int get_rsa_payload_exponent(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, size_t exponentnum) { const RSA *r = EVP_PKEY_get0_RSA(ctx->p2); const BIGNUM *bn = NULL; switch (exponentnum) { case 0: bn = RSA_get0_dmp1(r); break; case 1: bn = RSA_get0_dmq1(r); break; default: { size_t pnum = RSA_get_multi_prime_extra_count(r); const BIGNUM *exps[10], *coeffs[10]; if (exponentnum - 2 < pnum && RSA_get0_multi_prime_crt_params(r, exps, coeffs)) bn = exps[exponentnum - 2]; } break; } return get_payload_bn(state, translation, ctx, bn); } static int get_rsa_payload_coefficient(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, size_t coefficientnum) { const RSA *r = EVP_PKEY_get0_RSA(ctx->p2); const BIGNUM *bn = NULL; switch (coefficientnum) { case 0: bn = RSA_get0_iqmp(r); break; default: { size_t pnum = RSA_get_multi_prime_extra_count(r); const BIGNUM *exps[10], *coeffs[10]; if (coefficientnum - 1 < pnum && RSA_get0_multi_prime_crt_params(r, exps, coeffs)) bn = coeffs[coefficientnum - 1]; } break; } return get_payload_bn(state, translation, ctx, bn); } #define IMPL_GET_RSA_PAYLOAD_FACTOR(n) \ static int \ get_rsa_payload_f##n(enum state state, \ const struct translation_st *translation, \ struct translation_ctx_st *ctx) \ { \ if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA \ && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) \ return 0; \ return get_rsa_payload_factor(state, translation, ctx, n - 1); \ } #define IMPL_GET_RSA_PAYLOAD_EXPONENT(n) \ static int \ get_rsa_payload_e##n(enum state state, \ const struct translation_st *translation, \ struct translation_ctx_st *ctx) \ { \ if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA \ && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) \ return 0; \ return get_rsa_payload_exponent(state, translation, ctx, \ n - 1); \ } #define IMPL_GET_RSA_PAYLOAD_COEFFICIENT(n) \ static int \ get_rsa_payload_c##n(enum state state, \ const struct translation_st *translation, \ struct translation_ctx_st *ctx) \ { \ if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA \ && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) \ return 0; \ return get_rsa_payload_coefficient(state, translation, ctx, \ n - 1); \ } IMPL_GET_RSA_PAYLOAD_FACTOR(1) IMPL_GET_RSA_PAYLOAD_FACTOR(2) IMPL_GET_RSA_PAYLOAD_FACTOR(3) IMPL_GET_RSA_PAYLOAD_FACTOR(4) IMPL_GET_RSA_PAYLOAD_FACTOR(5) IMPL_GET_RSA_PAYLOAD_FACTOR(6) IMPL_GET_RSA_PAYLOAD_FACTOR(7) IMPL_GET_RSA_PAYLOAD_FACTOR(8) IMPL_GET_RSA_PAYLOAD_FACTOR(9) IMPL_GET_RSA_PAYLOAD_FACTOR(10) IMPL_GET_RSA_PAYLOAD_EXPONENT(1) IMPL_GET_RSA_PAYLOAD_EXPONENT(2) IMPL_GET_RSA_PAYLOAD_EXPONENT(3) IMPL_GET_RSA_PAYLOAD_EXPONENT(4) IMPL_GET_RSA_PAYLOAD_EXPONENT(5) IMPL_GET_RSA_PAYLOAD_EXPONENT(6) IMPL_GET_RSA_PAYLOAD_EXPONENT(7) IMPL_GET_RSA_PAYLOAD_EXPONENT(8) IMPL_GET_RSA_PAYLOAD_EXPONENT(9) IMPL_GET_RSA_PAYLOAD_EXPONENT(10) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(1) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(2) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(3) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(4) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(5) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(6) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(7) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(8) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(9) static int fix_group_ecx(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const char *value = NULL; switch (state) { case PRE_PARAMS_TO_CTRL: if (!EVP_PKEY_CTX_IS_GEN_OP(ctx->pctx)) return 0; ctx->action_type = NONE; return 1; case POST_PARAMS_TO_CTRL: if (OSSL_PARAM_get_utf8_string_ptr(ctx->params, &value) == 0 || OPENSSL_strcasecmp(ctx->pctx->keytype, value) != 0) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_INVALID_ARGUMENT); ctx->p1 = 0; return 0; } ctx->p1 = 1; return 1; default: return 0; } } /*- * The translation table itself * ============================ */ static const struct translation_st evp_pkey_ctx_translations[] = { /* * DistID: we pass it to the backend as an octet string, * but get it back as a pointer to an octet string. * * Note that the EVP_PKEY_CTRL_GET1_ID_LEN is purely for legacy purposes * that has no separate counterpart in OSSL_PARAM terms, since we get * the length of the DistID automatically when getting the DistID itself. */ { SET, -1, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_SET1_ID, "distid", "hexdistid", OSSL_PKEY_PARAM_DIST_ID, OSSL_PARAM_OCTET_STRING, NULL }, { GET, -1, -1, -1, EVP_PKEY_CTRL_GET1_ID, "distid", "hexdistid", OSSL_PKEY_PARAM_DIST_ID, OSSL_PARAM_OCTET_PTR, NULL }, { GET, -1, -1, -1, EVP_PKEY_CTRL_GET1_ID_LEN, NULL, NULL, OSSL_PKEY_PARAM_DIST_ID, OSSL_PARAM_OCTET_PTR, fix_distid_len }, /*- * DH & DHX * ======== */ /* * EVP_PKEY_CTRL_DH_KDF_TYPE is used both for setting and getting. The * fixup function has to handle this... */ { NONE, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_TYPE, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_TYPE, OSSL_PARAM_UTF8_STRING, fix_dh_kdf_type }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_MD, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_DH_KDF_MD, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_STRING, NULL }, { GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_DH_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_PTR, NULL }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_OID, NULL, NULL, OSSL_KDF_PARAM_CEK_ALG, OSSL_PARAM_UTF8_STRING, fix_oid }, { GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_DH_KDF_OID, NULL, NULL, OSSL_KDF_PARAM_CEK_ALG, OSSL_PARAM_UTF8_STRING, fix_oid }, /* DHX Keygen Parameters that are shared with DH */ { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_TYPE, "dh_paramgen_type", NULL, OSSL_PKEY_PARAM_FFC_TYPE, OSSL_PARAM_UTF8_STRING, fix_dh_paramgen_type }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, "dh_paramgen_prime_len", NULL, OSSL_PKEY_PARAM_FFC_PBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_DH_NID, "dh_param", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, NULL }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_DH_RFC5114, "dh_rfc5114", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_dh_nid5114 }, /* DH Keygen Parameters that are shared with DHX */ { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_TYPE, "dh_paramgen_type", NULL, OSSL_PKEY_PARAM_FFC_TYPE, OSSL_PARAM_UTF8_STRING, fix_dh_paramgen_type }, { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, "dh_paramgen_prime_len", NULL, OSSL_PKEY_PARAM_FFC_PBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_DH_NID, "dh_param", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_dh_nid }, { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_DH_RFC5114, "dh_rfc5114", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_dh_nid5114 }, /* DH specific Keygen Parameters */ { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR, "dh_paramgen_generator", NULL, OSSL_PKEY_PARAM_DH_GENERATOR, OSSL_PARAM_INTEGER, NULL }, /* DHX specific Keygen Parameters */ { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN, "dh_paramgen_subprime_len", NULL, OSSL_PKEY_PARAM_FFC_QBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_PAD, "dh_pad", NULL, OSSL_EXCHANGE_PARAM_PAD, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, /*- * DSA * === */ { SET, EVP_PKEY_DSA, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DSA_PARAMGEN_BITS, "dsa_paramgen_bits", NULL, OSSL_PKEY_PARAM_FFC_PBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DSA, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS, "dsa_paramgen_q_bits", NULL, OSSL_PKEY_PARAM_FFC_QBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DSA, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DSA_PARAMGEN_MD, "dsa_paramgen_md", NULL, OSSL_PKEY_PARAM_FFC_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, /*- * EC * == */ { SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_EC_PARAM_ENC, "ec_param_enc", NULL, OSSL_PKEY_PARAM_EC_ENCODING, OSSL_PARAM_UTF8_STRING, fix_ec_param_enc }, { SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, "ec_paramgen_curve", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_ec_paramgen_curve_nid }, /* * EVP_PKEY_CTRL_EC_ECDH_COFACTOR and EVP_PKEY_CTRL_EC_KDF_TYPE are used * both for setting and getting. The fixup function has to handle this... */ { NONE, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_ECDH_COFACTOR, "ecdh_cofactor_mode", NULL, OSSL_EXCHANGE_PARAM_EC_ECDH_COFACTOR_MODE, OSSL_PARAM_INTEGER, fix_ecdh_cofactor }, { NONE, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_TYPE, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_TYPE, OSSL_PARAM_UTF8_STRING, fix_ec_kdf_type }, { SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_MD, "ecdh_kdf_md", NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_MD, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { GET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_STRING, NULL }, { GET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_PTR, NULL }, /*- * SM2 * == */ { SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_EC_PARAM_ENC, "ec_param_enc", NULL, OSSL_PKEY_PARAM_EC_ENCODING, OSSL_PARAM_UTF8_STRING, fix_ec_param_enc }, { SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, "ec_paramgen_curve", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_ec_paramgen_curve_nid }, /* * EVP_PKEY_CTRL_EC_ECDH_COFACTOR and EVP_PKEY_CTRL_EC_KDF_TYPE are used * both for setting and getting. The fixup function has to handle this... */ { NONE, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_ECDH_COFACTOR, "ecdh_cofactor_mode", NULL, OSSL_EXCHANGE_PARAM_EC_ECDH_COFACTOR_MODE, OSSL_PARAM_INTEGER, fix_ecdh_cofactor }, { NONE, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_TYPE, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_TYPE, OSSL_PARAM_UTF8_STRING, fix_ec_kdf_type }, { SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_MD, "ecdh_kdf_md", NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_MD, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { GET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_STRING, NULL }, { GET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_PTR, NULL }, /*- * RSA * === */ /* * RSA padding modes are numeric with ctrls, strings with ctrl_strs, * and can be both with OSSL_PARAM. We standardise on strings here, * fix_rsa_padding_mode() does the work when the caller has a different * idea. */ { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_RSA_PADDING, "rsa_padding_mode", NULL, OSSL_PKEY_PARAM_PAD_MODE, OSSL_PARAM_UTF8_STRING, fix_rsa_padding_mode }, { GET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_GET_RSA_PADDING, NULL, NULL, OSSL_PKEY_PARAM_PAD_MODE, OSSL_PARAM_UTF8_STRING, fix_rsa_padding_mode }, { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_RSA_MGF1_MD, "rsa_mgf1_md", NULL, OSSL_PKEY_PARAM_MGF1_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_GET_RSA_MGF1_MD, NULL, NULL, OSSL_PKEY_PARAM_MGF1_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, /* * RSA-PSS saltlen is essentially numeric, but certain values can be * expressed as keywords (strings) with ctrl_str. The corresponding * OSSL_PARAM allows both forms. * fix_rsa_pss_saltlen() takes care of the distinction. */ { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_RSA_PSS_SALTLEN, "rsa_pss_saltlen", NULL, OSSL_PKEY_PARAM_RSA_PSS_SALTLEN, OSSL_PARAM_UTF8_STRING, fix_rsa_pss_saltlen }, { GET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN, NULL, NULL, OSSL_PKEY_PARAM_RSA_PSS_SALTLEN, OSSL_PARAM_UTF8_STRING, fix_rsa_pss_saltlen }, { SET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_OAEP_MD, "rsa_oaep_md", NULL, OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_GET_RSA_OAEP_MD, NULL, NULL, OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, /* * The "rsa_oaep_label" ctrl_str expects the value to always be hex. * This is accommodated by default_fixup_args() above, which mimics that * expectation for any translation item where |ctrl_str| is NULL and * |ctrl_hexstr| is non-NULL. */ { SET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_OAEP_LABEL, NULL, "rsa_oaep_label", OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, OSSL_PARAM_OCTET_STRING, NULL }, { GET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL, NULL, NULL, OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, OSSL_PARAM_OCTET_PTR, NULL }, { SET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_IMPLICIT_REJECTION, NULL, "rsa_pkcs1_implicit_rejection", OSSL_ASYM_CIPHER_PARAM_IMPLICIT_REJECTION, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_RSA_PSS, 0, EVP_PKEY_OP_TYPE_GEN, EVP_PKEY_CTRL_MD, "rsa_pss_keygen_md", NULL, OSSL_ALG_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, EVP_PKEY_RSA_PSS, 0, EVP_PKEY_OP_TYPE_GEN, EVP_PKEY_CTRL_RSA_MGF1_MD, "rsa_pss_keygen_mgf1_md", NULL, OSSL_PKEY_PARAM_MGF1_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, EVP_PKEY_RSA_PSS, 0, EVP_PKEY_OP_TYPE_GEN, EVP_PKEY_CTRL_RSA_PSS_SALTLEN, "rsa_pss_keygen_saltlen", NULL, OSSL_SIGNATURE_PARAM_PSS_SALTLEN, OSSL_PARAM_INTEGER, NULL }, { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_KEYGEN_BITS, "rsa_keygen_bits", NULL, OSSL_PKEY_PARAM_RSA_BITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, "rsa_keygen_pubexp", NULL, OSSL_PKEY_PARAM_RSA_E, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_KEYGEN_PRIMES, "rsa_keygen_primes", NULL, OSSL_PKEY_PARAM_RSA_PRIMES, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, /*- * SipHash * ====== */ { SET, -1, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_SET_DIGEST_SIZE, "digestsize", NULL, OSSL_MAC_PARAM_SIZE, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, /*- * TLS1-PRF * ======== */ { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_MD, "md", NULL, OSSL_KDF_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_SECRET, "secret", "hexsecret", OSSL_KDF_PARAM_SECRET, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_SEED, "seed", "hexseed", OSSL_KDF_PARAM_SEED, OSSL_PARAM_OCTET_STRING, NULL }, /*- * HKDF * ==== */ { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_MD, "md", NULL, OSSL_KDF_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_SALT, "salt", "hexsalt", OSSL_KDF_PARAM_SALT, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_KEY, "key", "hexkey", OSSL_KDF_PARAM_KEY, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_INFO, "info", "hexinfo", OSSL_KDF_PARAM_INFO, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_MODE, "mode", NULL, OSSL_KDF_PARAM_MODE, OSSL_PARAM_INTEGER, fix_hkdf_mode }, /*- * Scrypt * ====== */ { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_PASS, "pass", "hexpass", OSSL_KDF_PARAM_PASSWORD, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_SALT, "salt", "hexsalt", OSSL_KDF_PARAM_SALT, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_N, "N", NULL, OSSL_KDF_PARAM_SCRYPT_N, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_R, "r", NULL, OSSL_KDF_PARAM_SCRYPT_R, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_P, "p", NULL, OSSL_KDF_PARAM_SCRYPT_P, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES, "maxmem_bytes", NULL, OSSL_KDF_PARAM_SCRYPT_MAXMEM, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, -1, -1, EVP_PKEY_OP_KEYGEN | EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_CIPHER, NULL, NULL, OSSL_PKEY_PARAM_CIPHER, OSSL_PARAM_UTF8_STRING, fix_cipher }, { SET, -1, -1, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_SET_MAC_KEY, "key", "hexkey", OSSL_PKEY_PARAM_PRIV_KEY, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_MD, NULL, NULL, OSSL_SIGNATURE_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, -1, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_GET_MD, NULL, NULL, OSSL_SIGNATURE_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, /*- * ECX * === */ { SET, EVP_PKEY_X25519, EVP_PKEY_X25519, EVP_PKEY_OP_KEYGEN, -1, NULL, NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx }, { SET, EVP_PKEY_X25519, EVP_PKEY_X25519, EVP_PKEY_OP_PARAMGEN, -1, NULL, NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx }, { SET, EVP_PKEY_X448, EVP_PKEY_X448, EVP_PKEY_OP_KEYGEN, -1, NULL, NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx }, { SET, EVP_PKEY_X448, EVP_PKEY_X448, EVP_PKEY_OP_PARAMGEN, -1, NULL, NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx }, }; static const struct translation_st evp_pkey_translations[] = { /* * The following contain no ctrls, they are exclusively here to extract * key payloads from legacy keys, using OSSL_PARAMs, and rely entirely * on |fixup_args| to pass the actual data. The |fixup_args| should * expect to get the EVP_PKEY pointer through |ctx->p2|. */ /* DH, DSA & EC */ { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, get_payload_group_name }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_PRIV_KEY, OSSL_PARAM_UNSIGNED_INTEGER, get_payload_private_key }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_PUB_KEY, 0 /* no data type, let get_payload_public_key() handle that */, get_payload_public_key }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_EC_PUB_X, OSSL_PARAM_UNSIGNED_INTEGER, get_payload_public_key_ec }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_EC_PUB_Y, OSSL_PARAM_UNSIGNED_INTEGER, get_payload_public_key_ec }, /* DH and DSA */ { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_FFC_P, OSSL_PARAM_UNSIGNED_INTEGER, get_dh_dsa_payload_p }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_FFC_G, OSSL_PARAM_UNSIGNED_INTEGER, get_dh_dsa_payload_g }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_FFC_Q, OSSL_PARAM_UNSIGNED_INTEGER, get_dh_dsa_payload_q }, /* RSA */ { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_N, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_n }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_E, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_D, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_d }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR1, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f1 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR2, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f2 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR3, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f3 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR4, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f4 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR5, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f5 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR6, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f6 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR7, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f7 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR8, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f8 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR9, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f9 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR10, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f10 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT1, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e1 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT2, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e2 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT3, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e3 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT4, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e4 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT5, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e5 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT6, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e6 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT7, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e7 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT8, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e8 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT9, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e9 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT10, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e10 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT1, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c1 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT2, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c2 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT3, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c3 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT4, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c4 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT5, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c5 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT6, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c6 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT7, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c7 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT8, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c8 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT9, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c9 }, /* EC */ { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS, OSSL_PARAM_INTEGER, get_ec_decoded_from_explicit_params }, }; static const struct translation_st * lookup_translation(struct translation_st *tmpl, const struct translation_st *translations, size_t translations_num) { size_t i; for (i = 0; i < translations_num; i++) { const struct translation_st *item = &translations[i]; /* * Sanity check the translation table item. * * 1. Either both keytypes are -1, or neither of them are. * 2. TBA... */ if (!ossl_assert((item->keytype1 == -1) == (item->keytype2 == -1))) continue; /* * Base search criteria: check that the optype and keytypes match, * if relevant. All callers must synthesise these bits somehow. */ if (item->optype != -1 && (tmpl->optype & item->optype) == 0) continue; /* * This expression is stunningly simple thanks to the sanity check * above. */ if (item->keytype1 != -1 && tmpl->keytype1 != item->keytype1 && tmpl->keytype2 != item->keytype2) continue; /* * Done with the base search criteria, now we check the criteria for * the individual types of translations: * ctrl->params, ctrl_str->params, and params->ctrl */ if (tmpl->ctrl_num != 0) { if (tmpl->ctrl_num != item->ctrl_num) continue; } else if (tmpl->ctrl_str != NULL) { const char *ctrl_str = NULL; const char *ctrl_hexstr = NULL; /* * Search criteria that originates from a ctrl_str is only used * for setting, never for getting. Therefore, we only look at * the setter items. */ if (item->action_type != NONE && item->action_type != SET) continue; /* * At least one of the ctrl cmd names must be match the ctrl * cmd name in the template. */ if (item->ctrl_str != NULL && OPENSSL_strcasecmp(tmpl->ctrl_str, item->ctrl_str) == 0) ctrl_str = tmpl->ctrl_str; else if (item->ctrl_hexstr != NULL && OPENSSL_strcasecmp(tmpl->ctrl_hexstr, item->ctrl_hexstr) == 0) ctrl_hexstr = tmpl->ctrl_hexstr; else continue; /* Modify the template to signal which string matched */ tmpl->ctrl_str = ctrl_str; tmpl->ctrl_hexstr = ctrl_hexstr; } else if (tmpl->param_key != NULL) { /* * Search criteria that originates from an OSSL_PARAM setter or * getter. * * Ctrls were fundamentally bidirectional, with only the ctrl * command macro name implying direction (if you're lucky). * A few ctrl commands were even taking advantage of the * bidirectional nature, making the direction depend in the * value of the numeric argument. * * OSSL_PARAM functions are fundamentally different, in that * setters and getters are separated, so the data direction is * implied by the function that's used. The same OSSL_PARAM * key name can therefore be used in both directions. We must * therefore take the action type into account in this case. */ if ((item->action_type != NONE && tmpl->action_type != item->action_type) || (item->param_key != NULL && OPENSSL_strcasecmp(tmpl->param_key, item->param_key) != 0)) continue; } else { return NULL; } return item; } return NULL; } static const struct translation_st * lookup_evp_pkey_ctx_translation(struct translation_st *tmpl) { return lookup_translation(tmpl, evp_pkey_ctx_translations, OSSL_NELEM(evp_pkey_ctx_translations)); } static const struct translation_st * lookup_evp_pkey_translation(struct translation_st *tmpl) { return lookup_translation(tmpl, evp_pkey_translations, OSSL_NELEM(evp_pkey_translations)); } /* This must ONLY be called for provider side operations */ int evp_pkey_ctx_ctrl_to_param(EVP_PKEY_CTX *pctx, int keytype, int optype, int cmd, int p1, void *p2) { struct translation_ctx_st ctx = { 0, }; struct translation_st tmpl = { 0, }; const struct translation_st *translation = NULL; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; int ret; fixup_args_fn *fixup = default_fixup_args; if (keytype == -1) keytype = pctx->legacy_keytype; tmpl.ctrl_num = cmd; tmpl.keytype1 = tmpl.keytype2 = keytype; tmpl.optype = optype; translation = lookup_evp_pkey_ctx_translation(&tmpl); if (translation == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (pctx->pmeth != NULL && pctx->pmeth->pkey_id != translation->keytype1 && pctx->pmeth->pkey_id != translation->keytype2) return -1; if (translation->fixup_args != NULL) fixup = translation->fixup_args; ctx.action_type = translation->action_type; ctx.ctrl_cmd = cmd; ctx.p1 = p1; ctx.p2 = p2; ctx.pctx = pctx; ctx.params = params; ret = fixup(PRE_CTRL_TO_PARAMS, translation, &ctx); if (ret > 0) { switch (ctx.action_type) { default: /* fixup_args is expected to make sure this is dead code */ break; case GET: ret = evp_pkey_ctx_get_params_strict(pctx, ctx.params); break; case SET: ret = evp_pkey_ctx_set_params_strict(pctx, ctx.params); break; } } /* * In POST, we pass the return value as p1, allowing the fixup_args * function to affect it by changing its value. */ if (ret > 0) { ctx.p1 = ret; fixup(POST_CTRL_TO_PARAMS, translation, &ctx); ret = ctx.p1; } cleanup_translation_ctx(POST_CTRL_TO_PARAMS, translation, &ctx); return ret; } /* This must ONLY be called for provider side operations */ int evp_pkey_ctx_ctrl_str_to_param(EVP_PKEY_CTX *pctx, const char *name, const char *value) { struct translation_ctx_st ctx = { 0, }; struct translation_st tmpl = { 0, }; const struct translation_st *translation = NULL; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; int keytype = pctx->legacy_keytype; int optype = pctx->operation == 0 ? -1 : pctx->operation; int ret; fixup_args_fn *fixup = default_fixup_args; tmpl.action_type = SET; tmpl.keytype1 = tmpl.keytype2 = keytype; tmpl.optype = optype; tmpl.ctrl_str = name; tmpl.ctrl_hexstr = name; translation = lookup_evp_pkey_ctx_translation(&tmpl); if (translation != NULL) { if (translation->fixup_args != NULL) fixup = translation->fixup_args; ctx.action_type = translation->action_type; ctx.ishex = (tmpl.ctrl_hexstr != NULL); } else { /* String controls really only support setting */ ctx.action_type = SET; } ctx.ctrl_str = name; ctx.p1 = (int)strlen(value); ctx.p2 = (char *)value; ctx.pctx = pctx; ctx.params = params; ret = fixup(PRE_CTRL_STR_TO_PARAMS, translation, &ctx); if (ret > 0) { switch (ctx.action_type) { default: /* fixup_args is expected to make sure this is dead code */ break; case GET: /* * this is dead code, but must be present, or some compilers * will complain */ break; case SET: ret = evp_pkey_ctx_set_params_strict(pctx, ctx.params); break; } } if (ret > 0) ret = fixup(POST_CTRL_STR_TO_PARAMS, translation, &ctx); cleanup_translation_ctx(CLEANUP_CTRL_STR_TO_PARAMS, translation, &ctx); return ret; } /* This must ONLY be called for legacy operations */ static int evp_pkey_ctx_setget_params_to_ctrl(EVP_PKEY_CTX *pctx, enum action action_type, OSSL_PARAM *params) { int keytype = pctx->legacy_keytype; int optype = pctx->operation == 0 ? -1 : pctx->operation; for (; params != NULL && params->key != NULL; params++) { struct translation_ctx_st ctx = { 0, }; struct translation_st tmpl = { 0, }; const struct translation_st *translation = NULL; fixup_args_fn *fixup = default_fixup_args; int ret; tmpl.action_type = action_type; tmpl.keytype1 = tmpl.keytype2 = keytype; tmpl.optype = optype; tmpl.param_key = params->key; translation = lookup_evp_pkey_ctx_translation(&tmpl); if (translation != NULL) { if (translation->fixup_args != NULL) fixup = translation->fixup_args; ctx.action_type = translation->action_type; ctx.ctrl_cmd = translation->ctrl_num; } ctx.pctx = pctx; ctx.params = params; ret = fixup(PRE_PARAMS_TO_CTRL, translation, &ctx); if (ret > 0 && ctx.action_type != NONE) ret = EVP_PKEY_CTX_ctrl(pctx, keytype, optype, ctx.ctrl_cmd, ctx.p1, ctx.p2); /* * In POST, we pass the return value as p1, allowing the fixup_args * function to put it to good use, or maybe affect it. */ if (ret > 0) { ctx.p1 = ret; fixup(POST_PARAMS_TO_CTRL, translation, &ctx); ret = ctx.p1; } cleanup_translation_ctx(CLEANUP_PARAMS_TO_CTRL, translation, &ctx); if (ret <= 0) return 0; } return 1; } int evp_pkey_ctx_set_params_to_ctrl(EVP_PKEY_CTX *ctx, const OSSL_PARAM *params) { return evp_pkey_ctx_setget_params_to_ctrl(ctx, SET, (OSSL_PARAM *)params); } int evp_pkey_ctx_get_params_to_ctrl(EVP_PKEY_CTX *ctx, OSSL_PARAM *params) { return evp_pkey_ctx_setget_params_to_ctrl(ctx, GET, params); } /* This must ONLY be called for legacy EVP_PKEYs */ static int evp_pkey_setget_params_to_ctrl(const EVP_PKEY *pkey, enum action action_type, OSSL_PARAM *params) { int ret = 1; for (; params != NULL && params->key != NULL; params++) { struct translation_ctx_st ctx = { 0, }; struct translation_st tmpl = { 0, }; const struct translation_st *translation = NULL; fixup_args_fn *fixup = default_fixup_args; tmpl.action_type = action_type; tmpl.param_key = params->key; translation = lookup_evp_pkey_translation(&tmpl); if (translation != NULL) { if (translation->fixup_args != NULL) fixup = translation->fixup_args; ctx.action_type = translation->action_type; } ctx.p2 = (void *)pkey; ctx.params = params; /* * EVP_PKEY doesn't have any ctrl function, so we rely completely * on fixup_args to do the whole work. Also, we currently only * support getting. */ if (!ossl_assert(translation != NULL) || !ossl_assert(translation->action_type == GET) || !ossl_assert(translation->fixup_args != NULL)) { return -2; } ret = fixup(PKEY, translation, &ctx); cleanup_translation_ctx(PKEY, translation, &ctx); } return ret; } int evp_pkey_get_params_to_ctrl(const EVP_PKEY *pkey, OSSL_PARAM *params) { return evp_pkey_setget_params_to_ctrl(pkey, GET, params); }
./openssl/crypto/evp/legacy_sha.c
/* * Copyright 2019-2021 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 */ /* * All SHA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/sha.h> /* diverse SHA macros */ #include "internal/sha3.h" /* KECCAK1600_WIDTH */ #include "crypto/evp.h" /* Used by legacy methods */ #include "crypto/sha.h" #include "legacy_meth.h" #include "evp_local.h" /*- * LEGACY methods for SHA. * These only remain to support engines that can get these methods. * Hardware support for SHA3 has been removed from these legacy cases. */ #define IMPLEMENT_LEGACY_EVP_MD_METH_SHA3(nm, fn, tag) \ static int nm##_init(EVP_MD_CTX *ctx) \ { \ return fn##_init(EVP_MD_CTX_get0_md_data(ctx), tag, ctx->digest->md_size * 8); \ } \ static int nm##_update(EVP_MD_CTX *ctx, const void *data, size_t count) \ { \ return fn##_update(EVP_MD_CTX_get0_md_data(ctx), data, count); \ } \ static int nm##_final(EVP_MD_CTX *ctx, unsigned char *md) \ { \ KECCAK1600_CTX *kctx = EVP_MD_CTX_get0_md_data(ctx); \ return fn##_final(kctx, md, kctx->md_size); \ } #define IMPLEMENT_LEGACY_EVP_MD_METH_SHAKE(nm, fn, tag) \ static int nm##_init(EVP_MD_CTX *ctx) \ { \ return fn##_init(EVP_MD_CTX_get0_md_data(ctx), tag, ctx->digest->md_size * 8); \ } \ #define sha512_224_Init sha512_224_init #define sha512_256_Init sha512_256_init #define sha512_224_Update SHA512_Update #define sha512_224_Final SHA512_Final #define sha512_256_Update SHA512_Update #define sha512_256_Final SHA512_Final IMPLEMENT_LEGACY_EVP_MD_METH(sha1, SHA1) IMPLEMENT_LEGACY_EVP_MD_METH(sha224, SHA224) IMPLEMENT_LEGACY_EVP_MD_METH(sha256, SHA256) IMPLEMENT_LEGACY_EVP_MD_METH(sha384, SHA384) IMPLEMENT_LEGACY_EVP_MD_METH(sha512, SHA512) IMPLEMENT_LEGACY_EVP_MD_METH(sha512_224_int, sha512_224) IMPLEMENT_LEGACY_EVP_MD_METH(sha512_256_int, sha512_256) IMPLEMENT_LEGACY_EVP_MD_METH_SHA3(sha3_int, ossl_sha3, '\x06') IMPLEMENT_LEGACY_EVP_MD_METH_SHAKE(shake, ossl_sha3, '\x1f') static int sha1_int_ctrl(EVP_MD_CTX *ctx, int cmd, int p1, void *p2) { return ossl_sha1_ctrl(ctx != NULL ? EVP_MD_CTX_get0_md_data(ctx) : NULL, cmd, p1, p2); } static int shake_ctrl(EVP_MD_CTX *evp_ctx, int cmd, int p1, void *p2) { KECCAK1600_CTX *ctx; if (evp_ctx == NULL) return 0; ctx = evp_ctx->md_data; switch (cmd) { case EVP_MD_CTRL_XOF_LEN: ctx->md_size = p1; return 1; default: return 0; } } static const EVP_MD sha1_md = { NID_sha1, NID_sha1WithRSAEncryption, SHA_DIGEST_LENGTH, EVP_MD_FLAG_DIGALGID_ABSENT, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(sha1_init, sha1_update, sha1_final, sha1_int_ctrl, SHA_CBLOCK), }; const EVP_MD *EVP_sha1(void) { return &sha1_md; } static const EVP_MD sha224_md = { NID_sha224, NID_sha224WithRSAEncryption, SHA224_DIGEST_LENGTH, EVP_MD_FLAG_DIGALGID_ABSENT, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(sha224_init, sha224_update, sha224_final, NULL, SHA256_CBLOCK), }; const EVP_MD *EVP_sha224(void) { return &sha224_md; } static const EVP_MD sha256_md = { NID_sha256, NID_sha256WithRSAEncryption, SHA256_DIGEST_LENGTH, EVP_MD_FLAG_DIGALGID_ABSENT, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(sha256_init, sha256_update, sha256_final, NULL, SHA256_CBLOCK), }; const EVP_MD *EVP_sha256(void) { return &sha256_md; } static const EVP_MD sha512_224_md = { NID_sha512_224, NID_sha512_224WithRSAEncryption, SHA224_DIGEST_LENGTH, EVP_MD_FLAG_DIGALGID_ABSENT, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(sha512_224_int_init, sha512_224_int_update, sha512_224_int_final, NULL, SHA512_CBLOCK), }; const EVP_MD *EVP_sha512_224(void) { return &sha512_224_md; } static const EVP_MD sha512_256_md = { NID_sha512_256, NID_sha512_256WithRSAEncryption, SHA256_DIGEST_LENGTH, EVP_MD_FLAG_DIGALGID_ABSENT, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(sha512_256_int_init, sha512_256_int_update, sha512_256_int_final, NULL, SHA512_CBLOCK), }; const EVP_MD *EVP_sha512_256(void) { return &sha512_256_md; } static const EVP_MD sha384_md = { NID_sha384, NID_sha384WithRSAEncryption, SHA384_DIGEST_LENGTH, EVP_MD_FLAG_DIGALGID_ABSENT, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(sha384_init, sha384_update, sha384_final, NULL, SHA512_CBLOCK), }; const EVP_MD *EVP_sha384(void) { return &sha384_md; } static const EVP_MD sha512_md = { NID_sha512, NID_sha512WithRSAEncryption, SHA512_DIGEST_LENGTH, EVP_MD_FLAG_DIGALGID_ABSENT, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(sha512_init, sha512_update, sha512_final, NULL, SHA512_CBLOCK), }; const EVP_MD *EVP_sha512(void) { return &sha512_md; } #define EVP_MD_SHA3(bitlen) \ const EVP_MD *EVP_sha3_##bitlen(void) \ { \ static const EVP_MD sha3_##bitlen##_md = { \ NID_sha3_##bitlen, \ NID_RSA_SHA3_##bitlen, \ bitlen / 8, \ EVP_MD_FLAG_DIGALGID_ABSENT, \ EVP_ORIG_GLOBAL, \ LEGACY_EVP_MD_METH_TABLE(sha3_int_init, sha3_int_update, \ sha3_int_final, NULL, \ (KECCAK1600_WIDTH - bitlen * 2) / 8), \ }; \ return &sha3_##bitlen##_md; \ } #define EVP_MD_SHAKE(bitlen) \ const EVP_MD *EVP_shake##bitlen(void) \ { \ static const EVP_MD shake##bitlen##_md = { \ NID_shake##bitlen, \ 0, \ bitlen / 8, \ EVP_MD_FLAG_XOF, \ EVP_ORIG_GLOBAL, \ LEGACY_EVP_MD_METH_TABLE(shake_init, sha3_int_update, sha3_int_final, \ shake_ctrl, (KECCAK1600_WIDTH - bitlen * 2) / 8), \ }; \ return &shake##bitlen##_md; \ } EVP_MD_SHA3(224) EVP_MD_SHA3(256) EVP_MD_SHA3(384) EVP_MD_SHA3(512) EVP_MD_SHAKE(128) EVP_MD_SHAKE(256)
./openssl/crypto/evp/legacy_blake2.c
/* * Copyright 2019-2023 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 "crypto/evp.h" #include "prov/blake2.h" /* diverse BLAKE2 macros */ #include "legacy_meth.h" /* * Local hack to adapt the BLAKE2 init functions to what the * legacy function signatures demand. */ static int blake2s_init(BLAKE2S_CTX *C) { BLAKE2S_PARAM P; ossl_blake2s_param_init(&P); return ossl_blake2s_init(C, &P); } static int blake2b_init(BLAKE2B_CTX *C) { BLAKE2B_PARAM P; ossl_blake2b_param_init(&P); return ossl_blake2b_init(C, &P); } #define blake2s_update ossl_blake2s_update #define blake2b_update ossl_blake2b_update #define blake2s_final ossl_blake2s_final #define blake2b_final ossl_blake2b_final IMPLEMENT_LEGACY_EVP_MD_METH_LC(blake2s_int, blake2s) IMPLEMENT_LEGACY_EVP_MD_METH_LC(blake2b_int, blake2b) static const EVP_MD blake2b_md = { NID_blake2b512, 0, BLAKE2B_DIGEST_LENGTH, 0, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(blake2b_int_init, blake2b_int_update, blake2b_int_final, NULL, BLAKE2B_BLOCKBYTES), }; const EVP_MD *EVP_blake2b512(void) { return &blake2b_md; } static const EVP_MD blake2s_md = { NID_blake2s256, 0, BLAKE2S_DIGEST_LENGTH, 0, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(blake2s_int_init, blake2s_int_update, blake2s_int_final, NULL, BLAKE2S_BLOCKBYTES), }; const EVP_MD *EVP_blake2s256(void) { return &blake2s_md; }
./openssl/crypto/evp/p5_crpt.c
/* * Copyright 1999-2021 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 <stdio.h> #include <stdlib.h> #include "internal/cryptlib.h" #include <openssl/x509.h> #include <openssl/evp.h> #include <openssl/core_names.h> #include <openssl/kdf.h> /* * Doesn't do anything now: Builtin PBE algorithms in static table. */ void PKCS5_PBE_add(void) { } int PKCS5_PBE_keyivgen_ex(EVP_CIPHER_CTX *cctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md, int en_de, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char md_tmp[EVP_MAX_MD_SIZE]; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; int ivl, kl; PBEPARAM *pbe = NULL; int saltlen, iter; unsigned char *salt; int mdsize; int rv = 0; EVP_KDF *kdf; EVP_KDF_CTX *kctx = NULL; OSSL_PARAM params[5], *p = params; const char *mdname = EVP_MD_name(md); /* Extract useful info from parameter */ if (param == NULL || param->type != V_ASN1_SEQUENCE || param->value.sequence == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_DECODE_ERROR); return 0; } pbe = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(PBEPARAM), param); if (pbe == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_DECODE_ERROR); return 0; } ivl = EVP_CIPHER_get_iv_length(cipher); if (ivl < 0 || ivl > 16) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_IV_LENGTH); goto err; } kl = EVP_CIPHER_get_key_length(cipher); if (kl < 0 || kl > (int)sizeof(md_tmp)) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); goto err; } if (pbe->iter == NULL) iter = 1; else iter = ASN1_INTEGER_get(pbe->iter); salt = pbe->salt->data; saltlen = pbe->salt->length; if (pass == NULL) passlen = 0; else if (passlen == -1) passlen = strlen(pass); mdsize = EVP_MD_get_size(md); if (mdsize < 0) goto err; kdf = EVP_KDF_fetch(libctx, OSSL_KDF_NAME_PBKDF1, propq); kctx = EVP_KDF_CTX_new(kdf); EVP_KDF_free(kdf); if (kctx == NULL) goto err; *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, (char *)pass, (size_t)passlen); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, salt, saltlen); *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_ITER, &iter); *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, (char *)mdname, 0); *p = OSSL_PARAM_construct_end(); if (EVP_KDF_derive(kctx, md_tmp, mdsize, params) != 1) goto err; memcpy(key, md_tmp, kl); memcpy(iv, md_tmp + (16 - ivl), ivl); if (!EVP_CipherInit_ex(cctx, cipher, NULL, key, iv, en_de)) goto err; OPENSSL_cleanse(md_tmp, EVP_MAX_MD_SIZE); OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH); OPENSSL_cleanse(iv, EVP_MAX_IV_LENGTH); rv = 1; err: EVP_KDF_CTX_free(kctx); PBEPARAM_free(pbe); return rv; } int PKCS5_PBE_keyivgen(EVP_CIPHER_CTX *cctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md, int en_de) { return PKCS5_PBE_keyivgen_ex(cctx, pass, passlen, param, cipher, md, en_de, NULL, NULL); }
./openssl/crypto/evp/pmeth_lib.c
/* * Copyright 2006-2023 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 */ /* * Low level key APIs (DH etc) are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <stdlib.h> #ifndef FIPS_MODULE # include <openssl/engine.h> #endif #include <openssl/evp.h> #include <openssl/core_names.h> #include <openssl/dh.h> #include <openssl/rsa.h> #include <openssl/kdf.h> #include "internal/cryptlib.h" #ifndef FIPS_MODULE # include "crypto/asn1.h" #endif #include "crypto/evp.h" #include "crypto/dh.h" #include "crypto/ec.h" #include "internal/ffc.h" #include "internal/numbers.h" #include "internal/provider.h" #include "evp_local.h" #ifndef FIPS_MODULE static int evp_pkey_ctx_store_cached_data(EVP_PKEY_CTX *ctx, int keytype, int optype, int cmd, const char *name, const void *data, size_t data_len); static void evp_pkey_ctx_free_cached_data(EVP_PKEY_CTX *ctx, int cmd, const char *name); static void evp_pkey_ctx_free_all_cached_data(EVP_PKEY_CTX *ctx); typedef const EVP_PKEY_METHOD *(*pmeth_fn)(void); typedef int sk_cmp_fn_type(const char *const *a, const char *const *b); static STACK_OF(EVP_PKEY_METHOD) *app_pkey_methods = NULL; /* This array needs to be in order of NIDs */ static pmeth_fn standard_methods[] = { ossl_rsa_pkey_method, # ifndef OPENSSL_NO_DH ossl_dh_pkey_method, # endif # ifndef OPENSSL_NO_DSA ossl_dsa_pkey_method, # endif # ifndef OPENSSL_NO_EC ossl_ec_pkey_method, # endif ossl_rsa_pss_pkey_method, # ifndef OPENSSL_NO_DH ossl_dhx_pkey_method, # endif # ifndef OPENSSL_NO_ECX ossl_ecx25519_pkey_method, ossl_ecx448_pkey_method, ossl_ed25519_pkey_method, ossl_ed448_pkey_method, # endif }; DECLARE_OBJ_BSEARCH_CMP_FN(const EVP_PKEY_METHOD *, pmeth_fn, pmeth_func); static int pmeth_func_cmp(const EVP_PKEY_METHOD *const *a, pmeth_fn const *b) { return ((*a)->pkey_id - ((**b)())->pkey_id); } IMPLEMENT_OBJ_BSEARCH_CMP_FN(const EVP_PKEY_METHOD *, pmeth_fn, pmeth_func); static int pmeth_cmp(const EVP_PKEY_METHOD *const *a, const EVP_PKEY_METHOD *const *b) { return ((*a)->pkey_id - (*b)->pkey_id); } static const EVP_PKEY_METHOD *evp_pkey_meth_find_added_by_application(int type) { if (app_pkey_methods != NULL) { int idx; EVP_PKEY_METHOD tmp; tmp.pkey_id = type; idx = sk_EVP_PKEY_METHOD_find(app_pkey_methods, &tmp); if (idx >= 0) return sk_EVP_PKEY_METHOD_value(app_pkey_methods, idx); } return NULL; } const EVP_PKEY_METHOD *EVP_PKEY_meth_find(int type) { pmeth_fn *ret; EVP_PKEY_METHOD tmp; const EVP_PKEY_METHOD *t; if ((t = evp_pkey_meth_find_added_by_application(type)) != NULL) return t; tmp.pkey_id = type; t = &tmp; ret = OBJ_bsearch_pmeth_func(&t, standard_methods, OSSL_NELEM(standard_methods)); if (ret == NULL || *ret == NULL) return NULL; return (**ret)(); } EVP_PKEY_METHOD *EVP_PKEY_meth_new(int id, int flags) { EVP_PKEY_METHOD *pmeth; pmeth = OPENSSL_zalloc(sizeof(*pmeth)); if (pmeth == NULL) return NULL; pmeth->pkey_id = id; pmeth->flags = flags | EVP_PKEY_FLAG_DYNAMIC; return pmeth; } #endif /* FIPS_MODULE */ int evp_pkey_ctx_state(const EVP_PKEY_CTX *ctx) { if (ctx->operation == EVP_PKEY_OP_UNDEFINED) return EVP_PKEY_STATE_UNKNOWN; if ((EVP_PKEY_CTX_IS_DERIVE_OP(ctx) && ctx->op.kex.algctx != NULL) || (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx) && ctx->op.sig.algctx != NULL) || (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx) && ctx->op.ciph.algctx != NULL) || (EVP_PKEY_CTX_IS_GEN_OP(ctx) && ctx->op.keymgmt.genctx != NULL) || (EVP_PKEY_CTX_IS_KEM_OP(ctx) && ctx->op.encap.algctx != NULL)) return EVP_PKEY_STATE_PROVIDER; return EVP_PKEY_STATE_LEGACY; } static EVP_PKEY_CTX *int_ctx_new(OSSL_LIB_CTX *libctx, EVP_PKEY *pkey, ENGINE *e, const char *keytype, const char *propquery, int id) { EVP_PKEY_CTX *ret = NULL; const EVP_PKEY_METHOD *pmeth = NULL, *app_pmeth = NULL; EVP_KEYMGMT *keymgmt = NULL; /* Code below to be removed when legacy support is dropped. */ /* BEGIN legacy */ if (id == -1) { if (pkey != NULL && !evp_pkey_is_provided(pkey)) { id = pkey->type; } else { if (pkey != NULL) { /* Must be provided if we get here */ keytype = EVP_KEYMGMT_get0_name(pkey->keymgmt); } #ifndef FIPS_MODULE if (keytype != NULL) { id = evp_pkey_name2type(keytype); if (id == NID_undef) id = -1; } #endif } } /* If no ID was found here, we can only resort to find a keymgmt */ if (id == -1) { #ifndef FIPS_MODULE /* Using engine with a key without id will not work */ if (e != NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM); return NULL; } #endif goto common; } #ifndef FIPS_MODULE /* * Here, we extract what information we can for the purpose of * supporting usage with implementations from providers, to make * for a smooth transition from legacy stuff to provider based stuff. * * If an engine is given, this is entirely legacy, and we should not * pretend anything else, so we clear the name. */ if (e != NULL) keytype = NULL; if (e == NULL && (pkey == NULL || pkey->foreign == 0)) keytype = OBJ_nid2sn(id); # ifndef OPENSSL_NO_ENGINE if (e == NULL && pkey != NULL) e = pkey->pmeth_engine != NULL ? pkey->pmeth_engine : pkey->engine; /* Try to find an ENGINE which implements this method */ if (e != NULL) { if (!ENGINE_init(e)) { ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB); return NULL; } } else { e = ENGINE_get_pkey_meth_engine(id); } /* * If an ENGINE handled this method look it up. Otherwise use internal * tables. */ if (e != NULL) pmeth = ENGINE_get_pkey_meth(e, id); else # endif /* OPENSSL_NO_ENGINE */ if (pkey != NULL && pkey->foreign) pmeth = EVP_PKEY_meth_find(id); else app_pmeth = pmeth = evp_pkey_meth_find_added_by_application(id); /* END legacy */ #endif /* FIPS_MODULE */ common: /* * If there's no engine and no app supplied pmeth and there's a name, we try * fetching a provider implementation. */ if (e == NULL && app_pmeth == NULL && keytype != NULL) { /* * If |pkey| is given and is provided, we take a reference to its * keymgmt. Otherwise, we fetch one for the keytype we got. This * is to ensure that operation init functions can access what they * need through this single pointer. */ if (pkey != NULL && pkey->keymgmt != NULL) { if (!EVP_KEYMGMT_up_ref(pkey->keymgmt)) ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); else keymgmt = pkey->keymgmt; } else { keymgmt = EVP_KEYMGMT_fetch(libctx, keytype, propquery); } if (keymgmt == NULL) return NULL; /* EVP_KEYMGMT_fetch() recorded an error */ #ifndef FIPS_MODULE /* * Chase down the legacy NID, as that might be needed for diverse * purposes, such as ensure that EVP_PKEY_type() can return sensible * values. We go through all keymgmt names, because the keytype * that's passed to this function doesn't necessarily translate * directly. */ if (keymgmt != NULL) { int tmp_id = evp_keymgmt_get_legacy_alg(keymgmt); if (tmp_id != NID_undef) { if (id == -1) { id = tmp_id; } else { /* * It really really shouldn't differ. If it still does, * something is very wrong. */ if (!ossl_assert(id == tmp_id)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); EVP_KEYMGMT_free(keymgmt); return NULL; } } } } #endif } if (pmeth == NULL && keymgmt == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM); } else { ret = OPENSSL_zalloc(sizeof(*ret)); } #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) if ((ret == NULL || pmeth == NULL) && e != NULL) ENGINE_finish(e); #endif if (ret == NULL) { EVP_KEYMGMT_free(keymgmt); return NULL; } if (propquery != NULL) { ret->propquery = OPENSSL_strdup(propquery); if (ret->propquery == NULL) { OPENSSL_free(ret); EVP_KEYMGMT_free(keymgmt); return NULL; } } ret->libctx = libctx; ret->keytype = keytype; ret->keymgmt = keymgmt; ret->legacy_keytype = id; ret->engine = e; ret->pmeth = pmeth; ret->operation = EVP_PKEY_OP_UNDEFINED; ret->pkey = pkey; if (pkey != NULL) EVP_PKEY_up_ref(pkey); if (pmeth != NULL && pmeth->init != NULL) { if (pmeth->init(ret) <= 0) { ret->pmeth = NULL; EVP_PKEY_CTX_free(ret); return NULL; } } return ret; } /*- All methods below can also be used in FIPS_MODULE */ EVP_PKEY_CTX *EVP_PKEY_CTX_new_from_name(OSSL_LIB_CTX *libctx, const char *name, const char *propquery) { return int_ctx_new(libctx, NULL, NULL, name, propquery, -1); } EVP_PKEY_CTX *EVP_PKEY_CTX_new_from_pkey(OSSL_LIB_CTX *libctx, EVP_PKEY *pkey, const char *propquery) { return int_ctx_new(libctx, pkey, NULL, NULL, propquery, -1); } void evp_pkey_ctx_free_old_ops(EVP_PKEY_CTX *ctx) { if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)) { if (ctx->op.sig.algctx != NULL && ctx->op.sig.signature != NULL) ctx->op.sig.signature->freectx(ctx->op.sig.algctx); EVP_SIGNATURE_free(ctx->op.sig.signature); ctx->op.sig.algctx = NULL; ctx->op.sig.signature = NULL; } else if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) { if (ctx->op.kex.algctx != NULL && ctx->op.kex.exchange != NULL) ctx->op.kex.exchange->freectx(ctx->op.kex.algctx); EVP_KEYEXCH_free(ctx->op.kex.exchange); ctx->op.kex.algctx = NULL; ctx->op.kex.exchange = NULL; } else if (EVP_PKEY_CTX_IS_KEM_OP(ctx)) { if (ctx->op.encap.algctx != NULL && ctx->op.encap.kem != NULL) ctx->op.encap.kem->freectx(ctx->op.encap.algctx); EVP_KEM_free(ctx->op.encap.kem); ctx->op.encap.algctx = NULL; ctx->op.encap.kem = NULL; } else if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) { if (ctx->op.ciph.algctx != NULL && ctx->op.ciph.cipher != NULL) ctx->op.ciph.cipher->freectx(ctx->op.ciph.algctx); EVP_ASYM_CIPHER_free(ctx->op.ciph.cipher); ctx->op.ciph.algctx = NULL; ctx->op.ciph.cipher = NULL; } else if (EVP_PKEY_CTX_IS_GEN_OP(ctx)) { if (ctx->op.keymgmt.genctx != NULL && ctx->keymgmt != NULL) evp_keymgmt_gen_cleanup(ctx->keymgmt, ctx->op.keymgmt.genctx); } } void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx) { if (ctx == NULL) return; if (ctx->pmeth && ctx->pmeth->cleanup) ctx->pmeth->cleanup(ctx); evp_pkey_ctx_free_old_ops(ctx); #ifndef FIPS_MODULE evp_pkey_ctx_free_all_cached_data(ctx); #endif EVP_KEYMGMT_free(ctx->keymgmt); OPENSSL_free(ctx->propquery); EVP_PKEY_free(ctx->pkey); EVP_PKEY_free(ctx->peerkey); #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) ENGINE_finish(ctx->engine); #endif BN_free(ctx->rsa_pubexp); OPENSSL_free(ctx); } #ifndef FIPS_MODULE void EVP_PKEY_meth_get0_info(int *ppkey_id, int *pflags, const EVP_PKEY_METHOD *meth) { if (ppkey_id) *ppkey_id = meth->pkey_id; if (pflags) *pflags = meth->flags; } void EVP_PKEY_meth_copy(EVP_PKEY_METHOD *dst, const EVP_PKEY_METHOD *src) { int pkey_id = dst->pkey_id; int flags = dst->flags; *dst = *src; /* We only copy the function pointers so restore the other values */ dst->pkey_id = pkey_id; dst->flags = flags; } void EVP_PKEY_meth_free(EVP_PKEY_METHOD *pmeth) { if (pmeth && (pmeth->flags & EVP_PKEY_FLAG_DYNAMIC)) OPENSSL_free(pmeth); } EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e) { return int_ctx_new(NULL, pkey, e, NULL, NULL, -1); } EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int id, ENGINE *e) { return int_ctx_new(NULL, NULL, e, NULL, NULL, id); } EVP_PKEY_CTX *EVP_PKEY_CTX_dup(const EVP_PKEY_CTX *pctx) { EVP_PKEY_CTX *rctx; # ifndef OPENSSL_NO_ENGINE /* Make sure it's safe to copy a pkey context using an ENGINE */ if (pctx->engine && !ENGINE_init(pctx->engine)) { ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB); return 0; } # endif rctx = OPENSSL_zalloc(sizeof(*rctx)); if (rctx == NULL) return NULL; if (pctx->pkey != NULL) EVP_PKEY_up_ref(pctx->pkey); rctx->pkey = pctx->pkey; rctx->operation = pctx->operation; rctx->libctx = pctx->libctx; rctx->keytype = pctx->keytype; rctx->propquery = NULL; if (pctx->propquery != NULL) { rctx->propquery = OPENSSL_strdup(pctx->propquery); if (rctx->propquery == NULL) goto err; } rctx->legacy_keytype = pctx->legacy_keytype; if (EVP_PKEY_CTX_IS_DERIVE_OP(pctx)) { if (pctx->op.kex.exchange != NULL) { rctx->op.kex.exchange = pctx->op.kex.exchange; if (!EVP_KEYEXCH_up_ref(rctx->op.kex.exchange)) goto err; } if (pctx->op.kex.algctx != NULL) { if (!ossl_assert(pctx->op.kex.exchange != NULL)) goto err; if (pctx->op.kex.exchange->dupctx != NULL) rctx->op.kex.algctx = pctx->op.kex.exchange->dupctx(pctx->op.kex.algctx); if (rctx->op.kex.algctx == NULL) { EVP_KEYEXCH_free(rctx->op.kex.exchange); rctx->op.kex.exchange = NULL; goto err; } return rctx; } } else if (EVP_PKEY_CTX_IS_SIGNATURE_OP(pctx)) { if (pctx->op.sig.signature != NULL) { rctx->op.sig.signature = pctx->op.sig.signature; if (!EVP_SIGNATURE_up_ref(rctx->op.sig.signature)) goto err; } if (pctx->op.sig.algctx != NULL) { if (!ossl_assert(pctx->op.sig.signature != NULL)) goto err; if (pctx->op.sig.signature->dupctx != NULL) rctx->op.sig.algctx = pctx->op.sig.signature->dupctx(pctx->op.sig.algctx); if (rctx->op.sig.algctx == NULL) { EVP_SIGNATURE_free(rctx->op.sig.signature); rctx->op.sig.signature = NULL; goto err; } return rctx; } } else if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(pctx)) { if (pctx->op.ciph.cipher != NULL) { rctx->op.ciph.cipher = pctx->op.ciph.cipher; if (!EVP_ASYM_CIPHER_up_ref(rctx->op.ciph.cipher)) goto err; } if (pctx->op.ciph.algctx != NULL) { if (!ossl_assert(pctx->op.ciph.cipher != NULL)) goto err; if (pctx->op.ciph.cipher->dupctx != NULL) rctx->op.ciph.algctx = pctx->op.ciph.cipher->dupctx(pctx->op.ciph.algctx); if (rctx->op.ciph.algctx == NULL) { EVP_ASYM_CIPHER_free(rctx->op.ciph.cipher); rctx->op.ciph.cipher = NULL; goto err; } return rctx; } } else if (EVP_PKEY_CTX_IS_KEM_OP(pctx)) { if (pctx->op.encap.kem != NULL) { rctx->op.encap.kem = pctx->op.encap.kem; if (!EVP_KEM_up_ref(rctx->op.encap.kem)) goto err; } if (pctx->op.encap.algctx != NULL) { if (!ossl_assert(pctx->op.encap.kem != NULL)) goto err; if (pctx->op.encap.kem->dupctx != NULL) rctx->op.encap.algctx = pctx->op.encap.kem->dupctx(pctx->op.encap.algctx); if (rctx->op.encap.algctx == NULL) { EVP_KEM_free(rctx->op.encap.kem); rctx->op.encap.kem = NULL; goto err; } return rctx; } } else if (EVP_PKEY_CTX_IS_GEN_OP(pctx)) { /* Not supported - This would need a gen_dupctx() to work */ goto err; } rctx->pmeth = pctx->pmeth; # ifndef OPENSSL_NO_ENGINE rctx->engine = pctx->engine; # endif if (pctx->peerkey != NULL) EVP_PKEY_up_ref(pctx->peerkey); rctx->peerkey = pctx->peerkey; if (pctx->pmeth == NULL) { if (rctx->operation == EVP_PKEY_OP_UNDEFINED) { EVP_KEYMGMT *tmp_keymgmt = pctx->keymgmt; void *provkey; provkey = evp_pkey_export_to_provider(pctx->pkey, pctx->libctx, &tmp_keymgmt, pctx->propquery); if (provkey == NULL) goto err; if (!EVP_KEYMGMT_up_ref(tmp_keymgmt)) goto err; EVP_KEYMGMT_free(rctx->keymgmt); rctx->keymgmt = tmp_keymgmt; return rctx; } } else if (pctx->pmeth->copy(rctx, pctx) > 0) { return rctx; } err: rctx->pmeth = NULL; EVP_PKEY_CTX_free(rctx); return NULL; } int EVP_PKEY_meth_add0(const EVP_PKEY_METHOD *pmeth) { if (app_pkey_methods == NULL) { app_pkey_methods = sk_EVP_PKEY_METHOD_new(pmeth_cmp); if (app_pkey_methods == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_CRYPTO_LIB); return 0; } } if (!sk_EVP_PKEY_METHOD_push(app_pkey_methods, pmeth)) { ERR_raise(ERR_LIB_EVP, ERR_R_CRYPTO_LIB); return 0; } sk_EVP_PKEY_METHOD_sort(app_pkey_methods); return 1; } void evp_app_cleanup_int(void) { if (app_pkey_methods != NULL) sk_EVP_PKEY_METHOD_pop_free(app_pkey_methods, EVP_PKEY_meth_free); } int EVP_PKEY_meth_remove(const EVP_PKEY_METHOD *pmeth) { const EVP_PKEY_METHOD *ret; ret = sk_EVP_PKEY_METHOD_delete_ptr(app_pkey_methods, pmeth); return ret == NULL ? 0 : 1; } size_t EVP_PKEY_meth_get_count(void) { size_t rv = OSSL_NELEM(standard_methods); if (app_pkey_methods) rv += sk_EVP_PKEY_METHOD_num(app_pkey_methods); return rv; } const EVP_PKEY_METHOD *EVP_PKEY_meth_get0(size_t idx) { if (idx < OSSL_NELEM(standard_methods)) return (standard_methods[idx])(); if (app_pkey_methods == NULL) return NULL; idx -= OSSL_NELEM(standard_methods); if (idx >= (size_t)sk_EVP_PKEY_METHOD_num(app_pkey_methods)) return NULL; return sk_EVP_PKEY_METHOD_value(app_pkey_methods, idx); } #endif int EVP_PKEY_CTX_is_a(EVP_PKEY_CTX *ctx, const char *keytype) { #ifndef FIPS_MODULE if (evp_pkey_ctx_is_legacy(ctx)) return (ctx->pmeth->pkey_id == evp_pkey_name2type(keytype)); #endif return EVP_KEYMGMT_is_a(ctx->keymgmt, keytype); } int EVP_PKEY_CTX_set_params(EVP_PKEY_CTX *ctx, const OSSL_PARAM *params) { switch (evp_pkey_ctx_state(ctx)) { case EVP_PKEY_STATE_PROVIDER: if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx) && ctx->op.kex.exchange != NULL && ctx->op.kex.exchange->set_ctx_params != NULL) return ctx->op.kex.exchange->set_ctx_params(ctx->op.kex.algctx, params); if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx) && ctx->op.sig.signature != NULL && ctx->op.sig.signature->set_ctx_params != NULL) return ctx->op.sig.signature->set_ctx_params(ctx->op.sig.algctx, params); if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx) && ctx->op.ciph.cipher != NULL && ctx->op.ciph.cipher->set_ctx_params != NULL) return ctx->op.ciph.cipher->set_ctx_params(ctx->op.ciph.algctx, params); if (EVP_PKEY_CTX_IS_GEN_OP(ctx) && ctx->keymgmt != NULL && ctx->keymgmt->gen_set_params != NULL) return evp_keymgmt_gen_set_params(ctx->keymgmt, ctx->op.keymgmt.genctx, params); if (EVP_PKEY_CTX_IS_KEM_OP(ctx) && ctx->op.encap.kem != NULL && ctx->op.encap.kem->set_ctx_params != NULL) return ctx->op.encap.kem->set_ctx_params(ctx->op.encap.algctx, params); break; #ifndef FIPS_MODULE case EVP_PKEY_STATE_UNKNOWN: case EVP_PKEY_STATE_LEGACY: return evp_pkey_ctx_set_params_to_ctrl(ctx, params); #endif } return 0; } int EVP_PKEY_CTX_get_params(EVP_PKEY_CTX *ctx, OSSL_PARAM *params) { switch (evp_pkey_ctx_state(ctx)) { case EVP_PKEY_STATE_PROVIDER: if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx) && ctx->op.kex.exchange != NULL && ctx->op.kex.exchange->get_ctx_params != NULL) return ctx->op.kex.exchange->get_ctx_params(ctx->op.kex.algctx, params); if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx) && ctx->op.sig.signature != NULL && ctx->op.sig.signature->get_ctx_params != NULL) return ctx->op.sig.signature->get_ctx_params(ctx->op.sig.algctx, params); if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx) && ctx->op.ciph.cipher != NULL && ctx->op.ciph.cipher->get_ctx_params != NULL) return ctx->op.ciph.cipher->get_ctx_params(ctx->op.ciph.algctx, params); if (EVP_PKEY_CTX_IS_KEM_OP(ctx) && ctx->op.encap.kem != NULL && ctx->op.encap.kem->get_ctx_params != NULL) return ctx->op.encap.kem->get_ctx_params(ctx->op.encap.algctx, params); break; #ifndef FIPS_MODULE case EVP_PKEY_STATE_UNKNOWN: case EVP_PKEY_STATE_LEGACY: return evp_pkey_ctx_get_params_to_ctrl(ctx, params); #endif } return 0; } #ifndef FIPS_MODULE const OSSL_PARAM *EVP_PKEY_CTX_gettable_params(const EVP_PKEY_CTX *ctx) { void *provctx; if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx) && ctx->op.kex.exchange != NULL && ctx->op.kex.exchange->gettable_ctx_params != NULL) { provctx = ossl_provider_ctx(EVP_KEYEXCH_get0_provider(ctx->op.kex.exchange)); return ctx->op.kex.exchange->gettable_ctx_params(ctx->op.kex.algctx, provctx); } if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx) && ctx->op.sig.signature != NULL && ctx->op.sig.signature->gettable_ctx_params != NULL) { provctx = ossl_provider_ctx( EVP_SIGNATURE_get0_provider(ctx->op.sig.signature)); return ctx->op.sig.signature->gettable_ctx_params(ctx->op.sig.algctx, provctx); } if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx) && ctx->op.ciph.cipher != NULL && ctx->op.ciph.cipher->gettable_ctx_params != NULL) { provctx = ossl_provider_ctx( EVP_ASYM_CIPHER_get0_provider(ctx->op.ciph.cipher)); return ctx->op.ciph.cipher->gettable_ctx_params(ctx->op.ciph.algctx, provctx); } if (EVP_PKEY_CTX_IS_KEM_OP(ctx) && ctx->op.encap.kem != NULL && ctx->op.encap.kem->gettable_ctx_params != NULL) { provctx = ossl_provider_ctx(EVP_KEM_get0_provider(ctx->op.encap.kem)); return ctx->op.encap.kem->gettable_ctx_params(ctx->op.encap.algctx, provctx); } return NULL; } const OSSL_PARAM *EVP_PKEY_CTX_settable_params(const EVP_PKEY_CTX *ctx) { void *provctx; if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx) && ctx->op.kex.exchange != NULL && ctx->op.kex.exchange->settable_ctx_params != NULL) { provctx = ossl_provider_ctx(EVP_KEYEXCH_get0_provider(ctx->op.kex.exchange)); return ctx->op.kex.exchange->settable_ctx_params(ctx->op.kex.algctx, provctx); } if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx) && ctx->op.sig.signature != NULL && ctx->op.sig.signature->settable_ctx_params != NULL) { provctx = ossl_provider_ctx( EVP_SIGNATURE_get0_provider(ctx->op.sig.signature)); return ctx->op.sig.signature->settable_ctx_params(ctx->op.sig.algctx, provctx); } if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx) && ctx->op.ciph.cipher != NULL && ctx->op.ciph.cipher->settable_ctx_params != NULL) { provctx = ossl_provider_ctx( EVP_ASYM_CIPHER_get0_provider(ctx->op.ciph.cipher)); return ctx->op.ciph.cipher->settable_ctx_params(ctx->op.ciph.algctx, provctx); } if (EVP_PKEY_CTX_IS_GEN_OP(ctx) && ctx->keymgmt != NULL && ctx->keymgmt->gen_settable_params != NULL) { provctx = ossl_provider_ctx(EVP_KEYMGMT_get0_provider(ctx->keymgmt)); return ctx->keymgmt->gen_settable_params(ctx->op.keymgmt.genctx, provctx); } if (EVP_PKEY_CTX_IS_KEM_OP(ctx) && ctx->op.encap.kem != NULL && ctx->op.encap.kem->settable_ctx_params != NULL) { provctx = ossl_provider_ctx(EVP_KEM_get0_provider(ctx->op.encap.kem)); return ctx->op.encap.kem->settable_ctx_params(ctx->op.encap.algctx, provctx); } return NULL; } /* * Internal helpers for stricter EVP_PKEY_CTX_{set,get}_params(). * * Return 1 on success, 0 or negative for errors. * * In particular they return -2 if any of the params is not supported. * * They are not available in FIPS_MODULE as they depend on * - EVP_PKEY_CTX_{get,set}_params() * - EVP_PKEY_CTX_{gettable,settable}_params() * */ int evp_pkey_ctx_set_params_strict(EVP_PKEY_CTX *ctx, OSSL_PARAM *params) { if (ctx == NULL || params == NULL) return 0; /* * We only check for provider side EVP_PKEY_CTX. For #legacy, we * depend on the translation that happens in EVP_PKEY_CTX_set_params() * call, and that the resulting ctrl call will return -2 if it doesn't * known the ctrl command number. */ if (evp_pkey_ctx_is_provided(ctx)) { const OSSL_PARAM *settable = EVP_PKEY_CTX_settable_params(ctx); const OSSL_PARAM *p; for (p = params; p->key != NULL; p++) { /* Check the ctx actually understands this parameter */ if (OSSL_PARAM_locate_const(settable, p->key) == NULL) return -2; } } return EVP_PKEY_CTX_set_params(ctx, params); } int evp_pkey_ctx_get_params_strict(EVP_PKEY_CTX *ctx, OSSL_PARAM *params) { if (ctx == NULL || params == NULL) return 0; /* * We only check for provider side EVP_PKEY_CTX. For #legacy, we * depend on the translation that happens in EVP_PKEY_CTX_get_params() * call, and that the resulting ctrl call will return -2 if it doesn't * known the ctrl command number. */ if (evp_pkey_ctx_is_provided(ctx)) { const OSSL_PARAM *gettable = EVP_PKEY_CTX_gettable_params(ctx); const OSSL_PARAM *p; for (p = params; p->key != NULL; p++) { /* Check the ctx actually understands this parameter */ if (OSSL_PARAM_locate_const(gettable, p->key) == NULL) return -2; } } return EVP_PKEY_CTX_get_params(ctx, params); } int EVP_PKEY_CTX_get_signature_md(EVP_PKEY_CTX *ctx, const EVP_MD **md) { OSSL_PARAM sig_md_params[2], *p = sig_md_params; /* 80 should be big enough */ char name[80] = ""; const EVP_MD *tmp; if (ctx == NULL || !EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } if (ctx->op.sig.algctx == NULL) return EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_GET_MD, 0, (void *)(md)); *p++ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST, name, sizeof(name)); *p = OSSL_PARAM_construct_end(); if (!EVP_PKEY_CTX_get_params(ctx, sig_md_params)) return 0; tmp = evp_get_digestbyname_ex(ctx->libctx, name); if (tmp == NULL) return 0; *md = tmp; return 1; } static int evp_pkey_ctx_set_md(EVP_PKEY_CTX *ctx, const EVP_MD *md, int fallback, const char *param, int op, int ctrl) { OSSL_PARAM md_params[2], *p = md_params; const char *name; if (ctx == NULL || (ctx->operation & op) == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } if (fallback) return EVP_PKEY_CTX_ctrl(ctx, -1, op, ctrl, 0, (void *)(md)); if (md == NULL) { name = ""; } else { name = EVP_MD_get0_name(md); } *p++ = OSSL_PARAM_construct_utf8_string(param, /* * Cast away the const. This is read * only so should be safe */ (char *)name, 0); *p = OSSL_PARAM_construct_end(); return EVP_PKEY_CTX_set_params(ctx, md_params); } int EVP_PKEY_CTX_set_signature_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { return evp_pkey_ctx_set_md(ctx, md, ctx->op.sig.algctx == NULL, OSSL_SIGNATURE_PARAM_DIGEST, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_MD); } int EVP_PKEY_CTX_set_tls1_prf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { return evp_pkey_ctx_set_md(ctx, md, ctx->op.kex.algctx == NULL, OSSL_KDF_PARAM_DIGEST, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_MD); } static int evp_pkey_ctx_set1_octet_string(EVP_PKEY_CTX *ctx, int fallback, const char *param, int op, int ctrl, const unsigned char *data, int datalen) { OSSL_PARAM octet_string_params[2], *p = octet_string_params; if (ctx == NULL || (ctx->operation & op) == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* Code below to be removed when legacy support is dropped. */ if (fallback) return EVP_PKEY_CTX_ctrl(ctx, -1, op, ctrl, datalen, (void *)(data)); /* end of legacy support */ if (datalen < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_LENGTH); return 0; } *p++ = OSSL_PARAM_construct_octet_string(param, /* * Cast away the const. This is read * only so should be safe */ (unsigned char *)data, (size_t)datalen); *p = OSSL_PARAM_construct_end(); return EVP_PKEY_CTX_set_params(ctx, octet_string_params); } int EVP_PKEY_CTX_set1_tls1_prf_secret(EVP_PKEY_CTX *ctx, const unsigned char *sec, int seclen) { return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL, OSSL_KDF_PARAM_SECRET, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_SECRET, sec, seclen); } int EVP_PKEY_CTX_add1_tls1_prf_seed(EVP_PKEY_CTX *ctx, const unsigned char *seed, int seedlen) { return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL, OSSL_KDF_PARAM_SEED, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_SEED, seed, seedlen); } int EVP_PKEY_CTX_set_hkdf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { return evp_pkey_ctx_set_md(ctx, md, ctx->op.kex.algctx == NULL, OSSL_KDF_PARAM_DIGEST, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_MD); } int EVP_PKEY_CTX_set1_hkdf_salt(EVP_PKEY_CTX *ctx, const unsigned char *salt, int saltlen) { return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL, OSSL_KDF_PARAM_SALT, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_SALT, salt, saltlen); } int EVP_PKEY_CTX_set1_hkdf_key(EVP_PKEY_CTX *ctx, const unsigned char *key, int keylen) { return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL, OSSL_KDF_PARAM_KEY, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_KEY, key, keylen); } int EVP_PKEY_CTX_add1_hkdf_info(EVP_PKEY_CTX *ctx, const unsigned char *info, int infolen) { return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL, OSSL_KDF_PARAM_INFO, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_INFO, info, infolen); } int EVP_PKEY_CTX_set_hkdf_mode(EVP_PKEY_CTX *ctx, int mode) { OSSL_PARAM int_params[2], *p = int_params; if (ctx == NULL || !EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* Code below to be removed when legacy support is dropped. */ if (ctx->op.kex.algctx == NULL) return EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_MODE, mode, NULL); /* end of legacy support */ if (mode < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE); return 0; } *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode); *p = OSSL_PARAM_construct_end(); return EVP_PKEY_CTX_set_params(ctx, int_params); } int EVP_PKEY_CTX_set1_pbe_pass(EVP_PKEY_CTX *ctx, const char *pass, int passlen) { return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL, OSSL_KDF_PARAM_PASSWORD, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_PASS, (const unsigned char *)pass, passlen); } int EVP_PKEY_CTX_set1_scrypt_salt(EVP_PKEY_CTX *ctx, const unsigned char *salt, int saltlen) { return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.kex.algctx == NULL, OSSL_KDF_PARAM_SALT, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_SALT, salt, saltlen); } static int evp_pkey_ctx_set_uint64(EVP_PKEY_CTX *ctx, const char *param, int op, int ctrl, uint64_t val) { OSSL_PARAM uint64_params[2], *p = uint64_params; if (ctx == NULL || !EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* Code below to be removed when legacy support is dropped. */ if (ctx->op.kex.algctx == NULL) return EVP_PKEY_CTX_ctrl_uint64(ctx, -1, op, ctrl, val); /* end of legacy support */ *p++ = OSSL_PARAM_construct_uint64(param, &val); *p = OSSL_PARAM_construct_end(); return EVP_PKEY_CTX_set_params(ctx, uint64_params); } int EVP_PKEY_CTX_set_scrypt_N(EVP_PKEY_CTX *ctx, uint64_t n) { return evp_pkey_ctx_set_uint64(ctx, OSSL_KDF_PARAM_SCRYPT_N, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_N, n); } int EVP_PKEY_CTX_set_scrypt_r(EVP_PKEY_CTX *ctx, uint64_t r) { return evp_pkey_ctx_set_uint64(ctx, OSSL_KDF_PARAM_SCRYPT_R, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_R, r); } int EVP_PKEY_CTX_set_scrypt_p(EVP_PKEY_CTX *ctx, uint64_t p) { return evp_pkey_ctx_set_uint64(ctx, OSSL_KDF_PARAM_SCRYPT_P, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_P, p); } int EVP_PKEY_CTX_set_scrypt_maxmem_bytes(EVP_PKEY_CTX *ctx, uint64_t maxmem_bytes) { return evp_pkey_ctx_set_uint64(ctx, OSSL_KDF_PARAM_SCRYPT_MAXMEM, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES, maxmem_bytes); } int EVP_PKEY_CTX_set_mac_key(EVP_PKEY_CTX *ctx, const unsigned char *key, int keylen) { return evp_pkey_ctx_set1_octet_string(ctx, ctx->op.keymgmt.genctx == NULL, OSSL_PKEY_PARAM_PRIV_KEY, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_SET_MAC_KEY, key, keylen); } int EVP_PKEY_CTX_set_kem_op(EVP_PKEY_CTX *ctx, const char *op) { OSSL_PARAM params[2], *p = params; if (ctx == NULL || op == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE); return 0; } if (!EVP_PKEY_CTX_IS_KEM_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KEM_PARAM_OPERATION, (char *)op, 0); *p = OSSL_PARAM_construct_end(); return EVP_PKEY_CTX_set_params(ctx, params); } int EVP_PKEY_CTX_set1_id(EVP_PKEY_CTX *ctx, const void *id, int len) { return EVP_PKEY_CTX_ctrl(ctx, -1, -1, EVP_PKEY_CTRL_SET1_ID, (int)len, (void*)(id)); } int EVP_PKEY_CTX_get1_id(EVP_PKEY_CTX *ctx, void *id) { return EVP_PKEY_CTX_ctrl(ctx, -1, -1, EVP_PKEY_CTRL_GET1_ID, 0, (void*)id); } int EVP_PKEY_CTX_get1_id_len(EVP_PKEY_CTX *ctx, size_t *id_len) { return EVP_PKEY_CTX_ctrl(ctx, -1, -1, EVP_PKEY_CTRL_GET1_ID_LEN, 0, (void*)id_len); } static int evp_pkey_ctx_ctrl_int(EVP_PKEY_CTX *ctx, int keytype, int optype, int cmd, int p1, void *p2) { int ret = 0; /* * If the method has a |digest_custom| function, we can relax the * operation type check, since this can be called before the operation * is initialized. */ if (ctx->pmeth == NULL || ctx->pmeth->digest_custom == NULL) { if (ctx->operation == EVP_PKEY_OP_UNDEFINED) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_OPERATION_SET); return -1; } if ((optype != -1) && !(ctx->operation & optype)) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION); return -1; } } switch (evp_pkey_ctx_state(ctx)) { case EVP_PKEY_STATE_PROVIDER: return evp_pkey_ctx_ctrl_to_param(ctx, keytype, optype, cmd, p1, p2); case EVP_PKEY_STATE_UNKNOWN: case EVP_PKEY_STATE_LEGACY: if (ctx->pmeth == NULL || ctx->pmeth->ctrl == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if ((keytype != -1) && (ctx->pmeth->pkey_id != keytype)) return -1; ret = ctx->pmeth->ctrl(ctx, cmd, p1, p2); if (ret == -2) ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); break; } return ret; } int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype, int cmd, int p1, void *p2) { int ret = 0; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } /* If unsupported, we don't want that reported here */ ERR_set_mark(); ret = evp_pkey_ctx_store_cached_data(ctx, keytype, optype, cmd, NULL, p2, p1); if (ret == -2) { ERR_pop_to_mark(); } else { ERR_clear_last_mark(); /* * If there was an error, there was an error. * If the operation isn't initialized yet, we also return, as * the saved values will be used then anyway. */ if (ret < 1 || ctx->operation == EVP_PKEY_OP_UNDEFINED) return ret; } return evp_pkey_ctx_ctrl_int(ctx, keytype, optype, cmd, p1, p2); } int EVP_PKEY_CTX_ctrl_uint64(EVP_PKEY_CTX *ctx, int keytype, int optype, int cmd, uint64_t value) { return EVP_PKEY_CTX_ctrl(ctx, keytype, optype, cmd, 0, &value); } static int evp_pkey_ctx_ctrl_str_int(EVP_PKEY_CTX *ctx, const char *name, const char *value) { int ret = 0; if (ctx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } switch (evp_pkey_ctx_state(ctx)) { case EVP_PKEY_STATE_PROVIDER: return evp_pkey_ctx_ctrl_str_to_param(ctx, name, value); case EVP_PKEY_STATE_UNKNOWN: case EVP_PKEY_STATE_LEGACY: if (ctx == NULL || ctx->pmeth == NULL || ctx->pmeth->ctrl_str == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (strcmp(name, "digest") == 0) ret = EVP_PKEY_CTX_md(ctx, EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_MD, value); else ret = ctx->pmeth->ctrl_str(ctx, name, value); break; } return ret; } int EVP_PKEY_CTX_ctrl_str(EVP_PKEY_CTX *ctx, const char *name, const char *value) { int ret = 0; /* If unsupported, we don't want that reported here */ ERR_set_mark(); ret = evp_pkey_ctx_store_cached_data(ctx, -1, -1, -1, name, value, strlen(value) + 1); if (ret == -2) { ERR_pop_to_mark(); } else { ERR_clear_last_mark(); /* * If there was an error, there was an error. * If the operation isn't initialized yet, we also return, as * the saved values will be used then anyway. */ if (ret < 1 || ctx->operation == EVP_PKEY_OP_UNDEFINED) return ret; } return evp_pkey_ctx_ctrl_str_int(ctx, name, value); } static int decode_cmd(int cmd, const char *name) { if (cmd == -1) { /* * The consequence of the assertion not being true is that this * function will return -1, which will cause the calling functions * to signal that the command is unsupported... in non-debug mode. */ if (ossl_assert(name != NULL)) if (strcmp(name, "distid") == 0 || strcmp(name, "hexdistid") == 0) cmd = EVP_PKEY_CTRL_SET1_ID; } return cmd; } static int evp_pkey_ctx_store_cached_data(EVP_PKEY_CTX *ctx, int keytype, int optype, int cmd, const char *name, const void *data, size_t data_len) { /* * Check that it's one of the supported commands. The ctrl commands * number cases here must correspond to the cases in the bottom switch * in this function. */ switch (cmd = decode_cmd(cmd, name)) { case EVP_PKEY_CTRL_SET1_ID: break; default: ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (keytype != -1) { switch (evp_pkey_ctx_state(ctx)) { case EVP_PKEY_STATE_PROVIDER: if (ctx->keymgmt == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (!EVP_KEYMGMT_is_a(ctx->keymgmt, evp_pkey_type2name(keytype))) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION); return -1; } break; case EVP_PKEY_STATE_UNKNOWN: case EVP_PKEY_STATE_LEGACY: if (ctx->pmeth == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (EVP_PKEY_type(ctx->pmeth->pkey_id) != EVP_PKEY_type(keytype)) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION); return -1; } break; } } if (optype != -1 && (ctx->operation & optype) == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION); return -1; } switch (cmd) { case EVP_PKEY_CTRL_SET1_ID: evp_pkey_ctx_free_cached_data(ctx, cmd, name); if (name != NULL) { ctx->cached_parameters.dist_id_name = OPENSSL_strdup(name); if (ctx->cached_parameters.dist_id_name == NULL) return 0; } if (data_len > 0) { ctx->cached_parameters.dist_id = OPENSSL_memdup(data, data_len); if (ctx->cached_parameters.dist_id == NULL) return 0; } ctx->cached_parameters.dist_id_set = 1; ctx->cached_parameters.dist_id_len = data_len; break; } return 1; } static void evp_pkey_ctx_free_cached_data(EVP_PKEY_CTX *ctx, int cmd, const char *name) { cmd = decode_cmd(cmd, name); switch (cmd) { case EVP_PKEY_CTRL_SET1_ID: OPENSSL_free(ctx->cached_parameters.dist_id); OPENSSL_free(ctx->cached_parameters.dist_id_name); ctx->cached_parameters.dist_id = NULL; ctx->cached_parameters.dist_id_name = NULL; break; } } static void evp_pkey_ctx_free_all_cached_data(EVP_PKEY_CTX *ctx) { evp_pkey_ctx_free_cached_data(ctx, EVP_PKEY_CTRL_SET1_ID, NULL); } int evp_pkey_ctx_use_cached_data(EVP_PKEY_CTX *ctx) { int ret = 1; if (ret && ctx->cached_parameters.dist_id_set) { const char *name = ctx->cached_parameters.dist_id_name; const void *val = ctx->cached_parameters.dist_id; size_t len = ctx->cached_parameters.dist_id_len; if (name != NULL) ret = evp_pkey_ctx_ctrl_str_int(ctx, name, val); else ret = evp_pkey_ctx_ctrl_int(ctx, -1, ctx->operation, EVP_PKEY_CTRL_SET1_ID, (int)len, (void *)val); } return ret; } OSSL_LIB_CTX *EVP_PKEY_CTX_get0_libctx(EVP_PKEY_CTX *ctx) { return ctx->libctx; } const char *EVP_PKEY_CTX_get0_propq(const EVP_PKEY_CTX *ctx) { return ctx->propquery; } const OSSL_PROVIDER *EVP_PKEY_CTX_get0_provider(const EVP_PKEY_CTX *ctx) { if (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)) { if (ctx->op.sig.signature != NULL) return EVP_SIGNATURE_get0_provider(ctx->op.sig.signature); } else if (EVP_PKEY_CTX_IS_DERIVE_OP(ctx)) { if (ctx->op.kex.exchange != NULL) return EVP_KEYEXCH_get0_provider(ctx->op.kex.exchange); } else if (EVP_PKEY_CTX_IS_KEM_OP(ctx)) { if (ctx->op.encap.kem != NULL) return EVP_KEM_get0_provider(ctx->op.encap.kem); } else if (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) { if (ctx->op.ciph.cipher != NULL) return EVP_ASYM_CIPHER_get0_provider(ctx->op.ciph.cipher); } else if (EVP_PKEY_CTX_IS_GEN_OP(ctx)) { if (ctx->keymgmt != NULL) return EVP_KEYMGMT_get0_provider(ctx->keymgmt); } return NULL; } /* Utility functions to send a string of hex string to a ctrl */ int EVP_PKEY_CTX_str2ctrl(EVP_PKEY_CTX *ctx, int cmd, const char *str) { size_t len; len = strlen(str); if (len > INT_MAX) return -1; return ctx->pmeth->ctrl(ctx, cmd, len, (void *)str); } int EVP_PKEY_CTX_hex2ctrl(EVP_PKEY_CTX *ctx, int cmd, const char *hex) { unsigned char *bin; long binlen; int rv = -1; bin = OPENSSL_hexstr2buf(hex, &binlen); if (bin == NULL) return 0; if (binlen <= INT_MAX) rv = ctx->pmeth->ctrl(ctx, cmd, binlen, bin); OPENSSL_free(bin); return rv; } /* Pass a message digest to a ctrl */ int EVP_PKEY_CTX_md(EVP_PKEY_CTX *ctx, int optype, int cmd, const char *md) { const EVP_MD *m; if (md == NULL || (m = EVP_get_digestbyname(md)) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_DIGEST); return 0; } return EVP_PKEY_CTX_ctrl(ctx, -1, optype, cmd, 0, (void *)m); } int EVP_PKEY_CTX_get_operation(EVP_PKEY_CTX *ctx) { return ctx->operation; } void EVP_PKEY_CTX_set0_keygen_info(EVP_PKEY_CTX *ctx, int *dat, int datlen) { ctx->keygen_info = dat; ctx->keygen_info_count = datlen; } void EVP_PKEY_CTX_set_data(EVP_PKEY_CTX *ctx, void *data) { ctx->data = data; } void *EVP_PKEY_CTX_get_data(const EVP_PKEY_CTX *ctx) { return ctx->data; } EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx) { return ctx->pkey; } EVP_PKEY *EVP_PKEY_CTX_get0_peerkey(EVP_PKEY_CTX *ctx) { return ctx->peerkey; } void EVP_PKEY_CTX_set_app_data(EVP_PKEY_CTX *ctx, void *data) { ctx->app_data = data; } void *EVP_PKEY_CTX_get_app_data(EVP_PKEY_CTX *ctx) { return ctx->app_data; } void EVP_PKEY_meth_set_init(EVP_PKEY_METHOD *pmeth, int (*init) (EVP_PKEY_CTX *ctx)) { pmeth->init = init; } void EVP_PKEY_meth_set_copy(EVP_PKEY_METHOD *pmeth, int (*copy) (EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src)) { pmeth->copy = copy; } void EVP_PKEY_meth_set_cleanup(EVP_PKEY_METHOD *pmeth, void (*cleanup) (EVP_PKEY_CTX *ctx)) { pmeth->cleanup = cleanup; } void EVP_PKEY_meth_set_paramgen(EVP_PKEY_METHOD *pmeth, int (*paramgen_init) (EVP_PKEY_CTX *ctx), int (*paramgen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)) { pmeth->paramgen_init = paramgen_init; pmeth->paramgen = paramgen; } void EVP_PKEY_meth_set_keygen(EVP_PKEY_METHOD *pmeth, int (*keygen_init) (EVP_PKEY_CTX *ctx), int (*keygen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)) { pmeth->keygen_init = keygen_init; pmeth->keygen = keygen; } void EVP_PKEY_meth_set_sign(EVP_PKEY_METHOD *pmeth, int (*sign_init) (EVP_PKEY_CTX *ctx), int (*sign) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen)) { pmeth->sign_init = sign_init; pmeth->sign = sign; } void EVP_PKEY_meth_set_verify(EVP_PKEY_METHOD *pmeth, int (*verify_init) (EVP_PKEY_CTX *ctx), int (*verify) (EVP_PKEY_CTX *ctx, const unsigned char *sig, size_t siglen, const unsigned char *tbs, size_t tbslen)) { pmeth->verify_init = verify_init; pmeth->verify = verify; } void EVP_PKEY_meth_set_verify_recover(EVP_PKEY_METHOD *pmeth, int (*verify_recover_init) (EVP_PKEY_CTX *ctx), int (*verify_recover) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen)) { pmeth->verify_recover_init = verify_recover_init; pmeth->verify_recover = verify_recover; } void EVP_PKEY_meth_set_signctx(EVP_PKEY_METHOD *pmeth, int (*signctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx), int (*signctx) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, EVP_MD_CTX *mctx)) { pmeth->signctx_init = signctx_init; pmeth->signctx = signctx; } void EVP_PKEY_meth_set_verifyctx(EVP_PKEY_METHOD *pmeth, int (*verifyctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx), int (*verifyctx) (EVP_PKEY_CTX *ctx, const unsigned char *sig, int siglen, EVP_MD_CTX *mctx)) { pmeth->verifyctx_init = verifyctx_init; pmeth->verifyctx = verifyctx; } void EVP_PKEY_meth_set_encrypt(EVP_PKEY_METHOD *pmeth, int (*encrypt_init) (EVP_PKEY_CTX *ctx), int (*encryptfn) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen)) { pmeth->encrypt_init = encrypt_init; pmeth->encrypt = encryptfn; } void EVP_PKEY_meth_set_decrypt(EVP_PKEY_METHOD *pmeth, int (*decrypt_init) (EVP_PKEY_CTX *ctx), int (*decrypt) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen)) { pmeth->decrypt_init = decrypt_init; pmeth->decrypt = decrypt; } void EVP_PKEY_meth_set_derive(EVP_PKEY_METHOD *pmeth, int (*derive_init) (EVP_PKEY_CTX *ctx), int (*derive) (EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen)) { pmeth->derive_init = derive_init; pmeth->derive = derive; } void EVP_PKEY_meth_set_ctrl(EVP_PKEY_METHOD *pmeth, int (*ctrl) (EVP_PKEY_CTX *ctx, int type, int p1, void *p2), int (*ctrl_str) (EVP_PKEY_CTX *ctx, const char *type, const char *value)) { pmeth->ctrl = ctrl; pmeth->ctrl_str = ctrl_str; } void EVP_PKEY_meth_set_digestsign(EVP_PKEY_METHOD *pmeth, int (*digestsign) (EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen)) { pmeth->digestsign = digestsign; } void EVP_PKEY_meth_set_digestverify(EVP_PKEY_METHOD *pmeth, int (*digestverify) (EVP_MD_CTX *ctx, const unsigned char *sig, size_t siglen, const unsigned char *tbs, size_t tbslen)) { pmeth->digestverify = digestverify; } void EVP_PKEY_meth_set_check(EVP_PKEY_METHOD *pmeth, int (*check) (EVP_PKEY *pkey)) { pmeth->check = check; } void EVP_PKEY_meth_set_public_check(EVP_PKEY_METHOD *pmeth, int (*check) (EVP_PKEY *pkey)) { pmeth->public_check = check; } void EVP_PKEY_meth_set_param_check(EVP_PKEY_METHOD *pmeth, int (*check) (EVP_PKEY *pkey)) { pmeth->param_check = check; } void EVP_PKEY_meth_set_digest_custom(EVP_PKEY_METHOD *pmeth, int (*digest_custom) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx)) { pmeth->digest_custom = digest_custom; } void EVP_PKEY_meth_get_init(const EVP_PKEY_METHOD *pmeth, int (**pinit) (EVP_PKEY_CTX *ctx)) { *pinit = pmeth->init; } void EVP_PKEY_meth_get_copy(const EVP_PKEY_METHOD *pmeth, int (**pcopy) (EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src)) { *pcopy = pmeth->copy; } void EVP_PKEY_meth_get_cleanup(const EVP_PKEY_METHOD *pmeth, void (**pcleanup) (EVP_PKEY_CTX *ctx)) { *pcleanup = pmeth->cleanup; } void EVP_PKEY_meth_get_paramgen(const EVP_PKEY_METHOD *pmeth, int (**pparamgen_init) (EVP_PKEY_CTX *ctx), int (**pparamgen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)) { if (pparamgen_init) *pparamgen_init = pmeth->paramgen_init; if (pparamgen) *pparamgen = pmeth->paramgen; } void EVP_PKEY_meth_get_keygen(const EVP_PKEY_METHOD *pmeth, int (**pkeygen_init) (EVP_PKEY_CTX *ctx), int (**pkeygen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)) { if (pkeygen_init) *pkeygen_init = pmeth->keygen_init; if (pkeygen) *pkeygen = pmeth->keygen; } void EVP_PKEY_meth_get_sign(const EVP_PKEY_METHOD *pmeth, int (**psign_init) (EVP_PKEY_CTX *ctx), int (**psign) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen)) { if (psign_init) *psign_init = pmeth->sign_init; if (psign) *psign = pmeth->sign; } void EVP_PKEY_meth_get_verify(const EVP_PKEY_METHOD *pmeth, int (**pverify_init) (EVP_PKEY_CTX *ctx), int (**pverify) (EVP_PKEY_CTX *ctx, const unsigned char *sig, size_t siglen, const unsigned char *tbs, size_t tbslen)) { if (pverify_init) *pverify_init = pmeth->verify_init; if (pverify) *pverify = pmeth->verify; } void EVP_PKEY_meth_get_verify_recover(const EVP_PKEY_METHOD *pmeth, int (**pverify_recover_init) (EVP_PKEY_CTX *ctx), int (**pverify_recover) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen)) { if (pverify_recover_init) *pverify_recover_init = pmeth->verify_recover_init; if (pverify_recover) *pverify_recover = pmeth->verify_recover; } void EVP_PKEY_meth_get_signctx(const EVP_PKEY_METHOD *pmeth, int (**psignctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx), int (**psignctx) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, EVP_MD_CTX *mctx)) { if (psignctx_init) *psignctx_init = pmeth->signctx_init; if (psignctx) *psignctx = pmeth->signctx; } void EVP_PKEY_meth_get_verifyctx(const EVP_PKEY_METHOD *pmeth, int (**pverifyctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx), int (**pverifyctx) (EVP_PKEY_CTX *ctx, const unsigned char *sig, int siglen, EVP_MD_CTX *mctx)) { if (pverifyctx_init) *pverifyctx_init = pmeth->verifyctx_init; if (pverifyctx) *pverifyctx = pmeth->verifyctx; } void EVP_PKEY_meth_get_encrypt(const EVP_PKEY_METHOD *pmeth, int (**pencrypt_init) (EVP_PKEY_CTX *ctx), int (**pencryptfn) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen)) { if (pencrypt_init) *pencrypt_init = pmeth->encrypt_init; if (pencryptfn) *pencryptfn = pmeth->encrypt; } void EVP_PKEY_meth_get_decrypt(const EVP_PKEY_METHOD *pmeth, int (**pdecrypt_init) (EVP_PKEY_CTX *ctx), int (**pdecrypt) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen)) { if (pdecrypt_init) *pdecrypt_init = pmeth->decrypt_init; if (pdecrypt) *pdecrypt = pmeth->decrypt; } void EVP_PKEY_meth_get_derive(const EVP_PKEY_METHOD *pmeth, int (**pderive_init) (EVP_PKEY_CTX *ctx), int (**pderive) (EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen)) { if (pderive_init) *pderive_init = pmeth->derive_init; if (pderive) *pderive = pmeth->derive; } void EVP_PKEY_meth_get_ctrl(const EVP_PKEY_METHOD *pmeth, int (**pctrl) (EVP_PKEY_CTX *ctx, int type, int p1, void *p2), int (**pctrl_str) (EVP_PKEY_CTX *ctx, const char *type, const char *value)) { if (pctrl) *pctrl = pmeth->ctrl; if (pctrl_str) *pctrl_str = pmeth->ctrl_str; } void EVP_PKEY_meth_get_digestsign(const EVP_PKEY_METHOD *pmeth, int (**digestsign) (EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen)) { if (digestsign) *digestsign = pmeth->digestsign; } void EVP_PKEY_meth_get_digestverify(const EVP_PKEY_METHOD *pmeth, int (**digestverify) (EVP_MD_CTX *ctx, const unsigned char *sig, size_t siglen, const unsigned char *tbs, size_t tbslen)) { if (digestverify) *digestverify = pmeth->digestverify; } void EVP_PKEY_meth_get_check(const EVP_PKEY_METHOD *pmeth, int (**pcheck) (EVP_PKEY *pkey)) { if (pcheck != NULL) *pcheck = pmeth->check; } void EVP_PKEY_meth_get_public_check(const EVP_PKEY_METHOD *pmeth, int (**pcheck) (EVP_PKEY *pkey)) { if (pcheck != NULL) *pcheck = pmeth->public_check; } void EVP_PKEY_meth_get_param_check(const EVP_PKEY_METHOD *pmeth, int (**pcheck) (EVP_PKEY *pkey)) { if (pcheck != NULL) *pcheck = pmeth->param_check; } void EVP_PKEY_meth_get_digest_custom(const EVP_PKEY_METHOD *pmeth, int (**pdigest_custom) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx)) { if (pdigest_custom != NULL) *pdigest_custom = pmeth->digest_custom; } #endif /* FIPS_MODULE */
./openssl/crypto/evp/p_lib.c
/* * Copyright 1995-2023 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 */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <assert.h> #include <stdio.h> #include "internal/cryptlib.h" #include "internal/refcount.h" #include "internal/namemap.h" #include <openssl/bn.h> #include <openssl/err.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/rsa.h> #include <openssl/dsa.h> #include <openssl/dh.h> #include <openssl/ec.h> #include <openssl/cmac.h> #ifndef FIPS_MODULE # include <openssl/engine.h> #endif #include <openssl/params.h> #include <openssl/param_build.h> #include <openssl/encoder.h> #include <openssl/core_names.h> #include "internal/numbers.h" /* includes SIZE_MAX */ #include "internal/ffc.h" #include "crypto/evp.h" #include "crypto/dh.h" #include "crypto/dsa.h" #include "crypto/ec.h" #include "crypto/ecx.h" #include "crypto/rsa.h" #ifndef FIPS_MODULE # include "crypto/asn1.h" # include "crypto/x509.h" #endif #include "internal/provider.h" #include "evp_local.h" static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str, int len, EVP_KEYMGMT *keymgmt); static void evp_pkey_free_it(EVP_PKEY *key); #ifndef FIPS_MODULE /* The type of parameters selected in key parameter functions */ # define SELECT_PARAMETERS OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS int EVP_PKEY_get_bits(const EVP_PKEY *pkey) { int size = 0; if (pkey != NULL) { size = pkey->cache.bits; if (pkey->ameth != NULL && pkey->ameth->pkey_bits != NULL) size = pkey->ameth->pkey_bits(pkey); } if (size <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_UNKNOWN_BITS); return 0; } return size; } int EVP_PKEY_get_security_bits(const EVP_PKEY *pkey) { int size = 0; if (pkey != NULL) { size = pkey->cache.security_bits; if (pkey->ameth != NULL && pkey->ameth->pkey_security_bits != NULL) size = pkey->ameth->pkey_security_bits(pkey); } if (size <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_UNKNOWN_SECURITY_BITS); return 0; } return size; } int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode) { # ifndef OPENSSL_NO_DSA if (pkey->type == EVP_PKEY_DSA) { int ret = pkey->save_parameters; if (mode >= 0) pkey->save_parameters = mode; return ret; } # endif # ifndef OPENSSL_NO_EC if (pkey->type == EVP_PKEY_EC) { int ret = pkey->save_parameters; if (mode >= 0) pkey->save_parameters = mode; return ret; } # endif return 0; } int EVP_PKEY_set_ex_data(EVP_PKEY *key, int idx, void *arg) { return CRYPTO_set_ex_data(&key->ex_data, idx, arg); } void *EVP_PKEY_get_ex_data(const EVP_PKEY *key, int idx) { return CRYPTO_get_ex_data(&key->ex_data, idx); } int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) { /* * Clean up legacy stuff from this function when legacy support is gone. */ EVP_PKEY *downgraded_from = NULL; int ok = 0; /* * If |to| is a legacy key and |from| isn't, we must make a downgraded * copy of |from|. If that fails, this function fails. */ if (evp_pkey_is_legacy(to) && evp_pkey_is_provided(from)) { if (!evp_pkey_copy_downgraded(&downgraded_from, from)) goto end; from = downgraded_from; } /* * Make sure |to| is typed. Content is less important at this early * stage. * * 1. If |to| is untyped, assign |from|'s key type to it. * 2. If |to| contains a legacy key, compare its |type| to |from|'s. * (|from| was already downgraded above) * * If |to| is a provided key, there's nothing more to do here, functions * like evp_keymgmt_util_copy() and evp_pkey_export_to_provider() called * further down help us find out if they are the same or not. */ if (evp_pkey_is_blank(to)) { if (evp_pkey_is_legacy(from)) { if (EVP_PKEY_set_type(to, from->type) == 0) goto end; } else { if (EVP_PKEY_set_type_by_keymgmt(to, from->keymgmt) == 0) goto end; } } else if (evp_pkey_is_legacy(to)) { if (to->type != from->type) { ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES); goto end; } } if (EVP_PKEY_missing_parameters(from)) { ERR_raise(ERR_LIB_EVP, EVP_R_MISSING_PARAMETERS); goto end; } if (!EVP_PKEY_missing_parameters(to)) { if (EVP_PKEY_parameters_eq(to, from) == 1) ok = 1; else ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_PARAMETERS); goto end; } /* For purely provided keys, we just call the keymgmt utility */ if (to->keymgmt != NULL && from->keymgmt != NULL) { ok = evp_keymgmt_util_copy(to, (EVP_PKEY *)from, SELECT_PARAMETERS); goto end; } /* * If |to| is provided, we know that |from| is legacy at this point. * Try exporting |from| to |to|'s keymgmt, then use evp_keymgmt_dup() * to copy the appropriate data to |to|'s keydata. * We cannot override existing data so do it only if there is no keydata * in |to| yet. */ if (to->keymgmt != NULL && to->keydata == NULL) { EVP_KEYMGMT *to_keymgmt = to->keymgmt; void *from_keydata = evp_pkey_export_to_provider((EVP_PKEY *)from, NULL, &to_keymgmt, NULL); /* * If we get a NULL, it could be an internal error, or it could be * that there's a key mismatch. We're pretending the latter... */ if (from_keydata == NULL) ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES); else ok = (to->keydata = evp_keymgmt_dup(to->keymgmt, from_keydata, SELECT_PARAMETERS)) != NULL; goto end; } /* Both keys are legacy */ if (from->ameth != NULL && from->ameth->param_copy != NULL) ok = from->ameth->param_copy(to, from); end: EVP_PKEY_free(downgraded_from); return ok; } int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey) { if (pkey != NULL) { if (pkey->keymgmt != NULL) return !evp_keymgmt_util_has((EVP_PKEY *)pkey, SELECT_PARAMETERS); else if (pkey->ameth != NULL && pkey->ameth->param_missing != NULL) return pkey->ameth->param_missing(pkey); } return 0; } /* * This function is called for any mixture of keys except pure legacy pair. * When legacy keys are gone, we replace a call to this functions with * a call to evp_keymgmt_util_match(). */ static int evp_pkey_cmp_any(const EVP_PKEY *a, const EVP_PKEY *b, int selection) { EVP_KEYMGMT *keymgmt1 = NULL, *keymgmt2 = NULL; void *keydata1 = NULL, *keydata2 = NULL, *tmp_keydata = NULL; /* If none of them are provided, this function shouldn't have been called */ if (!ossl_assert(evp_pkey_is_provided(a) || evp_pkey_is_provided(b))) return -2; /* For purely provided keys, we just call the keymgmt utility */ if (evp_pkey_is_provided(a) && evp_pkey_is_provided(b)) return evp_keymgmt_util_match((EVP_PKEY *)a, (EVP_PKEY *)b, selection); /* * At this point, one of them is provided, the other not. This allows * us to compare types using legacy NIDs. */ if (evp_pkey_is_legacy(a) && !EVP_KEYMGMT_is_a(b->keymgmt, OBJ_nid2sn(a->type))) return -1; /* not the same key type */ if (evp_pkey_is_legacy(b) && !EVP_KEYMGMT_is_a(a->keymgmt, OBJ_nid2sn(b->type))) return -1; /* not the same key type */ /* * We've determined that they both are the same keytype, so the next * step is to do a bit of cross export to ensure we have keydata for * both keys in the same keymgmt. */ keymgmt1 = a->keymgmt; keydata1 = a->keydata; keymgmt2 = b->keymgmt; keydata2 = b->keydata; if (keymgmt2 != NULL && keymgmt2->match != NULL) { tmp_keydata = evp_pkey_export_to_provider((EVP_PKEY *)a, NULL, &keymgmt2, NULL); if (tmp_keydata != NULL) { keymgmt1 = keymgmt2; keydata1 = tmp_keydata; } } if (tmp_keydata == NULL && keymgmt1 != NULL && keymgmt1->match != NULL) { tmp_keydata = evp_pkey_export_to_provider((EVP_PKEY *)b, NULL, &keymgmt1, NULL); if (tmp_keydata != NULL) { keymgmt2 = keymgmt1; keydata2 = tmp_keydata; } } /* If we still don't have matching keymgmt implementations, we give up */ if (keymgmt1 != keymgmt2) return -2; /* If the keymgmt implementations are NULL, the export failed */ if (keymgmt1 == NULL) return -2; return evp_keymgmt_match(keymgmt1, keydata1, keydata2, selection); } # ifndef OPENSSL_NO_DEPRECATED_3_0 int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { return EVP_PKEY_parameters_eq(a, b); } #endif int EVP_PKEY_parameters_eq(const EVP_PKEY *a, const EVP_PKEY *b) { /* * This will just call evp_keymgmt_util_match when legacy support * is gone. */ if (a->keymgmt != NULL || b->keymgmt != NULL) return evp_pkey_cmp_any(a, b, SELECT_PARAMETERS); /* All legacy keys */ if (a->type != b->type) return -1; if (a->ameth != NULL && a->ameth->param_cmp != NULL) return a->ameth->param_cmp(a, b); return -2; } # ifndef OPENSSL_NO_DEPRECATED_3_0 int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { return EVP_PKEY_eq(a, b); } #endif int EVP_PKEY_eq(const EVP_PKEY *a, const EVP_PKEY *b) { /* * This will just call evp_keymgmt_util_match when legacy support * is gone. */ /* Trivial shortcuts */ if (a == b) return 1; if (a == NULL || b == NULL) return 0; if (a->keymgmt != NULL || b->keymgmt != NULL) { int selection = SELECT_PARAMETERS; if (evp_keymgmt_util_has((EVP_PKEY *)a, OSSL_KEYMGMT_SELECT_PUBLIC_KEY) && evp_keymgmt_util_has((EVP_PKEY *)b, OSSL_KEYMGMT_SELECT_PUBLIC_KEY)) selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY; else selection |= OSSL_KEYMGMT_SELECT_KEYPAIR; return evp_pkey_cmp_any(a, b, selection); } /* All legacy keys */ if (a->type != b->type) return -1; if (a->ameth != NULL) { int ret; /* Compare parameters if the algorithm has them */ if (a->ameth->param_cmp != NULL) { ret = a->ameth->param_cmp(a, b); if (ret <= 0) return ret; } if (a->ameth->pub_cmp != NULL) return a->ameth->pub_cmp(a, b); } return -2; } static EVP_PKEY *new_raw_key_int(OSSL_LIB_CTX *libctx, const char *strtype, const char *propq, int nidtype, ENGINE *e, const unsigned char *key, size_t len, int key_is_priv) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; const EVP_PKEY_ASN1_METHOD *ameth = NULL; int result = 0; # ifndef OPENSSL_NO_ENGINE /* Check if there is an Engine for this type */ if (e == NULL) { ENGINE *tmpe = NULL; if (strtype != NULL) ameth = EVP_PKEY_asn1_find_str(&tmpe, strtype, -1); else if (nidtype != EVP_PKEY_NONE) ameth = EVP_PKEY_asn1_find(&tmpe, nidtype); /* If tmpe is NULL then no engine is claiming to support this type */ if (tmpe == NULL) ameth = NULL; ENGINE_finish(tmpe); } # endif if (e == NULL && ameth == NULL) { /* * No engine is claiming to support this type, so lets see if we have * a provider. */ ctx = EVP_PKEY_CTX_new_from_name(libctx, strtype != NULL ? strtype : OBJ_nid2sn(nidtype), propq); if (ctx == NULL) goto err; /* May fail if no provider available */ ERR_set_mark(); if (EVP_PKEY_fromdata_init(ctx) == 1) { OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; ERR_clear_last_mark(); params[0] = OSSL_PARAM_construct_octet_string( key_is_priv ? OSSL_PKEY_PARAM_PRIV_KEY : OSSL_PKEY_PARAM_PUB_KEY, (void *)key, len); if (EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) != 1) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); goto err; } EVP_PKEY_CTX_free(ctx); return pkey; } ERR_pop_to_mark(); /* else not supported so fallback to legacy */ } /* Legacy code path */ pkey = EVP_PKEY_new(); if (pkey == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); goto err; } if (!pkey_set_type(pkey, e, nidtype, strtype, -1, NULL)) { /* ERR_raise(ERR_LIB_EVP, ...) already called */ goto err; } if (!ossl_assert(pkey->ameth != NULL)) goto err; if (key_is_priv) { if (pkey->ameth->set_priv_key == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); goto err; } if (!pkey->ameth->set_priv_key(pkey, key, len)) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); goto err; } } else { if (pkey->ameth->set_pub_key == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); goto err; } if (!pkey->ameth->set_pub_key(pkey, key, len)) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); goto err; } } result = 1; err: if (!result) { EVP_PKEY_free(pkey); pkey = NULL; } EVP_PKEY_CTX_free(ctx); return pkey; } EVP_PKEY *EVP_PKEY_new_raw_private_key_ex(OSSL_LIB_CTX *libctx, const char *keytype, const char *propq, const unsigned char *priv, size_t len) { return new_raw_key_int(libctx, keytype, propq, EVP_PKEY_NONE, NULL, priv, len, 1); } EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *e, const unsigned char *priv, size_t len) { return new_raw_key_int(NULL, NULL, NULL, type, e, priv, len, 1); } EVP_PKEY *EVP_PKEY_new_raw_public_key_ex(OSSL_LIB_CTX *libctx, const char *keytype, const char *propq, const unsigned char *pub, size_t len) { return new_raw_key_int(libctx, keytype, propq, EVP_PKEY_NONE, NULL, pub, len, 0); } EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *e, const unsigned char *pub, size_t len) { return new_raw_key_int(NULL, NULL, NULL, type, e, pub, len, 0); } struct raw_key_details_st { unsigned char **key; size_t *len; int selection; }; static OSSL_CALLBACK get_raw_key_details; static int get_raw_key_details(const OSSL_PARAM params[], void *arg) { const OSSL_PARAM *p = NULL; struct raw_key_details_st *raw_key = arg; if (raw_key->selection == OSSL_KEYMGMT_SELECT_PRIVATE_KEY) { if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY)) != NULL) return OSSL_PARAM_get_octet_string(p, (void **)raw_key->key, raw_key->key == NULL ? 0 : *raw_key->len, raw_key->len); } else if (raw_key->selection == OSSL_KEYMGMT_SELECT_PUBLIC_KEY) { if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY)) != NULL) return OSSL_PARAM_get_octet_string(p, (void **)raw_key->key, raw_key->key == NULL ? 0 : *raw_key->len, raw_key->len); } return 0; } int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, unsigned char *priv, size_t *len) { if (pkey->keymgmt != NULL) { struct raw_key_details_st raw_key; raw_key.key = priv == NULL ? NULL : &priv; raw_key.len = len; raw_key.selection = OSSL_KEYMGMT_SELECT_PRIVATE_KEY; return evp_keymgmt_util_export(pkey, OSSL_KEYMGMT_SELECT_PRIVATE_KEY, get_raw_key_details, &raw_key); } if (pkey->ameth == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } if (pkey->ameth->get_priv_key == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } if (!pkey->ameth->get_priv_key(pkey, priv, len)) { ERR_raise(ERR_LIB_EVP, EVP_R_GET_RAW_KEY_FAILED); return 0; } return 1; } int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, unsigned char *pub, size_t *len) { if (pkey->keymgmt != NULL) { struct raw_key_details_st raw_key; raw_key.key = pub == NULL ? NULL : &pub; raw_key.len = len; raw_key.selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY; return evp_keymgmt_util_export(pkey, OSSL_KEYMGMT_SELECT_PUBLIC_KEY, get_raw_key_details, &raw_key); } if (pkey->ameth == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } if (pkey->ameth->get_pub_key == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } if (!pkey->ameth->get_pub_key(pkey, pub, len)) { ERR_raise(ERR_LIB_EVP, EVP_R_GET_RAW_KEY_FAILED); return 0; } return 1; } static EVP_PKEY *new_cmac_key_int(const unsigned char *priv, size_t len, const char *cipher_name, const EVP_CIPHER *cipher, OSSL_LIB_CTX *libctx, const char *propq, ENGINE *e) { # ifndef OPENSSL_NO_CMAC # ifndef OPENSSL_NO_ENGINE const char *engine_id = e != NULL ? ENGINE_get_id(e) : NULL; # endif OSSL_PARAM params[5], *p = params; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx; if (cipher != NULL) cipher_name = EVP_CIPHER_get0_name(cipher); if (cipher_name == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); return NULL; } ctx = EVP_PKEY_CTX_new_from_name(libctx, "CMAC", propq); if (ctx == NULL) goto err; if (EVP_PKEY_fromdata_init(ctx) <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); goto err; } *p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, (void *)priv, len); *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_CIPHER, (char *)cipher_name, 0); if (propq != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_PROPERTIES, (char *)propq, 0); # ifndef OPENSSL_NO_ENGINE if (engine_id != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_ENGINE, (char *)engine_id, 0); # endif *p = OSSL_PARAM_construct_end(); if (EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); goto err; } err: EVP_PKEY_CTX_free(ctx); return pkey; # else ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return NULL; # endif } EVP_PKEY *EVP_PKEY_new_CMAC_key(ENGINE *e, const unsigned char *priv, size_t len, const EVP_CIPHER *cipher) { return new_cmac_key_int(priv, len, NULL, cipher, NULL, NULL, e); } int EVP_PKEY_set_type(EVP_PKEY *pkey, int type) { return pkey_set_type(pkey, NULL, type, NULL, -1, NULL); } int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len) { return pkey_set_type(pkey, NULL, EVP_PKEY_NONE, str, len, NULL); } # ifndef OPENSSL_NO_ENGINE int EVP_PKEY_set1_engine(EVP_PKEY *pkey, ENGINE *e) { if (e != NULL) { if (!ENGINE_init(e)) { ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB); return 0; } if (ENGINE_get_pkey_meth(e, pkey->type) == NULL) { ENGINE_finish(e); ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM); return 0; } } ENGINE_finish(pkey->pmeth_engine); pkey->pmeth_engine = e; return 1; } ENGINE *EVP_PKEY_get0_engine(const EVP_PKEY *pkey) { return pkey->engine; } # endif # ifndef OPENSSL_NO_DEPRECATED_3_0 static void detect_foreign_key(EVP_PKEY *pkey) { switch (pkey->type) { case EVP_PKEY_RSA: case EVP_PKEY_RSA_PSS: pkey->foreign = pkey->pkey.rsa != NULL && ossl_rsa_is_foreign(pkey->pkey.rsa); break; # ifndef OPENSSL_NO_EC case EVP_PKEY_SM2: break; case EVP_PKEY_EC: pkey->foreign = pkey->pkey.ec != NULL && ossl_ec_key_is_foreign(pkey->pkey.ec); break; # endif # ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: pkey->foreign = pkey->pkey.dsa != NULL && ossl_dsa_is_foreign(pkey->pkey.dsa); break; #endif # ifndef OPENSSL_NO_DH case EVP_PKEY_DH: pkey->foreign = pkey->pkey.dh != NULL && ossl_dh_is_foreign(pkey->pkey.dh); break; #endif default: pkey->foreign = 0; break; } } int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key) { # ifndef OPENSSL_NO_EC int pktype; pktype = EVP_PKEY_type(type); if ((key != NULL) && (pktype == EVP_PKEY_EC || pktype == EVP_PKEY_SM2)) { const EC_GROUP *group = EC_KEY_get0_group(key); if (group != NULL) { int curve = EC_GROUP_get_curve_name(group); /* * Regardless of what is requested the SM2 curve must be SM2 type, * and non SM2 curves are EC type. */ if (curve == NID_sm2 && pktype == EVP_PKEY_EC) type = EVP_PKEY_SM2; else if(curve != NID_sm2 && pktype == EVP_PKEY_SM2) type = EVP_PKEY_EC; } } # endif if (pkey == NULL || !EVP_PKEY_set_type(pkey, type)) return 0; pkey->pkey.ptr = key; detect_foreign_key(pkey); return (key != NULL); } # endif void *EVP_PKEY_get0(const EVP_PKEY *pkey) { if (pkey == NULL) return NULL; if (!evp_pkey_is_provided(pkey)) return pkey->pkey.ptr; return NULL; } const unsigned char *EVP_PKEY_get0_hmac(const EVP_PKEY *pkey, size_t *len) { const ASN1_OCTET_STRING *os = NULL; if (pkey->type != EVP_PKEY_HMAC) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_AN_HMAC_KEY); return NULL; } os = evp_pkey_get_legacy((EVP_PKEY *)pkey); if (os != NULL) { *len = os->length; return os->data; } return NULL; } # ifndef OPENSSL_NO_POLY1305 const unsigned char *EVP_PKEY_get0_poly1305(const EVP_PKEY *pkey, size_t *len) { const ASN1_OCTET_STRING *os = NULL; if (pkey->type != EVP_PKEY_POLY1305) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_POLY1305_KEY); return NULL; } os = evp_pkey_get_legacy((EVP_PKEY *)pkey); if (os != NULL) { *len = os->length; return os->data; } return NULL; } # endif # ifndef OPENSSL_NO_SIPHASH const unsigned char *EVP_PKEY_get0_siphash(const EVP_PKEY *pkey, size_t *len) { const ASN1_OCTET_STRING *os = NULL; if (pkey->type != EVP_PKEY_SIPHASH) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_SIPHASH_KEY); return NULL; } os = evp_pkey_get_legacy((EVP_PKEY *)pkey); if (os != NULL) { *len = os->length; return os->data; } return NULL; } # endif # ifndef OPENSSL_NO_DSA static DSA *evp_pkey_get0_DSA_int(const EVP_PKEY *pkey) { if (pkey->type != EVP_PKEY_DSA) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_DSA_KEY); return NULL; } return evp_pkey_get_legacy((EVP_PKEY *)pkey); } const DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey) { return evp_pkey_get0_DSA_int(pkey); } int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key) { int ret = EVP_PKEY_assign_DSA(pkey, key); if (ret) DSA_up_ref(key); return ret; } DSA *EVP_PKEY_get1_DSA(EVP_PKEY *pkey) { DSA *ret = evp_pkey_get0_DSA_int(pkey); if (ret != NULL) DSA_up_ref(ret); return ret; } # endif /* OPENSSL_NO_DSA */ # ifndef OPENSSL_NO_ECX static const ECX_KEY *evp_pkey_get0_ECX_KEY(const EVP_PKEY *pkey, int type) { if (EVP_PKEY_get_base_id(pkey) != type) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_ECX_KEY); return NULL; } return evp_pkey_get_legacy((EVP_PKEY *)pkey); } static ECX_KEY *evp_pkey_get1_ECX_KEY(EVP_PKEY *pkey, int type) { ECX_KEY *ret = (ECX_KEY *)evp_pkey_get0_ECX_KEY(pkey, type); if (ret != NULL && !ossl_ecx_key_up_ref(ret)) ret = NULL; return ret; } # define IMPLEMENT_ECX_VARIANT(NAME) \ ECX_KEY *ossl_evp_pkey_get1_##NAME(EVP_PKEY *pkey) \ { \ return evp_pkey_get1_ECX_KEY(pkey, EVP_PKEY_##NAME); \ } IMPLEMENT_ECX_VARIANT(X25519) IMPLEMENT_ECX_VARIANT(X448) IMPLEMENT_ECX_VARIANT(ED25519) IMPLEMENT_ECX_VARIANT(ED448) # endif /* OPENSSL_NO_ECX */ # if !defined(OPENSSL_NO_DH) && !defined(OPENSSL_NO_DEPRECATED_3_0) int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *dhkey) { int ret, type; /* * ossl_dh_is_named_safe_prime_group() returns 1 for named safe prime groups * related to ffdhe and modp (which cache q = (p - 1) / 2), * and returns 0 for all other dh parameter generation types including * RFC5114 named groups. * * The EVP_PKEY_DH type is used for dh parameter generation types: * - named safe prime groups related to ffdhe and modp * - safe prime generator * * The type EVP_PKEY_DHX is used for dh parameter generation types * - fips186-4 and fips186-2 * - rfc5114 named groups. * * The EVP_PKEY_DH type is used to save PKCS#3 data than can be stored * without a q value. * The EVP_PKEY_DHX type is used to save X9.42 data that requires the * q value to be stored. */ if (ossl_dh_is_named_safe_prime_group(dhkey)) type = EVP_PKEY_DH; else type = DH_get0_q(dhkey) == NULL ? EVP_PKEY_DH : EVP_PKEY_DHX; ret = EVP_PKEY_assign(pkey, type, dhkey); if (ret) DH_up_ref(dhkey); return ret; } DH *evp_pkey_get0_DH_int(const EVP_PKEY *pkey) { if (pkey->type != EVP_PKEY_DH && pkey->type != EVP_PKEY_DHX) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_DH_KEY); return NULL; } return evp_pkey_get_legacy((EVP_PKEY *)pkey); } const DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey) { return evp_pkey_get0_DH_int(pkey); } DH *EVP_PKEY_get1_DH(EVP_PKEY *pkey) { DH *ret = evp_pkey_get0_DH_int(pkey); if (ret != NULL) DH_up_ref(ret); return ret; } # endif int EVP_PKEY_type(int type) { int ret; const EVP_PKEY_ASN1_METHOD *ameth; ENGINE *e; ameth = EVP_PKEY_asn1_find(&e, type); if (ameth) ret = ameth->pkey_id; else ret = NID_undef; # ifndef OPENSSL_NO_ENGINE ENGINE_finish(e); # endif return ret; } int EVP_PKEY_get_id(const EVP_PKEY *pkey) { return pkey->type; } int EVP_PKEY_get_base_id(const EVP_PKEY *pkey) { return EVP_PKEY_type(pkey->type); } /* * These hard coded cases are pure hackery to get around the fact * that names in crypto/objects/objects.txt are a mess. There is * no "EC", and "RSA" leads to the NID for 2.5.8.1.1, an OID that's * fallen out in favor of { pkcs-1 1 }, i.e. 1.2.840.113549.1.1.1, * the NID of which is used for EVP_PKEY_RSA. Strangely enough, * "DSA" is accurate... but still, better be safe and hard-code * names that we know. * On a similar topic, EVP_PKEY_type(EVP_PKEY_SM2) will result in * EVP_PKEY_EC, because of aliasing. * This should be cleaned away along with all other #legacy support. */ static const OSSL_ITEM standard_name2type[] = { { EVP_PKEY_RSA, "RSA" }, { EVP_PKEY_RSA_PSS, "RSA-PSS" }, { EVP_PKEY_EC, "EC" }, { EVP_PKEY_ED25519, "ED25519" }, { EVP_PKEY_ED448, "ED448" }, { EVP_PKEY_X25519, "X25519" }, { EVP_PKEY_X448, "X448" }, { EVP_PKEY_SM2, "SM2" }, { EVP_PKEY_DH, "DH" }, { EVP_PKEY_DHX, "X9.42 DH" }, { EVP_PKEY_DHX, "DHX" }, { EVP_PKEY_DSA, "DSA" }, }; int evp_pkey_name2type(const char *name) { int type; size_t i; for (i = 0; i < OSSL_NELEM(standard_name2type); i++) { if (OPENSSL_strcasecmp(name, standard_name2type[i].ptr) == 0) return (int)standard_name2type[i].id; } if ((type = EVP_PKEY_type(OBJ_sn2nid(name))) != NID_undef) return type; return EVP_PKEY_type(OBJ_ln2nid(name)); } const char *evp_pkey_type2name(int type) { size_t i; for (i = 0; i < OSSL_NELEM(standard_name2type); i++) { if (type == (int)standard_name2type[i].id) return standard_name2type[i].ptr; } return OBJ_nid2sn(type); } int EVP_PKEY_is_a(const EVP_PKEY *pkey, const char *name) { if (pkey == NULL) return 0; if (pkey->keymgmt == NULL) return pkey->type == evp_pkey_name2type(name); return EVP_KEYMGMT_is_a(pkey->keymgmt, name); } int EVP_PKEY_type_names_do_all(const EVP_PKEY *pkey, void (*fn)(const char *name, void *data), void *data) { if (!evp_pkey_is_typed(pkey)) return 0; if (!evp_pkey_is_provided(pkey)) { const char *name = OBJ_nid2sn(EVP_PKEY_get_id(pkey)); fn(name, data); return 1; } return EVP_KEYMGMT_names_do_all(pkey->keymgmt, fn, data); } int EVP_PKEY_can_sign(const EVP_PKEY *pkey) { if (pkey->keymgmt == NULL) { switch (EVP_PKEY_get_base_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA_PSS: return 1; # ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: return 1; # endif # ifndef OPENSSL_NO_EC case EVP_PKEY_ED25519: case EVP_PKEY_ED448: return 1; case EVP_PKEY_EC: /* Including SM2 */ return EC_KEY_can_sign(pkey->pkey.ec); # endif default: break; } } else { const OSSL_PROVIDER *prov = EVP_KEYMGMT_get0_provider(pkey->keymgmt); OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); const char *supported_sig = pkey->keymgmt->query_operation_name != NULL ? pkey->keymgmt->query_operation_name(OSSL_OP_SIGNATURE) : EVP_KEYMGMT_get0_name(pkey->keymgmt); EVP_SIGNATURE *signature = NULL; signature = EVP_SIGNATURE_fetch(libctx, supported_sig, NULL); if (signature != NULL) { EVP_SIGNATURE_free(signature); return 1; } } return 0; } static int print_reset_indent(BIO **out, int pop_f_prefix, long saved_indent) { BIO_set_indent(*out, saved_indent); if (pop_f_prefix) { BIO *next = BIO_pop(*out); BIO_free(*out); *out = next; } return 1; } static int print_set_indent(BIO **out, int *pop_f_prefix, long *saved_indent, long indent) { *pop_f_prefix = 0; *saved_indent = 0; if (indent > 0) { long i = BIO_get_indent(*out); *saved_indent = (i < 0 ? 0 : i); if (BIO_set_indent(*out, indent) <= 0) { BIO *prefbio = BIO_new(BIO_f_prefix()); if (prefbio == NULL) return 0; *out = BIO_push(prefbio, *out); *pop_f_prefix = 1; } if (BIO_set_indent(*out, indent) <= 0) { print_reset_indent(out, *pop_f_prefix, *saved_indent); return 0; } } return 1; } static int unsup_alg(BIO *out, const EVP_PKEY *pkey, int indent, const char *kstr) { return BIO_indent(out, indent, 128) && BIO_printf(out, "%s algorithm \"%s\" unsupported\n", kstr, OBJ_nid2ln(pkey->type)) > 0; } static int print_pkey(const EVP_PKEY *pkey, BIO *out, int indent, int selection /* For provided encoding */, const char *propquery /* For provided encoding */, int (*legacy_print)(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx), ASN1_PCTX *legacy_pctx /* For legacy print */) { int pop_f_prefix; long saved_indent; OSSL_ENCODER_CTX *ctx = NULL; int ret = -2; /* default to unsupported */ if (!print_set_indent(&out, &pop_f_prefix, &saved_indent, indent)) return 0; ctx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, "TEXT", NULL, propquery); if (OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0) ret = OSSL_ENCODER_to_bio(ctx, out); OSSL_ENCODER_CTX_free(ctx); if (ret != -2) goto end; /* legacy fallback */ if (legacy_print != NULL) ret = legacy_print(out, pkey, 0, legacy_pctx); else ret = unsup_alg(out, pkey, 0, "Public Key"); end: print_reset_indent(&out, pop_f_prefix, saved_indent); return ret; } int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { return print_pkey(pkey, out, indent, EVP_PKEY_PUBLIC_KEY, NULL, (pkey->ameth != NULL ? pkey->ameth->pub_print : NULL), pctx); } int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { return print_pkey(pkey, out, indent, EVP_PKEY_PRIVATE_KEY, NULL, (pkey->ameth != NULL ? pkey->ameth->priv_print : NULL), pctx); } int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { return print_pkey(pkey, out, indent, EVP_PKEY_KEY_PARAMETERS, NULL, (pkey->ameth != NULL ? pkey->ameth->param_print : NULL), pctx); } # ifndef OPENSSL_NO_STDIO int EVP_PKEY_print_public_fp(FILE *fp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { int ret; BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); if (b == NULL) return 0; ret = EVP_PKEY_print_public(b, pkey, indent, pctx); BIO_free(b); return ret; } int EVP_PKEY_print_private_fp(FILE *fp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { int ret; BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); if (b == NULL) return 0; ret = EVP_PKEY_print_private(b, pkey, indent, pctx); BIO_free(b); return ret; } int EVP_PKEY_print_params_fp(FILE *fp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { int ret; BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); if (b == NULL) return 0; ret = EVP_PKEY_print_params(b, pkey, indent, pctx); BIO_free(b); return ret; } # endif static void mdname2nid(const char *mdname, void *data) { int *nid = (int *)data; if (*nid != NID_undef) return; *nid = OBJ_sn2nid(mdname); if (*nid == NID_undef) *nid = OBJ_ln2nid(mdname); } static int legacy_asn1_ctrl_to_param(EVP_PKEY *pkey, int op, int arg1, void *arg2) { if (pkey->keymgmt == NULL) return 0; switch (op) { case ASN1_PKEY_CTRL_DEFAULT_MD_NID: { char mdname[80] = ""; int rv = EVP_PKEY_get_default_digest_name(pkey, mdname, sizeof(mdname)); if (rv > 0) { int mdnum; OSSL_LIB_CTX *libctx = ossl_provider_libctx(pkey->keymgmt->prov); /* Make sure the MD is in the namemap if available */ EVP_MD *md; OSSL_NAMEMAP *namemap; int nid = NID_undef; (void)ERR_set_mark(); md = EVP_MD_fetch(libctx, mdname, NULL); (void)ERR_pop_to_mark(); namemap = ossl_namemap_stored(libctx); /* * The only reason to fetch the MD was to make sure it is in the * namemap. We can immediately free it. */ EVP_MD_free(md); mdnum = ossl_namemap_name2num(namemap, mdname); if (mdnum == 0) return 0; /* * We have the namemap number - now we need to find the * associated nid */ if (!ossl_namemap_doall_names(namemap, mdnum, mdname2nid, &nid)) return 0; *(int *)arg2 = nid; } return rv; } default: return -2; } } static int evp_pkey_asn1_ctrl(EVP_PKEY *pkey, int op, int arg1, void *arg2) { if (pkey->ameth == NULL) return legacy_asn1_ctrl_to_param(pkey, op, arg1, arg2); if (pkey->ameth->pkey_ctrl == NULL) return -2; return pkey->ameth->pkey_ctrl(pkey, op, arg1, arg2); } int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid) { if (pkey == NULL) return 0; return evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_DEFAULT_MD_NID, 0, pnid); } int EVP_PKEY_get_default_digest_name(EVP_PKEY *pkey, char *mdname, size_t mdname_sz) { if (pkey->ameth == NULL) return evp_keymgmt_util_get_deflt_digest_name(pkey->keymgmt, pkey->keydata, mdname, mdname_sz); { int nid = NID_undef; int rv = EVP_PKEY_get_default_digest_nid(pkey, &nid); const char *name = rv > 0 ? OBJ_nid2sn(nid) : NULL; if (rv > 0) OPENSSL_strlcpy(mdname, name, mdname_sz); return rv; } } int EVP_PKEY_get_group_name(const EVP_PKEY *pkey, char *gname, size_t gname_sz, size_t *gname_len) { return EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_GROUP_NAME, gname, gname_sz, gname_len); } int EVP_PKEY_digestsign_supports_digest(EVP_PKEY *pkey, OSSL_LIB_CTX *libctx, const char *name, const char *propq) { int rv; EVP_MD_CTX *ctx = NULL; if ((ctx = EVP_MD_CTX_new()) == NULL) return -1; ERR_set_mark(); rv = EVP_DigestSignInit_ex(ctx, NULL, name, libctx, propq, pkey, NULL); ERR_pop_to_mark(); EVP_MD_CTX_free(ctx); return rv; } int EVP_PKEY_set1_encoded_public_key(EVP_PKEY *pkey, const unsigned char *pub, size_t publen) { if (pkey == NULL) return 0; if (evp_pkey_is_provided(pkey)) return EVP_PKEY_set_octet_string_param(pkey, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, (unsigned char *)pub, publen); if (publen > INT_MAX) return 0; /* Historically this function was EVP_PKEY_set1_tls_encodedpoint */ if (evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SET1_TLS_ENCPT, publen, (void *)pub) <= 0) return 0; return 1; } size_t EVP_PKEY_get1_encoded_public_key(EVP_PKEY *pkey, unsigned char **ppub) { int rv; if (pkey == NULL) return 0; if (evp_pkey_is_provided(pkey)) { size_t return_size = OSSL_PARAM_UNMODIFIED; unsigned char *buf; /* * We know that this is going to fail, but it will give us a size * to allocate. */ EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0, &return_size); if (return_size == OSSL_PARAM_UNMODIFIED) return 0; *ppub = NULL; buf = OPENSSL_malloc(return_size); if (buf == NULL) return 0; if (!EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, buf, return_size, NULL)) { OPENSSL_free(buf); return 0; } *ppub = buf; return return_size; } rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_GET1_TLS_ENCPT, 0, ppub); if (rv <= 0) return 0; return rv; } #endif /* FIPS_MODULE */ /*- All methods below can also be used in FIPS_MODULE */ EVP_PKEY *EVP_PKEY_new(void) { EVP_PKEY *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->type = EVP_PKEY_NONE; ret->save_type = EVP_PKEY_NONE; if (!CRYPTO_NEW_REF(&ret->references, 1)) goto err; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_CRYPTO_LIB); goto err; } #ifndef FIPS_MODULE ret->save_parameters = 1; if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, ret, &ret->ex_data)) { ERR_raise(ERR_LIB_EVP, ERR_R_CRYPTO_LIB); goto err; } #endif return ret; err: CRYPTO_FREE_REF(&ret->references); CRYPTO_THREAD_lock_free(ret->lock); OPENSSL_free(ret); return NULL; } /* * Setup a public key management method. * * For legacy keys, either |type| or |str| is expected to have the type * information. In this case, the setup consists of finding an ASN1 method * and potentially an ENGINE, and setting those fields in |pkey|. * * For provider side keys, |keymgmt| is expected to be non-NULL. In this * case, the setup consists of setting the |keymgmt| field in |pkey|. * * If pkey is NULL just return 1 or 0 if the key management method exists. */ static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str, int len, EVP_KEYMGMT *keymgmt) { #ifndef FIPS_MODULE const EVP_PKEY_ASN1_METHOD *ameth = NULL; ENGINE **eptr = (e == NULL) ? &e : NULL; #endif /* * The setups can't set both legacy and provider side methods. * It is forbidden */ if (!ossl_assert(type == EVP_PKEY_NONE || keymgmt == NULL) || !ossl_assert(e == NULL || keymgmt == NULL)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } if (pkey != NULL) { int free_it = 0; #ifndef FIPS_MODULE free_it = free_it || pkey->pkey.ptr != NULL; #endif free_it = free_it || pkey->keydata != NULL; if (free_it) evp_pkey_free_it(pkey); #ifndef FIPS_MODULE /* * If key type matches and a method exists then this lookup has * succeeded once so just indicate success. */ if (pkey->type != EVP_PKEY_NONE && type == pkey->save_type && pkey->ameth != NULL) return 1; # ifndef OPENSSL_NO_ENGINE /* If we have ENGINEs release them */ ENGINE_finish(pkey->engine); pkey->engine = NULL; ENGINE_finish(pkey->pmeth_engine); pkey->pmeth_engine = NULL; # endif #endif } #ifndef FIPS_MODULE if (str != NULL) ameth = EVP_PKEY_asn1_find_str(eptr, str, len); else if (type != EVP_PKEY_NONE) ameth = EVP_PKEY_asn1_find(eptr, type); # ifndef OPENSSL_NO_ENGINE if (pkey == NULL && eptr != NULL) ENGINE_finish(e); # endif #endif { int check = 1; #ifndef FIPS_MODULE check = check && ameth == NULL; #endif check = check && keymgmt == NULL; if (check) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM); return 0; } } if (pkey != NULL) { if (keymgmt != NULL && !EVP_KEYMGMT_up_ref(keymgmt)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } pkey->keymgmt = keymgmt; pkey->save_type = type; pkey->type = type; #ifndef FIPS_MODULE /* * If the internal "origin" key is provider side, don't save |ameth|. * The main reason is that |ameth| is one factor to detect that the * internal "origin" key is a legacy one. */ if (keymgmt == NULL) pkey->ameth = ameth; /* * The EVP_PKEY_ASN1_METHOD |pkey_id| retains its legacy key purpose * for any key type that has a legacy implementation, regardless of * if the internal key is a legacy or a provider side one. When * there is no legacy implementation for the key, the type becomes * EVP_PKEY_KEYMGMT, which indicates that one should be cautious * with functions that expect legacy internal keys. */ if (ameth != NULL) { if (type == EVP_PKEY_NONE) pkey->type = ameth->pkey_id; } else { pkey->type = EVP_PKEY_KEYMGMT; } # ifndef OPENSSL_NO_ENGINE if (eptr == NULL && e != NULL && !ENGINE_init(e)) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } # endif pkey->engine = e; #endif } return 1; } #ifndef FIPS_MODULE static void find_ameth(const char *name, void *data) { const char **str = data; /* * The error messages from pkey_set_type() are uninteresting here, * and misleading. */ ERR_set_mark(); if (pkey_set_type(NULL, NULL, EVP_PKEY_NONE, name, strlen(name), NULL)) { if (str[0] == NULL) str[0] = name; else if (str[1] == NULL) str[1] = name; } ERR_pop_to_mark(); } #endif int EVP_PKEY_set_type_by_keymgmt(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt) { #ifndef FIPS_MODULE # define EVP_PKEY_TYPE_STR str[0] # define EVP_PKEY_TYPE_STRLEN (str[0] == NULL ? -1 : (int)strlen(str[0])) /* * Find at most two strings that have an associated EVP_PKEY_ASN1_METHOD * Ideally, only one should be found. If two (or more) are found, the * match is ambiguous. This should never happen, but... */ const char *str[2] = { NULL, NULL }; if (!EVP_KEYMGMT_names_do_all(keymgmt, find_ameth, &str) || str[1] != NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } #else # define EVP_PKEY_TYPE_STR NULL # define EVP_PKEY_TYPE_STRLEN -1 #endif return pkey_set_type(pkey, NULL, EVP_PKEY_NONE, EVP_PKEY_TYPE_STR, EVP_PKEY_TYPE_STRLEN, keymgmt); #undef EVP_PKEY_TYPE_STR #undef EVP_PKEY_TYPE_STRLEN } int EVP_PKEY_up_ref(EVP_PKEY *pkey) { int i; if (CRYPTO_UP_REF(&pkey->references, &i) <= 0) return 0; REF_PRINT_COUNT("EVP_PKEY", pkey); REF_ASSERT_ISNT(i < 2); return ((i > 1) ? 1 : 0); } #ifndef FIPS_MODULE EVP_PKEY *EVP_PKEY_dup(EVP_PKEY *pkey) { EVP_PKEY *dup_pk; if (pkey == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((dup_pk = EVP_PKEY_new()) == NULL) return NULL; if (evp_pkey_is_blank(pkey)) goto done; if (evp_pkey_is_provided(pkey)) { if (!evp_keymgmt_util_copy(dup_pk, pkey, OSSL_KEYMGMT_SELECT_ALL)) goto err; goto done; } if (evp_pkey_is_legacy(pkey)) { const EVP_PKEY_ASN1_METHOD *ameth = pkey->ameth; if (ameth == NULL || ameth->copy == NULL) { if (pkey->pkey.ptr == NULL /* empty key, just set type */ && EVP_PKEY_set_type(dup_pk, pkey->type) != 0) goto done; ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); goto err; } if (!ameth->copy(dup_pk, pkey)) goto err; goto done; } goto err; done: /* copy auxiliary data */ if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, &dup_pk->ex_data, &pkey->ex_data)) goto err; if (pkey->attributes != NULL) { if ((dup_pk->attributes = ossl_x509at_dup(pkey->attributes)) == NULL) goto err; } return dup_pk; err: EVP_PKEY_free(dup_pk); return NULL; } void evp_pkey_free_legacy(EVP_PKEY *x) { const EVP_PKEY_ASN1_METHOD *ameth = x->ameth; ENGINE *tmpe = NULL; if (ameth == NULL && x->legacy_cache_pkey.ptr != NULL) ameth = EVP_PKEY_asn1_find(&tmpe, x->type); if (ameth != NULL) { if (x->legacy_cache_pkey.ptr != NULL) { /* * We should never have both a legacy origin key, and a key in the * legacy cache. */ assert(x->pkey.ptr == NULL); /* * For the purposes of freeing we make the legacy cache look like * a legacy origin key. */ x->pkey = x->legacy_cache_pkey; x->legacy_cache_pkey.ptr = NULL; } if (ameth->pkey_free != NULL) ameth->pkey_free(x); x->pkey.ptr = NULL; } # ifndef OPENSSL_NO_ENGINE ENGINE_finish(tmpe); ENGINE_finish(x->engine); x->engine = NULL; ENGINE_finish(x->pmeth_engine); x->pmeth_engine = NULL; # endif } #endif /* FIPS_MODULE */ static void evp_pkey_free_it(EVP_PKEY *x) { /* internal function; x is never NULL */ evp_keymgmt_util_clear_operation_cache(x); #ifndef FIPS_MODULE evp_pkey_free_legacy(x); #endif if (x->keymgmt != NULL) { evp_keymgmt_freedata(x->keymgmt, x->keydata); EVP_KEYMGMT_free(x->keymgmt); x->keymgmt = NULL; x->keydata = NULL; } x->type = EVP_PKEY_NONE; } void EVP_PKEY_free(EVP_PKEY *x) { int i; if (x == NULL) return; CRYPTO_DOWN_REF(&x->references, &i); REF_PRINT_COUNT("EVP_PKEY", x); if (i > 0) return; REF_ASSERT_ISNT(i < 0); evp_pkey_free_it(x); #ifndef FIPS_MODULE CRYPTO_free_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, x, &x->ex_data); #endif CRYPTO_THREAD_lock_free(x->lock); CRYPTO_FREE_REF(&x->references); #ifndef FIPS_MODULE sk_X509_ATTRIBUTE_pop_free(x->attributes, X509_ATTRIBUTE_free); #endif OPENSSL_free(x); } int EVP_PKEY_get_size(const EVP_PKEY *pkey) { int size = 0; if (pkey != NULL) { size = pkey->cache.size; #ifndef FIPS_MODULE if (pkey->ameth != NULL && pkey->ameth->pkey_size != NULL) size = pkey->ameth->pkey_size(pkey); #endif } if (size <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_UNKNOWN_MAX_SIZE); return 0; } return size; } const char *EVP_PKEY_get0_description(const EVP_PKEY *pkey) { if (!evp_pkey_is_assigned(pkey)) return NULL; if (evp_pkey_is_provided(pkey) && pkey->keymgmt->description != NULL) return pkey->keymgmt->description; #ifndef FIPS_MODULE if (pkey->ameth != NULL) return pkey->ameth->info; #endif return NULL; } void *evp_pkey_export_to_provider(EVP_PKEY *pk, OSSL_LIB_CTX *libctx, EVP_KEYMGMT **keymgmt, const char *propquery) { EVP_KEYMGMT *allocated_keymgmt = NULL; EVP_KEYMGMT *tmp_keymgmt = NULL; int selection = OSSL_KEYMGMT_SELECT_ALL; void *keydata = NULL; int check; if (pk == NULL) return NULL; /* No key data => nothing to export */ check = 1; #ifndef FIPS_MODULE check = check && pk->pkey.ptr == NULL; #endif check = check && pk->keydata == NULL; if (check) return NULL; #ifndef FIPS_MODULE if (pk->pkey.ptr != NULL) { /* * If the legacy key doesn't have an dirty counter or export function, * give up */ if (pk->ameth->dirty_cnt == NULL || pk->ameth->export_to == NULL) return NULL; } #endif if (keymgmt != NULL) { tmp_keymgmt = *keymgmt; *keymgmt = NULL; } /* * If no keymgmt was given or found, get a default keymgmt. We do so by * letting EVP_PKEY_CTX_new_from_pkey() do it for us, then we steal it. */ if (tmp_keymgmt == NULL) { EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery); if (ctx == NULL) goto end; allocated_keymgmt = tmp_keymgmt = ctx->keymgmt; ctx->keymgmt = NULL; EVP_PKEY_CTX_free(ctx); } /* If there's still no keymgmt to be had, give up */ if (tmp_keymgmt == NULL) goto end; #ifndef FIPS_MODULE if (pk->pkey.ptr != NULL) { OP_CACHE_ELEM *op; /* * If the legacy "origin" hasn't changed since last time, we try * to find our keymgmt in the operation cache. If it has changed, * |i| remains zero, and we will clear the cache further down. */ if (pk->ameth->dirty_cnt(pk) == pk->dirty_cnt_copy) { if (!CRYPTO_THREAD_read_lock(pk->lock)) goto end; op = evp_keymgmt_util_find_operation_cache(pk, tmp_keymgmt, selection); /* * If |tmp_keymgmt| is present in the operation cache, it means * that export doesn't need to be redone. In that case, we take * token copies of the cached pointers, to have token success * values to return. */ if (op != NULL && op->keymgmt != NULL) { keydata = op->keydata; CRYPTO_THREAD_unlock(pk->lock); goto end; } CRYPTO_THREAD_unlock(pk->lock); } /* Make sure that the keymgmt key type matches the legacy NID */ if (!EVP_KEYMGMT_is_a(tmp_keymgmt, OBJ_nid2sn(pk->type))) goto end; if ((keydata = evp_keymgmt_newdata(tmp_keymgmt)) == NULL) goto end; if (!pk->ameth->export_to(pk, keydata, tmp_keymgmt->import, libctx, propquery)) { evp_keymgmt_freedata(tmp_keymgmt, keydata); keydata = NULL; goto end; } /* * If the dirty counter changed since last time, then clear the * operation cache. In that case, we know that |i| is zero. Just * in case this is a re-export, we increment then decrement the * keymgmt reference counter. */ if (!EVP_KEYMGMT_up_ref(tmp_keymgmt)) { /* refcnt++ */ evp_keymgmt_freedata(tmp_keymgmt, keydata); keydata = NULL; goto end; } if (!CRYPTO_THREAD_write_lock(pk->lock)) goto end; if (pk->ameth->dirty_cnt(pk) != pk->dirty_cnt_copy && !evp_keymgmt_util_clear_operation_cache(pk)) { CRYPTO_THREAD_unlock(pk->lock); evp_keymgmt_freedata(tmp_keymgmt, keydata); keydata = NULL; EVP_KEYMGMT_free(tmp_keymgmt); goto end; } EVP_KEYMGMT_free(tmp_keymgmt); /* refcnt-- */ /* Check to make sure some other thread didn't get there first */ op = evp_keymgmt_util_find_operation_cache(pk, tmp_keymgmt, selection); if (op != NULL && op->keymgmt != NULL) { void *tmp_keydata = op->keydata; CRYPTO_THREAD_unlock(pk->lock); evp_keymgmt_freedata(tmp_keymgmt, keydata); keydata = tmp_keydata; goto end; } /* Add the new export to the operation cache */ if (!evp_keymgmt_util_cache_keydata(pk, tmp_keymgmt, keydata, selection)) { CRYPTO_THREAD_unlock(pk->lock); evp_keymgmt_freedata(tmp_keymgmt, keydata); keydata = NULL; goto end; } /* Synchronize the dirty count */ pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk); CRYPTO_THREAD_unlock(pk->lock); goto end; } #endif /* FIPS_MODULE */ keydata = evp_keymgmt_util_export_to_provider(pk, tmp_keymgmt, selection); end: /* * If nothing was exported, |tmp_keymgmt| might point at a freed * EVP_KEYMGMT, so we clear it to be safe. It shouldn't be useful for * the caller either way in that case. */ if (keydata == NULL) tmp_keymgmt = NULL; if (keymgmt != NULL && tmp_keymgmt != NULL) { *keymgmt = tmp_keymgmt; allocated_keymgmt = NULL; } EVP_KEYMGMT_free(allocated_keymgmt); return keydata; } #ifndef FIPS_MODULE int evp_pkey_copy_downgraded(EVP_PKEY **dest, const EVP_PKEY *src) { EVP_PKEY *allocpkey = NULL; if (!ossl_assert(dest != NULL)) return 0; if (evp_pkey_is_assigned(src) && evp_pkey_is_provided(src)) { EVP_KEYMGMT *keymgmt = src->keymgmt; void *keydata = src->keydata; int type = src->type; const char *keytype = NULL; keytype = EVP_KEYMGMT_get0_name(keymgmt); /* * If the type is EVP_PKEY_NONE, then we have a problem somewhere * else in our code. If it's not one of the well known EVP_PKEY_xxx * values, it should at least be EVP_PKEY_KEYMGMT at this point. * The check is kept as a safety measure. */ if (!ossl_assert(type != EVP_PKEY_NONE)) { ERR_raise_data(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR, "keymgmt key type = %s but legacy type = EVP_PKEY_NONE", keytype); return 0; } /* Prefer the legacy key type name for error reporting */ if (type != EVP_PKEY_KEYMGMT) keytype = OBJ_nid2sn(type); /* Make sure we have a clean slate to copy into */ if (*dest == NULL) { allocpkey = *dest = EVP_PKEY_new(); if (*dest == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); return 0; } } else { evp_pkey_free_it(*dest); } if (EVP_PKEY_set_type(*dest, type)) { /* If the key is typed but empty, we're done */ if (keydata == NULL) return 1; if ((*dest)->ameth->import_from == NULL) { ERR_raise_data(ERR_LIB_EVP, EVP_R_NO_IMPORT_FUNCTION, "key type = %s", keytype); } else { /* * We perform the export in the same libctx as the keymgmt * that we are using. */ OSSL_LIB_CTX *libctx = ossl_provider_libctx(keymgmt->prov); EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_pkey(libctx, *dest, NULL); if (pctx == NULL) ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB); if (pctx != NULL && evp_keymgmt_export(keymgmt, keydata, OSSL_KEYMGMT_SELECT_ALL, (*dest)->ameth->import_from, pctx)) { /* Synchronize the dirty count */ (*dest)->dirty_cnt_copy = (*dest)->ameth->dirty_cnt(*dest); EVP_PKEY_CTX_free(pctx); return 1; } EVP_PKEY_CTX_free(pctx); } ERR_raise_data(ERR_LIB_EVP, EVP_R_KEYMGMT_EXPORT_FAILURE, "key type = %s", keytype); } } if (allocpkey != NULL) { EVP_PKEY_free(allocpkey); *dest = NULL; } return 0; } void *evp_pkey_get_legacy(EVP_PKEY *pk) { EVP_PKEY *tmp_copy = NULL; void *ret = NULL; if (!ossl_assert(pk != NULL)) return NULL; /* * If this isn't an assigned provider side key, we just use any existing * origin legacy key. */ if (!evp_pkey_is_assigned(pk)) return NULL; if (!evp_pkey_is_provided(pk)) return pk->pkey.ptr; if (!CRYPTO_THREAD_read_lock(pk->lock)) return NULL; ret = pk->legacy_cache_pkey.ptr; if (!CRYPTO_THREAD_unlock(pk->lock)) return NULL; if (ret != NULL) return ret; if (!evp_pkey_copy_downgraded(&tmp_copy, pk)) goto err; if (!CRYPTO_THREAD_write_lock(pk->lock)) goto err; /* Check again in case some other thread has updated it in the meantime */ ret = pk->legacy_cache_pkey.ptr; if (ret == NULL) { /* Steal the legacy key reference from the temporary copy */ ret = pk->legacy_cache_pkey.ptr = tmp_copy->pkey.ptr; tmp_copy->pkey.ptr = NULL; } if (!CRYPTO_THREAD_unlock(pk->lock)) { ret = NULL; goto err; } err: EVP_PKEY_free(tmp_copy); return ret; } #endif /* FIPS_MODULE */ int EVP_PKEY_get_bn_param(const EVP_PKEY *pkey, const char *key_name, BIGNUM **bn) { int ret = 0; OSSL_PARAM params[2]; unsigned char buffer[2048]; unsigned char *buf = NULL; size_t buf_sz = 0; if (key_name == NULL || bn == NULL) return 0; memset(buffer, 0, sizeof(buffer)); params[0] = OSSL_PARAM_construct_BN(key_name, buffer, sizeof(buffer)); params[1] = OSSL_PARAM_construct_end(); if (!EVP_PKEY_get_params(pkey, params)) { if (!OSSL_PARAM_modified(params) || params[0].return_size == 0) return 0; buf_sz = params[0].return_size; /* * If it failed because the buffer was too small then allocate the * required buffer size and retry. */ buf = OPENSSL_zalloc(buf_sz); if (buf == NULL) return 0; params[0].data = buf; params[0].data_size = buf_sz; if (!EVP_PKEY_get_params(pkey, params)) goto err; } /* Fail if the param was not found */ if (!OSSL_PARAM_modified(params)) goto err; ret = OSSL_PARAM_get_BN(params, bn); err: if (buf != NULL) { if (OSSL_PARAM_modified(params)) OPENSSL_clear_free(buf, buf_sz); else OPENSSL_free(buf); } else if (OSSL_PARAM_modified(params)) { OPENSSL_cleanse(buffer, params[0].data_size); } return ret; } int EVP_PKEY_get_octet_string_param(const EVP_PKEY *pkey, const char *key_name, unsigned char *buf, size_t max_buf_sz, size_t *out_len) { OSSL_PARAM params[2]; int ret1 = 0, ret2 = 0; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_octet_string(key_name, buf, max_buf_sz); params[1] = OSSL_PARAM_construct_end(); if ((ret1 = EVP_PKEY_get_params(pkey, params))) ret2 = OSSL_PARAM_modified(params); if (ret2 && out_len != NULL) *out_len = params[0].return_size; return ret1 && ret2; } int EVP_PKEY_get_utf8_string_param(const EVP_PKEY *pkey, const char *key_name, char *str, size_t max_buf_sz, size_t *out_len) { OSSL_PARAM params[2]; int ret1 = 0, ret2 = 0; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_utf8_string(key_name, str, max_buf_sz); params[1] = OSSL_PARAM_construct_end(); if ((ret1 = EVP_PKEY_get_params(pkey, params))) ret2 = OSSL_PARAM_modified(params); if (ret2 && out_len != NULL) *out_len = params[0].return_size; if (ret2 && params[0].return_size == max_buf_sz) /* There was no space for a NUL byte */ return 0; /* Add a terminating NUL byte for good measure */ if (ret2 && str != NULL) str[params[0].return_size] = '\0'; return ret1 && ret2; } int EVP_PKEY_get_int_param(const EVP_PKEY *pkey, const char *key_name, int *out) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_int(key_name, out); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_get_params(pkey, params) && OSSL_PARAM_modified(params); } int EVP_PKEY_get_size_t_param(const EVP_PKEY *pkey, const char *key_name, size_t *out) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_size_t(key_name, out); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_get_params(pkey, params) && OSSL_PARAM_modified(params); } int EVP_PKEY_set_int_param(EVP_PKEY *pkey, const char *key_name, int in) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_int(key_name, &in); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_set_params(pkey, params); } int EVP_PKEY_set_size_t_param(EVP_PKEY *pkey, const char *key_name, size_t in) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_size_t(key_name, &in); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_set_params(pkey, params); } int EVP_PKEY_set_bn_param(EVP_PKEY *pkey, const char *key_name, const BIGNUM *bn) { OSSL_PARAM params[2]; unsigned char buffer[2048]; int bsize = 0; if (key_name == NULL || bn == NULL || pkey == NULL || !evp_pkey_is_assigned(pkey)) return 0; bsize = BN_num_bytes(bn); if (!ossl_assert(bsize <= (int)sizeof(buffer))) return 0; if (BN_bn2nativepad(bn, buffer, bsize) < 0) return 0; params[0] = OSSL_PARAM_construct_BN(key_name, buffer, bsize); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_set_params(pkey, params); } int EVP_PKEY_set_utf8_string_param(EVP_PKEY *pkey, const char *key_name, const char *str) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_utf8_string(key_name, (char *)str, 0); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_set_params(pkey, params); } int EVP_PKEY_set_octet_string_param(EVP_PKEY *pkey, const char *key_name, const unsigned char *buf, size_t bsize) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_octet_string(key_name, (unsigned char *)buf, bsize); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_set_params(pkey, params); } const OSSL_PARAM *EVP_PKEY_settable_params(const EVP_PKEY *pkey) { return (pkey != NULL && evp_pkey_is_provided(pkey)) ? EVP_KEYMGMT_settable_params(pkey->keymgmt) : NULL; } int EVP_PKEY_set_params(EVP_PKEY *pkey, OSSL_PARAM params[]) { if (pkey != NULL) { if (evp_pkey_is_provided(pkey)) { pkey->dirty_cnt++; return evp_keymgmt_set_params(pkey->keymgmt, pkey->keydata, params); } #ifndef FIPS_MODULE /* * We will hopefully never find the need to set individual data in * EVP_PKEYs with a legacy internal key, but we can't be entirely * sure. This bit of code can be enabled if we find the need. If * not, it can safely be removed when #legacy support is removed. */ # if 0 else if (evp_pkey_is_legacy(pkey)) { return evp_pkey_set_params_to_ctrl(pkey, params); } # endif #endif } ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY); return 0; } const OSSL_PARAM *EVP_PKEY_gettable_params(const EVP_PKEY *pkey) { return (pkey != NULL && evp_pkey_is_provided(pkey)) ? EVP_KEYMGMT_gettable_params(pkey->keymgmt) : NULL; } int EVP_PKEY_get_params(const EVP_PKEY *pkey, OSSL_PARAM params[]) { if (pkey != NULL) { if (evp_pkey_is_provided(pkey)) return evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params) > 0; #ifndef FIPS_MODULE else if (evp_pkey_is_legacy(pkey)) return evp_pkey_get_params_to_ctrl(pkey, params) > 0; #endif } ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY); return 0; } #ifndef FIPS_MODULE int EVP_PKEY_get_ec_point_conv_form(const EVP_PKEY *pkey) { char name[80]; size_t name_len; if (pkey == NULL) return 0; if (pkey->keymgmt == NULL || pkey->keydata == NULL) { # ifndef OPENSSL_NO_EC /* Might work through the legacy route */ const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey); if (ec == NULL) return 0; return EC_KEY_get_conv_form(ec); # else return 0; # endif } if (!EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, name, sizeof(name), &name_len)) return 0; if (strcmp(name, "uncompressed") == 0) return POINT_CONVERSION_UNCOMPRESSED; if (strcmp(name, "compressed") == 0) return POINT_CONVERSION_COMPRESSED; if (strcmp(name, "hybrid") == 0) return POINT_CONVERSION_HYBRID; return 0; } int EVP_PKEY_get_field_type(const EVP_PKEY *pkey) { char fstr[80]; size_t fstrlen; if (pkey == NULL) return 0; if (pkey->keymgmt == NULL || pkey->keydata == NULL) { # ifndef OPENSSL_NO_EC /* Might work through the legacy route */ const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey); const EC_GROUP *grp; if (ec == NULL) return 0; grp = EC_KEY_get0_group(ec); if (grp == NULL) return 0; return EC_GROUP_get_field_type(grp); # else return 0; # endif } if (!EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_EC_FIELD_TYPE, fstr, sizeof(fstr), &fstrlen)) return 0; if (strcmp(fstr, SN_X9_62_prime_field) == 0) return NID_X9_62_prime_field; else if (strcmp(fstr, SN_X9_62_characteristic_two_field)) return NID_X9_62_characteristic_two_field; return 0; } #endif
./openssl/crypto/evp/e_camellia.c
/* * Copyright 2006-2021 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 */ /* * Camellia low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/opensslconf.h> #include <openssl/evp.h> #include <openssl/err.h> #include <string.h> #include <assert.h> #include <openssl/camellia.h> #include "crypto/evp.h" #include "crypto/modes.h" #include "crypto/cmll_platform.h" #include "evp_local.h" static int camellia_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); /* Camellia subkey Structure */ typedef struct { CAMELLIA_KEY ks; block128_f block; union { cbc128_f cbc; ctr128_f ctr; } stream; } EVP_CAMELLIA_KEY; #define MAXBITCHUNK ((size_t)1<<(sizeof(size_t)*8-4)) /* Attribute operation for Camellia */ #define data(ctx) EVP_C_DATA(EVP_CAMELLIA_KEY,ctx) #if defined(AES_ASM) && (defined(__sparc) || defined(__sparc__)) /* ---------^^^ this is not a typo, just a way to detect that * assembler support was in general requested... */ # include "crypto/sparc_arch.h" static int cmll_t4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int ret, mode, bits; EVP_CAMELLIA_KEY *dat = (EVP_CAMELLIA_KEY *)EVP_CIPHER_CTX_get_cipher_data(ctx); mode = EVP_CIPHER_CTX_get_mode(ctx); bits = EVP_CIPHER_CTX_get_key_length(ctx) * 8; cmll_t4_set_key(key, bits, &dat->ks); if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE) && !enc) { ret = 0; dat->block = (block128_f) cmll_t4_decrypt; switch (bits) { case 128: dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) cmll128_t4_cbc_decrypt : NULL; break; case 192: case 256: dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) cmll256_t4_cbc_decrypt : NULL; break; default: ret = -1; } } else { ret = 0; dat->block = (block128_f) cmll_t4_encrypt; switch (bits) { case 128: if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) cmll128_t4_cbc_encrypt; else if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) cmll128_t4_ctr32_encrypt; else dat->stream.cbc = NULL; break; case 192: case 256: if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) cmll256_t4_cbc_encrypt; else if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) cmll256_t4_ctr32_encrypt; else dat->stream.cbc = NULL; break; default: ret = -1; } } if (ret < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_CAMELLIA_KEY_SETUP_FAILED); return 0; } return 1; } # define cmll_t4_cbc_cipher camellia_cbc_cipher static int cmll_t4_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define cmll_t4_ecb_cipher camellia_ecb_cipher static int cmll_t4_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define cmll_t4_ofb_cipher camellia_ofb_cipher static int cmll_t4_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define cmll_t4_cfb_cipher camellia_cfb_cipher static int cmll_t4_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define cmll_t4_cfb8_cipher camellia_cfb8_cipher static int cmll_t4_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define cmll_t4_cfb1_cipher camellia_cfb1_cipher static int cmll_t4_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define cmll_t4_ctr_cipher camellia_ctr_cipher static int cmll_t4_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ static const EVP_CIPHER cmll_t4_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ cmll_t4_init_key, \ cmll_t4_##mode##_cipher, \ NULL, \ sizeof(EVP_CAMELLIA_KEY), \ NULL,NULL,NULL,NULL }; \ static const EVP_CIPHER camellia_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize, \ keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ camellia_init_key, \ camellia_##mode##_cipher, \ NULL, \ sizeof(EVP_CAMELLIA_KEY), \ NULL,NULL,NULL,NULL }; \ const EVP_CIPHER *EVP_camellia_##keylen##_##mode(void) \ { return SPARC_CMLL_CAPABLE?&cmll_t4_##keylen##_##mode:&camellia_##keylen##_##mode; } #else # define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ static const EVP_CIPHER camellia_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ EVP_ORIG_GLOBAL, \ camellia_init_key, \ camellia_##mode##_cipher, \ NULL, \ sizeof(EVP_CAMELLIA_KEY), \ NULL,NULL,NULL,NULL }; \ const EVP_CIPHER *EVP_camellia_##keylen##_##mode(void) \ { return &camellia_##keylen##_##mode; } #endif #define BLOCK_CIPHER_generic_pack(nid,keylen,flags) \ BLOCK_CIPHER_generic(nid,keylen,16,16,cbc,cbc,CBC,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,16,0,ecb,ecb,ECB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,1,16,ofb128,ofb,OFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,1,16,cfb128,cfb,CFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,1,16,cfb1,cfb1,CFB,flags) \ BLOCK_CIPHER_generic(nid,keylen,1,16,cfb8,cfb8,CFB,flags) \ BLOCK_CIPHER_generic(nid, keylen, 1, 16, ctr, ctr, CTR, flags) /* The subkey for Camellia is generated. */ static int camellia_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int ret, mode; EVP_CAMELLIA_KEY *dat = EVP_C_DATA(EVP_CAMELLIA_KEY, ctx); ret = Camellia_set_key(key, EVP_CIPHER_CTX_get_key_length(ctx) * 8, &dat->ks); if (ret < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_CAMELLIA_KEY_SETUP_FAILED); return 0; } mode = EVP_CIPHER_CTX_get_mode(ctx); if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE) && !enc) { dat->block = (block128_f) Camellia_decrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) Camellia_cbc_encrypt : NULL; } else { dat->block = (block128_f) Camellia_encrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) Camellia_cbc_encrypt : NULL; } return 1; } static int camellia_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_CAMELLIA_KEY *dat = EVP_C_DATA(EVP_CAMELLIA_KEY, ctx); if (dat->stream.cbc) (*dat->stream.cbc) (in, out, len, &dat->ks, ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx)); else if (EVP_CIPHER_CTX_is_encrypting(ctx)) CRYPTO_cbc128_encrypt(in, out, len, &dat->ks, ctx->iv, dat->block); else CRYPTO_cbc128_decrypt(in, out, len, &dat->ks, ctx->iv, dat->block); return 1; } static int camellia_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { size_t bl = EVP_CIPHER_CTX_get_block_size(ctx); size_t i; EVP_CAMELLIA_KEY *dat = EVP_C_DATA(EVP_CAMELLIA_KEY, ctx); if (len < bl) return 1; for (i = 0, len -= bl; i <= len; i += bl) (*dat->block) (in + i, out + i, &dat->ks); return 1; } static int camellia_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_CAMELLIA_KEY *dat = EVP_C_DATA(EVP_CAMELLIA_KEY, ctx); int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_ofb128_encrypt(in, out, len, &dat->ks, ctx->iv, &num, dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } static int camellia_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_CAMELLIA_KEY *dat = EVP_C_DATA(EVP_CAMELLIA_KEY, ctx); int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_cfb128_encrypt(in, out, len, &dat->ks, ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } static int camellia_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_CAMELLIA_KEY *dat = EVP_C_DATA(EVP_CAMELLIA_KEY, ctx); int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_cfb128_8_encrypt(in, out, len, &dat->ks, ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } static int camellia_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_CAMELLIA_KEY *dat = EVP_C_DATA(EVP_CAMELLIA_KEY, ctx); if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS)) { int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_cfb128_1_encrypt(in, out, len, &dat->ks, ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } while (len >= MAXBITCHUNK) { int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_cfb128_1_encrypt(in, out, MAXBITCHUNK * 8, &dat->ks, ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); len -= MAXBITCHUNK; out += MAXBITCHUNK; in += MAXBITCHUNK; } if (len) { int num = EVP_CIPHER_CTX_get_num(ctx); CRYPTO_cfb128_1_encrypt(in, out, len * 8, &dat->ks, ctx->iv, &num, EVP_CIPHER_CTX_is_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); } return 1; } static int camellia_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { int snum = EVP_CIPHER_CTX_get_num(ctx); unsigned int num; EVP_CAMELLIA_KEY *dat = EVP_C_DATA(EVP_CAMELLIA_KEY, ctx); if (snum < 0) return 0; num = snum; if (dat->stream.ctr) CRYPTO_ctr128_encrypt_ctr32(in, out, len, &dat->ks, ctx->iv, EVP_CIPHER_CTX_buf_noconst(ctx), &num, dat->stream.ctr); else CRYPTO_ctr128_encrypt(in, out, len, &dat->ks, ctx->iv, EVP_CIPHER_CTX_buf_noconst(ctx), &num, dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } BLOCK_CIPHER_generic_pack(NID_camellia, 128, 0) BLOCK_CIPHER_generic_pack(NID_camellia, 192, 0) BLOCK_CIPHER_generic_pack(NID_camellia, 256, 0)
./openssl/crypto/evp/legacy_wp.c
/* * Copyright 2005-2021 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 */ /* * Whirlpool low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/whrlpool.h> #include "crypto/evp.h" #include "legacy_meth.h" IMPLEMENT_LEGACY_EVP_MD_METH(wp, WHIRLPOOL) static const EVP_MD whirlpool_md = { NID_whirlpool, 0, WHIRLPOOL_DIGEST_LENGTH, 0, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(wp_init, wp_update, wp_final, NULL, WHIRLPOOL_BBLOCK / 8), }; const EVP_MD *EVP_whirlpool(void) { return &whirlpool_md; }