repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
openssl
openssl-master/crypto/des/spr.h
/* * Copyright 1995-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 */ const DES_LONG DES_SPtrans[8][64] = { { /* nibble 0 */ 0x02080800L, 0x00080000L, 0x02000002L, 0x02080802L, 0x02000000L, 0x00080802L, 0x00080002L, 0x02000002L, 0x00080802L, 0x02080800L, 0x02080000L, 0x00000802L, 0x02000802L, 0x02000000L, 0x00000000L, 0x00080002L, 0x00080000L, 0x00000002L, 0x02000800L, 0x00080800L, 0x02080802L, 0x02080000L, 0x00000802L, 0x02000800L, 0x00000002L, 0x00000800L, 0x00080800L, 0x02080002L, 0x00000800L, 0x02000802L, 0x02080002L, 0x00000000L, 0x00000000L, 0x02080802L, 0x02000800L, 0x00080002L, 0x02080800L, 0x00080000L, 0x00000802L, 0x02000800L, 0x02080002L, 0x00000800L, 0x00080800L, 0x02000002L, 0x00080802L, 0x00000002L, 0x02000002L, 0x02080000L, 0x02080802L, 0x00080800L, 0x02080000L, 0x02000802L, 0x02000000L, 0x00000802L, 0x00080002L, 0x00000000L, 0x00080000L, 0x02000000L, 0x02000802L, 0x02080800L, 0x00000002L, 0x02080002L, 0x00000800L, 0x00080802L, }, { /* nibble 1 */ 0x40108010L, 0x00000000L, 0x00108000L, 0x40100000L, 0x40000010L, 0x00008010L, 0x40008000L, 0x00108000L, 0x00008000L, 0x40100010L, 0x00000010L, 0x40008000L, 0x00100010L, 0x40108000L, 0x40100000L, 0x00000010L, 0x00100000L, 0x40008010L, 0x40100010L, 0x00008000L, 0x00108010L, 0x40000000L, 0x00000000L, 0x00100010L, 0x40008010L, 0x00108010L, 0x40108000L, 0x40000010L, 0x40000000L, 0x00100000L, 0x00008010L, 0x40108010L, 0x00100010L, 0x40108000L, 0x40008000L, 0x00108010L, 0x40108010L, 0x00100010L, 0x40000010L, 0x00000000L, 0x40000000L, 0x00008010L, 0x00100000L, 0x40100010L, 0x00008000L, 0x40000000L, 0x00108010L, 0x40008010L, 0x40108000L, 0x00008000L, 0x00000000L, 0x40000010L, 0x00000010L, 0x40108010L, 0x00108000L, 0x40100000L, 0x40100010L, 0x00100000L, 0x00008010L, 0x40008000L, 0x40008010L, 0x00000010L, 0x40100000L, 0x00108000L, }, { /* nibble 2 */ 0x04000001L, 0x04040100L, 0x00000100L, 0x04000101L, 0x00040001L, 0x04000000L, 0x04000101L, 0x00040100L, 0x04000100L, 0x00040000L, 0x04040000L, 0x00000001L, 0x04040101L, 0x00000101L, 0x00000001L, 0x04040001L, 0x00000000L, 0x00040001L, 0x04040100L, 0x00000100L, 0x00000101L, 0x04040101L, 0x00040000L, 0x04000001L, 0x04040001L, 0x04000100L, 0x00040101L, 0x04040000L, 0x00040100L, 0x00000000L, 0x04000000L, 0x00040101L, 0x04040100L, 0x00000100L, 0x00000001L, 0x00040000L, 0x00000101L, 0x00040001L, 0x04040000L, 0x04000101L, 0x00000000L, 0x04040100L, 0x00040100L, 0x04040001L, 0x00040001L, 0x04000000L, 0x04040101L, 0x00000001L, 0x00040101L, 0x04000001L, 0x04000000L, 0x04040101L, 0x00040000L, 0x04000100L, 0x04000101L, 0x00040100L, 0x04000100L, 0x00000000L, 0x04040001L, 0x00000101L, 0x04000001L, 0x00040101L, 0x00000100L, 0x04040000L, }, { /* nibble 3 */ 0x00401008L, 0x10001000L, 0x00000008L, 0x10401008L, 0x00000000L, 0x10400000L, 0x10001008L, 0x00400008L, 0x10401000L, 0x10000008L, 0x10000000L, 0x00001008L, 0x10000008L, 0x00401008L, 0x00400000L, 0x10000000L, 0x10400008L, 0x00401000L, 0x00001000L, 0x00000008L, 0x00401000L, 0x10001008L, 0x10400000L, 0x00001000L, 0x00001008L, 0x00000000L, 0x00400008L, 0x10401000L, 0x10001000L, 0x10400008L, 0x10401008L, 0x00400000L, 0x10400008L, 0x00001008L, 0x00400000L, 0x10000008L, 0x00401000L, 0x10001000L, 0x00000008L, 0x10400000L, 0x10001008L, 0x00000000L, 0x00001000L, 0x00400008L, 0x00000000L, 0x10400008L, 0x10401000L, 0x00001000L, 0x10000000L, 0x10401008L, 0x00401008L, 0x00400000L, 0x10401008L, 0x00000008L, 0x10001000L, 0x00401008L, 0x00400008L, 0x00401000L, 0x10400000L, 0x10001008L, 0x00001008L, 0x10000000L, 0x10000008L, 0x10401000L, }, { /* nibble 4 */ 0x08000000L, 0x00010000L, 0x00000400L, 0x08010420L, 0x08010020L, 0x08000400L, 0x00010420L, 0x08010000L, 0x00010000L, 0x00000020L, 0x08000020L, 0x00010400L, 0x08000420L, 0x08010020L, 0x08010400L, 0x00000000L, 0x00010400L, 0x08000000L, 0x00010020L, 0x00000420L, 0x08000400L, 0x00010420L, 0x00000000L, 0x08000020L, 0x00000020L, 0x08000420L, 0x08010420L, 0x00010020L, 0x08010000L, 0x00000400L, 0x00000420L, 0x08010400L, 0x08010400L, 0x08000420L, 0x00010020L, 0x08010000L, 0x00010000L, 0x00000020L, 0x08000020L, 0x08000400L, 0x08000000L, 0x00010400L, 0x08010420L, 0x00000000L, 0x00010420L, 0x08000000L, 0x00000400L, 0x00010020L, 0x08000420L, 0x00000400L, 0x00000000L, 0x08010420L, 0x08010020L, 0x08010400L, 0x00000420L, 0x00010000L, 0x00010400L, 0x08010020L, 0x08000400L, 0x00000420L, 0x00000020L, 0x00010420L, 0x08010000L, 0x08000020L, }, { /* nibble 5 */ 0x80000040L, 0x00200040L, 0x00000000L, 0x80202000L, 0x00200040L, 0x00002000L, 0x80002040L, 0x00200000L, 0x00002040L, 0x80202040L, 0x00202000L, 0x80000000L, 0x80002000L, 0x80000040L, 0x80200000L, 0x00202040L, 0x00200000L, 0x80002040L, 0x80200040L, 0x00000000L, 0x00002000L, 0x00000040L, 0x80202000L, 0x80200040L, 0x80202040L, 0x80200000L, 0x80000000L, 0x00002040L, 0x00000040L, 0x00202000L, 0x00202040L, 0x80002000L, 0x00002040L, 0x80000000L, 0x80002000L, 0x00202040L, 0x80202000L, 0x00200040L, 0x00000000L, 0x80002000L, 0x80000000L, 0x00002000L, 0x80200040L, 0x00200000L, 0x00200040L, 0x80202040L, 0x00202000L, 0x00000040L, 0x80202040L, 0x00202000L, 0x00200000L, 0x80002040L, 0x80000040L, 0x80200000L, 0x00202040L, 0x00000000L, 0x00002000L, 0x80000040L, 0x80002040L, 0x80202000L, 0x80200000L, 0x00002040L, 0x00000040L, 0x80200040L, }, { /* nibble 6 */ 0x00004000L, 0x00000200L, 0x01000200L, 0x01000004L, 0x01004204L, 0x00004004L, 0x00004200L, 0x00000000L, 0x01000000L, 0x01000204L, 0x00000204L, 0x01004000L, 0x00000004L, 0x01004200L, 0x01004000L, 0x00000204L, 0x01000204L, 0x00004000L, 0x00004004L, 0x01004204L, 0x00000000L, 0x01000200L, 0x01000004L, 0x00004200L, 0x01004004L, 0x00004204L, 0x01004200L, 0x00000004L, 0x00004204L, 0x01004004L, 0x00000200L, 0x01000000L, 0x00004204L, 0x01004000L, 0x01004004L, 0x00000204L, 0x00004000L, 0x00000200L, 0x01000000L, 0x01004004L, 0x01000204L, 0x00004204L, 0x00004200L, 0x00000000L, 0x00000200L, 0x01000004L, 0x00000004L, 0x01000200L, 0x00000000L, 0x01000204L, 0x01000200L, 0x00004200L, 0x00000204L, 0x00004000L, 0x01004204L, 0x01000000L, 0x01004200L, 0x00000004L, 0x00004004L, 0x01004204L, 0x01000004L, 0x01004200L, 0x01004000L, 0x00004004L, }, { /* nibble 7 */ 0x20800080L, 0x20820000L, 0x00020080L, 0x00000000L, 0x20020000L, 0x00800080L, 0x20800000L, 0x20820080L, 0x00000080L, 0x20000000L, 0x00820000L, 0x00020080L, 0x00820080L, 0x20020080L, 0x20000080L, 0x20800000L, 0x00020000L, 0x00820080L, 0x00800080L, 0x20020000L, 0x20820080L, 0x20000080L, 0x00000000L, 0x00820000L, 0x20000000L, 0x00800000L, 0x20020080L, 0x20800080L, 0x00800000L, 0x00020000L, 0x20820000L, 0x00000080L, 0x00800000L, 0x00020000L, 0x20000080L, 0x20820080L, 0x00020080L, 0x20000000L, 0x00000000L, 0x00820000L, 0x20800080L, 0x20020080L, 0x20020000L, 0x00800080L, 0x20820000L, 0x00000080L, 0x00800080L, 0x20020000L, 0x20820080L, 0x00800000L, 0x20800000L, 0x20000080L, 0x00820000L, 0x00020080L, 0x20020080L, 0x20800000L, 0x00000080L, 0x20820000L, 0x00820080L, 0x00000000L, 0x20000000L, 0x20800080L, 0x00020000L, 0x00820080L, } };
8,345
49.890244
74
h
openssl
openssl-master/crypto/des/str2key.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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/crypto.h> #include "des_local.h" void DES_string_to_key(const char *str, DES_cblock *key) { DES_key_schedule ks; int i, length; memset(key, 0, 8); length = strlen(str); for (i = 0; i < length; i++) { register unsigned char j = str[i]; if ((i % 16) < 8) (*key)[i % 8] ^= (j << 1); else { /* Reverse the bit order 05/05/92 eay */ j = ((j << 4) & 0xf0) | ((j >> 4) & 0x0f); j = ((j << 2) & 0xcc) | ((j >> 2) & 0x33); j = ((j << 1) & 0xaa) | ((j >> 1) & 0x55); (*key)[7 - (i % 8)] ^= j; } } DES_set_odd_parity(key); DES_set_key_unchecked(key, &ks); DES_cbc_cksum((const unsigned char *)str, key, length, &ks, key); OPENSSL_cleanse(&ks, sizeof(ks)); DES_set_odd_parity(key); } void DES_string_to_2keys(const char *str, DES_cblock *key1, DES_cblock *key2) { DES_key_schedule ks; int i, length; memset(key1, 0, 8); memset(key2, 0, 8); length = strlen(str); for (i = 0; i < length; i++) { register unsigned char j = str[i]; if ((i % 32) < 16) { if ((i % 16) < 8) (*key1)[i % 8] ^= (j << 1); else (*key2)[i % 8] ^= (j << 1); } else { j = ((j << 4) & 0xf0) | ((j >> 4) & 0x0f); j = ((j << 2) & 0xcc) | ((j >> 2) & 0x33); j = ((j << 1) & 0xaa) | ((j >> 1) & 0x55); if ((i % 16) < 8) (*key1)[7 - (i % 8)] ^= j; else (*key2)[7 - (i % 8)] ^= j; } } if (length <= 8) memcpy(key2, key1, 8); DES_set_odd_parity(key1); DES_set_odd_parity(key2); DES_set_key_unchecked(key1, &ks); DES_cbc_cksum((const unsigned char *)str, key1, length, &ks, key1); DES_set_key_unchecked(key2, &ks); DES_cbc_cksum((const unsigned char *)str, key2, length, &ks, key2); OPENSSL_cleanse(&ks, sizeof(ks)); DES_set_odd_parity(key1); DES_set_odd_parity(key2); }
2,512
28.916667
78
c
openssl
openssl-master/crypto/des/xcbc_enc.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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "des_local.h" /* RSA's DESX */ void DES_xcbc_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *schedule, DES_cblock *ivec, const_DES_cblock *inw, const_DES_cblock *outw, int enc) { register DES_LONG tin0, tin1; register DES_LONG tout0, tout1, xor0, xor1; register DES_LONG inW0, inW1, outW0, outW1; register const unsigned char *in2; register long l = length; DES_LONG tin[2]; unsigned char *iv; in2 = &(*inw)[0]; c2l(in2, inW0); c2l(in2, inW1); in2 = &(*outw)[0]; c2l(in2, outW0); c2l(in2, outW1); iv = &(*ivec)[0]; if (enc) { c2l(iv, tout0); c2l(iv, tout1); for (l -= 8; l >= 0; l -= 8) { c2l(in, tin0); c2l(in, tin1); tin0 ^= tout0 ^ inW0; tin[0] = tin0; tin1 ^= tout1 ^ inW1; tin[1] = tin1; DES_encrypt1(tin, schedule, DES_ENCRYPT); tout0 = tin[0] ^ outW0; l2c(tout0, out); tout1 = tin[1] ^ outW1; l2c(tout1, out); } if (l != -8) { c2ln(in, tin0, tin1, l + 8); tin0 ^= tout0 ^ inW0; tin[0] = tin0; tin1 ^= tout1 ^ inW1; tin[1] = tin1; DES_encrypt1(tin, schedule, DES_ENCRYPT); tout0 = tin[0] ^ outW0; l2c(tout0, out); tout1 = tin[1] ^ outW1; l2c(tout1, out); } iv = &(*ivec)[0]; l2c(tout0, iv); l2c(tout1, iv); } else { c2l(iv, xor0); c2l(iv, xor1); for (l -= 8; l > 0; l -= 8) { c2l(in, tin0); tin[0] = tin0 ^ outW0; c2l(in, tin1); tin[1] = tin1 ^ outW1; DES_encrypt1(tin, schedule, DES_DECRYPT); tout0 = tin[0] ^ xor0 ^ inW0; tout1 = tin[1] ^ xor1 ^ inW1; l2c(tout0, out); l2c(tout1, out); xor0 = tin0; xor1 = tin1; } if (l != -8) { c2l(in, tin0); tin[0] = tin0 ^ outW0; c2l(in, tin1); tin[1] = tin1 ^ outW1; DES_encrypt1(tin, schedule, DES_DECRYPT); tout0 = tin[0] ^ xor0 ^ inW0; tout1 = tin[1] ^ xor1 ^ inW1; l2cn(tout0, tout1, out, l + 8); xor0 = tin0; xor1 = tin1; } iv = &(*ivec)[0]; l2c(xor0, iv); l2c(xor1, iv); } tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; inW0 = inW1 = outW0 = outW1 = 0; tin[0] = tin[1] = 0; }
3,138
27.536364
78
c
openssl
openssl-master/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 };
15,225
22.460709
79
c
openssl
openssl-master/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; }
4,831
27.761905
80
c
openssl
openssl-master/crypto/dh/dh_backend.c
/* * Copyright 2020-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 <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
6,290
24.677551
83
c
openssl
openssl-master/crypto/dh/dh_check.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 */ /* * 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; BN_CTX *ctx = NULL; BIGNUM *t1 = NULL, *t2 = NULL; int nid = DH_get_nid((DH *)dh); *ret = 0; if (nid != NID_undef) return 1; 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_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) { 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); } 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; }
9,302
26.853293
80
c
openssl
openssl-master/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; }
1,226
24.040816
77
c
openssl
openssl-master/crypto/dh/dh_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * 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 <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_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
3,180
40.311688
79
c
openssl
openssl-master/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 */
6,967
28.154812
78
c
openssl
openssl-master/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; }
2,512
24.13
77
c
openssl
openssl-master/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) */
2,833
33.987654
79
c
openssl
openssl-master/crypto/dh/dh_key.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 */ /* * 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 (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; ossl_ffc_params_init(&dh->params); 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 (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; }
12,408
26.698661
84
c
openssl
openssl-master/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); };
1,791
28.377049
75
h
openssl
openssl-master/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; }
13,316
23.706865
78
c
openssl
openssl-master/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
889
23.054054
74
c
openssl
openssl-master/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)
1,305
26.208333
80
c
openssl
openssl-master/crypto/dsa/dsa_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 */ /* * DSA 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/cryptlib.h" #include "crypto/asn1.h" #include "crypto/dsa.h" #include "crypto/evp.h" #include "internal/ffc.h" #include "dsa_local.h" static int dsa_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; DSA *dsa = 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) { pstr = pval; pm = pstr->data; pmlen = pstr->length; if ((dsa = d2i_DSAparams(NULL, &pm, pmlen)) == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_DECODE_ERROR); goto err; } } else if ((ptype == V_ASN1_NULL) || (ptype == V_ASN1_UNDEF)) { if ((dsa = DSA_new()) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_DSA_LIB); goto err; } } else { ERR_raise(ERR_LIB_DSA, DSA_R_PARAMETER_ENCODING_ERROR); goto err; } if ((public_key = d2i_ASN1_INTEGER(NULL, &p, pklen)) == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_DECODE_ERROR); goto err; } if ((dsa->pub_key = ASN1_INTEGER_to_BN(public_key, NULL)) == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_BN_DECODE_ERROR); goto err; } dsa->dirty_cnt++; ASN1_INTEGER_free(public_key); EVP_PKEY_assign_DSA(pkey, dsa); return 1; err: ASN1_INTEGER_free(public_key); DSA_free(dsa); return 0; } static int dsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) { DSA *dsa; int ptype; unsigned char *penc = NULL; int penclen; ASN1_STRING *str = NULL; ASN1_INTEGER *pubint = NULL; ASN1_OBJECT *aobj; dsa = pkey->pkey.dsa; if (pkey->save_parameters && dsa->params.p != NULL && dsa->params.q != NULL && dsa->params.g != NULL) { str = ASN1_STRING_new(); if (str == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } str->length = i2d_DSAparams(dsa, &str->data); if (str->length <= 0) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } ptype = V_ASN1_SEQUENCE; } else ptype = V_ASN1_UNDEF; pubint = BN_to_ASN1_INTEGER(dsa->pub_key, NULL); if (pubint == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } penclen = i2d_ASN1_INTEGER(pubint, &penc); ASN1_INTEGER_free(pubint); if (penclen <= 0) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } aobj = OBJ_nid2obj(EVP_PKEY_DSA); if (aobj == NULL) goto err; if (X509_PUBKEY_set0_param(pk, aobj, ptype, str, penc, penclen)) return 1; err: OPENSSL_free(penc); ASN1_STRING_free(str); return 0; } /* * In PKCS#8 DSA: you just get a private key integer and parameters in the * AlgorithmIdentifier the pubkey must be recalculated. */ static int dsa_priv_decode(EVP_PKEY *pkey, const PKCS8_PRIV_KEY_INFO *p8) { int ret = 0; DSA *dsa = ossl_dsa_key_from_pkcs8(p8, NULL, NULL); if (dsa != NULL) { ret = 1; EVP_PKEY_assign_DSA(pkey, dsa); } return ret; } static int dsa_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; if (pkey->pkey.dsa == NULL|| pkey->pkey.dsa->priv_key == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_MISSING_PARAMETERS); goto err; } params = ASN1_STRING_new(); if (params == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } params->length = i2d_DSAparams(pkey->pkey.dsa, &params->data); if (params->length <= 0) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } params->type = V_ASN1_SEQUENCE; /* Get private key into integer */ prkey = BN_to_ASN1_INTEGER(pkey->pkey.dsa->priv_key, NULL); if (prkey == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_BN_ERROR); goto err; } dplen = i2d_ASN1_INTEGER(prkey, &dp); ASN1_STRING_clear_free(prkey); if (dplen <= 0) { ERR_raise(ERR_LIB_DSA, DSA_R_BN_ERROR); goto err; } if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_dsa), 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 int_dsa_size(const EVP_PKEY *pkey) { return DSA_size(pkey->pkey.dsa); } static int dsa_bits(const EVP_PKEY *pkey) { return DSA_bits(pkey->pkey.dsa); } static int dsa_security_bits(const EVP_PKEY *pkey) { return DSA_security_bits(pkey->pkey.dsa); } static int dsa_missing_parameters(const EVP_PKEY *pkey) { DSA *dsa; dsa = pkey->pkey.dsa; return dsa == NULL || dsa->params.p == NULL || dsa->params.q == NULL || dsa->params.g == NULL; } static int dsa_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) { if (to->pkey.dsa == NULL) { to->pkey.dsa = DSA_new(); if (to->pkey.dsa == NULL) return 0; } if (!ossl_ffc_params_copy(&to->pkey.dsa->params, &from->pkey.dsa->params)) return 0; to->pkey.dsa->dirty_cnt++; return 1; } static int dsa_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { return ossl_ffc_params_cmp(&a->pkey.dsa->params, &b->pkey.dsa->params, 1); } static int dsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { return BN_cmp(b->pkey.dsa->pub_key, a->pkey.dsa->pub_key) == 0; } static void int_dsa_free(EVP_PKEY *pkey) { DSA_free(pkey->pkey.dsa); } static int do_dsa_print(BIO *bp, const DSA *x, int off, int ptype) { int ret = 0; const char *ktype = NULL; const BIGNUM *priv_key, *pub_key; int mod_len = 0; if (x->params.p != NULL) mod_len = DSA_bits(x); 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 (ptype == 2) ktype = "Private-Key"; else if (ptype == 1) ktype = "Public-Key"; else ktype = "DSA-Parameters"; if (priv_key != NULL) { if (!BIO_indent(bp, off, 128)) goto err; if (BIO_printf(bp, "%s: (%d bit)\n", ktype, mod_len) <= 0) goto err; } else { if (BIO_printf(bp, "Public-Key: (%d bit)\n", mod_len) <= 0) goto err; } if (!ASN1_bn_print(bp, "priv:", priv_key, NULL, off)) goto err; if (!ASN1_bn_print(bp, "pub: ", pub_key, NULL, off)) goto err; if (!ossl_ffc_params_print(bp, &x->params, off)) goto err; ret = 1; err: return ret; } static int dsa_param_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { DSA *dsa; if ((dsa = d2i_DSAparams(NULL, pder, derlen)) == NULL) return 0; dsa->dirty_cnt++; EVP_PKEY_assign_DSA(pkey, dsa); return 1; } static int dsa_param_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_DSAparams(pkey->pkey.dsa, pder); } static int dsa_param_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dsa_print(bp, pkey->pkey.dsa, indent, 0); } static int dsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dsa_print(bp, pkey->pkey.dsa, indent, 1); } static int dsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dsa_print(bp, pkey->pkey.dsa, indent, 2); } static int old_dsa_priv_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { DSA *dsa; if ((dsa = d2i_DSAPrivateKey(NULL, pder, derlen)) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_DSA_LIB); return 0; } dsa->dirty_cnt++; EVP_PKEY_assign_DSA(pkey, dsa); return 1; } static int old_dsa_priv_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_DSAPrivateKey(pkey->pkey.dsa, pder); } static int dsa_sig_print(BIO *bp, const X509_ALGOR *sigalg, const ASN1_STRING *sig, int indent, ASN1_PCTX *pctx) { DSA_SIG *dsa_sig; const unsigned char *p; if (sig == NULL) { if (BIO_puts(bp, "\n") <= 0) return 0; else return 1; } p = sig->data; dsa_sig = d2i_DSA_SIG(NULL, &p, sig->length); if (dsa_sig != NULL) { int rv = 0; const BIGNUM *r, *s; DSA_SIG_get0(dsa_sig, &r, &s); if (BIO_write(bp, "\n", 1) != 1) goto err; if (!ASN1_bn_print(bp, "r: ", r, NULL, indent)) goto err; if (!ASN1_bn_print(bp, "s: ", s, NULL, indent)) goto err; rv = 1; err: DSA_SIG_free(dsa_sig); return rv; } if (BIO_puts(bp, "\n") <= 0) return 0; return X509_signature_dump(bp, sig, indent); } static int dsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) { switch (op) { case ASN1_PKEY_CTRL_DEFAULT_MD_NID: *(int *)arg2 = NID_sha256; return 1; default: return -2; } } static size_t dsa_pkey_dirty_cnt(const EVP_PKEY *pkey) { return pkey->pkey.dsa->dirty_cnt; } static int dsa_pkey_export_to(const EVP_PKEY *from, void *to_keydata, OSSL_FUNC_keymgmt_import_fn *importer, OSSL_LIB_CTX *libctx, const char *propq) { DSA *dsa = from->pkey.dsa; OSSL_PARAM_BLD *tmpl; const BIGNUM *p = DSA_get0_p(dsa), *g = DSA_get0_g(dsa); const BIGNUM *q = DSA_get0_q(dsa), *pub_key = DSA_get0_pub_key(dsa); const BIGNUM *priv_key = DSA_get0_priv_key(dsa); OSSL_PARAM *params; int selection = 0; int rv = 0; if (p == NULL || q == 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_Q, q) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)) goto err; selection |= OSSL_KEYMGMT_SELECT_DOMAIN_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 dsa_pkey_import_from(const OSSL_PARAM params[], void *vpctx) { EVP_PKEY_CTX *pctx = vpctx; EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pctx); DSA *dsa = ossl_dsa_new(pctx->libctx); if (dsa == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_DSA_LIB); return 0; } if (!ossl_dsa_ffc_params_fromdata(dsa, params) || !ossl_dsa_key_fromdata(dsa, params, 1) || !EVP_PKEY_assign_DSA(pkey, dsa)) { DSA_free(dsa); return 0; } return 1; } static int dsa_pkey_copy(EVP_PKEY *to, EVP_PKEY *from) { DSA *dsa = from->pkey.dsa; DSA *dupkey = NULL; int ret; if (dsa != NULL) { dupkey = ossl_dsa_dup(dsa, OSSL_KEYMGMT_SELECT_ALL); if (dupkey == NULL) return 0; } ret = EVP_PKEY_assign_DSA(to, dupkey); if (!ret) DSA_free(dupkey); return ret; } /* NB these are sorted in pkey_id order, lowest first */ const EVP_PKEY_ASN1_METHOD ossl_dsa_asn1_meths[5] = { { EVP_PKEY_DSA2, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA1, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA4, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA3, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA, EVP_PKEY_DSA, 0, "DSA", "OpenSSL DSA method", dsa_pub_decode, dsa_pub_encode, dsa_pub_cmp, dsa_pub_print, dsa_priv_decode, dsa_priv_encode, dsa_priv_print, int_dsa_size, dsa_bits, dsa_security_bits, dsa_param_decode, dsa_param_encode, dsa_missing_parameters, dsa_copy_parameters, dsa_cmp_parameters, dsa_param_print, dsa_sig_print, int_dsa_free, dsa_pkey_ctrl, old_dsa_priv_decode, old_dsa_priv_encode, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, dsa_pkey_dirty_cnt, dsa_pkey_export_to, dsa_pkey_import_from, dsa_pkey_copy } };
13,853
22.682051
78
c
openssl
openssl-master/crypto/dsa/dsa_asn1.c
/* * Copyright 1999-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 */ /* * 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 "dsa_local.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/rand.h> #include "crypto/asn1_dsa.h" /* Override the default free and new methods */ static int dsa_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_NEW_PRE) { *pval = (ASN1_VALUE *)DSA_new(); if (*pval != NULL) return 2; return 0; } else if (operation == ASN1_OP_FREE_PRE) { DSA_free((DSA *)*pval); *pval = NULL; return 2; } return 1; } ASN1_SEQUENCE_cb(DSAPrivateKey, dsa_cb) = { ASN1_EMBED(DSA, version, INT32), ASN1_SIMPLE(DSA, params.p, BIGNUM), ASN1_SIMPLE(DSA, params.q, BIGNUM), ASN1_SIMPLE(DSA, params.g, BIGNUM), ASN1_SIMPLE(DSA, pub_key, BIGNUM), ASN1_SIMPLE(DSA, priv_key, CBIGNUM) } static_ASN1_SEQUENCE_END_cb(DSA, DSAPrivateKey) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(DSA, DSAPrivateKey, DSAPrivateKey) ASN1_SEQUENCE_cb(DSAparams, dsa_cb) = { ASN1_SIMPLE(DSA, params.p, BIGNUM), ASN1_SIMPLE(DSA, params.q, BIGNUM), ASN1_SIMPLE(DSA, params.g, BIGNUM), } static_ASN1_SEQUENCE_END_cb(DSA, DSAparams) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(DSA, DSAparams, DSAparams) ASN1_SEQUENCE_cb(DSAPublicKey, dsa_cb) = { ASN1_SIMPLE(DSA, pub_key, BIGNUM), ASN1_SIMPLE(DSA, params.p, BIGNUM), ASN1_SIMPLE(DSA, params.q, BIGNUM), ASN1_SIMPLE(DSA, params.g, BIGNUM) } static_ASN1_SEQUENCE_END_cb(DSA, DSAPublicKey) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(DSA, DSAPublicKey, DSAPublicKey) DSA *DSAparams_dup(const DSA *dsa) { return ASN1_item_dup(ASN1_ITEM_rptr(DSAparams), dsa); }
2,242
29.726027
74
c
openssl
openssl-master/crypto/dsa/dsa_backend.c
/* * Copyright 2020-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 */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/core_names.h> #include <openssl/err.h> #ifndef FIPS_MODULE # include <openssl/x509.h> #endif #include "crypto/dsa.h" #include "dsa_local.h" /* * The intention with the "backend" source file is to offer backend support * for legacy backends (EVP_PKEY_ASN1_METHOD and EVP_PKEY_METHOD) and provider * implementations alike. */ int ossl_dsa_key_fromdata(DSA *dsa, const OSSL_PARAM params[], int include_private) { const OSSL_PARAM *param_priv_key = NULL, *param_pub_key; BIGNUM *priv_key = NULL, *pub_key = NULL; if (dsa == NULL) return 0; if (include_private) { 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); /* It's ok if neither half is present */ if (param_priv_key == NULL && param_pub_key == NULL) return 1; if (param_pub_key != NULL && !OSSL_PARAM_get_BN(param_pub_key, &pub_key)) goto err; if (param_priv_key != NULL && !OSSL_PARAM_get_BN(param_priv_key, &priv_key)) goto err; if (!DSA_set0_key(dsa, pub_key, priv_key)) goto err; return 1; err: BN_clear_free(priv_key); BN_free(pub_key); return 0; } int ossl_dsa_is_foreign(const DSA *dsa) { #ifndef FIPS_MODULE if (dsa->engine != NULL || DSA_get_method((DSA *)dsa) != DSA_OpenSSL()) return 1; #endif return 0; } static ossl_inline int dsa_bn_dup_check(BIGNUM **out, const BIGNUM *f) { if (f != NULL && (*out = BN_dup(f)) == NULL) return 0; return 1; } DSA *ossl_dsa_dup(const DSA *dsa, int selection) { DSA *dupkey = NULL; /* Do not try to duplicate foreign DSA keys */ if (ossl_dsa_is_foreign(dsa)) return NULL; if ((dupkey = ossl_dsa_new(dsa->libctx)) == NULL) return NULL; if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0 && !ossl_ffc_params_copy(&dupkey->params, &dsa->params)) goto err; dupkey->flags = dsa->flags; if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0 && ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0 || !dsa_bn_dup_check(&dupkey->pub_key, dsa->pub_key))) goto err; if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0 && ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0 || !dsa_bn_dup_check(&dupkey->priv_key, dsa->priv_key))) goto err; #ifndef FIPS_MODULE if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_DSA, &dupkey->ex_data, &dsa->ex_data)) goto err; #endif return dupkey; err: DSA_free(dupkey); return NULL; } #ifndef FIPS_MODULE DSA *ossl_dsa_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; ASN1_INTEGER *privkey = NULL; const BIGNUM *dsa_p, *dsa_g; BIGNUM *dsa_pubkey = NULL, *dsa_privkey = NULL; BN_CTX *ctx = NULL; DSA *dsa = NULL; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8inf)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if ((privkey = d2i_ASN1_INTEGER(NULL, &p, pklen)) == NULL) goto decerr; if (privkey->type == V_ASN1_NEG_INTEGER || ptype != V_ASN1_SEQUENCE) goto decerr; pstr = pval; pm = pstr->data; pmlen = pstr->length; if ((dsa = d2i_DSAparams(NULL, &pm, pmlen)) == NULL) goto decerr; /* We have parameters now set private key */ if ((dsa_privkey = BN_secure_new()) == NULL || !ASN1_INTEGER_to_BN(privkey, dsa_privkey)) { ERR_raise(ERR_LIB_DSA, DSA_R_BN_ERROR); goto dsaerr; } /* Calculate public key */ if ((dsa_pubkey = BN_new()) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_BN_LIB); goto dsaerr; } if ((ctx = BN_CTX_new()) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_BN_LIB); goto dsaerr; } dsa_p = DSA_get0_p(dsa); dsa_g = DSA_get0_g(dsa); BN_set_flags(dsa_privkey, BN_FLG_CONSTTIME); if (!BN_mod_exp(dsa_pubkey, dsa_g, dsa_privkey, dsa_p, ctx)) { ERR_raise(ERR_LIB_DSA, DSA_R_BN_ERROR); goto dsaerr; } if (!DSA_set0_key(dsa, dsa_pubkey, dsa_privkey)) { ERR_raise(ERR_LIB_DSA, ERR_R_INTERNAL_ERROR); goto dsaerr; } goto done; decerr: ERR_raise(ERR_LIB_DSA, DSA_R_DECODE_ERROR); dsaerr: BN_free(dsa_privkey); BN_free(dsa_pubkey); DSA_free(dsa); dsa = NULL; done: BN_CTX_free(ctx); ASN1_STRING_clear_free(privkey); return dsa; } #endif
5,243
25.755102
80
c
openssl
openssl-master/crypto/dsa/dsa_check.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 */ /* * 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/bn.h> #include "dsa_local.h" #include "crypto/dsa.h" int ossl_dsa_check_params(const DSA *dsa, int checktype, int *ret) { if (checktype == OSSL_KEYMGMT_VALIDATE_QUICK_CHECK) return ossl_ffc_params_simple_validate(dsa->libctx, &dsa->params, FFC_PARAM_TYPE_DSA, ret); else /* * Do full FFC domain params validation according to FIPS-186-4 * - always in FIPS_MODULE * - only if possible (i.e., seed is set) in default provider */ return ossl_ffc_params_full_validate(dsa->libctx, &dsa->params, FFC_PARAM_TYPE_DSA, ret); } /* * See SP800-56Ar3 Section 5.6.2.3.1 : FFC Full public key validation. */ int ossl_dsa_check_pub_key(const DSA *dsa, const BIGNUM *pub_key, int *ret) { return ossl_ffc_validate_public_key(&dsa->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_dsa_check_pub_key_partial(const DSA *dsa, const BIGNUM *pub_key, int *ret) { return ossl_ffc_validate_public_key_partial(&dsa->params, pub_key, ret); } int ossl_dsa_check_priv_key(const DSA *dsa, const BIGNUM *priv_key, int *ret) { *ret = 0; return (dsa->params.q != NULL && ossl_ffc_validate_private_key(dsa->params.q, priv_key, ret)); } /* * FFC pairwise check from SP800-56A R3. * Section 5.6.2.1.4 Owner Assurance of Pair-wise Consistency */ int ossl_dsa_check_pairwise(const DSA *dsa) { int ret = 0; BN_CTX *ctx = NULL; BIGNUM *pub_key = NULL; if (dsa->params.p == NULL || dsa->params.g == NULL || dsa->priv_key == NULL || dsa->pub_key == NULL) return 0; ctx = BN_CTX_new_ex(dsa->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_dsa_generate_public_key(ctx, dsa, dsa->priv_key, pub_key)) goto err; /* check it matches the existing pubic_key */ ret = BN_cmp(pub_key, dsa->pub_key) == 0; err: BN_free(pub_key); BN_CTX_free(ctx); return ret; }
2,833
28.520833
83
c
openssl
openssl-master/crypto/dsa/dsa_depr.c
/* * Copyright 2002-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 */ /* * This file contains deprecated function(s) that are now wrappers to the new * version(s). */ /* * DSA 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 <time.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/bn.h> #include <openssl/dsa.h> #include <openssl/sha.h> DSA *DSA_generate_parameters(int bits, unsigned char *seed_in, int seed_len, int *counter_ret, unsigned long *h_ret, void (*callback) (int, int, void *), void *cb_arg) { BN_GENCB *cb; DSA *ret; if ((ret = DSA_new()) == NULL) return NULL; cb = BN_GENCB_new(); if (cb == NULL) goto err; BN_GENCB_set_old(cb, callback, cb_arg); if (DSA_generate_parameters_ex(ret, bits, seed_in, seed_len, counter_ret, h_ret, cb)) { BN_GENCB_free(cb); return ret; } BN_GENCB_free(cb); err: DSA_free(ret); return NULL; }
1,498
24.844828
77
c
openssl
openssl-master/crypto/dsa/dsa_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/dsaerr.h> #include "crypto/dsaerr.h" #ifndef OPENSSL_NO_DSA # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA DSA_str_reasons[] = { {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_BAD_FFC_PARAMETERS), "bad ffc parameters"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_BAD_Q_VALUE), "bad q value"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_BN_DECODE_ERROR), "bn decode error"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_BN_ERROR), "bn error"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_DECODE_ERROR), "decode error"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_INVALID_DIGEST_TYPE), "invalid digest type"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_INVALID_PARAMETERS), "invalid parameters"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_MISSING_PARAMETERS), "missing parameters"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_MISSING_PRIVATE_KEY), "missing private key"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_MODULUS_TOO_LARGE), "modulus too large"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_NO_PARAMETERS_SET), "no parameters set"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_PARAMETER_ENCODING_ERROR), "parameter encoding error"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_P_NOT_PRIME), "p not prime"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_Q_NOT_PRIME), "q not prime"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_SEED_LEN_SMALL), "seed_len is less than the length of q"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_TOO_MANY_RETRIES), "too many retries"}, {0, NULL} }; # endif int ossl_err_load_DSA_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(DSA_str_reasons[0].error) == NULL) ERR_load_strings_const(DSA_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
2,068
35.946429
79
c
openssl
openssl-master/crypto/dsa/dsa_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 */ /* * DSA 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/evp.h> #include <openssl/bn.h> #include <openssl/rand.h> #include <openssl/sha.h> #include "crypto/dsa.h" #include "dsa_local.h" int ossl_dsa_generate_ffc_parameters(DSA *dsa, int type, int pbits, int qbits, BN_GENCB *cb) { int ret = 0, res; #ifndef FIPS_MODULE if (type == DSA_PARAMGEN_TYPE_FIPS_186_2) ret = ossl_ffc_params_FIPS186_2_generate(dsa->libctx, &dsa->params, FFC_PARAM_TYPE_DSA, pbits, qbits, &res, cb); else #endif ret = ossl_ffc_params_FIPS186_4_generate(dsa->libctx, &dsa->params, FFC_PARAM_TYPE_DSA, pbits, qbits, &res, cb); if (ret > 0) dsa->dirty_cnt++; return ret; } #ifndef FIPS_MODULE int DSA_generate_parameters_ex(DSA *dsa, int bits, const unsigned char *seed_in, int seed_len, int *counter_ret, unsigned long *h_ret, BN_GENCB *cb) { if (dsa->meth->dsa_paramgen) return dsa->meth->dsa_paramgen(dsa, bits, seed_in, seed_len, counter_ret, h_ret, cb); if (seed_in != NULL && !ossl_ffc_params_set_validate_params(&dsa->params, seed_in, seed_len, -1)) return 0; /* The old code used FIPS 186-2 DSA Parameter generation */ if (bits < 2048 && seed_len <= 20) { if (!ossl_dsa_generate_ffc_parameters(dsa, DSA_PARAMGEN_TYPE_FIPS_186_2, bits, 160, cb)) return 0; } else { if (!ossl_dsa_generate_ffc_parameters(dsa, DSA_PARAMGEN_TYPE_FIPS_186_4, bits, 0, cb)) return 0; } if (counter_ret != NULL) *counter_ret = dsa->params.pcounter; if (h_ret != NULL) *h_ret = dsa->params.h; return 1; } #endif
2,645
32.923077
80
c
openssl
openssl-master/crypto/dsa/dsa_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 */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/self_test.h> #include "prov/providercommon.h" #include "crypto/dsa.h" #include "dsa_local.h" #ifdef FIPS_MODULE # define MIN_STRENGTH 112 #else # define MIN_STRENGTH 80 #endif static int dsa_keygen(DSA *dsa); int DSA_generate_key(DSA *dsa) { #ifndef FIPS_MODULE if (dsa->meth->dsa_keygen != NULL) return dsa->meth->dsa_keygen(dsa); #endif return dsa_keygen(dsa); } int ossl_dsa_generate_public_key(BN_CTX *ctx, const DSA *dsa, const BIGNUM *priv_key, BIGNUM *pub_key) { int ret = 0; BIGNUM *prk = BN_new(); if (prk == NULL) return 0; BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME); /* pub_key = g ^ priv_key mod p */ if (!BN_mod_exp(pub_key, dsa->params.g, prk, dsa->params.p, ctx)) goto err; ret = 1; err: BN_clear_free(prk); return ret; } #ifdef FIPS_MODULE /* * Refer: FIPS 140-3 IG 10.3.A Additional Comment 1 * Perform a KAT by duplicating the public key generation. * * NOTE: This issue requires a background understanding, provided in a separate * document; the current IG 10.3.A AC1 is insufficient regarding the PCT for * the key agreement scenario. * * Currently IG 10.3.A requires PCT in the mode of use prior to use of the * key pair, citing the PCT defined in the associated standard. For key * agreement, the only PCT defined in SP 800-56A is that of Section 5.6.2.4: * the comparison of the original public key to a newly calculated public key. */ static int dsa_keygen_knownanswer_test(DSA *dsa, BN_CTX *ctx, OSSL_CALLBACK *cb, void *cbarg) { int len, ret = 0; OSSL_SELF_TEST *st = NULL; unsigned char bytes[512] = {0}; BIGNUM *pub_key2 = BN_new(); if (pub_key2 == NULL) return 0; st = OSSL_SELF_TEST_new(cb, cbarg); if (st == NULL) goto err; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT_KAT, OSSL_SELF_TEST_DESC_PCT_DSA); if (!ossl_dsa_generate_public_key(ctx, dsa, dsa->priv_key, pub_key2)) goto err; if (BN_num_bytes(pub_key2) > (int)sizeof(bytes)) goto err; len = BN_bn2bin(pub_key2, bytes); OSSL_SELF_TEST_oncorrupt_byte(st, bytes); if (BN_bin2bn(bytes, len, pub_key2) != NULL) ret = !BN_cmp(dsa->pub_key, pub_key2); err: OSSL_SELF_TEST_onend(st, ret); OSSL_SELF_TEST_free(st); BN_free(pub_key2); return ret; } /* * FIPS 140-2 IG 9.9 AS09.33 * Perform a sign/verify operation. */ static int dsa_keygen_pairwise_test(DSA *dsa, OSSL_CALLBACK *cb, void *cbarg) { int ret = 0; unsigned char dgst[16] = {0}; unsigned int dgst_len = (unsigned int)sizeof(dgst); DSA_SIG *sig = NULL; OSSL_SELF_TEST *st = NULL; st = OSSL_SELF_TEST_new(cb, cbarg); if (st == NULL) goto err; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT, OSSL_SELF_TEST_DESC_PCT_DSA); sig = DSA_do_sign(dgst, (int)dgst_len, dsa); if (sig == NULL) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, dgst); if (DSA_do_verify(dgst, dgst_len, sig, dsa) != 1) goto err; ret = 1; err: OSSL_SELF_TEST_onend(st, ret); OSSL_SELF_TEST_free(st); DSA_SIG_free(sig); return ret; } #endif /* FIPS_MODULE */ static int dsa_keygen(DSA *dsa) { int ok = 0; BN_CTX *ctx = NULL; BIGNUM *pub_key = NULL, *priv_key = NULL; if ((ctx = BN_CTX_new_ex(dsa->libctx)) == NULL) goto err; if (dsa->priv_key == NULL) { if ((priv_key = BN_secure_new()) == NULL) goto err; } else { priv_key = dsa->priv_key; } /* Do a partial check for invalid p, q, g */ if (!ossl_ffc_params_simple_validate(dsa->libctx, &dsa->params, FFC_PARAM_TYPE_DSA, 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, &dsa->params, BN_num_bits(dsa->params.q), MIN_STRENGTH, priv_key)) goto err; if (dsa->pub_key == NULL) { if ((pub_key = BN_new()) == NULL) goto err; } else { pub_key = dsa->pub_key; } if (!ossl_dsa_generate_public_key(ctx, dsa, priv_key, pub_key)) goto err; dsa->priv_key = priv_key; dsa->pub_key = pub_key; ok = 1; #ifdef FIPS_MODULE { OSSL_CALLBACK *cb = NULL; void *cbarg = NULL; OSSL_SELF_TEST_get_callback(dsa->libctx, &cb, &cbarg); ok = dsa_keygen_pairwise_test(dsa, cb, cbarg) && dsa_keygen_knownanswer_test(dsa, ctx, cb, cbarg); if (!ok) { ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT); BN_free(dsa->pub_key); BN_clear_free(dsa->priv_key); dsa->pub_key = NULL; dsa->priv_key = NULL; BN_CTX_free(ctx); return ok; } } #endif dsa->dirty_cnt++; err: if (pub_key != dsa->pub_key) BN_free(pub_key); if (priv_key != dsa->priv_key) BN_free(priv_key); BN_CTX_free(ctx); return ok; }
5,833
25.279279
79
c
openssl
openssl-master/crypto/dsa/dsa_lib.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 */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/bn.h> #ifndef FIPS_MODULE # include <openssl/engine.h> #endif #include "internal/cryptlib.h" #include "internal/refcount.h" #include "crypto/dsa.h" #include "crypto/dh.h" /* required by DSA_dup_DH() */ #include "dsa_local.h" static DSA *dsa_new_intern(ENGINE *engine, OSSL_LIB_CTX *libctx); #ifndef FIPS_MODULE int DSA_set_ex_data(DSA *d, int idx, void *arg) { return CRYPTO_set_ex_data(&d->ex_data, idx, arg); } void *DSA_get_ex_data(const DSA *d, int idx) { return CRYPTO_get_ex_data(&d->ex_data, idx); } # ifndef OPENSSL_NO_DH DH *DSA_dup_DH(const DSA *r) { /* * DSA has p, q, g, optional pub_key, optional priv_key. * DH has p, optional length, g, optional pub_key, * optional priv_key, optional q. */ DH *ret = NULL; BIGNUM *pub_key = NULL, *priv_key = NULL; if (r == NULL) goto err; ret = DH_new(); if (ret == NULL) goto err; if (!ossl_ffc_params_copy(ossl_dh_get0_params(ret), &r->params)) goto err; if (r->pub_key != NULL) { pub_key = BN_dup(r->pub_key); if (pub_key == NULL) goto err; if (r->priv_key != NULL) { priv_key = BN_dup(r->priv_key); if (priv_key == NULL) goto err; } if (!DH_set0_key(ret, pub_key, priv_key)) goto err; } else if (r->priv_key != NULL) { /* Shouldn't happen */ goto err; } return ret; err: BN_free(pub_key); BN_free(priv_key); DH_free(ret); return NULL; } # endif /* OPENSSL_NO_DH */ void DSA_clear_flags(DSA *d, int flags) { d->flags &= ~flags; } int DSA_test_flags(const DSA *d, int flags) { return d->flags & flags; } void DSA_set_flags(DSA *d, int flags) { d->flags |= flags; } ENGINE *DSA_get0_engine(DSA *d) { return d->engine; } int DSA_set_method(DSA *dsa, const DSA_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 DSA_METHOD *mtmp; mtmp = dsa->meth; if (mtmp->finish) mtmp->finish(dsa); #ifndef OPENSSL_NO_ENGINE ENGINE_finish(dsa->engine); dsa->engine = NULL; #endif dsa->meth = meth; if (meth->init) meth->init(dsa); return 1; } #endif /* FIPS_MODULE */ const DSA_METHOD *DSA_get_method(DSA *d) { return d->meth; } static DSA *dsa_new_intern(ENGINE *engine, OSSL_LIB_CTX *libctx) { DSA *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { ERR_raise(ERR_LIB_DSA, 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 = DSA_get_default_method(); #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_ENGINE) ret->flags = ret->meth->flags & ~DSA_FLAG_NON_FIPS_ALLOW; /* early default init */ if (engine) { if (!ENGINE_init(engine)) { ERR_raise(ERR_LIB_DSA, ERR_R_ENGINE_LIB); goto err; } ret->engine = engine; } else ret->engine = ENGINE_get_default_DSA(); if (ret->engine) { ret->meth = ENGINE_get_DSA(ret->engine); if (ret->meth == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_ENGINE_LIB); goto err; } } #endif ret->flags = ret->meth->flags & ~DSA_FLAG_NON_FIPS_ALLOW; #ifndef FIPS_MODULE if (!ossl_crypto_new_ex_data_ex(libctx, CRYPTO_EX_INDEX_DSA, ret, &ret->ex_data)) goto err; #endif if ((ret->meth->init != NULL) && !ret->meth->init(ret)) { ERR_raise(ERR_LIB_DSA, ERR_R_INIT_FAIL); goto err; } return ret; err: DSA_free(ret); return NULL; } DSA *DSA_new_method(ENGINE *engine) { return dsa_new_intern(engine, NULL); } DSA *ossl_dsa_new(OSSL_LIB_CTX *libctx) { return dsa_new_intern(NULL, libctx); } #ifndef FIPS_MODULE DSA *DSA_new(void) { return dsa_new_intern(NULL, NULL); } #endif void DSA_free(DSA *r) { int i; if (r == NULL) return; CRYPTO_DOWN_REF(&r->references, &i); REF_PRINT_COUNT("DSA", 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) && !defined(OPENSSL_NO_ENGINE) ENGINE_finish(r->engine); #endif #ifndef FIPS_MODULE CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DSA, 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 DSA_up_ref(DSA *r) { int i; if (CRYPTO_UP_REF(&r->references, &i) <= 0) return 0; REF_PRINT_COUNT("DSA", r); REF_ASSERT_ISNT(i < 2); return ((i > 1) ? 1 : 0); } void ossl_dsa_set0_libctx(DSA *d, OSSL_LIB_CTX *libctx) { d->libctx = libctx; } void DSA_get0_pqg(const DSA *d, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g) { ossl_ffc_params_get0_pqg(&d->params, p, q, g); } int DSA_set0_pqg(DSA *d, BIGNUM *p, BIGNUM *q, BIGNUM *g) { /* If the fields p, q and g in d are NULL, the corresponding input * parameters MUST be non-NULL. */ if ((d->params.p == NULL && p == NULL) || (d->params.q == NULL && q == NULL) || (d->params.g == NULL && g == NULL)) return 0; ossl_ffc_params_set0_pqg(&d->params, p, q, g); d->dirty_cnt++; return 1; } const BIGNUM *DSA_get0_p(const DSA *d) { return d->params.p; } const BIGNUM *DSA_get0_q(const DSA *d) { return d->params.q; } const BIGNUM *DSA_get0_g(const DSA *d) { return d->params.g; } const BIGNUM *DSA_get0_pub_key(const DSA *d) { return d->pub_key; } const BIGNUM *DSA_get0_priv_key(const DSA *d) { return d->priv_key; } void DSA_get0_key(const DSA *d, const BIGNUM **pub_key, const BIGNUM **priv_key) { if (pub_key != NULL) *pub_key = d->pub_key; if (priv_key != NULL) *priv_key = d->priv_key; } int DSA_set0_key(DSA *d, BIGNUM *pub_key, BIGNUM *priv_key) { if (pub_key != NULL) { BN_free(d->pub_key); d->pub_key = pub_key; } if (priv_key != NULL) { BN_free(d->priv_key); d->priv_key = priv_key; } d->dirty_cnt++; return 1; } int DSA_security_bits(const DSA *d) { if (d->params.p != NULL && d->params.q != NULL) return BN_security_bits(BN_num_bits(d->params.p), BN_num_bits(d->params.q)); return -1; } int DSA_bits(const DSA *dsa) { if (dsa->params.p != NULL) return BN_num_bits(dsa->params.p); return -1; } FFC_PARAMS *ossl_dsa_get0_params(DSA *dsa) { return &dsa->params; } int ossl_dsa_ffc_params_fromdata(DSA *dsa, const OSSL_PARAM params[]) { int ret; FFC_PARAMS *ffc = ossl_dsa_get0_params(dsa); ret = ossl_ffc_params_fromdata(ffc, params); if (ret) dsa->dirty_cnt++; return ret; }
7,744
20.454294
86
c
openssl
openssl-master/crypto/dsa/dsa_local.h
/* * Copyright 2007-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/dsa.h> #include "internal/refcount.h" #include "internal/ffc.h" struct dsa_st { /* * This first variable is used to pick up errors where a DSA is passed * instead of an EVP_PKEY */ int pad; int32_t version; FFC_PARAMS params; BIGNUM *pub_key; /* y public key */ BIGNUM *priv_key; /* x private key */ int flags; /* Normally used to cache montgomery values */ BN_MONT_CTX *method_mont_p; CRYPTO_REF_COUNT references; #ifndef FIPS_MODULE CRYPTO_EX_DATA ex_data; #endif const DSA_METHOD *meth; /* functional reference if 'meth' is ENGINE-provided */ ENGINE *engine; CRYPTO_RWLOCK *lock; OSSL_LIB_CTX *libctx; /* Provider data */ size_t dirty_cnt; /* If any key material changes, increment this */ }; struct DSA_SIG_st { BIGNUM *r; BIGNUM *s; }; struct dsa_method { char *name; DSA_SIG *(*dsa_do_sign) (const unsigned char *dgst, int dlen, DSA *dsa); int (*dsa_sign_setup) (DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp); int (*dsa_do_verify) (const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa); int (*dsa_mod_exp) (DSA *dsa, BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1, const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont); /* Can be null */ int (*bn_mod_exp) (DSA *dsa, BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); int (*init) (DSA *dsa); int (*finish) (DSA *dsa); int flags; void *app_data; /* If this is non-NULL, it is used to generate DSA parameters */ int (*dsa_paramgen) (DSA *dsa, int bits, const unsigned char *seed, int seed_len, int *counter_ret, unsigned long *h_ret, BN_GENCB *cb); /* If this is non-NULL, it is used to generate DSA keys */ int (*dsa_keygen) (DSA *dsa); }; DSA_SIG *ossl_dsa_do_sign_int(const unsigned char *dgst, int dlen, DSA *dsa, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq);
2,657
34.44
78
h
openssl
openssl-master/crypto/dsa/dsa_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 */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "dsa_local.h" #include <string.h> #include <openssl/err.h> #ifndef OPENSSL_NO_DEPRECATED_3_0 DSA_METHOD *DSA_meth_new(const char *name, int flags) { DSA_METHOD *dsam = OPENSSL_zalloc(sizeof(*dsam)); if (dsam != NULL) { dsam->flags = flags; dsam->name = OPENSSL_strdup(name); if (dsam->name != NULL) return dsam; OPENSSL_free(dsam); } return NULL; } void DSA_meth_free(DSA_METHOD *dsam) { if (dsam != NULL) { OPENSSL_free(dsam->name); OPENSSL_free(dsam); } } DSA_METHOD *DSA_meth_dup(const DSA_METHOD *dsam) { DSA_METHOD *ret = OPENSSL_malloc(sizeof(*ret)); if (ret != NULL) { memcpy(ret, dsam, sizeof(*dsam)); ret->name = OPENSSL_strdup(dsam->name); if (ret->name != NULL) return ret; OPENSSL_free(ret); } return NULL; } const char *DSA_meth_get0_name(const DSA_METHOD *dsam) { return dsam->name; } int DSA_meth_set1_name(DSA_METHOD *dsam, const char *name) { char *tmpname = OPENSSL_strdup(name); if (tmpname == NULL) return 0; OPENSSL_free(dsam->name); dsam->name = tmpname; return 1; } int DSA_meth_get_flags(const DSA_METHOD *dsam) { return dsam->flags; } int DSA_meth_set_flags(DSA_METHOD *dsam, int flags) { dsam->flags = flags; return 1; } void *DSA_meth_get0_app_data(const DSA_METHOD *dsam) { return dsam->app_data; } int DSA_meth_set0_app_data(DSA_METHOD *dsam, void *app_data) { dsam->app_data = app_data; return 1; } DSA_SIG *(*DSA_meth_get_sign(const DSA_METHOD *dsam)) (const unsigned char *, int, DSA *) { return dsam->dsa_do_sign; } int DSA_meth_set_sign(DSA_METHOD *dsam, DSA_SIG *(*sign) (const unsigned char *, int, DSA *)) { dsam->dsa_do_sign = sign; return 1; } int (*DSA_meth_get_sign_setup(const DSA_METHOD *dsam)) (DSA *, BN_CTX *, BIGNUM **, BIGNUM **) { return dsam->dsa_sign_setup; } int DSA_meth_set_sign_setup(DSA_METHOD *dsam, int (*sign_setup) (DSA *, BN_CTX *, BIGNUM **, BIGNUM **)) { dsam->dsa_sign_setup = sign_setup; return 1; } int (*DSA_meth_get_verify(const DSA_METHOD *dsam)) (const unsigned char *, int, DSA_SIG *, DSA *) { return dsam->dsa_do_verify; } int DSA_meth_set_verify(DSA_METHOD *dsam, int (*verify) (const unsigned char *, int, DSA_SIG *, DSA *)) { dsam->dsa_do_verify = verify; return 1; } int (*DSA_meth_get_mod_exp(const DSA_METHOD *dsam)) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *) { return dsam->dsa_mod_exp; } int DSA_meth_set_mod_exp(DSA_METHOD *dsam, int (*mod_exp) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *)) { dsam->dsa_mod_exp = mod_exp; return 1; } int (*DSA_meth_get_bn_mod_exp(const DSA_METHOD *dsam)) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *) { return dsam->bn_mod_exp; } int DSA_meth_set_bn_mod_exp(DSA_METHOD *dsam, int (*bn_mod_exp) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *)) { dsam->bn_mod_exp = bn_mod_exp; return 1; } int (*DSA_meth_get_init(const DSA_METHOD *dsam))(DSA *) { return dsam->init; } int DSA_meth_set_init(DSA_METHOD *dsam, int (*init)(DSA *)) { dsam->init = init; return 1; } int (*DSA_meth_get_finish(const DSA_METHOD *dsam)) (DSA *) { return dsam->finish; } int DSA_meth_set_finish(DSA_METHOD *dsam, int (*finish) (DSA *)) { dsam->finish = finish; return 1; } int (*DSA_meth_get_paramgen(const DSA_METHOD *dsam)) (DSA *, int, const unsigned char *, int, int *, unsigned long *, BN_GENCB *) { return dsam->dsa_paramgen; } int DSA_meth_set_paramgen(DSA_METHOD *dsam, int (*paramgen) (DSA *, int, const unsigned char *, int, int *, unsigned long *, BN_GENCB *)) { dsam->dsa_paramgen = paramgen; return 1; } int (*DSA_meth_get_keygen(const DSA_METHOD *dsam)) (DSA *) { return dsam->dsa_keygen; } int DSA_meth_set_keygen(DSA_METHOD *dsam, int (*keygen) (DSA *)) { dsam->dsa_keygen = keygen; return 1; } #endif
4,878
21.076923
79
c
openssl
openssl-master/crypto/dsa/dsa_ossl.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 */ /* * 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 "crypto/bn.h" #include <openssl/bn.h> #include <openssl/sha.h> #include "dsa_local.h" #include <openssl/asn1.h> #include "internal/deterministic_nonce.h" #define MIN_DSA_SIGN_QBITS 128 #define MAX_DSA_SIGN_RETRIES 8 static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa); static int dsa_sign_setup_no_digest(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp); static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp, const unsigned char *dgst, int dlen, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq); static int dsa_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa); static int dsa_init(DSA *dsa); static int dsa_finish(DSA *dsa); static BIGNUM *dsa_mod_inverse_fermat(const BIGNUM *k, const BIGNUM *q, BN_CTX *ctx); static DSA_METHOD openssl_dsa_meth = { "OpenSSL DSA method", dsa_do_sign, dsa_sign_setup_no_digest, dsa_do_verify, NULL, /* dsa_mod_exp, */ NULL, /* dsa_bn_mod_exp, */ dsa_init, dsa_finish, DSA_FLAG_FIPS_METHOD, NULL, NULL, NULL }; static const DSA_METHOD *default_DSA_method = &openssl_dsa_meth; #ifndef FIPS_MODULE void DSA_set_default_method(const DSA_METHOD *meth) { default_DSA_method = meth; } #endif /* FIPS_MODULE */ const DSA_METHOD *DSA_get_default_method(void) { return default_DSA_method; } const DSA_METHOD *DSA_OpenSSL(void) { return &openssl_dsa_meth; } DSA_SIG *ossl_dsa_do_sign_int(const unsigned char *dgst, int dlen, DSA *dsa, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq) { BIGNUM *kinv = NULL; BIGNUM *m, *blind, *blindm, *tmp; BN_CTX *ctx = NULL; int reason = ERR_R_BN_LIB; DSA_SIG *ret = NULL; int rv = 0; int retries = 0; if (dsa->params.p == NULL || dsa->params.q == NULL || dsa->params.g == NULL) { reason = DSA_R_MISSING_PARAMETERS; goto err; } if (dsa->priv_key == NULL) { reason = DSA_R_MISSING_PRIVATE_KEY; goto err; } ret = DSA_SIG_new(); if (ret == NULL) goto err; ret->r = BN_new(); ret->s = BN_new(); if (ret->r == NULL || ret->s == NULL) goto err; ctx = BN_CTX_new_ex(dsa->libctx); if (ctx == NULL) goto err; m = BN_CTX_get(ctx); blind = BN_CTX_get(ctx); blindm = BN_CTX_get(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) goto err; redo: if (!dsa_sign_setup(dsa, ctx, &kinv, &ret->r, dgst, dlen, nonce_type, digestname, libctx, propq)) goto err; if (dlen > BN_num_bytes(dsa->params.q)) /* * if the digest length is greater than the size of q use the * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3, * 4.2 */ dlen = BN_num_bytes(dsa->params.q); if (BN_bin2bn(dgst, dlen, m) == NULL) goto err; /* * The normal signature calculation is: * * s := k^-1 * (m + r * priv_key) mod q * * We will blind this to protect against side channel attacks * * s := blind^-1 * k^-1 * (blind * m + blind * r * priv_key) mod q */ /* * Generate a blinding value * The size of q is tested in dsa_sign_setup() so there should not be an infinite loop here. */ do { if (!BN_priv_rand_ex(blind, BN_num_bits(dsa->params.q) - 1, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY, 0, ctx)) goto err; } while (BN_is_zero(blind)); BN_set_flags(blind, BN_FLG_CONSTTIME); BN_set_flags(blindm, BN_FLG_CONSTTIME); BN_set_flags(tmp, BN_FLG_CONSTTIME); /* tmp := blind * priv_key * r mod q */ if (!BN_mod_mul(tmp, blind, dsa->priv_key, dsa->params.q, ctx)) goto err; if (!BN_mod_mul(tmp, tmp, ret->r, dsa->params.q, ctx)) goto err; /* blindm := blind * m mod q */ if (!BN_mod_mul(blindm, blind, m, dsa->params.q, ctx)) goto err; /* s : = (blind * priv_key * r) + (blind * m) mod q */ if (!BN_mod_add_quick(ret->s, tmp, blindm, dsa->params.q)) goto err; /* s := s * k^-1 mod q */ if (!BN_mod_mul(ret->s, ret->s, kinv, dsa->params.q, ctx)) goto err; /* s:= s * blind^-1 mod q */ if (BN_mod_inverse(blind, blind, dsa->params.q, ctx) == NULL) goto err; if (!BN_mod_mul(ret->s, ret->s, blind, dsa->params.q, ctx)) goto err; /* * Redo if r or s is zero as required by FIPS 186-4: Section 4.6 * This is very unlikely. * Limit the retries so there is no possibility of an infinite * loop for bad domain parameter values. */ if (BN_is_zero(ret->r) || BN_is_zero(ret->s)) { if (retries++ > MAX_DSA_SIGN_RETRIES) { reason = DSA_R_TOO_MANY_RETRIES; goto err; } goto redo; } rv = 1; err: if (rv == 0) { ERR_raise(ERR_LIB_DSA, reason); DSA_SIG_free(ret); ret = NULL; } BN_CTX_free(ctx); BN_clear_free(kinv); return ret; } static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) { return ossl_dsa_do_sign_int(dgst, dlen, dsa, 0, NULL, NULL, NULL); } static int dsa_sign_setup_no_digest(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { return dsa_sign_setup(dsa, ctx_in, kinvp, rp, NULL, 0, 0, NULL, NULL, NULL); } static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp, const unsigned char *dgst, int dlen, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq) { BN_CTX *ctx = NULL; BIGNUM *k, *kinv = NULL, *r = *rp; BIGNUM *l; int ret = 0; int q_bits, q_words; if (!dsa->params.p || !dsa->params.q || !dsa->params.g) { ERR_raise(ERR_LIB_DSA, DSA_R_MISSING_PARAMETERS); return 0; } /* Reject obviously invalid parameters */ if (BN_is_zero(dsa->params.p) || BN_is_zero(dsa->params.q) || BN_is_zero(dsa->params.g) || BN_is_negative(dsa->params.p) || BN_is_negative(dsa->params.q) || BN_is_negative(dsa->params.g)) { ERR_raise(ERR_LIB_DSA, DSA_R_INVALID_PARAMETERS); return 0; } if (dsa->priv_key == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_MISSING_PRIVATE_KEY); return 0; } k = BN_new(); l = BN_new(); if (k == NULL || l == NULL) goto err; if (ctx_in == NULL) { /* if you don't pass in ctx_in you get a default libctx */ if ((ctx = BN_CTX_new_ex(NULL)) == NULL) goto err; } else ctx = ctx_in; /* Preallocate space */ q_bits = BN_num_bits(dsa->params.q); q_words = bn_get_top(dsa->params.q); if (q_bits < MIN_DSA_SIGN_QBITS || !bn_wexpand(k, q_words + 2) || !bn_wexpand(l, q_words + 2)) goto err; /* Get random k */ do { if (dgst != NULL) { if (nonce_type == 1) { #ifndef FIPS_MODULE if (!ossl_gen_deterministic_nonce_rfc6979(k, dsa->params.q, dsa->priv_key, dgst, dlen, digestname, libctx, propq)) #endif goto err; } else { /* * We calculate k from SHA512(private_key + H(message) + random). * This protects the private key from a weak PRNG. */ if (!BN_generate_dsa_nonce(k, dsa->params.q, dsa->priv_key, dgst, dlen, ctx)) goto err; } } else if (!BN_priv_rand_range_ex(k, dsa->params.q, 0, ctx)) goto err; } while (BN_is_zero(k)); BN_set_flags(k, BN_FLG_CONSTTIME); BN_set_flags(l, BN_FLG_CONSTTIME); if (dsa->flags & DSA_FLAG_CACHE_MONT_P) { if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p, dsa->lock, dsa->params.p, ctx)) goto err; } /* Compute r = (g^k mod p) mod q */ /* * We do not want timing information to leak the length of k, so we * compute G^k using an equivalent scalar of fixed bit-length. * * We unconditionally perform both of these additions to prevent a * small timing information leakage. We then choose the sum that is * one bit longer than the modulus. * * There are some concerns about the efficacy of doing this. More * specifically refer to the discussion starting with: * https://github.com/openssl/openssl/pull/7486#discussion_r228323705 * The fix is to rework BN so these gymnastics aren't required. */ if (!BN_add(l, k, dsa->params.q) || !BN_add(k, l, dsa->params.q)) goto err; BN_consttime_swap(BN_is_bit_set(l, q_bits), k, l, q_words + 2); if ((dsa)->meth->bn_mod_exp != NULL) { if (!dsa->meth->bn_mod_exp(dsa, r, dsa->params.g, k, dsa->params.p, ctx, dsa->method_mont_p)) goto err; } else { if (!BN_mod_exp_mont(r, dsa->params.g, k, dsa->params.p, ctx, dsa->method_mont_p)) goto err; } if (!BN_mod(r, r, dsa->params.q, ctx)) goto err; /* Compute part of 's = inv(k) (m + xr) mod q' */ if ((kinv = dsa_mod_inverse_fermat(k, dsa->params.q, ctx)) == NULL) goto err; BN_clear_free(*kinvp); *kinvp = kinv; kinv = NULL; ret = 1; err: if (!ret) ERR_raise(ERR_LIB_DSA, ERR_R_BN_LIB); if (ctx != ctx_in) BN_CTX_free(ctx); BN_clear_free(k); BN_clear_free(l); return ret; } static int dsa_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa) { BN_CTX *ctx; BIGNUM *u1, *u2, *t1; BN_MONT_CTX *mont = NULL; const BIGNUM *r, *s; int ret = -1, i; if (dsa->params.p == NULL || dsa->params.q == NULL || dsa->params.g == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_MISSING_PARAMETERS); return -1; } i = BN_num_bits(dsa->params.q); /* fips 186-3 allows only different sizes for q */ if (i != 160 && i != 224 && i != 256) { ERR_raise(ERR_LIB_DSA, DSA_R_BAD_Q_VALUE); return -1; } if (BN_num_bits(dsa->params.p) > OPENSSL_DSA_MAX_MODULUS_BITS) { ERR_raise(ERR_LIB_DSA, DSA_R_MODULUS_TOO_LARGE); return -1; } u1 = BN_new(); u2 = BN_new(); t1 = BN_new(); ctx = BN_CTX_new_ex(NULL); /* verify does not need a libctx */ if (u1 == NULL || u2 == NULL || t1 == NULL || ctx == NULL) goto err; DSA_SIG_get0(sig, &r, &s); if (BN_is_zero(r) || BN_is_negative(r) || BN_ucmp(r, dsa->params.q) >= 0) { ret = 0; goto err; } if (BN_is_zero(s) || BN_is_negative(s) || BN_ucmp(s, dsa->params.q) >= 0) { ret = 0; goto err; } /* * Calculate W = inv(S) mod Q save W in u2 */ if ((BN_mod_inverse(u2, s, dsa->params.q, ctx)) == NULL) goto err; /* save M in u1 */ if (dgst_len > (i >> 3)) /* * if the digest length is greater than the size of q use the * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3, * 4.2 */ dgst_len = (i >> 3); if (BN_bin2bn(dgst, dgst_len, u1) == NULL) goto err; /* u1 = M * w mod q */ if (!BN_mod_mul(u1, u1, u2, dsa->params.q, ctx)) goto err; /* u2 = r * w mod q */ if (!BN_mod_mul(u2, r, u2, dsa->params.q, ctx)) goto err; if (dsa->flags & DSA_FLAG_CACHE_MONT_P) { mont = BN_MONT_CTX_set_locked(&dsa->method_mont_p, dsa->lock, dsa->params.p, ctx); if (!mont) goto err; } if (dsa->meth->dsa_mod_exp != NULL) { if (!dsa->meth->dsa_mod_exp(dsa, t1, dsa->params.g, u1, dsa->pub_key, u2, dsa->params.p, ctx, mont)) goto err; } else { if (!BN_mod_exp2_mont(t1, dsa->params.g, u1, dsa->pub_key, u2, dsa->params.p, ctx, mont)) goto err; } /* let u1 = u1 mod q */ if (!BN_mod(u1, t1, dsa->params.q, ctx)) goto err; /* * V is now in u1. If the signature is correct, it will be equal to R. */ ret = (BN_ucmp(u1, r) == 0); err: if (ret < 0) ERR_raise(ERR_LIB_DSA, ERR_R_BN_LIB); BN_CTX_free(ctx); BN_free(u1); BN_free(u2); BN_free(t1); return ret; } static int dsa_init(DSA *dsa) { dsa->flags |= DSA_FLAG_CACHE_MONT_P; ossl_ffc_params_init(&dsa->params); dsa->dirty_cnt++; return 1; } static int dsa_finish(DSA *dsa) { BN_MONT_CTX_free(dsa->method_mont_p); return 1; } /* * Compute the inverse of k modulo q. * Since q is prime, Fermat's Little Theorem applies, which reduces this to * mod-exp operation. Both the exponent and modulus are public information * so a mod-exp that doesn't leak the base is sufficient. A newly allocated * BIGNUM is returned which the caller must free. */ static BIGNUM *dsa_mod_inverse_fermat(const BIGNUM *k, const BIGNUM *q, BN_CTX *ctx) { BIGNUM *res = NULL; BIGNUM *r, *e; if ((r = BN_new()) == NULL) return NULL; BN_CTX_start(ctx); if ((e = BN_CTX_get(ctx)) != NULL && BN_set_word(r, 2) && BN_sub(e, q, r) && BN_mod_exp_mont(r, k, e, q, ctx, NULL)) res = r; else BN_free(r); BN_CTX_end(ctx); return res; }
14,911
28.646123
96
c
openssl
openssl-master/crypto/dsa/dsa_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 */ /* * 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 <openssl/bn.h> #include "crypto/evp.h" #include "dsa_local.h" /* DSA pkey context structure */ typedef struct { /* Parameter gen parameters */ int nbits; /* size of p in bits (default: 2048) */ int qbits; /* size of q in bits (default: 224) */ const EVP_MD *pmd; /* MD for parameter generation */ /* Keygen callback info */ int gentmp[2]; /* message digest */ const EVP_MD *md; /* MD for the signature */ } DSA_PKEY_CTX; static int pkey_dsa_init(EVP_PKEY_CTX *ctx) { DSA_PKEY_CTX *dctx = OPENSSL_malloc(sizeof(*dctx)); if (dctx == NULL) return 0; dctx->nbits = 2048; dctx->qbits = 224; dctx->pmd = NULL; dctx->md = NULL; ctx->data = dctx; ctx->keygen_info = dctx->gentmp; ctx->keygen_info_count = 2; return 1; } static int pkey_dsa_copy(EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src) { DSA_PKEY_CTX *dctx, *sctx; if (!pkey_dsa_init(dst)) return 0; sctx = src->data; dctx = dst->data; dctx->nbits = sctx->nbits; dctx->qbits = sctx->qbits; dctx->pmd = sctx->pmd; dctx->md = sctx->md; return 1; } static void pkey_dsa_cleanup(EVP_PKEY_CTX *ctx) { DSA_PKEY_CTX *dctx = ctx->data; OPENSSL_free(dctx); } static int pkey_dsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen) { int ret; unsigned int sltmp; DSA_PKEY_CTX *dctx = ctx->data; /* * Discard const. Its marked as const because this may be a cached copy of * the "real" key. These calls don't make any modifications that need to * be reflected back in the "original" key. */ DSA *dsa = (DSA *)EVP_PKEY_get0_DSA(ctx->pkey); if (dctx->md != NULL && tbslen != (size_t)EVP_MD_get_size(dctx->md)) return 0; ret = DSA_sign(0, tbs, tbslen, sig, &sltmp, dsa); if (ret <= 0) return ret; *siglen = sltmp; return 1; } static int pkey_dsa_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig, size_t siglen, const unsigned char *tbs, size_t tbslen) { int ret; DSA_PKEY_CTX *dctx = ctx->data; /* * Discard const. Its marked as const because this may be a cached copy of * the "real" key. These calls don't make any modifications that need to * be reflected back in the "original" key. */ DSA *dsa = (DSA *)EVP_PKEY_get0_DSA(ctx->pkey); if (dctx->md != NULL && tbslen != (size_t)EVP_MD_get_size(dctx->md)) return 0; ret = DSA_verify(0, tbs, tbslen, sig, siglen, dsa); return ret; } static int pkey_dsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { DSA_PKEY_CTX *dctx = ctx->data; switch (type) { case EVP_PKEY_CTRL_DSA_PARAMGEN_BITS: if (p1 < 256) return -2; dctx->nbits = p1; return 1; case EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS: if (p1 != 160 && p1 != 224 && p1 && p1 != 256) return -2; dctx->qbits = p1; return 1; case EVP_PKEY_CTRL_DSA_PARAMGEN_MD: if (EVP_MD_get_type((const EVP_MD *)p2) != NID_sha1 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha224 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha256) { ERR_raise(ERR_LIB_DSA, DSA_R_INVALID_DIGEST_TYPE); return 0; } dctx->pmd = p2; return 1; case EVP_PKEY_CTRL_MD: if (EVP_MD_get_type((const EVP_MD *)p2) != NID_sha1 && EVP_MD_get_type((const EVP_MD *)p2) != NID_dsa && EVP_MD_get_type((const EVP_MD *)p2) != NID_dsaWithSHA && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha224 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha256 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha384 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha512 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_224 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_256 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_384 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_512) { ERR_raise(ERR_LIB_DSA, DSA_R_INVALID_DIGEST_TYPE); return 0; } dctx->md = p2; return 1; case EVP_PKEY_CTRL_GET_MD: *(const EVP_MD **)p2 = dctx->md; return 1; case EVP_PKEY_CTRL_DIGESTINIT: case EVP_PKEY_CTRL_PKCS7_SIGN: case EVP_PKEY_CTRL_CMS_SIGN: return 1; case EVP_PKEY_CTRL_PEER_KEY: ERR_raise(ERR_LIB_DSA, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; default: return -2; } } static int pkey_dsa_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { if (strcmp(type, "dsa_paramgen_bits") == 0) { int nbits; nbits = atoi(value); return EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, nbits); } if (strcmp(type, "dsa_paramgen_q_bits") == 0) { int qbits = atoi(value); return EVP_PKEY_CTX_set_dsa_paramgen_q_bits(ctx, qbits); } if (strcmp(type, "dsa_paramgen_md") == 0) { const EVP_MD *md = EVP_get_digestbyname(value); if (md == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_INVALID_DIGEST_TYPE); return 0; } return EVP_PKEY_CTX_set_dsa_paramgen_md(ctx, md); } return -2; } static int pkey_dsa_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { DSA *dsa = NULL; DSA_PKEY_CTX *dctx = ctx->data; BN_GENCB *pcb; int ret, res; if (ctx->pkey_gencb) { pcb = BN_GENCB_new(); if (pcb == NULL) return 0; evp_pkey_set_cb_translate(pcb, ctx); } else pcb = NULL; dsa = DSA_new(); if (dsa == NULL) { BN_GENCB_free(pcb); return 0; } if (dctx->md != NULL) ossl_ffc_set_digest(&dsa->params, EVP_MD_get0_name(dctx->md), NULL); ret = ossl_ffc_params_FIPS186_4_generate(NULL, &dsa->params, FFC_PARAM_TYPE_DSA, dctx->nbits, dctx->qbits, &res, pcb); BN_GENCB_free(pcb); if (ret > 0) EVP_PKEY_assign_DSA(pkey, dsa); else DSA_free(dsa); return ret; } static int pkey_dsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { DSA *dsa = NULL; if (ctx->pkey == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_NO_PARAMETERS_SET); return 0; } dsa = DSA_new(); if (dsa == NULL) return 0; EVP_PKEY_assign_DSA(pkey, dsa); /* Note: if error return, pkey is freed by parent routine */ if (!EVP_PKEY_copy_parameters(pkey, ctx->pkey)) return 0; return DSA_generate_key((DSA *)EVP_PKEY_get0_DSA(pkey)); } static const EVP_PKEY_METHOD dsa_pkey_meth = { EVP_PKEY_DSA, EVP_PKEY_FLAG_AUTOARGLEN, pkey_dsa_init, pkey_dsa_copy, pkey_dsa_cleanup, 0, pkey_dsa_paramgen, 0, pkey_dsa_keygen, 0, pkey_dsa_sign, 0, pkey_dsa_verify, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, pkey_dsa_ctrl, pkey_dsa_ctrl_str }; const EVP_PKEY_METHOD *ossl_dsa_pkey_method(void) { return &dsa_pkey_meth; }
7,963
25.724832
79
c
openssl
openssl-master/crypto/dsa/dsa_prn.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 */ /* * 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/evp.h> #include <openssl/dsa.h> #ifndef OPENSSL_NO_STDIO int DSA_print_fp(FILE *fp, const DSA *x, int off) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = DSA_print(b, x, off); BIO_free(b); return ret; } int DSAparams_print_fp(FILE *fp, const DSA *x) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = DSAparams_print(b, x); BIO_free(b); return ret; } #endif int DSA_print(BIO *bp, const DSA *x, int off) { EVP_PKEY *pk; int ret; pk = EVP_PKEY_new(); if (pk == NULL) return 0; ret = EVP_PKEY_set1_DSA(pk, (DSA *)x); if (ret) ret = EVP_PKEY_print_private(bp, pk, off, NULL); EVP_PKEY_free(pk); return ret; } int DSAparams_print(BIO *bp, const DSA *x) { EVP_PKEY *pk; int ret; pk = EVP_PKEY_new(); if (pk == NULL) return 0; ret = EVP_PKEY_set1_DSA(pk, (DSA *)x); if (ret) ret = EVP_PKEY_print_params(bp, pk, 4, NULL); EVP_PKEY_free(pk); return ret; }
1,783
21.3
74
c
openssl
openssl-master/crypto/dsa/dsa_sign.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 */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/bn.h> #include "internal/cryptlib.h" #include "dsa_local.h" #include "crypto/asn1_dsa.h" #include "crypto/dsa.h" DSA_SIG *DSA_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) { return dsa->meth->dsa_do_sign(dgst, dlen, dsa); } #ifndef OPENSSL_NO_DEPRECATED_3_0 int DSA_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { return dsa->meth->dsa_sign_setup(dsa, ctx_in, kinvp, rp); } #endif DSA_SIG *DSA_SIG_new(void) { DSA_SIG *sig = OPENSSL_zalloc(sizeof(*sig)); return sig; } void DSA_SIG_free(DSA_SIG *sig) { if (sig == NULL) return; BN_clear_free(sig->r); BN_clear_free(sig->s); OPENSSL_free(sig); } DSA_SIG *d2i_DSA_SIG(DSA_SIG **psig, const unsigned char **ppin, long len) { DSA_SIG *sig; if (len < 0) return NULL; if (psig != NULL && *psig != NULL) { sig = *psig; } else { sig = DSA_SIG_new(); if (sig == NULL) return NULL; } if (sig->r == NULL) sig->r = BN_new(); if (sig->s == NULL) sig->s = BN_new(); if (sig->r == NULL || sig->s == NULL || ossl_decode_der_dsa_sig(sig->r, sig->s, ppin, (size_t)len) == 0) { if (psig == NULL || *psig == NULL) DSA_SIG_free(sig); return NULL; } if (psig != NULL && *psig == NULL) *psig = sig; return sig; } int i2d_DSA_SIG(const DSA_SIG *sig, unsigned char **ppout) { BUF_MEM *buf = NULL; size_t encoded_len; WPACKET pkt; if (ppout == NULL) { if (!WPACKET_init_null(&pkt, 0)) return -1; } else if (*ppout == NULL) { if ((buf = BUF_MEM_new()) == NULL || !WPACKET_init_len(&pkt, buf, 0)) { BUF_MEM_free(buf); return -1; } } else { if (!WPACKET_init_static_len(&pkt, *ppout, SIZE_MAX, 0)) return -1; } if (!ossl_encode_der_dsa_sig(&pkt, sig->r, sig->s) || !WPACKET_get_total_written(&pkt, &encoded_len) || !WPACKET_finish(&pkt)) { BUF_MEM_free(buf); WPACKET_cleanup(&pkt); return -1; } if (ppout != NULL) { if (*ppout == NULL) { *ppout = (unsigned char *)buf->data; buf->data = NULL; BUF_MEM_free(buf); } else { *ppout += encoded_len; } } return (int)encoded_len; } int DSA_size(const DSA *dsa) { int ret = -1; DSA_SIG sig; if (dsa->params.q != NULL) { sig.r = sig.s = dsa->params.q; ret = i2d_DSA_SIG(&sig, NULL); if (ret < 0) ret = 0; } return ret; } void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps) { if (pr != NULL) *pr = sig->r; if (ps != NULL) *ps = sig->s; } int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s) { if (r == NULL || s == NULL) return 0; BN_clear_free(sig->r); BN_clear_free(sig->s); sig->r = r; sig->s = s; return 1; } int ossl_dsa_sign_int(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, DSA *dsa, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq) { DSA_SIG *s; /* legacy case uses the method table */ if (dsa->libctx == NULL || dsa->meth != DSA_get_default_method()) s = DSA_do_sign(dgst, dlen, dsa); else s = ossl_dsa_do_sign_int(dgst, dlen, dsa, nonce_type, digestname, libctx, propq); if (s == NULL) { *siglen = 0; return 0; } *siglen = i2d_DSA_SIG(s, sig != NULL ? &sig : NULL); DSA_SIG_free(s); return 1; } int DSA_sign(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, DSA *dsa) { return ossl_dsa_sign_int(type, dgst, dlen, sig, siglen, dsa, 0, NULL, NULL, NULL); } /* data has already been hashed (probably with SHA or SHA-1). */ /*- * returns * 1: correct signature * 0: incorrect signature * -1: error */ int DSA_verify(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int siglen, DSA *dsa) { DSA_SIG *s; const unsigned char *p = sigbuf; unsigned char *der = NULL; int derlen = -1; int ret = -1; s = DSA_SIG_new(); if (s == NULL) return ret; if (d2i_DSA_SIG(&s, &p, siglen) == NULL) goto err; /* Ensure signature uses DER and doesn't have trailing garbage */ derlen = i2d_DSA_SIG(s, &der); if (derlen != siglen || memcmp(sigbuf, der, derlen)) goto err; ret = DSA_do_verify(dgst, dgst_len, s, dsa); err: OPENSSL_clear_free(der, derlen); DSA_SIG_free(s); return ret; }
5,338
24.065728
77
c
openssl
openssl-master/crypto/dsa/dsa_vrf.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 */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "internal/cryptlib.h" #include "dsa_local.h" int DSA_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa) { return dsa->meth->dsa_do_verify(dgst, dgst_len, sig, dsa); }
688
27.708333
74
c
openssl
openssl-master/crypto/dso/dso_dl.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 */ #include "dso_local.h" #ifdef DSO_DL # include <dl.h> /* Part of the hack in "dl_load" ... */ # define DSO_MAX_TRANSLATED_SIZE 256 static int dl_load(DSO *dso); static int dl_unload(DSO *dso); static DSO_FUNC_TYPE dl_bind_func(DSO *dso, const char *symname); static char *dl_name_converter(DSO *dso, const char *filename); static char *dl_merger(DSO *dso, const char *filespec1, const char *filespec2); static int dl_pathbyaddr(void *addr, char *path, int sz); static void *dl_globallookup(const char *name); static DSO_METHOD dso_meth_dl = { "OpenSSL 'dl' shared library method", dl_load, dl_unload, dl_bind_func, NULL, /* ctrl */ dl_name_converter, dl_merger, NULL, /* init */ NULL, /* finish */ dl_pathbyaddr, dl_globallookup }; DSO_METHOD *DSO_METHOD_openssl(void) { return &dso_meth_dl; } /* * For this DSO_METHOD, our meth_data STACK will contain; (i) the handle * (shl_t) returned from shl_load(). NB: I checked on HPUX11 and shl_t is * itself a pointer type so the cast is safe. */ static int dl_load(DSO *dso) { shl_t ptr = NULL; /* * We don't do any fancy retries or anything, just take the method's (or * DSO's if it has the callback set) best translation of the * platform-independent filename and try once with that. */ char *filename = DSO_convert_filename(dso, NULL); if (filename == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NO_FILENAME); goto err; } ptr = shl_load(filename, BIND_IMMEDIATE | (dso->flags & DSO_FLAG_NO_NAME_TRANSLATION ? 0 : DYNAMIC_PATH), 0L); if (ptr == NULL) { char errbuf[160]; if (openssl_strerror_r(errno, errbuf, sizeof(errbuf))) ERR_raise_data(ERR_LIB_DSO, DSO_R_LOAD_FAILED, "filename(%s): %s", filename, errbuf); else ERR_raise_data(ERR_LIB_DSO, DSO_R_LOAD_FAILED, "filename(%s): errno %d", filename, errno); goto err; } if (!sk_push(dso->meth_data, (char *)ptr)) { ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR); goto err; } /* * Success, stick the converted filename we've loaded under into the DSO * (it also serves as the indicator that we are currently loaded). */ dso->loaded_filename = filename; return 1; err: /* Cleanup! */ OPENSSL_free(filename); if (ptr != NULL) shl_unload(ptr); return 0; } static int dl_unload(DSO *dso) { shl_t ptr; if (dso == NULL) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (sk_num(dso->meth_data) < 1) return 1; /* Is this statement legal? */ ptr = (shl_t) sk_pop(dso->meth_data); if (ptr == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE); /* * Should push the value back onto the stack in case of a retry. */ sk_push(dso->meth_data, (char *)ptr); return 0; } shl_unload(ptr); return 1; } static DSO_FUNC_TYPE dl_bind_func(DSO *dso, const char *symname) { shl_t ptr; void *sym; if ((dso == NULL) || (symname == NULL)) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (sk_num(dso->meth_data) < 1) { ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR); return NULL; } ptr = (shl_t) sk_value(dso->meth_data, sk_num(dso->meth_data) - 1); if (ptr == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE); return NULL; } if (shl_findsym(&ptr, symname, TYPE_UNDEFINED, &sym) < 0) { char errbuf[160]; if (openssl_strerror_r(errno, errbuf, sizeof(errbuf))) ERR_raise_data(ERR_LIB_DSO, DSO_R_SYM_FAILURE, "symname(%s): %s", symname, errbuf); else ERR_raise_data(ERR_LIB_DSO, DSO_R_SYM_FAILURE, "symname(%s): errno %d", symname, errno); return NULL; } return (DSO_FUNC_TYPE)sym; } static char *dl_merger(DSO *dso, const char *filespec1, const char *filespec2) { char *merged; if (!filespec1 && !filespec2) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } /* * If the first file specification is a rooted path, it rules. same goes * if the second file specification is missing. */ if (!filespec2 || filespec1[0] == '/') { merged = OPENSSL_strdup(filespec1); if (merged == NULL) return NULL; } /* * If the first file specification is missing, the second one rules. */ else if (!filespec1) { merged = OPENSSL_strdup(filespec2); if (merged == NULL) return NULL; } else /* * This part isn't as trivial as it looks. It assumes that the * second file specification really is a directory, and makes no * checks whatsoever. Therefore, the result becomes the * concatenation of filespec2 followed by a slash followed by * filespec1. */ { int spec2len, len; spec2len = (filespec2 ? strlen(filespec2) : 0); len = spec2len + (filespec1 ? strlen(filespec1) : 0); if (spec2len && filespec2[spec2len - 1] == '/') { spec2len--; len--; } merged = OPENSSL_malloc(len + 2); if (merged == NULL) return NULL; strcpy(merged, filespec2); merged[spec2len] = '/'; strcpy(&merged[spec2len + 1], filespec1); } return merged; } /* * This function is identical to the one in dso_dlfcn.c, but as it is highly * unlikely that both the "dl" *and* "dlfcn" variants are being compiled at * the same time, there's no great duplicating the code. Figuring out an * elegant way to share one copy of the code would be more difficult and * would not leave the implementations independent. */ static char *dl_name_converter(DSO *dso, const char *filename) { char *translated; int len, rsize, transform; len = strlen(filename); rsize = len + 1; transform = (strstr(filename, "/") == NULL); if (transform) { /* We will convert this to "%s.s?" or "lib%s.s?" */ rsize += strlen(DSO_EXTENSION); /* The length of ".s?" */ if ((DSO_flags(dso) & DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == 0) rsize += 3; /* The length of "lib" */ } translated = OPENSSL_malloc(rsize); if (translated == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NAME_TRANSLATION_FAILED); return NULL; } if (transform) { if ((DSO_flags(dso) & DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == 0) sprintf(translated, "lib%s%s", filename, DSO_EXTENSION); else sprintf(translated, "%s%s", filename, DSO_EXTENSION); } else sprintf(translated, "%s", filename); return translated; } static int dl_pathbyaddr(void *addr, char *path, int sz) { struct shl_descriptor inf; int i, len; if (addr == NULL) { union { int (*f) (void *, char *, int); void *p; } t = { dl_pathbyaddr }; addr = t.p; } for (i = -1; shl_get_r(i, &inf) == 0; i++) { if (((size_t)addr >= inf.tstart && (size_t)addr < inf.tend) || ((size_t)addr >= inf.dstart && (size_t)addr < inf.dend)) { len = (int)strlen(inf.filename); if (sz <= 0) return len + 1; if (len >= sz) len = sz - 1; memcpy(path, inf.filename, len); path[len++] = 0; return len; } } return -1; } static void *dl_globallookup(const char *name) { void *ret; shl_t h = NULL; return shl_findsym(&h, name, TYPE_UNDEFINED, &ret) ? NULL : ret; } #endif /* DSO_DL */
8,368
28.677305
78
c
openssl
openssl-master/crypto/dso/dso_dlfcn.c
/* * Copyright 2000-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 */ /* * We need to do this early, because stdio.h includes the header files that * handle _GNU_SOURCE and other similar macros. Defining it later is simply * too late, because those headers are protected from re- inclusion. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE /* make sure dladdr is declared */ #endif #include "dso_local.h" #include "internal/e_os.h" #ifdef DSO_DLFCN # ifdef HAVE_DLFCN_H # ifdef __osf__ # define __EXTENSIONS__ # endif # include <dlfcn.h> # define HAVE_DLINFO 1 # if defined(__SCO_VERSION__) || defined(_SCO_ELF) || \ (defined(__osf__) && !defined(RTLD_NEXT)) || \ (defined(__OpenBSD__) && !defined(RTLD_SELF)) || \ defined(__ANDROID__) || defined(__TANDEM) # undef HAVE_DLINFO # endif # endif /* Part of the hack in "dlfcn_load" ... */ # define DSO_MAX_TRANSLATED_SIZE 256 static int dlfcn_load(DSO *dso); static int dlfcn_unload(DSO *dso); static DSO_FUNC_TYPE dlfcn_bind_func(DSO *dso, const char *symname); static char *dlfcn_name_converter(DSO *dso, const char *filename); static char *dlfcn_merger(DSO *dso, const char *filespec1, const char *filespec2); static int dlfcn_pathbyaddr(void *addr, char *path, int sz); static void *dlfcn_globallookup(const char *name); static DSO_METHOD dso_meth_dlfcn = { "OpenSSL 'dlfcn' shared library method", dlfcn_load, dlfcn_unload, dlfcn_bind_func, NULL, /* ctrl */ dlfcn_name_converter, dlfcn_merger, NULL, /* init */ NULL, /* finish */ dlfcn_pathbyaddr, dlfcn_globallookup }; DSO_METHOD *DSO_METHOD_openssl(void) { return &dso_meth_dlfcn; } /* * Prior to using the dlopen() function, we should decide on the flag we * send. There's a few different ways of doing this and it's a messy * venn-diagram to match up which platforms support what. So as we don't have * autoconf yet, I'm implementing a hack that could be hacked further * relatively easily to deal with cases as we find them. Initially this is to * cope with OpenBSD. */ # if defined(__OpenBSD__) || defined(__NetBSD__) # ifdef DL_LAZY # define DLOPEN_FLAG DL_LAZY # else # ifdef RTLD_NOW # define DLOPEN_FLAG RTLD_NOW # else # define DLOPEN_FLAG 0 # endif # endif # else # define DLOPEN_FLAG RTLD_NOW /* Hope this works everywhere else */ # endif /* * For this DSO_METHOD, our meth_data STACK will contain; (i) the handle * (void*) returned from dlopen(). */ static int dlfcn_load(DSO *dso) { void *ptr = NULL; /* See applicable comments in dso_dl.c */ char *filename = DSO_convert_filename(dso, NULL); int flags = DLOPEN_FLAG; int saveerrno = get_last_sys_error(); if (filename == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NO_FILENAME); goto err; } # ifdef RTLD_GLOBAL if (dso->flags & DSO_FLAG_GLOBAL_SYMBOLS) flags |= RTLD_GLOBAL; # endif # ifdef _AIX if (filename[strlen(filename) - 1] == ')') flags |= RTLD_MEMBER; # endif ptr = dlopen(filename, flags); if (ptr == NULL) { ERR_raise_data(ERR_LIB_DSO, DSO_R_LOAD_FAILED, "filename(%s): %s", filename, dlerror()); goto err; } /* * Some dlopen() implementations (e.g. solaris) do no preserve errno, even * on a successful call. */ set_sys_error(saveerrno); if (!sk_void_push(dso->meth_data, (char *)ptr)) { ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR); goto err; } /* Success */ dso->loaded_filename = filename; return 1; err: /* Cleanup! */ OPENSSL_free(filename); if (ptr != NULL) dlclose(ptr); return 0; } static int dlfcn_unload(DSO *dso) { void *ptr; if (dso == NULL) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (sk_void_num(dso->meth_data) < 1) return 1; ptr = sk_void_pop(dso->meth_data); if (ptr == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE); /* * Should push the value back onto the stack in case of a retry. */ sk_void_push(dso->meth_data, ptr); return 0; } /* For now I'm not aware of any errors associated with dlclose() */ dlclose(ptr); return 1; } static DSO_FUNC_TYPE dlfcn_bind_func(DSO *dso, const char *symname) { void *ptr; union { DSO_FUNC_TYPE sym; void *dlret; } u; if ((dso == NULL) || (symname == NULL)) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (sk_void_num(dso->meth_data) < 1) { ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR); return NULL; } ptr = sk_void_value(dso->meth_data, sk_void_num(dso->meth_data) - 1); if (ptr == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE); return NULL; } u.dlret = dlsym(ptr, symname); if (u.dlret == NULL) { ERR_raise_data(ERR_LIB_DSO, DSO_R_SYM_FAILURE, "symname(%s): %s", symname, dlerror()); return NULL; } return u.sym; } static char *dlfcn_merger(DSO *dso, const char *filespec1, const char *filespec2) { char *merged; if (!filespec1 && !filespec2) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } /* * If the first file specification is a rooted path, it rules. same goes * if the second file specification is missing. */ if (!filespec2 || (filespec1 != NULL && filespec1[0] == '/')) { merged = OPENSSL_strdup(filespec1); if (merged == NULL) return NULL; } /* * If the first file specification is missing, the second one rules. */ else if (!filespec1) { merged = OPENSSL_strdup(filespec2); if (merged == NULL) return NULL; } else { /* * This part isn't as trivial as it looks. It assumes that the * second file specification really is a directory, and makes no * checks whatsoever. Therefore, the result becomes the * concatenation of filespec2 followed by a slash followed by * filespec1. */ int spec2len, len; spec2len = strlen(filespec2); len = spec2len + strlen(filespec1); if (spec2len && filespec2[spec2len - 1] == '/') { spec2len--; len--; } merged = OPENSSL_malloc(len + 2); if (merged == NULL) return NULL; strcpy(merged, filespec2); merged[spec2len] = '/'; strcpy(&merged[spec2len + 1], filespec1); } return merged; } static char *dlfcn_name_converter(DSO *dso, const char *filename) { char *translated; int len, rsize, transform; len = strlen(filename); rsize = len + 1; transform = (strstr(filename, "/") == NULL); if (transform) { /* We will convert this to "%s.so" or "lib%s.so" etc */ rsize += strlen(DSO_EXTENSION); /* The length of ".so" */ if ((DSO_flags(dso) & DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == 0) rsize += 3; /* The length of "lib" */ } translated = OPENSSL_malloc(rsize); if (translated == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NAME_TRANSLATION_FAILED); return NULL; } if (transform) { if ((DSO_flags(dso) & DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == 0) sprintf(translated, "lib%s" DSO_EXTENSION, filename); else sprintf(translated, "%s" DSO_EXTENSION, filename); } else sprintf(translated, "%s", filename); return translated; } # ifdef __sgi /*- This is a quote from IRIX manual for dladdr(3c): <dlfcn.h> does not contain a prototype for dladdr or definition of Dl_info. The #include <dlfcn.h> in the SYNOPSIS line is traditional, but contains no dladdr prototype and no IRIX library contains an implementation. Write your own declaration based on the code below. The following code is dependent on internal interfaces that are not part of the IRIX compatibility guarantee; however, there is no future intention to change this interface, so on a practical level, the code below is safe to use on IRIX. */ # include <rld_interface.h> # ifndef _RLD_INTERFACE_DLFCN_H_DLADDR # define _RLD_INTERFACE_DLFCN_H_DLADDR typedef struct Dl_info { const char *dli_fname; void *dli_fbase; const char *dli_sname; void *dli_saddr; int dli_version; int dli_reserved1; long dli_reserved[4]; } Dl_info; # else typedef struct Dl_info Dl_info; # endif # define _RLD_DLADDR 14 static int dladdr(void *address, Dl_info *dl) { void *v; v = _rld_new_interface(_RLD_DLADDR, address, dl); return (int)v; } # endif /* __sgi */ # ifdef _AIX /*- * See IBM's AIX Version 7.2, Technical Reference: * Base Operating System and Extensions, Volume 1 and 2 * https://www.ibm.com/support/knowledgecenter/ssw_aix_72/com.ibm.aix.base/technicalreferences.htm */ # include <sys/ldr.h> # include <errno.h> /* ~ 64 * (sizeof(struct ld_info) + _XOPEN_PATH_MAX + _XOPEN_NAME_MAX) */ # define DLFCN_LDINFO_SIZE 86976 typedef struct Dl_info { const char *dli_fname; } Dl_info; /* * This dladdr()-implementation will also find the ptrgl (Pointer Glue) virtual * address of a function, which is just located in the DATA segment instead of * the TEXT segment. */ static int dladdr(void *ptr, Dl_info *dl) { uintptr_t addr = (uintptr_t)ptr; unsigned int found = 0; struct ld_info *ldinfos, *next_ldi, *this_ldi; if ((ldinfos = OPENSSL_malloc(DLFCN_LDINFO_SIZE)) == NULL) { errno = ENOMEM; dl->dli_fname = NULL; return 0; } if ((loadquery(L_GETINFO, (void *)ldinfos, DLFCN_LDINFO_SIZE)) < 0) { /*- * Error handling is done through errno and dlerror() reading errno: * ENOMEM (ldinfos buffer is too small), * EINVAL (invalid flags), * EFAULT (invalid ldinfos ptr) */ OPENSSL_free((void *)ldinfos); dl->dli_fname = NULL; return 0; } next_ldi = ldinfos; do { this_ldi = next_ldi; if (((addr >= (uintptr_t)this_ldi->ldinfo_textorg) && (addr < ((uintptr_t)this_ldi->ldinfo_textorg + this_ldi->ldinfo_textsize))) || ((addr >= (uintptr_t)this_ldi->ldinfo_dataorg) && (addr < ((uintptr_t)this_ldi->ldinfo_dataorg + this_ldi->ldinfo_datasize)))) { char *buffer, *member; size_t buffer_sz, member_len; buffer_sz = strlen(this_ldi->ldinfo_filename) + 1; member = this_ldi->ldinfo_filename + buffer_sz; if ((member_len = strlen(member)) > 0) buffer_sz += 1 + member_len + 1; found = 1; if ((buffer = OPENSSL_malloc(buffer_sz)) != NULL) { OPENSSL_strlcpy(buffer, this_ldi->ldinfo_filename, buffer_sz); if (member_len > 0) { /* * Need to respect a possible member name and not just * returning the path name in this case. See docs: * sys/ldr.h, loadquery() and dlopen()/RTLD_MEMBER. */ OPENSSL_strlcat(buffer, "(", buffer_sz); OPENSSL_strlcat(buffer, member, buffer_sz); OPENSSL_strlcat(buffer, ")", buffer_sz); } dl->dli_fname = buffer; } else { errno = ENOMEM; } } else { next_ldi = (struct ld_info *)((uintptr_t)this_ldi + this_ldi->ldinfo_next); } } while (this_ldi->ldinfo_next && !found); OPENSSL_free((void *)ldinfos); return (found && dl->dli_fname != NULL); } # endif /* _AIX */ static int dlfcn_pathbyaddr(void *addr, char *path, int sz) { # ifdef HAVE_DLINFO Dl_info dli; int len; if (addr == NULL) { union { int (*f) (void *, char *, int); void *p; } t = { dlfcn_pathbyaddr }; addr = t.p; } if (dladdr(addr, &dli)) { len = (int)strlen(dli.dli_fname); if (sz <= 0) { # ifdef _AIX OPENSSL_free((void *)dli.dli_fname); # endif return len + 1; } if (len >= sz) len = sz - 1; memcpy(path, dli.dli_fname, len); path[len++] = 0; # ifdef _AIX OPENSSL_free((void *)dli.dli_fname); # endif return len; } ERR_add_error_data(2, "dlfcn_pathbyaddr(): ", dlerror()); # endif return -1; } static void *dlfcn_globallookup(const char *name) { void *ret = NULL, *handle = dlopen(NULL, RTLD_LAZY); if (handle) { ret = dlsym(handle, name); dlclose(handle); } return ret; } #endif /* DSO_DLFCN */
13,469
28.866962
99
c
openssl
openssl-master/crypto/dso/dso_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * 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 <openssl/err.h> #include "internal/dsoerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA DSO_str_reasons[] = { {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_CTRL_FAILED), "control command failed"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_DSO_ALREADY_LOADED), "dso already loaded"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_EMPTY_FILE_STRUCTURE), "empty file structure"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_FAILURE), "failure"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_FILENAME_TOO_BIG), "filename too big"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_FINISH_FAILED), "cleanup method function failed"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_INCORRECT_FILE_SYNTAX), "incorrect file syntax"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_LOAD_FAILED), "could not load the shared library"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_NAME_TRANSLATION_FAILED), "name translation failed"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_NO_FILENAME), "no filename"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_NULL_HANDLE), "a null shared library handle was used"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_SET_FILENAME_FAILED), "set filename failed"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_STACK_ERROR), "the meth_data stack is corrupt"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_SYM_FAILURE), "could not bind to the requested symbol name"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_UNLOAD_FAILED), "could not unload the shared library"}, {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_UNSUPPORTED), "functionality not supported"}, {0, NULL} }; #endif int ossl_err_load_DSO_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(DSO_str_reasons[0].error) == NULL) ERR_load_strings_const(DSO_str_reasons); #endif return 1; }
2,102
35.894737
79
c
openssl
openssl-master/crypto/dso/dso_lib.c
/* * Copyright 2000-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 "dso_local.h" #include "internal/refcount.h" static DSO *DSO_new_method(DSO_METHOD *meth) { DSO *ret; ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->meth_data = sk_void_new_null(); if (ret->meth_data == NULL) { /* sk_new doesn't generate any errors so we do */ ERR_raise(ERR_LIB_DSO, ERR_R_CRYPTO_LIB); OPENSSL_free(ret); return NULL; } ret->meth = DSO_METHOD_openssl(); if (!CRYPTO_NEW_REF(&ret->references, 1)) { sk_void_free(ret->meth_data); OPENSSL_free(ret); return NULL; } if ((ret->meth->init != NULL) && !ret->meth->init(ret)) { DSO_free(ret); ret = NULL; } return ret; } DSO *DSO_new(void) { return DSO_new_method(NULL); } int DSO_free(DSO *dso) { int i; if (dso == NULL) return 1; if (CRYPTO_DOWN_REF(&dso->references, &i) <= 0) return 0; REF_PRINT_COUNT("DSO", dso); if (i > 0) return 1; REF_ASSERT_ISNT(i < 0); if ((dso->flags & DSO_FLAG_NO_UNLOAD_ON_FREE) == 0) { if ((dso->meth->dso_unload != NULL) && !dso->meth->dso_unload(dso)) { ERR_raise(ERR_LIB_DSO, DSO_R_UNLOAD_FAILED); return 0; } } if ((dso->meth->finish != NULL) && !dso->meth->finish(dso)) { ERR_raise(ERR_LIB_DSO, DSO_R_FINISH_FAILED); return 0; } sk_void_free(dso->meth_data); OPENSSL_free(dso->filename); OPENSSL_free(dso->loaded_filename); CRYPTO_FREE_REF(&dso->references); OPENSSL_free(dso); return 1; } int DSO_flags(DSO *dso) { return ((dso == NULL) ? 0 : dso->flags); } int DSO_up_ref(DSO *dso) { int i; if (dso == NULL) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (CRYPTO_UP_REF(&dso->references, &i) <= 0) return 0; REF_PRINT_COUNT("DSO", dso); REF_ASSERT_ISNT(i < 2); return ((i > 1) ? 1 : 0); } DSO *DSO_load(DSO *dso, const char *filename, DSO_METHOD *meth, int flags) { DSO *ret; int allocated = 0; if (dso == NULL) { ret = DSO_new_method(meth); if (ret == NULL) { ERR_raise(ERR_LIB_DSO, ERR_R_DSO_LIB); goto err; } allocated = 1; /* Pass the provided flags to the new DSO object */ if (DSO_ctrl(ret, DSO_CTRL_SET_FLAGS, flags, NULL) < 0) { ERR_raise(ERR_LIB_DSO, DSO_R_CTRL_FAILED); goto err; } } else ret = dso; /* Don't load if we're currently already loaded */ if (ret->filename != NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_DSO_ALREADY_LOADED); goto err; } /* * filename can only be NULL if we were passed a dso that already has one * set. */ if (filename != NULL) if (!DSO_set_filename(ret, filename)) { ERR_raise(ERR_LIB_DSO, DSO_R_SET_FILENAME_FAILED); goto err; } filename = ret->filename; if (filename == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NO_FILENAME); goto err; } if (ret->meth->dso_load == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED); goto err; } if (!ret->meth->dso_load(ret)) { ERR_raise(ERR_LIB_DSO, DSO_R_LOAD_FAILED); goto err; } /* Load succeeded */ return ret; err: if (allocated) DSO_free(ret); return NULL; } DSO_FUNC_TYPE DSO_bind_func(DSO *dso, const char *symname) { DSO_FUNC_TYPE ret = NULL; if ((dso == NULL) || (symname == NULL)) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (dso->meth->dso_bind_func == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED); return NULL; } if ((ret = dso->meth->dso_bind_func(dso, symname)) == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_SYM_FAILURE); return NULL; } /* Success */ return ret; } /* * I don't really like these *_ctrl functions very much to be perfectly * honest. For one thing, I think I have to return a negative value for any * error because possible DSO_ctrl() commands may return values such as * "size"s that can legitimately be zero (making the standard * "if (DSO_cmd(...))" form that works almost everywhere else fail at odd * times. I'd prefer "output" values to be passed by reference and the return * value as success/failure like usual ... but we conform when we must... :-) */ long DSO_ctrl(DSO *dso, int cmd, long larg, void *parg) { if (dso == NULL) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return -1; } /* * We should intercept certain generic commands and only pass control to * the method-specific ctrl() function if it's something we don't handle. */ switch (cmd) { case DSO_CTRL_GET_FLAGS: return dso->flags; case DSO_CTRL_SET_FLAGS: dso->flags = (int)larg; return 0; case DSO_CTRL_OR_FLAGS: dso->flags |= (int)larg; return 0; default: break; } if ((dso->meth == NULL) || (dso->meth->dso_ctrl == NULL)) { ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED); return -1; } return dso->meth->dso_ctrl(dso, cmd, larg, parg); } const char *DSO_get_filename(DSO *dso) { if (dso == NULL) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } return dso->filename; } int DSO_set_filename(DSO *dso, const char *filename) { char *copied; if ((dso == NULL) || (filename == NULL)) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (dso->loaded_filename) { ERR_raise(ERR_LIB_DSO, DSO_R_DSO_ALREADY_LOADED); return 0; } /* We'll duplicate filename */ copied = OPENSSL_strdup(filename); if (copied == NULL) return 0; OPENSSL_free(dso->filename); dso->filename = copied; return 1; } char *DSO_merge(DSO *dso, const char *filespec1, const char *filespec2) { char *result = NULL; if (dso == NULL || filespec1 == NULL) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((dso->flags & DSO_FLAG_NO_NAME_TRANSLATION) == 0) { if (dso->merger != NULL) result = dso->merger(dso, filespec1, filespec2); else if (dso->meth->dso_merger != NULL) result = dso->meth->dso_merger(dso, filespec1, filespec2); } return result; } char *DSO_convert_filename(DSO *dso, const char *filename) { char *result = NULL; if (dso == NULL) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (filename == NULL) filename = dso->filename; if (filename == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NO_FILENAME); return NULL; } if ((dso->flags & DSO_FLAG_NO_NAME_TRANSLATION) == 0) { if (dso->name_converter != NULL) result = dso->name_converter(dso, filename); else if (dso->meth->dso_name_converter != NULL) result = dso->meth->dso_name_converter(dso, filename); } if (result == NULL) { result = OPENSSL_strdup(filename); if (result == NULL) return NULL; } return result; } int DSO_pathbyaddr(void *addr, char *path, int sz) { DSO_METHOD *meth = DSO_METHOD_openssl(); if (meth->pathbyaddr == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED); return -1; } return (*meth->pathbyaddr) (addr, path, sz); } DSO *DSO_dsobyaddr(void *addr, int flags) { DSO *ret = NULL; char *filename = NULL; int len = DSO_pathbyaddr(addr, NULL, 0); if (len < 0) return NULL; filename = OPENSSL_malloc(len); if (filename != NULL && DSO_pathbyaddr(addr, filename, len) == len) ret = DSO_load(NULL, filename, NULL, flags); OPENSSL_free(filename); return ret; } void *DSO_global_lookup(const char *name) { DSO_METHOD *meth = DSO_METHOD_openssl(); if (meth->globallookup == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED); return NULL; } return (*meth->globallookup) (name); }
8,580
25.00303
77
c
openssl
openssl-master/crypto/dso/dso_local.h
/* * Copyright 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 <stdio.h> #include "internal/cryptlib.h" #include "internal/dso.h" #include "crypto/dso_conf.h" #include "internal/refcount.h" /**********************************************************************/ /* The low-level handle type used to refer to a loaded shared library */ struct dso_st { DSO_METHOD *meth; /* * Standard dlopen uses a (void *). Win32 uses a HANDLE. VMS doesn't use * anything but will need to cache the filename for use in the dso_bind * handler. All in all, let each method control its own destiny. * "Handles" and such go in a STACK. */ STACK_OF(void) *meth_data; CRYPTO_REF_COUNT references; int flags; /* * For use by applications etc ... use this for your bits'n'pieces, don't * touch meth_data! */ CRYPTO_EX_DATA ex_data; /* * If this callback function pointer is set to non-NULL, then it will be * used in DSO_load() in place of meth->dso_name_converter. NB: This * should normally set using DSO_set_name_converter(). */ DSO_NAME_CONVERTER_FUNC name_converter; /* * If this callback function pointer is set to non-NULL, then it will be * used in DSO_load() in place of meth->dso_merger. NB: This should * normally set using DSO_set_merger(). */ DSO_MERGER_FUNC merger; /* * This is populated with (a copy of) the platform-independent filename * used for this DSO. */ char *filename; /* * This is populated with (a copy of) the translated filename by which * the DSO was actually loaded. It is NULL iff the DSO is not currently * loaded. NB: This is here because the filename translation process may * involve a callback being invoked more than once not only to convert to * a platform-specific form, but also to try different filenames in the * process of trying to perform a load. As such, this variable can be * used to indicate (a) whether this DSO structure corresponds to a * loaded library or not, and (b) the filename with which it was actually * loaded. */ char *loaded_filename; }; struct dso_meth_st { const char *name; /* * Loads a shared library, NB: new DSO_METHODs must ensure that a * successful load populates the loaded_filename field, and likewise a * successful unload OPENSSL_frees and NULLs it out. */ int (*dso_load) (DSO *dso); /* Unloads a shared library */ int (*dso_unload) (DSO *dso); /* * Binds a function - assumes a return type of DSO_FUNC_TYPE. This should * be cast to the real function prototype by the caller. Platforms that * don't have compatible representations for different prototypes (this * is possible within ANSI C) are highly unlikely to have shared * libraries at all, let alone a DSO_METHOD implemented for them. */ DSO_FUNC_TYPE (*dso_bind_func) (DSO *dso, const char *symname); /* * The generic (yuck) "ctrl()" function. NB: Negative return values * (rather than zero) indicate errors. */ long (*dso_ctrl) (DSO *dso, int cmd, long larg, void *parg); /* * The default DSO_METHOD-specific function for converting filenames to a * canonical native form. */ DSO_NAME_CONVERTER_FUNC dso_name_converter; /* * The default DSO_METHOD-specific function for converting filenames to a * canonical native form. */ DSO_MERGER_FUNC dso_merger; /* [De]Initialisation handlers. */ int (*init) (DSO *dso); int (*finish) (DSO *dso); /* Return pathname of the module containing location */ int (*pathbyaddr) (void *addr, char *path, int sz); /* Perform global symbol lookup, i.e. among *all* modules */ void *(*globallookup) (const char *symname); };
4,128
37.588785
77
h
openssl
openssl-master/crypto/dso/dso_openssl.c
/* * Copyright 2000-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 "dso_local.h" #ifdef DSO_NONE static DSO_METHOD dso_meth_null = { "NULL shared library method" }; DSO_METHOD *DSO_METHOD_openssl(void) { return &dso_meth_null; } #endif
526
21.913043
74
c
openssl
openssl-master/crypto/dso/dso_vms.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 */ #include "dso_local.h" #ifdef OPENSSL_SYS_VMS # pragma message disable DOLLARID # include <errno.h> # include <rms.h> # include <lib$routines.h> # include <libfisdef.h> # include <stsdef.h> # include <descrip.h> # include <starlet.h> # include "../vms_rms.h" /* Some compiler options may mask the declaration of "_malloc32". */ # define DSO_MALLOC OPENSSL_malloc # if __INITIAL_POINTER_SIZE && defined _ANSI_C_SOURCE # if __INITIAL_POINTER_SIZE == 64 # pragma pointer_size save # pragma pointer_size 32 void *_malloc32(__size_t); static void *dso_malloc(__size_t num, const char *file, int line) { void *ret = _malloc32(num); if (ret == NULL && (file != NULL || line != 0)) { ERR_new(); ERR_set_debug(file, line, NULL); ERR_set_error(ERR_LIB_DSO, ERR_R_MALLOC_FAILURE, NULL); } return ret; } # undef DSO_MALLOC # define DSO_MALLOC(num) dso_malloc((num), OPENSSL_FILE, OPENSSL_LINE) # pragma pointer_size restore # endif /* __INITIAL_POINTER_SIZE == 64 [else] */ # endif /* __INITIAL_POINTER_SIZE && defined * _ANSI_C_SOURCE */ # pragma message disable DOLLARID static int vms_load(DSO *dso); static int vms_unload(DSO *dso); static DSO_FUNC_TYPE vms_bind_func(DSO *dso, const char *symname); static char *vms_name_converter(DSO *dso, const char *filename); static char *vms_merger(DSO *dso, const char *filespec1, const char *filespec2); static DSO_METHOD dso_meth_vms = { "OpenSSL 'VMS' shared library method", vms_load, NULL, /* unload */ vms_bind_func, NULL, /* ctrl */ vms_name_converter, vms_merger, NULL, /* init */ NULL, /* finish */ NULL, /* pathbyaddr */ NULL /* globallookup */ }; /* * On VMS, the only "handle" is the file name. LIB$FIND_IMAGE_SYMBOL depends * on the reference to the file name being the same for all calls regarding * one shared image, so we'll just store it in an instance of the following * structure and put a pointer to that instance in the meth_data stack. */ typedef struct dso_internal_st { /* * This should contain the name only, no directory, no extension, nothing * but a name. */ struct dsc$descriptor_s filename_dsc; char filename[NAMX_MAXRSS + 1]; /* * This contains whatever is not in filename, if needed. Normally not * defined. */ struct dsc$descriptor_s imagename_dsc; char imagename[NAMX_MAXRSS + 1]; } DSO_VMS_INTERNAL; DSO_METHOD *DSO_METHOD_openssl(void) { return &dso_meth_vms; } static int vms_load(DSO *dso) { void *ptr = NULL; /* See applicable comments in dso_dl.c */ char *filename = DSO_convert_filename(dso, NULL); /* Ensure 32-bit pointer for "p", and appropriate malloc() function. */ # if __INITIAL_POINTER_SIZE && defined _ANSI_C_SOURCE # if __INITIAL_POINTER_SIZE == 64 # pragma pointer_size save # pragma pointer_size 32 # endif /* __INITIAL_POINTER_SIZE == 64 */ # endif /* __INITIAL_POINTER_SIZE && defined * _ANSI_C_SOURCE */ DSO_VMS_INTERNAL *p = NULL; # if __INITIAL_POINTER_SIZE && defined _ANSI_C_SOURCE # if __INITIAL_POINTER_SIZE == 64 # pragma pointer_size restore # endif /* __INITIAL_POINTER_SIZE == 64 */ # endif /* __INITIAL_POINTER_SIZE && defined * _ANSI_C_SOURCE */ const char *sp1, *sp2; /* Search result */ const char *ext = NULL; /* possible extension to add */ if (filename == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NO_FILENAME); goto err; } /*- * A file specification may look like this: * * node::dev:[dir-spec]name.type;ver * * or (for compatibility with TOPS-20): * * node::dev:<dir-spec>name.type;ver * * and the dir-spec uses '.' as separator. Also, a dir-spec * may consist of several parts, with mixed use of [] and <>: * * [dir1.]<dir2> * * We need to split the file specification into the name and * the rest (both before and after the name itself). */ /* * Start with trying to find the end of a dir-spec, and save the position * of the byte after in sp1 */ sp1 = strrchr(filename, ']'); sp2 = strrchr(filename, '>'); if (sp1 == NULL) sp1 = sp2; if (sp2 != NULL && sp2 > sp1) sp1 = sp2; if (sp1 == NULL) sp1 = strrchr(filename, ':'); if (sp1 == NULL) sp1 = filename; else sp1++; /* The byte after the found character */ /* Now, let's see if there's a type, and save the position in sp2 */ sp2 = strchr(sp1, '.'); /* * If there is a period and the next character is a semi-colon, * we need to add an extension */ if (sp2 != NULL && sp2[1] == ';') ext = ".EXE"; /* * If we found it, that's where we'll cut. Otherwise, look for a version * number and save the position in sp2 */ if (sp2 == NULL) { sp2 = strchr(sp1, ';'); ext = ".EXE"; } /* * If there was still nothing to find, set sp2 to point at the end of the * string */ if (sp2 == NULL) sp2 = sp1 + strlen(sp1); /* Check that we won't get buffer overflows */ if (sp2 - sp1 > FILENAME_MAX || (sp1 - filename) + strlen(sp2) > FILENAME_MAX) { ERR_raise(ERR_LIB_DSO, DSO_R_FILENAME_TOO_BIG); goto err; } p = DSO_MALLOC(sizeof(*p)); if (p == NULL) goto err; strncpy(p->filename, sp1, sp2 - sp1); p->filename[sp2 - sp1] = '\0'; strncpy(p->imagename, filename, sp1 - filename); p->imagename[sp1 - filename] = '\0'; if (ext) { strcat(p->imagename, ext); if (*sp2 == '.') sp2++; } strcat(p->imagename, sp2); p->filename_dsc.dsc$w_length = strlen(p->filename); p->filename_dsc.dsc$b_dtype = DSC$K_DTYPE_T; p->filename_dsc.dsc$b_class = DSC$K_CLASS_S; p->filename_dsc.dsc$a_pointer = p->filename; p->imagename_dsc.dsc$w_length = strlen(p->imagename); p->imagename_dsc.dsc$b_dtype = DSC$K_DTYPE_T; p->imagename_dsc.dsc$b_class = DSC$K_CLASS_S; p->imagename_dsc.dsc$a_pointer = p->imagename; if (!sk_void_push(dso->meth_data, (char *)p)) { ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR); goto err; } /* Success (for now, we lie. We actually do not know...) */ dso->loaded_filename = filename; return 1; err: /* Cleanup! */ OPENSSL_free(p); OPENSSL_free(filename); return 0; } /* * Note that this doesn't actually unload the shared image, as there is no * such thing in VMS. Next time it get loaded again, a new copy will * actually be loaded. */ static int vms_unload(DSO *dso) { DSO_VMS_INTERNAL *p; if (dso == NULL) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (sk_void_num(dso->meth_data) < 1) return 1; p = (DSO_VMS_INTERNAL *)sk_void_pop(dso->meth_data); if (p == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE); return 0; } /* Cleanup */ OPENSSL_free(p); return 1; } /* * We must do this in a separate function because of the way the exception * handler works (it makes this function return */ static int do_find_symbol(DSO_VMS_INTERNAL *ptr, struct dsc$descriptor_s *symname_dsc, void **sym, unsigned long flags) { /* * Make sure that signals are caught and returned instead of aborting the * program. The exception handler gets unestablished automatically on * return from this function. */ lib$establish(lib$sig_to_ret); if (ptr->imagename_dsc.dsc$w_length) return lib$find_image_symbol(&ptr->filename_dsc, symname_dsc, sym, &ptr->imagename_dsc, flags); else return lib$find_image_symbol(&ptr->filename_dsc, symname_dsc, sym, 0, flags); } # ifndef LIB$M_FIS_MIXEDCASE # define LIB$M_FIS_MIXEDCASE (1 << 4); # endif void vms_bind_sym(DSO *dso, const char *symname, void **sym) { DSO_VMS_INTERNAL *ptr; int status = 0; struct dsc$descriptor_s symname_dsc; /* Arrange 32-bit pointer to (copied) string storage, if needed. */ # if __INITIAL_POINTER_SIZE == 64 # define SYMNAME symname_32p # pragma pointer_size save # pragma pointer_size 32 char *symname_32p; # pragma pointer_size restore char symname_32[NAMX_MAXRSS + 1]; # else /* __INITIAL_POINTER_SIZE == 64 */ # define SYMNAME ((char *) symname) # endif /* __INITIAL_POINTER_SIZE == 64 [else] */ *sym = NULL; if ((dso == NULL) || (symname == NULL)) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return; } # if __INITIAL_POINTER_SIZE == 64 /* Copy the symbol name to storage with a 32-bit pointer. */ symname_32p = symname_32; strcpy(symname_32p, symname); # endif /* __INITIAL_POINTER_SIZE == 64 [else] */ symname_dsc.dsc$w_length = strlen(SYMNAME); symname_dsc.dsc$b_dtype = DSC$K_DTYPE_T; symname_dsc.dsc$b_class = DSC$K_CLASS_S; symname_dsc.dsc$a_pointer = SYMNAME; if (sk_void_num(dso->meth_data) < 1) { ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR); return; } ptr = (DSO_VMS_INTERNAL *)sk_void_value(dso->meth_data, sk_void_num(dso->meth_data) - 1); if (ptr == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE); return; } status = do_find_symbol(ptr, &symname_dsc, sym, LIB$M_FIS_MIXEDCASE); if (!$VMS_STATUS_SUCCESS(status)) status = do_find_symbol(ptr, &symname_dsc, sym, 0); if (!$VMS_STATUS_SUCCESS(status)) { unsigned short length; char errstring[257]; struct dsc$descriptor_s errstring_dsc; errstring_dsc.dsc$w_length = sizeof(errstring); errstring_dsc.dsc$b_dtype = DSC$K_DTYPE_T; errstring_dsc.dsc$b_class = DSC$K_CLASS_S; errstring_dsc.dsc$a_pointer = errstring; *sym = NULL; status = sys$getmsg(status, &length, &errstring_dsc, 1, 0); if (!$VMS_STATUS_SUCCESS(status)) lib$signal(status); /* This is really bad. Abort! */ else { errstring[length] = '\0'; if (ptr->imagename_dsc.dsc$w_length) ERR_raise_data(ERR_LIB_DSO, DSO_R_SYM_FAILURE, "Symbol %s in %s (%s): %s", symname, ptr->filename, ptr->imagename, errstring); else ERR_raise_data(ERR_LIB_DSO, DSO_R_SYM_FAILURE, "Symbol %s in %s: %s", symname, ptr->filename, errstring); } return; } return; } static DSO_FUNC_TYPE vms_bind_func(DSO *dso, const char *symname) { DSO_FUNC_TYPE sym = 0; vms_bind_sym(dso, symname, (void **)&sym); return sym; } static char *vms_merger(DSO *dso, const char *filespec1, const char *filespec2) { int status; int filespec1len, filespec2len; struct FAB fab; struct NAMX_STRUCT nam; char esa[NAMX_MAXRSS + 1]; char *merged; /* Arrange 32-bit pointer to (copied) string storage, if needed. */ # if __INITIAL_POINTER_SIZE == 64 # define FILESPEC1 filespec1_32p; # define FILESPEC2 filespec2_32p; # pragma pointer_size save # pragma pointer_size 32 char *filespec1_32p; char *filespec2_32p; # pragma pointer_size restore char filespec1_32[NAMX_MAXRSS + 1]; char filespec2_32[NAMX_MAXRSS + 1]; # else /* __INITIAL_POINTER_SIZE == 64 */ # define FILESPEC1 ((char *) filespec1) # define FILESPEC2 ((char *) filespec2) # endif /* __INITIAL_POINTER_SIZE == 64 [else] */ if (!filespec1) filespec1 = ""; if (!filespec2) filespec2 = ""; filespec1len = strlen(filespec1); filespec2len = strlen(filespec2); # if __INITIAL_POINTER_SIZE == 64 /* Copy the file names to storage with a 32-bit pointer. */ filespec1_32p = filespec1_32; filespec2_32p = filespec2_32; strcpy(filespec1_32p, filespec1); strcpy(filespec2_32p, filespec2); # endif /* __INITIAL_POINTER_SIZE == 64 [else] */ fab = cc$rms_fab; nam = CC_RMS_NAMX; FAB_OR_NAML(fab, nam).FAB_OR_NAML_FNA = FILESPEC1; FAB_OR_NAML(fab, nam).FAB_OR_NAML_FNS = filespec1len; FAB_OR_NAML(fab, nam).FAB_OR_NAML_DNA = FILESPEC2; FAB_OR_NAML(fab, nam).FAB_OR_NAML_DNS = filespec2len; NAMX_DNA_FNA_SET(fab) nam.NAMX_ESA = esa; nam.NAMX_ESS = NAMX_MAXRSS; nam.NAMX_NOP = NAM$M_SYNCHK | NAM$M_PWD; SET_NAMX_NO_SHORT_UPCASE(nam); fab.FAB_NAMX = &nam; status = sys$parse(&fab, 0, 0); if (!$VMS_STATUS_SUCCESS(status)) { unsigned short length; char errstring[257]; struct dsc$descriptor_s errstring_dsc; errstring_dsc.dsc$w_length = sizeof(errstring); errstring_dsc.dsc$b_dtype = DSC$K_DTYPE_T; errstring_dsc.dsc$b_class = DSC$K_CLASS_S; errstring_dsc.dsc$a_pointer = errstring; status = sys$getmsg(status, &length, &errstring_dsc, 1, 0); if (!$VMS_STATUS_SUCCESS(status)) lib$signal(status); /* This is really bad. Abort! */ else { errstring[length] = '\0'; ERR_raise_data(ERR_LIB_DSO, DSO_R_FAILURE, "filespec \"%s\", default \"%s\": %s", filespec1, filespec2, errstring); } return NULL; } merged = OPENSSL_malloc(nam.NAMX_ESL + 1); if (merged == NULL) return NULL; strncpy(merged, nam.NAMX_ESA, nam.NAMX_ESL); merged[nam.NAMX_ESL] = '\0'; return merged; } static char *vms_name_converter(DSO *dso, const char *filename) { char *translated; int len, transform; const char *p; len = strlen(filename); p = strchr(filename, ':'); if (p != NULL) { transform = 0; } else { p = filename; transform = (strrchr(p, '>') == NULL && strrchr(p, ']') == NULL); } if (transform) { int rsize = len + sizeof(DSO_EXTENSION); if ((translated = OPENSSL_malloc(rsize)) != NULL) { p = strrchr(filename, ';'); if (p != NULL) len = p - filename; strncpy(translated, filename, len); translated[len] = '\0'; strcat(translated, DSO_EXTENSION); if (p != NULL) strcat(translated, p); } } else { translated = OPENSSL_strdup(filename); } return translated; } #endif /* OPENSSL_SYS_VMS */
15,580
30.037849
77
c
openssl
openssl-master/crypto/dso/dso_win32.c
/* * Copyright 2000-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 "internal/e_os.h" #include "dso_local.h" #if defined(DSO_WIN32) # ifdef _WIN32_WCE # if _WIN32_WCE < 300 static FARPROC GetProcAddressA(HMODULE hModule, LPCSTR lpProcName) { WCHAR lpProcNameW[64]; int i; for (i = 0; lpProcName[i] && i < 64; i++) lpProcNameW[i] = (WCHAR)lpProcName[i]; if (i == 64) return NULL; lpProcNameW[i] = 0; return GetProcAddressW(hModule, lpProcNameW); } # endif # undef GetProcAddress # define GetProcAddress GetProcAddressA static HINSTANCE LoadLibraryA(LPCSTR lpLibFileName) { WCHAR *fnamw; size_t len_0 = strlen(lpLibFileName) + 1, i; # ifdef _MSC_VER fnamw = (WCHAR *)_alloca(len_0 * sizeof(WCHAR)); # else fnamw = (WCHAR *)alloca(len_0 * sizeof(WCHAR)); # endif if (fnamw == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return NULL; } # if defined(_WIN32_WCE) && _WIN32_WCE>=101 if (!MultiByteToWideChar(CP_ACP, 0, lpLibFileName, len_0, fnamw, len_0)) # endif for (i = 0; i < len_0; i++) fnamw[i] = (WCHAR)lpLibFileName[i]; return LoadLibraryW(fnamw); } # endif /* Part of the hack in "win32_load" ... */ # define DSO_MAX_TRANSLATED_SIZE 256 static int win32_load(DSO *dso); static int win32_unload(DSO *dso); static DSO_FUNC_TYPE win32_bind_func(DSO *dso, const char *symname); static char *win32_name_converter(DSO *dso, const char *filename); static char *win32_merger(DSO *dso, const char *filespec1, const char *filespec2); static int win32_pathbyaddr(void *addr, char *path, int sz); static void *win32_globallookup(const char *name); static const char *openssl_strnchr(const char *string, int c, size_t len); static DSO_METHOD dso_meth_win32 = { "OpenSSL 'win32' shared library method", win32_load, win32_unload, win32_bind_func, NULL, /* ctrl */ win32_name_converter, win32_merger, NULL, /* init */ NULL, /* finish */ win32_pathbyaddr, /* pathbyaddr */ win32_globallookup }; DSO_METHOD *DSO_METHOD_openssl(void) { return &dso_meth_win32; } /* * For this DSO_METHOD, our meth_data STACK will contain; (i) a pointer to * the handle (HINSTANCE) returned from LoadLibrary(), and copied. */ static int win32_load(DSO *dso) { HINSTANCE h = NULL, *p = NULL; /* See applicable comments from dso_dl.c */ char *filename = DSO_convert_filename(dso, NULL); if (filename == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NO_FILENAME); goto err; } h = LoadLibraryA(filename); if (h == NULL) { ERR_raise_data(ERR_LIB_DSO, DSO_R_LOAD_FAILED, "filename(%s)", filename); goto err; } p = OPENSSL_malloc(sizeof(*p)); if (p == NULL) goto err; *p = h; if (!sk_void_push(dso->meth_data, p)) { ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR); goto err; } /* Success */ dso->loaded_filename = filename; return 1; err: /* Cleanup ! */ OPENSSL_free(filename); OPENSSL_free(p); if (h != NULL) FreeLibrary(h); return 0; } static int win32_unload(DSO *dso) { HINSTANCE *p; if (dso == NULL) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (sk_void_num(dso->meth_data) < 1) return 1; p = sk_void_pop(dso->meth_data); if (p == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE); return 0; } if (!FreeLibrary(*p)) { ERR_raise(ERR_LIB_DSO, DSO_R_UNLOAD_FAILED); /* * We should push the value back onto the stack in case of a retry. */ sk_void_push(dso->meth_data, p); return 0; } /* Cleanup */ OPENSSL_free(p); return 1; } static DSO_FUNC_TYPE win32_bind_func(DSO *dso, const char *symname) { HINSTANCE *ptr; union { void *p; FARPROC f; } sym; if ((dso == NULL) || (symname == NULL)) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (sk_void_num(dso->meth_data) < 1) { ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR); return NULL; } ptr = sk_void_value(dso->meth_data, sk_void_num(dso->meth_data) - 1); if (ptr == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE); return NULL; } sym.f = GetProcAddress(*ptr, symname); if (sym.p == NULL) { ERR_raise_data(ERR_LIB_DSO, DSO_R_SYM_FAILURE, "symname(%s)", symname); return NULL; } return (DSO_FUNC_TYPE)sym.f; } struct file_st { const char *node; int nodelen; const char *device; int devicelen; const char *predir; int predirlen; const char *dir; int dirlen; const char *file; int filelen; }; static struct file_st *win32_splitter(DSO *dso, const char *filename, int assume_last_is_dir) { struct file_st *result = NULL; enum { IN_NODE, IN_DEVICE, IN_FILE } position; const char *start = filename; char last; if (!filename) { ERR_raise(ERR_LIB_DSO, DSO_R_NO_FILENAME); return NULL; } result = OPENSSL_zalloc(sizeof(*result)); if (result == NULL) return NULL; position = IN_DEVICE; if ((filename[0] == '\\' && filename[1] == '\\') || (filename[0] == '/' && filename[1] == '/')) { position = IN_NODE; filename += 2; start = filename; result->node = start; } do { last = filename[0]; switch (last) { case ':': if (position != IN_DEVICE) { ERR_raise(ERR_LIB_DSO, DSO_R_INCORRECT_FILE_SYNTAX); OPENSSL_free(result); return NULL; } result->device = start; result->devicelen = (int)(filename - start); position = IN_FILE; start = ++filename; result->dir = start; break; case '\\': case '/': if (position == IN_NODE) { result->nodelen = (int)(filename - start); position = IN_FILE; start = ++filename; result->dir = start; } else if (position == IN_DEVICE) { position = IN_FILE; filename++; result->dir = start; result->dirlen = (int)(filename - start); start = filename; } else { filename++; result->dirlen += (int)(filename - start); start = filename; } break; case '\0': if (position == IN_NODE) { result->nodelen = (int)(filename - start); } else { if (filename - start > 0) { if (assume_last_is_dir) { if (position == IN_DEVICE) { result->dir = start; result->dirlen = 0; } result->dirlen += (int)(filename - start); } else { result->file = start; result->filelen = (int)(filename - start); } } } break; default: filename++; break; } } while (last); if (!result->nodelen) result->node = NULL; if (!result->devicelen) result->device = NULL; if (!result->dirlen) result->dir = NULL; if (!result->filelen) result->file = NULL; return result; } static char *win32_joiner(DSO *dso, const struct file_st *file_split) { int len = 0, offset = 0; char *result = NULL; const char *start; if (!file_split) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (file_split->node) { len += 2 + file_split->nodelen; /* 2 for starting \\ */ if (file_split->predir || file_split->dir || file_split->file) len++; /* 1 for ending \ */ } else if (file_split->device) { len += file_split->devicelen + 1; /* 1 for ending : */ } len += file_split->predirlen; if (file_split->predir && (file_split->dir || file_split->file)) { len++; /* 1 for ending \ */ } len += file_split->dirlen; if (file_split->dir && file_split->file) { len++; /* 1 for ending \ */ } len += file_split->filelen; if (!len) { ERR_raise(ERR_LIB_DSO, DSO_R_EMPTY_FILE_STRUCTURE); return NULL; } result = OPENSSL_malloc(len + 1); if (result == NULL) return NULL; if (file_split->node) { strcpy(&result[offset], "\\\\"); offset += 2; strncpy(&result[offset], file_split->node, file_split->nodelen); offset += file_split->nodelen; if (file_split->predir || file_split->dir || file_split->file) { result[offset] = '\\'; offset++; } } else if (file_split->device) { strncpy(&result[offset], file_split->device, file_split->devicelen); offset += file_split->devicelen; result[offset] = ':'; offset++; } start = file_split->predir; while (file_split->predirlen > (start - file_split->predir)) { const char *end = openssl_strnchr(start, '/', file_split->predirlen - (start - file_split->predir)); if (!end) end = start + file_split->predirlen - (start - file_split->predir); strncpy(&result[offset], start, end - start); offset += (int)(end - start); result[offset] = '\\'; offset++; start = end + 1; } start = file_split->dir; while (file_split->dirlen > (start - file_split->dir)) { const char *end = openssl_strnchr(start, '/', file_split->dirlen - (start - file_split->dir)); if (!end) end = start + file_split->dirlen - (start - file_split->dir); strncpy(&result[offset], start, end - start); offset += (int)(end - start); result[offset] = '\\'; offset++; start = end + 1; } strncpy(&result[offset], file_split->file, file_split->filelen); offset += file_split->filelen; result[offset] = '\0'; return result; } static char *win32_merger(DSO *dso, const char *filespec1, const char *filespec2) { char *merged = NULL; struct file_st *filespec1_split = NULL; struct file_st *filespec2_split = NULL; if (!filespec1 && !filespec2) { ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!filespec2) { merged = OPENSSL_strdup(filespec1); if (merged == NULL) return NULL; } else if (!filespec1) { merged = OPENSSL_strdup(filespec2); if (merged == NULL) return NULL; } else { filespec1_split = win32_splitter(dso, filespec1, 0); if (!filespec1_split) { ERR_raise(ERR_LIB_DSO, ERR_R_DSO_LIB); return NULL; } filespec2_split = win32_splitter(dso, filespec2, 1); if (!filespec2_split) { ERR_raise(ERR_LIB_DSO, ERR_R_DSO_LIB); OPENSSL_free(filespec1_split); return NULL; } /* Fill in into filespec1_split */ if (!filespec1_split->node && !filespec1_split->device) { filespec1_split->node = filespec2_split->node; filespec1_split->nodelen = filespec2_split->nodelen; filespec1_split->device = filespec2_split->device; filespec1_split->devicelen = filespec2_split->devicelen; } if (!filespec1_split->dir) { filespec1_split->dir = filespec2_split->dir; filespec1_split->dirlen = filespec2_split->dirlen; } else if (filespec1_split->dir[0] != '\\' && filespec1_split->dir[0] != '/') { filespec1_split->predir = filespec2_split->dir; filespec1_split->predirlen = filespec2_split->dirlen; } if (!filespec1_split->file) { filespec1_split->file = filespec2_split->file; filespec1_split->filelen = filespec2_split->filelen; } merged = win32_joiner(dso, filespec1_split); } OPENSSL_free(filespec1_split); OPENSSL_free(filespec2_split); return merged; } static char *win32_name_converter(DSO *dso, const char *filename) { char *translated; int len, transform; len = strlen(filename); transform = ((strstr(filename, "/") == NULL) && (strstr(filename, "\\") == NULL) && (strstr(filename, ":") == NULL)); if (transform) /* We will convert this to "%s.dll" */ translated = OPENSSL_malloc(len + 5); else /* We will simply duplicate filename */ translated = OPENSSL_malloc(len + 1); if (translated == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_NAME_TRANSLATION_FAILED); return NULL; } if (transform) sprintf(translated, "%s.dll", filename); else sprintf(translated, "%s", filename); return translated; } static const char *openssl_strnchr(const char *string, int c, size_t len) { size_t i; const char *p; for (i = 0, p = string; i < len && *p; i++, p++) { if (*p == c) return p; } return NULL; } # include <tlhelp32.h> # ifdef _WIN32_WCE # define DLLNAME "TOOLHELP.DLL" # else # ifdef MODULEENTRY32 # undef MODULEENTRY32 /* unmask the ASCII version! */ # endif # define DLLNAME "KERNEL32.DLL" # endif typedef HANDLE(WINAPI *CREATETOOLHELP32SNAPSHOT) (DWORD, DWORD); typedef BOOL(WINAPI *CLOSETOOLHELP32SNAPSHOT) (HANDLE); typedef BOOL(WINAPI *MODULE32) (HANDLE, MODULEENTRY32 *); static int win32_pathbyaddr(void *addr, char *path, int sz) { HMODULE dll; HANDLE hModuleSnap = INVALID_HANDLE_VALUE; MODULEENTRY32 me32; CREATETOOLHELP32SNAPSHOT create_snap; CLOSETOOLHELP32SNAPSHOT close_snap; MODULE32 module_first, module_next; if (addr == NULL) { union { int (*f) (void *, char *, int); void *p; } t = { win32_pathbyaddr }; addr = t.p; } dll = LoadLibrary(TEXT(DLLNAME)); if (dll == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED); return -1; } create_snap = (CREATETOOLHELP32SNAPSHOT) GetProcAddress(dll, "CreateToolhelp32Snapshot"); if (create_snap == NULL) { FreeLibrary(dll); ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED); return -1; } /* We take the rest for granted... */ # ifdef _WIN32_WCE close_snap = (CLOSETOOLHELP32SNAPSHOT) GetProcAddress(dll, "CloseToolhelp32Snapshot"); # else close_snap = (CLOSETOOLHELP32SNAPSHOT) CloseHandle; # endif module_first = (MODULE32) GetProcAddress(dll, "Module32First"); module_next = (MODULE32) GetProcAddress(dll, "Module32Next"); /* * Take a snapshot of current process which includes * list of all involved modules. */ hModuleSnap = (*create_snap) (TH32CS_SNAPMODULE, 0); if (hModuleSnap == INVALID_HANDLE_VALUE) { FreeLibrary(dll); ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED); return -1; } me32.dwSize = sizeof(me32); if (!(*module_first) (hModuleSnap, &me32)) { (*close_snap) (hModuleSnap); FreeLibrary(dll); ERR_raise(ERR_LIB_DSO, DSO_R_FAILURE); return -1; } /* Enumerate the modules to find one which includes me. */ do { if ((size_t) addr >= (size_t) me32.modBaseAddr && (size_t) addr < (size_t) (me32.modBaseAddr + me32.modBaseSize)) { (*close_snap) (hModuleSnap); FreeLibrary(dll); # ifdef _WIN32_WCE # if _WIN32_WCE >= 101 return WideCharToMultiByte(CP_ACP, 0, me32.szExePath, -1, path, sz, NULL, NULL); # else { int i, len = (int)wcslen(me32.szExePath); if (sz <= 0) return len + 1; if (len >= sz) len = sz - 1; for (i = 0; i < len; i++) path[i] = (char)me32.szExePath[i]; path[len++] = '\0'; return len; } # endif # else { int len = (int)strlen(me32.szExePath); if (sz <= 0) return len + 1; if (len >= sz) len = sz - 1; memcpy(path, me32.szExePath, len); path[len++] = '\0'; return len; } # endif } } while ((*module_next) (hModuleSnap, &me32)); (*close_snap) (hModuleSnap); FreeLibrary(dll); return 0; } static void *win32_globallookup(const char *name) { HMODULE dll; HANDLE hModuleSnap = INVALID_HANDLE_VALUE; MODULEENTRY32 me32; CREATETOOLHELP32SNAPSHOT create_snap; CLOSETOOLHELP32SNAPSHOT close_snap; MODULE32 module_first, module_next; union { void *p; FARPROC f; } ret = { NULL }; dll = LoadLibrary(TEXT(DLLNAME)); if (dll == NULL) { ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED); return NULL; } create_snap = (CREATETOOLHELP32SNAPSHOT) GetProcAddress(dll, "CreateToolhelp32Snapshot"); if (create_snap == NULL) { FreeLibrary(dll); ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED); return NULL; } /* We take the rest for granted... */ # ifdef _WIN32_WCE close_snap = (CLOSETOOLHELP32SNAPSHOT) GetProcAddress(dll, "CloseToolhelp32Snapshot"); # else close_snap = (CLOSETOOLHELP32SNAPSHOT) CloseHandle; # endif module_first = (MODULE32) GetProcAddress(dll, "Module32First"); module_next = (MODULE32) GetProcAddress(dll, "Module32Next"); hModuleSnap = (*create_snap) (TH32CS_SNAPMODULE, 0); if (hModuleSnap == INVALID_HANDLE_VALUE) { FreeLibrary(dll); ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED); return NULL; } me32.dwSize = sizeof(me32); if (!(*module_first) (hModuleSnap, &me32)) { (*close_snap) (hModuleSnap); FreeLibrary(dll); return NULL; } do { if ((ret.f = GetProcAddress(me32.hModule, name))) { (*close_snap) (hModuleSnap); FreeLibrary(dll); return ret.p; } } while ((*module_next) (hModuleSnap, &me32)); (*close_snap) (hModuleSnap); FreeLibrary(dll); return NULL; } #endif /* DSO_WIN32 */
19,431
28.353474
88
c
openssl
openssl-master/crypto/ec/ec2_oct.c
/* * Copyright 2011-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/err.h> #include "ec_local.h" #ifndef OPENSSL_NO_EC2M /*- * Calculates and sets the affine coordinates of an EC_POINT from the given * compressed coordinates. Uses algorithm 2.3.4 of SEC 1. * Note that the simple implementation only uses affine coordinates. * * The method is from the following publication: * * Harper, Menezes, Vanstone: * "Public-Key Cryptosystems with Very Small Key Lengths", * EUROCRYPT '92, Springer-Verlag LNCS 658, * published February 1993 * * US Patents 6,141,420 and 6,618,483 (Vanstone, Mullin, Agnew) describe * the same method, but claim no priority date earlier than July 29, 1994 * (and additionally fail to cite the EUROCRYPT '92 publication as prior art). */ int ossl_ec_GF2m_simple_set_compressed_coordinates(const EC_GROUP *group, EC_POINT *point, const BIGNUM *x_, int y_bit, BN_CTX *ctx) { BIGNUM *tmp, *x, *y, *z; int ret = 0, z0; #ifndef FIPS_MODULE BN_CTX *new_ctx = NULL; if (ctx == NULL) { ctx = new_ctx = BN_CTX_new(); if (ctx == NULL) return 0; } #endif y_bit = (y_bit != 0) ? 1 : 0; BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); z = BN_CTX_get(ctx); if (z == NULL) goto err; if (!BN_GF2m_mod_arr(x, x_, group->poly)) goto err; if (BN_is_zero(x)) { if (!BN_GF2m_mod_sqrt_arr(y, group->b, group->poly, ctx)) goto err; } else { if (!group->meth->field_sqr(group, tmp, x, ctx)) goto err; if (!group->meth->field_div(group, tmp, group->b, tmp, ctx)) goto err; if (!BN_GF2m_add(tmp, group->a, tmp)) goto err; if (!BN_GF2m_add(tmp, x, tmp)) goto err; ERR_set_mark(); if (!BN_GF2m_mod_solve_quad_arr(z, tmp, group->poly, ctx)) { #ifndef FIPS_MODULE unsigned long err = ERR_peek_last_error(); if (ERR_GET_LIB(err) == ERR_LIB_BN && ERR_GET_REASON(err) == BN_R_NO_SOLUTION) { ERR_pop_to_mark(); ERR_raise(ERR_LIB_EC, EC_R_INVALID_COMPRESSED_POINT); } else #endif { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); } goto err; } ERR_clear_last_mark(); z0 = (BN_is_odd(z)) ? 1 : 0; if (!group->meth->field_mul(group, y, x, z, ctx)) goto err; if (z0 != y_bit) { if (!BN_GF2m_add(y, y, x)) goto err; } } if (!EC_POINT_set_affine_coordinates(group, point, x, y, ctx)) goto err; ret = 1; err: BN_CTX_end(ctx); #ifndef FIPS_MODULE BN_CTX_free(new_ctx); #endif return ret; } /* * Converts an EC_POINT to an octet string. If buf is NULL, the encoded * length will be returned. If the length len of buf is smaller than required * an error will be returned. */ size_t ossl_ec_GF2m_simple_point2oct(const EC_GROUP *group, const EC_POINT *point, point_conversion_form_t form, unsigned char *buf, size_t len, BN_CTX *ctx) { size_t ret; int used_ctx = 0; BIGNUM *x, *y, *yxi; size_t field_len, i, skip; #ifndef FIPS_MODULE BN_CTX *new_ctx = NULL; #endif if ((form != POINT_CONVERSION_COMPRESSED) && (form != POINT_CONVERSION_UNCOMPRESSED) && (form != POINT_CONVERSION_HYBRID)) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_FORM); goto err; } if (EC_POINT_is_at_infinity(group, point)) { /* encodes to a single 0 octet */ if (buf != NULL) { if (len < 1) { ERR_raise(ERR_LIB_EC, EC_R_BUFFER_TOO_SMALL); return 0; } buf[0] = 0; } return 1; } /* ret := required output buffer length */ field_len = (EC_GROUP_get_degree(group) + 7) / 8; ret = (form == POINT_CONVERSION_COMPRESSED) ? 1 + field_len : 1 + 2 * field_len; /* if 'buf' is NULL, just return required length */ if (buf != NULL) { if (len < ret) { ERR_raise(ERR_LIB_EC, EC_R_BUFFER_TOO_SMALL); goto err; } #ifndef FIPS_MODULE if (ctx == NULL) { ctx = new_ctx = BN_CTX_new(); if (ctx == NULL) return 0; } #endif BN_CTX_start(ctx); used_ctx = 1; x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); yxi = BN_CTX_get(ctx); if (yxi == NULL) goto err; if (!EC_POINT_get_affine_coordinates(group, point, x, y, ctx)) goto err; buf[0] = form; if ((form != POINT_CONVERSION_UNCOMPRESSED) && !BN_is_zero(x)) { if (!group->meth->field_div(group, yxi, y, x, ctx)) goto err; if (BN_is_odd(yxi)) buf[0]++; } i = 1; skip = field_len - BN_num_bytes(x); if (skip > field_len) { ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR); goto err; } while (skip > 0) { buf[i++] = 0; skip--; } skip = BN_bn2bin(x, buf + i); i += skip; if (i != 1 + field_len) { ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR); goto err; } if (form == POINT_CONVERSION_UNCOMPRESSED || form == POINT_CONVERSION_HYBRID) { skip = field_len - BN_num_bytes(y); if (skip > field_len) { ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR); goto err; } while (skip > 0) { buf[i++] = 0; skip--; } skip = BN_bn2bin(y, buf + i); i += skip; } if (i != ret) { ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR); goto err; } } if (used_ctx) BN_CTX_end(ctx); #ifndef FIPS_MODULE BN_CTX_free(new_ctx); #endif return ret; err: if (used_ctx) BN_CTX_end(ctx); #ifndef FIPS_MODULE BN_CTX_free(new_ctx); #endif return 0; } /* * Converts an octet string representation to an EC_POINT. Note that the * simple implementation only uses affine coordinates. */ int ossl_ec_GF2m_simple_oct2point(const EC_GROUP *group, EC_POINT *point, const unsigned char *buf, size_t len, BN_CTX *ctx) { point_conversion_form_t form; int y_bit, m; BIGNUM *x, *y, *yxi; size_t field_len, enc_len; int ret = 0; #ifndef FIPS_MODULE BN_CTX *new_ctx = NULL; #endif if (len == 0) { ERR_raise(ERR_LIB_EC, EC_R_BUFFER_TOO_SMALL); return 0; } /* * The first octet is the point conversion octet PC, see X9.62, page 4 * and section 4.4.2. It must be: * 0x00 for the point at infinity * 0x02 or 0x03 for compressed form * 0x04 for uncompressed form * 0x06 or 0x07 for hybrid form. * For compressed or hybrid forms, we store the last bit of buf[0] as * y_bit and clear it from buf[0] so as to obtain a POINT_CONVERSION_*. * We error if buf[0] contains any but the above values. */ y_bit = buf[0] & 1; form = buf[0] & ~1U; if ((form != 0) && (form != POINT_CONVERSION_COMPRESSED) && (form != POINT_CONVERSION_UNCOMPRESSED) && (form != POINT_CONVERSION_HYBRID)) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); return 0; } if ((form == 0 || form == POINT_CONVERSION_UNCOMPRESSED) && y_bit) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); return 0; } /* The point at infinity is represented by a single zero octet. */ if (form == 0) { if (len != 1) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); return 0; } return EC_POINT_set_to_infinity(group, point); } m = EC_GROUP_get_degree(group); field_len = (m + 7) / 8; enc_len = (form == POINT_CONVERSION_COMPRESSED) ? 1 + field_len : 1 + 2 * field_len; if (len != enc_len) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); return 0; } #ifndef FIPS_MODULE if (ctx == NULL) { ctx = new_ctx = BN_CTX_new(); if (ctx == NULL) return 0; } #endif BN_CTX_start(ctx); x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); yxi = BN_CTX_get(ctx); if (yxi == NULL) goto err; if (!BN_bin2bn(buf + 1, field_len, x)) goto err; if (BN_num_bits(x) > m) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); goto err; } if (form == POINT_CONVERSION_COMPRESSED) { if (!EC_POINT_set_compressed_coordinates(group, point, x, y_bit, ctx)) goto err; } else { if (!BN_bin2bn(buf + 1 + field_len, field_len, y)) goto err; if (BN_num_bits(y) > m) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); goto err; } if (form == POINT_CONVERSION_HYBRID) { /* * Check that the form in the encoding was set correctly * according to X9.62 4.4.2.a, 4(c), see also first paragraph * of X9.62, 4.4.1.b. */ if (BN_is_zero(x)) { if (y_bit != 0) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); goto err; } } else { if (!group->meth->field_div(group, yxi, y, x, ctx)) goto err; if (y_bit != BN_is_odd(yxi)) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); goto err; } } } /* * EC_POINT_set_affine_coordinates is responsible for checking that * the point is on the curve. */ if (!EC_POINT_set_affine_coordinates(group, point, x, y, ctx)) goto err; } ret = 1; err: BN_CTX_end(ctx); #ifndef FIPS_MODULE BN_CTX_free(new_ctx); #endif return ret; } #endif
11,022
27.191816
81
c
openssl
openssl-master/crypto/ec/ec_ameth.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 */ /* * ECDH and ECDSA 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/x509.h> #include <openssl/ec.h> #include <openssl/bn.h> #include <openssl/asn1t.h> #include "crypto/asn1.h" #include "crypto/evp.h" #include "crypto/x509.h" #include <openssl/core_names.h> #include <openssl/param_build.h> #include "ec_local.h" static int eckey_param2type(int *pptype, void **ppval, const EC_KEY *ec_key) { const EC_GROUP *group; int nid; if (ec_key == NULL || (group = EC_KEY_get0_group(ec_key)) == NULL) { ERR_raise(ERR_LIB_EC, EC_R_MISSING_PARAMETERS); return 0; } if (EC_GROUP_get_asn1_flag(group) && (nid = EC_GROUP_get_curve_name(group))) /* we have a 'named curve' => just set the OID */ { ASN1_OBJECT *asn1obj = OBJ_nid2obj(nid); if (asn1obj == NULL || OBJ_length(asn1obj) == 0) { ERR_raise(ERR_LIB_EC, EC_R_MISSING_OID); return 0; } *ppval = asn1obj; *pptype = V_ASN1_OBJECT; } else { /* explicit parameters */ ASN1_STRING *pstr = NULL; pstr = ASN1_STRING_new(); if (pstr == NULL) return 0; pstr->length = i2d_ECParameters(ec_key, &pstr->data); if (pstr->length <= 0) { ASN1_STRING_free(pstr); ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); return 0; } *ppval = pstr; *pptype = V_ASN1_SEQUENCE; } return 1; } static int eckey_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) { const EC_KEY *ec_key = pkey->pkey.ec; void *pval = NULL; int ptype; unsigned char *penc = NULL, *p; int penclen; if (!eckey_param2type(&ptype, &pval, ec_key)) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); return 0; } penclen = i2o_ECPublicKey(ec_key, NULL); if (penclen <= 0) goto err; penc = OPENSSL_malloc(penclen); if (penc == NULL) goto err; p = penc; penclen = i2o_ECPublicKey(ec_key, &p); if (penclen <= 0) goto err; if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_EC), ptype, pval, penc, penclen)) return 1; err: if (ptype == V_ASN1_SEQUENCE) ASN1_STRING_free(pval); OPENSSL_free(penc); return 0; } static int eckey_pub_decode(EVP_PKEY *pkey, const X509_PUBKEY *pubkey) { const unsigned char *p = NULL; int pklen; EC_KEY *eckey = NULL; X509_ALGOR *palg; OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; if (!ossl_x509_PUBKEY_get0_libctx(&libctx, &propq, pubkey) || !X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey)) return 0; eckey = ossl_ec_key_param_from_x509_algor(palg, libctx, propq); if (!eckey) return 0; /* We have parameters now set public key */ if (!o2i_ECPublicKey(&eckey, &p, pklen)) { ERR_raise(ERR_LIB_EC, EC_R_DECODE_ERROR); goto ecerr; } EVP_PKEY_assign_EC_KEY(pkey, eckey); return 1; ecerr: EC_KEY_free(eckey); return 0; } static int eckey_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { int r; const EC_GROUP *group = EC_KEY_get0_group(b->pkey.ec); const EC_POINT *pa = EC_KEY_get0_public_key(a->pkey.ec), *pb = EC_KEY_get0_public_key(b->pkey.ec); if (group == NULL || pa == NULL || pb == NULL) return -2; r = EC_POINT_cmp(group, pa, pb, NULL); if (r == 0) return 1; if (r == 1) return 0; return -2; } static int eckey_priv_decode_ex(EVP_PKEY *pkey, const PKCS8_PRIV_KEY_INFO *p8, OSSL_LIB_CTX *libctx, const char *propq) { int ret = 0; EC_KEY *eckey = ossl_ec_key_from_pkcs8(p8, libctx, propq); if (eckey != NULL) { ret = 1; EVP_PKEY_assign_EC_KEY(pkey, eckey); } return ret; } static int eckey_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey) { EC_KEY ec_key = *(pkey->pkey.ec); unsigned char *ep = NULL; int eplen, ptype; void *pval; unsigned int old_flags; if (!eckey_param2type(&ptype, &pval, &ec_key)) { ERR_raise(ERR_LIB_EC, EC_R_DECODE_ERROR); return 0; } /* set the private key */ /* * do not include the parameters in the SEC1 private key see PKCS#11 * 12.11 */ old_flags = EC_KEY_get_enc_flags(&ec_key); EC_KEY_set_enc_flags(&ec_key, old_flags | EC_PKEY_NO_PARAMETERS); eplen = i2d_ECPrivateKey(&ec_key, &ep); if (eplen <= 0) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_X9_62_id_ecPublicKey), 0, ptype, pval, ep, eplen)) { ERR_raise(ERR_LIB_EC, ERR_R_ASN1_LIB); OPENSSL_clear_free(ep, eplen); goto err; } return 1; err: if (ptype == V_ASN1_SEQUENCE) ASN1_STRING_free(pval); return 0; } static int int_ec_size(const EVP_PKEY *pkey) { return ECDSA_size(pkey->pkey.ec); } static int ec_bits(const EVP_PKEY *pkey) { return EC_GROUP_order_bits(EC_KEY_get0_group(pkey->pkey.ec)); } static int ec_security_bits(const EVP_PKEY *pkey) { int ecbits = ec_bits(pkey); if (ecbits >= 512) return 256; if (ecbits >= 384) return 192; if (ecbits >= 256) return 128; if (ecbits >= 224) return 112; if (ecbits >= 160) return 80; return ecbits / 2; } static int ec_missing_parameters(const EVP_PKEY *pkey) { if (pkey->pkey.ec == NULL || EC_KEY_get0_group(pkey->pkey.ec) == NULL) return 1; return 0; } static int ec_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) { EC_GROUP *group = EC_GROUP_dup(EC_KEY_get0_group(from->pkey.ec)); if (group == NULL) return 0; if (to->pkey.ec == NULL) { to->pkey.ec = EC_KEY_new(); if (to->pkey.ec == NULL) goto err; } if (EC_KEY_set_group(to->pkey.ec, group) == 0) goto err; EC_GROUP_free(group); return 1; err: EC_GROUP_free(group); return 0; } static int ec_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { const EC_GROUP *group_a = EC_KEY_get0_group(a->pkey.ec), *group_b = EC_KEY_get0_group(b->pkey.ec); if (group_a == NULL || group_b == NULL) return -2; if (EC_GROUP_cmp(group_a, group_b, NULL)) return 0; else return 1; } static void int_ec_free(EVP_PKEY *pkey) { EC_KEY_free(pkey->pkey.ec); } typedef enum { EC_KEY_PRINT_PRIVATE, EC_KEY_PRINT_PUBLIC, EC_KEY_PRINT_PARAM } ec_print_t; static int do_EC_KEY_print(BIO *bp, const EC_KEY *x, int off, ec_print_t ktype) { const char *ecstr; unsigned char *priv = NULL, *pub = NULL; size_t privlen = 0, publen = 0; int ret = 0; const EC_GROUP *group; if (x == NULL || (group = EC_KEY_get0_group(x)) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ktype != EC_KEY_PRINT_PARAM && EC_KEY_get0_public_key(x) != NULL) { publen = EC_KEY_key2buf(x, EC_KEY_get_conv_form(x), &pub, NULL); if (publen == 0) goto err; } if (ktype == EC_KEY_PRINT_PRIVATE && EC_KEY_get0_private_key(x) != NULL) { privlen = EC_KEY_priv2buf(x, &priv); if (privlen == 0) goto err; } if (ktype == EC_KEY_PRINT_PRIVATE) ecstr = "Private-Key"; else if (ktype == EC_KEY_PRINT_PUBLIC) ecstr = "Public-Key"; else ecstr = "ECDSA-Parameters"; if (!BIO_indent(bp, off, 128)) goto err; if (BIO_printf(bp, "%s: (%d bit)\n", ecstr, EC_GROUP_order_bits(group)) <= 0) goto err; if (privlen != 0) { if (BIO_printf(bp, "%*spriv:\n", off, "") <= 0) goto err; if (ASN1_buf_print(bp, priv, privlen, off + 4) == 0) goto err; } if (publen != 0) { if (BIO_printf(bp, "%*spub:\n", off, "") <= 0) goto err; if (ASN1_buf_print(bp, pub, publen, off + 4) == 0) goto err; } if (!ECPKParameters_print(bp, group, off)) goto err; ret = 1; err: if (!ret) ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); OPENSSL_clear_free(priv, privlen); OPENSSL_free(pub); return ret; } static int eckey_param_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { EC_KEY *eckey; if ((eckey = d2i_ECParameters(NULL, pder, derlen)) == NULL) return 0; EVP_PKEY_assign_EC_KEY(pkey, eckey); return 1; } static int eckey_param_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_ECParameters(pkey->pkey.ec, pder); } static int eckey_param_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_EC_KEY_print(bp, pkey->pkey.ec, indent, EC_KEY_PRINT_PARAM); } static int eckey_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_EC_KEY_print(bp, pkey->pkey.ec, indent, EC_KEY_PRINT_PUBLIC); } static int eckey_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_EC_KEY_print(bp, pkey->pkey.ec, indent, EC_KEY_PRINT_PRIVATE); } static int old_ec_priv_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { EC_KEY *ec; if ((ec = d2i_ECPrivateKey(NULL, pder, derlen)) == NULL) return 0; EVP_PKEY_assign_EC_KEY(pkey, ec); return 1; } static int old_ec_priv_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_ECPrivateKey(pkey->pkey.ec, pder); } static int ec_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) { switch (op) { case ASN1_PKEY_CTRL_DEFAULT_MD_NID: if (EVP_PKEY_get_id(pkey) == EVP_PKEY_SM2) { /* For SM2, the only valid digest-alg is SM3 */ *(int *)arg2 = NID_sm3; return 2; /* Make it mandatory */ } *(int *)arg2 = NID_sha256; return 1; 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; return EC_KEY_oct2key(evp_pkey_get0_EC_KEY_int(pkey), arg2, arg1, NULL); case ASN1_PKEY_CTRL_GET1_TLS_ENCPT: return EC_KEY_key2buf(EVP_PKEY_get0_EC_KEY(pkey), POINT_CONVERSION_UNCOMPRESSED, arg2, NULL); default: return -2; } } static int ec_pkey_check(const EVP_PKEY *pkey) { EC_KEY *eckey = pkey->pkey.ec; /* stay consistent to what EVP_PKEY_check demands */ if (eckey->priv_key == NULL) { ERR_raise(ERR_LIB_EC, EC_R_MISSING_PRIVATE_KEY); return 0; } return EC_KEY_check_key(eckey); } static int ec_pkey_public_check(const EVP_PKEY *pkey) { EC_KEY *eckey = pkey->pkey.ec; /* * Note: it unnecessary to check eckey->pub_key here since * it will be checked in EC_KEY_check_key(). In fact, the * EC_KEY_check_key() mainly checks the public key, and checks * the private key optionally (only if there is one). So if * someone passes a whole EC key (public + private), this * will also work... */ return EC_KEY_check_key(eckey); } static int ec_pkey_param_check(const EVP_PKEY *pkey) { EC_KEY *eckey = pkey->pkey.ec; /* stay consistent to what EVP_PKEY_check demands */ if (eckey->group == NULL) { ERR_raise(ERR_LIB_EC, EC_R_MISSING_PARAMETERS); return 0; } return EC_GROUP_check(eckey->group, NULL); } static size_t ec_pkey_dirty_cnt(const EVP_PKEY *pkey) { return pkey->pkey.ec->dirty_cnt; } static int ec_pkey_export_to(const EVP_PKEY *from, void *to_keydata, OSSL_FUNC_keymgmt_import_fn *importer, OSSL_LIB_CTX *libctx, const char *propq) { const EC_KEY *eckey = NULL; const EC_GROUP *ecg = NULL; unsigned char *pub_key_buf = NULL, *gen_buf = NULL; size_t pub_key_buflen; OSSL_PARAM_BLD *tmpl; OSSL_PARAM *params = NULL; const BIGNUM *priv_key = NULL; const EC_POINT *pub_point = NULL; int selection = 0; int rv = 0; BN_CTX *bnctx = NULL; if (from == NULL || (eckey = from->pkey.ec) == NULL || (ecg = EC_KEY_get0_group(eckey)) == NULL) return 0; tmpl = OSSL_PARAM_BLD_new(); if (tmpl == NULL) return 0; /* * EC_POINT_point2buf() can generate random numbers in some * implementations so we need to ensure we use the correct libctx. */ bnctx = BN_CTX_new_ex(libctx); if (bnctx == NULL) goto err; BN_CTX_start(bnctx); /* export the domain parameters */ if (!ossl_ec_group_todata(ecg, tmpl, NULL, libctx, propq, bnctx, &gen_buf)) goto err; selection |= OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS; priv_key = EC_KEY_get0_private_key(eckey); pub_point = EC_KEY_get0_public_key(eckey); if (pub_point != NULL) { /* convert pub_point to a octet string according to the SECG standard */ point_conversion_form_t format = EC_KEY_get_conv_form(eckey); if ((pub_key_buflen = EC_POINT_point2buf(ecg, pub_point, format, &pub_key_buf, bnctx)) == 0 || !OSSL_PARAM_BLD_push_octet_string(tmpl, OSSL_PKEY_PARAM_PUB_KEY, pub_key_buf, pub_key_buflen)) goto err; selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY; } if (priv_key != NULL) { size_t sz; int ecbits; int ecdh_cofactor_mode; /* * Key import/export should never leak the bit length of the secret * scalar in the key. * * For this reason, on export we use padded BIGNUMs with fixed length. * * When importing we also should make sure that, even if short lived, * the newly created BIGNUM is marked with the BN_FLG_CONSTTIME flag as * soon as possible, so that any processing of this BIGNUM might opt for * constant time implementations in the backend. * * Setting the BN_FLG_CONSTTIME flag alone is never enough, we also have * to preallocate the BIGNUM internal buffer to a fixed public size big * enough that operations performed during the processing never trigger * a realloc which would leak the size of the scalar through memory * accesses. * * Fixed Length * ------------ * * The order of the large prime subgroup of the curve is our choice for * a fixed public size, as that is generally the upper bound for * generating a private key in EC cryptosystems and should fit all valid * secret scalars. * * For padding on export we just use the bit length of the order * converted to bytes (rounding up). * * For preallocating the BIGNUM storage we look at the number of "words" * required for the internal representation of the order, and we * preallocate 2 extra "words" in case any of the subsequent processing * might temporarily overflow the order length. */ ecbits = EC_GROUP_order_bits(ecg); if (ecbits <= 0) goto err; sz = (ecbits + 7) / 8; if (!OSSL_PARAM_BLD_push_BN_pad(tmpl, OSSL_PKEY_PARAM_PRIV_KEY, priv_key, sz)) goto err; selection |= OSSL_KEYMGMT_SELECT_PRIVATE_KEY; /* * The ECDH Cofactor Mode is defined only if the EC_KEY actually * contains a private key, so we check for the flag and export it only * in this case. */ ecdh_cofactor_mode = (EC_KEY_get_flags(eckey) & EC_FLAG_COFACTOR_ECDH) ? 1 : 0; /* Export the ECDH_COFACTOR_MODE parameter */ if (!OSSL_PARAM_BLD_push_int(tmpl, OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, ecdh_cofactor_mode)) goto err; selection |= OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS; } params = OSSL_PARAM_BLD_to_param(tmpl); /* We export, the provider imports */ rv = importer(to_keydata, selection, params); err: OSSL_PARAM_BLD_free(tmpl); OSSL_PARAM_free(params); OPENSSL_free(pub_key_buf); OPENSSL_free(gen_buf); BN_CTX_end(bnctx); BN_CTX_free(bnctx); return rv; } static int ec_pkey_import_from(const OSSL_PARAM params[], void *vpctx) { EVP_PKEY_CTX *pctx = vpctx; EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pctx); EC_KEY *ec = EC_KEY_new_ex(pctx->libctx, pctx->propquery); if (ec == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); return 0; } if (!ossl_ec_group_fromdata(ec, params) || !ossl_ec_key_otherparams_fromdata(ec, params) || !ossl_ec_key_fromdata(ec, params, 1) || !EVP_PKEY_assign_EC_KEY(pkey, ec)) { EC_KEY_free(ec); return 0; } return 1; } static int ec_pkey_copy(EVP_PKEY *to, EVP_PKEY *from) { EC_KEY *eckey = from->pkey.ec; EC_KEY *dupkey = NULL; int ret; if (eckey != NULL) { dupkey = EC_KEY_dup(eckey); if (dupkey == NULL) return 0; } else { /* necessary to properly copy empty SM2 keys */ return EVP_PKEY_set_type(to, from->type); } ret = EVP_PKEY_assign_EC_KEY(to, dupkey); if (!ret) EC_KEY_free(dupkey); return ret; } const EVP_PKEY_ASN1_METHOD ossl_eckey_asn1_meth = { EVP_PKEY_EC, EVP_PKEY_EC, 0, "EC", "OpenSSL EC algorithm", eckey_pub_decode, eckey_pub_encode, eckey_pub_cmp, eckey_pub_print, NULL, eckey_priv_encode, eckey_priv_print, int_ec_size, ec_bits, ec_security_bits, eckey_param_decode, eckey_param_encode, ec_missing_parameters, ec_copy_parameters, ec_cmp_parameters, eckey_param_print, 0, int_ec_free, ec_pkey_ctrl, old_ec_priv_decode, old_ec_priv_encode, 0, 0, 0, ec_pkey_check, ec_pkey_public_check, ec_pkey_param_check, 0, /* set_priv_key */ 0, /* set_pub_key */ 0, /* get_priv_key */ 0, /* get_pub_key */ ec_pkey_dirty_cnt, ec_pkey_export_to, ec_pkey_import_from, ec_pkey_copy, eckey_priv_decode_ex }; #if !defined(OPENSSL_NO_SM2) const EVP_PKEY_ASN1_METHOD ossl_sm2_asn1_meth = { EVP_PKEY_SM2, EVP_PKEY_EC, ASN1_PKEY_ALIAS }; #endif int EC_KEY_print(BIO *bp, const EC_KEY *x, int off) { int private = EC_KEY_get0_private_key(x) != NULL; return do_EC_KEY_print(bp, x, off, private ? EC_KEY_PRINT_PRIVATE : EC_KEY_PRINT_PUBLIC); } int ECParameters_print(BIO *bp, const EC_KEY *x) { return do_EC_KEY_print(bp, x, 4, EC_KEY_PRINT_PARAM); }
19,715
26.307479
80
c
openssl
openssl-master/crypto/ec/ec_check.c
/* * Copyright 2002-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 */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "ec_local.h" #include <openssl/err.h> int EC_GROUP_check_named_curve(const EC_GROUP *group, int nist_only, BN_CTX *ctx) { int nid; BN_CTX *new_ctx = NULL; if (group == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER); return NID_undef; } if (ctx == NULL) { ctx = new_ctx = BN_CTX_new_ex(NULL); if (ctx == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); return NID_undef; } } nid = ossl_ec_curve_nid_from_params(group, ctx); if (nid > 0 && nist_only && EC_curve_nid2nist(nid) == NULL) nid = NID_undef; BN_CTX_free(new_ctx); return nid; } int EC_GROUP_check(const EC_GROUP *group, BN_CTX *ctx) { #ifdef FIPS_MODULE /* * ECC domain parameter validation. * See SP800-56A R3 5.5.2 "Assurances of Domain-Parameter Validity" Part 1b. */ return EC_GROUP_check_named_curve(group, 1, ctx) >= 0 ? 1 : 0; #else int ret = 0; const BIGNUM *order; BN_CTX *new_ctx = NULL; EC_POINT *point = NULL; if (group == NULL || group->meth == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* Custom curves assumed to be correct */ if ((group->meth->flags & EC_FLAGS_CUSTOM_CURVE) != 0) return 1; if (ctx == NULL) { ctx = new_ctx = BN_CTX_new(); if (ctx == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } } /* check the discriminant */ if (!EC_GROUP_check_discriminant(group, ctx)) { ERR_raise(ERR_LIB_EC, EC_R_DISCRIMINANT_IS_ZERO); goto err; } /* check the generator */ if (group->generator == NULL) { ERR_raise(ERR_LIB_EC, EC_R_UNDEFINED_GENERATOR); goto err; } if (EC_POINT_is_on_curve(group, group->generator, ctx) <= 0) { ERR_raise(ERR_LIB_EC, EC_R_POINT_IS_NOT_ON_CURVE); goto err; } /* check the order of the generator */ if ((point = EC_POINT_new(group)) == NULL) goto err; order = EC_GROUP_get0_order(group); if (order == NULL) goto err; if (BN_is_zero(order)) { ERR_raise(ERR_LIB_EC, EC_R_UNDEFINED_ORDER); goto err; } if (!EC_POINT_mul(group, point, order, NULL, NULL, ctx)) goto err; if (!EC_POINT_is_at_infinity(group, point)) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_GROUP_ORDER); goto err; } ret = 1; err: BN_CTX_free(new_ctx); EC_POINT_free(point); return ret; #endif /* FIPS_MODULE */ }
3,071
24.815126
79
c
openssl
openssl-master/crypto/ec/ec_cvt.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/err.h> #include "crypto/bn.h" #include "ec_local.h" EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { const EC_METHOD *meth; EC_GROUP *ret; #if defined(OPENSSL_BN_ASM_MONT) /* * This might appear controversial, but the fact is that generic * prime method was observed to deliver better performance even * for NIST primes on a range of platforms, e.g.: 60%-15% * improvement on IA-64, ~25% on ARM, 30%-90% on P4, 20%-25% * in 32-bit build and 35%--12% in 64-bit build on Core2... * Coefficients are relative to optimized bn_nist.c for most * intensive ECDSA verify and ECDH operations for 192- and 521- * bit keys respectively. Choice of these boundary values is * arguable, because the dependency of improvement coefficient * from key length is not a "monotone" curve. For example while * 571-bit result is 23% on ARM, 384-bit one is -1%. But it's * generally faster, sometimes "respectfully" faster, sometimes * "tolerably" slower... What effectively happens is that loop * with bn_mul_add_words is put against bn_mul_mont, and the * latter "wins" on short vectors. Correct solution should be * implementing dedicated NxN multiplication subroutines for * small N. But till it materializes, let's stick to generic * prime method... * <appro> */ meth = EC_GFp_mont_method(); #else if (BN_nist_mod_func(p)) meth = EC_GFp_nist_method(); else meth = EC_GFp_mont_method(); #endif ret = ossl_ec_group_new_ex(ossl_bn_get_libctx(ctx), NULL, meth); if (ret == NULL) return NULL; if (!EC_GROUP_set_curve(ret, p, a, b, ctx)) { EC_GROUP_free(ret); return NULL; } return ret; } #ifndef OPENSSL_NO_EC2M EC_GROUP *EC_GROUP_new_curve_GF2m(const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { const EC_METHOD *meth; EC_GROUP *ret; meth = EC_GF2m_simple_method(); ret = ossl_ec_group_new_ex(ossl_bn_get_libctx(ctx), NULL, meth); if (ret == NULL) return NULL; if (!EC_GROUP_set_curve(ret, p, a, b, ctx)) { EC_GROUP_free(ret); return NULL; } return ret; } #endif
2,925
31.511111
74
c
openssl
openssl-master/crypto/ec/ec_deprecated.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 */ /* * Suppress deprecation warnings for EC low level implementations that are * kept until removal. */ #define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/ec.h> #ifndef OPENSSL_NO_DEPRECATED_3_0 BIGNUM *EC_POINT_point2bn(const EC_GROUP *group, const EC_POINT *point, point_conversion_form_t form, BIGNUM *ret, BN_CTX *ctx) { size_t buf_len = 0; unsigned char *buf; buf_len = EC_POINT_point2buf(group, point, form, &buf, ctx); if (buf_len == 0) return NULL; ret = BN_bin2bn(buf, buf_len, ret); OPENSSL_free(buf); return ret; } EC_POINT *EC_POINT_bn2point(const EC_GROUP *group, const BIGNUM *bn, EC_POINT *point, BN_CTX *ctx) { size_t buf_len = 0; unsigned char *buf; EC_POINT *ret; if ((buf_len = BN_num_bytes(bn)) == 0) buf_len = 1; if ((buf = OPENSSL_malloc(buf_len)) == NULL) return NULL; if (BN_bn2binpad(bn, buf, buf_len) < 0) { OPENSSL_free(buf); return NULL; } if (point == NULL) { if ((ret = EC_POINT_new(group)) == NULL) { OPENSSL_free(buf); return NULL; } } else ret = point; if (!EC_POINT_oct2point(group, ret, buf, buf_len, ctx)) { if (ret != point) EC_POINT_clear_free(ret); OPENSSL_free(buf); return NULL; } OPENSSL_free(buf); return ret; } #endif /* OPENSSL_NO_DEPRECATED_3_0 */
1,911
23.831169
75
c
openssl
openssl-master/crypto/ec/ec_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/ecerr.h> #include "crypto/ecerr.h" #ifndef OPENSSL_NO_EC # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA EC_str_reasons[] = { {ERR_PACK(ERR_LIB_EC, 0, EC_R_ASN1_ERROR), "asn1 error"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_BAD_SIGNATURE), "bad signature"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_BIGNUM_OUT_OF_RANGE), "bignum out of range"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_BUFFER_TOO_SMALL), "buffer too small"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_CANNOT_INVERT), "cannot invert"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_COORDINATES_OUT_OF_RANGE), "coordinates out of range"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_CURVE_DOES_NOT_SUPPORT_ECDH), "curve does not support ecdh"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_CURVE_DOES_NOT_SUPPORT_ECDSA), "curve does not support ecdsa"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING), "curve does not support signing"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_DECODE_ERROR), "decode error"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_DISCRIMINANT_IS_ZERO), "discriminant is zero"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_EC_GROUP_NEW_BY_NAME_FAILURE), "ec group new by name failure"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_EXPLICIT_PARAMS_NOT_SUPPORTED), "explicit params not supported"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_FAILED_MAKING_PUBLIC_KEY), "failed making public key"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_FIELD_TOO_LARGE), "field too large"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_GF2M_NOT_SUPPORTED), "gf2m not supported"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_GROUP2PKPARAMETERS_FAILURE), "group2pkparameters failure"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_I2D_ECPKPARAMETERS_FAILURE), "i2d ecpkparameters failure"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INCOMPATIBLE_OBJECTS), "incompatible objects"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_A), "invalid a"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_ARGUMENT), "invalid argument"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_B), "invalid b"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_COFACTOR), "invalid cofactor"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_COMPRESSED_POINT), "invalid compressed point"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_COMPRESSION_BIT), "invalid compression bit"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_CURVE), "invalid curve"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_DIGEST), "invalid digest"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_DIGEST_TYPE), "invalid digest type"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_ENCODING), "invalid encoding"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_FIELD), "invalid field"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_FORM), "invalid form"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_GENERATOR), "invalid generator"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_GROUP_ORDER), "invalid group order"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_KEY), "invalid key"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_LENGTH), "invalid length"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_NAMED_GROUP_CONVERSION), "invalid named group conversion"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_OUTPUT_LENGTH), "invalid output length"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_P), "invalid p"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_PEER_KEY), "invalid peer key"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_PENTANOMIAL_BASIS), "invalid pentanomial basis"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_PRIVATE_KEY), "invalid private key"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_SEED), "invalid seed"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_TRINOMIAL_BASIS), "invalid trinomial basis"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_KDF_PARAMETER_ERROR), "kdf parameter error"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_KEYS_NOT_SET), "keys not set"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_LADDER_POST_FAILURE), "ladder post failure"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_LADDER_PRE_FAILURE), "ladder pre failure"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_LADDER_STEP_FAILURE), "ladder step failure"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_MISSING_OID), "missing OID"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_MISSING_PARAMETERS), "missing parameters"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_MISSING_PRIVATE_KEY), "missing private key"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_NEED_NEW_SETUP_VALUES), "need new setup values"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_NOT_A_NIST_PRIME), "not a NIST prime"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_NOT_IMPLEMENTED), "not implemented"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_NOT_INITIALIZED), "not initialized"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_NO_PARAMETERS_SET), "no parameters set"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_NO_PRIVATE_VALUE), "no private value"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_OPERATION_NOT_SUPPORTED), "operation not supported"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_PASSED_NULL_PARAMETER), "passed null parameter"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_PEER_KEY_ERROR), "peer key error"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_POINT_ARITHMETIC_FAILURE), "point arithmetic failure"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_POINT_AT_INFINITY), "point at infinity"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_POINT_COORDINATES_BLIND_FAILURE), "point coordinates blind failure"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_POINT_IS_NOT_ON_CURVE), "point is not on curve"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_RANDOM_NUMBER_GENERATION_FAILED), "random number generation failed"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_SHARED_INFO_ERROR), "shared info error"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_SLOT_FULL), "slot full"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_TOO_MANY_RETRIES), "too many retries"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_UNDEFINED_GENERATOR), "undefined generator"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_UNDEFINED_ORDER), "undefined order"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_UNKNOWN_COFACTOR), "unknown cofactor"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_UNKNOWN_GROUP), "unknown group"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_UNKNOWN_ORDER), "unknown order"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_UNSUPPORTED_FIELD), "unsupported field"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_WRONG_CURVE_PARAMETERS), "wrong curve parameters"}, {ERR_PACK(ERR_LIB_EC, 0, EC_R_WRONG_ORDER), "wrong order"}, {0, NULL} }; # endif int ossl_err_load_EC_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(EC_str_reasons[0].error) == NULL) ERR_load_strings_const(EC_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
6,880
49.226277
79
c
openssl
openssl-master/crypto/ec/ec_kmeth.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 */ /* * ECDH and ECDSA low level APIs are deprecated for public use, but still ok * for internal use. */ #include "internal/deprecated.h" #include <string.h> #include <openssl/ec.h> #ifndef FIPS_MODULE # include <openssl/engine.h> #endif #include <openssl/err.h> #include "ec_local.h" static const EC_KEY_METHOD openssl_ec_key_method = { "OpenSSL EC_KEY method", 0, 0,0,0,0,0,0, ossl_ec_key_gen, ossl_ecdh_compute_key, ossl_ecdsa_sign, ossl_ecdsa_sign_setup, ossl_ecdsa_sign_sig, ossl_ecdsa_verify, ossl_ecdsa_verify_sig }; static const EC_KEY_METHOD *default_ec_key_meth = &openssl_ec_key_method; const EC_KEY_METHOD *EC_KEY_OpenSSL(void) { return &openssl_ec_key_method; } const EC_KEY_METHOD *EC_KEY_get_default_method(void) { return default_ec_key_meth; } void EC_KEY_set_default_method(const EC_KEY_METHOD *meth) { if (meth == NULL) default_ec_key_meth = &openssl_ec_key_method; else default_ec_key_meth = meth; } const EC_KEY_METHOD *EC_KEY_get_method(const EC_KEY *key) { return key->meth; } int EC_KEY_set_method(EC_KEY *key, const EC_KEY_METHOD *meth) { void (*finish)(EC_KEY *key) = key->meth->finish; if (finish != NULL) finish(key); #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) ENGINE_finish(key->engine); key->engine = NULL; #endif key->meth = meth; if (meth->init != NULL) return meth->init(key); return 1; } EC_KEY *ossl_ec_key_new_method_int(OSSL_LIB_CTX *libctx, const char *propq, ENGINE *engine) { EC_KEY *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; if (!CRYPTO_NEW_REF(&ret->references, 1)) { OPENSSL_free(ret); return NULL; } ret->libctx = libctx; if (propq != NULL) { ret->propq = OPENSSL_strdup(propq); if (ret->propq == NULL) goto err; } ret->meth = EC_KEY_get_default_method(); #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) if (engine != NULL) { if (!ENGINE_init(engine)) { ERR_raise(ERR_LIB_EC, ERR_R_ENGINE_LIB); goto err; } ret->engine = engine; } else ret->engine = ENGINE_get_default_EC(); if (ret->engine != NULL) { ret->meth = ENGINE_get_EC(ret->engine); if (ret->meth == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_ENGINE_LIB); goto err; } } #endif ret->version = 1; ret->conv_form = POINT_CONVERSION_UNCOMPRESSED; /* No ex_data inside the FIPS provider */ #ifndef FIPS_MODULE if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_EC_KEY, ret, &ret->ex_data)) { ERR_raise(ERR_LIB_EC, ERR_R_CRYPTO_LIB); goto err; } #endif if (ret->meth->init != NULL && ret->meth->init(ret) == 0) { ERR_raise(ERR_LIB_EC, ERR_R_INIT_FAIL); goto err; } return ret; err: EC_KEY_free(ret); return NULL; } #ifndef FIPS_MODULE EC_KEY *EC_KEY_new_method(ENGINE *engine) { return ossl_ec_key_new_method_int(NULL, NULL, engine); } #endif int ECDH_compute_key(void *out, size_t outlen, const EC_POINT *pub_key, const EC_KEY *eckey, void *(*KDF) (const void *in, size_t inlen, void *out, size_t *outlen)) { unsigned char *sec = NULL; size_t seclen; if (eckey->meth->compute_key == NULL) { ERR_raise(ERR_LIB_EC, EC_R_OPERATION_NOT_SUPPORTED); return 0; } if (outlen > INT_MAX) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_OUTPUT_LENGTH); return 0; } if (!eckey->meth->compute_key(&sec, &seclen, pub_key, eckey)) return 0; if (KDF != NULL) { KDF(sec, seclen, out, &outlen); } else { if (outlen > seclen) outlen = seclen; memcpy(out, sec, outlen); } OPENSSL_clear_free(sec, seclen); return outlen; } EC_KEY_METHOD *EC_KEY_METHOD_new(const EC_KEY_METHOD *meth) { EC_KEY_METHOD *ret = OPENSSL_zalloc(sizeof(*meth)); if (ret == NULL) return NULL; if (meth != NULL) *ret = *meth; ret->flags |= EC_KEY_METHOD_DYNAMIC; return ret; } void EC_KEY_METHOD_free(EC_KEY_METHOD *meth) { if (meth->flags & EC_KEY_METHOD_DYNAMIC) OPENSSL_free(meth); } void EC_KEY_METHOD_set_init(EC_KEY_METHOD *meth, int (*init)(EC_KEY *key), void (*finish)(EC_KEY *key), int (*copy)(EC_KEY *dest, const EC_KEY *src), int (*set_group)(EC_KEY *key, const EC_GROUP *grp), int (*set_private)(EC_KEY *key, const BIGNUM *priv_key), int (*set_public)(EC_KEY *key, const EC_POINT *pub_key)) { meth->init = init; meth->finish = finish; meth->copy = copy; meth->set_group = set_group; meth->set_private = set_private; meth->set_public = set_public; } void EC_KEY_METHOD_set_keygen(EC_KEY_METHOD *meth, int (*keygen)(EC_KEY *key)) { meth->keygen = keygen; } void EC_KEY_METHOD_set_compute_key(EC_KEY_METHOD *meth, int (*ckey)(unsigned char **psec, size_t *pseclen, const EC_POINT *pub_key, const EC_KEY *ecdh)) { meth->compute_key = ckey; } void EC_KEY_METHOD_set_sign(EC_KEY_METHOD *meth, int (*sign)(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey), int (*sign_setup)(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp), ECDSA_SIG *(*sign_sig)(const unsigned char *dgst, int dgst_len, const BIGNUM *in_kinv, const BIGNUM *in_r, EC_KEY *eckey)) { meth->sign = sign; meth->sign_setup = sign_setup; meth->sign_sig = sign_sig; } void EC_KEY_METHOD_set_verify(EC_KEY_METHOD *meth, int (*verify)(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int sig_len, EC_KEY *eckey), int (*verify_sig)(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey)) { meth->verify = verify; meth->verify_sig = verify_sig; } void EC_KEY_METHOD_get_init(const EC_KEY_METHOD *meth, int (**pinit)(EC_KEY *key), void (**pfinish)(EC_KEY *key), int (**pcopy)(EC_KEY *dest, const EC_KEY *src), int (**pset_group)(EC_KEY *key, const EC_GROUP *grp), int (**pset_private)(EC_KEY *key, const BIGNUM *priv_key), int (**pset_public)(EC_KEY *key, const EC_POINT *pub_key)) { if (pinit != NULL) *pinit = meth->init; if (pfinish != NULL) *pfinish = meth->finish; if (pcopy != NULL) *pcopy = meth->copy; if (pset_group != NULL) *pset_group = meth->set_group; if (pset_private != NULL) *pset_private = meth->set_private; if (pset_public != NULL) *pset_public = meth->set_public; } void EC_KEY_METHOD_get_keygen(const EC_KEY_METHOD *meth, int (**pkeygen)(EC_KEY *key)) { if (pkeygen != NULL) *pkeygen = meth->keygen; } void EC_KEY_METHOD_get_compute_key(const EC_KEY_METHOD *meth, int (**pck)(unsigned char **pout, size_t *poutlen, const EC_POINT *pub_key, const EC_KEY *ecdh)) { if (pck != NULL) *pck = meth->compute_key; } void EC_KEY_METHOD_get_sign(const EC_KEY_METHOD *meth, int (**psign)(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey), int (**psign_setup)(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp), ECDSA_SIG *(**psign_sig)(const unsigned char *dgst, int dgst_len, const BIGNUM *in_kinv, const BIGNUM *in_r, EC_KEY *eckey)) { if (psign != NULL) *psign = meth->sign; if (psign_setup != NULL) *psign_setup = meth->sign_setup; if (psign_sig != NULL) *psign_sig = meth->sign_sig; } void EC_KEY_METHOD_get_verify(const EC_KEY_METHOD *meth, int (**pverify)(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int sig_len, EC_KEY *eckey), int (**pverify_sig)(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey)) { if (pverify != NULL) *pverify = meth->verify; if (pverify_sig != NULL) *pverify_sig = meth->verify_sig; }
11,110
31.679412
79
c
openssl
openssl-master/crypto/ec/ec_oct.c
/* * Copyright 2011-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <string.h> #include <openssl/err.h> #include <openssl/opensslv.h> #include "ec_local.h" int EC_POINT_set_compressed_coordinates(const EC_GROUP *group, EC_POINT *point, const BIGNUM *x, int y_bit, BN_CTX *ctx) { if (group->meth->point_set_compressed_coordinates == NULL && !(group->meth->flags & EC_FLAGS_DEFAULT_OCT)) { ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (!ec_point_is_compat(point, group)) { ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } if (group->meth->flags & EC_FLAGS_DEFAULT_OCT) { if (group->meth->field_type == NID_X9_62_prime_field) return ossl_ec_GFp_simple_set_compressed_coordinates(group, point, x, y_bit, ctx); else #ifdef OPENSSL_NO_EC2M { ERR_raise(ERR_LIB_EC, EC_R_GF2M_NOT_SUPPORTED); return 0; } #else return ossl_ec_GF2m_simple_set_compressed_coordinates(group, point, x, y_bit, ctx); #endif } return group->meth->point_set_compressed_coordinates(group, point, x, y_bit, ctx); } #ifndef OPENSSL_NO_DEPRECATED_3_0 int EC_POINT_set_compressed_coordinates_GFp(const EC_GROUP *group, EC_POINT *point, const BIGNUM *x, int y_bit, BN_CTX *ctx) { return EC_POINT_set_compressed_coordinates(group, point, x, y_bit, ctx); } # ifndef OPENSSL_NO_EC2M int EC_POINT_set_compressed_coordinates_GF2m(const EC_GROUP *group, EC_POINT *point, const BIGNUM *x, int y_bit, BN_CTX *ctx) { return EC_POINT_set_compressed_coordinates(group, point, x, y_bit, ctx); } # endif #endif size_t EC_POINT_point2oct(const EC_GROUP *group, const EC_POINT *point, point_conversion_form_t form, unsigned char *buf, size_t len, BN_CTX *ctx) { if (group->meth->point2oct == 0 && !(group->meth->flags & EC_FLAGS_DEFAULT_OCT)) { ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (!ec_point_is_compat(point, group)) { ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } if (group->meth->flags & EC_FLAGS_DEFAULT_OCT) { if (group->meth->field_type == NID_X9_62_prime_field) return ossl_ec_GFp_simple_point2oct(group, point, form, buf, len, ctx); else #ifdef OPENSSL_NO_EC2M { ERR_raise(ERR_LIB_EC, EC_R_GF2M_NOT_SUPPORTED); return 0; } #else return ossl_ec_GF2m_simple_point2oct(group, point, form, buf, len, ctx); #endif } return group->meth->point2oct(group, point, form, buf, len, ctx); } int EC_POINT_oct2point(const EC_GROUP *group, EC_POINT *point, const unsigned char *buf, size_t len, BN_CTX *ctx) { if (group->meth->oct2point == 0 && !(group->meth->flags & EC_FLAGS_DEFAULT_OCT)) { ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (!ec_point_is_compat(point, group)) { ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS); return 0; } if (group->meth->flags & EC_FLAGS_DEFAULT_OCT) { if (group->meth->field_type == NID_X9_62_prime_field) return ossl_ec_GFp_simple_oct2point(group, point, buf, len, ctx); else #ifdef OPENSSL_NO_EC2M { ERR_raise(ERR_LIB_EC, EC_R_GF2M_NOT_SUPPORTED); return 0; } #else return ossl_ec_GF2m_simple_oct2point(group, point, buf, len, ctx); #endif } return group->meth->oct2point(group, point, buf, len, ctx); } size_t EC_POINT_point2buf(const EC_GROUP *group, const EC_POINT *point, point_conversion_form_t form, unsigned char **pbuf, BN_CTX *ctx) { size_t len; unsigned char *buf; len = EC_POINT_point2oct(group, point, form, NULL, 0, NULL); if (len == 0) return 0; if ((buf = OPENSSL_malloc(len)) == NULL) return 0; len = EC_POINT_point2oct(group, point, form, buf, len, ctx); if (len == 0) { OPENSSL_free(buf); return 0; } *pbuf = buf; return len; }
5,188
32.915033
81
c
openssl
openssl-master/crypto/ec/ec_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 */ /* * ECDH and ECDSA 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/ec.h> #include "ec_local.h" #include <openssl/evp.h> #include "crypto/evp.h" /* EC pkey context structure */ typedef struct { /* Key and paramgen group */ EC_GROUP *gen_group; /* message digest */ const EVP_MD *md; /* Duplicate key if custom cofactor needed */ EC_KEY *co_key; /* Cofactor mode */ signed char cofactor_mode; /* KDF (if any) to use for ECDH */ char kdf_type; /* 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; } EC_PKEY_CTX; static int pkey_ec_init(EVP_PKEY_CTX *ctx) { EC_PKEY_CTX *dctx; if ((dctx = OPENSSL_zalloc(sizeof(*dctx))) == NULL) return 0; dctx->cofactor_mode = -1; dctx->kdf_type = EVP_PKEY_ECDH_KDF_NONE; ctx->data = dctx; return 1; } static int pkey_ec_copy(EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src) { EC_PKEY_CTX *dctx, *sctx; if (!pkey_ec_init(dst)) return 0; sctx = src->data; dctx = dst->data; if (sctx->gen_group) { dctx->gen_group = EC_GROUP_dup(sctx->gen_group); if (!dctx->gen_group) return 0; } dctx->md = sctx->md; if (sctx->co_key) { dctx->co_key = EC_KEY_dup(sctx->co_key); if (!dctx->co_key) return 0; } dctx->kdf_type = sctx->kdf_type; dctx->kdf_md = sctx->kdf_md; dctx->kdf_outlen = sctx->kdf_outlen; if (sctx->kdf_ukm) { dctx->kdf_ukm = OPENSSL_memdup(sctx->kdf_ukm, sctx->kdf_ukmlen); if (!dctx->kdf_ukm) return 0; } else dctx->kdf_ukm = NULL; dctx->kdf_ukmlen = sctx->kdf_ukmlen; return 1; } static void pkey_ec_cleanup(EVP_PKEY_CTX *ctx) { EC_PKEY_CTX *dctx = ctx->data; if (dctx != NULL) { EC_GROUP_free(dctx->gen_group); EC_KEY_free(dctx->co_key); OPENSSL_free(dctx->kdf_ukm); OPENSSL_free(dctx); ctx->data = NULL; } } static int pkey_ec_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen) { int ret, type; unsigned int sltmp; EC_PKEY_CTX *dctx = ctx->data; /* * Discard const. Its marked as const because this may be a cached copy of * the "real" key. These calls don't make any modifications that need to * be reflected back in the "original" key. */ EC_KEY *ec = (EC_KEY *)EVP_PKEY_get0_EC_KEY(ctx->pkey); const int sig_sz = ECDSA_size(ec); /* ensure cast to size_t is safe */ if (!ossl_assert(sig_sz > 0)) return 0; if (sig == NULL) { *siglen = (size_t)sig_sz; return 1; } if (*siglen < (size_t)sig_sz) { ERR_raise(ERR_LIB_EC, EC_R_BUFFER_TOO_SMALL); return 0; } type = (dctx->md != NULL) ? EVP_MD_get_type(dctx->md) : NID_sha1; ret = ECDSA_sign(type, tbs, tbslen, sig, &sltmp, ec); if (ret <= 0) return ret; *siglen = (size_t)sltmp; return 1; } static int pkey_ec_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig, size_t siglen, const unsigned char *tbs, size_t tbslen) { int ret, type; EC_PKEY_CTX *dctx = ctx->data; /* * Discard const. Its marked as const because this may be a cached copy of * the "real" key. These calls don't make any modifications that need to * be reflected back in the "original" key. */ EC_KEY *ec = (EC_KEY *)EVP_PKEY_get0_EC_KEY(ctx->pkey); if (dctx->md) type = EVP_MD_get_type(dctx->md); else type = NID_sha1; ret = ECDSA_verify(type, tbs, tbslen, sig, siglen, ec); return ret; } #ifndef OPENSSL_NO_EC static int pkey_ec_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen) { int ret; size_t outlen; const EC_POINT *pubkey = NULL; EC_KEY *eckey; const EC_KEY *eckeypub; EC_PKEY_CTX *dctx = ctx->data; if (ctx->pkey == NULL || ctx->peerkey == NULL) { ERR_raise(ERR_LIB_EC, EC_R_KEYS_NOT_SET); return 0; } eckeypub = EVP_PKEY_get0_EC_KEY(ctx->peerkey); if (eckeypub == NULL) { ERR_raise(ERR_LIB_EC, EC_R_KEYS_NOT_SET); return 0; } eckey = dctx->co_key ? dctx->co_key : (EC_KEY *)EVP_PKEY_get0_EC_KEY(ctx->pkey); if (!key) { const EC_GROUP *group; group = EC_KEY_get0_group(eckey); if (group == NULL) return 0; *keylen = (EC_GROUP_get_degree(group) + 7) / 8; return 1; } pubkey = EC_KEY_get0_public_key(eckeypub); /* * NB: unlike PKCS#3 DH, if *outlen is less than maximum size this is not * an error, the result is truncated. */ outlen = *keylen; ret = ECDH_compute_key(key, outlen, pubkey, eckey, 0); if (ret <= 0) return 0; *keylen = ret; return 1; } static int pkey_ec_kdf_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen) { EC_PKEY_CTX *dctx = ctx->data; unsigned char *ktmp = NULL; size_t ktmplen; int rv = 0; if (dctx->kdf_type == EVP_PKEY_ECDH_KDF_NONE) return pkey_ec_derive(ctx, key, keylen); if (!key) { *keylen = dctx->kdf_outlen; return 1; } if (*keylen != dctx->kdf_outlen) return 0; if (!pkey_ec_derive(ctx, NULL, &ktmplen)) return 0; if ((ktmp = OPENSSL_malloc(ktmplen)) == NULL) return 0; if (!pkey_ec_derive(ctx, ktmp, &ktmplen)) goto err; /* Do KDF stuff */ if (!ossl_ecdh_kdf_X9_63(key, *keylen, ktmp, ktmplen, dctx->kdf_ukm, dctx->kdf_ukmlen, dctx->kdf_md, ctx->libctx, ctx->propquery)) goto err; rv = 1; err: OPENSSL_clear_free(ktmp, ktmplen); return rv; } #endif static int pkey_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { EC_PKEY_CTX *dctx = ctx->data; EC_GROUP *group; switch (type) { case EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID: group = EC_GROUP_new_by_curve_name(p1); if (group == NULL) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_CURVE); return 0; } EC_GROUP_free(dctx->gen_group); dctx->gen_group = group; return 1; case EVP_PKEY_CTRL_EC_PARAM_ENC: if (!dctx->gen_group) { ERR_raise(ERR_LIB_EC, EC_R_NO_PARAMETERS_SET); return 0; } EC_GROUP_set_asn1_flag(dctx->gen_group, p1); return 1; #ifndef OPENSSL_NO_EC case EVP_PKEY_CTRL_EC_ECDH_COFACTOR: if (p1 == -2) { if (dctx->cofactor_mode != -1) return dctx->cofactor_mode; else { const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(ctx->pkey); return EC_KEY_get_flags(ec_key) & EC_FLAG_COFACTOR_ECDH ? 1 : 0; } } else if (p1 < -1 || p1 > 1) return -2; dctx->cofactor_mode = p1; if (p1 != -1) { EC_KEY *ec_key = (EC_KEY *)EVP_PKEY_get0_EC_KEY(ctx->pkey); /* * We discarded the "const" above. This will only work if the key is * a "real" legacy key, and not a cached copy of a provided key */ if (evp_pkey_is_provided(ctx->pkey)) { ERR_raise(ERR_LIB_EC, ERR_R_UNSUPPORTED); return 0; } if (!ec_key->group) return -2; /* If cofactor is 1 cofactor mode does nothing */ if (BN_is_one(ec_key->group->cofactor)) return 1; if (!dctx->co_key) { dctx->co_key = EC_KEY_dup(ec_key); if (!dctx->co_key) return 0; } if (p1) EC_KEY_set_flags(dctx->co_key, EC_FLAG_COFACTOR_ECDH); else EC_KEY_clear_flags(dctx->co_key, EC_FLAG_COFACTOR_ECDH); } else { EC_KEY_free(dctx->co_key); dctx->co_key = NULL; } return 1; #endif case EVP_PKEY_CTRL_EC_KDF_TYPE: if (p1 == -2) return dctx->kdf_type; if (p1 != EVP_PKEY_ECDH_KDF_NONE && p1 != EVP_PKEY_ECDH_KDF_X9_63) return -2; dctx->kdf_type = p1; return 1; case EVP_PKEY_CTRL_EC_KDF_MD: dctx->kdf_md = p2; return 1; case EVP_PKEY_CTRL_GET_EC_KDF_MD: *(const EVP_MD **)p2 = dctx->kdf_md; return 1; case EVP_PKEY_CTRL_EC_KDF_OUTLEN: if (p1 <= 0) return -2; dctx->kdf_outlen = (size_t)p1; return 1; case EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN: *(int *)p2 = dctx->kdf_outlen; return 1; case EVP_PKEY_CTRL_EC_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_EC_KDF_UKM: *(unsigned char **)p2 = dctx->kdf_ukm; return dctx->kdf_ukmlen; case EVP_PKEY_CTRL_MD: if (EVP_MD_get_type((const EVP_MD *)p2) != NID_sha1 && EVP_MD_get_type((const EVP_MD *)p2) != NID_ecdsa_with_SHA1 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha224 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha256 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha384 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha512 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_224 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_256 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_384 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_512 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sm3) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_DIGEST_TYPE); return 0; } dctx->md = p2; return 1; case EVP_PKEY_CTRL_GET_MD: *(const EVP_MD **)p2 = dctx->md; return 1; case EVP_PKEY_CTRL_PEER_KEY: /* Default behaviour is OK */ case EVP_PKEY_CTRL_DIGESTINIT: case EVP_PKEY_CTRL_PKCS7_SIGN: case EVP_PKEY_CTRL_CMS_SIGN: return 1; default: return -2; } } static int pkey_ec_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { if (strcmp(type, "ec_paramgen_curve") == 0) { int nid; nid = EC_curve_nist2nid(value); if (nid == NID_undef) nid = OBJ_sn2nid(value); if (nid == NID_undef) nid = OBJ_ln2nid(value); if (nid == NID_undef) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_CURVE); return 0; } return EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, nid); } else if (strcmp(type, "ec_param_enc") == 0) { int param_enc; if (strcmp(value, "explicit") == 0) param_enc = 0; else if (strcmp(value, "named_curve") == 0) param_enc = OPENSSL_EC_NAMED_CURVE; else return -2; return EVP_PKEY_CTX_set_ec_param_enc(ctx, param_enc); } else if (strcmp(type, "ecdh_kdf_md") == 0) { const EVP_MD *md; if ((md = EVP_get_digestbyname(value)) == NULL) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_DIGEST); return 0; } return EVP_PKEY_CTX_set_ecdh_kdf_md(ctx, md); } else if (strcmp(type, "ecdh_cofactor_mode") == 0) { int co_mode; co_mode = atoi(value); return EVP_PKEY_CTX_set_ecdh_cofactor_mode(ctx, co_mode); } return -2; } static int pkey_ec_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { EC_KEY *ec = NULL; EC_PKEY_CTX *dctx = ctx->data; int ret; if (dctx->gen_group == NULL) { ERR_raise(ERR_LIB_EC, EC_R_NO_PARAMETERS_SET); return 0; } ec = EC_KEY_new(); if (ec == NULL) return 0; if (!(ret = EC_KEY_set_group(ec, dctx->gen_group)) || !ossl_assert(ret = EVP_PKEY_assign_EC_KEY(pkey, ec))) EC_KEY_free(ec); return ret; } static int pkey_ec_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { EC_KEY *ec = NULL; EC_PKEY_CTX *dctx = ctx->data; int ret; if (ctx->pkey == NULL && dctx->gen_group == NULL) { ERR_raise(ERR_LIB_EC, EC_R_NO_PARAMETERS_SET); return 0; } ec = EC_KEY_new(); if (ec == NULL) return 0; if (!ossl_assert(EVP_PKEY_assign_EC_KEY(pkey, ec))) { EC_KEY_free(ec); return 0; } /* Note: if error is returned, we count on caller to free pkey->pkey.ec */ if (ctx->pkey != NULL) ret = EVP_PKEY_copy_parameters(pkey, ctx->pkey); else ret = EC_KEY_set_group(ec, dctx->gen_group); return ret ? EC_KEY_generate_key(ec) : 0; } static const EVP_PKEY_METHOD ec_pkey_meth = { EVP_PKEY_EC, 0, pkey_ec_init, pkey_ec_copy, pkey_ec_cleanup, 0, pkey_ec_paramgen, 0, pkey_ec_keygen, 0, pkey_ec_sign, 0, pkey_ec_verify, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #ifndef OPENSSL_NO_EC pkey_ec_kdf_derive, #else 0, #endif pkey_ec_ctrl, pkey_ec_ctrl_str }; const EVP_PKEY_METHOD *ossl_ec_pkey_method(void) { return &ec_pkey_meth; }
14,021
26.174419
80
c
openssl
openssl-master/crypto/ec/ec_print.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 */ #include <string.h> /* strlen */ #include <openssl/crypto.h> #include "ec_local.h" static const char *HEX_DIGITS = "0123456789ABCDEF"; /* the return value must be freed (using OPENSSL_free()) */ char *EC_POINT_point2hex(const EC_GROUP *group, const EC_POINT *point, point_conversion_form_t form, BN_CTX *ctx) { char *ret, *p; size_t buf_len = 0, i; unsigned char *buf = NULL, *pbuf; buf_len = EC_POINT_point2buf(group, point, form, &buf, ctx); if (buf_len == 0) return NULL; ret = OPENSSL_malloc(buf_len * 2 + 2); if (ret == NULL) { OPENSSL_free(buf); return NULL; } p = ret; pbuf = buf; for (i = buf_len; i > 0; i--) { int v = (int)*(pbuf++); *(p++) = HEX_DIGITS[v >> 4]; *(p++) = HEX_DIGITS[v & 0x0F]; } *p = '\0'; OPENSSL_free(buf); return ret; } EC_POINT *EC_POINT_hex2point(const EC_GROUP *group, const char *hex, EC_POINT *point, BN_CTX *ctx) { int ok = 0; unsigned char *oct_buf = NULL; size_t len, oct_buf_len = 0; EC_POINT *pt = NULL; if (group == NULL || hex == NULL) return NULL; if (point == NULL) { pt = EC_POINT_new(group); if (pt == NULL) goto err; } else { pt = point; } len = strlen(hex) / 2; oct_buf = OPENSSL_malloc(len); if (oct_buf == NULL) goto err; if (!OPENSSL_hexstr2buf_ex(oct_buf, len, &oct_buf_len, hex, '\0') || !EC_POINT_oct2point(group, pt, oct_buf, oct_buf_len, ctx)) goto err; ok = 1; err: OPENSSL_clear_free(oct_buf, oct_buf_len); if (!ok) { if (pt != point) EC_POINT_clear_free(pt); pt = NULL; } return pt; }
2,144
23.94186
75
c
openssl
openssl-master/crypto/ec/ecdh_kdf.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 */ /* * ECDH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <string.h> #include <openssl/core_names.h> #include <openssl/ec.h> #include <openssl/evp.h> #include <openssl/kdf.h> #include "ec_local.h" /* Key derivation function from X9.63/SECG */ int ossl_ecdh_kdf_X9_63(unsigned char *out, size_t outlen, const unsigned char *Z, size_t Zlen, const unsigned char *sinfo, size_t sinfolen, const EVP_MD *md, OSSL_LIB_CTX *libctx, const char *propq) { int ret = 0; EVP_KDF_CTX *kctx = NULL; OSSL_PARAM params[4], *p = params; const char *mdname = EVP_MD_get0_name(md); EVP_KDF *kdf = EVP_KDF_fetch(libctx, OSSL_KDF_NAME_X963KDF, propq); if ((kctx = EVP_KDF_CTX_new(kdf)) != NULL) { *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, (char *)mdname, 0); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY, (void *)Z, Zlen); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_INFO, (void *)sinfo, sinfolen); *p = OSSL_PARAM_construct_end(); ret = EVP_KDF_derive(kctx, out, outlen, params) > 0; EVP_KDF_CTX_free(kctx); } EVP_KDF_free(kdf); return ret; } /*- * The old name for ecdh_KDF_X9_63 * Retained for ABI compatibility */ #ifndef OPENSSL_NO_DEPRECATED_3_0 int ECDH_KDF_X9_62(unsigned char *out, size_t outlen, const unsigned char *Z, size_t Zlen, const unsigned char *sinfo, size_t sinfolen, const EVP_MD *md) { return ossl_ecdh_kdf_X9_63(out, outlen, Z, Zlen, sinfo, sinfolen, md, NULL, NULL); } #endif
2,268
33.378788
79
c
openssl
openssl-master/crypto/ec/ecdh_ossl.c
/* * Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 */ /* * ECDH low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <string.h> #include <limits.h> #include "internal/cryptlib.h" #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/objects.h> #include <openssl/ec.h> #include "ec_local.h" int ossl_ecdh_compute_key(unsigned char **psec, size_t *pseclen, const EC_POINT *pub_key, const EC_KEY *ecdh) { if (ecdh->group->meth->ecdh_compute_key == NULL) { ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_ECDH); return 0; } return ecdh->group->meth->ecdh_compute_key(psec, pseclen, pub_key, ecdh); } /*- * This implementation is based on the following primitives in the * IEEE 1363 standard: * - ECKAS-DH1 * - ECSVDP-DH * * It also conforms to SP800-56A r3 * See Section 5.7.1.2 "Elliptic Curve Cryptography Cofactor Diffie-Hellman * (ECC CDH) Primitive:". The steps listed below refer to SP800-56A. */ int ossl_ecdh_simple_compute_key(unsigned char **pout, size_t *poutlen, const EC_POINT *pub_key, const EC_KEY *ecdh) { BN_CTX *ctx; EC_POINT *tmp = NULL; BIGNUM *x = NULL; const BIGNUM *priv_key; const EC_GROUP *group; int ret = 0; size_t buflen, len; unsigned char *buf = NULL; if ((ctx = BN_CTX_new_ex(ecdh->libctx)) == NULL) goto err; BN_CTX_start(ctx); x = BN_CTX_get(ctx); if (x == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } priv_key = EC_KEY_get0_private_key(ecdh); if (priv_key == NULL) { ERR_raise(ERR_LIB_EC, EC_R_MISSING_PRIVATE_KEY); goto err; } group = EC_KEY_get0_group(ecdh); /* * Step(1) - Compute the point tmp = cofactor * owners_private_key * * peer_public_key. */ if (EC_KEY_get_flags(ecdh) & EC_FLAG_COFACTOR_ECDH) { if (!EC_GROUP_get_cofactor(group, x, NULL)) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } if (!BN_mul(x, x, priv_key, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } priv_key = x; } if ((tmp = EC_POINT_new(group)) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } if (!EC_POINT_mul(group, tmp, NULL, pub_key, priv_key, ctx)) { ERR_raise(ERR_LIB_EC, EC_R_POINT_ARITHMETIC_FAILURE); goto err; } /* * Step(2) : If point tmp is at infinity then clear intermediate values and * exit. Note: getting affine coordinates returns 0 if point is at infinity. * Step(3a) : Get x-coordinate of point x = tmp.x */ if (!EC_POINT_get_affine_coordinates(group, tmp, x, NULL, ctx)) { ERR_raise(ERR_LIB_EC, EC_R_POINT_ARITHMETIC_FAILURE); goto err; } /* * Step(3b) : convert x to a byte string, using the field-element-to-byte * string conversion routine defined in Appendix C.2 */ buflen = (EC_GROUP_get_degree(group) + 7) / 8; len = BN_num_bytes(x); if (len > buflen) { ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR); goto err; } if ((buf = OPENSSL_malloc(buflen)) == NULL) goto err; memset(buf, 0, buflen - len); if (len != (size_t)BN_bn2bin(x, buf + buflen - len)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } *pout = buf; *poutlen = buflen; buf = NULL; ret = 1; err: /* Step(4) : Destroy all intermediate calculations */ BN_clear(x); EC_POINT_clear_free(tmp); BN_CTX_end(ctx); BN_CTX_free(ctx); OPENSSL_free(buf); return ret; }
4,140
26.97973
80
c
openssl
openssl-master/crypto/ec/ecdsa_ossl.c
/* * Copyright 2002-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 */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <string.h> #include <openssl/err.h> #include <openssl/obj_mac.h> #include <openssl/rand.h> #include "crypto/bn.h" #include "ec_local.h" #include "internal/deterministic_nonce.h" #define MIN_ECDSA_SIGN_ORDERBITS 64 /* * It is highly unlikely that a retry will happen, * Multiple retries would indicate that something is wrong * with the group parameters (which would normally only happen * with a bad custom group). */ #define MAX_ECDSA_SIGN_RETRIES 8 static int ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp, const unsigned char *dgst, int dlen, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq); int ossl_ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { if (eckey->group->meth->ecdsa_sign_setup == NULL) { ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_ECDSA); return 0; } return eckey->group->meth->ecdsa_sign_setup(eckey, ctx_in, kinvp, rp); } ECDSA_SIG *ossl_ecdsa_sign_sig(const unsigned char *dgst, int dgst_len, const BIGNUM *in_kinv, const BIGNUM *in_r, EC_KEY *eckey) { if (eckey->group->meth->ecdsa_sign_sig == NULL) { ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_ECDSA); return NULL; } return eckey->group->meth->ecdsa_sign_sig(dgst, dgst_len, in_kinv, in_r, eckey); } int ossl_ecdsa_verify_sig(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey) { if (eckey->group->meth->ecdsa_verify_sig == NULL) { ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_ECDSA); return 0; } return eckey->group->meth->ecdsa_verify_sig(dgst, dgst_len, sig, eckey); } int ossl_ecdsa_sign(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey) { ECDSA_SIG *s; s = ECDSA_do_sign_ex(dgst, dlen, kinv, r, eckey); if (s == NULL) { *siglen = 0; return 0; } *siglen = i2d_ECDSA_SIG(s, sig != NULL ? &sig : NULL); ECDSA_SIG_free(s); return 1; } int ossl_ecdsa_deterministic_sign(const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, EC_KEY *eckey, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq) { ECDSA_SIG *s; BIGNUM *kinv = NULL, *r = NULL; int ret = 0; *siglen = 0; if (!ecdsa_sign_setup(eckey, NULL, &kinv, &r, dgst, dlen, nonce_type, digestname, libctx, propq)) return 0; s = ECDSA_do_sign_ex(dgst, dlen, kinv, r, eckey); if (s == NULL) goto end; *siglen = i2d_ECDSA_SIG(s, sig != NULL ? &sig : NULL); ECDSA_SIG_free(s); ret = 1; end: BN_clear_free(kinv); BN_clear_free(r); return ret; } static int ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp, const unsigned char *dgst, int dlen, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq) { BN_CTX *ctx = NULL; BIGNUM *k = NULL, *r = NULL, *X = NULL; const BIGNUM *order; EC_POINT *tmp_point = NULL; const EC_GROUP *group; int ret = 0; int order_bits; const BIGNUM *priv_key; if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((priv_key = EC_KEY_get0_private_key(eckey)) == NULL) { ERR_raise(ERR_LIB_EC, EC_R_MISSING_PRIVATE_KEY); return 0; } if (!EC_KEY_can_sign(eckey)) { ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING); return 0; } if ((ctx = ctx_in) == NULL) { if ((ctx = BN_CTX_new_ex(eckey->libctx)) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); return 0; } } k = BN_secure_new(); /* this value is later returned in *kinvp */ r = BN_new(); /* this value is later returned in *rp */ X = BN_new(); if (k == NULL || r == NULL || X == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } if ((tmp_point = EC_POINT_new(group)) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } order = EC_GROUP_get0_order(group); /* Preallocate space */ order_bits = BN_num_bits(order); /* Check the number of bits here so that an infinite loop is not possible */ if (order_bits < MIN_ECDSA_SIGN_ORDERBITS || !BN_set_bit(k, order_bits) || !BN_set_bit(r, order_bits) || !BN_set_bit(X, order_bits)) goto err; do { /* get random or deterministic value of k */ do { int res = 0; if (dgst != NULL) { if (nonce_type == 1) { #ifndef FIPS_MODULE res = ossl_gen_deterministic_nonce_rfc6979(k, order, priv_key, dgst, dlen, digestname, libctx, propq); #endif } else { res = BN_generate_dsa_nonce(k, order, priv_key, dgst, dlen, ctx); } } else { res = BN_priv_rand_range_ex(k, order, 0, ctx); } if (!res) { ERR_raise(ERR_LIB_EC, EC_R_RANDOM_NUMBER_GENERATION_FAILED); goto err; } } while (BN_is_zero(k)); /* compute r the x-coordinate of generator * k */ if (!EC_POINT_mul(group, tmp_point, k, NULL, NULL, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } if (!EC_POINT_get_affine_coordinates(group, tmp_point, X, NULL, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } if (!BN_nnmod(r, X, order, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } } while (BN_is_zero(r)); /* compute the inverse of k */ if (!ossl_ec_group_do_inverse_ord(group, k, k, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } /* clear old values if necessary */ BN_clear_free(*rp); BN_clear_free(*kinvp); /* save the pre-computed values */ *rp = r; *kinvp = k; ret = 1; err: if (!ret) { BN_clear_free(k); BN_clear_free(r); } if (ctx != ctx_in) BN_CTX_free(ctx); EC_POINT_free(tmp_point); BN_clear_free(X); return ret; } int ossl_ecdsa_simple_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { return ecdsa_sign_setup(eckey, ctx_in, kinvp, rp, NULL, 0, 0, NULL, NULL, NULL); } ECDSA_SIG *ossl_ecdsa_simple_sign_sig(const unsigned char *dgst, int dgst_len, const BIGNUM *in_kinv, const BIGNUM *in_r, EC_KEY *eckey) { int ok = 0, i; int retries = 0; BIGNUM *kinv = NULL, *s, *m = NULL; const BIGNUM *order, *ckinv; BN_CTX *ctx = NULL; const EC_GROUP *group; ECDSA_SIG *ret; const BIGNUM *priv_key; group = EC_KEY_get0_group(eckey); priv_key = EC_KEY_get0_private_key(eckey); if (group == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (priv_key == NULL) { ERR_raise(ERR_LIB_EC, EC_R_MISSING_PRIVATE_KEY); return NULL; } if (!EC_KEY_can_sign(eckey)) { ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING); return NULL; } ret = ECDSA_SIG_new(); if (ret == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_ECDSA_LIB); return NULL; } ret->r = BN_new(); ret->s = BN_new(); if (ret->r == NULL || ret->s == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } s = ret->s; if ((ctx = BN_CTX_new_ex(eckey->libctx)) == NULL || (m = BN_new()) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } order = EC_GROUP_get0_order(group); i = BN_num_bits(order); /* * Need to truncate digest if it is too long: first truncate whole bytes. */ if (8 * dgst_len > i) dgst_len = (i + 7) / 8; if (!BN_bin2bn(dgst, dgst_len, m)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } /* If still too long, truncate remaining bits with a shift */ if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } do { if (in_kinv == NULL || in_r == NULL) { if (!ecdsa_sign_setup(eckey, ctx, &kinv, &ret->r, dgst, dgst_len, 0, NULL, NULL, NULL)) { ERR_raise(ERR_LIB_EC, ERR_R_ECDSA_LIB); goto err; } ckinv = kinv; } else { ckinv = in_kinv; if (BN_copy(ret->r, in_r) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } } /* * With only one multiplicant being in Montgomery domain * multiplication yields real result without post-conversion. * Also note that all operations but last are performed with * zero-padded vectors. Last operation, BN_mod_mul_montgomery * below, returns user-visible value with removed zero padding. */ if (!bn_to_mont_fixed_top(s, ret->r, group->mont_data, ctx) || !bn_mul_mont_fixed_top(s, s, priv_key, group->mont_data, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } if (!bn_mod_add_fixed_top(s, s, m, order)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } /* * |s| can still be larger than modulus, because |m| can be. In * such case we count on Montgomery reduction to tie it up. */ if (!bn_to_mont_fixed_top(s, s, group->mont_data, ctx) || !BN_mod_mul_montgomery(s, s, ckinv, group->mont_data, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } if (BN_is_zero(s)) { /* * if kinv and r have been supplied by the caller, don't * generate new kinv and r values */ if (in_kinv != NULL && in_r != NULL) { ERR_raise(ERR_LIB_EC, EC_R_NEED_NEW_SETUP_VALUES); goto err; } /* Avoid infinite loops cause by invalid group parameters */ if (retries++ > MAX_ECDSA_SIGN_RETRIES) { ERR_raise(ERR_LIB_EC, EC_R_TOO_MANY_RETRIES); goto err; } } else { /* s != 0 => we have a valid signature */ break; } } while (1); ok = 1; err: if (!ok) { ECDSA_SIG_free(ret); ret = NULL; } BN_CTX_free(ctx); BN_clear_free(m); BN_clear_free(kinv); return ret; } /*- * returns * 1: correct signature * 0: incorrect signature * -1: error */ int ossl_ecdsa_verify(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int sig_len, EC_KEY *eckey) { ECDSA_SIG *s; const unsigned char *p = sigbuf; unsigned char *der = NULL; int derlen = -1; int ret = -1; s = ECDSA_SIG_new(); if (s == NULL) return ret; if (d2i_ECDSA_SIG(&s, &p, sig_len) == NULL) goto err; /* Ensure signature uses DER and doesn't have trailing garbage */ derlen = i2d_ECDSA_SIG(s, &der); if (derlen != sig_len || memcmp(sigbuf, der, derlen) != 0) goto err; ret = ECDSA_do_verify(dgst, dgst_len, s, eckey); err: OPENSSL_free(der); ECDSA_SIG_free(s); return ret; } int ossl_ecdsa_simple_verify_sig(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey) { int ret = -1, i; BN_CTX *ctx; const BIGNUM *order; BIGNUM *u1, *u2, *m, *X; EC_POINT *point = NULL; const EC_GROUP *group; const EC_POINT *pub_key; /* check input values */ if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL || (pub_key = EC_KEY_get0_public_key(eckey)) == NULL || sig == NULL) { ERR_raise(ERR_LIB_EC, EC_R_MISSING_PARAMETERS); return -1; } if (!EC_KEY_can_sign(eckey)) { ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING); return -1; } ctx = BN_CTX_new_ex(eckey->libctx); if (ctx == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); return -1; } BN_CTX_start(ctx); u1 = BN_CTX_get(ctx); u2 = BN_CTX_get(ctx); m = BN_CTX_get(ctx); X = BN_CTX_get(ctx); if (X == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } order = EC_GROUP_get0_order(group); if (order == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } if (BN_is_zero(sig->r) || BN_is_negative(sig->r) || BN_ucmp(sig->r, order) >= 0 || BN_is_zero(sig->s) || BN_is_negative(sig->s) || BN_ucmp(sig->s, order) >= 0) { ERR_raise(ERR_LIB_EC, EC_R_BAD_SIGNATURE); ret = 0; /* signature is invalid */ goto err; } /* calculate tmp1 = inv(S) mod order */ if (!ossl_ec_group_do_inverse_ord(group, u2, sig->s, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } /* digest -> m */ i = BN_num_bits(order); /* * Need to truncate digest if it is too long: first truncate whole bytes. */ if (8 * dgst_len > i) dgst_len = (i + 7) / 8; if (!BN_bin2bn(dgst, dgst_len, m)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } /* If still too long truncate remaining bits with a shift */ if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } /* u1 = m * tmp mod order */ if (!BN_mod_mul(u1, m, u2, order, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } /* u2 = r * w mod q */ if (!BN_mod_mul(u2, sig->r, u2, order, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } if ((point = EC_POINT_new(group)) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } if (!EC_POINT_mul(group, point, u1, pub_key, u2, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } if (!EC_POINT_get_affine_coordinates(group, point, X, NULL, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } if (!BN_nnmod(u1, X, order, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } /* if the signature is correct u1 is equal to sig->r */ ret = (BN_ucmp(u1, sig->r) == 0); err: BN_CTX_end(ctx); BN_CTX_free(ctx); EC_POINT_free(point); return ret; }
16,337
29.768362
80
c
openssl
openssl-master/crypto/ec/ecdsa_sign.c
/* * Copyright 2015-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 */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/ec.h> #include "ec_local.h" #include <openssl/err.h> ECDSA_SIG *ECDSA_do_sign(const unsigned char *dgst, int dlen, EC_KEY *eckey) { return ECDSA_do_sign_ex(dgst, dlen, NULL, NULL, eckey); } ECDSA_SIG *ECDSA_do_sign_ex(const unsigned char *dgst, int dlen, const BIGNUM *kinv, const BIGNUM *rp, EC_KEY *eckey) { if (eckey->meth->sign_sig != NULL) return eckey->meth->sign_sig(dgst, dlen, kinv, rp, eckey); ERR_raise(ERR_LIB_EC, EC_R_OPERATION_NOT_SUPPORTED); return NULL; } int ECDSA_sign(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, EC_KEY *eckey) { return ECDSA_sign_ex(type, dgst, dlen, sig, siglen, NULL, NULL, eckey); } int ECDSA_sign_ex(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey) { if (eckey->meth->sign != NULL) return eckey->meth->sign(type, dgst, dlen, sig, siglen, kinv, r, eckey); ERR_raise(ERR_LIB_EC, EC_R_OPERATION_NOT_SUPPORTED); return 0; } int ECDSA_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { if (eckey->meth->sign_setup != NULL) return eckey->meth->sign_setup(eckey, ctx_in, kinvp, rp); ERR_raise(ERR_LIB_EC, EC_R_OPERATION_NOT_SUPPORTED); return 0; }
1,926
31.661017
80
c
openssl
openssl-master/crypto/ec/ecdsa_vrf.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 */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/ec.h> #include "ec_local.h" #include <openssl/err.h> /*- * returns * 1: correct signature * 0: incorrect signature * -1: error */ int ECDSA_do_verify(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey) { if (eckey->meth->verify_sig != NULL) return eckey->meth->verify_sig(dgst, dgst_len, sig, eckey); ERR_raise(ERR_LIB_EC, EC_R_OPERATION_NOT_SUPPORTED); return -1; } /*- * returns * 1: correct signature * 0: incorrect signature * -1: error */ int ECDSA_verify(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int sig_len, EC_KEY *eckey) { if (eckey->meth->verify != NULL) return eckey->meth->verify(type, dgst, dgst_len, sigbuf, sig_len, eckey); ERR_raise(ERR_LIB_EC, EC_R_OPERATION_NOT_SUPPORTED); return -1; }
1,407
27.16
74
c
openssl
openssl-master/crypto/ec/eck_prn.c
/* * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/ec.h> #include <openssl/bn.h> #ifndef OPENSSL_NO_DEPRECATED_3_0 # ifndef OPENSSL_NO_STDIO int ECPKParameters_print_fp(FILE *fp, const EC_GROUP *x, int off) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = ECPKParameters_print(b, x, off); BIO_free(b); return ret; } int EC_KEY_print_fp(FILE *fp, const EC_KEY *x, int off) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BIO_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = EC_KEY_print(b, x, off); BIO_free(b); return ret; } int ECParameters_print_fp(FILE *fp, const EC_KEY *x) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BIO_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = ECParameters_print(b, x); BIO_free(b); return ret; } #endif /* OPENSSL_NO_STDIO */ static int print_bin(BIO *fp, const char *str, const unsigned char *num, size_t len, int off); int ECPKParameters_print(BIO *bp, const EC_GROUP *x, int off) { int ret = 0, reason = ERR_R_BIO_LIB; BN_CTX *ctx = NULL; const EC_POINT *point = NULL; BIGNUM *p = NULL, *a = NULL, *b = NULL; unsigned char *gen_buf = NULL; const BIGNUM *order = NULL, *cofactor = NULL; const unsigned char *seed; size_t seed_len = 0, gen_buf_len = 0; static const char *gen_compressed = "Generator (compressed):"; static const char *gen_uncompressed = "Generator (uncompressed):"; static const char *gen_hybrid = "Generator (hybrid):"; if (!x) { reason = ERR_R_PASSED_NULL_PARAMETER; goto err; } ctx = BN_CTX_new(); if (ctx == NULL) { reason = ERR_R_BN_LIB; goto err; } if (EC_GROUP_get_asn1_flag(x)) { /* the curve parameter are given by an asn1 OID */ int nid; const char *nname; if (!BIO_indent(bp, off, 128)) goto err; nid = EC_GROUP_get_curve_name(x); if (nid == 0) goto err; if (BIO_printf(bp, "ASN1 OID: %s", OBJ_nid2sn(nid)) <= 0) goto err; if (BIO_printf(bp, "\n") <= 0) goto err; nname = EC_curve_nid2nist(nid); if (nname) { if (!BIO_indent(bp, off, 128)) goto err; if (BIO_printf(bp, "NIST CURVE: %s\n", nname) <= 0) goto err; } } else { const char *form_str; /* explicit parameters */ int is_char_two = 0; point_conversion_form_t form; int tmp_nid = EC_GROUP_get_field_type(x); if (tmp_nid == NID_X9_62_characteristic_two_field) is_char_two = 1; if ((p = BN_new()) == NULL || (a = BN_new()) == NULL || (b = BN_new()) == NULL) { reason = ERR_R_BN_LIB; goto err; } if (!EC_GROUP_get_curve(x, p, a, b, ctx)) { reason = ERR_R_EC_LIB; goto err; } if ((point = EC_GROUP_get0_generator(x)) == NULL) { reason = ERR_R_EC_LIB; goto err; } order = EC_GROUP_get0_order(x); cofactor = EC_GROUP_get0_cofactor(x); if (order == NULL) { reason = ERR_R_EC_LIB; goto err; } form = EC_GROUP_get_point_conversion_form(x); gen_buf_len = EC_POINT_point2buf(x, point, form, &gen_buf, ctx); if (gen_buf_len == 0) { reason = ERR_R_EC_LIB; goto err; } if ((seed = EC_GROUP_get0_seed(x)) != NULL) seed_len = EC_GROUP_get_seed_len(x); if (!BIO_indent(bp, off, 128)) goto err; /* print the 'short name' of the field type */ if (BIO_printf(bp, "Field Type: %s\n", OBJ_nid2sn(tmp_nid)) <= 0) goto err; if (is_char_two) { /* print the 'short name' of the base type OID */ int basis_type = EC_GROUP_get_basis_type(x); if (basis_type == 0) goto err; if (!BIO_indent(bp, off, 128)) goto err; if (BIO_printf(bp, "Basis Type: %s\n", OBJ_nid2sn(basis_type)) <= 0) goto err; /* print the polynomial */ if ((p != NULL) && !ASN1_bn_print(bp, "Polynomial:", p, NULL, off)) goto err; } else { if ((p != NULL) && !ASN1_bn_print(bp, "Prime:", p, NULL, off)) goto err; } if ((a != NULL) && !ASN1_bn_print(bp, "A: ", a, NULL, off)) goto err; if ((b != NULL) && !ASN1_bn_print(bp, "B: ", b, NULL, off)) goto err; if (form == POINT_CONVERSION_COMPRESSED) form_str = gen_compressed; else if (form == POINT_CONVERSION_UNCOMPRESSED) form_str = gen_uncompressed; else form_str = gen_hybrid; if (gen_buf != NULL && !print_bin(bp, form_str, gen_buf, gen_buf_len, off)) goto err; if ((order != NULL) && !ASN1_bn_print(bp, "Order: ", order, NULL, off)) goto err; if ((cofactor != NULL) && !ASN1_bn_print(bp, "Cofactor: ", cofactor, NULL, off)) goto err; if (seed && !print_bin(bp, "Seed:", seed, seed_len, off)) goto err; } ret = 1; err: if (!ret) ERR_raise(ERR_LIB_EC, reason); BN_free(p); BN_free(a); BN_free(b); OPENSSL_clear_free(gen_buf, gen_buf_len); BN_CTX_free(ctx); return ret; } static int print_bin(BIO *fp, const char *name, const unsigned char *buf, size_t len, int off) { size_t i; char str[128 + 1 + 4]; if (buf == NULL) return 1; if (off > 0) { if (off > 128) off = 128; memset(str, ' ', off); if (BIO_write(fp, str, off) <= 0) return 0; } else { off = 0; } if (BIO_printf(fp, "%s", name) <= 0) return 0; for (i = 0; i < len; i++) { if ((i % 15) == 0) { str[0] = '\n'; memset(&(str[1]), ' ', off + 4); if (BIO_write(fp, str, off + 1 + 4) <= 0) return 0; } if (BIO_printf(fp, "%02x%s", buf[i], ((i + 1) == len) ? "" : ":") <= 0) return 0; } if (BIO_write(fp, "\n", 1) <= 0) return 0; return 1; } #endif /* OPENSSL_NO_DEPRECATED_3_0 */
7,315
26.81749
79
c
openssl
openssl-master/crypto/ec/ecp_mont.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 */ /* * ECDSA low-level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/err.h> #include "ec_local.h" const EC_METHOD *EC_GFp_mont_method(void) { static const EC_METHOD ret = { EC_FLAGS_DEFAULT_OCT, NID_X9_62_prime_field, ossl_ec_GFp_mont_group_init, ossl_ec_GFp_mont_group_finish, ossl_ec_GFp_mont_group_clear_finish, ossl_ec_GFp_mont_group_copy, ossl_ec_GFp_mont_group_set_curve, ossl_ec_GFp_simple_group_get_curve, ossl_ec_GFp_simple_group_get_degree, ossl_ec_group_simple_order_bits, ossl_ec_GFp_simple_group_check_discriminant, ossl_ec_GFp_simple_point_init, ossl_ec_GFp_simple_point_finish, ossl_ec_GFp_simple_point_clear_finish, ossl_ec_GFp_simple_point_copy, ossl_ec_GFp_simple_point_set_to_infinity, ossl_ec_GFp_simple_point_set_affine_coordinates, ossl_ec_GFp_simple_point_get_affine_coordinates, 0, 0, 0, ossl_ec_GFp_simple_add, ossl_ec_GFp_simple_dbl, ossl_ec_GFp_simple_invert, ossl_ec_GFp_simple_is_at_infinity, ossl_ec_GFp_simple_is_on_curve, ossl_ec_GFp_simple_cmp, ossl_ec_GFp_simple_make_affine, ossl_ec_GFp_simple_points_make_affine, 0 /* mul */ , 0 /* precompute_mult */ , 0 /* have_precompute_mult */ , ossl_ec_GFp_mont_field_mul, ossl_ec_GFp_mont_field_sqr, 0 /* field_div */ , ossl_ec_GFp_mont_field_inv, ossl_ec_GFp_mont_field_encode, ossl_ec_GFp_mont_field_decode, ossl_ec_GFp_mont_field_set_to_one, ossl_ec_key_simple_priv2oct, ossl_ec_key_simple_oct2priv, 0, /* set private */ ossl_ec_key_simple_generate_key, ossl_ec_key_simple_check_key, ossl_ec_key_simple_generate_public_key, 0, /* keycopy */ 0, /* keyfinish */ ossl_ecdh_simple_compute_key, ossl_ecdsa_simple_sign_setup, ossl_ecdsa_simple_sign_sig, ossl_ecdsa_simple_verify_sig, 0, /* field_inverse_mod_ord */ ossl_ec_GFp_simple_blind_coordinates, ossl_ec_GFp_simple_ladder_pre, ossl_ec_GFp_simple_ladder_step, ossl_ec_GFp_simple_ladder_post }; return &ret; } int ossl_ec_GFp_mont_group_init(EC_GROUP *group) { int ok; ok = ossl_ec_GFp_simple_group_init(group); group->field_data1 = NULL; group->field_data2 = NULL; return ok; } void ossl_ec_GFp_mont_group_finish(EC_GROUP *group) { BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; BN_free(group->field_data2); group->field_data2 = NULL; ossl_ec_GFp_simple_group_finish(group); } void ossl_ec_GFp_mont_group_clear_finish(EC_GROUP *group) { BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; BN_clear_free(group->field_data2); group->field_data2 = NULL; ossl_ec_GFp_simple_group_clear_finish(group); } int ossl_ec_GFp_mont_group_copy(EC_GROUP *dest, const EC_GROUP *src) { BN_MONT_CTX_free(dest->field_data1); dest->field_data1 = NULL; BN_clear_free(dest->field_data2); dest->field_data2 = NULL; if (!ossl_ec_GFp_simple_group_copy(dest, src)) return 0; if (src->field_data1 != NULL) { dest->field_data1 = BN_MONT_CTX_new(); if (dest->field_data1 == NULL) return 0; if (!BN_MONT_CTX_copy(dest->field_data1, src->field_data1)) goto err; } if (src->field_data2 != NULL) { dest->field_data2 = BN_dup(src->field_data2); if (dest->field_data2 == NULL) goto err; } return 1; err: BN_MONT_CTX_free(dest->field_data1); dest->field_data1 = NULL; return 0; } int ossl_ec_GFp_mont_group_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { BN_CTX *new_ctx = NULL; BN_MONT_CTX *mont = NULL; BIGNUM *one = NULL; int ret = 0; BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; BN_free(group->field_data2); group->field_data2 = NULL; if (ctx == NULL) { ctx = new_ctx = BN_CTX_new_ex(group->libctx); if (ctx == NULL) return 0; } mont = BN_MONT_CTX_new(); if (mont == NULL) goto err; if (!BN_MONT_CTX_set(mont, p, ctx)) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } one = BN_new(); if (one == NULL) goto err; if (!BN_to_montgomery(one, BN_value_one(), mont, ctx)) goto err; group->field_data1 = mont; mont = NULL; group->field_data2 = one; one = NULL; ret = ossl_ec_GFp_simple_group_set_curve(group, p, a, b, ctx); if (!ret) { BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; BN_free(group->field_data2); group->field_data2 = NULL; } err: BN_free(one); BN_CTX_free(new_ctx); BN_MONT_CTX_free(mont); return ret; } int ossl_ec_GFp_mont_field_mul(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { if (group->field_data1 == NULL) { ERR_raise(ERR_LIB_EC, EC_R_NOT_INITIALIZED); return 0; } return BN_mod_mul_montgomery(r, a, b, group->field_data1, ctx); } int ossl_ec_GFp_mont_field_sqr(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { if (group->field_data1 == NULL) { ERR_raise(ERR_LIB_EC, EC_R_NOT_INITIALIZED); return 0; } return BN_mod_mul_montgomery(r, a, a, group->field_data1, ctx); } /*- * Computes the multiplicative inverse of a in GF(p), storing the result in r. * If a is zero (or equivalent), you'll get an EC_R_CANNOT_INVERT error. * We have a Mont structure, so SCA hardening is FLT inversion. */ int ossl_ec_GFp_mont_field_inv(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { BIGNUM *e = NULL; BN_CTX *new_ctx = NULL; int ret = 0; if (group->field_data1 == NULL) return 0; if (ctx == NULL && (ctx = new_ctx = BN_CTX_secure_new_ex(group->libctx)) == NULL) return 0; BN_CTX_start(ctx); if ((e = BN_CTX_get(ctx)) == NULL) goto err; /* Inverse in constant time with Fermats Little Theorem */ if (!BN_set_word(e, 2)) goto err; if (!BN_sub(e, group->field, e)) goto err; /*- * Exponent e is public. * No need for scatter-gather or BN_FLG_CONSTTIME. */ if (!BN_mod_exp_mont(r, a, e, group->field, ctx, group->field_data1)) goto err; /* throw an error on zero */ if (BN_is_zero(r)) { ERR_raise(ERR_LIB_EC, EC_R_CANNOT_INVERT); goto err; } ret = 1; err: BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; } int ossl_ec_GFp_mont_field_encode(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { if (group->field_data1 == NULL) { ERR_raise(ERR_LIB_EC, EC_R_NOT_INITIALIZED); return 0; } return BN_to_montgomery(r, a, (BN_MONT_CTX *)group->field_data1, ctx); } int ossl_ec_GFp_mont_field_decode(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { if (group->field_data1 == NULL) { ERR_raise(ERR_LIB_EC, EC_R_NOT_INITIALIZED); return 0; } return BN_from_montgomery(r, a, group->field_data1, ctx); } int ossl_ec_GFp_mont_field_set_to_one(const EC_GROUP *group, BIGNUM *r, BN_CTX *ctx) { if (group->field_data2 == NULL) { ERR_raise(ERR_LIB_EC, EC_R_NOT_INITIALIZED); return 0; } if (!BN_copy(r, group->field_data2)) return 0; return 1; }
8,422
26.983389
81
c
openssl
openssl-master/crypto/ec/ecp_nist.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <limits.h> #include <openssl/err.h> #include <openssl/obj_mac.h> #include "ec_local.h" const EC_METHOD *EC_GFp_nist_method(void) { static const EC_METHOD ret = { EC_FLAGS_DEFAULT_OCT, NID_X9_62_prime_field, ossl_ec_GFp_simple_group_init, ossl_ec_GFp_simple_group_finish, ossl_ec_GFp_simple_group_clear_finish, ossl_ec_GFp_nist_group_copy, ossl_ec_GFp_nist_group_set_curve, ossl_ec_GFp_simple_group_get_curve, ossl_ec_GFp_simple_group_get_degree, ossl_ec_group_simple_order_bits, ossl_ec_GFp_simple_group_check_discriminant, ossl_ec_GFp_simple_point_init, ossl_ec_GFp_simple_point_finish, ossl_ec_GFp_simple_point_clear_finish, ossl_ec_GFp_simple_point_copy, ossl_ec_GFp_simple_point_set_to_infinity, ossl_ec_GFp_simple_point_set_affine_coordinates, ossl_ec_GFp_simple_point_get_affine_coordinates, 0, 0, 0, ossl_ec_GFp_simple_add, ossl_ec_GFp_simple_dbl, ossl_ec_GFp_simple_invert, ossl_ec_GFp_simple_is_at_infinity, ossl_ec_GFp_simple_is_on_curve, ossl_ec_GFp_simple_cmp, ossl_ec_GFp_simple_make_affine, ossl_ec_GFp_simple_points_make_affine, 0 /* mul */ , 0 /* precompute_mult */ , 0 /* have_precompute_mult */ , ossl_ec_GFp_nist_field_mul, ossl_ec_GFp_nist_field_sqr, 0 /* field_div */ , ossl_ec_GFp_simple_field_inv, 0 /* field_encode */ , 0 /* field_decode */ , 0, /* field_set_to_one */ ossl_ec_key_simple_priv2oct, ossl_ec_key_simple_oct2priv, 0, /* set private */ ossl_ec_key_simple_generate_key, ossl_ec_key_simple_check_key, ossl_ec_key_simple_generate_public_key, 0, /* keycopy */ 0, /* keyfinish */ ossl_ecdh_simple_compute_key, ossl_ecdsa_simple_sign_setup, ossl_ecdsa_simple_sign_sig, ossl_ecdsa_simple_verify_sig, 0, /* field_inverse_mod_ord */ ossl_ec_GFp_simple_blind_coordinates, ossl_ec_GFp_simple_ladder_pre, ossl_ec_GFp_simple_ladder_step, ossl_ec_GFp_simple_ladder_post }; return &ret; } int ossl_ec_GFp_nist_group_copy(EC_GROUP *dest, const EC_GROUP *src) { dest->field_mod_func = src->field_mod_func; return ossl_ec_GFp_simple_group_copy(dest, src); } int ossl_ec_GFp_nist_group_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; BN_CTX *new_ctx = NULL; if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new_ex(group->libctx)) == NULL) return 0; BN_CTX_start(ctx); if (BN_ucmp(BN_get0_nist_prime_192(), p) == 0) group->field_mod_func = BN_nist_mod_192; else if (BN_ucmp(BN_get0_nist_prime_224(), p) == 0) group->field_mod_func = BN_nist_mod_224; else if (BN_ucmp(BN_get0_nist_prime_256(), p) == 0) group->field_mod_func = BN_nist_mod_256; else if (BN_ucmp(BN_get0_nist_prime_384(), p) == 0) group->field_mod_func = BN_nist_mod_384; else if (BN_ucmp(BN_get0_nist_prime_521(), p) == 0) group->field_mod_func = BN_nist_mod_521; else { ERR_raise(ERR_LIB_EC, EC_R_NOT_A_NIST_PRIME); goto err; } ret = ossl_ec_GFp_simple_group_set_curve(group, p, a, b, ctx); err: BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; } int ossl_ec_GFp_nist_field_mul(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; BN_CTX *ctx_new = NULL; if (!group || !r || !a || !b) { ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER); goto err; } if (!ctx) if ((ctx_new = ctx = BN_CTX_new_ex(group->libctx)) == NULL) goto err; if (!BN_mul(r, a, b, ctx)) goto err; if (!group->field_mod_func(r, r, group->field, ctx)) goto err; ret = 1; err: BN_CTX_free(ctx_new); return ret; } int ossl_ec_GFp_nist_field_sqr(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { int ret = 0; BN_CTX *ctx_new = NULL; if (!group || !r || !a) { ERR_raise(ERR_LIB_EC, EC_R_PASSED_NULL_PARAMETER); goto err; } if (!ctx) if ((ctx_new = ctx = BN_CTX_new_ex(group->libctx)) == NULL) goto err; if (!BN_sqr(r, a, ctx)) goto err; if (!group->field_mod_func(r, r, group->field, ctx)) goto err; ret = 1; err: BN_CTX_free(ctx_new); return ret; }
5,312
29.016949
81
c
openssl
openssl-master/crypto/ec/ecp_nistputil.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 */ /* Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/opensslconf.h> /* * Common utility functions for ecp_nistp224.c, ecp_nistp256.c, ecp_nistp521.c. */ #include <stddef.h> #include "ec_local.h" /* * Convert an array of points into affine coordinates. (If the point at * infinity is found (Z = 0), it remains unchanged.) This function is * essentially an equivalent to EC_POINTs_make_affine(), but works with the * internal representation of points as used by ecp_nistp###.c rather than * with (BIGNUM-based) EC_POINT data structures. point_array is the * input/output buffer ('num' points in projective form, i.e. three * coordinates each), based on an internal representation of field elements * of size 'felem_size'. tmp_felems needs to point to a temporary array of * 'num'+1 field elements for storage of intermediate values. */ void ossl_ec_GFp_nistp_points_make_affine_internal(size_t num, void *point_array, size_t felem_size, void *tmp_felems, void (*felem_one) (void *out), int (*felem_is_zero) (const void *in), void (*felem_assign) (void *out, const void *in), void (*felem_square) (void *out, const void *in), void (*felem_mul) (void *out, const void *in1, const void *in2), void (*felem_inv) (void *out, const void *in), void (*felem_contract) (void *out, const void *in)) { int i = 0; #define tmp_felem(I) (&((char *)tmp_felems)[(I) * felem_size]) #define X(I) (&((char *)point_array)[3*(I) * felem_size]) #define Y(I) (&((char *)point_array)[(3*(I) + 1) * felem_size]) #define Z(I) (&((char *)point_array)[(3*(I) + 2) * felem_size]) if (!felem_is_zero(Z(0))) felem_assign(tmp_felem(0), Z(0)); else felem_one(tmp_felem(0)); for (i = 1; i < (int)num; i++) { if (!felem_is_zero(Z(i))) felem_mul(tmp_felem(i), tmp_felem(i - 1), Z(i)); else felem_assign(tmp_felem(i), tmp_felem(i - 1)); } /* * Now each tmp_felem(i) is the product of Z(0) .. Z(i), skipping any * zero-valued factors: if Z(i) = 0, we essentially pretend that Z(i) = 1 */ felem_inv(tmp_felem(num - 1), tmp_felem(num - 1)); for (i = num - 1; i >= 0; i--) { if (i > 0) /* * tmp_felem(i-1) is the product of Z(0) .. Z(i-1), tmp_felem(i) * is the inverse of the product of Z(0) .. Z(i) */ /* 1/Z(i) */ felem_mul(tmp_felem(num), tmp_felem(i - 1), tmp_felem(i)); else felem_assign(tmp_felem(num), tmp_felem(0)); /* 1/Z(0) */ if (!felem_is_zero(Z(i))) { if (i > 0) /* * For next iteration, replace tmp_felem(i-1) by its inverse */ felem_mul(tmp_felem(i - 1), tmp_felem(i), Z(i)); /* * Convert point (X, Y, Z) into affine form (X/(Z^2), Y/(Z^3), 1) */ felem_square(Z(i), tmp_felem(num)); /* 1/(Z^2) */ felem_mul(X(i), X(i), Z(i)); /* X/(Z^2) */ felem_mul(Z(i), Z(i), tmp_felem(num)); /* 1/(Z^3) */ felem_mul(Y(i), Y(i), Z(i)); /* Y/(Z^3) */ felem_contract(X(i), X(i)); felem_contract(Y(i), Y(i)); felem_one(Z(i)); } else { if (i > 0) /* * For next iteration, replace tmp_felem(i-1) by its inverse */ felem_assign(tmp_felem(i - 1), tmp_felem(i)); } } } /*- * This function looks at 5+1 scalar bits (5 current, 1 adjacent less * significant bit), and recodes them into a signed digit for use in fast point * multiplication: the use of signed rather than unsigned digits means that * fewer points need to be precomputed, given that point inversion is easy * (a precomputed point dP makes -dP available as well). * * BACKGROUND: * * Signed digits for multiplication were introduced by Booth ("A signed binary * multiplication technique", Quart. Journ. Mech. and Applied Math., vol. IV, * pt. 2 (1951), pp. 236-240), in that case for multiplication of integers. * Booth's original encoding did not generally improve the density of nonzero * digits over the binary representation, and was merely meant to simplify the * handling of signed factors given in two's complement; but it has since been * shown to be the basis of various signed-digit representations that do have * further advantages, including the wNAF, using the following general approach: * * (1) Given a binary representation * * b_k ... b_2 b_1 b_0, * * of a nonnegative integer (b_k in {0, 1}), rewrite it in digits 0, 1, -1 * by using bit-wise subtraction as follows: * * b_k b_(k-1) ... b_2 b_1 b_0 * - b_k ... b_3 b_2 b_1 b_0 * ----------------------------------------- * s_(k+1) s_k ... s_3 s_2 s_1 s_0 * * A left-shift followed by subtraction of the original value yields a new * representation of the same value, using signed bits s_i = b_(i-1) - b_i. * This representation from Booth's paper has since appeared in the * literature under a variety of different names including "reversed binary * form", "alternating greedy expansion", "mutual opposite form", and * "sign-alternating {+-1}-representation". * * An interesting property is that among the nonzero bits, values 1 and -1 * strictly alternate. * * (2) Various window schemes can be applied to the Booth representation of * integers: for example, right-to-left sliding windows yield the wNAF * (a signed-digit encoding independently discovered by various researchers * in the 1990s), and left-to-right sliding windows yield a left-to-right * equivalent of the wNAF (independently discovered by various researchers * around 2004). * * To prevent leaking information through side channels in point multiplication, * we need to recode the given integer into a regular pattern: sliding windows * as in wNAFs won't do, we need their fixed-window equivalent -- which is a few * decades older: we'll be using the so-called "modified Booth encoding" due to * MacSorley ("High-speed arithmetic in binary computers", Proc. IRE, vol. 49 * (1961), pp. 67-91), in a radix-2^5 setting. That is, we always combine five * signed bits into a signed digit: * * s_(5j + 4) s_(5j + 3) s_(5j + 2) s_(5j + 1) s_(5j) * * The sign-alternating property implies that the resulting digit values are * integers from -16 to 16. * * Of course, we don't actually need to compute the signed digits s_i as an * intermediate step (that's just a nice way to see how this scheme relates * to the wNAF): a direct computation obtains the recoded digit from the * six bits b_(5j + 4) ... b_(5j - 1). * * This function takes those six bits as an integer (0 .. 63), writing the * recoded digit to *sign (0 for positive, 1 for negative) and *digit (absolute * value, in the range 0 .. 16). Note that this integer essentially provides * the input bits "shifted to the left" by one position: for example, the input * to compute the least significant recoded digit, given that there's no bit * b_-1, has to be b_4 b_3 b_2 b_1 b_0 0. * */ void ossl_ec_GFp_nistp_recode_scalar_bits(unsigned char *sign, unsigned char *digit, unsigned char in) { unsigned char s, d; s = ~((in >> 5) - 1); /* sets all bits to MSB(in), 'in' seen as * 6-bit value */ d = (1 << 6) - in - 1; d = (d & s) | (in & ~s); d = (d >> 1) + (d & 1); *sign = s & 1; *digit = d; }
10,104
43.515419
81
c
openssl
openssl-master/crypto/ec/ecp_oct.c
/* * Copyright 2011-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/err.h> #include <openssl/symhacks.h> #include "ec_local.h" int ossl_ec_GFp_simple_set_compressed_coordinates(const EC_GROUP *group, EC_POINT *point, const BIGNUM *x_, int y_bit, BN_CTX *ctx) { BN_CTX *new_ctx = NULL; BIGNUM *tmp1, *tmp2, *x, *y; int ret = 0; if (ctx == NULL) { ctx = new_ctx = BN_CTX_new_ex(group->libctx); if (ctx == NULL) return 0; } y_bit = (y_bit != 0); BN_CTX_start(ctx); tmp1 = BN_CTX_get(ctx); tmp2 = BN_CTX_get(ctx); x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); if (y == NULL) goto err; /*- * Recover y. We have a Weierstrass equation * y^2 = x^3 + a*x + b, * so y is one of the square roots of x^3 + a*x + b. */ /* tmp1 := x^3 */ if (!BN_nnmod(x, x_, group->field, ctx)) goto err; if (group->meth->field_decode == 0) { /* field_{sqr,mul} work on standard representation */ if (!group->meth->field_sqr(group, tmp2, x_, ctx)) goto err; if (!group->meth->field_mul(group, tmp1, tmp2, x_, ctx)) goto err; } else { if (!BN_mod_sqr(tmp2, x_, group->field, ctx)) goto err; if (!BN_mod_mul(tmp1, tmp2, x_, group->field, ctx)) goto err; } /* tmp1 := tmp1 + a*x */ if (group->a_is_minus3) { if (!BN_mod_lshift1_quick(tmp2, x, group->field)) goto err; if (!BN_mod_add_quick(tmp2, tmp2, x, group->field)) goto err; if (!BN_mod_sub_quick(tmp1, tmp1, tmp2, group->field)) goto err; } else { if (group->meth->field_decode) { if (!group->meth->field_decode(group, tmp2, group->a, ctx)) goto err; if (!BN_mod_mul(tmp2, tmp2, x, group->field, ctx)) goto err; } else { /* field_mul works on standard representation */ if (!group->meth->field_mul(group, tmp2, group->a, x, ctx)) goto err; } if (!BN_mod_add_quick(tmp1, tmp1, tmp2, group->field)) goto err; } /* tmp1 := tmp1 + b */ if (group->meth->field_decode) { if (!group->meth->field_decode(group, tmp2, group->b, ctx)) goto err; if (!BN_mod_add_quick(tmp1, tmp1, tmp2, group->field)) goto err; } else { if (!BN_mod_add_quick(tmp1, tmp1, group->b, group->field)) goto err; } ERR_set_mark(); if (!BN_mod_sqrt(y, tmp1, group->field, ctx)) { #ifndef FIPS_MODULE unsigned long err = ERR_peek_last_error(); if (ERR_GET_LIB(err) == ERR_LIB_BN && ERR_GET_REASON(err) == BN_R_NOT_A_SQUARE) { ERR_pop_to_mark(); ERR_raise(ERR_LIB_EC, EC_R_INVALID_COMPRESSED_POINT); } else #endif { ERR_clear_last_mark(); ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); } goto err; } ERR_clear_last_mark(); if (y_bit != BN_is_odd(y)) { if (BN_is_zero(y)) { int kron; kron = BN_kronecker(x, group->field, ctx); if (kron == -2) goto err; if (kron == 1) ERR_raise(ERR_LIB_EC, EC_R_INVALID_COMPRESSION_BIT); else /* * BN_mod_sqrt() should have caught this error (not a square) */ ERR_raise(ERR_LIB_EC, EC_R_INVALID_COMPRESSED_POINT); goto err; } if (!BN_usub(y, group->field, y)) goto err; } if (y_bit != BN_is_odd(y)) { ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR); goto err; } if (!EC_POINT_set_affine_coordinates(group, point, x, y, ctx)) goto err; ret = 1; err: BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; } size_t ossl_ec_GFp_simple_point2oct(const EC_GROUP *group, const EC_POINT *point, point_conversion_form_t form, unsigned char *buf, size_t len, BN_CTX *ctx) { size_t ret; BN_CTX *new_ctx = NULL; int used_ctx = 0; BIGNUM *x, *y; size_t field_len, i, skip; if ((form != POINT_CONVERSION_COMPRESSED) && (form != POINT_CONVERSION_UNCOMPRESSED) && (form != POINT_CONVERSION_HYBRID)) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_FORM); goto err; } if (EC_POINT_is_at_infinity(group, point)) { /* encodes to a single 0 octet */ if (buf != NULL) { if (len < 1) { ERR_raise(ERR_LIB_EC, EC_R_BUFFER_TOO_SMALL); return 0; } buf[0] = 0; } return 1; } /* ret := required output buffer length */ field_len = BN_num_bytes(group->field); ret = (form == POINT_CONVERSION_COMPRESSED) ? 1 + field_len : 1 + 2 * field_len; /* if 'buf' is NULL, just return required length */ if (buf != NULL) { if (len < ret) { ERR_raise(ERR_LIB_EC, EC_R_BUFFER_TOO_SMALL); goto err; } if (ctx == NULL) { ctx = new_ctx = BN_CTX_new_ex(group->libctx); if (ctx == NULL) return 0; } BN_CTX_start(ctx); used_ctx = 1; x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); if (y == NULL) goto err; if (!EC_POINT_get_affine_coordinates(group, point, x, y, ctx)) goto err; if ((form == POINT_CONVERSION_COMPRESSED || form == POINT_CONVERSION_HYBRID) && BN_is_odd(y)) buf[0] = form + 1; else buf[0] = form; i = 1; skip = field_len - BN_num_bytes(x); if (skip > field_len) { ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR); goto err; } while (skip > 0) { buf[i++] = 0; skip--; } skip = BN_bn2bin(x, buf + i); i += skip; if (i != 1 + field_len) { ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR); goto err; } if (form == POINT_CONVERSION_UNCOMPRESSED || form == POINT_CONVERSION_HYBRID) { skip = field_len - BN_num_bytes(y); if (skip > field_len) { ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR); goto err; } while (skip > 0) { buf[i++] = 0; skip--; } skip = BN_bn2bin(y, buf + i); i += skip; } if (i != ret) { ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR); goto err; } } if (used_ctx) BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; err: if (used_ctx) BN_CTX_end(ctx); BN_CTX_free(new_ctx); return 0; } int ossl_ec_GFp_simple_oct2point(const EC_GROUP *group, EC_POINT *point, const unsigned char *buf, size_t len, BN_CTX *ctx) { point_conversion_form_t form; int y_bit; BN_CTX *new_ctx = NULL; BIGNUM *x, *y; size_t field_len, enc_len; int ret = 0; if (len == 0) { ERR_raise(ERR_LIB_EC, EC_R_BUFFER_TOO_SMALL); return 0; } form = buf[0]; y_bit = form & 1; form = form & ~1U; if ((form != 0) && (form != POINT_CONVERSION_COMPRESSED) && (form != POINT_CONVERSION_UNCOMPRESSED) && (form != POINT_CONVERSION_HYBRID)) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); return 0; } if ((form == 0 || form == POINT_CONVERSION_UNCOMPRESSED) && y_bit) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); return 0; } if (form == 0) { if (len != 1) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); return 0; } return EC_POINT_set_to_infinity(group, point); } field_len = BN_num_bytes(group->field); enc_len = (form == POINT_CONVERSION_COMPRESSED) ? 1 + field_len : 1 + 2 * field_len; if (len != enc_len) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); return 0; } if (ctx == NULL) { ctx = new_ctx = BN_CTX_new_ex(group->libctx); if (ctx == NULL) return 0; } BN_CTX_start(ctx); x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); if (y == NULL) goto err; if (!BN_bin2bn(buf + 1, field_len, x)) goto err; if (BN_ucmp(x, group->field) >= 0) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); goto err; } if (form == POINT_CONVERSION_COMPRESSED) { if (!EC_POINT_set_compressed_coordinates(group, point, x, y_bit, ctx)) goto err; } else { if (!BN_bin2bn(buf + 1 + field_len, field_len, y)) goto err; if (BN_ucmp(y, group->field) >= 0) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); goto err; } if (form == POINT_CONVERSION_HYBRID) { if (y_bit != BN_is_odd(y)) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); goto err; } } /* * EC_POINT_set_affine_coordinates is responsible for checking that * the point is on the curve. */ if (!EC_POINT_set_affine_coordinates(group, point, x, y, ctx)) goto err; } ret = 1; err: BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; }
10,293
26.597855
81
c
openssl
openssl-master/crypto/ec/ecp_ppc.c
/* * Copyright 2009-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/cryptlib.h" #include "crypto/ppc_arch.h" #include "ec_local.h" void ecp_nistz256_mul_mont(unsigned long res[4], const unsigned long a[4], const unsigned long b[4]); void ecp_nistz256_to_mont(unsigned long res[4], const unsigned long in[4]); void ecp_nistz256_to_mont(unsigned long res[4], const unsigned long in[4]) { static const unsigned long RR[] = { 0x0000000000000003U, 0xfffffffbffffffffU, 0xfffffffffffffffeU, 0x00000004fffffffdU }; ecp_nistz256_mul_mont(res, in, RR); } void ecp_nistz256_from_mont(unsigned long res[4], const unsigned long in[4]); void ecp_nistz256_from_mont(unsigned long res[4], const unsigned long in[4]) { static const unsigned long one[] = { 1, 0, 0, 0 }; ecp_nistz256_mul_mont(res, in, one); }
1,249
34.714286
77
c
openssl
openssl-master/crypto/ec/ecp_s390x_nistp.c
/* * Copyright 2019-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 */ /* * EC_METHOD low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdlib.h> #include <string.h> #include <openssl/err.h> #include <openssl/rand.h> #include "ec_local.h" #include "s390x_arch.h" /* Size of parameter blocks */ #define S390X_SIZE_PARAM 4096 /* Size of fields in parameter blocks */ #define S390X_SIZE_P256 32 #define S390X_SIZE_P384 48 #define S390X_SIZE_P521 80 /* Offsets of fields in PCC parameter blocks */ #define S390X_OFF_RES_X(n) (0 * n) #define S390X_OFF_RES_Y(n) (1 * n) #define S390X_OFF_SRC_X(n) (2 * n) #define S390X_OFF_SRC_Y(n) (3 * n) #define S390X_OFF_SCALAR(n) (4 * n) /* Offsets of fields in KDSA parameter blocks */ #define S390X_OFF_R(n) (0 * n) #define S390X_OFF_S(n) (1 * n) #define S390X_OFF_H(n) (2 * n) #define S390X_OFF_K(n) (3 * n) #define S390X_OFF_X(n) (3 * n) #define S390X_OFF_RN(n) (4 * n) #define S390X_OFF_Y(n) (4 * n) static int ec_GFp_s390x_nistp_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx, unsigned int fc, int len) { unsigned char param[S390X_SIZE_PARAM]; BIGNUM *x, *y; const EC_POINT *point_ptr = NULL; const BIGNUM *scalar_ptr = NULL; BN_CTX *new_ctx = NULL; int rc = -1; if (ctx == NULL) { ctx = new_ctx = BN_CTX_new_ex(group->libctx); if (ctx == NULL) return 0; } BN_CTX_start(ctx); x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); if (x == NULL || y == NULL) { rc = 0; goto ret; } /* * Use PCC for EC keygen and ECDH key derivation: * scalar * generator and scalar * peer public key, * scalar in [0,order). */ if ((scalar != NULL && num == 0 && BN_is_negative(scalar) == 0) || (scalar == NULL && num == 1 && BN_is_negative(scalars[0]) == 0)) { if (num == 0) { point_ptr = EC_GROUP_get0_generator(group); scalar_ptr = scalar; } else { point_ptr = points[0]; scalar_ptr = scalars[0]; } if (EC_POINT_is_at_infinity(group, point_ptr) == 1 || BN_is_zero(scalar_ptr)) { rc = EC_POINT_set_to_infinity(group, r); goto ret; } memset(&param, 0, sizeof(param)); if (group->meth->point_get_affine_coordinates(group, point_ptr, x, y, ctx) != 1 || BN_bn2binpad(x, param + S390X_OFF_SRC_X(len), len) == -1 || BN_bn2binpad(y, param + S390X_OFF_SRC_Y(len), len) == -1 || BN_bn2binpad(scalar_ptr, param + S390X_OFF_SCALAR(len), len) == -1 || s390x_pcc(fc, param) != 0 || BN_bin2bn(param + S390X_OFF_RES_X(len), len, x) == NULL || BN_bin2bn(param + S390X_OFF_RES_Y(len), len, y) == NULL || group->meth->point_set_affine_coordinates(group, r, x, y, ctx) != 1) goto ret; rc = 1; } ret: /* Otherwise use default. */ if (rc == -1) rc = ossl_ec_wNAF_mul(group, r, scalar, num, points, scalars, ctx); OPENSSL_cleanse(param, sizeof(param)); BN_CTX_end(ctx); BN_CTX_free(new_ctx); return rc; } static ECDSA_SIG *ecdsa_s390x_nistp_sign_sig(const unsigned char *dgst, int dgstlen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey, unsigned int fc, int len) { unsigned char param[S390X_SIZE_PARAM]; int ok = 0; BIGNUM *k; ECDSA_SIG *sig; const EC_GROUP *group; const BIGNUM *privkey; int off; group = EC_KEY_get0_group(eckey); privkey = EC_KEY_get0_private_key(eckey); if (group == NULL || privkey == NULL) { ERR_raise(ERR_LIB_EC, EC_R_MISSING_PARAMETERS); return NULL; } if (!EC_KEY_can_sign(eckey)) { ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING); return NULL; } k = BN_secure_new(); sig = ECDSA_SIG_new(); if (k == NULL || sig == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_ECDSA_LIB); goto ret; } sig->r = BN_new(); sig->s = BN_new(); if (sig->r == NULL || sig->s == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto ret; } memset(param, 0, sizeof(param)); off = len - (dgstlen > len ? len : dgstlen); memcpy(param + S390X_OFF_H(len) + off, dgst, len - off); if (BN_bn2binpad(privkey, param + S390X_OFF_K(len), len) == -1) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto ret; } if (r == NULL || kinv == NULL) { if (len < 0) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_LENGTH); goto ret; } /* * Generate random k and copy to param param block. RAND_priv_bytes_ex * is used instead of BN_priv_rand_range or BN_generate_dsa_nonce * because kdsa instruction constructs an in-range, invertible nonce * internally implementing counter-measures for RNG weakness. */ if (RAND_priv_bytes_ex(eckey->libctx, param + S390X_OFF_RN(len), (size_t)len, 0) != 1) { ERR_raise(ERR_LIB_EC, EC_R_RANDOM_NUMBER_GENERATION_FAILED); goto ret; } } else { /* Reconstruct k = (k^-1)^-1. */ if (ossl_ec_group_do_inverse_ord(group, k, kinv, NULL) == 0 || BN_bn2binpad(k, param + S390X_OFF_RN(len), len) == -1) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto ret; } /* Turns KDSA internal nonce-generation off. */ fc |= S390X_KDSA_D; } if (s390x_kdsa(fc, param, NULL, 0) != 0) { ERR_raise(ERR_LIB_EC, ERR_R_ECDSA_LIB); goto ret; } if (BN_bin2bn(param + S390X_OFF_R(len), len, sig->r) == NULL || BN_bin2bn(param + S390X_OFF_S(len), len, sig->s) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto ret; } ok = 1; ret: OPENSSL_cleanse(param, sizeof(param)); if (ok != 1) { ECDSA_SIG_free(sig); sig = NULL; } BN_clear_free(k); return sig; } static int ecdsa_s390x_nistp_verify_sig(const unsigned char *dgst, int dgstlen, const ECDSA_SIG *sig, EC_KEY *eckey, unsigned int fc, int len) { unsigned char param[S390X_SIZE_PARAM]; int rc = -1; BN_CTX *ctx; BIGNUM *x, *y; const EC_GROUP *group; const EC_POINT *pubkey; int off; group = EC_KEY_get0_group(eckey); pubkey = EC_KEY_get0_public_key(eckey); if (eckey == NULL || group == NULL || pubkey == NULL || sig == NULL) { ERR_raise(ERR_LIB_EC, EC_R_MISSING_PARAMETERS); return -1; } if (!EC_KEY_can_sign(eckey)) { ERR_raise(ERR_LIB_EC, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING); return -1; } ctx = BN_CTX_new_ex(group->libctx); if (ctx == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); return -1; } BN_CTX_start(ctx); x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); if (x == NULL || y == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto ret; } memset(param, 0, sizeof(param)); off = len - (dgstlen > len ? len : dgstlen); memcpy(param + S390X_OFF_H(len) + off, dgst, len - off); if (group->meth->point_get_affine_coordinates(group, pubkey, x, y, ctx) != 1 || BN_bn2binpad(sig->r, param + S390X_OFF_R(len), len) == -1 || BN_bn2binpad(sig->s, param + S390X_OFF_S(len), len) == -1 || BN_bn2binpad(x, param + S390X_OFF_X(len), len) == -1 || BN_bn2binpad(y, param + S390X_OFF_Y(len), len) == -1) { ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB); goto ret; } rc = s390x_kdsa(fc, param, NULL, 0) == 0 ? 1 : 0; ret: BN_CTX_end(ctx); BN_CTX_free(ctx); return rc; } #define EC_GFP_S390X_NISTP_METHOD(bits) \ \ static int ec_GFp_s390x_nistp##bits##_mul(const EC_GROUP *group, \ EC_POINT *r, \ const BIGNUM *scalar, \ size_t num, \ const EC_POINT *points[], \ const BIGNUM *scalars[], \ BN_CTX *ctx) \ { \ return ec_GFp_s390x_nistp_mul(group, r, scalar, num, points, \ scalars, ctx, \ S390X_SCALAR_MULTIPLY_P##bits, \ S390X_SIZE_P##bits); \ } \ \ static ECDSA_SIG *ecdsa_s390x_nistp##bits##_sign_sig(const unsigned \ char *dgst, \ int dgstlen, \ const BIGNUM *kinv,\ const BIGNUM *r, \ EC_KEY *eckey) \ { \ return ecdsa_s390x_nistp_sign_sig(dgst, dgstlen, kinv, r, eckey, \ S390X_ECDSA_SIGN_P##bits, \ S390X_SIZE_P##bits); \ } \ \ static int ecdsa_s390x_nistp##bits##_verify_sig(const \ unsigned char *dgst, \ int dgstlen, \ const ECDSA_SIG *sig, \ EC_KEY *eckey) \ { \ return ecdsa_s390x_nistp_verify_sig(dgst, dgstlen, sig, eckey, \ S390X_ECDSA_VERIFY_P##bits, \ S390X_SIZE_P##bits); \ } \ \ const EC_METHOD *EC_GFp_s390x_nistp##bits##_method(void) \ { \ static const EC_METHOD EC_GFp_s390x_nistp##bits##_meth = { \ EC_FLAGS_DEFAULT_OCT, \ NID_X9_62_prime_field, \ ossl_ec_GFp_simple_group_init, \ ossl_ec_GFp_simple_group_finish, \ ossl_ec_GFp_simple_group_clear_finish, \ ossl_ec_GFp_simple_group_copy, \ ossl_ec_GFp_simple_group_set_curve, \ ossl_ec_GFp_simple_group_get_curve, \ ossl_ec_GFp_simple_group_get_degree, \ ossl_ec_group_simple_order_bits, \ ossl_ec_GFp_simple_group_check_discriminant, \ ossl_ec_GFp_simple_point_init, \ ossl_ec_GFp_simple_point_finish, \ ossl_ec_GFp_simple_point_clear_finish, \ ossl_ec_GFp_simple_point_copy, \ ossl_ec_GFp_simple_point_set_to_infinity, \ ossl_ec_GFp_simple_point_set_affine_coordinates, \ ossl_ec_GFp_simple_point_get_affine_coordinates, \ NULL, /* point_set_compressed_coordinates */ \ NULL, /* point2oct */ \ NULL, /* oct2point */ \ ossl_ec_GFp_simple_add, \ ossl_ec_GFp_simple_dbl, \ ossl_ec_GFp_simple_invert, \ ossl_ec_GFp_simple_is_at_infinity, \ ossl_ec_GFp_simple_is_on_curve, \ ossl_ec_GFp_simple_cmp, \ ossl_ec_GFp_simple_make_affine, \ ossl_ec_GFp_simple_points_make_affine, \ ec_GFp_s390x_nistp##bits##_mul, \ NULL, /* precompute_mult */ \ NULL, /* have_precompute_mult */ \ ossl_ec_GFp_simple_field_mul, \ ossl_ec_GFp_simple_field_sqr, \ NULL, /* field_div */ \ ossl_ec_GFp_simple_field_inv, \ NULL, /* field_encode */ \ NULL, /* field_decode */ \ NULL, /* field_set_to_one */ \ ossl_ec_key_simple_priv2oct, \ ossl_ec_key_simple_oct2priv, \ NULL, /* set_private */ \ ossl_ec_key_simple_generate_key, \ ossl_ec_key_simple_check_key, \ ossl_ec_key_simple_generate_public_key, \ NULL, /* keycopy */ \ NULL, /* keyfinish */ \ ossl_ecdh_simple_compute_key, \ ossl_ecdsa_simple_sign_setup, \ ecdsa_s390x_nistp##bits##_sign_sig, \ ecdsa_s390x_nistp##bits##_verify_sig, \ NULL, /* field_inverse_mod_ord */ \ ossl_ec_GFp_simple_blind_coordinates, \ ossl_ec_GFp_simple_ladder_pre, \ ossl_ec_GFp_simple_ladder_step, \ ossl_ec_GFp_simple_ladder_post \ }; \ static const EC_METHOD *ret; \ \ if ((OPENSSL_s390xcap_P.pcc[1] \ & S390X_CAPBIT(S390X_SCALAR_MULTIPLY_P##bits)) \ && (OPENSSL_s390xcap_P.kdsa[0] \ & S390X_CAPBIT(S390X_ECDSA_VERIFY_P##bits)) \ && (OPENSSL_s390xcap_P.kdsa[0] \ & S390X_CAPBIT(S390X_ECDSA_SIGN_P##bits))) \ ret = &EC_GFp_s390x_nistp##bits##_meth; \ else \ ret = EC_GFp_mont_method(); \ \ return ret; \ } EC_GFP_S390X_NISTP_METHOD(256) EC_GFP_S390X_NISTP_METHOD(384) EC_GFP_S390X_NISTP_METHOD(521)
17,347
42.261845
79
c
openssl
openssl-master/crypto/ec/ecx_backend.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> #include <openssl/core_names.h> #include <openssl/params.h> #include <openssl/ec.h> #include <openssl/rand.h> #include <openssl/err.h> #ifndef FIPS_MODULE # include <openssl/x509.h> #endif #include "crypto/ecx.h" #include "ecx_backend.h" /* * The intention with the "backend" source file is to offer backend support * for legacy backends (EVP_PKEY_ASN1_METHOD and EVP_PKEY_METHOD) and provider * implementations alike. */ int ossl_ecx_public_from_private(ECX_KEY *key) { switch (key->type) { case ECX_KEY_TYPE_X25519: ossl_x25519_public_from_private(key->pubkey, key->privkey); break; case ECX_KEY_TYPE_ED25519: if (!ossl_ed25519_public_from_private(key->libctx, key->pubkey, key->privkey, key->propq)) { ERR_raise(ERR_LIB_EC, EC_R_FAILED_MAKING_PUBLIC_KEY); return 0; } break; case ECX_KEY_TYPE_X448: ossl_x448_public_from_private(key->pubkey, key->privkey); break; case ECX_KEY_TYPE_ED448: if (!ossl_ed448_public_from_private(key->libctx, key->pubkey, key->privkey, key->propq)) { ERR_raise(ERR_LIB_EC, EC_R_FAILED_MAKING_PUBLIC_KEY); return 0; } break; } return 1; } int ossl_ecx_key_fromdata(ECX_KEY *ecx, const OSSL_PARAM params[], int include_private) { size_t privkeylen = 0, pubkeylen = 0; const OSSL_PARAM *param_priv_key = NULL, *param_pub_key; unsigned char *pubkey; if (ecx == NULL) return 0; param_pub_key = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY); if (include_private) param_priv_key = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY); if (param_pub_key == NULL && param_priv_key == NULL) return 0; if (param_priv_key != NULL) { if (!OSSL_PARAM_get_octet_string(param_priv_key, (void **)&ecx->privkey, ecx->keylen, &privkeylen)) return 0; if (privkeylen != ecx->keylen) { /* * Invalid key length. We will clear what we've received now. We * can't leave it to ossl_ecx_key_free() because that will call * OPENSSL_secure_clear_free() and assume the correct key length */ OPENSSL_secure_clear_free(ecx->privkey, privkeylen); ecx->privkey = NULL; return 0; } } pubkey = ecx->pubkey; if (param_pub_key != NULL && !OSSL_PARAM_get_octet_string(param_pub_key, (void **)&pubkey, sizeof(ecx->pubkey), &pubkeylen)) return 0; if ((param_pub_key != NULL && pubkeylen != ecx->keylen)) return 0; if (param_pub_key == NULL && !ossl_ecx_public_from_private(ecx)) return 0; ecx->haspubkey = 1; return 1; } ECX_KEY *ossl_ecx_key_dup(const ECX_KEY *key, int selection) { ECX_KEY *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->libctx = key->libctx; ret->haspubkey = key->haspubkey; ret->keylen = key->keylen; ret->type = key->type; if (!CRYPTO_NEW_REF(&ret->references, 1)) goto err; if (key->propq != NULL) { ret->propq = OPENSSL_strdup(key->propq); if (ret->propq == NULL) goto err; } if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) memcpy(ret->pubkey, key->pubkey, sizeof(ret->pubkey)); if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0 && key->privkey != NULL) { if (ossl_ecx_key_allocate_privkey(ret) == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } memcpy(ret->privkey, key->privkey, ret->keylen); } return ret; err: CRYPTO_FREE_REF(&ret->references); ossl_ecx_key_free(ret); return NULL; } #ifndef FIPS_MODULE ECX_KEY *ossl_ecx_key_op(const X509_ALGOR *palg, const unsigned char *p, int plen, int id, ecx_key_op_t op, OSSL_LIB_CTX *libctx, const char *propq) { ECX_KEY *key = NULL; unsigned char *privkey, *pubkey; if (op != KEY_OP_KEYGEN) { if (palg != NULL) { int ptype; /* Algorithm parameters must be absent */ X509_ALGOR_get0(NULL, &ptype, NULL, palg); if (ptype != V_ASN1_UNDEF) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); return 0; } if (id == EVP_PKEY_NONE) id = OBJ_obj2nid(palg->algorithm); else if (id != OBJ_obj2nid(palg->algorithm)) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); return 0; } } if (p == NULL || id == EVP_PKEY_NONE || plen != KEYLENID(id)) { ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING); return 0; } } key = ossl_ecx_key_new(libctx, KEYNID2TYPE(id), 1, propq); if (key == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); return 0; } pubkey = key->pubkey; if (op == KEY_OP_PUBLIC) { memcpy(pubkey, p, plen); } else { privkey = ossl_ecx_key_allocate_privkey(key); if (privkey == NULL) { ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB); goto err; } if (op == KEY_OP_KEYGEN) { if (id != EVP_PKEY_NONE) { if (RAND_priv_bytes_ex(libctx, privkey, KEYLENID(id), 0) <= 0) goto err; if (id == EVP_PKEY_X25519) { privkey[0] &= 248; privkey[X25519_KEYLEN - 1] &= 127; privkey[X25519_KEYLEN - 1] |= 64; } else if (id == EVP_PKEY_X448) { privkey[0] &= 252; privkey[X448_KEYLEN - 1] |= 128; } } } else { memcpy(privkey, p, KEYLENID(id)); } if (!ossl_ecx_public_from_private(key)) { ERR_raise(ERR_LIB_EC, EC_R_FAILED_MAKING_PUBLIC_KEY); goto err; } } return key; err: ossl_ecx_key_free(key); return NULL; } ECX_KEY *ossl_ecx_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *libctx, const char *propq) { ECX_KEY *ecx = NULL; const unsigned char *p; int plen; ASN1_OCTET_STRING *oct = NULL; const X509_ALGOR *palg; if (!PKCS8_pkey_get0(NULL, &p, &plen, &palg, p8inf)) return 0; oct = d2i_ASN1_OCTET_STRING(NULL, &p, plen); if (oct == NULL) { p = NULL; plen = 0; } else { p = ASN1_STRING_get0_data(oct); plen = ASN1_STRING_length(oct); } /* * EVP_PKEY_NONE means that ecx_key_op() has to figure out the key type * on its own. */ ecx = ossl_ecx_key_op(palg, p, plen, EVP_PKEY_NONE, KEY_OP_PRIVATE, libctx, propq); ASN1_OCTET_STRING_free(oct); return ecx; } #endif
7,605
28.595331
78
c
openssl
openssl-master/crypto/ec/ecx_backend.h
/* * Copyright 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 */ #define ISX448(id) ((id) == EVP_PKEY_X448) #define IS25519(id) ((id) == EVP_PKEY_X25519 || (id) == EVP_PKEY_ED25519) #define KEYLENID(id) (IS25519(id) ? X25519_KEYLEN \ : ((id) == EVP_PKEY_X448 ? X448_KEYLEN \ : ED448_KEYLEN)) #define KEYNID2TYPE(id) \ (IS25519(id) ? ((id) == EVP_PKEY_X25519 ? ECX_KEY_TYPE_X25519 \ : ECX_KEY_TYPE_ED25519) \ : ((id) == EVP_PKEY_X448 ? ECX_KEY_TYPE_X448 \ : ECX_KEY_TYPE_ED448)) #define KEYLEN(p) KEYLENID((p)->ameth->pkey_id)
1,017
47.47619
78
h
openssl
openssl-master/crypto/ec/ecx_key.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> #include <openssl/err.h> #include <openssl/proverr.h> #include "crypto/ecx.h" #include "internal/common.h" /* for ossl_assert() */ #ifdef S390X_EC_ASM # include "s390x_arch.h" #endif ECX_KEY *ossl_ecx_key_new(OSSL_LIB_CTX *libctx, ECX_KEY_TYPE type, int haspubkey, const char *propq) { ECX_KEY *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->libctx = libctx; ret->haspubkey = haspubkey; switch (type) { case ECX_KEY_TYPE_X25519: ret->keylen = X25519_KEYLEN; break; case ECX_KEY_TYPE_X448: ret->keylen = X448_KEYLEN; break; case ECX_KEY_TYPE_ED25519: ret->keylen = ED25519_KEYLEN; break; case ECX_KEY_TYPE_ED448: ret->keylen = ED448_KEYLEN; break; } ret->type = type; if (!CRYPTO_NEW_REF(&ret->references, 1)) goto err; if (propq != NULL) { ret->propq = OPENSSL_strdup(propq); if (ret->propq == NULL) goto err; } return ret; err: if (ret != NULL) { OPENSSL_free(ret->propq); CRYPTO_FREE_REF(&ret->references); } OPENSSL_free(ret); return NULL; } void ossl_ecx_key_free(ECX_KEY *key) { int i; if (key == NULL) return; CRYPTO_DOWN_REF(&key->references, &i); REF_PRINT_COUNT("ECX_KEY", key); if (i > 0) return; REF_ASSERT_ISNT(i < 0); OPENSSL_free(key->propq); OPENSSL_secure_clear_free(key->privkey, key->keylen); CRYPTO_FREE_REF(&key->references); OPENSSL_free(key); } void ossl_ecx_key_set0_libctx(ECX_KEY *key, OSSL_LIB_CTX *libctx) { key->libctx = libctx; } int ossl_ecx_key_up_ref(ECX_KEY *key) { int i; if (CRYPTO_UP_REF(&key->references, &i) <= 0) return 0; REF_PRINT_COUNT("ECX_KEY", key); REF_ASSERT_ISNT(i < 2); return ((i > 1) ? 1 : 0); } unsigned char *ossl_ecx_key_allocate_privkey(ECX_KEY *key) { key->privkey = OPENSSL_secure_zalloc(key->keylen); return key->privkey; } int ossl_ecx_compute_key(ECX_KEY *peer, ECX_KEY *priv, size_t keylen, unsigned char *secret, size_t *secretlen, size_t outlen) { if (priv == NULL || priv->privkey == NULL || peer == NULL) { ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY); return 0; } if (!ossl_assert(keylen == X25519_KEYLEN || keylen == X448_KEYLEN)) { ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH); return 0; } if (secret == NULL) { *secretlen = keylen; return 1; } if (outlen < keylen) { ERR_raise(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL); return 0; } if (keylen == X25519_KEYLEN) { #ifdef S390X_EC_ASM if (OPENSSL_s390xcap_P.pcc[1] & S390X_CAPBIT(S390X_SCALAR_MULTIPLY_X25519)) { if (s390x_x25519_mul(secret, peer->pubkey, priv->privkey) == 0) { ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_DURING_DERIVATION); return 0; } } else #endif if (ossl_x25519(secret, priv->privkey, peer->pubkey) == 0) { ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_DURING_DERIVATION); return 0; } } else { #ifdef S390X_EC_ASM if (OPENSSL_s390xcap_P.pcc[1] & S390X_CAPBIT(S390X_SCALAR_MULTIPLY_X448)) { if (s390x_x448_mul(secret, peer->pubkey, priv->privkey) == 0) { ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_DURING_DERIVATION); return 0; } } else #endif if (ossl_x448(secret, priv->privkey, peer->pubkey) == 0) { ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_DURING_DERIVATION); return 0; } } *secretlen = keylen; return 1; }
4,193
24.573171
81
c
openssl
openssl-master/crypto/ec/ecx_s390x.c
/* * Copyright 2006-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 "internal/cryptlib.h" #include <openssl/ec.h> #include <openssl/rand.h> #include "crypto/ecx.h" #include "ec_local.h" #include "curve448/curve448_local.h" #include "ecx_backend.h" #include "s390x_arch.h" #include "internal/constant_time.h" static void s390x_x25519_mod_p(unsigned char u[32]) { unsigned char u_red[32]; unsigned int c = 0; int i; memcpy(u_red, u, sizeof(u_red)); c += (unsigned int)u_red[31] + 19; u_red[31] = (unsigned char)c; c >>= 8; for (i = 30; i >= 0; i--) { c += (unsigned int)u_red[i]; u_red[i] = (unsigned char)c; c >>= 8; } c = (u_red[0] & 0x80) >> 7; u_red[0] &= 0x7f; constant_time_cond_swap_buff(0 - (unsigned char)c, u, u_red, sizeof(u_red)); } static void s390x_x448_mod_p(unsigned char u[56]) { unsigned char u_red[56]; unsigned int c = 0; int i; memcpy(u_red, u, sizeof(u_red)); c += (unsigned int)u_red[55] + 1; u_red[55] = (unsigned char)c; c >>= 8; for (i = 54; i >= 28; i--) { c += (unsigned int)u_red[i]; u_red[i] = (unsigned char)c; c >>= 8; } c += (unsigned int)u_red[27] + 1; u_red[27] = (unsigned char)c; c >>= 8; for (i = 26; i >= 0; i--) { c += (unsigned int)u_red[i]; u_red[i] = (unsigned char)c; c >>= 8; } constant_time_cond_swap_buff(0 - (unsigned char)c, u, u_red, sizeof(u_red)); } int s390x_x25519_mul(unsigned char u_dst[32], const unsigned char u_src[32], const unsigned char d_src[32]) { union { struct { unsigned char u_dst[32]; unsigned char u_src[32]; unsigned char d_src[32]; } x25519; unsigned long long buff[512]; } param; int rc; memset(&param, 0, sizeof(param)); s390x_flip_endian32(param.x25519.u_src, u_src); param.x25519.u_src[0] &= 0x7f; s390x_x25519_mod_p(param.x25519.u_src); s390x_flip_endian32(param.x25519.d_src, d_src); param.x25519.d_src[31] &= 248; param.x25519.d_src[0] &= 127; param.x25519.d_src[0] |= 64; rc = s390x_pcc(S390X_SCALAR_MULTIPLY_X25519, &param.x25519) ? 0 : 1; if (rc == 1) s390x_flip_endian32(u_dst, param.x25519.u_dst); OPENSSL_cleanse(param.x25519.d_src, sizeof(param.x25519.d_src)); return rc; } int s390x_x448_mul(unsigned char u_dst[56], const unsigned char u_src[56], const unsigned char d_src[56]) { union { struct { unsigned char u_dst[64]; unsigned char u_src[64]; unsigned char d_src[64]; } x448; unsigned long long buff[512]; } param; int rc; memset(&param, 0, sizeof(param)); memcpy(param.x448.u_src, u_src, 56); memcpy(param.x448.d_src, d_src, 56); s390x_flip_endian64(param.x448.u_src, param.x448.u_src); s390x_x448_mod_p(param.x448.u_src + 8); s390x_flip_endian64(param.x448.d_src, param.x448.d_src); param.x448.d_src[63] &= 252; param.x448.d_src[8] |= 128; rc = s390x_pcc(S390X_SCALAR_MULTIPLY_X448, &param.x448) ? 0 : 1; if (rc == 1) { s390x_flip_endian64(param.x448.u_dst, param.x448.u_dst); memcpy(u_dst, param.x448.u_dst, 56); } OPENSSL_cleanse(param.x448.d_src, sizeof(param.x448.d_src)); return rc; } int s390x_ed25519_mul(unsigned char x_dst[32], unsigned char y_dst[32], const unsigned char x_src[32], const unsigned char y_src[32], const unsigned char d_src[32]) { union { struct { unsigned char x_dst[32]; unsigned char y_dst[32]; unsigned char x_src[32]; unsigned char y_src[32]; unsigned char d_src[32]; } ed25519; unsigned long long buff[512]; } param; int rc; memset(&param, 0, sizeof(param)); s390x_flip_endian32(param.ed25519.x_src, x_src); s390x_flip_endian32(param.ed25519.y_src, y_src); s390x_flip_endian32(param.ed25519.d_src, d_src); rc = s390x_pcc(S390X_SCALAR_MULTIPLY_ED25519, &param.ed25519) ? 0 : 1; if (rc == 1) { s390x_flip_endian32(x_dst, param.ed25519.x_dst); s390x_flip_endian32(y_dst, param.ed25519.y_dst); } OPENSSL_cleanse(param.ed25519.d_src, sizeof(param.ed25519.d_src)); return rc; } int s390x_ed448_mul(unsigned char x_dst[57], unsigned char y_dst[57], const unsigned char x_src[57], const unsigned char y_src[57], const unsigned char d_src[57]) { union { struct { unsigned char x_dst[64]; unsigned char y_dst[64]; unsigned char x_src[64]; unsigned char y_src[64]; unsigned char d_src[64]; } ed448; unsigned long long buff[512]; } param; int rc; memset(&param, 0, sizeof(param)); memcpy(param.ed448.x_src, x_src, 57); memcpy(param.ed448.y_src, y_src, 57); memcpy(param.ed448.d_src, d_src, 57); s390x_flip_endian64(param.ed448.x_src, param.ed448.x_src); s390x_flip_endian64(param.ed448.y_src, param.ed448.y_src); s390x_flip_endian64(param.ed448.d_src, param.ed448.d_src); rc = s390x_pcc(S390X_SCALAR_MULTIPLY_ED448, &param.ed448) ? 0 : 1; if (rc == 1) { s390x_flip_endian64(param.ed448.x_dst, param.ed448.x_dst); s390x_flip_endian64(param.ed448.y_dst, param.ed448.y_dst); memcpy(x_dst, param.ed448.x_dst, 57); memcpy(y_dst, param.ed448.y_dst, 57); } OPENSSL_cleanse(param.ed448.d_src, sizeof(param.ed448.d_src)); return rc; }
6,156
27.243119
74
c
openssl
openssl-master/crypto/ec/curve448/curve448.c
/* * Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2015-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 */ #include <openssl/crypto.h> #include "word.h" #include "field.h" #include "point_448.h" #include "ed448.h" #include "crypto/ecx.h" #include "curve448_local.h" #define COFACTOR 4 #define C448_WNAF_FIXED_TABLE_BITS 5 #define C448_WNAF_VAR_TABLE_BITS 3 #define EDWARDS_D (-39081) static const curve448_scalar_t precomputed_scalarmul_adjustment = { { { SC_LIMB(0xc873d6d54a7bb0cfULL), SC_LIMB(0xe933d8d723a70aadULL), SC_LIMB(0xbb124b65129c96fdULL), SC_LIMB(0x00000008335dc163ULL) } } }; #define TWISTED_D (EDWARDS_D - 1) #define WBITS C448_WORD_BITS /* NB this may be different from ARCH_WORD_BITS */ /* Inverse. */ static void gf_invert(gf y, const gf x, int assert_nonzero) { mask_t ret; gf t1, t2; ossl_gf_sqr(t1, x); /* o^2 */ ret = gf_isr(t2, t1); /* +-1/sqrt(o^2) = +-1/o */ (void)ret; if (assert_nonzero) assert(ret); ossl_gf_sqr(t1, t2); ossl_gf_mul(t2, t1, x); /* not direct to y in case of alias. */ gf_copy(y, t2); } /** identity = (0,1) */ const curve448_point_t ossl_curve448_point_identity = { {{{{0}}}, {{{1}}}, {{{1}}}, {{{0}}}} }; static void point_double_internal(curve448_point_t p, const curve448_point_t q, int before_double) { gf a, b, c, d; ossl_gf_sqr(c, q->x); ossl_gf_sqr(a, q->y); gf_add_nr(d, c, a); /* 2+e */ gf_add_nr(p->t, q->y, q->x); /* 2+e */ ossl_gf_sqr(b, p->t); gf_subx_nr(b, b, d, 3); /* 4+e */ gf_sub_nr(p->t, a, c); /* 3+e */ ossl_gf_sqr(p->x, q->z); gf_add_nr(p->z, p->x, p->x); /* 2+e */ gf_subx_nr(a, p->z, p->t, 4); /* 6+e */ if (GF_HEADROOM == 5) gf_weak_reduce(a); /* or 1+e */ ossl_gf_mul(p->x, a, b); ossl_gf_mul(p->z, p->t, a); ossl_gf_mul(p->y, p->t, d); if (!before_double) ossl_gf_mul(p->t, b, d); } void ossl_curve448_point_double(curve448_point_t p, const curve448_point_t q) { point_double_internal(p, q, 0); } /* Operations on [p]niels */ static ossl_inline void cond_neg_niels(niels_t n, mask_t neg) { gf_cond_swap(n->a, n->b, neg); gf_cond_neg(n->c, neg); } static void pt_to_pniels(pniels_t b, const curve448_point_t a) { gf_sub(b->n->a, a->y, a->x); gf_add(b->n->b, a->x, a->y); gf_mulw(b->n->c, a->t, 2 * TWISTED_D); gf_add(b->z, a->z, a->z); } static void pniels_to_pt(curve448_point_t e, const pniels_t d) { gf eu; gf_add(eu, d->n->b, d->n->a); gf_sub(e->y, d->n->b, d->n->a); ossl_gf_mul(e->t, e->y, eu); ossl_gf_mul(e->x, d->z, e->y); ossl_gf_mul(e->y, d->z, eu); ossl_gf_sqr(e->z, d->z); } static void niels_to_pt(curve448_point_t e, const niels_t n) { gf_add(e->y, n->b, n->a); gf_sub(e->x, n->b, n->a); ossl_gf_mul(e->t, e->y, e->x); gf_copy(e->z, ONE); } static void add_niels_to_pt(curve448_point_t d, const niels_t e, int before_double) { gf a, b, c; gf_sub_nr(b, d->y, d->x); /* 3+e */ ossl_gf_mul(a, e->a, b); gf_add_nr(b, d->x, d->y); /* 2+e */ ossl_gf_mul(d->y, e->b, b); ossl_gf_mul(d->x, e->c, d->t); gf_add_nr(c, a, d->y); /* 2+e */ gf_sub_nr(b, d->y, a); /* 3+e */ gf_sub_nr(d->y, d->z, d->x); /* 3+e */ gf_add_nr(a, d->x, d->z); /* 2+e */ ossl_gf_mul(d->z, a, d->y); ossl_gf_mul(d->x, d->y, b); ossl_gf_mul(d->y, a, c); if (!before_double) ossl_gf_mul(d->t, b, c); } static void sub_niels_from_pt(curve448_point_t d, const niels_t e, int before_double) { gf a, b, c; gf_sub_nr(b, d->y, d->x); /* 3+e */ ossl_gf_mul(a, e->b, b); gf_add_nr(b, d->x, d->y); /* 2+e */ ossl_gf_mul(d->y, e->a, b); ossl_gf_mul(d->x, e->c, d->t); gf_add_nr(c, a, d->y); /* 2+e */ gf_sub_nr(b, d->y, a); /* 3+e */ gf_add_nr(d->y, d->z, d->x); /* 2+e */ gf_sub_nr(a, d->z, d->x); /* 3+e */ ossl_gf_mul(d->z, a, d->y); ossl_gf_mul(d->x, d->y, b); ossl_gf_mul(d->y, a, c); if (!before_double) ossl_gf_mul(d->t, b, c); } static void add_pniels_to_pt(curve448_point_t p, const pniels_t pn, int before_double) { gf L0; ossl_gf_mul(L0, p->z, pn->z); gf_copy(p->z, L0); add_niels_to_pt(p, pn->n, before_double); } static void sub_pniels_from_pt(curve448_point_t p, const pniels_t pn, int before_double) { gf L0; ossl_gf_mul(L0, p->z, pn->z); gf_copy(p->z, L0); sub_niels_from_pt(p, pn->n, before_double); } c448_bool_t ossl_curve448_point_eq(const curve448_point_t p, const curve448_point_t q) { mask_t succ; gf a, b; /* equality mod 2-torsion compares x/y */ ossl_gf_mul(a, p->y, q->x); ossl_gf_mul(b, q->y, p->x); succ = gf_eq(a, b); return mask_to_bool(succ); } c448_bool_t ossl_curve448_point_valid(const curve448_point_t p) { mask_t out; gf a, b, c; ossl_gf_mul(a, p->x, p->y); ossl_gf_mul(b, p->z, p->t); out = gf_eq(a, b); ossl_gf_sqr(a, p->x); ossl_gf_sqr(b, p->y); gf_sub(a, b, a); ossl_gf_sqr(b, p->t); gf_mulw(c, b, TWISTED_D); ossl_gf_sqr(b, p->z); gf_add(b, b, c); out &= gf_eq(a, b); out &= ~gf_eq(p->z, ZERO); return mask_to_bool(out); } static ossl_inline void constant_time_lookup_niels(niels_s * RESTRICT ni, const niels_t * table, int nelts, int idx) { constant_time_lookup(ni, table, sizeof(niels_s), nelts, idx); } void ossl_curve448_precomputed_scalarmul(curve448_point_t out, const curve448_precomputed_s * table, const curve448_scalar_t scalar) { unsigned int i, j, k; const unsigned int n = COMBS_N, t = COMBS_T, s = COMBS_S; niels_t ni; curve448_scalar_t scalar1x; ossl_curve448_scalar_add(scalar1x, scalar, precomputed_scalarmul_adjustment); ossl_curve448_scalar_halve(scalar1x, scalar1x); for (i = s; i > 0; i--) { if (i != s) point_double_internal(out, out, 0); for (j = 0; j < n; j++) { int tab = 0; mask_t invert; for (k = 0; k < t; k++) { unsigned int bit = (i - 1) + s * (k + j * t); if (bit < C448_SCALAR_BITS) tab |= (scalar1x->limb[bit / WBITS] >> (bit % WBITS) & 1) << k; } invert = (tab >> (t - 1)) - 1; tab ^= invert; tab &= (1 << (t - 1)) - 1; constant_time_lookup_niels(ni, &table->table[j << (t - 1)], 1 << (t - 1), tab); cond_neg_niels(ni, invert); if ((i != s) || j != 0) add_niels_to_pt(out, ni, j == n - 1 && i != 1); else niels_to_pt(out, ni); } } OPENSSL_cleanse(ni, sizeof(ni)); OPENSSL_cleanse(scalar1x, sizeof(scalar1x)); } void ossl_curve448_point_mul_by_ratio_and_encode_like_eddsa( uint8_t enc[EDDSA_448_PUBLIC_BYTES], const curve448_point_t p) { gf x, y, z, t; curve448_point_t q; /* The point is now on the twisted curve. Move it to untwisted. */ curve448_point_copy(q, p); { /* 4-isogeny: 2xy/(y^+x^2), (y^2-x^2)/(2z^2-y^2+x^2) */ gf u; ossl_gf_sqr(x, q->x); ossl_gf_sqr(t, q->y); gf_add(u, x, t); gf_add(z, q->y, q->x); ossl_gf_sqr(y, z); gf_sub(y, y, u); gf_sub(z, t, x); ossl_gf_sqr(x, q->z); gf_add(t, x, x); gf_sub(t, t, z); ossl_gf_mul(x, t, y); ossl_gf_mul(y, z, u); ossl_gf_mul(z, u, t); OPENSSL_cleanse(u, sizeof(u)); } /* Affinize */ gf_invert(z, z, 1); ossl_gf_mul(t, x, z); ossl_gf_mul(x, y, z); /* Encode */ enc[EDDSA_448_PRIVATE_BYTES - 1] = 0; gf_serialize(enc, x, 1); enc[EDDSA_448_PRIVATE_BYTES - 1] |= 0x80 & gf_lobit(t); OPENSSL_cleanse(x, sizeof(x)); OPENSSL_cleanse(y, sizeof(y)); OPENSSL_cleanse(z, sizeof(z)); OPENSSL_cleanse(t, sizeof(t)); ossl_curve448_point_destroy(q); } c448_error_t ossl_curve448_point_decode_like_eddsa_and_mul_by_ratio( curve448_point_t p, const uint8_t enc[EDDSA_448_PUBLIC_BYTES]) { uint8_t enc2[EDDSA_448_PUBLIC_BYTES]; mask_t low; mask_t succ; memcpy(enc2, enc, sizeof(enc2)); low = ~word_is_zero(enc2[EDDSA_448_PRIVATE_BYTES - 1] & 0x80); enc2[EDDSA_448_PRIVATE_BYTES - 1] &= ~0x80; succ = gf_deserialize(p->y, enc2, 1, 0); succ &= word_is_zero(enc2[EDDSA_448_PRIVATE_BYTES - 1]); ossl_gf_sqr(p->x, p->y); gf_sub(p->z, ONE, p->x); /* num = 1-y^2 */ gf_mulw(p->t, p->x, EDWARDS_D); /* dy^2 */ gf_sub(p->t, ONE, p->t); /* denom = 1-dy^2 or 1-d + dy^2 */ ossl_gf_mul(p->x, p->z, p->t); succ &= gf_isr(p->t, p->x); /* 1/sqrt(num * denom) */ ossl_gf_mul(p->x, p->t, p->z); /* sqrt(num / denom) */ gf_cond_neg(p->x, gf_lobit(p->x) ^ low); gf_copy(p->z, ONE); { gf a, b, c, d; /* 4-isogeny 2xy/(y^2-ax^2), (y^2+ax^2)/(2-y^2-ax^2) */ ossl_gf_sqr(c, p->x); ossl_gf_sqr(a, p->y); gf_add(d, c, a); gf_add(p->t, p->y, p->x); ossl_gf_sqr(b, p->t); gf_sub(b, b, d); gf_sub(p->t, a, c); ossl_gf_sqr(p->x, p->z); gf_add(p->z, p->x, p->x); gf_sub(a, p->z, d); ossl_gf_mul(p->x, a, b); ossl_gf_mul(p->z, p->t, a); ossl_gf_mul(p->y, p->t, d); ossl_gf_mul(p->t, b, d); OPENSSL_cleanse(a, sizeof(a)); OPENSSL_cleanse(b, sizeof(b)); OPENSSL_cleanse(c, sizeof(c)); OPENSSL_cleanse(d, sizeof(d)); } OPENSSL_cleanse(enc2, sizeof(enc2)); assert(ossl_curve448_point_valid(p) || ~succ); return c448_succeed_if(mask_to_bool(succ)); } c448_error_t ossl_x448_int(uint8_t out[X_PUBLIC_BYTES], const uint8_t base[X_PUBLIC_BYTES], const uint8_t scalar[X_PRIVATE_BYTES]) { gf x1, x2, z2, x3, z3, t1, t2; int t; mask_t swap = 0; mask_t nz; (void)gf_deserialize(x1, base, 1, 0); gf_copy(x2, ONE); gf_copy(z2, ZERO); gf_copy(x3, x1); gf_copy(z3, ONE); for (t = X_PRIVATE_BITS - 1; t >= 0; t--) { uint8_t sb = scalar[t / 8]; mask_t k_t; /* Scalar conditioning */ if (t / 8 == 0) sb &= -(uint8_t)COFACTOR; else if (t == X_PRIVATE_BITS - 1) sb = -1; k_t = (sb >> (t % 8)) & 1; k_t = 0 - k_t; /* set to all 0s or all 1s */ swap ^= k_t; gf_cond_swap(x2, x3, swap); gf_cond_swap(z2, z3, swap); swap = k_t; /* * The "_nr" below skips coefficient reduction. In the following * comments, "2+e" is saying that the coefficients are at most 2+epsilon * times the reduction limit. */ gf_add_nr(t1, x2, z2); /* A = x2 + z2 */ /* 2+e */ gf_sub_nr(t2, x2, z2); /* B = x2 - z2 */ /* 3+e */ gf_sub_nr(z2, x3, z3); /* D = x3 - z3 */ /* 3+e */ ossl_gf_mul(x2, t1, z2); /* DA */ gf_add_nr(z2, z3, x3); /* C = x3 + z3 */ /* 2+e */ ossl_gf_mul(x3, t2, z2); /* CB */ gf_sub_nr(z3, x2, x3); /* DA-CB */ /* 3+e */ ossl_gf_sqr(z2, z3); /* (DA-CB)^2 */ ossl_gf_mul(z3, x1, z2); /* z3 = x1(DA-CB)^2 */ gf_add_nr(z2, x2, x3); /* (DA+CB) */ /* 2+e */ ossl_gf_sqr(x3, z2); /* x3 = (DA+CB)^2 */ ossl_gf_sqr(z2, t1); /* AA = A^2 */ ossl_gf_sqr(t1, t2); /* BB = B^2 */ ossl_gf_mul(x2, z2, t1); /* x2 = AA*BB */ gf_sub_nr(t2, z2, t1); /* E = AA-BB */ /* 3+e */ gf_mulw(t1, t2, -EDWARDS_D); /* E*-d = a24*E */ gf_add_nr(t1, t1, z2); /* AA + a24*E */ /* 2+e */ ossl_gf_mul(z2, t2, t1); /* z2 = E(AA+a24*E) */ } /* Finish */ gf_cond_swap(x2, x3, swap); gf_cond_swap(z2, z3, swap); gf_invert(z2, z2, 0); ossl_gf_mul(x1, x2, z2); gf_serialize(out, x1, 1); nz = ~gf_eq(x1, ZERO); OPENSSL_cleanse(x1, sizeof(x1)); OPENSSL_cleanse(x2, sizeof(x2)); OPENSSL_cleanse(z2, sizeof(z2)); OPENSSL_cleanse(x3, sizeof(x3)); OPENSSL_cleanse(z3, sizeof(z3)); OPENSSL_cleanse(t1, sizeof(t1)); OPENSSL_cleanse(t2, sizeof(t2)); return c448_succeed_if(mask_to_bool(nz)); } void ossl_curve448_point_mul_by_ratio_and_encode_like_x448(uint8_t out[X_PUBLIC_BYTES], const curve448_point_t p) { curve448_point_t q; curve448_point_copy(q, p); gf_invert(q->t, q->x, 0); /* 1/x */ ossl_gf_mul(q->z, q->t, q->y); /* y/x */ ossl_gf_sqr(q->y, q->z); /* (y/x)^2 */ gf_serialize(out, q->y, 1); ossl_curve448_point_destroy(q); } void ossl_x448_derive_public_key(uint8_t out[X_PUBLIC_BYTES], const uint8_t scalar[X_PRIVATE_BYTES]) { /* Scalar conditioning */ uint8_t scalar2[X_PRIVATE_BYTES]; curve448_scalar_t the_scalar; curve448_point_t p; unsigned int i; memcpy(scalar2, scalar, sizeof(scalar2)); scalar2[0] &= -(uint8_t)COFACTOR; scalar2[X_PRIVATE_BYTES - 1] &= ~((0u - 1u) << ((X_PRIVATE_BITS + 7) % 8)); scalar2[X_PRIVATE_BYTES - 1] |= 1 << ((X_PRIVATE_BITS + 7) % 8); ossl_curve448_scalar_decode_long(the_scalar, scalar2, sizeof(scalar2)); /* Compensate for the encoding ratio */ for (i = 1; i < X448_ENCODE_RATIO; i <<= 1) ossl_curve448_scalar_halve(the_scalar, the_scalar); ossl_curve448_precomputed_scalarmul(p, ossl_curve448_precomputed_base, the_scalar); ossl_curve448_point_mul_by_ratio_and_encode_like_x448(out, p); ossl_curve448_point_destroy(p); } /* Control for variable-time scalar multiply algorithms. */ struct smvt_control { int power, addend; }; #if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3)) # define NUMTRAILINGZEROS __builtin_ctz #else # define NUMTRAILINGZEROS numtrailingzeros static uint32_t numtrailingzeros(uint32_t i) { uint32_t tmp; uint32_t num = 31; if (i == 0) return 32; tmp = i << 16; if (tmp != 0) { i = tmp; num -= 16; } tmp = i << 8; if (tmp != 0) { i = tmp; num -= 8; } tmp = i << 4; if (tmp != 0) { i = tmp; num -= 4; } tmp = i << 2; if (tmp != 0) { i = tmp; num -= 2; } tmp = i << 1; if (tmp != 0) num--; return num; } #endif static int recode_wnaf(struct smvt_control *control, /* [nbits/(table_bits + 1) + 3] */ const curve448_scalar_t scalar, unsigned int table_bits) { unsigned int table_size = C448_SCALAR_BITS / (table_bits + 1) + 3; int position = table_size - 1; /* at the end */ uint64_t current = scalar->limb[0] & 0xFFFF; uint32_t mask = (1 << (table_bits + 1)) - 1; unsigned int w; const unsigned int B_OVER_16 = sizeof(scalar->limb[0]) / 2; unsigned int n, i; /* place the end marker */ control[position].power = -1; control[position].addend = 0; position--; /* * PERF: Could negate scalar if it's large. But then would need more cases * in the actual code that uses it, all for an expected reduction of like * 1/5 op. Probably not worth it. */ for (w = 1; w < (C448_SCALAR_BITS - 1) / 16 + 3; w++) { if (w < (C448_SCALAR_BITS - 1) / 16 + 1) { /* Refill the 16 high bits of current */ current += (uint32_t)((scalar->limb[w / B_OVER_16] >> (16 * (w % B_OVER_16))) << 16); } while (current & 0xFFFF) { uint32_t pos = NUMTRAILINGZEROS((uint32_t)current); uint32_t odd = (uint32_t)current >> pos; int32_t delta = odd & mask; assert(position >= 0); if (odd & (1 << (table_bits + 1))) delta -= (1 << (table_bits + 1)); /* * Coverity gets confused by the value of pos, thinking it might be * 32. This would require current & 0xFFFF to be zero which isn't * possible. Suppress this false positive, since adding a check * isn't desirable. */ /* coverity[overflow_before_widen] */ current -= delta * (1 << pos); control[position].power = pos + 16 * (w - 1); control[position].addend = delta; position--; } current >>= 16; } assert(current == 0); position++; n = table_size - position; for (i = 0; i < n; i++) control[i] = control[i + position]; return n - 1; } static void prepare_wnaf_table(pniels_t * output, const curve448_point_t working, unsigned int tbits) { curve448_point_t tmp; int i; pniels_t twop; pt_to_pniels(output[0], working); if (tbits == 0) return; ossl_curve448_point_double(tmp, working); pt_to_pniels(twop, tmp); add_pniels_to_pt(tmp, output[0], 0); pt_to_pniels(output[1], tmp); for (i = 2; i < 1 << tbits; i++) { add_pniels_to_pt(tmp, twop, 0); pt_to_pniels(output[i], tmp); } ossl_curve448_point_destroy(tmp); OPENSSL_cleanse(twop, sizeof(twop)); } void ossl_curve448_base_double_scalarmul_non_secret(curve448_point_t combo, const curve448_scalar_t scalar1, const curve448_point_t base2, const curve448_scalar_t scalar2) { const int table_bits_var = C448_WNAF_VAR_TABLE_BITS; const int table_bits_pre = C448_WNAF_FIXED_TABLE_BITS; struct smvt_control control_var[C448_SCALAR_BITS / (C448_WNAF_VAR_TABLE_BITS + 1) + 3]; struct smvt_control control_pre[C448_SCALAR_BITS / (C448_WNAF_FIXED_TABLE_BITS + 1) + 3]; int ncb_pre = recode_wnaf(control_pre, scalar1, table_bits_pre); int ncb_var = recode_wnaf(control_var, scalar2, table_bits_var); pniels_t precmp_var[1 << C448_WNAF_VAR_TABLE_BITS]; int contp = 0, contv = 0, i; prepare_wnaf_table(precmp_var, base2, table_bits_var); i = control_var[0].power; if (i < 0) { curve448_point_copy(combo, ossl_curve448_point_identity); return; } if (i > control_pre[0].power) { pniels_to_pt(combo, precmp_var[control_var[0].addend >> 1]); contv++; } else if (i == control_pre[0].power && i >= 0) { pniels_to_pt(combo, precmp_var[control_var[0].addend >> 1]); add_niels_to_pt(combo, ossl_curve448_wnaf_base[control_pre[0].addend >> 1], i); contv++; contp++; } else { i = control_pre[0].power; niels_to_pt(combo, ossl_curve448_wnaf_base[control_pre[0].addend >> 1]); contp++; } for (i--; i >= 0; i--) { int cv = (i == control_var[contv].power); int cp = (i == control_pre[contp].power); point_double_internal(combo, combo, i && !(cv || cp)); if (cv) { assert(control_var[contv].addend); if (control_var[contv].addend > 0) add_pniels_to_pt(combo, precmp_var[control_var[contv].addend >> 1], i && !cp); else sub_pniels_from_pt(combo, precmp_var[(-control_var[contv].addend) >> 1], i && !cp); contv++; } if (cp) { assert(control_pre[contp].addend); if (control_pre[contp].addend > 0) add_niels_to_pt(combo, ossl_curve448_wnaf_base[control_pre[contp].addend >> 1], i); else sub_niels_from_pt(combo, ossl_curve448_wnaf_base[(-control_pre [contp].addend) >> 1], i); contp++; } } /* This function is non-secret, but whatever this is cheap. */ OPENSSL_cleanse(control_var, sizeof(control_var)); OPENSSL_cleanse(control_pre, sizeof(control_pre)); OPENSSL_cleanse(precmp_var, sizeof(precmp_var)); assert(contv == ncb_var); (void)ncb_var; assert(contp == ncb_pre); (void)ncb_pre; } void ossl_curve448_point_destroy(curve448_point_t point) { OPENSSL_cleanse(point, sizeof(curve448_point_t)); } int ossl_x448(uint8_t out_shared_key[56], const uint8_t private_key[56], const uint8_t peer_public_value[56]) { return ossl_x448_int(out_shared_key, peer_public_value, private_key) == C448_SUCCESS; } void ossl_x448_public_from_private(uint8_t out_public_value[56], const uint8_t private_key[56]) { ossl_x448_derive_public_key(out_public_value, private_key); }
22,186
28.741287
81
c
openssl
openssl-master/crypto/ec/curve448/curve448_local.h
/* * Copyright 2017-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 */ #ifndef OSSL_CRYPTO_EC_CURVE448_LOCAL_H # define OSSL_CRYPTO_EC_CURVE448_LOCAL_H # include "curve448utils.h" #endif /* OSSL_CRYPTO_EC_CURVE448_LOCAL_H */
504
35.071429
74
h
openssl
openssl-master/crypto/ec/curve448/curve448utils.h
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2015 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_CURVE448UTILS_H # define OSSL_CRYPTO_EC_CURVE448UTILS_H # include <openssl/e_os2.h> # include "internal/numbers.h" /* * Internal word types. Somewhat tricky. This could be decided separately per * platform. However, the structs do need to be all the same size and * alignment on a given platform to support dynamic linking, since even if you * header was built with eg arch_neon, you might end up linking a library built * with arch_arm32. */ # ifndef C448_WORD_BITS # if (defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16)) \ && !defined(__sparc__) \ && (!defined(__SIZEOF_LONG__) || (__SIZEOF_LONG__ == 8)) # define C448_WORD_BITS 64 /* The number of bits in a word */ # else # define C448_WORD_BITS 32 /* The number of bits in a word */ # endif # endif # if C448_WORD_BITS == 64 /* Word size for internal computations */ typedef uint64_t c448_word_t; /* Signed word size for internal computations */ typedef int64_t c448_sword_t; /* "Boolean" type, will be set to all-zero or all-one (i.e. -1u) */ typedef uint64_t c448_bool_t; /* Double-word size for internal computations */ typedef uint128_t c448_dword_t; /* Signed double-word size for internal computations */ typedef int128_t c448_dsword_t; # elif C448_WORD_BITS == 32 /* Word size for internal computations */ typedef uint32_t c448_word_t; /* Signed word size for internal computations */ typedef int32_t c448_sword_t; /* "Boolean" type, will be set to all-zero or all-one (i.e. -1u) */ typedef uint32_t c448_bool_t; /* Double-word size for internal computations */ typedef uint64_t c448_dword_t; /* Signed double-word size for internal computations */ typedef int64_t c448_dsword_t; # else # error "Only supporting C448_WORD_BITS = 32 or 64 for now" # endif /* C448_TRUE = -1 so that C448_TRUE & x = x */ # define C448_TRUE (0 - (c448_bool_t)1) /* C448_FALSE = 0 so that C448_FALSE & x = 0 */ # define C448_FALSE 0 /* Another boolean type used to indicate success or failure. */ typedef enum { C448_SUCCESS = -1, /**< The operation succeeded. */ C448_FAILURE = 0 /**< The operation failed. */ } c448_error_t; /* Return success if x is true */ static ossl_inline c448_error_t c448_succeed_if(c448_bool_t x) { return (c448_error_t) x; } #endif /* __C448_COMMON_H__ */
2,775
32.445783
79
h
openssl
openssl-master/crypto/ec/curve448/ed448.h
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2015-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_ED448_H # define OSSL_CRYPTO_EC_CURVE448_ED448_H # include "point_448.h" /* Number of bytes in an EdDSA public key. */ # define EDDSA_448_PUBLIC_BYTES 57 /* Number of bytes in an EdDSA private key. */ # define EDDSA_448_PRIVATE_BYTES EDDSA_448_PUBLIC_BYTES /* Number of bytes in an EdDSA private key. */ # define EDDSA_448_SIGNATURE_BYTES (EDDSA_448_PUBLIC_BYTES + \ EDDSA_448_PRIVATE_BYTES) /* EdDSA encoding ratio. */ # define C448_EDDSA_ENCODE_RATIO 4 /* EdDSA decoding ratio. */ # define C448_EDDSA_DECODE_RATIO (4 / 4) /* * EdDSA key generation. This function uses a different (non-Decaf) encoding. * * pubkey (out): The public key. * privkey (in): The private key. */ c448_error_t ossl_c448_ed448_derive_public_key( OSSL_LIB_CTX *ctx, uint8_t pubkey [EDDSA_448_PUBLIC_BYTES], const uint8_t privkey [EDDSA_448_PRIVATE_BYTES], const char *propq); /* * EdDSA signing. * * signature (out): The signature. * privkey (in): The private key. * pubkey (in): The public key. * message (in): The message to sign. * message_len (in): The length of the message. * prehashed (in): Nonzero if the message is actually the hash of something * you want to sign. * context (in): A "context" for this signature of up to 255 bytes. * context_len (in): Length of the context. * * For Ed25519, it is unsafe to use the same key for both prehashed and * non-prehashed messages, at least without some very careful protocol-level * disambiguation. For Ed448 it is safe. */ c448_error_t ossl_c448_ed448_sign(OSSL_LIB_CTX *ctx, uint8_t signature[EDDSA_448_SIGNATURE_BYTES], const uint8_t privkey[EDDSA_448_PRIVATE_BYTES], const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], const uint8_t *message, size_t message_len, uint8_t prehashed, const uint8_t *context, size_t context_len, const char *propq); /* * EdDSA signing with prehash. * * signature (out): The signature. * privkey (in): The private key. * pubkey (in): The public key. * hash (in): The hash of the message. This object will not be modified by the * call. * context (in): A "context" for this signature of up to 255 bytes. Must be the * same as what was used for the prehash. * context_len (in): Length of the context. * * For Ed25519, it is unsafe to use the same key for both prehashed and * non-prehashed messages, at least without some very careful protocol-level * disambiguation. For Ed448 it is safe. */ c448_error_t ossl_c448_ed448_sign_prehash(OSSL_LIB_CTX *ctx, uint8_t signature[EDDSA_448_SIGNATURE_BYTES], const uint8_t privkey[EDDSA_448_PRIVATE_BYTES], const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], const uint8_t hash[64], const uint8_t *context, size_t context_len, const char *propq); /* * EdDSA signature verification. * * Uses the standard (i.e. less-strict) verification formula. * * signature (in): The signature. * pubkey (in): The public key. * message (in): The message to verify. * message_len (in): The length of the message. * prehashed (in): Nonzero if the message is actually the hash of something you * want to verify. * context (in): A "context" for this signature of up to 255 bytes. * context_len (in): Length of the context. * * For Ed25519, it is unsafe to use the same key for both prehashed and * non-prehashed messages, at least without some very careful protocol-level * disambiguation. For Ed448 it is safe. */ c448_error_t ossl_c448_ed448_verify(OSSL_LIB_CTX *ctx, const uint8_t signature[EDDSA_448_SIGNATURE_BYTES], const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], const uint8_t *message, size_t message_len, uint8_t prehashed, const uint8_t *context, uint8_t context_len, const char *propq); /* * EdDSA signature verification. * * Uses the standard (i.e. less-strict) verification formula. * * signature (in): The signature. * pubkey (in): The public key. * hash (in): The hash of the message. This object will not be modified by the * call. * context (in): A "context" for this signature of up to 255 bytes. Must be the * same as what was used for the prehash. * context_len (in): Length of the context. * * For Ed25519, it is unsafe to use the same key for both prehashed and * non-prehashed messages, at least without some very careful protocol-level * disambiguation. For Ed448 it is safe. */ c448_error_t ossl_c448_ed448_verify_prehash( OSSL_LIB_CTX *ctx, const uint8_t signature[EDDSA_448_SIGNATURE_BYTES], const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], const uint8_t hash[64], const uint8_t *context, uint8_t context_len, const char *propq); /* * EdDSA point encoding. Used internally, exposed externally. * Multiplies by C448_EDDSA_ENCODE_RATIO first. * * The multiplication is required because the EdDSA encoding represents * the cofactor information, but the Decaf encoding ignores it (which * is the whole point). So if you decode from EdDSA and re-encode to * EdDSA, the cofactor info must get cleared, because the intermediate * representation doesn't track it. * * The way we handle this is to multiply by C448_EDDSA_DECODE_RATIO when * decoding, and by C448_EDDSA_ENCODE_RATIO when encoding. The product of * these ratios is always exactly the cofactor 4, so the cofactor ends up * cleared one way or another. But exactly how that shakes out depends on the * base points specified in RFC 8032. * * The upshot is that if you pass the Decaf/Ristretto base point to * this function, you will get C448_EDDSA_ENCODE_RATIO times the * EdDSA base point. * * enc (out): The encoded point. * p (in): The point. */ void ossl_curve448_point_mul_by_ratio_and_encode_like_eddsa( uint8_t enc [EDDSA_448_PUBLIC_BYTES], const curve448_point_t p); /* * EdDSA point decoding. Multiplies by C448_EDDSA_DECODE_RATIO, and * ignores cofactor information. * * See notes on curve448_point_mul_by_ratio_and_encode_like_eddsa * * enc (out): The encoded point. * p (in): The point. */ c448_error_t ossl_curve448_point_decode_like_eddsa_and_mul_by_ratio( curve448_point_t p, const uint8_t enc[EDDSA_448_PUBLIC_BYTES]); /* * EdDSA to ECDH private key conversion * Using the appropriate hash function, hash the EdDSA private key * and keep only the lower bytes to get the ECDH private key * * x (out): The ECDH private key as in RFC7748 * ed (in): The EdDSA private key */ c448_error_t ossl_c448_ed448_convert_private_key_to_x448( OSSL_LIB_CTX *ctx, uint8_t x[X448_PRIVATE_BYTES], const uint8_t ed[EDDSA_448_PRIVATE_BYTES], const char *propq); #endif /* OSSL_CRYPTO_EC_CURVE448_ED448_H */
8,214
37.38785
80
h
openssl
openssl-master/crypto/ec/curve448/eddsa.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2015-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 */ #include <string.h> #include <openssl/crypto.h> #include <openssl/evp.h> #include "crypto/ecx.h" #include "curve448_local.h" #include "word.h" #include "ed448.h" #include "internal/numbers.h" #define COFACTOR 4 static c448_error_t oneshot_hash(OSSL_LIB_CTX *ctx, uint8_t *out, size_t outlen, const uint8_t *in, size_t inlen, const char *propq) { EVP_MD_CTX *hashctx = EVP_MD_CTX_new(); EVP_MD *shake256 = NULL; c448_error_t ret = C448_FAILURE; if (hashctx == NULL) return C448_FAILURE; shake256 = EVP_MD_fetch(ctx, "SHAKE256", propq); if (shake256 == NULL) goto err; if (!EVP_DigestInit_ex(hashctx, shake256, NULL) || !EVP_DigestUpdate(hashctx, in, inlen) || !EVP_DigestFinalXOF(hashctx, out, outlen)) goto err; ret = C448_SUCCESS; err: EVP_MD_CTX_free(hashctx); EVP_MD_free(shake256); return ret; } static void clamp(uint8_t secret_scalar_ser[EDDSA_448_PRIVATE_BYTES]) { secret_scalar_ser[0] &= -COFACTOR; secret_scalar_ser[EDDSA_448_PRIVATE_BYTES - 1] = 0; secret_scalar_ser[EDDSA_448_PRIVATE_BYTES - 2] |= 0x80; } static c448_error_t hash_init_with_dom(OSSL_LIB_CTX *ctx, EVP_MD_CTX *hashctx, uint8_t prehashed, uint8_t for_prehash, const uint8_t *context, size_t context_len, const char *propq) { /* ASCII: "SigEd448", in hex for EBCDIC compatibility */ const char dom_s[] = "\x53\x69\x67\x45\x64\x34\x34\x38"; uint8_t dom[2]; EVP_MD *shake256 = NULL; if (context_len > UINT8_MAX) return C448_FAILURE; dom[0] = (uint8_t)(2 - (prehashed == 0 ? 1 : 0) - (for_prehash == 0 ? 1 : 0)); dom[1] = (uint8_t)context_len; shake256 = EVP_MD_fetch(ctx, "SHAKE256", propq); if (shake256 == NULL) return C448_FAILURE; if (!EVP_DigestInit_ex(hashctx, shake256, NULL) || !EVP_DigestUpdate(hashctx, dom_s, sizeof(dom_s)-1) || !EVP_DigestUpdate(hashctx, dom, sizeof(dom)) || !EVP_DigestUpdate(hashctx, context, context_len)) { EVP_MD_free(shake256); return C448_FAILURE; } EVP_MD_free(shake256); return C448_SUCCESS; } /* In this file because it uses the hash */ c448_error_t ossl_c448_ed448_convert_private_key_to_x448( OSSL_LIB_CTX *ctx, uint8_t x[X448_PRIVATE_BYTES], const uint8_t ed [EDDSA_448_PRIVATE_BYTES], const char *propq) { /* pass the private key through oneshot_hash function */ /* and keep the first X448_PRIVATE_BYTES bytes */ return oneshot_hash(ctx, x, X448_PRIVATE_BYTES, ed, EDDSA_448_PRIVATE_BYTES, propq); } c448_error_t ossl_c448_ed448_derive_public_key( OSSL_LIB_CTX *ctx, uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], const uint8_t privkey[EDDSA_448_PRIVATE_BYTES], const char *propq) { /* only this much used for keygen */ uint8_t secret_scalar_ser[EDDSA_448_PRIVATE_BYTES]; curve448_scalar_t secret_scalar; unsigned int c; curve448_point_t p; if (!oneshot_hash(ctx, secret_scalar_ser, sizeof(secret_scalar_ser), privkey, EDDSA_448_PRIVATE_BYTES, propq)) return C448_FAILURE; clamp(secret_scalar_ser); ossl_curve448_scalar_decode_long(secret_scalar, secret_scalar_ser, sizeof(secret_scalar_ser)); /* * Since we are going to mul_by_cofactor during encoding, divide by it * here. However, the EdDSA base point is not the same as the decaf base * point if the sigma isogeny is in use: the EdDSA base point is on * Etwist_d/(1-d) and the decaf base point is on Etwist_d, and when * converted it effectively picks up a factor of 2 from the isogenies. So * we might start at 2 instead of 1. */ for (c = 1; c < C448_EDDSA_ENCODE_RATIO; c <<= 1) ossl_curve448_scalar_halve(secret_scalar, secret_scalar); ossl_curve448_precomputed_scalarmul(p, ossl_curve448_precomputed_base, secret_scalar); ossl_curve448_point_mul_by_ratio_and_encode_like_eddsa(pubkey, p); /* Cleanup */ ossl_curve448_scalar_destroy(secret_scalar); ossl_curve448_point_destroy(p); OPENSSL_cleanse(secret_scalar_ser, sizeof(secret_scalar_ser)); return C448_SUCCESS; } c448_error_t ossl_c448_ed448_sign(OSSL_LIB_CTX *ctx, uint8_t signature[EDDSA_448_SIGNATURE_BYTES], const uint8_t privkey[EDDSA_448_PRIVATE_BYTES], const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], const uint8_t *message, size_t message_len, uint8_t prehashed, const uint8_t *context, size_t context_len, const char *propq) { curve448_scalar_t secret_scalar; EVP_MD_CTX *hashctx = EVP_MD_CTX_new(); c448_error_t ret = C448_FAILURE; curve448_scalar_t nonce_scalar; uint8_t nonce_point[EDDSA_448_PUBLIC_BYTES] = { 0 }; unsigned int c; curve448_scalar_t challenge_scalar; if (hashctx == NULL) return C448_FAILURE; { /* * Schedule the secret key, First EDDSA_448_PRIVATE_BYTES is serialized * secret scalar,next EDDSA_448_PRIVATE_BYTES bytes is the seed. */ uint8_t expanded[EDDSA_448_PRIVATE_BYTES * 2]; if (!oneshot_hash(ctx, expanded, sizeof(expanded), privkey, EDDSA_448_PRIVATE_BYTES, propq)) goto err; clamp(expanded); ossl_curve448_scalar_decode_long(secret_scalar, expanded, EDDSA_448_PRIVATE_BYTES); /* Hash to create the nonce */ if (!hash_init_with_dom(ctx, hashctx, prehashed, 0, context, context_len, propq) || !EVP_DigestUpdate(hashctx, expanded + EDDSA_448_PRIVATE_BYTES, EDDSA_448_PRIVATE_BYTES) || !EVP_DigestUpdate(hashctx, message, message_len)) { OPENSSL_cleanse(expanded, sizeof(expanded)); goto err; } OPENSSL_cleanse(expanded, sizeof(expanded)); } /* Decode the nonce */ { uint8_t nonce[2 * EDDSA_448_PRIVATE_BYTES]; if (!EVP_DigestFinalXOF(hashctx, nonce, sizeof(nonce))) goto err; ossl_curve448_scalar_decode_long(nonce_scalar, nonce, sizeof(nonce)); OPENSSL_cleanse(nonce, sizeof(nonce)); } { /* Scalarmul to create the nonce-point */ curve448_scalar_t nonce_scalar_2; curve448_point_t p; ossl_curve448_scalar_halve(nonce_scalar_2, nonce_scalar); for (c = 2; c < C448_EDDSA_ENCODE_RATIO; c <<= 1) ossl_curve448_scalar_halve(nonce_scalar_2, nonce_scalar_2); ossl_curve448_precomputed_scalarmul(p, ossl_curve448_precomputed_base, nonce_scalar_2); ossl_curve448_point_mul_by_ratio_and_encode_like_eddsa(nonce_point, p); ossl_curve448_point_destroy(p); ossl_curve448_scalar_destroy(nonce_scalar_2); } { uint8_t challenge[2 * EDDSA_448_PRIVATE_BYTES]; /* Compute the challenge */ if (!hash_init_with_dom(ctx, hashctx, prehashed, 0, context, context_len, propq) || !EVP_DigestUpdate(hashctx, nonce_point, sizeof(nonce_point)) || !EVP_DigestUpdate(hashctx, pubkey, EDDSA_448_PUBLIC_BYTES) || !EVP_DigestUpdate(hashctx, message, message_len) || !EVP_DigestFinalXOF(hashctx, challenge, sizeof(challenge))) goto err; ossl_curve448_scalar_decode_long(challenge_scalar, challenge, sizeof(challenge)); OPENSSL_cleanse(challenge, sizeof(challenge)); } ossl_curve448_scalar_mul(challenge_scalar, challenge_scalar, secret_scalar); ossl_curve448_scalar_add(challenge_scalar, challenge_scalar, nonce_scalar); OPENSSL_cleanse(signature, EDDSA_448_SIGNATURE_BYTES); memcpy(signature, nonce_point, sizeof(nonce_point)); ossl_curve448_scalar_encode(&signature[EDDSA_448_PUBLIC_BYTES], challenge_scalar); ossl_curve448_scalar_destroy(secret_scalar); ossl_curve448_scalar_destroy(nonce_scalar); ossl_curve448_scalar_destroy(challenge_scalar); ret = C448_SUCCESS; err: EVP_MD_CTX_free(hashctx); return ret; } c448_error_t ossl_c448_ed448_sign_prehash( OSSL_LIB_CTX *ctx, uint8_t signature[EDDSA_448_SIGNATURE_BYTES], const uint8_t privkey[EDDSA_448_PRIVATE_BYTES], const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], const uint8_t hash[64], const uint8_t *context, size_t context_len, const char *propq) { return ossl_c448_ed448_sign(ctx, signature, privkey, pubkey, hash, 64, 1, context, context_len, propq); } c448_error_t ossl_c448_ed448_verify( OSSL_LIB_CTX *ctx, const uint8_t signature[EDDSA_448_SIGNATURE_BYTES], const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], const uint8_t *message, size_t message_len, uint8_t prehashed, const uint8_t *context, uint8_t context_len, const char *propq) { curve448_point_t pk_point, r_point; c448_error_t error; curve448_scalar_t challenge_scalar; curve448_scalar_t response_scalar; /* Order in little endian format */ static const uint8_t order[] = { 0xF3, 0x44, 0x58, 0xAB, 0x92, 0xC2, 0x78, 0x23, 0x55, 0x8F, 0xC5, 0x8D, 0x72, 0xC2, 0x6C, 0x21, 0x90, 0x36, 0xD6, 0xAE, 0x49, 0xDB, 0x4E, 0xC4, 0xE9, 0x23, 0xCA, 0x7C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00 }; int i; /* * Check that s (second 57 bytes of the sig) is less than the order. Both * s and the order are in little-endian format. This can be done in * variable time, since if this is not the case the signature if publicly * invalid. */ for (i = EDDSA_448_PUBLIC_BYTES - 1; i >= 0; i--) { if (signature[i + EDDSA_448_PUBLIC_BYTES] > order[i]) return C448_FAILURE; if (signature[i + EDDSA_448_PUBLIC_BYTES] < order[i]) break; } if (i < 0) return C448_FAILURE; error = ossl_curve448_point_decode_like_eddsa_and_mul_by_ratio(pk_point, pubkey); if (C448_SUCCESS != error) return error; error = ossl_curve448_point_decode_like_eddsa_and_mul_by_ratio(r_point, signature); if (C448_SUCCESS != error) return error; { /* Compute the challenge */ EVP_MD_CTX *hashctx = EVP_MD_CTX_new(); uint8_t challenge[2 * EDDSA_448_PRIVATE_BYTES]; if (hashctx == NULL || !hash_init_with_dom(ctx, hashctx, prehashed, 0, context, context_len, propq) || !EVP_DigestUpdate(hashctx, signature, EDDSA_448_PUBLIC_BYTES) || !EVP_DigestUpdate(hashctx, pubkey, EDDSA_448_PUBLIC_BYTES) || !EVP_DigestUpdate(hashctx, message, message_len) || !EVP_DigestFinalXOF(hashctx, challenge, sizeof(challenge))) { EVP_MD_CTX_free(hashctx); return C448_FAILURE; } EVP_MD_CTX_free(hashctx); ossl_curve448_scalar_decode_long(challenge_scalar, challenge, sizeof(challenge)); OPENSSL_cleanse(challenge, sizeof(challenge)); } ossl_curve448_scalar_sub(challenge_scalar, ossl_curve448_scalar_zero, challenge_scalar); ossl_curve448_scalar_decode_long(response_scalar, &signature[EDDSA_448_PUBLIC_BYTES], EDDSA_448_PRIVATE_BYTES); /* pk_point = -c(x(P)) + (cx + k)G = kG */ ossl_curve448_base_double_scalarmul_non_secret(pk_point, response_scalar, pk_point, challenge_scalar); return c448_succeed_if(ossl_curve448_point_eq(pk_point, r_point)); } c448_error_t ossl_c448_ed448_verify_prehash( OSSL_LIB_CTX *ctx, const uint8_t signature[EDDSA_448_SIGNATURE_BYTES], const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], const uint8_t hash[64], const uint8_t *context, uint8_t context_len, const char *propq) { return ossl_c448_ed448_verify(ctx, signature, pubkey, hash, 64, 1, context, context_len, propq); } int ossl_ed448_sign(OSSL_LIB_CTX *ctx, uint8_t *out_sig, const uint8_t *message, size_t message_len, const uint8_t public_key[57], const uint8_t private_key[57], const uint8_t *context, size_t context_len, const uint8_t phflag, const char *propq) { return ossl_c448_ed448_sign(ctx, out_sig, private_key, public_key, message, message_len, phflag, context, context_len, propq) == C448_SUCCESS; } int ossl_ed448_verify(OSSL_LIB_CTX *ctx, const uint8_t *message, size_t message_len, const uint8_t signature[114], const uint8_t public_key[57], const uint8_t *context, size_t context_len, const uint8_t phflag, const char *propq) { return ossl_c448_ed448_verify(ctx, signature, public_key, message, message_len, phflag, context, (uint8_t)context_len, propq) == C448_SUCCESS; } int ossl_ed448_public_from_private(OSSL_LIB_CTX *ctx, uint8_t out_public_key[57], const uint8_t private_key[57], const char *propq) { return ossl_c448_ed448_derive_public_key(ctx, out_public_key, private_key, propq) == C448_SUCCESS; }
15,265
36.975124
85
c
openssl
openssl-master/crypto/ec/curve448/f_generic.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2015-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 */ #include "field.h" static const gf MODULUS = { FIELD_LITERAL(0xffffffffffffffULL, 0xffffffffffffffULL, 0xffffffffffffffULL, 0xffffffffffffffULL, 0xfffffffffffffeULL, 0xffffffffffffffULL, 0xffffffffffffffULL, 0xffffffffffffffULL) }; /* Serialize to wire format. */ void gf_serialize(uint8_t serial[SER_BYTES], const gf x, int with_hibit) { unsigned int j = 0, fill = 0; dword_t buffer = 0; int i; gf red; gf_copy(red, x); gf_strong_reduce(red); if (!with_hibit) assert(gf_hibit(red) == 0); for (i = 0; i < (with_hibit ? X_SER_BYTES : SER_BYTES); i++) { if (fill < 8 && j < NLIMBS) { buffer |= ((dword_t) red->limb[LIMBPERM(j)]) << fill; fill += LIMB_PLACE_VALUE(LIMBPERM(j)); j++; } serial[i] = (uint8_t)buffer; fill -= 8; buffer >>= 8; } } /* Return high bit of x = low bit of 2x mod p */ mask_t gf_hibit(const gf x) { gf y; gf_add(y, x, x); gf_strong_reduce(y); return 0 - (y->limb[0] & 1); } /* Return high bit of x = low bit of 2x mod p */ mask_t gf_lobit(const gf x) { gf y; gf_copy(y, x); gf_strong_reduce(y); return 0 - (y->limb[0] & 1); } /* Deserialize from wire format; return -1 on success and 0 on failure. */ mask_t gf_deserialize(gf x, const uint8_t serial[SER_BYTES], int with_hibit, uint8_t hi_nmask) { unsigned int j = 0, fill = 0; dword_t buffer = 0; dsword_t scarry = 0; const unsigned nbytes = with_hibit ? X_SER_BYTES : SER_BYTES; unsigned int i; mask_t succ; for (i = 0; i < NLIMBS; i++) { while (fill < LIMB_PLACE_VALUE(LIMBPERM(i)) && j < nbytes) { uint8_t sj; sj = serial[j]; if (j == nbytes - 1) sj &= ~hi_nmask; buffer |= ((dword_t) sj) << fill; fill += 8; j++; } x->limb[LIMBPERM(i)] = (word_t) ((i < NLIMBS - 1) ? buffer & LIMB_MASK(LIMBPERM(i)) : buffer); fill -= LIMB_PLACE_VALUE(LIMBPERM(i)); buffer >>= LIMB_PLACE_VALUE(LIMBPERM(i)); scarry = (scarry + x->limb[LIMBPERM(i)] - MODULUS->limb[LIMBPERM(i)]) >> (8 * sizeof(word_t)); } succ = with_hibit ? 0 - (mask_t) 1 : ~gf_hibit(x); return succ & word_is_zero((word_t)buffer) & ~word_is_zero((word_t)scarry); } /* Reduce to canonical form. */ void gf_strong_reduce(gf a) { dsword_t scarry; word_t scarry_0; dword_t carry = 0; unsigned int i; /* first, clear high */ gf_weak_reduce(a); /* Determined to have negligible perf impact. */ /* now the total is less than 2p */ /* compute total_value - p. No need to reduce mod p. */ scarry = 0; for (i = 0; i < NLIMBS; i++) { scarry = scarry + a->limb[LIMBPERM(i)] - MODULUS->limb[LIMBPERM(i)]; a->limb[LIMBPERM(i)] = scarry & LIMB_MASK(LIMBPERM(i)); scarry >>= LIMB_PLACE_VALUE(LIMBPERM(i)); } /* * uncommon case: it was >= p, so now scarry = 0 and this = x common case: * it was < p, so now scarry = -1 and this = x - p + 2^255 so let's add * back in p. will carry back off the top for 2^255. */ assert(scarry == 0 || scarry == -1); scarry_0 = (word_t)scarry; /* add it back */ for (i = 0; i < NLIMBS; i++) { carry = carry + a->limb[LIMBPERM(i)] + (scarry_0 & MODULUS->limb[LIMBPERM(i)]); a->limb[LIMBPERM(i)] = carry & LIMB_MASK(LIMBPERM(i)); carry >>= LIMB_PLACE_VALUE(LIMBPERM(i)); } assert(carry < 2 && ((word_t)carry + scarry_0) == 0); } /* Subtract two gf elements d=a-b */ void gf_sub(gf d, const gf a, const gf b) { gf_sub_RAW(d, a, b); gf_bias(d, 2); gf_weak_reduce(d); } /* Add two field elements d = a+b */ void gf_add(gf d, const gf a, const gf b) { gf_add_RAW(d, a, b); gf_weak_reduce(d); } /* Compare a==b */ mask_t gf_eq(const gf a, const gf b) { gf c; mask_t ret = 0; unsigned int i; gf_sub(c, a, b); gf_strong_reduce(c); for (i = 0; i < NLIMBS; i++) ret |= c->limb[LIMBPERM(i)]; return word_is_zero(ret); } mask_t gf_isr(gf a, const gf x) { gf L0, L1, L2; ossl_gf_sqr(L1, x); ossl_gf_mul(L2, x, L1); ossl_gf_sqr(L1, L2); ossl_gf_mul(L2, x, L1); gf_sqrn(L1, L2, 3); ossl_gf_mul(L0, L2, L1); gf_sqrn(L1, L0, 3); ossl_gf_mul(L0, L2, L1); gf_sqrn(L2, L0, 9); ossl_gf_mul(L1, L0, L2); ossl_gf_sqr(L0, L1); ossl_gf_mul(L2, x, L0); gf_sqrn(L0, L2, 18); ossl_gf_mul(L2, L1, L0); gf_sqrn(L0, L2, 37); ossl_gf_mul(L1, L2, L0); gf_sqrn(L0, L1, 37); ossl_gf_mul(L1, L2, L0); gf_sqrn(L0, L1, 111); ossl_gf_mul(L2, L1, L0); ossl_gf_sqr(L0, L2); ossl_gf_mul(L1, x, L0); gf_sqrn(L0, L1, 223); ossl_gf_mul(L1, L2, L0); ossl_gf_sqr(L2, L1); ossl_gf_mul(L0, L2, x); gf_copy(a, L1); return gf_eq(L0, ONE); }
5,460
25.639024
80
c
openssl
openssl-master/crypto/ec/curve448/field.h
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2014 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_FIELD_H # define OSSL_CRYPTO_EC_CURVE448_FIELD_H # include "internal/constant_time.h" # include <string.h> # include <assert.h> # include "word.h" # define NLIMBS (64/sizeof(word_t)) # define X_SER_BYTES 56 # define SER_BYTES 56 # if defined(__GNUC__) || defined(__clang__) # define INLINE_UNUSED __inline__ __attribute__((__unused__,__always_inline__)) # define RESTRICT __restrict__ # define ALIGNED __attribute__((__aligned__(16))) # else # define INLINE_UNUSED ossl_inline # define RESTRICT # define ALIGNED # endif typedef struct gf_s { word_t limb[NLIMBS]; } ALIGNED gf_s, gf[1]; /* RFC 7748 support */ # define X_PUBLIC_BYTES X_SER_BYTES # define X_PRIVATE_BYTES X_PUBLIC_BYTES # define X_PRIVATE_BITS 448 static INLINE_UNUSED void gf_copy(gf out, const gf a) { *out = *a; } static INLINE_UNUSED void gf_add_RAW(gf out, const gf a, const gf b); static INLINE_UNUSED void gf_sub_RAW(gf out, const gf a, const gf b); static INLINE_UNUSED void gf_bias(gf inout, int amount); static INLINE_UNUSED void gf_weak_reduce(gf inout); void gf_strong_reduce(gf inout); void gf_add(gf out, const gf a, const gf b); void gf_sub(gf out, const gf a, const gf b); void ossl_gf_mul(gf_s * RESTRICT out, const gf a, const gf b); void ossl_gf_mulw_unsigned(gf_s * RESTRICT out, const gf a, uint32_t b); void ossl_gf_sqr(gf_s * RESTRICT out, const gf a); mask_t gf_isr(gf a, const gf x); /** a^2 x = 1, QNR, or 0 if x=0. Return true if successful */ mask_t gf_eq(const gf x, const gf y); mask_t gf_lobit(const gf x); mask_t gf_hibit(const gf x); void gf_serialize(uint8_t serial[SER_BYTES], const gf x, int with_highbit); mask_t gf_deserialize(gf x, const uint8_t serial[SER_BYTES], int with_hibit, uint8_t hi_nmask); # define LIMBPERM(i) (i) # if (ARCH_WORD_BITS == 32) # include "arch_32/f_impl.h" /* Bring in the inline implementations */ # define LIMB_MASK(i) (((1)<<LIMB_PLACE_VALUE(i))-1) # elif (ARCH_WORD_BITS == 64) # include "arch_64/f_impl.h" /* Bring in the inline implementations */ # define LIMB_MASK(i) (((1ULL)<<LIMB_PLACE_VALUE(i))-1) # endif static const gf ZERO = {{{0}}}, ONE = {{{1}}}; /* Square x, n times. */ static ossl_inline void gf_sqrn(gf_s * RESTRICT y, const gf x, int n) { gf tmp; assert(n > 0); if (n & 1) { ossl_gf_sqr(y, x); n--; } else { ossl_gf_sqr(tmp, x); ossl_gf_sqr(y, tmp); n -= 2; } for (; n; n -= 2) { ossl_gf_sqr(tmp, y); ossl_gf_sqr(y, tmp); } } # define gf_add_nr gf_add_RAW /* Subtract mod p. Bias by 2 and don't reduce */ static ossl_inline void gf_sub_nr(gf c, const gf a, const gf b) { gf_sub_RAW(c, a, b); gf_bias(c, 2); if (GF_HEADROOM < 3) gf_weak_reduce(c); } /* Subtract mod p. Bias by amt but don't reduce. */ static ossl_inline void gf_subx_nr(gf c, const gf a, const gf b, int amt) { gf_sub_RAW(c, a, b); gf_bias(c, amt); if (GF_HEADROOM < amt + 1) gf_weak_reduce(c); } /* Mul by signed int. Not constant-time WRT the sign of that int. */ static ossl_inline void gf_mulw(gf c, const gf a, int32_t w) { if (w > 0) { ossl_gf_mulw_unsigned(c, a, w); } else { ossl_gf_mulw_unsigned(c, a, -w); gf_sub(c, ZERO, c); } } /* Constant time, x = is_z ? z : y */ static ossl_inline void gf_cond_sel(gf x, const gf y, const gf z, mask_t is_z) { size_t i; for (i = 0; i < NLIMBS; i++) { #if ARCH_WORD_BITS == 32 x[0].limb[i] = constant_time_select_32(is_z, z[0].limb[i], y[0].limb[i]); #else /* Must be 64 bit */ x[0].limb[i] = constant_time_select_64(is_z, z[0].limb[i], y[0].limb[i]); #endif } } /* Constant time, if (neg) x=-x; */ static ossl_inline void gf_cond_neg(gf x, mask_t neg) { gf y; gf_sub(y, ZERO, x); gf_cond_sel(x, x, y, neg); } /* Constant time, if (swap) (x,y) = (y,x); */ static ossl_inline void gf_cond_swap(gf x, gf_s * RESTRICT y, mask_t swap) { size_t i; for (i = 0; i < NLIMBS; i++) { #if ARCH_WORD_BITS == 32 constant_time_cond_swap_32(swap, &(x[0].limb[i]), &(y->limb[i])); #else /* Must be 64 bit */ constant_time_cond_swap_64(swap, &(x[0].limb[i]), &(y->limb[i])); #endif } } #endif /* OSSL_CRYPTO_EC_CURVE448_FIELD_H */
4,876
27.028736
95
h
openssl
openssl-master/crypto/ec/curve448/point_448.h
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2015-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_POINT_448_H # define OSSL_CRYPTO_EC_CURVE448_POINT_448_H # include "curve448utils.h" # include "field.h" /* Comb config: number of combs, n, t, s. */ #define COMBS_N 5 #define COMBS_T 5 #define COMBS_S 18 /* Projective Niels coordinates */ typedef struct { gf a, b, c; } niels_s, niels_t[1]; typedef struct { niels_t n; gf z; } pniels_t[1]; /* Precomputed base */ struct curve448_precomputed_s { niels_t table[COMBS_N << (COMBS_T - 1)]; }; # define C448_SCALAR_LIMBS ((446-1)/C448_WORD_BITS+1) /* The number of bits in a scalar */ # define C448_SCALAR_BITS 446 /* Number of bytes in a serialized scalar. */ # define C448_SCALAR_BYTES 56 /* X448 encoding ratio. */ # define X448_ENCODE_RATIO 2 /* Number of bytes in an x448 public key */ # define X448_PUBLIC_BYTES 56 /* Number of bytes in an x448 private key */ # define X448_PRIVATE_BYTES 56 /* Twisted Edwards extended homogeneous coordinates */ typedef struct curve448_point_s { gf x, y, z, t; } curve448_point_t[1]; /* Precomputed table based on a point. Can be trivial implementation. */ struct curve448_precomputed_s; /* Precomputed table based on a point. Can be trivial implementation. */ typedef struct curve448_precomputed_s curve448_precomputed_s; /* Scalar is stored packed, because we don't need the speed. */ typedef struct curve448_scalar_s { c448_word_t limb[C448_SCALAR_LIMBS]; } curve448_scalar_t[1]; /* A scalar equal to 1. */ extern const curve448_scalar_t ossl_curve448_scalar_one; /* A scalar equal to 0. */ extern const curve448_scalar_t ossl_curve448_scalar_zero; /* The identity point on the curve. */ extern const curve448_point_t ossl_curve448_point_identity; /* Precomputed table for the base point on the curve. */ extern const struct curve448_precomputed_s *ossl_curve448_precomputed_base; extern const niels_t *ossl_curve448_wnaf_base; /* * Read a scalar from wire format or from bytes. * * ser (in): Serialized form of a scalar. * out (out): Deserialized form. * * Returns: * C448_SUCCESS: The scalar was correctly encoded. * C448_FAILURE: The scalar was greater than the modulus, and has been reduced * modulo that modulus. */ c448_error_t ossl_curve448_scalar_decode(curve448_scalar_t out, const unsigned char ser[C448_SCALAR_BYTES]); /* * Read a scalar from wire format or from bytes. Reduces mod scalar prime. * * ser (in): Serialized form of a scalar. * ser_len (in): Length of serialized form. * out (out): Deserialized form. */ void ossl_curve448_scalar_decode_long(curve448_scalar_t out, const unsigned char *ser, size_t ser_len); /* * Serialize a scalar to wire format. * * ser (out): Serialized form of a scalar. * s (in): Deserialized scalar. */ void ossl_curve448_scalar_encode(unsigned char ser[C448_SCALAR_BYTES], const curve448_scalar_t s); /* * Add two scalars. |a|, |b| and |out| may alias each other. * * a (in): One scalar. * b (in): Another scalar. * out (out): a+b. */ void ossl_curve448_scalar_add(curve448_scalar_t out, const curve448_scalar_t a, const curve448_scalar_t b); /* * Subtract two scalars. |a|, |b| and |out| may alias each other. * a (in): One scalar. * b (in): Another scalar. * out (out): a-b. */ void ossl_curve448_scalar_sub(curve448_scalar_t out, const curve448_scalar_t a, const curve448_scalar_t b); /* * Multiply two scalars. |a|, |b| and |out| may alias each other. * * a (in): One scalar. * b (in): Another scalar. * out (out): a*b. */ void ossl_curve448_scalar_mul(curve448_scalar_t out, const curve448_scalar_t a, const curve448_scalar_t b); /* * Halve a scalar. |a| and |out| may alias each other. * * a (in): A scalar. * out (out): a/2. */ void ossl_curve448_scalar_halve(curve448_scalar_t out, const curve448_scalar_t a); /* * Copy a scalar. The scalars may alias each other, in which case this * function does nothing. * * a (in): A scalar. * out (out): Will become a copy of a. */ static ossl_inline void curve448_scalar_copy(curve448_scalar_t out, const curve448_scalar_t a) { *out = *a; } /* * Copy a point. The input and output may alias, in which case this function * does nothing. * * a (out): A copy of the point. * b (in): Any point. */ static ossl_inline void curve448_point_copy(curve448_point_t a, const curve448_point_t b) { *a = *b; } /* * Test whether two points are equal. If yes, return C448_TRUE, else return * C448_FALSE. * * a (in): A point. * b (in): Another point. * * Returns: * C448_TRUE: The points are equal. * C448_FALSE: The points are not equal. */ __owur c448_bool_t ossl_curve448_point_eq(const curve448_point_t a, const curve448_point_t b); /* * Double a point. Equivalent to curve448_point_add(two_a,a,a), but potentially * faster. * * two_a (out): The sum a+a. * a (in): A point. */ void ossl_curve448_point_double(curve448_point_t two_a, const curve448_point_t a); /* * RFC 7748 Diffie-Hellman scalarmul. This function uses a different * (non-Decaf) encoding. * * out (out): The scaled point base*scalar * base (in): The point to be scaled. * scalar (in): The scalar to multiply by. * * Returns: * C448_SUCCESS: The scalarmul succeeded. * C448_FAILURE: The scalarmul didn't succeed, because the base point is in a * small subgroup. */ __owur c448_error_t ossl_x448_int(uint8_t out[X448_PUBLIC_BYTES], const uint8_t base[X448_PUBLIC_BYTES], const uint8_t scalar[X448_PRIVATE_BYTES]); /* * Multiply a point by X448_ENCODE_RATIO, then encode it like RFC 7748. * * This function is mainly used internally, but is exported in case * it will be useful. * * The ratio is necessary because the internal representation doesn't * track the cofactor information, so on output we must clear the cofactor. * This would multiply by the cofactor, but in fact internally points are always * even, so it multiplies by half the cofactor instead. * * As it happens, this aligns with the base point definitions; that is, * if you pass the Decaf/Ristretto base point to this function, the result * will be X448_ENCODE_RATIO times the X448 * base point. * * out (out): The scaled and encoded point. * p (in): The point to be scaled and encoded. */ void ossl_curve448_point_mul_by_ratio_and_encode_like_x448( uint8_t out[X448_PUBLIC_BYTES], const curve448_point_t p); /* * RFC 7748 Diffie-Hellman base point scalarmul. This function uses a different * (non-Decaf) encoding. * * out (out): The scaled point base*scalar * scalar (in): The scalar to multiply by. */ void ossl_x448_derive_public_key(uint8_t out[X448_PUBLIC_BYTES], const uint8_t scalar[X448_PRIVATE_BYTES]); /* * Multiply a precomputed base point by a scalar: out = scalar*base. * * scaled (out): The scaled point base*scalar * base (in): The point to be scaled. * scalar (in): The scalar to multiply by. */ void ossl_curve448_precomputed_scalarmul(curve448_point_t scaled, const curve448_precomputed_s * base, const curve448_scalar_t scalar); /* * Multiply two base points by two scalars: * combo = scalar1*curve448_point_base + scalar2*base2. * * Otherwise equivalent to curve448_point_double_scalarmul, but may be * faster at the expense of being variable time. * * combo (out): The linear combination scalar1*base + scalar2*base2. * scalar1 (in): A first scalar to multiply by. * base2 (in): A second point to be scaled. * scalar2 (in) A second scalar to multiply by. * * Warning: This function takes variable time, and may leak the scalars used. * It is designed for signature verification. */ void ossl_curve448_base_double_scalarmul_non_secret(curve448_point_t combo, const curve448_scalar_t scalar1, const curve448_point_t base2, const curve448_scalar_t scalar2); /* * Test that a point is valid, for debugging purposes. * * to_test (in): The point to test. * * Returns: * C448_TRUE The point is valid. * C448_FALSE The point is invalid. */ __owur c448_bool_t ossl_curve448_point_valid(const curve448_point_t to_test); /* Overwrite scalar with zeros. */ void ossl_curve448_scalar_destroy(curve448_scalar_t scalar); /* Overwrite point with zeros. */ void ossl_curve448_point_destroy(curve448_point_t point); #endif /* OSSL_CRYPTO_EC_CURVE448_POINT_448_H */
9,293
28.318612
80
h
openssl
openssl-master/crypto/ec/curve448/scalar.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2015-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 */ #include <openssl/crypto.h> #include "word.h" #include "point_448.h" static const c448_word_t MONTGOMERY_FACTOR = (c448_word_t) 0x3bd440fae918bc5ULL; static const curve448_scalar_t sc_p = { { { SC_LIMB(0x2378c292ab5844f3ULL), SC_LIMB(0x216cc2728dc58f55ULL), SC_LIMB(0xc44edb49aed63690ULL), SC_LIMB(0xffffffff7cca23e9ULL), SC_LIMB(0xffffffffffffffffULL), SC_LIMB(0xffffffffffffffffULL), SC_LIMB(0x3fffffffffffffffULL) } } }, sc_r2 = { { { SC_LIMB(0xe3539257049b9b60ULL), SC_LIMB(0x7af32c4bc1b195d9ULL), SC_LIMB(0x0d66de2388ea1859ULL), SC_LIMB(0xae17cf725ee4d838ULL), SC_LIMB(0x1a9cc14ba3c47c44ULL), SC_LIMB(0x2052bcb7e4d070afULL), SC_LIMB(0x3402a939f823b729ULL) } } }; #define WBITS C448_WORD_BITS /* NB this may be different from ARCH_WORD_BITS */ const curve448_scalar_t ossl_curve448_scalar_one = {{{1}}}; const curve448_scalar_t ossl_curve448_scalar_zero = {{{0}}}; /* * {extra,accum} - sub +? p * Must have extra <= 1 */ static void sc_subx(curve448_scalar_t out, const c448_word_t accum[C448_SCALAR_LIMBS], const curve448_scalar_t sub, const curve448_scalar_t p, c448_word_t extra) { c448_dsword_t chain = 0; unsigned int i; c448_word_t borrow; for (i = 0; i < C448_SCALAR_LIMBS; i++) { chain = (chain + accum[i]) - sub->limb[i]; out->limb[i] = (c448_word_t)chain; chain >>= WBITS; } borrow = (c448_word_t)chain + extra; /* = 0 or -1 */ chain = 0; for (i = 0; i < C448_SCALAR_LIMBS; i++) { chain = (chain + out->limb[i]) + (p->limb[i] & borrow); out->limb[i] = (c448_word_t)chain; chain >>= WBITS; } } static void sc_montmul(curve448_scalar_t out, const curve448_scalar_t a, const curve448_scalar_t b) { unsigned int i, j; c448_word_t accum[C448_SCALAR_LIMBS + 1] = { 0 }; c448_word_t hi_carry = 0; for (i = 0; i < C448_SCALAR_LIMBS; i++) { c448_word_t mand = a->limb[i]; const c448_word_t *mier = b->limb; c448_dword_t chain = 0; for (j = 0; j < C448_SCALAR_LIMBS; j++) { chain += ((c448_dword_t) mand) * mier[j] + accum[j]; accum[j] = (c448_word_t)chain; chain >>= WBITS; } accum[j] = (c448_word_t)chain; mand = accum[0] * MONTGOMERY_FACTOR; chain = 0; mier = sc_p->limb; for (j = 0; j < C448_SCALAR_LIMBS; j++) { chain += (c448_dword_t) mand *mier[j] + accum[j]; if (j) accum[j - 1] = (c448_word_t)chain; chain >>= WBITS; } chain += accum[j]; chain += hi_carry; accum[j - 1] = (c448_word_t)chain; hi_carry = chain >> WBITS; } sc_subx(out, accum, sc_p, sc_p, hi_carry); } void ossl_curve448_scalar_mul(curve448_scalar_t out, const curve448_scalar_t a, const curve448_scalar_t b) { sc_montmul(out, a, b); sc_montmul(out, out, sc_r2); } void ossl_curve448_scalar_sub(curve448_scalar_t out, const curve448_scalar_t a, const curve448_scalar_t b) { sc_subx(out, a->limb, b, sc_p, 0); } void ossl_curve448_scalar_add(curve448_scalar_t out, const curve448_scalar_t a, const curve448_scalar_t b) { c448_dword_t chain = 0; unsigned int i; for (i = 0; i < C448_SCALAR_LIMBS; i++) { chain = (chain + a->limb[i]) + b->limb[i]; out->limb[i] = (c448_word_t)chain; chain >>= WBITS; } sc_subx(out, out->limb, sc_p, sc_p, (c448_word_t)chain); } static ossl_inline void scalar_decode_short(curve448_scalar_t s, const unsigned char *ser, size_t nbytes) { size_t i, j, k = 0; for (i = 0; i < C448_SCALAR_LIMBS; i++) { c448_word_t out = 0; for (j = 0; j < sizeof(c448_word_t) && k < nbytes; j++, k++) out |= ((c448_word_t) ser[k]) << (8 * j); s->limb[i] = out; } } c448_error_t ossl_curve448_scalar_decode(curve448_scalar_t s, const unsigned char ser[C448_SCALAR_BYTES]) { unsigned int i; c448_dsword_t accum = 0; scalar_decode_short(s, ser, C448_SCALAR_BYTES); for (i = 0; i < C448_SCALAR_LIMBS; i++) accum = (accum + s->limb[i] - sc_p->limb[i]) >> WBITS; /* Here accum == 0 or -1 */ ossl_curve448_scalar_mul(s, s, ossl_curve448_scalar_one); /* ham-handed reduce */ return c448_succeed_if(~word_is_zero((uint32_t)accum)); } void ossl_curve448_scalar_destroy(curve448_scalar_t scalar) { OPENSSL_cleanse(scalar, sizeof(curve448_scalar_t)); } void ossl_curve448_scalar_decode_long(curve448_scalar_t s, const unsigned char *ser, size_t ser_len) { size_t i; curve448_scalar_t t1, t2; if (ser_len == 0) { curve448_scalar_copy(s, ossl_curve448_scalar_zero); return; } i = ser_len - (ser_len % C448_SCALAR_BYTES); if (i == ser_len) i -= C448_SCALAR_BYTES; scalar_decode_short(t1, &ser[i], ser_len - i); if (ser_len == sizeof(curve448_scalar_t)) { assert(i == 0); /* ham-handed reduce */ ossl_curve448_scalar_mul(s, t1, ossl_curve448_scalar_one); ossl_curve448_scalar_destroy(t1); return; } while (i) { i -= C448_SCALAR_BYTES; sc_montmul(t1, t1, sc_r2); (void)ossl_curve448_scalar_decode(t2, ser + i); ossl_curve448_scalar_add(t1, t1, t2); } curve448_scalar_copy(s, t1); ossl_curve448_scalar_destroy(t1); ossl_curve448_scalar_destroy(t2); } void ossl_curve448_scalar_encode(unsigned char ser[C448_SCALAR_BYTES], const curve448_scalar_t s) { unsigned int i, j, k = 0; for (i = 0; i < C448_SCALAR_LIMBS; i++) { for (j = 0; j < sizeof(c448_word_t); j++, k++) ser[k] = s->limb[i] >> (8 * j); } } void ossl_curve448_scalar_halve(curve448_scalar_t out, const curve448_scalar_t a) { c448_word_t mask = 0 - (a->limb[0] & 1); c448_dword_t chain = 0; unsigned int i; for (i = 0; i < C448_SCALAR_LIMBS; i++) { chain = (chain + a->limb[i]) + (sc_p->limb[i] & mask); out->limb[i] = (c448_word_t)chain; chain >>= C448_WORD_BITS; } for (i = 0; i < C448_SCALAR_LIMBS - 1; i++) out->limb[i] = out->limb[i] >> 1 | out->limb[i + 1] << (WBITS - 1); out->limb[i] = out->limb[i] >> 1 | (c448_word_t)(chain << (WBITS - 1)); }
7,142
28.639004
85
c
openssl
openssl-master/crypto/ec/curve448/word.h
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2014 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_WORD_H # define OSSL_CRYPTO_EC_CURVE448_WORD_H # include <string.h> # include <assert.h> # include <stdlib.h> # include <openssl/e_os2.h> # include "curve448utils.h" # ifdef INT128_MAX # include "arch_64/arch_intrinsics.h" # else # include "arch_32/arch_intrinsics.h" # endif # if (ARCH_WORD_BITS == 64) typedef uint64_t word_t, mask_t; typedef uint128_t dword_t; typedef int32_t hsword_t; typedef int64_t sword_t; typedef int128_t dsword_t; # elif (ARCH_WORD_BITS == 32) typedef uint32_t word_t, mask_t; typedef uint64_t dword_t; typedef int16_t hsword_t; typedef int32_t sword_t; typedef int64_t dsword_t; # else # error "For now, we only support 32- and 64-bit architectures." # endif /* * Scalar limbs are keyed off of the API word size instead of the arch word * size. */ # if C448_WORD_BITS == 64 # define SC_LIMB(x) (x) # elif C448_WORD_BITS == 32 # define SC_LIMB(x) ((uint32_t)(x)),((x) >> 32) # else # error "For now we only support 32- and 64-bit architectures." # endif /* * The plan on booleans: The external interface uses c448_bool_t, but this * might be a different size than our particular arch's word_t (and thus * mask_t). Also, the caller isn't guaranteed to pass it as nonzero. So * bool_to_mask converts word sizes and checks nonzero. On the flip side, * mask_t is always -1 or 0, but it might be a different size than * c448_bool_t. On the third hand, we have success vs boolean types, but * that's handled in common.h: it converts between c448_bool_t and * c448_error_t. */ static ossl_inline c448_bool_t mask_to_bool(mask_t m) { return (c448_sword_t)(sword_t)m; } static ossl_inline mask_t bool_to_mask(c448_bool_t m) { /* On most arches this will be optimized to a simple cast. */ mask_t ret = 0; unsigned int i; unsigned int limit = sizeof(c448_bool_t) / sizeof(mask_t); if (limit < 1) limit = 1; for (i = 0; i < limit; i++) ret |= ~word_is_zero(m >> (i * 8 * sizeof(word_t))); return ret; } #endif /* OSSL_CRYPTO_EC_CURVE448_WORD_H */
2,521
27.988506
75
h
openssl
openssl-master/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 */
832
28.75
82
h
openssl
openssl-master/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 */
1,661
26.245902
78
h
openssl
openssl-master/crypto/ec/curve448/arch_32/f_impl32.c
/* * Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2014 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 */ #include "internal/e_os.h" #include <openssl/macros.h> #include "internal/numbers.h" #ifdef UINT128_MAX /* We have support for 128 bit ints, so do nothing here */ NON_EMPTY_TRANSLATION_UNIT #else # include "../field.h" void ossl_gf_mul(gf_s * RESTRICT cs, const gf as, const gf bs) { const uint32_t *a = as->limb, *b = bs->limb; uint32_t *c = cs->limb; uint64_t accum0 = 0, accum1 = 0, accum2 = 0; uint32_t mask = (1 << 28) - 1; uint32_t aa[8], bb[8]; int i, j; for (i = 0; i < 8; i++) { aa[i] = a[i] + a[i + 8]; bb[i] = b[i] + b[i + 8]; } for (j = 0; j < 8; j++) { accum2 = 0; for (i = 0; i < j + 1; i++) { accum2 += widemul(a[j - i], b[i]); accum1 += widemul(aa[j - i], bb[i]); accum0 += widemul(a[8 + j - i], b[8 + i]); } accum1 -= accum2; accum0 += accum2; accum2 = 0; for (i = j + 1; i < 8; i++) { accum0 -= widemul(a[8 + j - i], b[i]); accum2 += widemul(aa[8 + j - i], bb[i]); accum1 += widemul(a[16 + j - i], b[8 + i]); } accum1 += accum2; accum0 += accum2; c[j] = ((uint32_t)(accum0)) & mask; c[j + 8] = ((uint32_t)(accum1)) & mask; accum0 >>= 28; accum1 >>= 28; } accum0 += accum1; accum0 += c[8]; accum1 += c[0]; c[8] = ((uint32_t)(accum0)) & mask; c[0] = ((uint32_t)(accum1)) & mask; accum0 >>= 28; accum1 >>= 28; c[9] += ((uint32_t)(accum0)); c[1] += ((uint32_t)(accum1)); } void ossl_gf_mulw_unsigned(gf_s * RESTRICT cs, const gf as, uint32_t b) { const uint32_t *a = as->limb; uint32_t *c = cs->limb; uint64_t accum0 = 0, accum8 = 0; uint32_t mask = (1 << 28) - 1; int i; assert(b <= mask); for (i = 0; i < 8; i++) { accum0 += widemul(b, a[i]); accum8 += widemul(b, a[i + 8]); c[i] = accum0 & mask; accum0 >>= 28; c[i + 8] = accum8 & mask; accum8 >>= 28; } accum0 += accum8 + c[8]; c[8] = ((uint32_t)accum0) & mask; c[9] += (uint32_t)(accum0 >> 28); accum8 += c[0]; c[0] = ((uint32_t)accum8) & mask; c[1] += (uint32_t)(accum8 >> 28); } void ossl_gf_sqr(gf_s * RESTRICT cs, const gf as) { ossl_gf_mul(cs, as, as); /* Performs better with a dedicated square */ } #endif
2,811
25.528302
82
c
openssl
openssl-master/crypto/ec/curve448/arch_64/arch_intrinsics.h
/* * Copyright 2017-2022 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_64_INTRINSICS_H # define OSSL_CRYPTO_EC_CURVE448_ARCH_64_INTRINSICS_H # include "internal/constant_time.h" # define ARCH_WORD_BITS 64 # define word_is_zero(a) constant_time_is_zero_64(a) static ossl_inline uint128_t widemul(uint64_t a, uint64_t b) { return ((uint128_t) a) * b; } #endif /* OSSL_CRYPTO_EC_CURVE448_ARCH_64_INTRINSICS_H */
837
28.928571
82
h
openssl
openssl-master/crypto/ec/curve448/arch_64/f_impl.h
/* * Copyright 2017-2022 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_64_F_IMPL_H # define OSSL_CRYPTO_EC_CURVE448_ARCH_64_F_IMPL_H # define GF_HEADROOM 9999 /* Everything is reduced anyway */ # define FIELD_LITERAL(a,b,c,d,e,f,g,h) {{a,b,c,d,e,f,g,h}} # define LIMB_PLACE_VALUE(i) 56 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]; gf_weak_reduce(out); } void gf_sub_RAW(gf out, const gf a, const gf b) { uint64_t co1 = ((1ULL << 56) - 1) * 2, co2 = co1 - 2; unsigned int i; for (i = 0; i < NLIMBS; i++) out->limb[i] = a->limb[i] - b->limb[i] + ((i == NLIMBS / 2) ? co2 : co1); gf_weak_reduce(out); } void gf_bias(gf a, int amt) { } void gf_weak_reduce(gf a) { uint64_t mask = (1ULL << 56) - 1; uint64_t tmp = a->limb[NLIMBS - 1] >> 56; 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] >> 56); a->limb[0] = (a->limb[0] & mask) + tmp; } #endif /* OSSL_CRYPTO_EC_CURVE448_ARCH_64_F_IMPL_H */
1,565
25.542373
81
h
openssl
openssl-master/crypto/ec/curve448/arch_64/f_impl64.c
/* * Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2014 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 */ #include "internal/e_os.h" #include <openssl/macros.h> #include "internal/numbers.h" #ifndef UINT128_MAX /* No support for 128 bit ints, so do nothing here */ NON_EMPTY_TRANSLATION_UNIT #else # include "../field.h" void ossl_gf_mul(gf_s * RESTRICT cs, const gf as, const gf bs) { const uint64_t *a = as->limb, *b = bs->limb; uint64_t *c = cs->limb; uint128_t accum0 = 0, accum1 = 0, accum2; uint64_t mask = (1ULL << 56) - 1; uint64_t aa[4], bb[4], bbb[4]; unsigned int i, j; for (i = 0; i < 4; i++) { aa[i] = a[i] + a[i + 4]; bb[i] = b[i] + b[i + 4]; bbb[i] = bb[i] + b[i + 4]; } for (i = 0; i < 4; i++) { accum2 = 0; for (j = 0; j <= i; j++) { accum2 += widemul(a[j], b[i - j]); accum1 += widemul(aa[j], bb[i - j]); accum0 += widemul(a[j + 4], b[i - j + 4]); } for (; j < 4; j++) { accum2 += widemul(a[j], b[i - j + 8]); accum1 += widemul(aa[j], bbb[i - j + 4]); accum0 += widemul(a[j + 4], bb[i - j + 4]); } accum1 -= accum2; accum0 += accum2; c[i] = ((uint64_t)(accum0)) & mask; c[i + 4] = ((uint64_t)(accum1)) & mask; accum0 >>= 56; accum1 >>= 56; } accum0 += accum1; accum0 += c[4]; accum1 += c[0]; c[4] = ((uint64_t)(accum0)) & mask; c[0] = ((uint64_t)(accum1)) & mask; accum0 >>= 56; accum1 >>= 56; c[5] += ((uint64_t)(accum0)); c[1] += ((uint64_t)(accum1)); } void ossl_gf_mulw_unsigned(gf_s * RESTRICT cs, const gf as, uint32_t b) { const uint64_t *a = as->limb; uint64_t *c = cs->limb; uint128_t accum0 = 0, accum4 = 0; uint64_t mask = (1ULL << 56) - 1; int i; for (i = 0; i < 4; i++) { accum0 += widemul(b, a[i]); accum4 += widemul(b, a[i + 4]); c[i] = accum0 & mask; accum0 >>= 56; c[i + 4] = accum4 & mask; accum4 >>= 56; } accum0 += accum4 + c[4]; c[4] = accum0 & mask; c[5] += accum0 >> 56; accum4 += c[0]; c[0] = accum4 & mask; c[1] += accum4 >> 56; } void ossl_gf_sqr(gf_s * RESTRICT cs, const gf as) { const uint64_t *a = as->limb; uint64_t *c = cs->limb; uint128_t accum0 = 0, accum1 = 0, accum2; uint64_t mask = (1ULL << 56) - 1; uint64_t aa[4]; unsigned int i; /* For some reason clang doesn't vectorize this without prompting? */ for (i = 0; i < 4; i++) aa[i] = a[i] + a[i + 4]; accum2 = widemul(a[0], a[3]); accum0 = widemul(aa[0], aa[3]); accum1 = widemul(a[4], a[7]); accum2 += widemul(a[1], a[2]); accum0 += widemul(aa[1], aa[2]); accum1 += widemul(a[5], a[6]); accum0 -= accum2; accum1 += accum2; c[3] = ((uint64_t)(accum1)) << 1 & mask; c[7] = ((uint64_t)(accum0)) << 1 & mask; accum0 >>= 55; accum1 >>= 55; accum0 += widemul(2 * aa[1], aa[3]); accum1 += widemul(2 * a[5], a[7]); accum0 += widemul(aa[2], aa[2]); accum1 += accum0; accum0 -= widemul(2 * a[1], a[3]); accum1 += widemul(a[6], a[6]); accum2 = widemul(a[0], a[0]); accum1 -= accum2; accum0 += accum2; accum0 -= widemul(a[2], a[2]); accum1 += widemul(aa[0], aa[0]); accum0 += widemul(a[4], a[4]); c[0] = ((uint64_t)(accum0)) & mask; c[4] = ((uint64_t)(accum1)) & mask; accum0 >>= 56; accum1 >>= 56; accum2 = widemul(2 * aa[2], aa[3]); accum0 -= widemul(2 * a[2], a[3]); accum1 += widemul(2 * a[6], a[7]); accum1 += accum2; accum0 += accum2; accum2 = widemul(2 * a[0], a[1]); accum1 += widemul(2 * aa[0], aa[1]); accum0 += widemul(2 * a[4], a[5]); accum1 -= accum2; accum0 += accum2; c[1] = ((uint64_t)(accum0)) & mask; c[5] = ((uint64_t)(accum1)) & mask; accum0 >>= 56; accum1 >>= 56; accum2 = widemul(aa[3], aa[3]); accum0 -= widemul(a[3], a[3]); accum1 += widemul(a[7], a[7]); accum1 += accum2; accum0 += accum2; accum2 = widemul(2 * a[0], a[2]); accum1 += widemul(2 * aa[0], aa[2]); accum0 += widemul(2 * a[4], a[6]); accum2 += widemul(a[1], a[1]); accum1 += widemul(aa[1], aa[1]); accum0 += widemul(a[5], a[5]); accum1 -= accum2; accum0 += accum2; c[2] = ((uint64_t)(accum0)) & mask; c[6] = ((uint64_t)(accum1)) & mask; accum0 >>= 56; accum1 >>= 56; accum0 += c[3]; accum1 += c[7]; c[3] = ((uint64_t)(accum0)) & mask; c[7] = ((uint64_t)(accum1)) & mask; /* we could almost stop here, but it wouldn't be stable, so... */ accum0 >>= 56; accum1 >>= 56; c[4] += ((uint64_t)(accum0)) + ((uint64_t)(accum1)); c[0] += ((uint64_t)(accum1)); } #endif
5,176
23.535545
74
c
openssl
openssl-master/crypto/encode_decode/decoder_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * 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 <openssl/err.h> #include <openssl/decodererr.h> #include "crypto/decodererr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA OSSL_DECODER_str_reasons[] = { {ERR_PACK(ERR_LIB_OSSL_DECODER, 0, OSSL_DECODER_R_COULD_NOT_DECODE_OBJECT), "could not decode object"}, {ERR_PACK(ERR_LIB_OSSL_DECODER, 0, OSSL_DECODER_R_DECODER_NOT_FOUND), "decoder not found"}, {ERR_PACK(ERR_LIB_OSSL_DECODER, 0, OSSL_DECODER_R_MISSING_GET_PARAMS), "missing get params"}, {0, NULL} }; #endif int ossl_err_load_OSSL_DECODER_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(OSSL_DECODER_str_reasons[0].error) == NULL) ERR_load_strings_const(OSSL_DECODER_str_reasons); #endif return 1; }
1,119
29.27027
79
c
openssl
openssl-master/crypto/encode_decode/decoder_meth.c
/* * Copyright 2020-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 <openssl/core.h> #include <openssl/core_dispatch.h> #include <openssl/decoder.h> #include <openssl/ui.h> #include "internal/core.h" #include "internal/namemap.h" #include "internal/property.h" #include "internal/provider.h" #include "crypto/decoder.h" #include "encoder_local.h" #include "crypto/context.h" /* * Decoder can have multiple names, separated with colons in a name string */ #define NAME_SEPARATOR ':' /* Simple method structure constructor and destructor */ static OSSL_DECODER *ossl_decoder_new(void) { OSSL_DECODER *decoder = NULL; if ((decoder = OPENSSL_zalloc(sizeof(*decoder))) == NULL) return NULL; if (!CRYPTO_NEW_REF(&decoder->base.refcnt, 1)) { OSSL_DECODER_free(decoder); return NULL; } return decoder; } int OSSL_DECODER_up_ref(OSSL_DECODER *decoder) { int ref = 0; CRYPTO_UP_REF(&decoder->base.refcnt, &ref); return 1; } void OSSL_DECODER_free(OSSL_DECODER *decoder) { int ref = 0; if (decoder == NULL) return; CRYPTO_DOWN_REF(&decoder->base.refcnt, &ref); if (ref > 0) return; OPENSSL_free(decoder->base.name); ossl_property_free(decoder->base.parsed_propdef); ossl_provider_free(decoder->base.prov); CRYPTO_FREE_REF(&decoder->base.refcnt); OPENSSL_free(decoder); } /* Data to be passed through ossl_method_construct() */ struct decoder_data_st { OSSL_LIB_CTX *libctx; int id; /* For get_decoder_from_store() */ const char *names; /* For get_decoder_from_store() */ const char *propquery; /* For get_decoder_from_store() */ OSSL_METHOD_STORE *tmp_store; /* For get_tmp_decoder_store() */ unsigned int flag_construct_error_occurred : 1; }; /* * Generic routines to fetch / create DECODER methods with * ossl_method_construct() */ /* Temporary decoder method store, constructor and destructor */ static void *get_tmp_decoder_store(void *data) { struct decoder_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_decoder_store(void *store) { if (store != NULL) ossl_method_store_free(store); } /* Get the permanent decoder store */ static OSSL_METHOD_STORE *get_decoder_store(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DECODER_STORE_INDEX); } static int reserve_decoder_store(void *store, void *data) { struct decoder_data_st *methdata = data; if (store == NULL && (store = get_decoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_lock_store(store); } static int unreserve_decoder_store(void *store, void *data) { struct decoder_data_st *methdata = data; if (store == NULL && (store = get_decoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_unlock_store(store); } /* Get decoder methods from a store, or put one in */ static void *get_decoder_from_store(void *store, const OSSL_PROVIDER **prov, void *data) { struct decoder_data_st *methdata = data; void *method = NULL; int id; /* * get_decoder_from_store() is only called to try and get the method * that OSSL_DECODER_fetch() is asking for, and the name or name id are * passed via methdata. */ if ((id = methdata->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; id = ossl_namemap_name2num_n(namemap, names, l); } if (id == 0) return NULL; if (store == NULL && (store = get_decoder_store(methdata->libctx)) == NULL) return NULL; if (!ossl_method_store_fetch(store, id, methdata->propquery, prov, &method)) return NULL; return method; } static int put_decoder_in_store(void *store, void *method, const OSSL_PROVIDER *prov, const char *names, const char *propdef, void *data) { struct decoder_data_st *methdata = data; OSSL_NAMEMAP *namemap; int id; size_t l = 0; /* * put_decoder_in_store() is only called with an OSSL_DECODER method that * was successfully created by construct_decoder() 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 || (id = ossl_namemap_name2num_n(namemap, names, l)) == 0) return 0; if (store == NULL && (store = get_decoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_store_add(store, prov, id, propdef, method, (int (*)(void *))OSSL_DECODER_up_ref, (void (*)(void *))OSSL_DECODER_free); } /* Create and populate a decoder method */ void *ossl_decoder_from_algorithm(int id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { OSSL_DECODER *decoder = NULL; const OSSL_DISPATCH *fns = algodef->implementation; OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); if ((decoder = ossl_decoder_new()) == NULL) return NULL; decoder->base.id = id; if ((decoder->base.name = ossl_algorithm_get1_first_name(algodef)) == NULL) { OSSL_DECODER_free(decoder); return NULL; } decoder->base.algodef = algodef; if ((decoder->base.parsed_propdef = ossl_parse_property(libctx, algodef->property_definition)) == NULL) { OSSL_DECODER_free(decoder); return NULL; } for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_DECODER_NEWCTX: if (decoder->newctx == NULL) decoder->newctx = OSSL_FUNC_decoder_newctx(fns); break; case OSSL_FUNC_DECODER_FREECTX: if (decoder->freectx == NULL) decoder->freectx = OSSL_FUNC_decoder_freectx(fns); break; case OSSL_FUNC_DECODER_GET_PARAMS: if (decoder->get_params == NULL) decoder->get_params = OSSL_FUNC_decoder_get_params(fns); break; case OSSL_FUNC_DECODER_GETTABLE_PARAMS: if (decoder->gettable_params == NULL) decoder->gettable_params = OSSL_FUNC_decoder_gettable_params(fns); break; case OSSL_FUNC_DECODER_SET_CTX_PARAMS: if (decoder->set_ctx_params == NULL) decoder->set_ctx_params = OSSL_FUNC_decoder_set_ctx_params(fns); break; case OSSL_FUNC_DECODER_SETTABLE_CTX_PARAMS: if (decoder->settable_ctx_params == NULL) decoder->settable_ctx_params = OSSL_FUNC_decoder_settable_ctx_params(fns); break; case OSSL_FUNC_DECODER_DOES_SELECTION: if (decoder->does_selection == NULL) decoder->does_selection = OSSL_FUNC_decoder_does_selection(fns); break; case OSSL_FUNC_DECODER_DECODE: if (decoder->decode == NULL) decoder->decode = OSSL_FUNC_decoder_decode(fns); break; case OSSL_FUNC_DECODER_EXPORT_OBJECT: if (decoder->export_object == NULL) decoder->export_object = OSSL_FUNC_decoder_export_object(fns); break; } } /* * Try to check that the method is sensible. * If you have a constructor, you must have a destructor and vice versa. * You must have at least one of the encoding driver functions. */ if (!((decoder->newctx == NULL && decoder->freectx == NULL) || (decoder->newctx != NULL && decoder->freectx != NULL)) || decoder->decode == NULL) { OSSL_DECODER_free(decoder); ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROVIDER_FUNCTIONS); return NULL; } if (prov != NULL && !ossl_provider_up_ref(prov)) { OSSL_DECODER_free(decoder); return NULL; } decoder->base.prov = prov; return decoder; } /* * The core fetching functionality passes the names of the implementation. * This function is responsible to getting an identity number for them, * then call ossl_decoder_from_algorithm() with that identity number. */ static void *construct_decoder(const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov, void *data) { /* * This function is only called if get_decoder_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() will return its corresponding number. */ struct decoder_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 id = ossl_namemap_add_names(namemap, 0, names, NAME_SEPARATOR); void *method = NULL; if (id != 0) method = ossl_decoder_from_algorithm(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; } /* Intermediary function to avoid ugly casts, used below */ static void destruct_decoder(void *method, void *data) { OSSL_DECODER_free(method); } static int up_ref_decoder(void *method) { return OSSL_DECODER_up_ref(method); } static void free_decoder(void *method) { OSSL_DECODER_free(method); } /* Fetching support. Can fetch by numeric identity or by name */ static OSSL_DECODER * inner_ossl_decoder_fetch(struct decoder_data_st *methdata, const char *name, const char *properties) { OSSL_METHOD_STORE *store = get_decoder_store(methdata->libctx); OSSL_NAMEMAP *namemap = ossl_namemap_stored(methdata->libctx); const char *const propq = properties != NULL ? properties : ""; void *method = NULL; int unsupported, id; if (store == NULL || namemap == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } id = name != NULL ? ossl_namemap_name2num(namemap, name) : 0; /* * If we haven't found the name yet, chances are that the algorithm to * be fetched is unsupported. */ unsupported = id == 0; if (id == 0 || !ossl_method_store_cache_get(store, NULL, id, propq, &method)) { OSSL_METHOD_CONSTRUCT_METHOD mcm = { get_tmp_decoder_store, reserve_decoder_store, unreserve_decoder_store, get_decoder_from_store, put_decoder_in_store, construct_decoder, destruct_decoder }; OSSL_PROVIDER *prov = NULL; methdata->id = id; methdata->names = name; methdata->propquery = propq; methdata->flag_construct_error_occurred = 0; if ((method = ossl_method_construct(methdata->libctx, OSSL_OP_DECODER, &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_decoder_from_store() and * put_decoder_in_store() above. */ if (id == 0 && name != NULL) id = ossl_namemap_name2num(namemap, name); if (id != 0) ossl_method_store_cache_set(store, prov, id, propq, method, up_ref_decoder, free_decoder); } /* * If we never were in the constructor, the algorithm to be fetched * is unsupported. */ unsupported = !methdata->flag_construct_error_occurred; } if ((id != 0 || name != NULL) && method == NULL) { int code = unsupported ? ERR_R_UNSUPPORTED : ERR_R_FETCH_FAILED; if (name == NULL) name = ossl_namemap_num2name(namemap, id, 0); ERR_raise_data(ERR_LIB_OSSL_DECODER, code, "%s, Name (%s : %d), Properties (%s)", ossl_lib_ctx_get_descriptor(methdata->libctx), name == NULL ? "<null>" : name, id, properties == NULL ? "<null>" : properties); } return method; } OSSL_DECODER *OSSL_DECODER_fetch(OSSL_LIB_CTX *libctx, const char *name, const char *properties) { struct decoder_data_st methdata; void *method; methdata.libctx = libctx; methdata.tmp_store = NULL; method = inner_ossl_decoder_fetch(&methdata, name, properties); dealloc_tmp_decoder_store(methdata.tmp_store); return method; } int ossl_decoder_store_cache_flush(OSSL_LIB_CTX *libctx) { OSSL_METHOD_STORE *store = get_decoder_store(libctx); if (store != NULL) return ossl_method_store_cache_flush_all(store); return 1; } int ossl_decoder_store_remove_all_provided(const OSSL_PROVIDER *prov) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_METHOD_STORE *store = get_decoder_store(libctx); if (store != NULL) return ossl_method_store_remove_all_provided(store, prov); return 1; } /* * Library of basic method functions */ const OSSL_PROVIDER *OSSL_DECODER_get0_provider(const OSSL_DECODER *decoder) { if (!ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return decoder->base.prov; } const char *OSSL_DECODER_get0_properties(const OSSL_DECODER *decoder) { if (!ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return decoder->base.algodef->property_definition; } const OSSL_PROPERTY_LIST * ossl_decoder_parsed_properties(const OSSL_DECODER *decoder) { if (!ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return decoder->base.parsed_propdef; } int ossl_decoder_get_number(const OSSL_DECODER *decoder) { if (!ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return decoder->base.id; } const char *OSSL_DECODER_get0_name(const OSSL_DECODER *decoder) { return decoder->base.name; } const char *OSSL_DECODER_get0_description(const OSSL_DECODER *decoder) { return decoder->base.algodef->algorithm_description; } int OSSL_DECODER_is_a(const OSSL_DECODER *decoder, const char *name) { if (decoder->base.prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(decoder->base.prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_name2num(namemap, name) == decoder->base.id; } return 0; } static int resolve_name(OSSL_DECODER *decoder, const char *name) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(decoder->base.prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_name2num(namemap, name); } int ossl_decoder_fast_is_a(OSSL_DECODER *decoder, const char *name, int *id_cache) { int id = *id_cache; if (id <= 0) *id_cache = id = resolve_name(decoder, name); return id > 0 && ossl_decoder_get_number(decoder) == id; } struct do_one_data_st { void (*user_fn)(OSSL_DECODER *decoder, void *arg); void *user_arg; }; static void do_one(ossl_unused int id, void *method, void *arg) { struct do_one_data_st *data = arg; data->user_fn(method, data->user_arg); } void OSSL_DECODER_do_all_provided(OSSL_LIB_CTX *libctx, void (*user_fn)(OSSL_DECODER *decoder, void *arg), void *user_arg) { struct decoder_data_st methdata; struct do_one_data_st data; methdata.libctx = libctx; methdata.tmp_store = NULL; (void)inner_ossl_decoder_fetch(&methdata, NULL, NULL /* properties */); data.user_fn = user_fn; data.user_arg = user_arg; if (methdata.tmp_store != NULL) ossl_method_store_do_all(methdata.tmp_store, &do_one, &data); ossl_method_store_do_all(get_decoder_store(libctx), &do_one, &data); dealloc_tmp_decoder_store(methdata.tmp_store); } int OSSL_DECODER_names_do_all(const OSSL_DECODER *decoder, void (*fn)(const char *name, void *data), void *data) { if (decoder == NULL) return 0; if (decoder->base.prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(decoder->base.prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_doall_names(namemap, decoder->base.id, fn, data); } return 1; } const OSSL_PARAM * OSSL_DECODER_gettable_params(OSSL_DECODER *decoder) { if (decoder != NULL && decoder->gettable_params != NULL) { void *provctx = ossl_provider_ctx(OSSL_DECODER_get0_provider(decoder)); return decoder->gettable_params(provctx); } return NULL; } int OSSL_DECODER_get_params(OSSL_DECODER *decoder, OSSL_PARAM params[]) { if (decoder != NULL && decoder->get_params != NULL) return decoder->get_params(params); return 0; } const OSSL_PARAM * OSSL_DECODER_settable_ctx_params(OSSL_DECODER *decoder) { if (decoder != NULL && decoder->settable_ctx_params != NULL) { void *provctx = ossl_provider_ctx(OSSL_DECODER_get0_provider(decoder)); return decoder->settable_ctx_params(provctx); } return NULL; } /* * Decoder context support */ /* * |encoder| value NULL is valid, and signifies that there is no decoder. * This is useful to provide fallback mechanisms. * Functions that want to verify if there is a decoder can do so with * OSSL_DECODER_CTX_get_decoder() */ OSSL_DECODER_CTX *OSSL_DECODER_CTX_new(void) { OSSL_DECODER_CTX *ctx; ctx = OPENSSL_zalloc(sizeof(*ctx)); return ctx; } int OSSL_DECODER_CTX_set_params(OSSL_DECODER_CTX *ctx, const OSSL_PARAM params[]) { int ok = 1; size_t i; size_t l; if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ctx->decoder_insts == NULL) return 1; l = OSSL_DECODER_CTX_get_num_decoders(ctx); for (i = 0; i < l; i++) { OSSL_DECODER_INSTANCE *decoder_inst = sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i); OSSL_DECODER *decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst); OSSL_DECODER *decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst); if (decoderctx == NULL || decoder->set_ctx_params == NULL) continue; if (!decoder->set_ctx_params(decoderctx, params)) ok = 0; } return ok; } void OSSL_DECODER_CTX_free(OSSL_DECODER_CTX *ctx) { if (ctx != NULL) { if (ctx->cleanup != NULL) ctx->cleanup(ctx->construct_data); sk_OSSL_DECODER_INSTANCE_pop_free(ctx->decoder_insts, ossl_decoder_instance_free); ossl_pw_clear_passphrase_data(&ctx->pwdata); OPENSSL_free(ctx); } }
20,695
29.751857
82
c
openssl
openssl-master/crypto/encode_decode/encoder_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * 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 <openssl/err.h> #include <openssl/encodererr.h> #include "crypto/encodererr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA OSSL_ENCODER_str_reasons[] = { {ERR_PACK(ERR_LIB_OSSL_ENCODER, 0, OSSL_ENCODER_R_ENCODER_NOT_FOUND), "encoder not found"}, {ERR_PACK(ERR_LIB_OSSL_ENCODER, 0, OSSL_ENCODER_R_INCORRECT_PROPERTY_QUERY), "incorrect property query"}, {ERR_PACK(ERR_LIB_OSSL_ENCODER, 0, OSSL_ENCODER_R_MISSING_GET_PARAMS), "missing get params"}, {0, NULL} }; #endif int ossl_err_load_OSSL_ENCODER_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(OSSL_ENCODER_str_reasons[0].error) == NULL) ERR_load_strings_const(OSSL_ENCODER_str_reasons); #endif return 1; }
1,121
29.324324
80
c
openssl
openssl-master/crypto/encode_decode/encoder_lib.c
/* * Copyright 2019-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 <openssl/core_names.h> #include <openssl/bio.h> #include <openssl/encoder.h> #include <openssl/buffer.h> #include <openssl/params.h> #include <openssl/provider.h> #include <openssl/trace.h> #include "internal/bio.h" #include "internal/provider.h" #include "encoder_local.h" struct encoder_process_data_st { OSSL_ENCODER_CTX *ctx; /* Current BIO */ BIO *bio; /* Index of the current encoder instance to be processed */ int current_encoder_inst_index; /* Processing data passed down through recursion */ int level; /* Recursion level */ OSSL_ENCODER_INSTANCE *next_encoder_inst; int count_output_structure; /* Processing data passed up through recursion */ OSSL_ENCODER_INSTANCE *prev_encoder_inst; unsigned char *running_output; size_t running_output_length; /* Data type = the name of the first succeeding encoder implementation */ const char *data_type; }; static int encoder_process(struct encoder_process_data_st *data); int OSSL_ENCODER_to_bio(OSSL_ENCODER_CTX *ctx, BIO *out) { struct encoder_process_data_st data; memset(&data, 0, sizeof(data)); data.ctx = ctx; data.bio = out; data.current_encoder_inst_index = OSSL_ENCODER_CTX_get_num_encoders(ctx); if (data.current_encoder_inst_index == 0) { ERR_raise_data(ERR_LIB_OSSL_ENCODER, OSSL_ENCODER_R_ENCODER_NOT_FOUND, "No encoders were found. For standard encoders you need " "at least one of the default or base providers " "available. Did you forget to load them?"); return 0; } return encoder_process(&data) > 0; } #ifndef OPENSSL_NO_STDIO static BIO *bio_from_file(FILE *fp) { BIO *b; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_BUF_LIB); return NULL; } BIO_set_fp(b, fp, BIO_NOCLOSE); return b; } int OSSL_ENCODER_to_fp(OSSL_ENCODER_CTX *ctx, FILE *fp) { BIO *b = bio_from_file(fp); int ret = 0; if (b != NULL) ret = OSSL_ENCODER_to_bio(ctx, b); BIO_free(b); return ret; } #endif int OSSL_ENCODER_to_data(OSSL_ENCODER_CTX *ctx, unsigned char **pdata, size_t *pdata_len) { BIO *out; BUF_MEM *buf = NULL; int ret = 0; if (pdata_len == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } out = BIO_new(BIO_s_mem()); if (out != NULL && OSSL_ENCODER_to_bio(ctx, out) && BIO_get_mem_ptr(out, &buf) > 0) { ret = 1; /* Hope for the best. A too small buffer will clear this */ if (pdata != NULL && *pdata != NULL) { if (*pdata_len < buf->length) /* * It's tempting to do |*pdata_len = (size_t)buf->length| * However, it's believed to be confusing more than helpful, * so we don't. */ ret = 0; else *pdata_len -= buf->length; } else { /* The buffer with the right size is already allocated for us */ *pdata_len = (size_t)buf->length; } if (ret) { if (pdata != NULL) { if (*pdata != NULL) { memcpy(*pdata, buf->data, buf->length); *pdata += buf->length; } else { /* In this case, we steal the data from BIO_s_mem() */ *pdata = (unsigned char *)buf->data; buf->data = NULL; } } } } BIO_free(out); return ret; } int OSSL_ENCODER_CTX_set_selection(OSSL_ENCODER_CTX *ctx, int selection) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (!ossl_assert(selection != 0)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } ctx->selection = selection; return 1; } int OSSL_ENCODER_CTX_set_output_type(OSSL_ENCODER_CTX *ctx, const char *output_type) { if (!ossl_assert(ctx != NULL) || !ossl_assert(output_type != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->output_type = output_type; return 1; } int OSSL_ENCODER_CTX_set_output_structure(OSSL_ENCODER_CTX *ctx, const char *output_structure) { if (!ossl_assert(ctx != NULL) || !ossl_assert(output_structure != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->output_structure = output_structure; return 1; } static OSSL_ENCODER_INSTANCE *ossl_encoder_instance_new(OSSL_ENCODER *encoder, void *encoderctx) { OSSL_ENCODER_INSTANCE *encoder_inst = NULL; const OSSL_PROVIDER *prov; OSSL_LIB_CTX *libctx; const OSSL_PROPERTY_LIST *props; const OSSL_PROPERTY_DEFINITION *prop; if (!ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((encoder_inst = OPENSSL_zalloc(sizeof(*encoder_inst))) == NULL) return 0; if (!OSSL_ENCODER_up_ref(encoder)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_INTERNAL_ERROR); goto err; } prov = OSSL_ENCODER_get0_provider(encoder); libctx = ossl_provider_libctx(prov); props = ossl_encoder_parsed_properties(encoder); if (props == NULL) { ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION, "there are no property definitions with encoder %s", OSSL_ENCODER_get0_name(encoder)); goto err; } /* The "output" property is mandatory */ prop = ossl_property_find_property(props, libctx, "output"); encoder_inst->output_type = ossl_property_get_string_value(libctx, prop); if (encoder_inst->output_type == NULL) { ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION, "the mandatory 'output' property is missing " "for encoder %s (properties: %s)", OSSL_ENCODER_get0_name(encoder), OSSL_ENCODER_get0_properties(encoder)); goto err; } /* The "structure" property is optional */ prop = ossl_property_find_property(props, libctx, "structure"); if (prop != NULL) encoder_inst->output_structure = ossl_property_get_string_value(libctx, prop); encoder_inst->encoder = encoder; encoder_inst->encoderctx = encoderctx; return encoder_inst; err: ossl_encoder_instance_free(encoder_inst); return NULL; } void ossl_encoder_instance_free(OSSL_ENCODER_INSTANCE *encoder_inst) { if (encoder_inst != NULL) { if (encoder_inst->encoder != NULL) encoder_inst->encoder->freectx(encoder_inst->encoderctx); encoder_inst->encoderctx = NULL; OSSL_ENCODER_free(encoder_inst->encoder); encoder_inst->encoder = NULL; OPENSSL_free(encoder_inst); } } static int ossl_encoder_ctx_add_encoder_inst(OSSL_ENCODER_CTX *ctx, OSSL_ENCODER_INSTANCE *ei) { int ok; if (ctx->encoder_insts == NULL && (ctx->encoder_insts = sk_OSSL_ENCODER_INSTANCE_new_null()) == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_CRYPTO_LIB); return 0; } ok = (sk_OSSL_ENCODER_INSTANCE_push(ctx->encoder_insts, ei) > 0); if (ok) { OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "(ctx %p) Added encoder instance %p (encoder %p):\n" " %s with %s\n", (void *)ctx, (void *)ei, (void *)ei->encoder, OSSL_ENCODER_get0_name(ei->encoder), OSSL_ENCODER_get0_properties(ei->encoder)); } OSSL_TRACE_END(ENCODER); } return ok; } int OSSL_ENCODER_CTX_add_encoder(OSSL_ENCODER_CTX *ctx, OSSL_ENCODER *encoder) { OSSL_ENCODER_INSTANCE *encoder_inst = NULL; const OSSL_PROVIDER *prov = NULL; void *encoderctx = NULL; void *provctx = NULL; if (!ossl_assert(ctx != NULL) || !ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } prov = OSSL_ENCODER_get0_provider(encoder); provctx = OSSL_PROVIDER_get0_provider_ctx(prov); if ((encoderctx = encoder->newctx(provctx)) == NULL || (encoder_inst = ossl_encoder_instance_new(encoder, encoderctx)) == NULL) goto err; /* Avoid double free of encoderctx on further errors */ encoderctx = NULL; if (!ossl_encoder_ctx_add_encoder_inst(ctx, encoder_inst)) goto err; return 1; err: ossl_encoder_instance_free(encoder_inst); if (encoderctx != NULL) encoder->freectx(encoderctx); return 0; } int OSSL_ENCODER_CTX_add_extra(OSSL_ENCODER_CTX *ctx, OSSL_LIB_CTX *libctx, const char *propq) { return 1; } int OSSL_ENCODER_CTX_get_num_encoders(OSSL_ENCODER_CTX *ctx) { if (ctx == NULL || ctx->encoder_insts == NULL) return 0; return sk_OSSL_ENCODER_INSTANCE_num(ctx->encoder_insts); } int OSSL_ENCODER_CTX_set_construct(OSSL_ENCODER_CTX *ctx, OSSL_ENCODER_CONSTRUCT *construct) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->construct = construct; return 1; } int OSSL_ENCODER_CTX_set_construct_data(OSSL_ENCODER_CTX *ctx, void *construct_data) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->construct_data = construct_data; return 1; } int OSSL_ENCODER_CTX_set_cleanup(OSSL_ENCODER_CTX *ctx, OSSL_ENCODER_CLEANUP *cleanup) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->cleanup = cleanup; return 1; } OSSL_ENCODER * OSSL_ENCODER_INSTANCE_get_encoder(OSSL_ENCODER_INSTANCE *encoder_inst) { if (encoder_inst == NULL) return NULL; return encoder_inst->encoder; } void * OSSL_ENCODER_INSTANCE_get_encoder_ctx(OSSL_ENCODER_INSTANCE *encoder_inst) { if (encoder_inst == NULL) return NULL; return encoder_inst->encoderctx; } const char * OSSL_ENCODER_INSTANCE_get_output_type(OSSL_ENCODER_INSTANCE *encoder_inst) { if (encoder_inst == NULL) return NULL; return encoder_inst->output_type; } const char * OSSL_ENCODER_INSTANCE_get_output_structure(OSSL_ENCODER_INSTANCE *encoder_inst) { if (encoder_inst == NULL) return NULL; return encoder_inst->output_structure; } static int encoder_process(struct encoder_process_data_st *data) { OSSL_ENCODER_INSTANCE *current_encoder_inst = NULL; OSSL_ENCODER *current_encoder = NULL; OSSL_ENCODER_CTX *current_encoder_ctx = NULL; BIO *allocated_out = NULL; const void *original_data = NULL; OSSL_PARAM abstract[10]; const OSSL_PARAM *current_abstract = NULL; int i; int ok = -1; /* -1 signifies that the lookup loop gave nothing */ int top = 0; if (data->next_encoder_inst == NULL) { /* First iteration, where we prepare for what is to come */ data->count_output_structure = data->ctx->output_structure == NULL ? -1 : 0; top = 1; } for (i = data->current_encoder_inst_index; i-- > 0;) { OSSL_ENCODER *next_encoder = NULL; const char *current_output_type; const char *current_output_structure; struct encoder_process_data_st new_data; if (!top) next_encoder = OSSL_ENCODER_INSTANCE_get_encoder(data->next_encoder_inst); current_encoder_inst = sk_OSSL_ENCODER_INSTANCE_value(data->ctx->encoder_insts, i); current_encoder = OSSL_ENCODER_INSTANCE_get_encoder(current_encoder_inst); current_encoder_ctx = OSSL_ENCODER_INSTANCE_get_encoder_ctx(current_encoder_inst); current_output_type = OSSL_ENCODER_INSTANCE_get_output_type(current_encoder_inst); current_output_structure = OSSL_ENCODER_INSTANCE_get_output_structure(current_encoder_inst); memset(&new_data, 0, sizeof(new_data)); new_data.ctx = data->ctx; new_data.current_encoder_inst_index = i; new_data.next_encoder_inst = current_encoder_inst; new_data.count_output_structure = data->count_output_structure; new_data.level = data->level + 1; OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] (ctx %p) Considering encoder instance %p (encoder %p)\n", data->level, (void *)data->ctx, (void *)current_encoder_inst, (void *)current_encoder); } OSSL_TRACE_END(ENCODER); /* * If this is the top call, we check if the output type of the current * encoder matches the desired output type. * If this isn't the top call, i.e. this is deeper in the recursion, * we instead check if the output type of the current encoder matches * the name of the next encoder (the one found by the parent call). */ if (top) { if (data->ctx->output_type != NULL && OPENSSL_strcasecmp(current_output_type, data->ctx->output_type) != 0) { OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] Skipping because current encoder output type (%s) != desired output type (%s)\n", data->level, current_output_type, data->ctx->output_type); } OSSL_TRACE_END(ENCODER); continue; } } else { if (!OSSL_ENCODER_is_a(next_encoder, current_output_type)) { OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] Skipping because current encoder output type (%s) != name of encoder %p\n", data->level, current_output_type, (void *)next_encoder); } OSSL_TRACE_END(ENCODER); continue; } } /* * If the caller and the current encoder specify an output structure, * Check if they match. If they do, count the match, otherwise skip * the current encoder. */ if (data->ctx->output_structure != NULL && current_output_structure != NULL) { if (OPENSSL_strcasecmp(data->ctx->output_structure, current_output_structure) != 0) { OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] Skipping because current encoder output structure (%s) != ctx output structure (%s)\n", data->level, current_output_structure, data->ctx->output_structure); } OSSL_TRACE_END(ENCODER); continue; } data->count_output_structure++; } /* * Recurse to process the encoder implementations before the current * one. */ ok = encoder_process(&new_data); data->prev_encoder_inst = new_data.prev_encoder_inst; data->running_output = new_data.running_output; data->running_output_length = new_data.running_output_length; /* * ok == -1 means that the recursion call above gave no further * encoders, and that the one we're currently at should * be tried. * ok == 0 means that something failed in the recursion call * above, making the result unsuitable for a chain. * In this case, we simply continue to try finding a * suitable encoder at this recursion level. * ok == 1 means that the recursion call was successful, and we * try to use the result at this recursion level. */ if (ok != 0) break; OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] Skipping because recursion level %d failed\n", data->level, new_data.level); } OSSL_TRACE_END(ENCODER); } /* * If |i < 0|, we didn't find any useful encoder in this recursion, so * we do the rest of the process only if |i >= 0|. */ if (i < 0) { ok = -1; OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] (ctx %p) No suitable encoder found\n", data->level, (void *)data->ctx); } OSSL_TRACE_END(ENCODER); } else { /* Preparations */ switch (ok) { case 0: break; case -1: /* * We have reached the beginning of the encoder instance sequence, * so we prepare the object to be encoded. */ /* * |data->count_output_structure| is one of these values: * * -1 There is no desired output structure * 0 There is a desired output structure, and it wasn't * matched by any of the encoder instances that were * considered * >0 There is a desired output structure, and at least one * of the encoder instances matched it */ if (data->count_output_structure == 0) return 0; original_data = data->ctx->construct(current_encoder_inst, data->ctx->construct_data); /* Also set the data type, using the encoder implementation name */ data->data_type = OSSL_ENCODER_get0_name(current_encoder); /* Assume that the constructor recorded an error */ if (original_data != NULL) ok = 1; else ok = 0; break; case 1: if (!ossl_assert(data->running_output != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_INTERNAL_ERROR); ok = 0; break; } { /* * Create an object abstraction from the latest output, which * was stolen from the previous round. */ OSSL_PARAM *abstract_p = abstract; const char *prev_output_structure = OSSL_ENCODER_INSTANCE_get_output_structure(data->prev_encoder_inst); *abstract_p++ = OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE, (char *)data->data_type, 0); if (prev_output_structure != NULL) *abstract_p++ = OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_STRUCTURE, (char *)prev_output_structure, 0); *abstract_p++ = OSSL_PARAM_construct_octet_string(OSSL_OBJECT_PARAM_DATA, data->running_output, data->running_output_length); *abstract_p = OSSL_PARAM_construct_end(); current_abstract = abstract; } break; } /* Calling the encoder implementation */ if (ok) { OSSL_CORE_BIO *cbio = NULL; BIO *current_out = NULL; /* * If we're at the last encoder instance to use, we're setting up * final output. Otherwise, set up an intermediary memory output. */ if (top) current_out = data->bio; else if ((current_out = allocated_out = BIO_new(BIO_s_mem())) == NULL) ok = 0; /* Assume BIO_new() recorded an error */ if (ok) ok = (cbio = ossl_core_bio_new_from_bio(current_out)) != NULL; if (ok) { ok = current_encoder->encode(current_encoder_ctx, cbio, original_data, current_abstract, data->ctx->selection, ossl_pw_passphrase_callback_enc, &data->ctx->pwdata); OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] (ctx %p) Running encoder instance %p => %d\n", data->level, (void *)data->ctx, (void *)current_encoder_inst, ok); } OSSL_TRACE_END(ENCODER); } ossl_core_bio_free(cbio); data->prev_encoder_inst = current_encoder_inst; } } /* Cleanup and collecting the result */ OPENSSL_free(data->running_output); data->running_output = NULL; /* * Steal the output from the BIO_s_mem, if we did allocate one. * That'll be the data for an object abstraction in the next round. */ if (allocated_out != NULL) { BUF_MEM *buf; BIO_get_mem_ptr(allocated_out, &buf); data->running_output = (unsigned char *)buf->data; data->running_output_length = buf->length; memset(buf, 0, sizeof(*buf)); } BIO_free(allocated_out); if (original_data != NULL) data->ctx->cleanup(data->ctx->construct_data); return ok; }
22,895
33.020802
127
c
openssl
openssl-master/crypto/encode_decode/encoder_local.h
/* * Copyright 2019-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 <openssl/core_dispatch.h> #include <openssl/types.h> #include <openssl/safestack.h> #include <openssl/encoder.h> #include <openssl/decoder.h> #include "internal/cryptlib.h" #include "internal/passphrase.h" #include "internal/property.h" #include "internal/refcount.h" struct ossl_endecode_base_st { OSSL_PROVIDER *prov; int id; char *name; const OSSL_ALGORITHM *algodef; OSSL_PROPERTY_LIST *parsed_propdef; CRYPTO_REF_COUNT refcnt; }; struct ossl_encoder_st { struct ossl_endecode_base_st base; OSSL_FUNC_encoder_newctx_fn *newctx; OSSL_FUNC_encoder_freectx_fn *freectx; OSSL_FUNC_encoder_get_params_fn *get_params; OSSL_FUNC_encoder_gettable_params_fn *gettable_params; OSSL_FUNC_encoder_set_ctx_params_fn *set_ctx_params; OSSL_FUNC_encoder_settable_ctx_params_fn *settable_ctx_params; OSSL_FUNC_encoder_does_selection_fn *does_selection; OSSL_FUNC_encoder_encode_fn *encode; OSSL_FUNC_encoder_import_object_fn *import_object; OSSL_FUNC_encoder_free_object_fn *free_object; }; struct ossl_decoder_st { struct ossl_endecode_base_st base; OSSL_FUNC_decoder_newctx_fn *newctx; OSSL_FUNC_decoder_freectx_fn *freectx; OSSL_FUNC_decoder_get_params_fn *get_params; OSSL_FUNC_decoder_gettable_params_fn *gettable_params; OSSL_FUNC_decoder_set_ctx_params_fn *set_ctx_params; OSSL_FUNC_decoder_settable_ctx_params_fn *settable_ctx_params; OSSL_FUNC_decoder_does_selection_fn *does_selection; OSSL_FUNC_decoder_decode_fn *decode; OSSL_FUNC_decoder_export_object_fn *export_object; }; struct ossl_encoder_instance_st { OSSL_ENCODER *encoder; /* Never NULL */ void *encoderctx; /* Never NULL */ const char *output_type; /* Never NULL */ const char *output_structure; /* May be NULL */ }; DEFINE_STACK_OF(OSSL_ENCODER_INSTANCE) void ossl_encoder_instance_free(OSSL_ENCODER_INSTANCE *encoder_inst); struct ossl_encoder_ctx_st { /* * Select what parts of an object will be encoded. This selection is * bit encoded, and the bits correspond to selection bits available with * the provider side operation. For example, when encoding an EVP_PKEY, * the OSSL_KEYMGMT_SELECT_ macros are used for this. */ int selection; /* * The desired output type. The encoder implementation must have a * gettable "output-type" parameter that this will match against. */ const char *output_type; /* * The desired output structure, if that's relevant for the type of * object being encoded. It may be used for selection of the starting * encoder implementations in a chain. */ const char *output_structure; /* * Decoders that are components of any current decoding path. */ STACK_OF(OSSL_ENCODER_INSTANCE) *encoder_insts; /* * The constructor and destructor of an object to pass to the first * encoder in a chain. */ OSSL_ENCODER_CONSTRUCT *construct; OSSL_ENCODER_CLEANUP *cleanup; void *construct_data; /* For any function that needs a passphrase reader */ struct ossl_passphrase_data_st pwdata; }; struct ossl_decoder_instance_st { OSSL_DECODER *decoder; /* Never NULL */ void *decoderctx; /* Never NULL */ const char *input_type; /* Never NULL */ const char *input_structure; /* May be NULL */ int input_type_id; unsigned int flag_input_structure_was_set : 1; }; DEFINE_STACK_OF(OSSL_DECODER_INSTANCE) struct ossl_decoder_ctx_st { /* * The caller may know the input type of the data they pass. If not, * this will remain NULL and the decoding functionality will start * with trying to decode with any desencoder in |decoder_insts|, * regardless of their respective input type. */ const char *start_input_type; /* * The desired input structure, if that's relevant for the type of * object being encoded. It may be used for selection of the ending * decoder implementations in a chain, i.e. those chosen using the * expected output data type. */ const char *input_structure; /* * Select what parts of an object are expected. This may affect what * decoder implementations are selected, because there are structures * that look different depending on this selection; for example, EVP_PKEY * objects often have different encoding structures for private keys, * public keys and key parameters. * This selection is bit encoded, and the bits correspond to selection * bits available with the provider side operation. For example, when * encoding an EVP_PKEY, the OSSL_KEYMGMT_SELECT_ macros are used for * this. */ int selection; /* * Decoders that are components of any current decoding path. */ STACK_OF(OSSL_DECODER_INSTANCE) *decoder_insts; /* * The constructors of a decoding, and its caller argument. */ OSSL_DECODER_CONSTRUCT *construct; OSSL_DECODER_CLEANUP *cleanup; void *construct_data; /* For any function that needs a passphrase reader */ struct ossl_passphrase_data_st pwdata; }; const OSSL_PROPERTY_LIST * ossl_decoder_parsed_properties(const OSSL_DECODER *decoder); const OSSL_PROPERTY_LIST * ossl_encoder_parsed_properties(const OSSL_ENCODER *encoder); int ossl_decoder_fast_is_a(OSSL_DECODER *decoder, const char *name, int *id_cache);
5,827
33.690476
77
h
openssl
openssl-master/crypto/encode_decode/encoder_meth.c
/* * Copyright 2019-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 <openssl/core.h> #include <openssl/core_dispatch.h> #include <openssl/encoder.h> #include <openssl/ui.h> #include "internal/core.h" #include "internal/namemap.h" #include "internal/property.h" #include "internal/provider.h" #include "crypto/encoder.h" #include "encoder_local.h" #include "crypto/context.h" /* * Encoder can have multiple names, separated with colons in a name string */ #define NAME_SEPARATOR ':' /* Simple method structure constructor and destructor */ static OSSL_ENCODER *ossl_encoder_new(void) { OSSL_ENCODER *encoder = NULL; if ((encoder = OPENSSL_zalloc(sizeof(*encoder))) == NULL) return NULL; if (!CRYPTO_NEW_REF(&encoder->base.refcnt, 1)) { OSSL_ENCODER_free(encoder); return NULL; } return encoder; } int OSSL_ENCODER_up_ref(OSSL_ENCODER *encoder) { int ref = 0; CRYPTO_UP_REF(&encoder->base.refcnt, &ref); return 1; } void OSSL_ENCODER_free(OSSL_ENCODER *encoder) { int ref = 0; if (encoder == NULL) return; CRYPTO_DOWN_REF(&encoder->base.refcnt, &ref); if (ref > 0) return; OPENSSL_free(encoder->base.name); ossl_property_free(encoder->base.parsed_propdef); ossl_provider_free(encoder->base.prov); CRYPTO_FREE_REF(&encoder->base.refcnt); OPENSSL_free(encoder); } /* Data to be passed through ossl_method_construct() */ struct encoder_data_st { OSSL_LIB_CTX *libctx; int id; /* For get_encoder_from_store() */ const char *names; /* For get_encoder_from_store() */ const char *propquery; /* For get_encoder_from_store() */ OSSL_METHOD_STORE *tmp_store; /* For get_tmp_encoder_store() */ unsigned int flag_construct_error_occurred : 1; }; /* * Generic routines to fetch / create ENCODER methods with * ossl_method_construct() */ /* Temporary encoder method store, constructor and destructor */ static void *get_tmp_encoder_store(void *data) { struct encoder_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_encoder_store(void *store) { if (store != NULL) ossl_method_store_free(store); } /* Get the permanent encoder store */ static OSSL_METHOD_STORE *get_encoder_store(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_ENCODER_STORE_INDEX); } static int reserve_encoder_store(void *store, void *data) { struct encoder_data_st *methdata = data; if (store == NULL && (store = get_encoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_lock_store(store); } static int unreserve_encoder_store(void *store, void *data) { struct encoder_data_st *methdata = data; if (store == NULL && (store = get_encoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_unlock_store(store); } /* Get encoder methods from a store, or put one in */ static void *get_encoder_from_store(void *store, const OSSL_PROVIDER **prov, void *data) { struct encoder_data_st *methdata = data; void *method = NULL; int id; /* * get_encoder_from_store() is only called to try and get the method * that OSSL_ENCODER_fetch() is asking for, and the name or name id are * passed via methdata. */ if ((id = methdata->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; id = ossl_namemap_name2num_n(namemap, methdata->names, l); } if (id == 0) return NULL; if (store == NULL && (store = get_encoder_store(methdata->libctx)) == NULL) return NULL; if (!ossl_method_store_fetch(store, id, methdata->propquery, prov, &method)) return NULL; return method; } static int put_encoder_in_store(void *store, void *method, const OSSL_PROVIDER *prov, const char *names, const char *propdef, void *data) { struct encoder_data_st *methdata = data; OSSL_NAMEMAP *namemap; int id; size_t l = 0; /* * put_encoder_in_store() is only called with an OSSL_ENCODER method that * was successfully created by construct_encoder() 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 || (id = ossl_namemap_name2num_n(namemap, names, l)) == 0) return 0; if (store == NULL && (store = get_encoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_store_add(store, prov, id, propdef, method, (int (*)(void *))OSSL_ENCODER_up_ref, (void (*)(void *))OSSL_ENCODER_free); } /* Create and populate a encoder method */ static void *encoder_from_algorithm(int id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { OSSL_ENCODER *encoder = NULL; const OSSL_DISPATCH *fns = algodef->implementation; OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); if ((encoder = ossl_encoder_new()) == NULL) return NULL; encoder->base.id = id; if ((encoder->base.name = ossl_algorithm_get1_first_name(algodef)) == NULL) { OSSL_ENCODER_free(encoder); return NULL; } encoder->base.algodef = algodef; if ((encoder->base.parsed_propdef = ossl_parse_property(libctx, algodef->property_definition)) == NULL) { OSSL_ENCODER_free(encoder); return NULL; } for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_ENCODER_NEWCTX: if (encoder->newctx == NULL) encoder->newctx = OSSL_FUNC_encoder_newctx(fns); break; case OSSL_FUNC_ENCODER_FREECTX: if (encoder->freectx == NULL) encoder->freectx = OSSL_FUNC_encoder_freectx(fns); break; case OSSL_FUNC_ENCODER_GET_PARAMS: if (encoder->get_params == NULL) encoder->get_params = OSSL_FUNC_encoder_get_params(fns); break; case OSSL_FUNC_ENCODER_GETTABLE_PARAMS: if (encoder->gettable_params == NULL) encoder->gettable_params = OSSL_FUNC_encoder_gettable_params(fns); break; case OSSL_FUNC_ENCODER_SET_CTX_PARAMS: if (encoder->set_ctx_params == NULL) encoder->set_ctx_params = OSSL_FUNC_encoder_set_ctx_params(fns); break; case OSSL_FUNC_ENCODER_SETTABLE_CTX_PARAMS: if (encoder->settable_ctx_params == NULL) encoder->settable_ctx_params = OSSL_FUNC_encoder_settable_ctx_params(fns); break; case OSSL_FUNC_ENCODER_DOES_SELECTION: if (encoder->does_selection == NULL) encoder->does_selection = OSSL_FUNC_encoder_does_selection(fns); break; case OSSL_FUNC_ENCODER_ENCODE: if (encoder->encode == NULL) encoder->encode = OSSL_FUNC_encoder_encode(fns); break; case OSSL_FUNC_ENCODER_IMPORT_OBJECT: if (encoder->import_object == NULL) encoder->import_object = OSSL_FUNC_encoder_import_object(fns); break; case OSSL_FUNC_ENCODER_FREE_OBJECT: if (encoder->free_object == NULL) encoder->free_object = OSSL_FUNC_encoder_free_object(fns); break; } } /* * Try to check that the method is sensible. * If you have a constructor, you must have a destructor and vice versa. * You must have the encoding driver functions. */ if (!((encoder->newctx == NULL && encoder->freectx == NULL) || (encoder->newctx != NULL && encoder->freectx != NULL) || (encoder->import_object != NULL && encoder->free_object != NULL) || (encoder->import_object == NULL && encoder->free_object == NULL)) || encoder->encode == NULL) { OSSL_ENCODER_free(encoder); ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_INVALID_PROVIDER_FUNCTIONS); return NULL; } if (prov != NULL && !ossl_provider_up_ref(prov)) { OSSL_ENCODER_free(encoder); return NULL; } encoder->base.prov = prov; return encoder; } /* * The core fetching functionality passes the names of the implementation. * This function is responsible to getting an identity number for them, * then call encoder_from_algorithm() with that identity number. */ static void *construct_encoder(const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov, void *data) { /* * This function is only called if get_encoder_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() will return its corresponding number. */ struct encoder_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 id = ossl_namemap_add_names(namemap, 0, names, NAME_SEPARATOR); void *method = NULL; if (id != 0) method = encoder_from_algorithm(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; } /* Intermediary function to avoid ugly casts, used below */ static void destruct_encoder(void *method, void *data) { OSSL_ENCODER_free(method); } static int up_ref_encoder(void *method) { return OSSL_ENCODER_up_ref(method); } static void free_encoder(void *method) { OSSL_ENCODER_free(method); } /* Fetching support. Can fetch by numeric identity or by name */ static OSSL_ENCODER * inner_ossl_encoder_fetch(struct encoder_data_st *methdata, const char *name, const char *properties) { OSSL_METHOD_STORE *store = get_encoder_store(methdata->libctx); OSSL_NAMEMAP *namemap = ossl_namemap_stored(methdata->libctx); const char *const propq = properties != NULL ? properties : ""; void *method = NULL; int unsupported, id; if (store == NULL || namemap == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } id = name != NULL ? ossl_namemap_name2num(namemap, name) : 0; /* * If we haven't found the name yet, chances are that the algorithm to * be fetched is unsupported. */ unsupported = id == 0; if (id == 0 || !ossl_method_store_cache_get(store, NULL, id, propq, &method)) { OSSL_METHOD_CONSTRUCT_METHOD mcm = { get_tmp_encoder_store, reserve_encoder_store, unreserve_encoder_store, get_encoder_from_store, put_encoder_in_store, construct_encoder, destruct_encoder }; OSSL_PROVIDER *prov = NULL; methdata->id = id; methdata->names = name; methdata->propquery = propq; methdata->flag_construct_error_occurred = 0; if ((method = ossl_method_construct(methdata->libctx, OSSL_OP_ENCODER, &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_encoder_from_store() and * put_encoder_in_store() above. */ if (id == 0) id = ossl_namemap_name2num(namemap, name); ossl_method_store_cache_set(store, prov, id, propq, method, up_ref_encoder, free_encoder); } /* * If we never were in the constructor, the algorithm to be fetched * is unsupported. */ unsupported = !methdata->flag_construct_error_occurred; } if ((id != 0 || name != NULL) && method == NULL) { int code = unsupported ? ERR_R_UNSUPPORTED : ERR_R_FETCH_FAILED; if (name == NULL) name = ossl_namemap_num2name(namemap, id, 0); ERR_raise_data(ERR_LIB_OSSL_ENCODER, code, "%s, Name (%s : %d), Properties (%s)", ossl_lib_ctx_get_descriptor(methdata->libctx), name == NULL ? "<null>" : name, id, properties == NULL ? "<null>" : properties); } return method; } OSSL_ENCODER *OSSL_ENCODER_fetch(OSSL_LIB_CTX *libctx, const char *name, const char *properties) { struct encoder_data_st methdata; void *method; methdata.libctx = libctx; methdata.tmp_store = NULL; method = inner_ossl_encoder_fetch(&methdata, name, properties); dealloc_tmp_encoder_store(methdata.tmp_store); return method; } int ossl_encoder_store_cache_flush(OSSL_LIB_CTX *libctx) { OSSL_METHOD_STORE *store = get_encoder_store(libctx); if (store != NULL) return ossl_method_store_cache_flush_all(store); return 1; } int ossl_encoder_store_remove_all_provided(const OSSL_PROVIDER *prov) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_METHOD_STORE *store = get_encoder_store(libctx); if (store != NULL) return ossl_method_store_remove_all_provided(store, prov); return 1; } /* * Library of basic method functions */ const OSSL_PROVIDER *OSSL_ENCODER_get0_provider(const OSSL_ENCODER *encoder) { if (!ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return encoder->base.prov; } const char *OSSL_ENCODER_get0_properties(const OSSL_ENCODER *encoder) { if (!ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return encoder->base.algodef->property_definition; } const OSSL_PROPERTY_LIST * ossl_encoder_parsed_properties(const OSSL_ENCODER *encoder) { if (!ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return encoder->base.parsed_propdef; } int ossl_encoder_get_number(const OSSL_ENCODER *encoder) { if (!ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return encoder->base.id; } const char *OSSL_ENCODER_get0_name(const OSSL_ENCODER *encoder) { return encoder->base.name; } const char *OSSL_ENCODER_get0_description(const OSSL_ENCODER *encoder) { return encoder->base.algodef->algorithm_description; } int OSSL_ENCODER_is_a(const OSSL_ENCODER *encoder, const char *name) { if (encoder->base.prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(encoder->base.prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_name2num(namemap, name) == encoder->base.id; } return 0; } struct do_one_data_st { void (*user_fn)(OSSL_ENCODER *encoder, void *arg); void *user_arg; }; static void do_one(ossl_unused int id, void *method, void *arg) { struct do_one_data_st *data = arg; data->user_fn(method, data->user_arg); } void OSSL_ENCODER_do_all_provided(OSSL_LIB_CTX *libctx, void (*user_fn)(OSSL_ENCODER *encoder, void *arg), void *user_arg) { struct encoder_data_st methdata; struct do_one_data_st data; methdata.libctx = libctx; methdata.tmp_store = NULL; (void)inner_ossl_encoder_fetch(&methdata, NULL, NULL /* properties */); data.user_fn = user_fn; data.user_arg = user_arg; if (methdata.tmp_store != NULL) ossl_method_store_do_all(methdata.tmp_store, &do_one, &data); ossl_method_store_do_all(get_encoder_store(libctx), &do_one, &data); dealloc_tmp_encoder_store(methdata.tmp_store); } int OSSL_ENCODER_names_do_all(const OSSL_ENCODER *encoder, void (*fn)(const char *name, void *data), void *data) { if (encoder == NULL) return 0; if (encoder->base.prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(encoder->base.prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_doall_names(namemap, encoder->base.id, fn, data); } return 1; } const OSSL_PARAM * OSSL_ENCODER_gettable_params(OSSL_ENCODER *encoder) { if (encoder != NULL && encoder->gettable_params != NULL) { void *provctx = ossl_provider_ctx(OSSL_ENCODER_get0_provider(encoder)); return encoder->gettable_params(provctx); } return NULL; } int OSSL_ENCODER_get_params(OSSL_ENCODER *encoder, OSSL_PARAM params[]) { if (encoder != NULL && encoder->get_params != NULL) return encoder->get_params(params); return 0; } const OSSL_PARAM *OSSL_ENCODER_settable_ctx_params(OSSL_ENCODER *encoder) { if (encoder != NULL && encoder->settable_ctx_params != NULL) { void *provctx = ossl_provider_ctx(OSSL_ENCODER_get0_provider(encoder)); return encoder->settable_ctx_params(provctx); } return NULL; } /* * Encoder context support */ OSSL_ENCODER_CTX *OSSL_ENCODER_CTX_new(void) { OSSL_ENCODER_CTX *ctx; ctx = OPENSSL_zalloc(sizeof(*ctx)); return ctx; } int OSSL_ENCODER_CTX_set_params(OSSL_ENCODER_CTX *ctx, const OSSL_PARAM params[]) { int ok = 1; size_t i; size_t l; if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ctx->encoder_insts == NULL) return 1; l = OSSL_ENCODER_CTX_get_num_encoders(ctx); for (i = 0; i < l; i++) { OSSL_ENCODER_INSTANCE *encoder_inst = sk_OSSL_ENCODER_INSTANCE_value(ctx->encoder_insts, i); OSSL_ENCODER *encoder = OSSL_ENCODER_INSTANCE_get_encoder(encoder_inst); void *encoderctx = OSSL_ENCODER_INSTANCE_get_encoder_ctx(encoder_inst); if (encoderctx == NULL || encoder->set_ctx_params == NULL) continue; if (!encoder->set_ctx_params(encoderctx, params)) ok = 0; } return ok; } void OSSL_ENCODER_CTX_free(OSSL_ENCODER_CTX *ctx) { if (ctx != NULL) { sk_OSSL_ENCODER_INSTANCE_pop_free(ctx->encoder_insts, ossl_encoder_instance_free); OPENSSL_free(ctx->construct_data); ossl_pw_clear_passphrase_data(&ctx->pwdata); OPENSSL_free(ctx); } }
20,255
29.972477
81
c
openssl
openssl-master/crypto/encode_decode/encoder_pkey.c
/* * Copyright 2019-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 <openssl/err.h> #include <openssl/ui.h> #include <openssl/params.h> #include <openssl/encoder.h> #include <openssl/core_names.h> #include <openssl/provider.h> #include <openssl/safestack.h> #include <openssl/trace.h> #include "internal/provider.h" #include "internal/property.h" #include "internal/namemap.h" #include "crypto/evp.h" #include "encoder_local.h" DEFINE_STACK_OF(OSSL_ENCODER) int OSSL_ENCODER_CTX_set_cipher(OSSL_ENCODER_CTX *ctx, const char *cipher_name, const char *propquery) { OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ENCODER_PARAM_CIPHER, (void *)cipher_name, 0); params[1] = OSSL_PARAM_construct_utf8_string(OSSL_ENCODER_PARAM_PROPERTIES, (void *)propquery, 0); return OSSL_ENCODER_CTX_set_params(ctx, params); } int OSSL_ENCODER_CTX_set_passphrase(OSSL_ENCODER_CTX *ctx, const unsigned char *kstr, size_t klen) { return ossl_pw_set_passphrase(&ctx->pwdata, kstr, klen); } int OSSL_ENCODER_CTX_set_passphrase_ui(OSSL_ENCODER_CTX *ctx, const UI_METHOD *ui_method, void *ui_data) { return ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data); } int OSSL_ENCODER_CTX_set_pem_password_cb(OSSL_ENCODER_CTX *ctx, pem_password_cb *cb, void *cbarg) { return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg); } int OSSL_ENCODER_CTX_set_passphrase_cb(OSSL_ENCODER_CTX *ctx, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { return ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, cb, cbarg); } /* * Support for OSSL_ENCODER_CTX_new_for_type: * finding a suitable encoder */ struct collected_encoder_st { STACK_OF(OPENSSL_CSTRING) *names; int *id_names; const char *output_structure; const char *output_type; const OSSL_PROVIDER *keymgmt_prov; OSSL_ENCODER_CTX *ctx; unsigned int flag_find_same_provider:1; int error_occurred; }; static void collect_encoder(OSSL_ENCODER *encoder, void *arg) { struct collected_encoder_st *data = arg; const OSSL_PROVIDER *prov; if (data->error_occurred) return; data->error_occurred = 1; /* Assume the worst */ prov = OSSL_ENCODER_get0_provider(encoder); /* * collect_encoder() is called in two passes, one where the encoders * from the same provider as the keymgmt are looked up, and one where * the other encoders are looked up. |data->flag_find_same_provider| * tells us which pass we're in. */ if ((data->keymgmt_prov == prov) == data->flag_find_same_provider) { void *provctx = OSSL_PROVIDER_get0_provider_ctx(prov); int i, end_i = sk_OPENSSL_CSTRING_num(data->names); int match; for (i = 0; i < end_i; i++) { if (data->flag_find_same_provider) match = (data->id_names[i] == encoder->base.id); else match = OSSL_ENCODER_is_a(encoder, sk_OPENSSL_CSTRING_value(data->names, i)); if (!match || (encoder->does_selection != NULL && !encoder->does_selection(provctx, data->ctx->selection)) || (data->keymgmt_prov != prov && encoder->import_object == NULL)) continue; /* Only add each encoder implementation once */ if (OSSL_ENCODER_CTX_add_encoder(data->ctx, encoder)) break; } } data->error_occurred = 0; /* All is good now */ } struct collected_names_st { STACK_OF(OPENSSL_CSTRING) *names; unsigned int error_occurred:1; }; static void collect_name(const char *name, void *arg) { struct collected_names_st *data = arg; if (data->error_occurred) return; data->error_occurred = 1; /* Assume the worst */ if (sk_OPENSSL_CSTRING_push(data->names, name) <= 0) return; data->error_occurred = 0; /* All is good now */ } /* * Support for OSSL_ENCODER_to_bio: * writing callback for the OSSL_PARAM (the implementation doesn't have * intimate knowledge of the provider side object) */ struct construct_data_st { const EVP_PKEY *pk; int selection; OSSL_ENCODER_INSTANCE *encoder_inst; const void *obj; void *constructed_obj; }; static int encoder_import_cb(const OSSL_PARAM params[], void *arg) { struct construct_data_st *construct_data = arg; OSSL_ENCODER_INSTANCE *encoder_inst = construct_data->encoder_inst; OSSL_ENCODER *encoder = OSSL_ENCODER_INSTANCE_get_encoder(encoder_inst); void *encoderctx = OSSL_ENCODER_INSTANCE_get_encoder_ctx(encoder_inst); construct_data->constructed_obj = encoder->import_object(encoderctx, construct_data->selection, params); return (construct_data->constructed_obj != NULL); } static const void * encoder_construct_pkey(OSSL_ENCODER_INSTANCE *encoder_inst, void *arg) { struct construct_data_st *data = arg; if (data->obj == NULL) { OSSL_ENCODER *encoder = OSSL_ENCODER_INSTANCE_get_encoder(encoder_inst); const EVP_PKEY *pk = data->pk; const OSSL_PROVIDER *k_prov = EVP_KEYMGMT_get0_provider(pk->keymgmt); const OSSL_PROVIDER *e_prov = OSSL_ENCODER_get0_provider(encoder); if (k_prov != e_prov) { data->encoder_inst = encoder_inst; if (!evp_keymgmt_export(pk->keymgmt, pk->keydata, data->selection, &encoder_import_cb, data)) return NULL; data->obj = data->constructed_obj; } else { data->obj = pk->keydata; } } return data->obj; } static void encoder_destruct_pkey(void *arg) { struct construct_data_st *data = arg; if (data->encoder_inst != NULL) { OSSL_ENCODER *encoder = OSSL_ENCODER_INSTANCE_get_encoder(data->encoder_inst); encoder->free_object(data->constructed_obj); } data->constructed_obj = NULL; } /* * OSSL_ENCODER_CTX_new_for_pkey() returns a ctx with no encoder if * it couldn't find a suitable encoder. This allows a caller to detect if * a suitable encoder was found, with OSSL_ENCODER_CTX_get_num_encoder(), * and to use fallback methods if the result is NULL. */ static int ossl_encoder_ctx_setup_for_pkey(OSSL_ENCODER_CTX *ctx, const EVP_PKEY *pkey, int selection, const char *propquery) { struct construct_data_st *data = NULL; const OSSL_PROVIDER *prov = NULL; OSSL_LIB_CTX *libctx = NULL; int ok = 0, i, end; OSSL_NAMEMAP *namemap; if (!ossl_assert(ctx != NULL) || !ossl_assert(pkey != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (evp_pkey_is_provided(pkey)) { prov = EVP_KEYMGMT_get0_provider(pkey->keymgmt); libctx = ossl_provider_libctx(prov); } if (pkey->keymgmt != NULL) { struct collected_encoder_st encoder_data; struct collected_names_st keymgmt_data; if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL) goto err; /* * Select the first encoder implementations in two steps. * First, collect the keymgmt names, then the encoders that match. */ keymgmt_data.names = sk_OPENSSL_CSTRING_new_null(); if (keymgmt_data.names == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_CRYPTO_LIB); goto err; } keymgmt_data.error_occurred = 0; EVP_KEYMGMT_names_do_all(pkey->keymgmt, collect_name, &keymgmt_data); if (keymgmt_data.error_occurred) { sk_OPENSSL_CSTRING_free(keymgmt_data.names); goto err; } encoder_data.names = keymgmt_data.names; encoder_data.output_type = ctx->output_type; encoder_data.output_structure = ctx->output_structure; encoder_data.error_occurred = 0; encoder_data.keymgmt_prov = prov; encoder_data.ctx = ctx; encoder_data.id_names = NULL; /* * collect_encoder() is called many times, and for every call it converts all encoder_data.names * into namemap ids if it calls OSSL_ENCODER_is_a(). We cache the ids here instead, * and can use them for encoders with the same provider as the keymgmt. */ namemap = ossl_namemap_stored(libctx); end = sk_OPENSSL_CSTRING_num(encoder_data.names); if (end > 0) { encoder_data.id_names = OPENSSL_malloc(end * sizeof(int)); if (encoder_data.id_names == NULL) goto err; for (i = 0; i < end; ++i) { const char *name = sk_OPENSSL_CSTRING_value(keymgmt_data.names, i); encoder_data.id_names[i] = ossl_namemap_name2num(namemap, name); } } /* * Place the encoders with the a different provider as the keymgmt * last (the chain is processed in reverse order) */ encoder_data.flag_find_same_provider = 0; OSSL_ENCODER_do_all_provided(libctx, collect_encoder, &encoder_data); /* * Place the encoders with the same provider as the keymgmt first * (the chain is processed in reverse order) */ encoder_data.flag_find_same_provider = 1; OSSL_ENCODER_do_all_provided(libctx, collect_encoder, &encoder_data); OPENSSL_free(encoder_data.id_names); sk_OPENSSL_CSTRING_free(keymgmt_data.names); if (encoder_data.error_occurred) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_CRYPTO_LIB); goto err; } } if (data != NULL && OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0) { if (!OSSL_ENCODER_CTX_set_construct(ctx, encoder_construct_pkey) || !OSSL_ENCODER_CTX_set_construct_data(ctx, data) || !OSSL_ENCODER_CTX_set_cleanup(ctx, encoder_destruct_pkey)) goto err; data->pk = pkey; data->selection = selection; data = NULL; /* Avoid it being freed */ } ok = 1; err: if (data != NULL) { OSSL_ENCODER_CTX_set_construct_data(ctx, NULL); OPENSSL_free(data); } return ok; } OSSL_ENCODER_CTX *OSSL_ENCODER_CTX_new_for_pkey(const EVP_PKEY *pkey, int selection, const char *output_type, const char *output_struct, const char *propquery) { OSSL_ENCODER_CTX *ctx = NULL; OSSL_LIB_CTX *libctx = NULL; if (pkey == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!evp_pkey_is_assigned(pkey)) { ERR_raise_data(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_INVALID_ARGUMENT, "The passed EVP_PKEY must be assigned a key"); return NULL; } if ((ctx = OSSL_ENCODER_CTX_new()) == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_OSSL_ENCODER_LIB); return NULL; } if (evp_pkey_is_provided(pkey)) { const OSSL_PROVIDER *prov = EVP_KEYMGMT_get0_provider(pkey->keymgmt); libctx = ossl_provider_libctx(prov); } OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "(ctx %p) Looking for %s encoders with selection %d\n", (void *)ctx, EVP_PKEY_get0_type_name(pkey), selection); BIO_printf(trc_out, " output type: %s, output structure: %s\n", output_type, output_struct); } OSSL_TRACE_END(ENCODER); if (OSSL_ENCODER_CTX_set_output_type(ctx, output_type) && (output_struct == NULL || OSSL_ENCODER_CTX_set_output_structure(ctx, output_struct)) && OSSL_ENCODER_CTX_set_selection(ctx, selection) && ossl_encoder_ctx_setup_for_pkey(ctx, pkey, selection, propquery) && OSSL_ENCODER_CTX_add_extra(ctx, libctx, propquery)) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; int save_parameters = pkey->save_parameters; params[0] = OSSL_PARAM_construct_int(OSSL_ENCODER_PARAM_SAVE_PARAMETERS, &save_parameters); /* ignoring error as this is only auxiliary parameter */ (void)OSSL_ENCODER_CTX_set_params(ctx, params); OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "(ctx %p) Got %d encoders\n", (void *)ctx, OSSL_ENCODER_CTX_get_num_encoders(ctx)); } OSSL_TRACE_END(ENCODER); return ctx; } OSSL_ENCODER_CTX_free(ctx); return NULL; }
13,577
32.860349
104
c
openssl
openssl-master/crypto/engine/eng_all.c
/* * Copyright 2001-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 "internal/cryptlib.h" #include "eng_local.h" void ENGINE_load_builtin_engines(void) { OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_ALL_BUILTIN, NULL); } #ifndef OPENSSL_NO_DEPRECATED_1_1_0 # if (defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)) void ENGINE_setup_bsd_cryptodev(void) { } # endif #endif
671
25.88
77
c
openssl
openssl-master/crypto/engine/eng_cnf.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 */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include "eng_local.h" #include <openssl/conf.h> #include <openssl/trace.h> /* ENGINE config module */ static const char *skip_dot(const char *name) { const char *p = strchr(name, '.'); if (p != NULL) return p + 1; return name; } static STACK_OF(ENGINE) *initialized_engines = NULL; static int int_engine_init(ENGINE *e) { if (!ENGINE_init(e)) return 0; if (!initialized_engines) initialized_engines = sk_ENGINE_new_null(); if (!initialized_engines || !sk_ENGINE_push(initialized_engines, e)) { ENGINE_finish(e); return 0; } return 1; } static int int_engine_configure(const char *name, const char *value, const CONF *cnf) { int i; int ret = 0; long do_init = -1; STACK_OF(CONF_VALUE) *ecmds; CONF_VALUE *ecmd = NULL; const char *ctrlname, *ctrlvalue; ENGINE *e = NULL; int soft = 0; name = skip_dot(name); OSSL_TRACE1(CONF, "Configuring engine %s\n", name); /* Value is a section containing ENGINE commands */ ecmds = NCONF_get_section(cnf, value); if (!ecmds) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_ENGINE_SECTION_ERROR); return 0; } for (i = 0; i < sk_CONF_VALUE_num(ecmds); i++) { ecmd = sk_CONF_VALUE_value(ecmds, i); ctrlname = skip_dot(ecmd->name); ctrlvalue = ecmd->value; OSSL_TRACE2(CONF, "ENGINE: doing ctrl(%s,%s)\n", ctrlname, ctrlvalue); /* First handle some special pseudo ctrls */ /* Override engine name to use */ if (strcmp(ctrlname, "engine_id") == 0) name = ctrlvalue; else if (strcmp(ctrlname, "soft_load") == 0) soft = 1; /* Load a dynamic ENGINE */ else if (strcmp(ctrlname, "dynamic_path") == 0) { e = ENGINE_by_id("dynamic"); if (!e) goto err; if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", ctrlvalue, 0)) goto err; if (!ENGINE_ctrl_cmd_string(e, "LIST_ADD", "2", 0)) goto err; if (!ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) goto err; } /* ... add other pseudos here ... */ else { /* * At this point we need an ENGINE structural reference if we * don't already have one. */ if (!e) { e = ENGINE_by_id(name); if (!e && soft) { ERR_clear_error(); return 1; } if (!e) goto err; } /* * Allow "EMPTY" to mean no value: this allows a valid "value" to * be passed to ctrls of type NO_INPUT */ if (strcmp(ctrlvalue, "EMPTY") == 0) ctrlvalue = NULL; if (strcmp(ctrlname, "init") == 0) { if (!NCONF_get_number_e(cnf, value, "init", &do_init)) goto err; if (do_init == 1) { if (!int_engine_init(e)) goto err; } else if (do_init != 0) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INVALID_INIT_VALUE); goto err; } } else if (strcmp(ctrlname, "default_algorithms") == 0) { if (!ENGINE_set_default_string(e, ctrlvalue)) goto err; } else if (!ENGINE_ctrl_cmd_string(e, ctrlname, ctrlvalue, 0)) goto err; } } if (e && (do_init == -1) && !int_engine_init(e)) { ecmd = NULL; goto err; } ret = 1; err: if (ret != 1) { if (ecmd == NULL) ERR_raise(ERR_LIB_ENGINE, ENGINE_R_ENGINE_CONFIGURATION_ERROR); else ERR_raise_data(ERR_LIB_ENGINE, ENGINE_R_ENGINE_CONFIGURATION_ERROR, "section=%s, name=%s, value=%s", ecmd->section, ecmd->name, ecmd->value); } ENGINE_free(e); return ret; } static int int_engine_module_init(CONF_IMODULE *md, const CONF *cnf) { STACK_OF(CONF_VALUE) *elist; CONF_VALUE *cval; int i; OSSL_TRACE2(CONF, "Called engine module: name %s, value %s\n", CONF_imodule_get_name(md), CONF_imodule_get_value(md)); /* Value is a section containing ENGINEs to configure */ elist = NCONF_get_section(cnf, CONF_imodule_get_value(md)); if (!elist) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_ENGINES_SECTION_ERROR); return 0; } for (i = 0; i < sk_CONF_VALUE_num(elist); i++) { cval = sk_CONF_VALUE_value(elist, i); if (!int_engine_configure(cval->name, cval->value, cnf)) return 0; } return 1; } static void int_engine_module_finish(CONF_IMODULE *md) { ENGINE *e; while ((e = sk_ENGINE_pop(initialized_engines))) ENGINE_finish(e); sk_ENGINE_free(initialized_engines); initialized_engines = NULL; } void ENGINE_add_conf_module(void) { CONF_module_add("engines", int_engine_module_init, int_engine_module_finish); }
5,602
29.123656
85
c
openssl
openssl-master/crypto/engine/eng_ctrl.c
/* * Copyright 2001-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 some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include "eng_local.h" /* * When querying a ENGINE-specific control command's 'description', this * string is used if the ENGINE_CMD_DEFN has cmd_desc set to NULL. */ static const char *int_no_description = ""; /* * These internal functions handle 'CMD'-related control commands when the * ENGINE in question has asked us to take care of it (ie. the ENGINE did not * set the ENGINE_FLAGS_MANUAL_CMD_CTRL flag. */ static int int_ctrl_cmd_is_null(const ENGINE_CMD_DEFN *defn) { if ((defn->cmd_num == 0) || (defn->cmd_name == NULL)) return 1; return 0; } static int int_ctrl_cmd_by_name(const ENGINE_CMD_DEFN *defn, const char *s) { int idx = 0; while (!int_ctrl_cmd_is_null(defn) && (strcmp(defn->cmd_name, s) != 0)) { idx++; defn++; } if (int_ctrl_cmd_is_null(defn)) /* The given name wasn't found */ return -1; return idx; } static int int_ctrl_cmd_by_num(const ENGINE_CMD_DEFN *defn, unsigned int num) { int idx = 0; /* * NB: It is stipulated that 'cmd_defn' lists are ordered by cmd_num. So * our searches don't need to take any longer than necessary. */ while (!int_ctrl_cmd_is_null(defn) && (defn->cmd_num < num)) { idx++; defn++; } if (defn->cmd_num == num) return idx; /* The given cmd_num wasn't found */ return -1; } static int int_ctrl_helper(ENGINE *e, int cmd, long i, void *p, void (*f) (void)) { int idx; char *s = (char *)p; const ENGINE_CMD_DEFN *cdp; /* Take care of the easy one first (eg. it requires no searches) */ if (cmd == ENGINE_CTRL_GET_FIRST_CMD_TYPE) { if ((e->cmd_defns == NULL) || int_ctrl_cmd_is_null(e->cmd_defns)) return 0; return e->cmd_defns->cmd_num; } /* One or two commands require that "p" be a valid string buffer */ if ((cmd == ENGINE_CTRL_GET_CMD_FROM_NAME) || (cmd == ENGINE_CTRL_GET_NAME_FROM_CMD) || (cmd == ENGINE_CTRL_GET_DESC_FROM_CMD)) { if (s == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return -1; } } /* Now handle cmd_name -> cmd_num conversion */ if (cmd == ENGINE_CTRL_GET_CMD_FROM_NAME) { if ((e->cmd_defns == NULL) || ((idx = int_ctrl_cmd_by_name(e->cmd_defns, s)) < 0)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INVALID_CMD_NAME); return -1; } return e->cmd_defns[idx].cmd_num; } /* * For the rest of the commands, the 'long' argument must specify a valid * command number - so we need to conduct a search. */ if ((e->cmd_defns == NULL) || ((idx = int_ctrl_cmd_by_num(e->cmd_defns, (unsigned int)i)) < 0)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INVALID_CMD_NUMBER); return -1; } /* Now the logic splits depending on command type */ cdp = &e->cmd_defns[idx]; switch (cmd) { case ENGINE_CTRL_GET_NEXT_CMD_TYPE: cdp++; return int_ctrl_cmd_is_null(cdp) ? 0 : cdp->cmd_num; case ENGINE_CTRL_GET_NAME_LEN_FROM_CMD: return strlen(cdp->cmd_name); case ENGINE_CTRL_GET_NAME_FROM_CMD: return strlen(strcpy(s, cdp->cmd_name)); case ENGINE_CTRL_GET_DESC_LEN_FROM_CMD: return strlen(cdp->cmd_desc == NULL ? int_no_description : cdp->cmd_desc); case ENGINE_CTRL_GET_DESC_FROM_CMD: return strlen(strcpy(s, cdp->cmd_desc == NULL ? int_no_description : cdp->cmd_desc)); case ENGINE_CTRL_GET_CMD_FLAGS: return cdp->cmd_flags; } /* Shouldn't really be here ... */ ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); return -1; } int ENGINE_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void)) { int ctrl_exists; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctrl_exists = ((e->ctrl == NULL) ? 0 : 1); /* * Intercept any "root-level" commands before trying to hand them on to * ctrl() handlers. */ switch (cmd) { case ENGINE_CTRL_HAS_CTRL_FUNCTION: return ctrl_exists; case ENGINE_CTRL_GET_FIRST_CMD_TYPE: case ENGINE_CTRL_GET_NEXT_CMD_TYPE: case ENGINE_CTRL_GET_CMD_FROM_NAME: case ENGINE_CTRL_GET_NAME_LEN_FROM_CMD: case ENGINE_CTRL_GET_NAME_FROM_CMD: case ENGINE_CTRL_GET_DESC_LEN_FROM_CMD: case ENGINE_CTRL_GET_DESC_FROM_CMD: case ENGINE_CTRL_GET_CMD_FLAGS: if (ctrl_exists && !(e->flags & ENGINE_FLAGS_MANUAL_CMD_CTRL)) return int_ctrl_helper(e, cmd, i, p, f); if (!ctrl_exists) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_NO_CONTROL_FUNCTION); /* * For these cmd-related functions, failure is indicated by a -1 * return value (because 0 is used as a valid return in some * places). */ return -1; } default: break; } /* Anything else requires a ctrl() handler to exist. */ if (!ctrl_exists) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_NO_CONTROL_FUNCTION); return 0; } return e->ctrl(e, cmd, i, p, f); } int ENGINE_cmd_is_executable(ENGINE *e, int cmd) { int flags; if ((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, cmd, NULL, NULL)) < 0) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INVALID_CMD_NUMBER); return 0; } if (!(flags & ENGINE_CMD_FLAG_NO_INPUT) && !(flags & ENGINE_CMD_FLAG_NUMERIC) && !(flags & ENGINE_CMD_FLAG_STRING)) return 0; return 1; } int ENGINE_ctrl_cmd(ENGINE *e, const char *cmd_name, long i, void *p, void (*f) (void), int cmd_optional) { int num; if (e == NULL || cmd_name == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (e->ctrl == NULL || (num = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FROM_NAME, 0, (void *)cmd_name, NULL)) <= 0) { /* * If the command didn't *have* to be supported, we fake success. * This allows certain settings to be specified for multiple ENGINEs * and only require a change of ENGINE id (without having to * selectively apply settings). Eg. changing from a hardware device * back to the regular software ENGINE without editing the config * file, etc. */ if (cmd_optional) { ERR_clear_error(); return 1; } ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INVALID_CMD_NAME); return 0; } /* * Force the result of the control command to 0 or 1, for the reasons * mentioned before. */ if (ENGINE_ctrl(e, num, i, p, f) > 0) return 1; return 0; } int ENGINE_ctrl_cmd_string(ENGINE *e, const char *cmd_name, const char *arg, int cmd_optional) { int num, flags; long l; char *ptr; if (e == NULL || cmd_name == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (e->ctrl == NULL || (num = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FROM_NAME, 0, (void *)cmd_name, NULL)) <= 0) { /* * If the command didn't *have* to be supported, we fake success. * This allows certain settings to be specified for multiple ENGINEs * and only require a change of ENGINE id (without having to * selectively apply settings). Eg. changing from a hardware device * back to the regular software ENGINE without editing the config * file, etc. */ if (cmd_optional) { ERR_clear_error(); return 1; } ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INVALID_CMD_NAME); return 0; } if (!ENGINE_cmd_is_executable(e, num)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_CMD_NOT_EXECUTABLE); return 0; } flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, num, NULL, NULL); if (flags < 0) { /* * Shouldn't happen, given that ENGINE_cmd_is_executable() returned * success. */ ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); return 0; } /* * If the command takes no input, there must be no input. And vice versa. */ if (flags & ENGINE_CMD_FLAG_NO_INPUT) { if (arg != NULL) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_COMMAND_TAKES_NO_INPUT); return 0; } /* * We deliberately force the result of ENGINE_ctrl() to 0 or 1 rather * than returning it as "return data". This is to ensure usage of * these commands is consistent across applications and that certain * applications don't understand it one way, and others another. */ if (ENGINE_ctrl(e, num, 0, (void *)arg, NULL) > 0) return 1; return 0; } /* So, we require input */ if (arg == NULL) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_COMMAND_TAKES_INPUT); return 0; } /* If it takes string input, that's easy */ if (flags & ENGINE_CMD_FLAG_STRING) { /* Same explanation as above */ if (ENGINE_ctrl(e, num, 0, (void *)arg, NULL) > 0) return 1; return 0; } /* * If it doesn't take numeric either, then it is unsupported for use in a * config-setting situation, which is what this function is for. This * should never happen though, because ENGINE_cmd_is_executable() was * used. */ if (!(flags & ENGINE_CMD_FLAG_NUMERIC)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); return 0; } l = strtol(arg, &ptr, 10); if ((arg == ptr) || (*ptr != '\0')) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER); return 0; } /* * Force the result of the control command to 0 or 1, for the reasons * mentioned before. */ if (ENGINE_ctrl(e, num, l, NULL, NULL) > 0) return 1; return 0; }
10,658
32
78
c
openssl
openssl-master/crypto/engine/eng_dyn.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 */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include "eng_local.h" #include "internal/dso.h" #include <openssl/crypto.h> /* * Shared libraries implementing ENGINEs for use by the "dynamic" ENGINE * loader should implement the hook-up functions with the following * prototypes. */ /* Our ENGINE handlers */ static int dynamic_init(ENGINE *e); static int dynamic_finish(ENGINE *e); static int dynamic_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void)); /* Predeclare our context type */ typedef struct st_dynamic_data_ctx dynamic_data_ctx; /* The implementation for the important control command */ static int dynamic_load(ENGINE *e, dynamic_data_ctx *ctx); #define DYNAMIC_CMD_SO_PATH ENGINE_CMD_BASE #define DYNAMIC_CMD_NO_VCHECK (ENGINE_CMD_BASE + 1) #define DYNAMIC_CMD_ID (ENGINE_CMD_BASE + 2) #define DYNAMIC_CMD_LIST_ADD (ENGINE_CMD_BASE + 3) #define DYNAMIC_CMD_DIR_LOAD (ENGINE_CMD_BASE + 4) #define DYNAMIC_CMD_DIR_ADD (ENGINE_CMD_BASE + 5) #define DYNAMIC_CMD_LOAD (ENGINE_CMD_BASE + 6) /* The constants used when creating the ENGINE */ static const char *engine_dynamic_id = "dynamic"; static const char *engine_dynamic_name = "Dynamic engine loading support"; static const ENGINE_CMD_DEFN dynamic_cmd_defns[] = { {DYNAMIC_CMD_SO_PATH, "SO_PATH", "Specifies the path to the new ENGINE shared library", ENGINE_CMD_FLAG_STRING}, {DYNAMIC_CMD_NO_VCHECK, "NO_VCHECK", "Specifies to continue even if version checking fails (boolean)", ENGINE_CMD_FLAG_NUMERIC}, {DYNAMIC_CMD_ID, "ID", "Specifies an ENGINE id name for loading", ENGINE_CMD_FLAG_STRING}, {DYNAMIC_CMD_LIST_ADD, "LIST_ADD", "Whether to add a loaded ENGINE to the internal list (0=no,1=yes,2=mandatory)", ENGINE_CMD_FLAG_NUMERIC}, {DYNAMIC_CMD_DIR_LOAD, "DIR_LOAD", "Specifies whether to load from 'DIR_ADD' directories (0=no,1=yes,2=mandatory)", ENGINE_CMD_FLAG_NUMERIC}, {DYNAMIC_CMD_DIR_ADD, "DIR_ADD", "Adds a directory from which ENGINEs can be loaded", ENGINE_CMD_FLAG_STRING}, {DYNAMIC_CMD_LOAD, "LOAD", "Load up the ENGINE specified by other settings", ENGINE_CMD_FLAG_NO_INPUT}, {0, NULL, NULL, 0} }; /* * Loading code stores state inside the ENGINE structure via the "ex_data" * element. We load all our state into a single structure and use that as a * single context in the "ex_data" stack. */ struct st_dynamic_data_ctx { /* The DSO object we load that supplies the ENGINE code */ DSO *dynamic_dso; /* * The function pointer to the version checking shared library function */ dynamic_v_check_fn v_check; /* * The function pointer to the engine-binding shared library function */ dynamic_bind_engine bind_engine; /* The default name/path for loading the shared library */ char *DYNAMIC_LIBNAME; /* Whether to continue loading on a version check failure */ int no_vcheck; /* If non-NULL, stipulates the 'id' of the ENGINE to be loaded */ char *engine_id; /* * If non-zero, a successfully loaded ENGINE should be added to the * internal ENGINE list. If 2, the add must succeed or the entire load * should fail. */ int list_add_value; /* The symbol name for the version checking function */ const char *DYNAMIC_F1; /* The symbol name for the "initialise ENGINE structure" function */ const char *DYNAMIC_F2; /* * Whether to never use 'dirs', use 'dirs' as a fallback, or only use * 'dirs' for loading. Default is to use 'dirs' as a fallback. */ int dir_load; /* A stack of directories from which ENGINEs could be loaded */ STACK_OF(OPENSSL_STRING) *dirs; }; /* * This is the "ex_data" index we obtain and reserve for use with our context * structure. */ static int dynamic_ex_data_idx = -1; static void int_free_str(char *s) { OPENSSL_free(s); } /* * Because our ex_data element may or may not get allocated depending on * whether a "first-use" occurs before the ENGINE is freed, we have a memory * leak problem to solve. We can't declare a "new" handler for the ex_data as * we don't want a dynamic_data_ctx in *all* ENGINE structures of all types * (this is a bug in the design of CRYPTO_EX_DATA). As such, we just declare * a "free" handler and that will get called if an ENGINE is being destroyed * and there was an ex_data element corresponding to our context type. */ static void dynamic_data_ctx_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { if (ptr) { dynamic_data_ctx *ctx = (dynamic_data_ctx *)ptr; DSO_free(ctx->dynamic_dso); OPENSSL_free(ctx->DYNAMIC_LIBNAME); OPENSSL_free(ctx->engine_id); sk_OPENSSL_STRING_pop_free(ctx->dirs, int_free_str); OPENSSL_free(ctx); } } /* * Construct the per-ENGINE context. We create it blindly and then use a lock * to check for a race - if so, all but one of the threads "racing" will have * wasted their time. The alternative involves creating everything inside the * lock which is far worse. */ static int dynamic_set_data_ctx(ENGINE *e, dynamic_data_ctx **ctx) { dynamic_data_ctx *c = OPENSSL_zalloc(sizeof(*c)); int ret = 0; if (c == NULL) return 0; c->dirs = sk_OPENSSL_STRING_new_null(); if (c->dirs == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); goto end; } c->DYNAMIC_F1 = "v_check"; c->DYNAMIC_F2 = "bind_engine"; c->dir_load = 1; if (!CRYPTO_THREAD_write_lock(global_engine_lock)) goto end; if ((*ctx = (dynamic_data_ctx *)ENGINE_get_ex_data(e, dynamic_ex_data_idx)) == NULL) { /* Good, we're the first */ ret = ENGINE_set_ex_data(e, dynamic_ex_data_idx, c); if (ret) { *ctx = c; c = NULL; } } CRYPTO_THREAD_unlock(global_engine_lock); ret = 1; /* * If we lost the race to set the context, c is non-NULL and *ctx is the * context of the thread that won. */ end: if (c != NULL) sk_OPENSSL_STRING_free(c->dirs); OPENSSL_free(c); return ret; } /* * This function retrieves the context structure from an ENGINE's "ex_data", * or if it doesn't exist yet, sets it up. */ static dynamic_data_ctx *dynamic_get_data_ctx(ENGINE *e) { dynamic_data_ctx *ctx; if (dynamic_ex_data_idx < 0) { /* * Create and register the ENGINE ex_data, and associate our "free" * function with it to ensure any allocated contexts get freed when * an ENGINE goes underground. */ int new_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, dynamic_data_ctx_free_func); if (new_idx == -1) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_NO_INDEX); return NULL; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return NULL; /* Avoid a race by checking again inside this lock */ if (dynamic_ex_data_idx < 0) { /* Good, someone didn't beat us to it */ dynamic_ex_data_idx = new_idx; new_idx = -1; } CRYPTO_THREAD_unlock(global_engine_lock); /* * In theory we could "give back" the index here if (new_idx>-1), but * it's not possible and wouldn't gain us much if it were. */ } ctx = (dynamic_data_ctx *)ENGINE_get_ex_data(e, dynamic_ex_data_idx); /* Check if the context needs to be created */ if ((ctx == NULL) && !dynamic_set_data_ctx(e, &ctx)) /* "set_data" will set errors if necessary */ return NULL; return ctx; } static ENGINE *engine_dynamic(void) { ENGINE *ret = ENGINE_new(); if (ret == NULL) return NULL; if (!ENGINE_set_id(ret, engine_dynamic_id) || !ENGINE_set_name(ret, engine_dynamic_name) || !ENGINE_set_init_function(ret, dynamic_init) || !ENGINE_set_finish_function(ret, dynamic_finish) || !ENGINE_set_ctrl_function(ret, dynamic_ctrl) || !ENGINE_set_flags(ret, ENGINE_FLAGS_BY_ID_COPY) || !ENGINE_set_cmd_defns(ret, dynamic_cmd_defns)) { ENGINE_free(ret); return NULL; } return ret; } void engine_load_dynamic_int(void) { ENGINE *toadd = engine_dynamic(); if (!toadd) return; ERR_set_mark(); ENGINE_add(toadd); /* * If the "add" worked, it gets a structural reference. So either way, we * release our just-created reference. */ ENGINE_free(toadd); /* * If the "add" didn't work, it was probably a conflict because it was * already added (eg. someone calling ENGINE_load_blah then calling * ENGINE_load_builtin_engines() perhaps). */ ERR_pop_to_mark(); } static int dynamic_init(ENGINE *e) { /* * We always return failure - the "dynamic" engine itself can't be used * for anything. */ return 0; } static int dynamic_finish(ENGINE *e) { /* * This should never be called on account of "dynamic_init" always * failing. */ return 0; } static int dynamic_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void)) { dynamic_data_ctx *ctx = dynamic_get_data_ctx(e); int initialised; if (!ctx) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_NOT_LOADED); return 0; } initialised = ((ctx->dynamic_dso == NULL) ? 0 : 1); /* All our control commands require the ENGINE to be uninitialised */ if (initialised) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_ALREADY_LOADED); return 0; } switch (cmd) { case DYNAMIC_CMD_SO_PATH: /* a NULL 'p' or a string of zero-length is the same thing */ if (p && (strlen((const char *)p) < 1)) p = NULL; OPENSSL_free(ctx->DYNAMIC_LIBNAME); if (p) ctx->DYNAMIC_LIBNAME = OPENSSL_strdup(p); else ctx->DYNAMIC_LIBNAME = NULL; return (ctx->DYNAMIC_LIBNAME ? 1 : 0); case DYNAMIC_CMD_NO_VCHECK: ctx->no_vcheck = ((i == 0) ? 0 : 1); return 1; case DYNAMIC_CMD_ID: /* a NULL 'p' or a string of zero-length is the same thing */ if (p && (strlen((const char *)p) < 1)) p = NULL; OPENSSL_free(ctx->engine_id); if (p) ctx->engine_id = OPENSSL_strdup(p); else ctx->engine_id = NULL; return (ctx->engine_id ? 1 : 0); case DYNAMIC_CMD_LIST_ADD: if ((i < 0) || (i > 2)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INVALID_ARGUMENT); return 0; } ctx->list_add_value = (int)i; return 1; case DYNAMIC_CMD_LOAD: return dynamic_load(e, ctx); case DYNAMIC_CMD_DIR_LOAD: if ((i < 0) || (i > 2)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INVALID_ARGUMENT); return 0; } ctx->dir_load = (int)i; return 1; case DYNAMIC_CMD_DIR_ADD: /* a NULL 'p' or a string of zero-length is the same thing */ if (p == NULL || (strlen((const char *)p) < 1)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INVALID_ARGUMENT); return 0; } { char *tmp_str = OPENSSL_strdup(p); if (tmp_str == NULL) return 0; if (!sk_OPENSSL_STRING_push(ctx->dirs, tmp_str)) { OPENSSL_free(tmp_str); ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); return 0; } } return 1; default: break; } ERR_raise(ERR_LIB_ENGINE, ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED); return 0; } static int int_load(dynamic_data_ctx *ctx) { int num, loop; /* Unless told not to, try a direct load */ if ((ctx->dir_load != 2) && (DSO_load(ctx->dynamic_dso, ctx->DYNAMIC_LIBNAME, NULL, 0)) != NULL) return 1; /* If we're not allowed to use 'dirs' or we have none, fail */ if (!ctx->dir_load || (num = sk_OPENSSL_STRING_num(ctx->dirs)) < 1) return 0; for (loop = 0; loop < num; loop++) { const char *s = sk_OPENSSL_STRING_value(ctx->dirs, loop); char *merge = DSO_merge(ctx->dynamic_dso, ctx->DYNAMIC_LIBNAME, s); if (!merge) return 0; if (DSO_load(ctx->dynamic_dso, merge, NULL, 0)) { /* Found what we're looking for */ OPENSSL_free(merge); return 1; } OPENSSL_free(merge); } return 0; } /* * Unfortunately the version checker does not distinguish between * engines built for openssl 1.1.x and openssl 3.x, but loading * an engine that is built for openssl 1.1.x will cause a fatal * error. Detect such engines, since EVP_PKEY_base_id is exported * as a function in openssl 1.1.x, while it is named EVP_PKEY_get_base_id * in openssl 3.x. Therefore we take the presence of that symbol * as an indication that the engine will be incompatible. */ static int using_libcrypto_11(dynamic_data_ctx *ctx) { int ret; ERR_set_mark(); ret = DSO_bind_func(ctx->dynamic_dso, "EVP_PKEY_base_id") != NULL; ERR_pop_to_mark(); return ret; } static int dynamic_load(ENGINE *e, dynamic_data_ctx *ctx) { ENGINE cpy; dynamic_fns fns; if (ctx->dynamic_dso == NULL) ctx->dynamic_dso = DSO_new(); if (ctx->dynamic_dso == NULL) return 0; if (!ctx->DYNAMIC_LIBNAME) { if (!ctx->engine_id) return 0; DSO_ctrl(ctx->dynamic_dso, DSO_CTRL_SET_FLAGS, DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL); ctx->DYNAMIC_LIBNAME = DSO_convert_filename(ctx->dynamic_dso, ctx->engine_id); } if (!int_load(ctx)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_DSO_NOT_FOUND); DSO_free(ctx->dynamic_dso); ctx->dynamic_dso = NULL; return 0; } /* We have to find a bind function otherwise it'll always end badly */ if (! (ctx->bind_engine = (dynamic_bind_engine) DSO_bind_func(ctx->dynamic_dso, ctx->DYNAMIC_F2))) { ctx->bind_engine = NULL; DSO_free(ctx->dynamic_dso); ctx->dynamic_dso = NULL; ERR_raise(ERR_LIB_ENGINE, ENGINE_R_DSO_FAILURE); return 0; } /* Do we perform version checking? */ if (!ctx->no_vcheck) { unsigned long vcheck_res = 0; /* * Now we try to find a version checking function and decide how to * cope with failure if/when it fails. */ ctx->v_check = (dynamic_v_check_fn) DSO_bind_func(ctx->dynamic_dso, ctx->DYNAMIC_F1); if (ctx->v_check) vcheck_res = ctx->v_check(OSSL_DYNAMIC_VERSION); /* * We fail if the version checker veto'd the load *or* if it is * deferring to us (by returning its version) and we think it is too * old. Also fail if this is engine for openssl 1.1.x. */ if (vcheck_res < OSSL_DYNAMIC_OLDEST || using_libcrypto_11(ctx)) { /* Fail */ ctx->bind_engine = NULL; ctx->v_check = NULL; DSO_free(ctx->dynamic_dso); ctx->dynamic_dso = NULL; ERR_raise(ERR_LIB_ENGINE, ENGINE_R_VERSION_INCOMPATIBILITY); return 0; } } /* * First binary copy the ENGINE structure so that we can roll back if the * hand-over fails */ memcpy(&cpy, e, sizeof(ENGINE)); /* * Provide the ERR, "ex_data", memory, and locking callbacks so the * loaded library uses our state rather than its own. FIXME: As noted in * engine.h, much of this would be simplified if each area of code * provided its own "summary" structure of all related callbacks. It * would also increase opaqueness. */ fns.static_state = ENGINE_get_static_state(); CRYPTO_get_mem_functions(&fns.mem_fns.malloc_fn, &fns.mem_fns.realloc_fn, &fns.mem_fns.free_fn); /* * Now that we've loaded the dynamic engine, make sure no "dynamic" * ENGINE elements will show through. */ engine_set_all_null(e); /* Try to bind the ENGINE onto our own ENGINE structure */ if (!engine_add_dynamic_id(e, (ENGINE_DYNAMIC_ID)ctx->bind_engine, 1) || !ctx->bind_engine(e, ctx->engine_id, &fns)) { engine_remove_dynamic_id(e, 1); ctx->bind_engine = NULL; ctx->v_check = NULL; DSO_free(ctx->dynamic_dso); ctx->dynamic_dso = NULL; ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INIT_FAILED); /* Copy the original ENGINE structure back */ memcpy(e, &cpy, sizeof(ENGINE)); return 0; } /* Do we try to add this ENGINE to the internal list too? */ if (ctx->list_add_value > 0) { if (!ENGINE_add(e)) { /* Do we tolerate this or fail? */ if (ctx->list_add_value > 1) { /* * Fail - NB: By this time, it's too late to rollback, and * trying to do so allows the bind_engine() code to have * created leaks. We just have to fail where we are, after * the ENGINE has changed. */ ERR_raise(ERR_LIB_ENGINE, ENGINE_R_CONFLICTING_ENGINE_ID); return 0; } /* Tolerate */ ERR_clear_error(); } } return 1; }
18,289
33.186916
85
c
openssl
openssl-master/crypto/engine/eng_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * 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 <openssl/err.h> #include <openssl/engineerr.h> #include "crypto/engineerr.h" #ifndef OPENSSL_NO_ENGINE # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA ENGINE_str_reasons[] = { {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ALREADY_LOADED), "already loaded"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER), "argument is not a number"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_CMD_NOT_EXECUTABLE), "cmd not executable"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_COMMAND_TAKES_INPUT), "command takes input"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_COMMAND_TAKES_NO_INPUT), "command takes no input"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_CONFLICTING_ENGINE_ID), "conflicting engine id"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED), "ctrl command not implemented"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_DSO_FAILURE), "DSO failure"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_DSO_NOT_FOUND), "dso not found"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINES_SECTION_ERROR), "engines section error"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINE_CONFIGURATION_ERROR), "engine configuration error"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINE_IS_NOT_IN_LIST), "engine is not in the list"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINE_SECTION_ERROR), "engine section error"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_FAILED_LOADING_PRIVATE_KEY), "failed loading private key"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_FAILED_LOADING_PUBLIC_KEY), "failed loading public key"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_FINISH_FAILED), "finish failed"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ID_OR_NAME_MISSING), "'id' or 'name' missing"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INIT_FAILED), "init failed"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INTERNAL_LIST_ERROR), "internal list error"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_ARGUMENT), "invalid argument"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_CMD_NAME), "invalid cmd name"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_CMD_NUMBER), "invalid cmd number"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_INIT_VALUE), "invalid init value"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_STRING), "invalid string"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NOT_INITIALISED), "not initialised"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NOT_LOADED), "not loaded"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_CONTROL_FUNCTION), "no control function"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_INDEX), "no index"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_LOAD_FUNCTION), "no load function"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_REFERENCE), "no reference"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_SUCH_ENGINE), "no such engine"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_UNIMPLEMENTED_CIPHER), "unimplemented cipher"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_UNIMPLEMENTED_DIGEST), "unimplemented digest"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_UNIMPLEMENTED_PUBLIC_KEY_METHOD), "unimplemented public key method"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_VERSION_INCOMPATIBILITY), "version incompatibility"}, {0, NULL} }; # endif int ossl_err_load_ENGINE_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(ENGINE_str_reasons[0].error) == NULL) ERR_load_strings_const(ENGINE_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
3,984
40.947368
79
c
openssl
openssl-master/crypto/engine/eng_fat.c
/* * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include "eng_local.h" #include <openssl/conf.h> int ENGINE_set_default(ENGINE *e, unsigned int flags) { if ((flags & ENGINE_METHOD_CIPHERS) && !ENGINE_set_default_ciphers(e)) return 0; if ((flags & ENGINE_METHOD_DIGESTS) && !ENGINE_set_default_digests(e)) return 0; if ((flags & ENGINE_METHOD_RSA) && !ENGINE_set_default_RSA(e)) return 0; #ifndef OPENSSL_NO_DSA if ((flags & ENGINE_METHOD_DSA) && !ENGINE_set_default_DSA(e)) return 0; #endif #ifndef OPENSSL_NO_DH if ((flags & ENGINE_METHOD_DH) && !ENGINE_set_default_DH(e)) return 0; #endif #ifndef OPENSSL_NO_EC if ((flags & ENGINE_METHOD_EC) && !ENGINE_set_default_EC(e)) return 0; #endif if ((flags & ENGINE_METHOD_RAND) && !ENGINE_set_default_RAND(e)) return 0; if ((flags & ENGINE_METHOD_PKEY_METHS) && !ENGINE_set_default_pkey_meths(e)) return 0; if ((flags & ENGINE_METHOD_PKEY_ASN1_METHS) && !ENGINE_set_default_pkey_asn1_meths(e)) return 0; return 1; } /* Set default algorithms using a string */ static int int_def_cb(const char *alg, int len, void *arg) { unsigned int *pflags = arg; if (alg == NULL) return 0; if (strncmp(alg, "ALL", len) == 0) *pflags |= ENGINE_METHOD_ALL; else if (strncmp(alg, "RSA", len) == 0) *pflags |= ENGINE_METHOD_RSA; else if (strncmp(alg, "DSA", len) == 0) *pflags |= ENGINE_METHOD_DSA; else if (strncmp(alg, "DH", len) == 0) *pflags |= ENGINE_METHOD_DH; else if (strncmp(alg, "EC", len) == 0) *pflags |= ENGINE_METHOD_EC; else if (strncmp(alg, "RAND", len) == 0) *pflags |= ENGINE_METHOD_RAND; else if (strncmp(alg, "CIPHERS", len) == 0) *pflags |= ENGINE_METHOD_CIPHERS; else if (strncmp(alg, "DIGESTS", len) == 0) *pflags |= ENGINE_METHOD_DIGESTS; else if (strncmp(alg, "PKEY", len) == 0) *pflags |= ENGINE_METHOD_PKEY_METHS | ENGINE_METHOD_PKEY_ASN1_METHS; else if (strncmp(alg, "PKEY_CRYPTO", len) == 0) *pflags |= ENGINE_METHOD_PKEY_METHS; else if (strncmp(alg, "PKEY_ASN1", len) == 0) *pflags |= ENGINE_METHOD_PKEY_ASN1_METHS; else return 0; return 1; } int ENGINE_set_default_string(ENGINE *e, const char *def_list) { unsigned int flags = 0; if (!CONF_parse_list(def_list, ',', 1, int_def_cb, &flags)) { ERR_raise_data(ERR_LIB_ENGINE, ENGINE_R_INVALID_STRING, "str=%s", def_list); return 0; } return ENGINE_set_default(e, flags); } int ENGINE_register_complete(ENGINE *e) { ENGINE_register_ciphers(e); ENGINE_register_digests(e); ENGINE_register_RSA(e); #ifndef OPENSSL_NO_DSA ENGINE_register_DSA(e); #endif #ifndef OPENSSL_NO_DH ENGINE_register_DH(e); #endif #ifndef OPENSSL_NO_EC ENGINE_register_EC(e); #endif ENGINE_register_RAND(e); ENGINE_register_pkey_meths(e); ENGINE_register_pkey_asn1_meths(e); return 1; } int ENGINE_register_all_complete(void) { ENGINE *e; for (e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) if (!(e->flags & ENGINE_FLAGS_NO_REGISTER_ALL)) ENGINE_register_complete(e); return 1; }
3,735
29.622951
76
c
openssl
openssl-master/crypto/engine/eng_init.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 */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include "internal/e_os.h" #include "eng_local.h" /* * Initialise an engine type for use (or up its functional reference count if * it's already in use). This version is only used internally. */ int engine_unlocked_init(ENGINE *e) { int to_return = 1; if ((e->funct_ref == 0) && e->init) /* * This is the first functional reference and the engine requires * initialisation so we do it now. */ to_return = e->init(e); if (to_return) { int ref; /* * OK, we return a functional reference which is also a structural * reference. */ if (!CRYPTO_UP_REF(&e->struct_ref, &ref)) { e->finish(e); return 0; } e->funct_ref++; ENGINE_REF_PRINT(e, 0, 1); ENGINE_REF_PRINT(e, 1, 1); } return to_return; } /* * Free a functional reference to an engine type. This version is only used * internally. */ int engine_unlocked_finish(ENGINE *e, int unlock_for_handlers) { int to_return = 1; /* * Reduce the functional reference count here so if it's the terminating * case, we can release the lock safely and call the finish() handler * without risk of a race. We get a race if we leave the count until * after and something else is calling "finish" at the same time - * there's a chance that both threads will together take the count from 2 * to 0 without either calling finish(). */ e->funct_ref--; ENGINE_REF_PRINT(e, 1, -1); if ((e->funct_ref == 0) && e->finish) { if (unlock_for_handlers) CRYPTO_THREAD_unlock(global_engine_lock); to_return = e->finish(e); if (unlock_for_handlers) if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return 0; if (!to_return) return 0; } REF_ASSERT_ISNT(e->funct_ref < 0); /* Release the structural reference too */ if (!engine_free_util(e, 0)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_FINISH_FAILED); return 0; } return to_return; } /* The API (locked) version of "init" */ int ENGINE_init(ENGINE *e) { int ret; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (!RUN_ONCE(&engine_lock_init, do_engine_lock_init)) { /* Maybe this should be raised in do_engine_lock_init() */ ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); return 0; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return 0; ret = engine_unlocked_init(e); CRYPTO_THREAD_unlock(global_engine_lock); return ret; } /* The API (locked) version of "finish" */ int ENGINE_finish(ENGINE *e) { int to_return = 1; if (e == NULL) return 1; if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return 0; to_return = engine_unlocked_finish(e, 1); CRYPTO_THREAD_unlock(global_engine_lock); if (!to_return) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_FINISH_FAILED); return 0; } return to_return; }
3,529
27.934426
77
c
openssl
openssl-master/crypto/engine/eng_lib.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 */ #include "internal/e_os.h" #include "eng_local.h" #include <openssl/rand.h> #include "internal/refcount.h" CRYPTO_RWLOCK *global_engine_lock; CRYPTO_ONCE engine_lock_init = CRYPTO_ONCE_STATIC_INIT; /* The "new"/"free" stuff first */ DEFINE_RUN_ONCE(do_engine_lock_init) { global_engine_lock = CRYPTO_THREAD_lock_new(); return global_engine_lock != NULL; } ENGINE *ENGINE_new(void) { ENGINE *ret; if (!RUN_ONCE(&engine_lock_init, do_engine_lock_init)) { /* Maybe this should be raised in do_engine_lock_init() */ ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); return 0; } if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; if (!CRYPTO_NEW_REF(&ret->struct_ref, 1)) { OPENSSL_free(ret); return NULL; } ENGINE_REF_PRINT(ret, 0, 1); if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_ENGINE, ret, &ret->ex_data)) { CRYPTO_FREE_REF(&ret->struct_ref); OPENSSL_free(ret); return NULL; } return ret; } /* * Placed here (close proximity to ENGINE_new) so that modifications to the * elements of the ENGINE structure are more likely to be caught and changed * here. */ void engine_set_all_null(ENGINE *e) { e->id = NULL; e->name = NULL; e->rsa_meth = NULL; e->dsa_meth = NULL; e->dh_meth = NULL; e->rand_meth = NULL; e->ciphers = NULL; e->digests = NULL; e->destroy = NULL; e->init = NULL; e->finish = NULL; e->ctrl = NULL; e->load_privkey = NULL; e->load_pubkey = NULL; e->cmd_defns = NULL; e->flags = 0; e->dynamic_id = NULL; } int engine_free_util(ENGINE *e, int not_locked) { int i; if (e == NULL) return 1; CRYPTO_DOWN_REF(&e->struct_ref, &i); ENGINE_REF_PRINT(e, 0, -1); if (i > 0) return 1; REF_ASSERT_ISNT(i < 0); /* Free up any dynamically allocated public key methods */ engine_pkey_meths_free(e); engine_pkey_asn1_meths_free(e); /* * Give the ENGINE a chance to do any structural cleanup corresponding to * allocation it did in its constructor (eg. unload error strings) */ if (e->destroy) e->destroy(e); engine_remove_dynamic_id(e, not_locked); CRYPTO_free_ex_data(CRYPTO_EX_INDEX_ENGINE, e, &e->ex_data); CRYPTO_FREE_REF(&e->struct_ref); OPENSSL_free(e); return 1; } int ENGINE_free(ENGINE *e) { return engine_free_util(e, 1); } /* Cleanup stuff */ /* * engine_cleanup_int() is coded such that anything that does work that will * need cleanup can register a "cleanup" callback here. That way we don't get * linker bloat by referring to all *possible* cleanups, but any linker bloat * into code "X" will cause X's cleanup function to end up here. */ static STACK_OF(ENGINE_CLEANUP_ITEM) *cleanup_stack = NULL; static int int_cleanup_check(int create) { if (cleanup_stack) return 1; if (!create) return 0; cleanup_stack = sk_ENGINE_CLEANUP_ITEM_new_null(); return (cleanup_stack ? 1 : 0); } static ENGINE_CLEANUP_ITEM *int_cleanup_item(ENGINE_CLEANUP_CB *cb) { ENGINE_CLEANUP_ITEM *item; if ((item = OPENSSL_malloc(sizeof(*item))) == NULL) return NULL; item->cb = cb; return item; } void engine_cleanup_add_first(ENGINE_CLEANUP_CB *cb) { ENGINE_CLEANUP_ITEM *item; if (!int_cleanup_check(1)) return; item = int_cleanup_item(cb); if (item != NULL) if (sk_ENGINE_CLEANUP_ITEM_insert(cleanup_stack, item, 0) <= 0) OPENSSL_free(item); } void engine_cleanup_add_last(ENGINE_CLEANUP_CB *cb) { ENGINE_CLEANUP_ITEM *item; if (!int_cleanup_check(1)) return; item = int_cleanup_item(cb); if (item != NULL) { if (sk_ENGINE_CLEANUP_ITEM_push(cleanup_stack, item) <= 0) OPENSSL_free(item); } } /* The API function that performs all cleanup */ static void engine_cleanup_cb_free(ENGINE_CLEANUP_ITEM *item) { (*(item->cb)) (); OPENSSL_free(item); } void engine_cleanup_int(void) { if (int_cleanup_check(0)) { sk_ENGINE_CLEANUP_ITEM_pop_free(cleanup_stack, engine_cleanup_cb_free); cleanup_stack = NULL; } CRYPTO_THREAD_lock_free(global_engine_lock); global_engine_lock = NULL; } /* Now the "ex_data" support */ int ENGINE_set_ex_data(ENGINE *e, int idx, void *arg) { return CRYPTO_set_ex_data(&e->ex_data, idx, arg); } void *ENGINE_get_ex_data(const ENGINE *e, int idx) { return CRYPTO_get_ex_data(&e->ex_data, idx); } /* * Functions to get/set an ENGINE's elements - mainly to avoid exposing the * ENGINE structure itself. */ int ENGINE_set_id(ENGINE *e, const char *id) { if (id == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } e->id = id; return 1; } int ENGINE_set_name(ENGINE *e, const char *name) { if (name == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } e->name = name; return 1; } int ENGINE_set_destroy_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR destroy_f) { e->destroy = destroy_f; return 1; } int ENGINE_set_init_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR init_f) { e->init = init_f; return 1; } int ENGINE_set_finish_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR finish_f) { e->finish = finish_f; return 1; } int ENGINE_set_ctrl_function(ENGINE *e, ENGINE_CTRL_FUNC_PTR ctrl_f) { e->ctrl = ctrl_f; return 1; } int ENGINE_set_flags(ENGINE *e, int flags) { e->flags = flags; return 1; } int ENGINE_set_cmd_defns(ENGINE *e, const ENGINE_CMD_DEFN *defns) { e->cmd_defns = defns; return 1; } const char *ENGINE_get_id(const ENGINE *e) { return e->id; } const char *ENGINE_get_name(const ENGINE *e) { return e->name; } ENGINE_GEN_INT_FUNC_PTR ENGINE_get_destroy_function(const ENGINE *e) { return e->destroy; } ENGINE_GEN_INT_FUNC_PTR ENGINE_get_init_function(const ENGINE *e) { return e->init; } ENGINE_GEN_INT_FUNC_PTR ENGINE_get_finish_function(const ENGINE *e) { return e->finish; } ENGINE_CTRL_FUNC_PTR ENGINE_get_ctrl_function(const ENGINE *e) { return e->ctrl; } int ENGINE_get_flags(const ENGINE *e) { return e->flags; } const ENGINE_CMD_DEFN *ENGINE_get_cmd_defns(const ENGINE *e) { return e->cmd_defns; } /* * eng_lib.o is pretty much linked into anything that touches ENGINE already, * so put the "static_state" hack here. */ static int internal_static_hack = 0; void *ENGINE_get_static_state(void) { return &internal_static_hack; }
6,970
21.930921
77
c
openssl
openssl-master/crypto/engine/eng_list.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include "eng_local.h" /* * The linked-list of pointers to engine types. engine_list_head incorporates * an implicit structural reference but engine_list_tail does not - the * latter is a computational optimization and only points to something that * is already pointed to by its predecessor in the list (or engine_list_head * itself). In the same way, the use of the "prev" pointer in each ENGINE is * to save excessive list iteration, it doesn't correspond to an extra * structural reference. Hence, engine_list_head, and each non-null "next" * pointer account for the list itself assuming exactly 1 structural * reference on each list member. */ static ENGINE *engine_list_head = NULL; static ENGINE *engine_list_tail = NULL; /* * The linked list of currently loaded dynamic engines. */ static ENGINE *engine_dyn_list_head = NULL; static ENGINE *engine_dyn_list_tail = NULL; /* * This cleanup function is only needed internally. If it should be called, * we register it with the "engine_cleanup_int()" stack to be called during * cleanup. */ static void engine_list_cleanup(void) { ENGINE *iterator = engine_list_head; while (iterator != NULL) { ENGINE_remove(iterator); iterator = engine_list_head; } return; } /* * These static functions starting with a lower case "engine_" always take * place when global_engine_lock has been locked up. */ static int engine_list_add(ENGINE *e) { int conflict = 0; ENGINE *iterator = NULL; int ref; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } iterator = engine_list_head; while (iterator && !conflict) { conflict = (strcmp(iterator->id, e->id) == 0); iterator = iterator->next; } if (conflict) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_CONFLICTING_ENGINE_ID); return 0; } /* * Having the engine in the list assumes a structural reference. */ if (!CRYPTO_UP_REF(&e->struct_ref, &ref)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); return 0; } ENGINE_REF_PRINT(e, 0, 1); if (engine_list_head == NULL) { /* We are adding to an empty list. */ if (engine_list_tail != NULL) { CRYPTO_DOWN_REF(&e->struct_ref, &ref); ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); return 0; } engine_list_head = e; e->prev = NULL; /* * The first time the list allocates, we should register the cleanup. */ engine_cleanup_add_last(engine_list_cleanup); } else { /* We are adding to the tail of an existing list. */ if ((engine_list_tail == NULL) || (engine_list_tail->next != NULL)) { CRYPTO_DOWN_REF(&e->struct_ref, &ref); ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); return 0; } engine_list_tail->next = e; e->prev = engine_list_tail; } /* However it came to be, e is the last item in the list. */ engine_list_tail = e; e->next = NULL; return 1; } static int engine_list_remove(ENGINE *e) { ENGINE *iterator; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* We need to check that e is in our linked list! */ iterator = engine_list_head; while (iterator && (iterator != e)) iterator = iterator->next; if (iterator == NULL) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_ENGINE_IS_NOT_IN_LIST); return 0; } /* un-link e from the chain. */ if (e->next) e->next->prev = e->prev; if (e->prev) e->prev->next = e->next; /* Correct our head/tail if necessary. */ if (engine_list_head == e) engine_list_head = e->next; if (engine_list_tail == e) engine_list_tail = e->prev; engine_free_util(e, 0); return 1; } /* Add engine to dynamic engine list. */ int engine_add_dynamic_id(ENGINE *e, ENGINE_DYNAMIC_ID dynamic_id, int not_locked) { int result = 0; ENGINE *iterator = NULL; if (e == NULL) return 0; if (e->dynamic_id == NULL && dynamic_id == NULL) return 0; if (not_locked && !CRYPTO_THREAD_write_lock(global_engine_lock)) return 0; if (dynamic_id != NULL) { iterator = engine_dyn_list_head; while (iterator != NULL) { if (iterator->dynamic_id == dynamic_id) goto err; iterator = iterator->next; } if (e->dynamic_id != NULL) goto err; e->dynamic_id = dynamic_id; } if (engine_dyn_list_head == NULL) { /* We are adding to an empty list. */ if (engine_dyn_list_tail != NULL) goto err; engine_dyn_list_head = e; e->prev_dyn = NULL; } else { /* We are adding to the tail of an existing list. */ if (engine_dyn_list_tail == NULL || engine_dyn_list_tail->next_dyn != NULL) goto err; engine_dyn_list_tail->next_dyn = e; e->prev_dyn = engine_dyn_list_tail; } engine_dyn_list_tail = e; e->next_dyn = NULL; result = 1; err: if (not_locked) CRYPTO_THREAD_unlock(global_engine_lock); return result; } /* Remove engine from dynamic engine list. */ void engine_remove_dynamic_id(ENGINE *e, int not_locked) { if (e == NULL || e->dynamic_id == NULL) return; if (not_locked && !CRYPTO_THREAD_write_lock(global_engine_lock)) return; e->dynamic_id = NULL; /* un-link e from the chain. */ if (e->next_dyn != NULL) e->next_dyn->prev_dyn = e->prev_dyn; if (e->prev_dyn != NULL) e->prev_dyn->next_dyn = e->next_dyn; /* Correct our head/tail if necessary. */ if (engine_dyn_list_head == e) engine_dyn_list_head = e->next_dyn; if (engine_dyn_list_tail == e) engine_dyn_list_tail = e->prev_dyn; if (not_locked) CRYPTO_THREAD_unlock(global_engine_lock); } /* Get the first/last "ENGINE" type available. */ ENGINE *ENGINE_get_first(void) { ENGINE *ret; if (!RUN_ONCE(&engine_lock_init, do_engine_lock_init)) { /* Maybe this should be raised in do_engine_lock_init() */ ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); return NULL; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return NULL; ret = engine_list_head; if (ret) { int ref; if (!CRYPTO_UP_REF(&ret->struct_ref, &ref)) { ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); return NULL; } ENGINE_REF_PRINT(ret, 0, 1); } CRYPTO_THREAD_unlock(global_engine_lock); return ret; } ENGINE *ENGINE_get_last(void) { ENGINE *ret; if (!RUN_ONCE(&engine_lock_init, do_engine_lock_init)) { /* Maybe this should be raised in do_engine_lock_init() */ ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); return NULL; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return NULL; ret = engine_list_tail; if (ret) { int ref; if (!CRYPTO_UP_REF(&ret->struct_ref, &ref)) { ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); return NULL; } ENGINE_REF_PRINT(ret, 0, 1); } CRYPTO_THREAD_unlock(global_engine_lock); return ret; } /* Iterate to the next/previous "ENGINE" type (NULL = end of the list). */ ENGINE *ENGINE_get_next(ENGINE *e) { ENGINE *ret = NULL; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return NULL; ret = e->next; if (ret) { int ref; /* Return a valid structural reference to the next ENGINE */ if (!CRYPTO_UP_REF(&ret->struct_ref, &ref)) { ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); return NULL; } ENGINE_REF_PRINT(ret, 0, 1); } CRYPTO_THREAD_unlock(global_engine_lock); /* Release the structural reference to the previous ENGINE */ ENGINE_free(e); return ret; } ENGINE *ENGINE_get_prev(ENGINE *e) { ENGINE *ret = NULL; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return NULL; ret = e->prev; if (ret) { int ref; /* Return a valid structural reference to the next ENGINE */ if (!CRYPTO_UP_REF(&ret->struct_ref, &ref)) { ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); return NULL; } ENGINE_REF_PRINT(ret, 0, 1); } CRYPTO_THREAD_unlock(global_engine_lock); /* Release the structural reference to the previous ENGINE */ ENGINE_free(e); return ret; } /* Add another "ENGINE" type into the list. */ int ENGINE_add(ENGINE *e) { int to_return = 1; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((e->id == NULL) || (e->name == NULL)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_ID_OR_NAME_MISSING); return 0; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return 0; if (!engine_list_add(e)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); to_return = 0; } CRYPTO_THREAD_unlock(global_engine_lock); return to_return; } /* Remove an existing "ENGINE" type from the array. */ int ENGINE_remove(ENGINE *e) { int to_return = 1; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return 0; if (!engine_list_remove(e)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); to_return = 0; } CRYPTO_THREAD_unlock(global_engine_lock); return to_return; } static void engine_cpy(ENGINE *dest, const ENGINE *src) { dest->id = src->id; dest->name = src->name; dest->rsa_meth = src->rsa_meth; #ifndef OPENSSL_NO_DSA dest->dsa_meth = src->dsa_meth; #endif #ifndef OPENSSL_NO_DH dest->dh_meth = src->dh_meth; #endif #ifndef OPENSSL_NO_EC dest->ec_meth = src->ec_meth; #endif dest->rand_meth = src->rand_meth; dest->ciphers = src->ciphers; dest->digests = src->digests; dest->pkey_meths = src->pkey_meths; dest->destroy = src->destroy; dest->init = src->init; dest->finish = src->finish; dest->ctrl = src->ctrl; dest->load_privkey = src->load_privkey; dest->load_pubkey = src->load_pubkey; dest->cmd_defns = src->cmd_defns; dest->flags = src->flags; dest->dynamic_id = src->dynamic_id; engine_add_dynamic_id(dest, NULL, 0); } ENGINE *ENGINE_by_id(const char *id) { ENGINE *iterator; char *load_dir = NULL; if (id == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return NULL; } ENGINE_load_builtin_engines(); if (!RUN_ONCE(&engine_lock_init, do_engine_lock_init)) { /* Maybe this should be raised in do_engine_lock_init() */ ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); return NULL; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return NULL; iterator = engine_list_head; while (iterator && (strcmp(id, iterator->id) != 0)) iterator = iterator->next; if (iterator != NULL) { /* * We need to return a structural reference. If this is an ENGINE * type that returns copies, make a duplicate - otherwise increment * the existing ENGINE's reference count. */ if (iterator->flags & ENGINE_FLAGS_BY_ID_COPY) { ENGINE *cp = ENGINE_new(); if (cp == NULL) iterator = NULL; else { engine_cpy(cp, iterator); iterator = cp; } } else { int ref; if (!CRYPTO_UP_REF(&iterator->struct_ref, &ref)) { CRYPTO_THREAD_unlock(global_engine_lock); ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB); return NULL; } ENGINE_REF_PRINT(iterator, 0, 1); } } CRYPTO_THREAD_unlock(global_engine_lock); if (iterator != NULL) return iterator; /* * Prevent infinite recursion if we're looking for the dynamic engine. */ if (strcmp(id, "dynamic")) { if ((load_dir = ossl_safe_getenv("OPENSSL_ENGINES")) == NULL) load_dir = ENGINESDIR; iterator = ENGINE_by_id("dynamic"); if (!iterator || !ENGINE_ctrl_cmd_string(iterator, "ID", id, 0) || !ENGINE_ctrl_cmd_string(iterator, "DIR_LOAD", "2", 0) || !ENGINE_ctrl_cmd_string(iterator, "DIR_ADD", load_dir, 0) || !ENGINE_ctrl_cmd_string(iterator, "LIST_ADD", "1", 0) || !ENGINE_ctrl_cmd_string(iterator, "LOAD", NULL, 0)) goto notfound; return iterator; } notfound: ENGINE_free(iterator); ERR_raise_data(ERR_LIB_ENGINE, ENGINE_R_NO_SUCH_ENGINE, "id=%s", id); return NULL; /* EEK! Experimental code ends */ } int ENGINE_up_ref(ENGINE *e) { int i; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } CRYPTO_UP_REF(&e->struct_ref, &i); return 1; }
14,075
28.20332
77
c
openssl
openssl-master/crypto/engine/eng_local.h
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 */ #ifndef OSSL_CRYPTO_ENGINE_ENG_LOCAL_H # define OSSL_CRYPTO_ENGINE_ENG_LOCAL_H # include <openssl/trace.h> # include "internal/cryptlib.h" # include "crypto/engine.h" # include "internal/thread_once.h" # include "internal/refcount.h" extern CRYPTO_RWLOCK *global_engine_lock; /* * This prints the engine's pointer address, "struct" or "funct" to * indicate the reference type, the before and after reference count, and * the file:line-number pair. The "ENGINE_REF_PRINT" statements must come * *after* the change. */ # define ENGINE_REF_PRINT(e, isfunct, diff) \ OSSL_TRACE6(ENGINE_REF_COUNT, \ "engine: %p %s from %d to %d (%s:%d)\n", \ (void *)(e), (isfunct ? "funct" : "struct"), \ ((isfunct) \ ? ((e)->funct_ref - (diff)) \ : (eng_struct_ref(e) - (diff))), \ ((isfunct) ? (e)->funct_ref : eng_struct_ref(e)), \ (OPENSSL_FILE), (OPENSSL_LINE)) /* * Any code that will need cleanup operations should use these functions to * register callbacks. engine_cleanup_int() will call all registered * callbacks in order. NB: both the "add" functions assume the engine lock to * already be held (in "write" mode). */ typedef void (ENGINE_CLEANUP_CB) (void); typedef struct st_engine_cleanup_item { ENGINE_CLEANUP_CB *cb; } ENGINE_CLEANUP_ITEM; DEFINE_STACK_OF(ENGINE_CLEANUP_ITEM) void engine_cleanup_add_first(ENGINE_CLEANUP_CB *cb); void engine_cleanup_add_last(ENGINE_CLEANUP_CB *cb); /* We need stacks of ENGINEs for use in eng_table.c */ DEFINE_STACK_OF(ENGINE) /* * This represents an implementation table. Dependent code should instantiate * it as a (ENGINE_TABLE *) pointer value set initially to NULL. */ typedef struct st_engine_table ENGINE_TABLE; int engine_table_register(ENGINE_TABLE **table, ENGINE_CLEANUP_CB *cleanup, ENGINE *e, const int *nids, int num_nids, int setdefault); void engine_table_unregister(ENGINE_TABLE **table, ENGINE *e); void engine_table_cleanup(ENGINE_TABLE **table); ENGINE *ossl_engine_table_select(ENGINE_TABLE **table, int nid, const char *f, int l); typedef void (engine_table_doall_cb) (int nid, STACK_OF(ENGINE) *sk, ENGINE *def, void *arg); void engine_table_doall(ENGINE_TABLE *table, engine_table_doall_cb *cb, void *arg); /* * Internal versions of API functions that have control over locking. These * are used between C files when functionality needs to be shared but the * caller may already be controlling of the engine lock. */ int engine_unlocked_init(ENGINE *e); int engine_unlocked_finish(ENGINE *e, int unlock_for_handlers); int engine_free_util(ENGINE *e, int not_locked); /* * This function will reset all "set"able values in an ENGINE to NULL. This * won't touch reference counts or ex_data, but is equivalent to calling all * the ENGINE_set_***() functions with a NULL value. */ void engine_set_all_null(ENGINE *e); /* * NB: Bitwise OR-able values for the "flags" variable in ENGINE are now * exposed in engine.h. */ /* Free up dynamically allocated public key methods associated with ENGINE */ void engine_pkey_meths_free(ENGINE *e); void engine_pkey_asn1_meths_free(ENGINE *e); /* Once initialisation function */ extern CRYPTO_ONCE engine_lock_init; DECLARE_RUN_ONCE(do_engine_lock_init) typedef void (*ENGINE_DYNAMIC_ID)(void); int engine_add_dynamic_id(ENGINE *e, ENGINE_DYNAMIC_ID dynamic_id, int not_locked); void engine_remove_dynamic_id(ENGINE *e, int not_locked); /* * This is a structure for storing implementations of various crypto * algorithms and functions. */ struct engine_st { const char *id; const char *name; const RSA_METHOD *rsa_meth; const DSA_METHOD *dsa_meth; const DH_METHOD *dh_meth; const EC_KEY_METHOD *ec_meth; const RAND_METHOD *rand_meth; /* Cipher handling is via this callback */ ENGINE_CIPHERS_PTR ciphers; /* Digest handling is via this callback */ ENGINE_DIGESTS_PTR digests; /* Public key handling via this callback */ ENGINE_PKEY_METHS_PTR pkey_meths; /* ASN1 public key handling via this callback */ ENGINE_PKEY_ASN1_METHS_PTR pkey_asn1_meths; ENGINE_GEN_INT_FUNC_PTR destroy; ENGINE_GEN_INT_FUNC_PTR init; ENGINE_GEN_INT_FUNC_PTR finish; ENGINE_CTRL_FUNC_PTR ctrl; ENGINE_LOAD_KEY_PTR load_privkey; ENGINE_LOAD_KEY_PTR load_pubkey; ENGINE_SSL_CLIENT_CERT_PTR load_ssl_client_cert; const ENGINE_CMD_DEFN *cmd_defns; int flags; /* reference count on the structure itself */ CRYPTO_REF_COUNT struct_ref; /* * reference count on usability of the engine type. NB: This controls the * loading and initialisation of any functionality required by this * engine, whereas the previous count is simply to cope with * (de)allocation of this structure. Hence, running_ref <= struct_ref at * all times. */ int funct_ref; /* A place to store per-ENGINE data */ CRYPTO_EX_DATA ex_data; /* Used to maintain the linked-list of engines. */ struct engine_st *prev; struct engine_st *next; /* Used to maintain the linked-list of dynamic engines. */ struct engine_st *prev_dyn; struct engine_st *next_dyn; ENGINE_DYNAMIC_ID dynamic_id; }; typedef struct st_engine_pile ENGINE_PILE; DEFINE_LHASH_OF_EX(ENGINE_PILE); static ossl_unused ossl_inline int eng_struct_ref(ENGINE *e) { int res; CRYPTO_GET_REF(&e->struct_ref, &res); return res; } #endif /* OSSL_CRYPTO_ENGINE_ENG_LOCAL_H */
6,312
36.135294
77
h