file_path
stringlengths
19
75
code
stringlengths
279
1.37M
./openssl/crypto/evp/ec_support.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 <string.h> #include <openssl/ec.h> #include "crypto/ec.h" #include "internal/nelem.h" typedef struct ec_name2nid_st { const char *name; int nid; } EC_NAME2NID; static const EC_NAME2NID curve_list[] = { /* prime field curves */ /* secg curves */ {"secp112r1", NID_secp112r1 }, {"secp112r2", NID_secp112r2 }, {"secp128r1", NID_secp128r1 }, {"secp128r2", NID_secp128r2 }, {"secp160k1", NID_secp160k1 }, {"secp160r1", NID_secp160r1 }, {"secp160r2", NID_secp160r2 }, {"secp192k1", NID_secp192k1 }, {"secp224k1", NID_secp224k1 }, {"secp224r1", NID_secp224r1 }, {"secp256k1", NID_secp256k1 }, {"secp384r1", NID_secp384r1 }, {"secp521r1", NID_secp521r1 }, /* X9.62 curves */ {"prime192v1", NID_X9_62_prime192v1 }, {"prime192v2", NID_X9_62_prime192v2 }, {"prime192v3", NID_X9_62_prime192v3 }, {"prime239v1", NID_X9_62_prime239v1 }, {"prime239v2", NID_X9_62_prime239v2 }, {"prime239v3", NID_X9_62_prime239v3 }, {"prime256v1", NID_X9_62_prime256v1 }, /* characteristic two field curves */ /* NIST/SECG curves */ {"sect113r1", NID_sect113r1 }, {"sect113r2", NID_sect113r2 }, {"sect131r1", NID_sect131r1 }, {"sect131r2", NID_sect131r2 }, {"sect163k1", NID_sect163k1 }, {"sect163r1", NID_sect163r1 }, {"sect163r2", NID_sect163r2 }, {"sect193r1", NID_sect193r1 }, {"sect193r2", NID_sect193r2 }, {"sect233k1", NID_sect233k1 }, {"sect233r1", NID_sect233r1 }, {"sect239k1", NID_sect239k1 }, {"sect283k1", NID_sect283k1 }, {"sect283r1", NID_sect283r1 }, {"sect409k1", NID_sect409k1 }, {"sect409r1", NID_sect409r1 }, {"sect571k1", NID_sect571k1 }, {"sect571r1", NID_sect571r1 }, /* X9.62 curves */ {"c2pnb163v1", NID_X9_62_c2pnb163v1 }, {"c2pnb163v2", NID_X9_62_c2pnb163v2 }, {"c2pnb163v3", NID_X9_62_c2pnb163v3 }, {"c2pnb176v1", NID_X9_62_c2pnb176v1 }, {"c2tnb191v1", NID_X9_62_c2tnb191v1 }, {"c2tnb191v2", NID_X9_62_c2tnb191v2 }, {"c2tnb191v3", NID_X9_62_c2tnb191v3 }, {"c2pnb208w1", NID_X9_62_c2pnb208w1 }, {"c2tnb239v1", NID_X9_62_c2tnb239v1 }, {"c2tnb239v2", NID_X9_62_c2tnb239v2 }, {"c2tnb239v3", NID_X9_62_c2tnb239v3 }, {"c2pnb272w1", NID_X9_62_c2pnb272w1 }, {"c2pnb304w1", NID_X9_62_c2pnb304w1 }, {"c2tnb359v1", NID_X9_62_c2tnb359v1 }, {"c2pnb368w1", NID_X9_62_c2pnb368w1 }, {"c2tnb431r1", NID_X9_62_c2tnb431r1 }, /* * the WAP/WTLS curves [unlike SECG, spec has its own OIDs for curves * from X9.62] */ {"wap-wsg-idm-ecid-wtls1", NID_wap_wsg_idm_ecid_wtls1 }, {"wap-wsg-idm-ecid-wtls3", NID_wap_wsg_idm_ecid_wtls3 }, {"wap-wsg-idm-ecid-wtls4", NID_wap_wsg_idm_ecid_wtls4 }, {"wap-wsg-idm-ecid-wtls5", NID_wap_wsg_idm_ecid_wtls5 }, {"wap-wsg-idm-ecid-wtls6", NID_wap_wsg_idm_ecid_wtls6 }, {"wap-wsg-idm-ecid-wtls7", NID_wap_wsg_idm_ecid_wtls7 }, {"wap-wsg-idm-ecid-wtls8", NID_wap_wsg_idm_ecid_wtls8 }, {"wap-wsg-idm-ecid-wtls9", NID_wap_wsg_idm_ecid_wtls9 }, {"wap-wsg-idm-ecid-wtls10", NID_wap_wsg_idm_ecid_wtls10 }, {"wap-wsg-idm-ecid-wtls11", NID_wap_wsg_idm_ecid_wtls11 }, {"wap-wsg-idm-ecid-wtls12", NID_wap_wsg_idm_ecid_wtls12 }, /* IPSec curves */ {"Oakley-EC2N-3", NID_ipsec3 }, {"Oakley-EC2N-4", NID_ipsec4 }, /* brainpool curves */ {"brainpoolP160r1", NID_brainpoolP160r1 }, {"brainpoolP160t1", NID_brainpoolP160t1 }, {"brainpoolP192r1", NID_brainpoolP192r1 }, {"brainpoolP192t1", NID_brainpoolP192t1 }, {"brainpoolP224r1", NID_brainpoolP224r1 }, {"brainpoolP224t1", NID_brainpoolP224t1 }, {"brainpoolP256r1", NID_brainpoolP256r1 }, {"brainpoolP256t1", NID_brainpoolP256t1 }, {"brainpoolP320r1", NID_brainpoolP320r1 }, {"brainpoolP320t1", NID_brainpoolP320t1 }, {"brainpoolP384r1", NID_brainpoolP384r1 }, {"brainpoolP384t1", NID_brainpoolP384t1 }, {"brainpoolP512r1", NID_brainpoolP512r1 }, {"brainpoolP512t1", NID_brainpoolP512t1 }, /* SM2 curve */ {"SM2", NID_sm2 }, }; const char *OSSL_EC_curve_nid2name(int nid) { size_t i; if (nid <= 0) return NULL; for (i = 0; i < OSSL_NELEM(curve_list); i++) { if (curve_list[i].nid == nid) return curve_list[i].name; } return NULL; } int ossl_ec_curve_name2nid(const char *name) { size_t i; int nid; if (name != NULL) { if ((nid = ossl_ec_curve_nist2nid_int(name)) != NID_undef) return nid; for (i = 0; i < OSSL_NELEM(curve_list); i++) { if (OPENSSL_strcasecmp(curve_list[i].name, name) == 0) return curve_list[i].nid; } } return NID_undef; } /* Functions to translate between common NIST curve names and NIDs */ static const EC_NAME2NID nist_curves[] = { {"B-163", NID_sect163r2}, {"B-233", NID_sect233r1}, {"B-283", NID_sect283r1}, {"B-409", NID_sect409r1}, {"B-571", NID_sect571r1}, {"K-163", NID_sect163k1}, {"K-233", NID_sect233k1}, {"K-283", NID_sect283k1}, {"K-409", NID_sect409k1}, {"K-571", NID_sect571k1}, {"P-192", NID_X9_62_prime192v1}, {"P-224", NID_secp224r1}, {"P-256", NID_X9_62_prime256v1}, {"P-384", NID_secp384r1}, {"P-521", NID_secp521r1} }; const char *ossl_ec_curve_nid2nist_int(int nid) { size_t i; for (i = 0; i < OSSL_NELEM(nist_curves); i++) { if (nist_curves[i].nid == nid) return nist_curves[i].name; } return NULL; } int ossl_ec_curve_nist2nid_int(const char *name) { size_t i; for (i = 0; i < OSSL_NELEM(nist_curves); i++) { if (strcmp(nist_curves[i].name, name) == 0) return nist_curves[i].nid; } return NID_undef; }
./openssl/crypto/evp/e_bf.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 */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_BF # include <openssl/evp.h> # include "crypto/evp.h" # include <openssl/objects.h> # include <openssl/blowfish.h> # include "evp_local.h" static int bf_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); typedef struct { BF_KEY ks; } EVP_BF_KEY; # define data(ctx) EVP_C_DATA(EVP_BF_KEY,ctx) IMPLEMENT_BLOCK_CIPHER(bf, ks, BF, EVP_BF_KEY, NID_bf, 8, 16, 8, 64, EVP_CIPH_VARIABLE_LENGTH, bf_init_key, NULL, EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL) static int bf_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int len = EVP_CIPHER_CTX_get_key_length(ctx); if (len < 0) return 0; BF_set_key(&data(ctx)->ks, len, key); return 1; } #endif
./openssl/crypto/evp/legacy_mdc2.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 */ /* * MDC2 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/mdc2.h> #include "crypto/evp.h" #include "legacy_meth.h" IMPLEMENT_LEGACY_EVP_MD_METH(mdc2, MDC2) static const EVP_MD mdc2_md = { NID_mdc2, NID_mdc2WithRSA, MDC2_DIGEST_LENGTH, 0, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(mdc2_init, mdc2_update, mdc2_final, NULL, MDC2_BLOCK), }; const EVP_MD *EVP_mdc2(void) { return &mdc2_md; }
./openssl/crypto/evp/e_cast.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 */ /* * CAST low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_CAST # include <openssl/evp.h> # include <openssl/objects.h> # include "crypto/evp.h" # include <openssl/cast.h> # include "evp_local.h" static int cast_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); typedef struct { CAST_KEY ks; } EVP_CAST_KEY; # define data(ctx) EVP_C_DATA(EVP_CAST_KEY,ctx) IMPLEMENT_BLOCK_CIPHER(cast5, ks, CAST, EVP_CAST_KEY, NID_cast5, 8, CAST_KEY_LENGTH, 8, 64, EVP_CIPH_VARIABLE_LENGTH, cast_init_key, NULL, EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL) static int cast_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int keylen = EVP_CIPHER_CTX_get_key_length(ctx); if (keylen <= 0) return 0; CAST_set_key(&data(ctx)->ks, keylen, key); return 1; } #endif
./openssl/crypto/evp/e_idea.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 */ /* * IDEA low level APIs are deprecated for public use, but still ok for internal * use where we're using them to implement the higher level EVP interface, as is * the case here. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_IDEA # include <openssl/evp.h> # include <openssl/objects.h> # include "crypto/evp.h" # include <openssl/idea.h> # include "evp_local.h" /* Can't use IMPLEMENT_BLOCK_CIPHER because IDEA_ecb_encrypt is different */ typedef struct { IDEA_KEY_SCHEDULE ks; } EVP_IDEA_KEY; static int idea_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); /* * NB IDEA_ecb_encrypt doesn't take an 'encrypt' argument so we treat it as a * special case */ static int idea_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { BLOCK_CIPHER_ecb_loop() IDEA_ecb_encrypt(in + i, out + i, &EVP_C_DATA(EVP_IDEA_KEY, ctx)->ks); return 1; } BLOCK_CIPHER_func_cbc(idea, IDEA, EVP_IDEA_KEY, ks) BLOCK_CIPHER_func_ofb(idea, IDEA, 64, EVP_IDEA_KEY, ks) BLOCK_CIPHER_func_cfb(idea, IDEA, 64, EVP_IDEA_KEY, ks) BLOCK_CIPHER_defs(idea, IDEA_KEY_SCHEDULE, NID_idea, 8, 16, 8, 64, 0, idea_init_key, NULL, EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL) static int idea_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { if (!enc) { if (EVP_CIPHER_CTX_get_mode(ctx) == EVP_CIPH_OFB_MODE) enc = 1; else if (EVP_CIPHER_CTX_get_mode(ctx) == EVP_CIPH_CFB_MODE) enc = 1; } if (enc) IDEA_set_encrypt_key(key, &EVP_C_DATA(EVP_IDEA_KEY, ctx)->ks); else { IDEA_KEY_SCHEDULE tmp; IDEA_set_encrypt_key(key, &tmp); IDEA_set_decrypt_key(&tmp, &EVP_C_DATA(EVP_IDEA_KEY, ctx)->ks); OPENSSL_cleanse((unsigned char *)&tmp, sizeof(IDEA_KEY_SCHEDULE)); } return 1; } #endif
./openssl/crypto/evp/e_chacha20_poly1305.c
/* * Copyright 2015-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include "internal/endian.h" #ifndef OPENSSL_NO_CHACHA # include <openssl/evp.h> # include <openssl/objects.h> # include "crypto/evp.h" # include "evp_local.h" # include "crypto/chacha.h" typedef struct { union { OSSL_UNION_ALIGN; /* this ensures even sizeof(EVP_CHACHA_KEY)%8==0 */ unsigned int d[CHACHA_KEY_SIZE / 4]; } key; unsigned int counter[CHACHA_CTR_SIZE / 4]; unsigned char buf[CHACHA_BLK_SIZE]; unsigned int partial_len; } EVP_CHACHA_KEY; #define data(ctx) ((EVP_CHACHA_KEY *)(ctx)->cipher_data) #define CHACHA20_POLY1305_MAX_IVLEN 12 static int chacha_init_key(EVP_CIPHER_CTX *ctx, const unsigned char user_key[CHACHA_KEY_SIZE], const unsigned char iv[CHACHA_CTR_SIZE], int enc) { EVP_CHACHA_KEY *key = data(ctx); unsigned int i; if (user_key) for (i = 0; i < CHACHA_KEY_SIZE; i+=4) { key->key.d[i/4] = CHACHA_U8TOU32(user_key+i); } if (iv) for (i = 0; i < CHACHA_CTR_SIZE; i+=4) { key->counter[i/4] = CHACHA_U8TOU32(iv+i); } key->partial_len = 0; return 1; } static int chacha_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *inp, size_t len) { EVP_CHACHA_KEY *key = data(ctx); unsigned int n, rem, ctr32; if ((n = key->partial_len)) { while (len && n < CHACHA_BLK_SIZE) { *out++ = *inp++ ^ key->buf[n++]; len--; } key->partial_len = n; if (len == 0) return 1; if (n == CHACHA_BLK_SIZE) { key->partial_len = 0; key->counter[0]++; if (key->counter[0] == 0) key->counter[1]++; } } rem = (unsigned int)(len % CHACHA_BLK_SIZE); len -= rem; ctr32 = key->counter[0]; while (len >= CHACHA_BLK_SIZE) { size_t blocks = len / CHACHA_BLK_SIZE; /* * 1<<28 is just a not-so-small yet not-so-large number... * Below condition is practically never met, but it has to * be checked for code correctness. */ if (sizeof(size_t)>sizeof(unsigned int) && blocks>(1U<<28)) blocks = (1U<<28); /* * As ChaCha20_ctr32 operates on 32-bit counter, caller * has to handle overflow. 'if' below detects the * overflow, which is then handled by limiting the * amount of blocks to the exact overflow point... */ ctr32 += (unsigned int)blocks; if (ctr32 < blocks) { blocks -= ctr32; ctr32 = 0; } blocks *= CHACHA_BLK_SIZE; ChaCha20_ctr32(out, inp, blocks, key->key.d, key->counter); len -= blocks; inp += blocks; out += blocks; key->counter[0] = ctr32; if (ctr32 == 0) key->counter[1]++; } if (rem) { memset(key->buf, 0, sizeof(key->buf)); ChaCha20_ctr32(key->buf, key->buf, CHACHA_BLK_SIZE, key->key.d, key->counter); for (n = 0; n < rem; n++) out[n] = inp[n] ^ key->buf[n]; key->partial_len = rem; } return 1; } static const EVP_CIPHER chacha20 = { NID_chacha20, 1, /* block_size */ CHACHA_KEY_SIZE, /* key_len */ CHACHA_CTR_SIZE, /* iv_len, 128-bit counter in the context */ EVP_CIPH_CUSTOM_IV | EVP_CIPH_ALWAYS_CALL_INIT, EVP_ORIG_GLOBAL, chacha_init_key, chacha_cipher, NULL, sizeof(EVP_CHACHA_KEY), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_chacha20(void) { return &chacha20; } # ifndef OPENSSL_NO_POLY1305 # include "crypto/poly1305.h" typedef struct { EVP_CHACHA_KEY key; unsigned int nonce[12/4]; unsigned char tag[POLY1305_BLOCK_SIZE]; unsigned char tls_aad[POLY1305_BLOCK_SIZE]; struct { uint64_t aad, text; } len; int aad, mac_inited, tag_len, nonce_len; size_t tls_payload_length; } EVP_CHACHA_AEAD_CTX; # define NO_TLS_PAYLOAD_LENGTH ((size_t)-1) # define aead_data(ctx) ((EVP_CHACHA_AEAD_CTX *)(ctx)->cipher_data) # define POLY1305_ctx(actx) ((POLY1305 *)(actx + 1)) static int chacha20_poly1305_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *inkey, const unsigned char *iv, int enc) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); if (!inkey && !iv) return 1; actx->len.aad = 0; actx->len.text = 0; actx->aad = 0; actx->mac_inited = 0; actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; if (iv != NULL) { unsigned char temp[CHACHA_CTR_SIZE] = { 0 }; /* pad on the left */ if (actx->nonce_len <= CHACHA_CTR_SIZE) memcpy(temp + CHACHA_CTR_SIZE - actx->nonce_len, iv, actx->nonce_len); chacha_init_key(ctx, inkey, temp, enc); actx->nonce[0] = actx->key.counter[1]; actx->nonce[1] = actx->key.counter[2]; actx->nonce[2] = actx->key.counter[3]; } else { chacha_init_key(ctx, inkey, NULL, enc); } return 1; } # if !defined(OPENSSL_SMALL_FOOTPRINT) # if defined(POLY1305_ASM) && (defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64)) # define XOR128_HELPERS void *xor128_encrypt_n_pad(void *out, const void *inp, void *otp, size_t len); void *xor128_decrypt_n_pad(void *out, const void *inp, void *otp, size_t len); static const unsigned char zero[4 * CHACHA_BLK_SIZE] = { 0 }; # else static const unsigned char zero[2 * CHACHA_BLK_SIZE] = { 0 }; # endif static int chacha20_poly1305_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); size_t tail, tohash_len, buf_len, plen = actx->tls_payload_length; unsigned char *buf, *tohash, *ctr, storage[sizeof(zero) + 32]; if (len != plen + POLY1305_BLOCK_SIZE) return -1; buf = storage + ((0 - (size_t)storage) & 15); /* align */ ctr = buf + CHACHA_BLK_SIZE; tohash = buf + CHACHA_BLK_SIZE - POLY1305_BLOCK_SIZE; # ifdef XOR128_HELPERS if (plen <= 3 * CHACHA_BLK_SIZE) { actx->key.counter[0] = 0; buf_len = (plen + 2 * CHACHA_BLK_SIZE - 1) & (0 - CHACHA_BLK_SIZE); ChaCha20_ctr32(buf, zero, buf_len, actx->key.key.d, actx->key.counter); Poly1305_Init(POLY1305_ctx(actx), buf); actx->key.partial_len = 0; memcpy(tohash, actx->tls_aad, POLY1305_BLOCK_SIZE); tohash_len = POLY1305_BLOCK_SIZE; actx->len.aad = EVP_AEAD_TLS1_AAD_LEN; actx->len.text = plen; if (plen) { if (EVP_CIPHER_CTX_is_encrypting(ctx)) ctr = xor128_encrypt_n_pad(out, in, ctr, plen); else ctr = xor128_decrypt_n_pad(out, in, ctr, plen); in += plen; out += plen; tohash_len = (size_t)(ctr - tohash); } } # else if (plen <= CHACHA_BLK_SIZE) { size_t i; actx->key.counter[0] = 0; ChaCha20_ctr32(buf, zero, (buf_len = 2 * CHACHA_BLK_SIZE), actx->key.key.d, actx->key.counter); Poly1305_Init(POLY1305_ctx(actx), buf); actx->key.partial_len = 0; memcpy(tohash, actx->tls_aad, POLY1305_BLOCK_SIZE); tohash_len = POLY1305_BLOCK_SIZE; actx->len.aad = EVP_AEAD_TLS1_AAD_LEN; actx->len.text = plen; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { for (i = 0; i < plen; i++) { out[i] = ctr[i] ^= in[i]; } } else { for (i = 0; i < plen; i++) { unsigned char c = in[i]; out[i] = ctr[i] ^ c; ctr[i] = c; } } in += i; out += i; tail = (0 - i) & (POLY1305_BLOCK_SIZE - 1); memset(ctr + i, 0, tail); ctr += i + tail; tohash_len += i + tail; } # endif else { actx->key.counter[0] = 0; ChaCha20_ctr32(buf, zero, (buf_len = CHACHA_BLK_SIZE), actx->key.key.d, actx->key.counter); Poly1305_Init(POLY1305_ctx(actx), buf); actx->key.counter[0] = 1; actx->key.partial_len = 0; Poly1305_Update(POLY1305_ctx(actx), actx->tls_aad, POLY1305_BLOCK_SIZE); tohash = ctr; tohash_len = 0; actx->len.aad = EVP_AEAD_TLS1_AAD_LEN; actx->len.text = plen; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { ChaCha20_ctr32(out, in, plen, actx->key.key.d, actx->key.counter); Poly1305_Update(POLY1305_ctx(actx), out, plen); } else { Poly1305_Update(POLY1305_ctx(actx), in, plen); ChaCha20_ctr32(out, in, plen, actx->key.key.d, actx->key.counter); } in += plen; out += plen; tail = (0 - plen) & (POLY1305_BLOCK_SIZE - 1); Poly1305_Update(POLY1305_ctx(actx), zero, tail); } { DECLARE_IS_ENDIAN; if (IS_LITTLE_ENDIAN) { memcpy(ctr, (unsigned char *)&actx->len, POLY1305_BLOCK_SIZE); } else { ctr[0] = (unsigned char)(actx->len.aad); ctr[1] = (unsigned char)(actx->len.aad>>8); ctr[2] = (unsigned char)(actx->len.aad>>16); ctr[3] = (unsigned char)(actx->len.aad>>24); ctr[4] = (unsigned char)(actx->len.aad>>32); ctr[5] = (unsigned char)(actx->len.aad>>40); ctr[6] = (unsigned char)(actx->len.aad>>48); ctr[7] = (unsigned char)(actx->len.aad>>56); ctr[8] = (unsigned char)(actx->len.text); ctr[9] = (unsigned char)(actx->len.text>>8); ctr[10] = (unsigned char)(actx->len.text>>16); ctr[11] = (unsigned char)(actx->len.text>>24); ctr[12] = (unsigned char)(actx->len.text>>32); ctr[13] = (unsigned char)(actx->len.text>>40); ctr[14] = (unsigned char)(actx->len.text>>48); ctr[15] = (unsigned char)(actx->len.text>>56); } tohash_len += POLY1305_BLOCK_SIZE; } Poly1305_Update(POLY1305_ctx(actx), tohash, tohash_len); OPENSSL_cleanse(buf, buf_len); Poly1305_Final(POLY1305_ctx(actx), EVP_CIPHER_CTX_is_encrypting(ctx) ? actx->tag : tohash); actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { memcpy(out, actx->tag, POLY1305_BLOCK_SIZE); } else { if (CRYPTO_memcmp(tohash, in, POLY1305_BLOCK_SIZE)) { memset(out - (len - POLY1305_BLOCK_SIZE), 0, len - POLY1305_BLOCK_SIZE); return -1; } } return len; } # else static const unsigned char zero[CHACHA_BLK_SIZE] = { 0 }; # endif static int chacha20_poly1305_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); size_t rem, plen = actx->tls_payload_length; if (!actx->mac_inited) { # if !defined(OPENSSL_SMALL_FOOTPRINT) if (plen != NO_TLS_PAYLOAD_LENGTH && out != NULL) return chacha20_poly1305_tls_cipher(ctx, out, in, len); # endif actx->key.counter[0] = 0; ChaCha20_ctr32(actx->key.buf, zero, CHACHA_BLK_SIZE, actx->key.key.d, actx->key.counter); Poly1305_Init(POLY1305_ctx(actx), actx->key.buf); actx->key.counter[0] = 1; actx->key.partial_len = 0; actx->len.aad = actx->len.text = 0; actx->mac_inited = 1; if (plen != NO_TLS_PAYLOAD_LENGTH) { Poly1305_Update(POLY1305_ctx(actx), actx->tls_aad, EVP_AEAD_TLS1_AAD_LEN); actx->len.aad = EVP_AEAD_TLS1_AAD_LEN; actx->aad = 1; } } if (in) { /* aad or text */ if (out == NULL) { /* aad */ Poly1305_Update(POLY1305_ctx(actx), in, len); actx->len.aad += len; actx->aad = 1; return len; } else { /* plain- or ciphertext */ if (actx->aad) { /* wrap up aad */ if ((rem = (size_t)actx->len.aad % POLY1305_BLOCK_SIZE)) Poly1305_Update(POLY1305_ctx(actx), zero, POLY1305_BLOCK_SIZE - rem); actx->aad = 0; } actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; if (plen == NO_TLS_PAYLOAD_LENGTH) plen = len; else if (len != plen + POLY1305_BLOCK_SIZE) return -1; if (EVP_CIPHER_CTX_is_encrypting(ctx)) { /* plaintext */ chacha_cipher(ctx, out, in, plen); Poly1305_Update(POLY1305_ctx(actx), out, plen); in += plen; out += plen; actx->len.text += plen; } else { /* ciphertext */ Poly1305_Update(POLY1305_ctx(actx), in, plen); chacha_cipher(ctx, out, in, plen); in += plen; out += plen; actx->len.text += plen; } } } if (in == NULL /* explicit final */ || plen != len) { /* or tls mode */ DECLARE_IS_ENDIAN; unsigned char temp[POLY1305_BLOCK_SIZE]; if (actx->aad) { /* wrap up aad */ if ((rem = (size_t)actx->len.aad % POLY1305_BLOCK_SIZE)) Poly1305_Update(POLY1305_ctx(actx), zero, POLY1305_BLOCK_SIZE - rem); actx->aad = 0; } if ((rem = (size_t)actx->len.text % POLY1305_BLOCK_SIZE)) Poly1305_Update(POLY1305_ctx(actx), zero, POLY1305_BLOCK_SIZE - rem); if (IS_LITTLE_ENDIAN) { Poly1305_Update(POLY1305_ctx(actx), (unsigned char *)&actx->len, POLY1305_BLOCK_SIZE); } else { temp[0] = (unsigned char)(actx->len.aad); temp[1] = (unsigned char)(actx->len.aad>>8); temp[2] = (unsigned char)(actx->len.aad>>16); temp[3] = (unsigned char)(actx->len.aad>>24); temp[4] = (unsigned char)(actx->len.aad>>32); temp[5] = (unsigned char)(actx->len.aad>>40); temp[6] = (unsigned char)(actx->len.aad>>48); temp[7] = (unsigned char)(actx->len.aad>>56); temp[8] = (unsigned char)(actx->len.text); temp[9] = (unsigned char)(actx->len.text>>8); temp[10] = (unsigned char)(actx->len.text>>16); temp[11] = (unsigned char)(actx->len.text>>24); temp[12] = (unsigned char)(actx->len.text>>32); temp[13] = (unsigned char)(actx->len.text>>40); temp[14] = (unsigned char)(actx->len.text>>48); temp[15] = (unsigned char)(actx->len.text>>56); Poly1305_Update(POLY1305_ctx(actx), temp, POLY1305_BLOCK_SIZE); } Poly1305_Final(POLY1305_ctx(actx), EVP_CIPHER_CTX_is_encrypting(ctx) ? actx->tag : temp); actx->mac_inited = 0; if (in != NULL && len != plen) { /* tls mode */ if (EVP_CIPHER_CTX_is_encrypting(ctx)) { memcpy(out, actx->tag, POLY1305_BLOCK_SIZE); } else { if (CRYPTO_memcmp(temp, in, POLY1305_BLOCK_SIZE)) { memset(out - plen, 0, plen); return -1; } } } else if (!EVP_CIPHER_CTX_is_encrypting(ctx)) { if (CRYPTO_memcmp(temp, actx->tag, actx->tag_len)) return -1; } } return len; } static int chacha20_poly1305_cleanup(EVP_CIPHER_CTX *ctx) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); if (actx) OPENSSL_cleanse(ctx->cipher_data, sizeof(*actx) + Poly1305_ctx_size()); return 1; } static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); switch (type) { case EVP_CTRL_INIT: if (actx == NULL) actx = ctx->cipher_data = OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size()); if (actx == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } actx->len.aad = 0; actx->len.text = 0; actx->aad = 0; actx->mac_inited = 0; actx->tag_len = 0; actx->nonce_len = 12; actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; memset(actx->tls_aad, 0, POLY1305_BLOCK_SIZE); return 1; case EVP_CTRL_COPY: if (actx) { EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr; dst->cipher_data = OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size()); if (dst->cipher_data == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_COPY_ERROR); return 0; } } return 1; case EVP_CTRL_GET_IVLEN: *(int *)ptr = actx->nonce_len; return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0 || arg > CHACHA20_POLY1305_MAX_IVLEN) return 0; actx->nonce_len = arg; return 1; case EVP_CTRL_AEAD_SET_IV_FIXED: if (arg != 12) return 0; actx->nonce[0] = actx->key.counter[1] = CHACHA_U8TOU32((unsigned char *)ptr); actx->nonce[1] = actx->key.counter[2] = CHACHA_U8TOU32((unsigned char *)ptr+4); actx->nonce[2] = actx->key.counter[3] = CHACHA_U8TOU32((unsigned char *)ptr+8); return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > POLY1305_BLOCK_SIZE) return 0; if (ptr != NULL) { memcpy(actx->tag, ptr, arg); actx->tag_len = arg; } return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !EVP_CIPHER_CTX_is_encrypting(ctx)) return 0; memcpy(ptr, actx->tag, arg); return 1; case EVP_CTRL_AEAD_TLS1_AAD: if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; { unsigned int len; unsigned char *aad = ptr; memcpy(actx->tls_aad, ptr, EVP_AEAD_TLS1_AAD_LEN); len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 | aad[EVP_AEAD_TLS1_AAD_LEN - 1]; aad = actx->tls_aad; if (!EVP_CIPHER_CTX_is_encrypting(ctx)) { if (len < POLY1305_BLOCK_SIZE) return 0; len -= POLY1305_BLOCK_SIZE; /* discount attached tag */ aad[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8); aad[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len; } actx->tls_payload_length = len; /* * merge record sequence number as per RFC7905 */ actx->key.counter[1] = actx->nonce[0]; actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad); actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4); actx->mac_inited = 0; return POLY1305_BLOCK_SIZE; /* tag length */ } case EVP_CTRL_AEAD_SET_MAC_KEY: /* no-op */ return 1; default: return -1; } } static EVP_CIPHER chacha20_poly1305 = { NID_chacha20_poly1305, 1, /* block_size */ CHACHA_KEY_SIZE, /* key_len */ 12, /* iv_len, 96-bit nonce in the context */ EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_CUSTOM_IV | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT | EVP_CIPH_CUSTOM_COPY | EVP_CIPH_FLAG_CUSTOM_CIPHER | EVP_CIPH_CUSTOM_IV_LENGTH, EVP_ORIG_GLOBAL, chacha20_poly1305_init_key, chacha20_poly1305_cipher, chacha20_poly1305_cleanup, 0, /* 0 moves context-specific structure allocation to ctrl */ NULL, /* set_asn1_parameters */ NULL, /* get_asn1_parameters */ chacha20_poly1305_ctrl, NULL /* app_data */ }; const EVP_CIPHER *EVP_chacha20_poly1305(void) { return(&chacha20_poly1305); } # endif #endif
./openssl/crypto/evp/legacy_md5_sha1.c
/* * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * MD5 and SHA-1 low level APIs are deprecated for public use, but still ok for * internal use. The prov/md5_sha1.h include requires this, but this must * be the first include loaded. */ #include "internal/deprecated.h" #include "crypto/evp.h" #include "prov/md5_sha1.h" /* diverse MD5_SHA1 macros */ #include "legacy_meth.h" IMPLEMENT_LEGACY_EVP_MD_METH_LC(md5_sha1_int, ossl_md5_sha1) static int md5_sha1_int_ctrl(EVP_MD_CTX *ctx, int cmd, int mslen, void *ms) { return ossl_md5_sha1_ctrl(EVP_MD_CTX_get0_md_data(ctx), cmd, mslen, ms); } static const EVP_MD md5_sha1_md = { NID_md5_sha1, NID_md5_sha1, MD5_SHA1_DIGEST_LENGTH, 0, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(md5_sha1_int_init, md5_sha1_int_update, md5_sha1_int_final, md5_sha1_int_ctrl, MD5_SHA1_CBLOCK), }; const EVP_MD *EVP_md5_sha1(void) { return &md5_sha1_md; }
./openssl/crypto/evp/evp_lib.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * EVP _meth_ APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/params.h> #include <openssl/core_names.h> #include <openssl/rsa.h> #include <openssl/dh.h> #include <openssl/ec.h> #include "crypto/evp.h" #include "crypto/cryptlib.h" #include "internal/provider.h" #include "evp_local.h" #if !defined(FIPS_MODULE) # include "crypto/asn1.h" int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type) { return evp_cipher_param_to_asn1_ex(c, type, NULL); } int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type) { return evp_cipher_asn1_to_param_ex(c, type, NULL); } int EVP_CIPHER_get_asn1_iv(EVP_CIPHER_CTX *ctx, ASN1_TYPE *type) { int i = 0; unsigned int l; if (type != NULL) { unsigned char iv[EVP_MAX_IV_LENGTH]; l = EVP_CIPHER_CTX_get_iv_length(ctx); if (!ossl_assert(l <= sizeof(iv))) return -1; i = ASN1_TYPE_get_octetstring(type, iv, l); if (i != (int)l) return -1; if (!EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1)) return -1; } return i; } int EVP_CIPHER_set_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type) { int i = 0; unsigned int j; unsigned char *oiv = NULL; if (type != NULL) { oiv = (unsigned char *)EVP_CIPHER_CTX_original_iv(c); j = EVP_CIPHER_CTX_get_iv_length(c); OPENSSL_assert(j <= sizeof(c->iv)); i = ASN1_TYPE_set_octetstring(type, oiv, j); } return i; } int evp_cipher_param_to_asn1_ex(EVP_CIPHER_CTX *c, ASN1_TYPE *type, evp_cipher_aead_asn1_params *asn1_params) { int ret = -1; /* Assume the worst */ const EVP_CIPHER *cipher = c->cipher; /* * For legacy implementations, we detect custom AlgorithmIdentifier * parameter handling by checking if the function pointer * cipher->set_asn1_parameters is set. We know that this pointer * is NULL for provided implementations. * * Otherwise, for any implementation, we check the flag * EVP_CIPH_FLAG_CUSTOM_ASN1. If it isn't set, we apply * default AI parameter extraction. * * Otherwise, for provided implementations, we convert |type| to * a DER encoded blob and pass to the implementation in OSSL_PARAM * form. * * If none of the above applies, this operation is unsupported. */ if (cipher->set_asn1_parameters != NULL) { ret = cipher->set_asn1_parameters(c, type); } else if ((EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_CUSTOM_ASN1) == 0) { switch (EVP_CIPHER_get_mode(cipher)) { case EVP_CIPH_WRAP_MODE: if (EVP_CIPHER_is_a(cipher, SN_id_smime_alg_CMS3DESwrap)) ASN1_TYPE_set(type, V_ASN1_NULL, NULL); ret = 1; break; case EVP_CIPH_GCM_MODE: ret = evp_cipher_set_asn1_aead_params(c, type, asn1_params); break; case EVP_CIPH_CCM_MODE: case EVP_CIPH_XTS_MODE: case EVP_CIPH_OCB_MODE: ret = -2; break; default: ret = EVP_CIPHER_set_asn1_iv(c, type); } } else if (cipher->prov != NULL) { OSSL_PARAM params[3], *p = params; unsigned char *der = NULL, *derp; /* * We make two passes, the first to get the appropriate buffer size, * and the second to get the actual value. */ *p++ = OSSL_PARAM_construct_octet_string( OSSL_CIPHER_PARAM_ALGORITHM_ID_PARAMS, NULL, 0); *p = OSSL_PARAM_construct_end(); if (!EVP_CIPHER_CTX_get_params(c, params)) goto err; /* ... but, we should get a return size too! */ if (OSSL_PARAM_modified(params) && params[0].return_size != 0 && (der = OPENSSL_malloc(params[0].return_size)) != NULL) { params[0].data = der; params[0].data_size = params[0].return_size; OSSL_PARAM_set_all_unmodified(params); derp = der; if (EVP_CIPHER_CTX_get_params(c, params) && OSSL_PARAM_modified(params) && d2i_ASN1_TYPE(&type, (const unsigned char **)&derp, params[0].return_size) != NULL) { ret = 1; } OPENSSL_free(der); } } else { ret = -2; } err: if (ret == -2) ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_CIPHER); else if (ret <= 0) ERR_raise(ERR_LIB_EVP, EVP_R_CIPHER_PARAMETER_ERROR); if (ret < -1) ret = -1; return ret; } int evp_cipher_asn1_to_param_ex(EVP_CIPHER_CTX *c, ASN1_TYPE *type, evp_cipher_aead_asn1_params *asn1_params) { int ret = -1; /* Assume the worst */ const EVP_CIPHER *cipher = c->cipher; /* * For legacy implementations, we detect custom AlgorithmIdentifier * parameter handling by checking if there the function pointer * cipher->get_asn1_parameters is set. We know that this pointer * is NULL for provided implementations. * * Otherwise, for any implementation, we check the flag * EVP_CIPH_FLAG_CUSTOM_ASN1. If it isn't set, we apply * default AI parameter creation. * * Otherwise, for provided implementations, we get the AI parameter * in DER encoded form from the implementation by requesting the * appropriate OSSL_PARAM and converting the result to a ASN1_TYPE. * * If none of the above applies, this operation is unsupported. */ if (cipher->get_asn1_parameters != NULL) { ret = cipher->get_asn1_parameters(c, type); } else if ((EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_CUSTOM_ASN1) == 0) { switch (EVP_CIPHER_get_mode(cipher)) { case EVP_CIPH_WRAP_MODE: ret = 1; break; case EVP_CIPH_GCM_MODE: ret = evp_cipher_get_asn1_aead_params(c, type, asn1_params); break; case EVP_CIPH_CCM_MODE: case EVP_CIPH_XTS_MODE: case EVP_CIPH_OCB_MODE: ret = -2; break; default: ret = EVP_CIPHER_get_asn1_iv(c, type) >= 0 ? 1 : -1; } } else if (cipher->prov != NULL) { OSSL_PARAM params[3], *p = params; unsigned char *der = NULL; int derl = -1; if ((derl = i2d_ASN1_TYPE(type, &der)) >= 0) { *p++ = OSSL_PARAM_construct_octet_string( OSSL_CIPHER_PARAM_ALGORITHM_ID_PARAMS, der, (size_t)derl); *p = OSSL_PARAM_construct_end(); if (EVP_CIPHER_CTX_set_params(c, params)) ret = 1; OPENSSL_free(der); } } else { ret = -2; } if (ret == -2) ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_CIPHER); else if (ret <= 0) ERR_raise(ERR_LIB_EVP, EVP_R_CIPHER_PARAMETER_ERROR); if (ret < -1) ret = -1; return ret; } int evp_cipher_get_asn1_aead_params(EVP_CIPHER_CTX *c, ASN1_TYPE *type, evp_cipher_aead_asn1_params *asn1_params) { int i = 0; long tl; unsigned char iv[EVP_MAX_IV_LENGTH]; if (type == NULL || asn1_params == NULL) return 0; i = ossl_asn1_type_get_octetstring_int(type, &tl, NULL, EVP_MAX_IV_LENGTH); if (i <= 0) return -1; ossl_asn1_type_get_octetstring_int(type, &tl, iv, i); memcpy(asn1_params->iv, iv, i); asn1_params->iv_len = i; return i; } int evp_cipher_set_asn1_aead_params(EVP_CIPHER_CTX *c, ASN1_TYPE *type, evp_cipher_aead_asn1_params *asn1_params) { if (type == NULL || asn1_params == NULL) return 0; return ossl_asn1_type_set_octetstring_int(type, asn1_params->tag_len, asn1_params->iv, asn1_params->iv_len); } #endif /* !defined(FIPS_MODULE) */ /* Convert the various cipher NIDs and dummies to a proper OID NID */ int EVP_CIPHER_get_type(const EVP_CIPHER *cipher) { int nid; nid = EVP_CIPHER_get_nid(cipher); switch (nid) { case NID_rc2_cbc: case NID_rc2_64_cbc: case NID_rc2_40_cbc: return NID_rc2_cbc; case NID_rc4: case NID_rc4_40: return NID_rc4; case NID_aes_128_cfb128: case NID_aes_128_cfb8: case NID_aes_128_cfb1: return NID_aes_128_cfb128; case NID_aes_192_cfb128: case NID_aes_192_cfb8: case NID_aes_192_cfb1: return NID_aes_192_cfb128; case NID_aes_256_cfb128: case NID_aes_256_cfb8: case NID_aes_256_cfb1: return NID_aes_256_cfb128; case NID_des_cfb64: case NID_des_cfb8: case NID_des_cfb1: return NID_des_cfb64; case NID_des_ede3_cfb64: case NID_des_ede3_cfb8: case NID_des_ede3_cfb1: return NID_des_cfb64; default: #ifdef FIPS_MODULE return NID_undef; #else { /* Check it has an OID and it is valid */ ASN1_OBJECT *otmp = OBJ_nid2obj(nid); if (OBJ_get0_data(otmp) == NULL) nid = NID_undef; ASN1_OBJECT_free(otmp); return nid; } #endif } } int evp_cipher_cache_constants(EVP_CIPHER *cipher) { int ok, aead = 0, custom_iv = 0, cts = 0, multiblock = 0, randkey = 0; size_t ivlen = 0; size_t blksz = 0; size_t keylen = 0; unsigned int mode = 0; OSSL_PARAM params[10]; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_BLOCK_SIZE, &blksz); params[1] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_IVLEN, &ivlen); params[2] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &keylen); params[3] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_MODE, &mode); params[4] = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_AEAD, &aead); params[5] = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_CUSTOM_IV, &custom_iv); params[6] = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_CTS, &cts); params[7] = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK, &multiblock); params[8] = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_HAS_RAND_KEY, &randkey); params[9] = OSSL_PARAM_construct_end(); ok = evp_do_ciph_getparams(cipher, params) > 0; if (ok) { cipher->block_size = blksz; cipher->iv_len = ivlen; cipher->key_len = keylen; cipher->flags = mode; if (aead) cipher->flags |= EVP_CIPH_FLAG_AEAD_CIPHER; if (custom_iv) cipher->flags |= EVP_CIPH_CUSTOM_IV; if (cts) cipher->flags |= EVP_CIPH_FLAG_CTS; if (multiblock) cipher->flags |= EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK; if (cipher->ccipher != NULL) cipher->flags |= EVP_CIPH_FLAG_CUSTOM_CIPHER; if (randkey) cipher->flags |= EVP_CIPH_RAND_KEY; if (OSSL_PARAM_locate_const(EVP_CIPHER_gettable_ctx_params(cipher), OSSL_CIPHER_PARAM_ALGORITHM_ID_PARAMS)) cipher->flags |= EVP_CIPH_FLAG_CUSTOM_ASN1; } return ok; } int EVP_CIPHER_get_block_size(const EVP_CIPHER *cipher) { return cipher->block_size; } int EVP_CIPHER_CTX_get_block_size(const EVP_CIPHER_CTX *ctx) { return EVP_CIPHER_get_block_size(ctx->cipher); } int EVP_CIPHER_impl_ctx_size(const EVP_CIPHER *e) { return e->ctx_size; } int EVP_Cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, unsigned int inl) { if (ctx->cipher->prov != NULL) { /* * If the provided implementation has a ccipher function, we use it, * and translate its return value like this: 0 => -1, 1 => outlen * * Otherwise, we call the cupdate function if in != NULL, or cfinal * if in == NULL. Regardless of which, we return what we got. */ int ret = -1; size_t outl = 0; size_t blocksize = EVP_CIPHER_CTX_get_block_size(ctx); if (ctx->cipher->ccipher != NULL) ret = ctx->cipher->ccipher(ctx->algctx, out, &outl, inl + (blocksize == 1 ? 0 : blocksize), in, (size_t)inl) ? (int)outl : -1; else if (in != NULL) ret = ctx->cipher->cupdate(ctx->algctx, out, &outl, inl + (blocksize == 1 ? 0 : blocksize), in, (size_t)inl); else ret = ctx->cipher->cfinal(ctx->algctx, out, &outl, blocksize == 1 ? 0 : blocksize); return ret; } return ctx->cipher->do_cipher(ctx, out, in, inl); } #ifndef OPENSSL_NO_DEPRECATED_3_0 const EVP_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->cipher; } #endif const EVP_CIPHER *EVP_CIPHER_CTX_get0_cipher(const EVP_CIPHER_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->cipher; } EVP_CIPHER *EVP_CIPHER_CTX_get1_cipher(EVP_CIPHER_CTX *ctx) { EVP_CIPHER *cipher; if (ctx == NULL) return NULL; cipher = (EVP_CIPHER *)ctx->cipher; if (!EVP_CIPHER_up_ref(cipher)) return NULL; return cipher; } int EVP_CIPHER_CTX_is_encrypting(const EVP_CIPHER_CTX *ctx) { return ctx->encrypt; } unsigned long EVP_CIPHER_get_flags(const EVP_CIPHER *cipher) { return cipher->flags; } void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx) { return ctx->app_data; } void EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *ctx, void *data) { ctx->app_data = data; } void *EVP_CIPHER_CTX_get_cipher_data(const EVP_CIPHER_CTX *ctx) { return ctx->cipher_data; } void *EVP_CIPHER_CTX_set_cipher_data(EVP_CIPHER_CTX *ctx, void *cipher_data) { void *old_cipher_data; old_cipher_data = ctx->cipher_data; ctx->cipher_data = cipher_data; return old_cipher_data; } int EVP_CIPHER_get_iv_length(const EVP_CIPHER *cipher) { return cipher->iv_len; } int EVP_CIPHER_CTX_get_iv_length(const EVP_CIPHER_CTX *ctx) { if (ctx->iv_len < 0) { int rv, len = EVP_CIPHER_get_iv_length(ctx->cipher); size_t v = len; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; if (ctx->cipher->get_ctx_params != NULL) { params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_IVLEN, &v); rv = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); if (rv > 0) { if (OSSL_PARAM_modified(params) && !OSSL_PARAM_get_int(params, &len)) return -1; } else if (rv != EVP_CTRL_RET_UNSUPPORTED) { return -1; } } /* Code below to be removed when legacy support is dropped. */ else if ((EVP_CIPHER_get_flags(ctx->cipher) & EVP_CIPH_CUSTOM_IV_LENGTH) != 0) { rv = EVP_CIPHER_CTX_ctrl((EVP_CIPHER_CTX *)ctx, EVP_CTRL_GET_IVLEN, 0, &len); if (rv <= 0) return -1; } /*- * Casting away the const is annoying but required here. We need to * cache the result for performance reasons. */ ((EVP_CIPHER_CTX *)ctx)->iv_len = len; } return ctx->iv_len; } int EVP_CIPHER_CTX_get_tag_length(const EVP_CIPHER_CTX *ctx) { int ret; size_t v = 0; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_TAGLEN, &v); ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); return ret == 1 ? (int)v : 0; } #ifndef OPENSSL_NO_DEPRECATED_3_0 const unsigned char *EVP_CIPHER_CTX_original_iv(const EVP_CIPHER_CTX *ctx) { int ok; const unsigned char *v = ctx->oiv; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_IV, (void **)&v, sizeof(ctx->oiv)); ok = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); return ok != 0 ? v : NULL; } /* * OSSL_PARAM_OCTET_PTR gets us the pointer to the running IV in the provider */ const unsigned char *EVP_CIPHER_CTX_iv(const EVP_CIPHER_CTX *ctx) { int ok; const unsigned char *v = ctx->iv; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_UPDATED_IV, (void **)&v, sizeof(ctx->iv)); ok = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); return ok != 0 ? v : NULL; } unsigned char *EVP_CIPHER_CTX_iv_noconst(EVP_CIPHER_CTX *ctx) { int ok; unsigned char *v = ctx->iv; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_UPDATED_IV, (void **)&v, sizeof(ctx->iv)); ok = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); return ok != 0 ? v : NULL; } #endif /* OPENSSL_NO_DEPRECATED_3_0_0 */ int EVP_CIPHER_CTX_get_updated_iv(EVP_CIPHER_CTX *ctx, void *buf, size_t len) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_UPDATED_IV, buf, len); return evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params) > 0; } int EVP_CIPHER_CTX_get_original_iv(EVP_CIPHER_CTX *ctx, void *buf, size_t len) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_IV, buf, len); return evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params) > 0; } unsigned char *EVP_CIPHER_CTX_buf_noconst(EVP_CIPHER_CTX *ctx) { return ctx->buf; } int EVP_CIPHER_CTX_get_num(const EVP_CIPHER_CTX *ctx) { int ok; unsigned int v = (unsigned int)ctx->num; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_NUM, &v); ok = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); return ok != 0 ? (int)v : EVP_CTRL_RET_UNSUPPORTED; } int EVP_CIPHER_CTX_set_num(EVP_CIPHER_CTX *ctx, int num) { int ok; unsigned int n = (unsigned int)num; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_NUM, &n); ok = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params); if (ok != 0) ctx->num = (int)n; return ok != 0; } int EVP_CIPHER_get_key_length(const EVP_CIPHER *cipher) { return cipher->key_len; } int EVP_CIPHER_CTX_get_key_length(const EVP_CIPHER_CTX *ctx) { if (ctx->key_len <= 0 && ctx->cipher->prov != NULL) { int ok; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; size_t len; params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &len); ok = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params); if (ok <= 0) return EVP_CTRL_RET_UNSUPPORTED; /*- * The if branch should never be taken since EVP_MAX_KEY_LENGTH is * less than INT_MAX but best to be safe. * * Casting away the const is annoying but required here. We need to * cache the result for performance reasons. */ if (!OSSL_PARAM_get_int(params, &((EVP_CIPHER_CTX *)ctx)->key_len)) return -1; ((EVP_CIPHER_CTX *)ctx)->key_len = (int)len; } return ctx->key_len; } int EVP_CIPHER_get_nid(const EVP_CIPHER *cipher) { return cipher->nid; } int EVP_CIPHER_CTX_get_nid(const EVP_CIPHER_CTX *ctx) { return ctx->cipher->nid; } int EVP_CIPHER_is_a(const EVP_CIPHER *cipher, const char *name) { if (cipher == NULL) return 0; if (cipher->prov != NULL) return evp_is_a(cipher->prov, cipher->name_id, NULL, name); return evp_is_a(NULL, 0, EVP_CIPHER_get0_name(cipher), name); } int evp_cipher_get_number(const EVP_CIPHER *cipher) { return cipher->name_id; } const char *EVP_CIPHER_get0_name(const EVP_CIPHER *cipher) { if (cipher->type_name != NULL) return cipher->type_name; #ifndef FIPS_MODULE return OBJ_nid2sn(EVP_CIPHER_get_nid(cipher)); #else return NULL; #endif } const char *EVP_CIPHER_get0_description(const EVP_CIPHER *cipher) { if (cipher->description != NULL) return cipher->description; #ifndef FIPS_MODULE return OBJ_nid2ln(EVP_CIPHER_get_nid(cipher)); #else return NULL; #endif } int EVP_CIPHER_names_do_all(const EVP_CIPHER *cipher, void (*fn)(const char *name, void *data), void *data) { if (cipher->prov != NULL) return evp_names_do_all(cipher->prov, cipher->name_id, fn, data); return 1; } const OSSL_PROVIDER *EVP_CIPHER_get0_provider(const EVP_CIPHER *cipher) { return cipher->prov; } int EVP_CIPHER_get_mode(const EVP_CIPHER *cipher) { return EVP_CIPHER_get_flags(cipher) & EVP_CIPH_MODE; } int EVP_MD_is_a(const EVP_MD *md, const char *name) { if (md == NULL) return 0; if (md->prov != NULL) return evp_is_a(md->prov, md->name_id, NULL, name); return evp_is_a(NULL, 0, EVP_MD_get0_name(md), name); } int evp_md_get_number(const EVP_MD *md) { return md->name_id; } const char *EVP_MD_get0_description(const EVP_MD *md) { if (md->description != NULL) return md->description; #ifndef FIPS_MODULE return OBJ_nid2ln(EVP_MD_nid(md)); #else return NULL; #endif } const char *EVP_MD_get0_name(const EVP_MD *md) { if (md == NULL) return NULL; if (md->type_name != NULL) return md->type_name; #ifndef FIPS_MODULE return OBJ_nid2sn(EVP_MD_nid(md)); #else return NULL; #endif } int EVP_MD_names_do_all(const EVP_MD *md, void (*fn)(const char *name, void *data), void *data) { if (md->prov != NULL) return evp_names_do_all(md->prov, md->name_id, fn, data); return 1; } const OSSL_PROVIDER *EVP_MD_get0_provider(const EVP_MD *md) { return md->prov; } int EVP_MD_get_type(const EVP_MD *md) { return md->type; } int EVP_MD_get_pkey_type(const EVP_MD *md) { return md->pkey_type; } int EVP_MD_get_block_size(const EVP_MD *md) { if (md == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_MESSAGE_DIGEST_IS_NULL); return -1; } return md->block_size; } int EVP_MD_get_size(const EVP_MD *md) { if (md == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_MESSAGE_DIGEST_IS_NULL); return -1; } return md->md_size; } unsigned long EVP_MD_get_flags(const EVP_MD *md) { return md->flags; } EVP_MD *EVP_MD_meth_new(int md_type, int pkey_type) { EVP_MD *md = evp_md_new(); if (md != NULL) { md->type = md_type; md->pkey_type = pkey_type; md->origin = EVP_ORIG_METH; } return md; } EVP_MD *EVP_MD_meth_dup(const EVP_MD *md) { EVP_MD *to = NULL; /* * Non-legacy EVP_MDs can't be duplicated like this. * Use EVP_MD_up_ref() instead. */ if (md->prov != NULL) return NULL; if ((to = EVP_MD_meth_new(md->type, md->pkey_type)) != NULL) { CRYPTO_REF_COUNT refcnt = to->refcnt; memcpy(to, md, sizeof(*to)); to->refcnt = refcnt; to->origin = EVP_ORIG_METH; } return to; } void evp_md_free_int(EVP_MD *md) { OPENSSL_free(md->type_name); ossl_provider_free(md->prov); CRYPTO_FREE_REF(&md->refcnt); OPENSSL_free(md); } void EVP_MD_meth_free(EVP_MD *md) { if (md == NULL || md->origin != EVP_ORIG_METH) return; evp_md_free_int(md); } int EVP_MD_meth_set_input_blocksize(EVP_MD *md, int blocksize) { if (md->block_size != 0) return 0; md->block_size = blocksize; return 1; } int EVP_MD_meth_set_result_size(EVP_MD *md, int resultsize) { if (md->md_size != 0) return 0; md->md_size = resultsize; return 1; } int EVP_MD_meth_set_app_datasize(EVP_MD *md, int datasize) { if (md->ctx_size != 0) return 0; md->ctx_size = datasize; return 1; } int EVP_MD_meth_set_flags(EVP_MD *md, unsigned long flags) { if (md->flags != 0) return 0; md->flags = flags; return 1; } int EVP_MD_meth_set_init(EVP_MD *md, int (*init)(EVP_MD_CTX *ctx)) { if (md->init != NULL) return 0; md->init = init; return 1; } int EVP_MD_meth_set_update(EVP_MD *md, int (*update)(EVP_MD_CTX *ctx, const void *data, size_t count)) { if (md->update != NULL) return 0; md->update = update; return 1; } int EVP_MD_meth_set_final(EVP_MD *md, int (*final)(EVP_MD_CTX *ctx, unsigned char *md)) { if (md->final != NULL) return 0; md->final = final; return 1; } int EVP_MD_meth_set_copy(EVP_MD *md, int (*copy)(EVP_MD_CTX *to, const EVP_MD_CTX *from)) { if (md->copy != NULL) return 0; md->copy = copy; return 1; } int EVP_MD_meth_set_cleanup(EVP_MD *md, int (*cleanup)(EVP_MD_CTX *ctx)) { if (md->cleanup != NULL) return 0; md->cleanup = cleanup; return 1; } int EVP_MD_meth_set_ctrl(EVP_MD *md, int (*ctrl)(EVP_MD_CTX *ctx, int cmd, int p1, void *p2)) { if (md->md_ctrl != NULL) return 0; md->md_ctrl = ctrl; return 1; } int EVP_MD_meth_get_input_blocksize(const EVP_MD *md) { return md->block_size; } int EVP_MD_meth_get_result_size(const EVP_MD *md) { return md->md_size; } int EVP_MD_meth_get_app_datasize(const EVP_MD *md) { return md->ctx_size; } unsigned long EVP_MD_meth_get_flags(const EVP_MD *md) { return md->flags; } int (*EVP_MD_meth_get_init(const EVP_MD *md))(EVP_MD_CTX *ctx) { return md->init; } int (*EVP_MD_meth_get_update(const EVP_MD *md))(EVP_MD_CTX *ctx, const void *data, size_t count) { return md->update; } int (*EVP_MD_meth_get_final(const EVP_MD *md))(EVP_MD_CTX *ctx, unsigned char *md) { return md->final; } int (*EVP_MD_meth_get_copy(const EVP_MD *md))(EVP_MD_CTX *to, const EVP_MD_CTX *from) { return md->copy; } int (*EVP_MD_meth_get_cleanup(const EVP_MD *md))(EVP_MD_CTX *ctx) { return md->cleanup; } int (*EVP_MD_meth_get_ctrl(const EVP_MD *md))(EVP_MD_CTX *ctx, int cmd, int p1, void *p2) { return md->md_ctrl; } #ifndef OPENSSL_NO_DEPRECATED_3_0 const EVP_MD *EVP_MD_CTX_md(const EVP_MD_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->reqdigest; } #endif const EVP_MD *EVP_MD_CTX_get0_md(const EVP_MD_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->reqdigest; } EVP_MD *EVP_MD_CTX_get1_md(EVP_MD_CTX *ctx) { EVP_MD *md; if (ctx == NULL) return NULL; md = (EVP_MD *)ctx->reqdigest; if (md == NULL || !EVP_MD_up_ref(md)) return NULL; return md; } EVP_PKEY_CTX *EVP_MD_CTX_get_pkey_ctx(const EVP_MD_CTX *ctx) { return ctx->pctx; } #if !defined(FIPS_MODULE) void EVP_MD_CTX_set_pkey_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pctx) { /* * it's reasonable to set NULL pctx (a.k.a clear the ctx->pctx), so * we have to deal with the cleanup job here. */ if (!EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX)) EVP_PKEY_CTX_free(ctx->pctx); ctx->pctx = pctx; if (pctx != NULL) { /* make sure pctx is not freed when destroying EVP_MD_CTX */ EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX); } else { EVP_MD_CTX_clear_flags(ctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX); } } #endif /* !defined(FIPS_MODULE) */ void *EVP_MD_CTX_get0_md_data(const EVP_MD_CTX *ctx) { return ctx->md_data; } int (*EVP_MD_CTX_update_fn(EVP_MD_CTX *ctx))(EVP_MD_CTX *ctx, const void *data, size_t count) { return ctx->update; } void EVP_MD_CTX_set_update_fn(EVP_MD_CTX *ctx, int (*update) (EVP_MD_CTX *ctx, const void *data, size_t count)) { ctx->update = update; } void EVP_MD_CTX_set_flags(EVP_MD_CTX *ctx, int flags) { ctx->flags |= flags; } void EVP_MD_CTX_clear_flags(EVP_MD_CTX *ctx, int flags) { ctx->flags &= ~flags; } int EVP_MD_CTX_test_flags(const EVP_MD_CTX *ctx, int flags) { return (ctx->flags & flags); } static int evp_cipher_ctx_enable_use_bits(EVP_CIPHER_CTX *ctx, unsigned int enable) { OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_USE_BITS, &enable); return EVP_CIPHER_CTX_set_params(ctx, params); } void EVP_CIPHER_CTX_set_flags(EVP_CIPHER_CTX *ctx, int flags) { int oldflags = ctx->flags; ctx->flags |= flags; if (((oldflags ^ ctx->flags) & EVP_CIPH_FLAG_LENGTH_BITS) != 0) evp_cipher_ctx_enable_use_bits(ctx, 1); } void EVP_CIPHER_CTX_clear_flags(EVP_CIPHER_CTX *ctx, int flags) { int oldflags = ctx->flags; ctx->flags &= ~flags; if (((oldflags ^ ctx->flags) & EVP_CIPH_FLAG_LENGTH_BITS) != 0) evp_cipher_ctx_enable_use_bits(ctx, 0); } int EVP_CIPHER_CTX_test_flags(const EVP_CIPHER_CTX *ctx, int flags) { return (ctx->flags & flags); } #if !defined(FIPS_MODULE) int EVP_PKEY_CTX_set_group_name(EVP_PKEY_CTX *ctx, const char *name) { OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; if (ctx == NULL || !EVP_PKEY_CTX_IS_GEN_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } if (name == NULL) return -1; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, (char *)name, 0); return EVP_PKEY_CTX_set_params(ctx, params); } int EVP_PKEY_CTX_get_group_name(EVP_PKEY_CTX *ctx, char *name, size_t namelen) { OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; OSSL_PARAM *p = params; if (ctx == NULL || !EVP_PKEY_CTX_IS_GEN_OP(ctx)) { /* There is no legacy support for this */ ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } if (name == NULL) return -1; *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, name, namelen); if (!EVP_PKEY_CTX_get_params(ctx, params)) return -1; return 1; } /* * evp_pkey_keygen() abstracts from the explicit use of B<EVP_PKEY_CTX> * while providing a generic way of generating a new asymmetric key pair * of algorithm type I<name> (e.g., C<RSA> or C<EC>). * The library context I<libctx> and property query I<propq> * are used when fetching algorithms from providers. * The I<params> specify algorithm-specific parameters * such as the RSA modulus size or the name of an EC curve. */ static EVP_PKEY *evp_pkey_keygen(OSSL_LIB_CTX *libctx, const char *name, const char *propq, const OSSL_PARAM *params) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_name(libctx, name, propq); if (ctx != NULL && EVP_PKEY_keygen_init(ctx) > 0 && EVP_PKEY_CTX_set_params(ctx, params)) (void)EVP_PKEY_generate(ctx, &pkey); EVP_PKEY_CTX_free(ctx); return pkey; } EVP_PKEY *EVP_PKEY_Q_keygen(OSSL_LIB_CTX *libctx, const char *propq, const char *type, ...) { va_list args; size_t bits; char *name; OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; EVP_PKEY *ret = NULL; va_start(args, type); if (OPENSSL_strcasecmp(type, "RSA") == 0) { bits = va_arg(args, size_t); params[0] = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_RSA_BITS, &bits); } else if (OPENSSL_strcasecmp(type, "EC") == 0) { name = va_arg(args, char *); params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, name, 0); } else if (OPENSSL_strcasecmp(type, "ED25519") != 0 && OPENSSL_strcasecmp(type, "X25519") != 0 && OPENSSL_strcasecmp(type, "ED448") != 0 && OPENSSL_strcasecmp(type, "X448") != 0 && OPENSSL_strcasecmp(type, "SM2") != 0) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_INVALID_ARGUMENT); goto end; } ret = evp_pkey_keygen(libctx, type, propq, params); end: va_end(args); return ret; } #endif /* !defined(FIPS_MODULE) */
./openssl/crypto/pkcs12/p12_crt.c
/* * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/pkcs12.h> #include "p12_local.h" static int pkcs12_add_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, PKCS12_SAFEBAG *bag); static int pkcs12_remove_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, PKCS12_SAFEBAG *bag); static PKCS12_SAFEBAG *pkcs12_add_cert_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, X509 *cert, const char *name, int namelen, unsigned char *keyid, int keyidlen); static int copy_bag_attr(PKCS12_SAFEBAG *bag, EVP_PKEY *pkey, int nid) { int idx = EVP_PKEY_get_attr_by_NID(pkey, nid, -1); if (idx < 0) return 1; return X509at_add1_attr(&bag->attrib, EVP_PKEY_get_attr(pkey, idx)) != NULL; } PKCS12 *PKCS12_create_ex2(const char *pass, const char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert, int iter, int mac_iter, int keytype, OSSL_LIB_CTX *ctx, const char *propq, PKCS12_create_cb *cb, void *cbarg) { PKCS12 *p12 = NULL; STACK_OF(PKCS7) *safes = NULL; STACK_OF(PKCS12_SAFEBAG) *bags = NULL; PKCS12_SAFEBAG *bag = NULL; int i, cbret; unsigned char keyid[EVP_MAX_MD_SIZE]; unsigned int keyidlen = 0; int namelen = -1; unsigned char *pkeyid = NULL; int pkeyidlen = -1; /* Set defaults */ if (nid_cert == NID_undef) nid_cert = NID_aes_256_cbc; if (nid_key == NID_undef) nid_key = NID_aes_256_cbc; if (!iter) iter = PKCS12_DEFAULT_ITER; if (!mac_iter) mac_iter = PKCS12_DEFAULT_ITER; if (pkey == NULL && cert == NULL && ca == NULL) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_INVALID_NULL_ARGUMENT); return NULL; } if (pkey && cert) { if (!X509_check_private_key(cert, pkey)) return NULL; if (!X509_digest(cert, EVP_sha1(), keyid, &keyidlen)) return NULL; } if (cert) { if (name == NULL) name = (char *)X509_alias_get0(cert, &namelen); if (keyidlen > 0) { pkeyid = keyid; pkeyidlen = keyidlen; } else { pkeyid = X509_keyid_get0(cert, &pkeyidlen); } bag = pkcs12_add_cert_bag(&bags, cert, name, namelen, pkeyid, pkeyidlen); if (cb != NULL) { cbret = cb(bag, cbarg); if (cbret == -1) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CALLBACK_FAILED); goto err; } else if (cbret == 0) { pkcs12_remove_bag(&bags, bag); } } } /* Add all other certificates */ for (i = 0; i < sk_X509_num(ca); i++) { if ((bag = PKCS12_add_cert(&bags, sk_X509_value(ca, i))) == NULL) goto err; if (cb != NULL) { cbret = cb(bag, cbarg); if (cbret == -1) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CALLBACK_FAILED); goto err; } else if (cbret == 0) { pkcs12_remove_bag(&bags, bag); } } } if (bags && !PKCS12_add_safe_ex(&safes, bags, nid_cert, iter, pass, ctx, propq)) goto err; sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); bags = NULL; if (pkey) { bag = PKCS12_add_key_ex(&bags, pkey, keytype, iter, nid_key, pass, ctx, propq); if (!bag) goto err; if (!copy_bag_attr(bag, pkey, NID_ms_csp_name)) goto err; if (!copy_bag_attr(bag, pkey, NID_LocalKeySet)) goto err; if (name && !PKCS12_add_friendlyname(bag, name, -1)) goto err; if (keyidlen && !PKCS12_add_localkeyid(bag, keyid, keyidlen)) goto err; if (cb != NULL) { cbret = cb(bag, cbarg); if (cbret == -1) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CALLBACK_FAILED); goto err; } else if (cbret == 0) { pkcs12_remove_bag(&bags, bag); } } } if (bags && !PKCS12_add_safe(&safes, bags, -1, 0, NULL)) goto err; sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); bags = NULL; p12 = PKCS12_add_safes_ex(safes, 0, ctx, propq); if (p12 == NULL) goto err; sk_PKCS7_pop_free(safes, PKCS7_free); safes = NULL; if ((mac_iter != -1) && !PKCS12_set_mac(p12, pass, -1, NULL, 0, mac_iter, NULL)) goto err; return p12; err: PKCS12_free(p12); sk_PKCS7_pop_free(safes, PKCS7_free); sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); return NULL; } PKCS12 *PKCS12_create_ex(const char *pass, const char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert, int iter, int mac_iter, int keytype, OSSL_LIB_CTX *ctx, const char *propq) { return PKCS12_create_ex2(pass, name, pkey, cert, ca, nid_key, nid_cert, iter, mac_iter, keytype, ctx, propq, NULL, NULL); } PKCS12 *PKCS12_create(const char *pass, const char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert, int iter, int mac_iter, int keytype) { return PKCS12_create_ex(pass, name, pkey, cert, ca, nid_key, nid_cert, iter, mac_iter, keytype, NULL, NULL); } static PKCS12_SAFEBAG *pkcs12_add_cert_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, X509 *cert, const char *name, int namelen, unsigned char *keyid, int keyidlen) { PKCS12_SAFEBAG *bag = NULL; /* Add user certificate */ if ((bag = PKCS12_SAFEBAG_create_cert(cert)) == NULL) goto err; if (name != NULL && !PKCS12_add_friendlyname(bag, name, namelen)) goto err; if (keyid != NULL && !PKCS12_add_localkeyid(bag, keyid, keyidlen)) goto err; if (!pkcs12_add_bag(pbags, bag)) goto err; return bag; err: PKCS12_SAFEBAG_free(bag); return NULL; } PKCS12_SAFEBAG *PKCS12_add_cert(STACK_OF(PKCS12_SAFEBAG) **pbags, X509 *cert) { char *name = NULL; int namelen = -1; unsigned char *keyid = NULL; int keyidlen = -1; /* * Use friendlyName and localKeyID in certificate. (if present) */ name = (char *)X509_alias_get0(cert, &namelen); keyid = X509_keyid_get0(cert, &keyidlen); return pkcs12_add_cert_bag(pbags, cert, name, namelen, keyid, keyidlen); } PKCS12_SAFEBAG *PKCS12_add_key_ex(STACK_OF(PKCS12_SAFEBAG) **pbags, EVP_PKEY *key, int key_usage, int iter, int nid_key, const char *pass, OSSL_LIB_CTX *ctx, const char *propq) { PKCS12_SAFEBAG *bag = NULL; PKCS8_PRIV_KEY_INFO *p8 = NULL; /* Make a PKCS#8 structure */ if ((p8 = EVP_PKEY2PKCS8(key)) == NULL) goto err; if (key_usage && !PKCS8_add_keyusage(p8, key_usage)) goto err; if (nid_key != -1) { bag = PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(nid_key, pass, -1, NULL, 0, iter, p8, ctx, propq); PKCS8_PRIV_KEY_INFO_free(p8); } else bag = PKCS12_SAFEBAG_create0_p8inf(p8); if (!bag) goto err; if (!pkcs12_add_bag(pbags, bag)) goto err; return bag; err: PKCS12_SAFEBAG_free(bag); return NULL; } PKCS12_SAFEBAG *PKCS12_add_key(STACK_OF(PKCS12_SAFEBAG) **pbags, EVP_PKEY *key, int key_usage, int iter, int nid_key, const char *pass) { return PKCS12_add_key_ex(pbags, key, key_usage, iter, nid_key, pass, NULL, NULL); } PKCS12_SAFEBAG *PKCS12_add_secret(STACK_OF(PKCS12_SAFEBAG) **pbags, int nid_type, const unsigned char *value, int len) { PKCS12_SAFEBAG *bag = NULL; /* Add secret, storing the value as an octet string */ if ((bag = PKCS12_SAFEBAG_create_secret(nid_type, V_ASN1_OCTET_STRING, value, len)) == NULL) goto err; if (!pkcs12_add_bag(pbags, bag)) goto err; return bag; err: PKCS12_SAFEBAG_free(bag); return NULL; } int PKCS12_add_safe_ex(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags, int nid_safe, int iter, const char *pass, OSSL_LIB_CTX *ctx, const char *propq) { PKCS7 *p7 = NULL; int free_safes = 0; if (*psafes == NULL) { *psafes = sk_PKCS7_new_null(); if (*psafes == NULL) return 0; free_safes = 1; } if (nid_safe == 0) #ifdef OPENSSL_NO_RC2 nid_safe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; #else nid_safe = NID_pbe_WithSHA1And40BitRC2_CBC; #endif if (nid_safe == -1) p7 = PKCS12_pack_p7data(bags); else p7 = PKCS12_pack_p7encdata_ex(nid_safe, pass, -1, NULL, 0, iter, bags, ctx, propq); if (p7 == NULL) goto err; if (!sk_PKCS7_push(*psafes, p7)) goto err; return 1; err: if (free_safes) { sk_PKCS7_free(*psafes); *psafes = NULL; } PKCS7_free(p7); return 0; } int PKCS12_add_safe(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags, int nid_safe, int iter, const char *pass) { return PKCS12_add_safe_ex(psafes, bags, nid_safe, iter, pass, NULL, NULL); } static int pkcs12_remove_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, PKCS12_SAFEBAG *bag) { PKCS12_SAFEBAG *tmp; if (pbags == NULL || bag == NULL) return 1; if ((tmp = sk_PKCS12_SAFEBAG_delete_ptr(*pbags, bag)) == NULL) return 0; PKCS12_SAFEBAG_free(tmp); return 1; } static int pkcs12_add_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, PKCS12_SAFEBAG *bag) { int free_bags = 0; if (pbags == NULL) return 1; if (*pbags == NULL) { *pbags = sk_PKCS12_SAFEBAG_new_null(); if (*pbags == NULL) return 0; free_bags = 1; } if (!sk_PKCS12_SAFEBAG_push(*pbags, bag)) { if (free_bags) { sk_PKCS12_SAFEBAG_free(*pbags); *pbags = NULL; } return 0; } return 1; } PKCS12 *PKCS12_add_safes_ex(STACK_OF(PKCS7) *safes, int nid_p7, OSSL_LIB_CTX *ctx, const char *propq) { PKCS12 *p12; if (nid_p7 <= 0) nid_p7 = NID_pkcs7_data; p12 = PKCS12_init_ex(nid_p7, ctx, propq); if (p12 == NULL) return NULL; if (!PKCS12_pack_authsafes(p12, safes)) { PKCS12_free(p12); return NULL; } return p12; } PKCS12 *PKCS12_add_safes(STACK_OF(PKCS7) *safes, int nid_p7) { return PKCS12_add_safes_ex(safes, nid_p7, NULL, NULL); }
./openssl/crypto/pkcs12/pk12err.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/pkcs12err.h> #include "crypto/pkcs12err.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA PKCS12_str_reasons[] = { {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_CALLBACK_FAILED), "callback failed"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_CANT_PACK_STRUCTURE), "can't pack structure"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_CONTENT_TYPE_NOT_DATA), "content type not data"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_DECODE_ERROR), "decode error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_ENCODE_ERROR), "encode error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_ENCRYPT_ERROR), "encrypt error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_ERROR_SETTING_ENCRYPTED_DATA_TYPE), "error setting encrypted data type"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_INVALID_NULL_ARGUMENT), "invalid null argument"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_INVALID_NULL_PKCS12_POINTER), "invalid null pkcs12 pointer"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_INVALID_TYPE), "invalid type"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_IV_GEN_ERROR), "iv gen error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_KEY_GEN_ERROR), "key gen error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_ABSENT), "mac absent"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_GENERATION_ERROR), "mac generation error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_SETUP_ERROR), "mac setup error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_STRING_SET_ERROR), "mac string set error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_VERIFY_FAILURE), "mac verify failure"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_PARSE_ERROR), "parse error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_PKCS12_CIPHERFINAL_ERROR), "pkcs12 cipherfinal error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_UNKNOWN_DIGEST_ALGORITHM), "unknown digest algorithm"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_UNSUPPORTED_PKCS12_MODE), "unsupported pkcs12 mode"}, {0, NULL} }; #endif int ossl_err_load_PKCS12_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(PKCS12_str_reasons[0].error) == NULL) ERR_load_strings_const(PKCS12_str_reasons); #endif return 1; }
./openssl/crypto/pkcs12/p12_decr.c
/* * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/pkcs12.h> #include <openssl/trace.h> /* * Encrypt/Decrypt a buffer based on password and algor, result in a * OPENSSL_malloc'ed buffer */ unsigned char *PKCS12_pbe_crypt_ex(const X509_ALGOR *algor, const char *pass, int passlen, const unsigned char *in, int inlen, unsigned char **data, int *datalen, int en_de, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char *out = NULL; int outlen, i; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); int max_out_len, mac_len = 0; if (ctx == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_EVP_LIB); goto err; } /* Process data */ if (!EVP_PBE_CipherInit_ex(algor->algorithm, pass, passlen, algor->parameter, ctx, en_de, libctx, propq)) goto err; /* * GOST algorithm specifics: * OMAC algorithm calculate and encrypt MAC of the encrypted objects * It's appended to encrypted text on encrypting * MAC should be processed on decrypting separately from plain text */ max_out_len = inlen + EVP_CIPHER_CTX_get_block_size(ctx); if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx)) & EVP_CIPH_FLAG_CIPHER_WITH_MAC) != 0) { if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, 0, &mac_len) < 0) { ERR_raise(ERR_LIB_PKCS12, ERR_R_INTERNAL_ERROR); goto err; } if (EVP_CIPHER_CTX_is_encrypting(ctx)) { max_out_len += mac_len; } else { if (inlen < mac_len) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_UNSUPPORTED_PKCS12_MODE); goto err; } inlen -= mac_len; if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, (int)mac_len, (unsigned char *)in+inlen) < 0) { ERR_raise(ERR_LIB_PKCS12, ERR_R_INTERNAL_ERROR); goto err; } } } if ((out = OPENSSL_malloc(max_out_len)) == NULL) goto err; if (!EVP_CipherUpdate(ctx, out, &i, in, inlen)) { OPENSSL_free(out); out = NULL; ERR_raise(ERR_LIB_PKCS12, ERR_R_EVP_LIB); goto err; } outlen = i; if (!EVP_CipherFinal_ex(ctx, out + i, &i)) { OPENSSL_free(out); out = NULL; ERR_raise_data(ERR_LIB_PKCS12, PKCS12_R_PKCS12_CIPHERFINAL_ERROR, passlen == 0 ? "empty password" : "maybe wrong password"); goto err; } outlen += i; if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx)) & EVP_CIPH_FLAG_CIPHER_WITH_MAC) != 0) { if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, (int)mac_len, out+outlen) < 0) { OPENSSL_free(out); out = NULL; ERR_raise(ERR_LIB_PKCS12, ERR_R_INTERNAL_ERROR); goto err; } outlen += mac_len; } } if (datalen) *datalen = outlen; if (data) *data = out; err: EVP_CIPHER_CTX_free(ctx); return out; } unsigned char *PKCS12_pbe_crypt(const X509_ALGOR *algor, const char *pass, int passlen, const unsigned char *in, int inlen, unsigned char **data, int *datalen, int en_de) { return PKCS12_pbe_crypt_ex(algor, pass, passlen, in, inlen, data, datalen, en_de, NULL, NULL); } /* * Decrypt an OCTET STRING and decode ASN1 structure if zbuf set zero buffer * after use. */ void *PKCS12_item_decrypt_d2i_ex(const X509_ALGOR *algor, const ASN1_ITEM *it, const char *pass, int passlen, const ASN1_OCTET_STRING *oct, int zbuf, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char *out = NULL; const unsigned char *p; void *ret; int outlen = 0; if (!PKCS12_pbe_crypt_ex(algor, pass, passlen, oct->data, oct->length, &out, &outlen, 0, libctx, propq)) return NULL; p = out; OSSL_TRACE_BEGIN(PKCS12_DECRYPT) { BIO_printf(trc_out, "\n"); BIO_dump(trc_out, out, outlen); BIO_printf(trc_out, "\n"); } OSSL_TRACE_END(PKCS12_DECRYPT); ret = ASN1_item_d2i(NULL, &p, outlen, it); if (zbuf) OPENSSL_cleanse(out, outlen); if (!ret) ERR_raise(ERR_LIB_PKCS12, PKCS12_R_DECODE_ERROR); OPENSSL_free(out); return ret; } void *PKCS12_item_decrypt_d2i(const X509_ALGOR *algor, const ASN1_ITEM *it, const char *pass, int passlen, const ASN1_OCTET_STRING *oct, int zbuf) { return PKCS12_item_decrypt_d2i_ex(algor, it, pass, passlen, oct, zbuf, NULL, NULL); } /* * Encode ASN1 structure and encrypt, return OCTET STRING if zbuf set zero * encoding. */ ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt_ex(X509_ALGOR *algor, const ASN1_ITEM *it, const char *pass, int passlen, void *obj, int zbuf, OSSL_LIB_CTX *ctx, const char *propq) { ASN1_OCTET_STRING *oct = NULL; unsigned char *in = NULL; int inlen; if ((oct = ASN1_OCTET_STRING_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } inlen = ASN1_item_i2d(obj, &in, it); if (!in) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ENCODE_ERROR); goto err; } if (!PKCS12_pbe_crypt_ex(algor, pass, passlen, in, inlen, &oct->data, &oct->length, 1, ctx, propq)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ENCRYPT_ERROR); OPENSSL_free(in); goto err; } if (zbuf) OPENSSL_cleanse(in, inlen); OPENSSL_free(in); return oct; err: ASN1_OCTET_STRING_free(oct); return NULL; } ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt(X509_ALGOR *algor, const ASN1_ITEM *it, const char *pass, int passlen, void *obj, int zbuf) { return PKCS12_item_i2d_encrypt_ex(algor, it, pass, passlen, obj, zbuf, NULL, NULL); }
./openssl/crypto/pkcs12/p12_crpt.c
/* * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/core.h> #include <openssl/core_names.h> #include "crypto/evp.h" #include <openssl/pkcs12.h> /* PKCS#12 PBE algorithms now in static table */ void PKCS12_PBE_add(void) { } int PKCS12_PBE_keyivgen_ex(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md, int en_de, OSSL_LIB_CTX *libctx, const char *propq) { PBEPARAM *pbe; int saltlen, iter, ret; unsigned char *salt; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char *piv = iv; if (cipher == NULL) return 0; /* Extract useful info from parameter */ pbe = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(PBEPARAM), param); if (pbe == NULL) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_DECODE_ERROR); return 0; } if (pbe->iter == NULL) iter = 1; else iter = ASN1_INTEGER_get(pbe->iter); salt = pbe->salt->data; saltlen = pbe->salt->length; if (!PKCS12_key_gen_utf8_ex(pass, passlen, salt, saltlen, PKCS12_KEY_ID, iter, EVP_CIPHER_get_key_length(cipher), key, md, libctx, propq)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_KEY_GEN_ERROR); PBEPARAM_free(pbe); return 0; } if (EVP_CIPHER_get_iv_length(cipher) > 0) { if (!PKCS12_key_gen_utf8_ex(pass, passlen, salt, saltlen, PKCS12_IV_ID, iter, EVP_CIPHER_get_iv_length(cipher), iv, md, libctx, propq)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_IV_GEN_ERROR); PBEPARAM_free(pbe); return 0; } } else { piv = NULL; } PBEPARAM_free(pbe); ret = EVP_CipherInit_ex(ctx, cipher, NULL, key, piv, en_de); OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH); OPENSSL_cleanse(iv, EVP_MAX_IV_LENGTH); return ret; } int PKCS12_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md, int en_de) { return PKCS12_PBE_keyivgen_ex(ctx, pass, passlen, param, cipher, md, en_de, NULL, NULL); }
./openssl/crypto/pkcs12/p12_key.c
/* * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/pkcs12.h> #include <openssl/bn.h> #include <openssl/trace.h> #include <openssl/kdf.h> #include <openssl/core_names.h> #include "internal/provider.h" int PKCS12_key_gen_asc_ex(const char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type, OSSL_LIB_CTX *ctx, const char *propq) { int ret; unsigned char *unipass; int uniplen; if (pass == NULL) { unipass = NULL; uniplen = 0; } else if (!OPENSSL_asc2uni(pass, passlen, &unipass, &uniplen)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_PKCS12_LIB); return 0; } ret = PKCS12_key_gen_uni_ex(unipass, uniplen, salt, saltlen, id, iter, n, out, md_type, ctx, propq); OPENSSL_clear_free(unipass, uniplen); return ret > 0; } int PKCS12_key_gen_asc(const char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type) { return PKCS12_key_gen_asc_ex(pass, passlen, salt, saltlen, id, iter, n, out, md_type, NULL, NULL); } int PKCS12_key_gen_utf8_ex(const char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type, OSSL_LIB_CTX *ctx, const char *propq) { int ret; unsigned char *unipass; int uniplen; if (pass == NULL) { unipass = NULL; uniplen = 0; } else if (!OPENSSL_utf82uni(pass, passlen, &unipass, &uniplen)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_PKCS12_LIB); return 0; } ret = PKCS12_key_gen_uni_ex(unipass, uniplen, salt, saltlen, id, iter, n, out, md_type, ctx, propq); OPENSSL_clear_free(unipass, uniplen); return ret > 0; } int PKCS12_key_gen_utf8(const char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type) { return PKCS12_key_gen_utf8_ex(pass, passlen, salt, saltlen, id, iter, n, out, md_type, NULL, NULL); } int PKCS12_key_gen_uni_ex(unsigned char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type, OSSL_LIB_CTX *libctx, const char *propq) { int res = 0; EVP_KDF *kdf; EVP_KDF_CTX *ctx; OSSL_PARAM params[6], *p = params; if (n <= 0) return 0; kdf = EVP_KDF_fetch(libctx, "PKCS12KDF", propq); if (kdf == NULL) return 0; ctx = EVP_KDF_CTX_new(kdf); EVP_KDF_free(kdf); if (ctx == NULL) return 0; *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, (char *)EVP_MD_get0_name(md_type), 0); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, pass, passlen); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, salt, saltlen); *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_PKCS12_ID, &id); *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_ITER, &iter); *p = OSSL_PARAM_construct_end(); OSSL_TRACE_BEGIN(PKCS12_KEYGEN) { BIO_printf(trc_out, "PKCS12_key_gen_uni_ex(): ID %d, ITER %d\n", id, iter); BIO_printf(trc_out, "Password (length %d):\n", passlen); BIO_hex_string(trc_out, 0, passlen, pass, passlen); BIO_printf(trc_out, "\n"); BIO_printf(trc_out, "Salt (length %d):\n", saltlen); BIO_hex_string(trc_out, 0, saltlen, salt, saltlen); BIO_printf(trc_out, "\n"); } OSSL_TRACE_END(PKCS12_KEYGEN); if (EVP_KDF_derive(ctx, out, (size_t)n, params)) { res = 1; OSSL_TRACE_BEGIN(PKCS12_KEYGEN) { BIO_printf(trc_out, "Output KEY (length %d)\n", n); BIO_hex_string(trc_out, 0, n, out, n); BIO_printf(trc_out, "\n"); } OSSL_TRACE_END(PKCS12_KEYGEN); } EVP_KDF_CTX_free(ctx); return res; } int PKCS12_key_gen_uni(unsigned char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type) { return PKCS12_key_gen_uni_ex(pass, passlen, salt, saltlen, id, iter, n, out, md_type, NULL, NULL); }
./openssl/crypto/pkcs12/p12_p8e.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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/core.h> #include <openssl/pkcs12.h> #include "crypto/x509.h" X509_SIG *PKCS8_encrypt_ex(int pbe_nid, const EVP_CIPHER *cipher, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *libctx, const char *propq) { X509_SIG *p8 = NULL; X509_ALGOR *pbe; if (pbe_nid == -1) { if (cipher == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_PASSED_NULL_PARAMETER); return NULL; } pbe = PKCS5_pbe2_set_iv_ex(cipher, iter, salt, saltlen, NULL, -1, libctx); } else { ERR_set_mark(); if (EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0)) { ERR_clear_last_mark(); if (cipher == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_PASSED_NULL_PARAMETER); return NULL; } pbe = PKCS5_pbe2_set_iv_ex(cipher, iter, salt, saltlen, NULL, pbe_nid, libctx); } else { ERR_pop_to_mark(); pbe = PKCS5_pbe_set_ex(pbe_nid, iter, salt, saltlen, libctx); } } if (pbe == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } p8 = PKCS8_set0_pbe_ex(pass, passlen, p8inf, pbe, libctx, propq); if (p8 == NULL) { X509_ALGOR_free(pbe); return NULL; } return p8; } X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8inf) { return PKCS8_encrypt_ex(pbe_nid, cipher, pass, passlen, salt, saltlen, iter, p8inf, NULL, NULL); } X509_SIG *PKCS8_set0_pbe_ex(const char *pass, int passlen, PKCS8_PRIV_KEY_INFO *p8inf, X509_ALGOR *pbe, OSSL_LIB_CTX *ctx, const char *propq) { X509_SIG *p8; ASN1_OCTET_STRING *enckey; enckey = PKCS12_item_i2d_encrypt_ex(pbe, ASN1_ITEM_rptr(PKCS8_PRIV_KEY_INFO), pass, passlen, p8inf, 1, ctx, propq); if (!enckey) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ENCRYPT_ERROR); return NULL; } p8 = OPENSSL_zalloc(sizeof(*p8)); if (p8 == NULL) { ASN1_OCTET_STRING_free(enckey); return NULL; } p8->algor = pbe; p8->digest = enckey; return p8; } X509_SIG *PKCS8_set0_pbe(const char *pass, int passlen, PKCS8_PRIV_KEY_INFO *p8inf, X509_ALGOR *pbe) { return PKCS8_set0_pbe_ex(pass, passlen, p8inf, pbe, NULL, NULL); }
./openssl/crypto/pkcs12/p12_local.h
/* * Copyright 2016-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 */ struct PKCS12_MAC_DATA_st { X509_SIG *dinfo; ASN1_OCTET_STRING *salt; ASN1_INTEGER *iter; /* defaults to 1 */ }; struct PKCS12_st { ASN1_INTEGER *version; PKCS12_MAC_DATA *mac; PKCS7 *authsafes; }; struct PKCS12_SAFEBAG_st { ASN1_OBJECT *type; union { struct pkcs12_bag_st *bag; /* secret, crl and certbag */ struct pkcs8_priv_key_info_st *keybag; /* keybag */ X509_SIG *shkeybag; /* shrouded key bag */ STACK_OF(PKCS12_SAFEBAG) *safes; ASN1_TYPE *other; } value; STACK_OF(X509_ATTRIBUTE) *attrib; }; struct pkcs12_bag_st { ASN1_OBJECT *type; union { ASN1_OCTET_STRING *x509cert; ASN1_OCTET_STRING *x509crl; ASN1_OCTET_STRING *octet; ASN1_IA5STRING *sdsicert; ASN1_TYPE *other; /* Secret or other bag */ } value; }; const PKCS7_CTX *ossl_pkcs12_get0_pkcs7ctx(const PKCS12 *p12);
./openssl/crypto/pkcs12/p12_sbag.c
/* * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/pkcs12.h> #include "p12_local.h" #include "crypto/x509.h" #ifndef OPENSSL_NO_DEPRECATED_1_1_0 ASN1_TYPE *PKCS12_get_attr(const PKCS12_SAFEBAG *bag, int attr_nid) { return PKCS12_get_attr_gen(bag->attrib, attr_nid); } #endif const ASN1_TYPE *PKCS12_SAFEBAG_get0_attr(const PKCS12_SAFEBAG *bag, int attr_nid) { return PKCS12_get_attr_gen(bag->attrib, attr_nid); } ASN1_TYPE *PKCS8_get_attr(PKCS8_PRIV_KEY_INFO *p8, int attr_nid) { return PKCS12_get_attr_gen(PKCS8_pkey_get0_attrs(p8), attr_nid); } const PKCS8_PRIV_KEY_INFO *PKCS12_SAFEBAG_get0_p8inf(const PKCS12_SAFEBAG *bag) { if (PKCS12_SAFEBAG_get_nid(bag) != NID_keyBag) return NULL; return bag->value.keybag; } const X509_SIG *PKCS12_SAFEBAG_get0_pkcs8(const PKCS12_SAFEBAG *bag) { if (OBJ_obj2nid(bag->type) != NID_pkcs8ShroudedKeyBag) return NULL; return bag->value.shkeybag; } const STACK_OF(PKCS12_SAFEBAG) * PKCS12_SAFEBAG_get0_safes(const PKCS12_SAFEBAG *bag) { if (OBJ_obj2nid(bag->type) != NID_safeContentsBag) return NULL; return bag->value.safes; } const ASN1_OBJECT *PKCS12_SAFEBAG_get0_type(const PKCS12_SAFEBAG *bag) { return bag->type; } int PKCS12_SAFEBAG_get_nid(const PKCS12_SAFEBAG *bag) { return OBJ_obj2nid(bag->type); } int PKCS12_SAFEBAG_get_bag_nid(const PKCS12_SAFEBAG *bag) { int btype = PKCS12_SAFEBAG_get_nid(bag); if (btype != NID_certBag && btype != NID_crlBag && btype != NID_secretBag) return -1; return OBJ_obj2nid(bag->value.bag->type); } const ASN1_OBJECT *PKCS12_SAFEBAG_get0_bag_type(const PKCS12_SAFEBAG *bag) { return bag->value.bag->type; } const ASN1_TYPE *PKCS12_SAFEBAG_get0_bag_obj(const PKCS12_SAFEBAG *bag) { return bag->value.bag->value.other; } X509 *PKCS12_SAFEBAG_get1_cert(const PKCS12_SAFEBAG *bag) { if (PKCS12_SAFEBAG_get_nid(bag) != NID_certBag) return NULL; if (OBJ_obj2nid(bag->value.bag->type) != NID_x509Certificate) return NULL; return ASN1_item_unpack(bag->value.bag->value.octet, ASN1_ITEM_rptr(X509)); } X509_CRL *PKCS12_SAFEBAG_get1_crl(const PKCS12_SAFEBAG *bag) { if (PKCS12_SAFEBAG_get_nid(bag) != NID_crlBag) return NULL; if (OBJ_obj2nid(bag->value.bag->type) != NID_x509Crl) return NULL; return ASN1_item_unpack(bag->value.bag->value.octet, ASN1_ITEM_rptr(X509_CRL)); } X509 *PKCS12_SAFEBAG_get1_cert_ex(const PKCS12_SAFEBAG *bag, OSSL_LIB_CTX *libctx, const char *propq) { X509 *ret = NULL; if (PKCS12_SAFEBAG_get_nid(bag) != NID_certBag) return NULL; if (OBJ_obj2nid(bag->value.bag->type) != NID_x509Certificate) return NULL; ret = ASN1_item_unpack_ex(bag->value.bag->value.octet, ASN1_ITEM_rptr(X509), libctx, propq); if (!ossl_x509_set0_libctx(ret, libctx, propq)) { X509_free(ret); return NULL; } return ret; } X509_CRL *PKCS12_SAFEBAG_get1_crl_ex(const PKCS12_SAFEBAG *bag, OSSL_LIB_CTX *libctx, const char *propq) { X509_CRL *ret = NULL; if (PKCS12_SAFEBAG_get_nid(bag) != NID_crlBag) return NULL; if (OBJ_obj2nid(bag->value.bag->type) != NID_x509Crl) return NULL; ret = ASN1_item_unpack_ex(bag->value.bag->value.octet, ASN1_ITEM_rptr(X509_CRL), libctx, propq); if (!ossl_x509_crl_set0_libctx(ret, libctx, propq)) { X509_CRL_free(ret); return NULL; } return ret; } PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_cert(X509 *x509) { return PKCS12_item_pack_safebag(x509, ASN1_ITEM_rptr(X509), NID_x509Certificate, NID_certBag); } PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_crl(X509_CRL *crl) { return PKCS12_item_pack_safebag(crl, ASN1_ITEM_rptr(X509_CRL), NID_x509Crl, NID_crlBag); } PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_secret(int type, int vtype, const unsigned char *value, int len) { PKCS12_BAGS *bag; PKCS12_SAFEBAG *safebag; if ((bag = PKCS12_BAGS_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } bag->type = OBJ_nid2obj(type); switch (vtype) { case V_ASN1_OCTET_STRING: { ASN1_OCTET_STRING *strtmp = ASN1_OCTET_STRING_new(); if (strtmp == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } /* Pack data into an octet string */ if (!ASN1_OCTET_STRING_set(strtmp, value, len)) { ASN1_OCTET_STRING_free(strtmp); ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ENCODE_ERROR); goto err; } bag->value.other = ASN1_TYPE_new(); if (bag->value.other == NULL) { ASN1_OCTET_STRING_free(strtmp); ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } ASN1_TYPE_set(bag->value.other, vtype, strtmp); } break; default: ERR_raise(ERR_LIB_PKCS12, PKCS12_R_INVALID_TYPE); goto err; } if ((safebag = PKCS12_SAFEBAG_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } safebag->value.bag = bag; safebag->type = OBJ_nid2obj(NID_secretBag); return safebag; err: PKCS12_BAGS_free(bag); return NULL; } /* Turn PKCS8 object into a keybag */ PKCS12_SAFEBAG *PKCS12_SAFEBAG_create0_p8inf(PKCS8_PRIV_KEY_INFO *p8) { PKCS12_SAFEBAG *bag = PKCS12_SAFEBAG_new(); if (bag == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } bag->type = OBJ_nid2obj(NID_keyBag); bag->value.keybag = p8; return bag; } /* Turn PKCS8 object into a shrouded keybag */ PKCS12_SAFEBAG *PKCS12_SAFEBAG_create0_pkcs8(X509_SIG *p8) { PKCS12_SAFEBAG *bag = PKCS12_SAFEBAG_new(); /* Set up the safe bag */ if (bag == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } bag->type = OBJ_nid2obj(NID_pkcs8ShroudedKeyBag); bag->value.shkeybag = p8; return bag; } PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(int pbe_nid, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *ctx, const char *propq) { PKCS12_SAFEBAG *bag = NULL; const EVP_CIPHER *pbe_ciph = NULL; EVP_CIPHER *pbe_ciph_fetch = NULL; X509_SIG *p8; ERR_set_mark(); pbe_ciph = pbe_ciph_fetch = EVP_CIPHER_fetch(ctx, OBJ_nid2sn(pbe_nid), propq); if (pbe_ciph == NULL) pbe_ciph = EVP_get_cipherbynid(pbe_nid); ERR_pop_to_mark(); if (pbe_ciph != NULL) pbe_nid = -1; p8 = PKCS8_encrypt_ex(pbe_nid, pbe_ciph, pass, passlen, salt, saltlen, iter, p8inf, ctx, propq); if (p8 == NULL) goto err; bag = PKCS12_SAFEBAG_create0_pkcs8(p8); if (bag == NULL) X509_SIG_free(p8); err: EVP_CIPHER_free(pbe_ciph_fetch); return bag; } PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_pkcs8_encrypt(int pbe_nid, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8inf) { return PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(pbe_nid, pass, passlen, salt, saltlen, iter, p8inf, NULL, NULL); }
./openssl/crypto/pkcs12/p12_attr.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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/pkcs12.h> #include "p12_local.h" /* Add a local keyid to a safebag */ int PKCS12_add_localkeyid(PKCS12_SAFEBAG *bag, unsigned char *name, int namelen) { if (X509at_add1_attr_by_NID(&bag->attrib, NID_localKeyID, V_ASN1_OCTET_STRING, name, namelen) != NULL) return 1; else return 0; } /* Add key usage to PKCS#8 structure */ int PKCS8_add_keyusage(PKCS8_PRIV_KEY_INFO *p8, int usage) { unsigned char us_val = (unsigned char)usage; return PKCS8_pkey_add1_attr_by_NID(p8, NID_key_usage, V_ASN1_BIT_STRING, &us_val, 1); } /* Add a friendlyname to a safebag */ int PKCS12_add_friendlyname_asc(PKCS12_SAFEBAG *bag, const char *name, int namelen) { if (X509at_add1_attr_by_NID(&bag->attrib, NID_friendlyName, MBSTRING_ASC, (unsigned char *)name, namelen) != NULL) return 1; else return 0; } int PKCS12_add_friendlyname_utf8(PKCS12_SAFEBAG *bag, const char *name, int namelen) { if (X509at_add1_attr_by_NID(&bag->attrib, NID_friendlyName, MBSTRING_UTF8, (unsigned char *)name, namelen) != NULL) return 1; else return 0; } int PKCS12_add_friendlyname_uni(PKCS12_SAFEBAG *bag, const unsigned char *name, int namelen) { if (X509at_add1_attr_by_NID(&bag->attrib, NID_friendlyName, MBSTRING_BMP, name, namelen) != NULL) return 1; else return 0; } int PKCS12_add_CSPName_asc(PKCS12_SAFEBAG *bag, const char *name, int namelen) { if (X509at_add1_attr_by_NID(&bag->attrib, NID_ms_csp_name, MBSTRING_ASC, (unsigned char *)name, namelen) != NULL) return 1; else return 0; } int PKCS12_add1_attr_by_NID(PKCS12_SAFEBAG *bag, int nid, int type, const unsigned char *bytes, int len) { if (X509at_add1_attr_by_NID(&bag->attrib, nid, type, bytes, len) != NULL) return 1; else return 0; } int PKCS12_add1_attr_by_txt(PKCS12_SAFEBAG *bag, const char *attrname, int type, const unsigned char *bytes, int len) { if (X509at_add1_attr_by_txt(&bag->attrib, attrname, type, bytes, len) != NULL) return 1; else return 0; } ASN1_TYPE *PKCS12_get_attr_gen(const STACK_OF(X509_ATTRIBUTE) *attrs, int attr_nid) { int i = X509at_get_attr_by_NID(attrs, attr_nid, -1); if (i < 0) return NULL; return X509_ATTRIBUTE_get0_type(X509at_get_attr(attrs, i), 0); } char *PKCS12_get_friendlyname(PKCS12_SAFEBAG *bag) { const ASN1_TYPE *atype; if ((atype = PKCS12_SAFEBAG_get0_attr(bag, NID_friendlyName)) == NULL) return NULL; if (atype->type != V_ASN1_BMPSTRING) return NULL; return OPENSSL_uni2utf8(atype->value.bmpstring->data, atype->value.bmpstring->length); } const STACK_OF(X509_ATTRIBUTE) * PKCS12_SAFEBAG_get0_attrs(const PKCS12_SAFEBAG *bag) { return bag->attrib; } void PKCS12_SAFEBAG_set0_attrs(PKCS12_SAFEBAG *bag, STACK_OF(X509_ATTRIBUTE) *attrs) { if (bag->attrib != attrs) sk_X509_ATTRIBUTE_free(bag->attrib); bag->attrib = attrs; }
./openssl/crypto/pkcs12/p12_init.c
/* * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/pkcs12.h> #include "crypto/pkcs7.h" #include "p12_local.h" /* Initialise a PKCS12 structure to take data */ PKCS12 *PKCS12_init_ex(int mode, OSSL_LIB_CTX *ctx, const char *propq) { PKCS12 *pkcs12; if ((pkcs12 = PKCS12_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } if (!ASN1_INTEGER_set(pkcs12->version, 3)) goto err; pkcs12->authsafes->type = OBJ_nid2obj(mode); ossl_pkcs7_set0_libctx(pkcs12->authsafes, ctx); if (!ossl_pkcs7_set1_propq(pkcs12->authsafes, propq)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_PKCS7_LIB); goto err; } switch (mode) { case NID_pkcs7_data: if ((pkcs12->authsafes->d.data = ASN1_OCTET_STRING_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } break; default: ERR_raise(ERR_LIB_PKCS12, PKCS12_R_UNSUPPORTED_PKCS12_MODE); goto err; } return pkcs12; err: PKCS12_free(pkcs12); return NULL; } PKCS12 *PKCS12_init(int mode) { return PKCS12_init_ex(mode, NULL, NULL); } const PKCS7_CTX *ossl_pkcs12_get0_pkcs7ctx(const PKCS12 *p12) { if (p12 == NULL || p12->authsafes == NULL) return NULL; return &p12->authsafes->ctx; }
./openssl/crypto/pkcs12/p12_npas.c
/* * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/pkcs12.h> #include "p12_local.h" /* PKCS#12 password change routine */ static int newpass_p12(PKCS12 *p12, const char *oldpass, const char *newpass); static int newpass_bags(STACK_OF(PKCS12_SAFEBAG) *bags, const char *oldpass, const char *newpass, OSSL_LIB_CTX *libctx, const char *propq); static int newpass_bag(PKCS12_SAFEBAG *bag, const char *oldpass, const char *newpass, OSSL_LIB_CTX *libctx, const char *propq); static int alg_get(const X509_ALGOR *alg, int *pnid, int *piter, int *psaltlen, int *cipherid); /* * Change the password on a PKCS#12 structure. */ int PKCS12_newpass(PKCS12 *p12, const char *oldpass, const char *newpass) { /* Check for NULL PKCS12 structure */ if (p12 == NULL) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_INVALID_NULL_PKCS12_POINTER); return 0; } /* Check the mac */ if (p12->mac != NULL) { if (!PKCS12_verify_mac(p12, oldpass, -1)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_VERIFY_FAILURE); return 0; } } if (!newpass_p12(p12, oldpass, newpass)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_PARSE_ERROR); return 0; } return 1; } /* Parse the outer PKCS#12 structure */ static int newpass_p12(PKCS12 *p12, const char *oldpass, const char *newpass) { STACK_OF(PKCS7) *asafes = NULL, *newsafes = NULL; STACK_OF(PKCS12_SAFEBAG) *bags = NULL; int i, bagnid, pbe_nid = 0, pbe_iter = 0, pbe_saltlen = 0, cipherid = NID_undef; PKCS7 *p7, *p7new; ASN1_OCTET_STRING *p12_data_tmp = NULL, *macoct = NULL; unsigned char mac[EVP_MAX_MD_SIZE]; unsigned int maclen; int rv = 0; if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL) goto err; if ((newsafes = sk_PKCS7_new_null()) == NULL) goto err; for (i = 0; i < sk_PKCS7_num(asafes); i++) { p7 = sk_PKCS7_value(asafes, i); bagnid = OBJ_obj2nid(p7->type); if (bagnid == NID_pkcs7_data) { bags = PKCS12_unpack_p7data(p7); } else if (bagnid == NID_pkcs7_encrypted) { bags = PKCS12_unpack_p7encdata(p7, oldpass, -1); if (!alg_get(p7->d.encrypted->enc_data->algorithm, &pbe_nid, &pbe_iter, &pbe_saltlen, &cipherid)) goto err; } else { continue; } if (bags == NULL) goto err; if (!newpass_bags(bags, oldpass, newpass, p7->ctx.libctx, p7->ctx.propq)) goto err; /* Repack bag in same form with new password */ if (bagnid == NID_pkcs7_data) p7new = PKCS12_pack_p7data(bags); else p7new = PKCS12_pack_p7encdata_ex(pbe_nid, newpass, -1, NULL, pbe_saltlen, pbe_iter, bags, p7->ctx.libctx, p7->ctx.propq); if (p7new == NULL || !sk_PKCS7_push(newsafes, p7new)) goto err; sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); bags = NULL; } /* Repack safe: save old safe in case of error */ p12_data_tmp = p12->authsafes->d.data; if ((p12->authsafes->d.data = ASN1_OCTET_STRING_new()) == NULL) goto err; if (!PKCS12_pack_authsafes(p12, newsafes)) goto err; if (p12->mac != NULL) { if (!PKCS12_gen_mac(p12, newpass, -1, mac, &maclen)) goto err; X509_SIG_getm(p12->mac->dinfo, NULL, &macoct); if (!ASN1_OCTET_STRING_set(macoct, mac, maclen)) goto err; } rv = 1; err: /* Restore old safe if necessary */ if (rv == 1) { ASN1_OCTET_STRING_free(p12_data_tmp); } else if (p12_data_tmp != NULL) { ASN1_OCTET_STRING_free(p12->authsafes->d.data); p12->authsafes->d.data = p12_data_tmp; } sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); sk_PKCS7_pop_free(asafes, PKCS7_free); sk_PKCS7_pop_free(newsafes, PKCS7_free); return rv; } static int newpass_bags(STACK_OF(PKCS12_SAFEBAG) *bags, const char *oldpass, const char *newpass, OSSL_LIB_CTX *libctx, const char *propq) { int i; for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) { if (!newpass_bag(sk_PKCS12_SAFEBAG_value(bags, i), oldpass, newpass, libctx, propq)) return 0; } return 1; } /* Change password of safebag: only needs handle shrouded keybags */ static int newpass_bag(PKCS12_SAFEBAG *bag, const char *oldpass, const char *newpass, OSSL_LIB_CTX *libctx, const char *propq) { EVP_CIPHER *cipher = NULL; PKCS8_PRIV_KEY_INFO *p8; X509_SIG *p8new; int p8_nid, p8_saltlen, p8_iter, cipherid = 0; const X509_ALGOR *shalg; if (PKCS12_SAFEBAG_get_nid(bag) != NID_pkcs8ShroudedKeyBag) return 1; if ((p8 = PKCS8_decrypt_ex(bag->value.shkeybag, oldpass, -1, libctx, propq)) == NULL) return 0; X509_SIG_get0(bag->value.shkeybag, &shalg, NULL); if (!alg_get(shalg, &p8_nid, &p8_iter, &p8_saltlen, &cipherid)) { PKCS8_PRIV_KEY_INFO_free(p8); return 0; } if (cipherid != NID_undef) { cipher = EVP_CIPHER_fetch(libctx, OBJ_nid2sn(cipherid), propq); if (cipher == NULL) { PKCS8_PRIV_KEY_INFO_free(p8); return 0; } } p8new = PKCS8_encrypt_ex(p8_nid, cipher, newpass, -1, NULL, p8_saltlen, p8_iter, p8, libctx, propq); PKCS8_PRIV_KEY_INFO_free(p8); EVP_CIPHER_free(cipher); if (p8new == NULL) return 0; X509_SIG_free(bag->value.shkeybag); bag->value.shkeybag = p8new; return 1; } static int alg_get(const X509_ALGOR *alg, int *pnid, int *piter, int *psaltlen, int *cipherid) { int ret = 0, pbenid, aparamtype; int encnid, prfnid; const ASN1_OBJECT *aoid; const void *aparam; PBEPARAM *pbe = NULL; PBE2PARAM *pbe2 = NULL; PBKDF2PARAM *kdf = NULL; X509_ALGOR_get0(&aoid, &aparamtype, &aparam, alg); pbenid = OBJ_obj2nid(aoid); switch (pbenid) { case NID_pbes2: if (aparamtype == V_ASN1_SEQUENCE) pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM)); if (pbe2 == NULL) goto done; X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc); pbenid = OBJ_obj2nid(aoid); X509_ALGOR_get0(&aoid, NULL, NULL, pbe2->encryption); encnid = OBJ_obj2nid(aoid); if (aparamtype == V_ASN1_SEQUENCE) kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM)); if (kdf == NULL) goto done; /* Only OCTET_STRING is supported */ if (kdf->salt->type != V_ASN1_OCTET_STRING) goto done; if (kdf->prf == NULL) { prfnid = NID_hmacWithSHA1; } else { X509_ALGOR_get0(&aoid, NULL, NULL, kdf->prf); prfnid = OBJ_obj2nid(aoid); } *psaltlen = kdf->salt->value.octet_string->length; *piter = ASN1_INTEGER_get(kdf->iter); *pnid = prfnid; *cipherid = encnid; break; default: pbe = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(PBEPARAM), alg->parameter); if (pbe == NULL) goto done; *pnid = OBJ_obj2nid(alg->algorithm); *piter = ASN1_INTEGER_get(pbe->iter); *psaltlen = pbe->salt->length; *cipherid = NID_undef; ret = 1; break; } ret = 1; done: if (kdf != NULL) PBKDF2PARAM_free(kdf); if (pbe2 != NULL) PBE2PARAM_free(pbe2); if (pbe != NULL) PBEPARAM_free(pbe); return ret; }
./openssl/crypto/pkcs12/p12_p8d.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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/pkcs12.h> PKCS8_PRIV_KEY_INFO *PKCS8_decrypt_ex(const X509_SIG *p8, const char *pass, int passlen, OSSL_LIB_CTX *ctx, const char *propq) { const X509_ALGOR *dalg; const ASN1_OCTET_STRING *doct; X509_SIG_get0(p8, &dalg, &doct); return PKCS12_item_decrypt_d2i_ex(dalg, ASN1_ITEM_rptr(PKCS8_PRIV_KEY_INFO), pass, passlen, doct, 1, ctx, propq); } PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(const X509_SIG *p8, const char *pass, int passlen) { return PKCS8_decrypt_ex(p8, pass, passlen, NULL, NULL); }
./openssl/crypto/pkcs12/p12_kiss.c
/* * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/pkcs12.h> #include "crypto/x509.h" /* for ossl_x509_add_cert_new() */ /* Simplified PKCS#12 routines */ static int parse_pk12(PKCS12 *p12, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts); static int parse_bags(const STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts, OSSL_LIB_CTX *libctx, const char *propq); static int parse_bag(PKCS12_SAFEBAG *bag, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts, OSSL_LIB_CTX *libctx, const char *propq); /* * Parse and decrypt a PKCS#12 structure returning user key, user cert and * other (CA) certs. Note either ca should be NULL, *ca should be NULL, or it * should point to a valid STACK structure. pkey and/or cert may be NULL; * if non-NULL the variables they point to can be passed uninitialised. */ int PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca) { STACK_OF(X509) *ocerts = NULL; X509 *x = NULL; if (pkey != NULL) *pkey = NULL; if (cert != NULL) *cert = NULL; /* Check for NULL PKCS12 structure */ if (p12 == NULL) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_INVALID_NULL_PKCS12_POINTER); return 0; } /* Check the mac */ if (PKCS12_mac_present(p12)) { /* * If password is zero length or NULL then try verifying both cases to * determine which password is correct. The reason for this is that under * PKCS#12 password based encryption no password and a zero length * password are two different things... */ if (pass == NULL || *pass == '\0') { if (PKCS12_verify_mac(p12, NULL, 0)) pass = NULL; else if (PKCS12_verify_mac(p12, "", 0)) pass = ""; else { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_VERIFY_FAILURE); goto err; } } else if (!PKCS12_verify_mac(p12, pass, -1)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_VERIFY_FAILURE); goto err; } } else if (pass == NULL || *pass == '\0') { pass = NULL; } /* If needed, allocate stack for other certificates */ if ((cert != NULL || ca != NULL) && (ocerts = sk_X509_new_null()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_CRYPTO_LIB); goto err; } if (!parse_pk12(p12, pass, -1, pkey, ocerts)) { int err = ERR_peek_last_error(); if (ERR_GET_LIB(err) != ERR_LIB_EVP && ERR_GET_REASON(err) != EVP_R_UNSUPPORTED_ALGORITHM) ERR_raise(ERR_LIB_PKCS12, PKCS12_R_PARSE_ERROR); goto err; } /* Split the certs in ocerts over *cert and *ca as far as requested */ while ((x = sk_X509_shift(ocerts)) != NULL) { if (pkey != NULL && *pkey != NULL && cert != NULL && *cert == NULL) { int match; ERR_set_mark(); match = X509_check_private_key(x, *pkey); ERR_pop_to_mark(); if (match) { *cert = x; continue; } } if (ca != NULL) { if (!ossl_x509_add_cert_new(ca, x, X509_ADD_FLAG_DEFAULT)) goto err; continue; } X509_free(x); } sk_X509_free(ocerts); return 1; err: if (pkey != NULL) { EVP_PKEY_free(*pkey); *pkey = NULL; } if (cert != NULL) { X509_free(*cert); *cert = NULL; } X509_free(x); OSSL_STACK_OF_X509_free(ocerts); return 0; } /* Parse the outer PKCS#12 structure */ /* pkey and/or ocerts may be NULL */ static int parse_pk12(PKCS12 *p12, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts) { STACK_OF(PKCS7) *asafes; STACK_OF(PKCS12_SAFEBAG) *bags; int i, bagnid; PKCS7 *p7; if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL) return 0; for (i = 0; i < sk_PKCS7_num(asafes); i++) { p7 = sk_PKCS7_value(asafes, i); bagnid = OBJ_obj2nid(p7->type); if (bagnid == NID_pkcs7_data) { bags = PKCS12_unpack_p7data(p7); } else if (bagnid == NID_pkcs7_encrypted) { bags = PKCS12_unpack_p7encdata(p7, pass, passlen); } else continue; if (!bags) { sk_PKCS7_pop_free(asafes, PKCS7_free); return 0; } if (!parse_bags(bags, pass, passlen, pkey, ocerts, p7->ctx.libctx, p7->ctx.propq)) { sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); sk_PKCS7_pop_free(asafes, PKCS7_free); return 0; } sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); } sk_PKCS7_pop_free(asafes, PKCS7_free); return 1; } /* pkey and/or ocerts may be NULL */ static int parse_bags(const STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts, OSSL_LIB_CTX *libctx, const char *propq) { int i; for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) { if (!parse_bag(sk_PKCS12_SAFEBAG_value(bags, i), pass, passlen, pkey, ocerts, libctx, propq)) return 0; } return 1; } /* pkey and/or ocerts may be NULL */ static int parse_bag(PKCS12_SAFEBAG *bag, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts, OSSL_LIB_CTX *libctx, const char *propq) { PKCS8_PRIV_KEY_INFO *p8; X509 *x509; const ASN1_TYPE *attrib; ASN1_BMPSTRING *fname = NULL; ASN1_OCTET_STRING *lkid = NULL; if ((attrib = PKCS12_SAFEBAG_get0_attr(bag, NID_friendlyName))) fname = attrib->value.bmpstring; if ((attrib = PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID))) lkid = attrib->value.octet_string; switch (PKCS12_SAFEBAG_get_nid(bag)) { case NID_keyBag: if (pkey == NULL || *pkey != NULL) return 1; *pkey = EVP_PKCS82PKEY_ex(PKCS12_SAFEBAG_get0_p8inf(bag), libctx, propq); if (*pkey == NULL) return 0; break; case NID_pkcs8ShroudedKeyBag: if (pkey == NULL || *pkey != NULL) return 1; if ((p8 = PKCS12_decrypt_skey_ex(bag, pass, passlen, libctx, propq)) == NULL) return 0; *pkey = EVP_PKCS82PKEY_ex(p8, libctx, propq); PKCS8_PRIV_KEY_INFO_free(p8); if (!(*pkey)) return 0; break; case NID_certBag: if (ocerts == NULL || PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate) return 1; if ((x509 = PKCS12_SAFEBAG_get1_cert_ex(bag, libctx, propq)) == NULL) return 0; if (lkid && !X509_keyid_set1(x509, lkid->data, lkid->length)) { X509_free(x509); return 0; } if (fname) { int len, r; unsigned char *data; len = ASN1_STRING_to_UTF8(&data, fname); if (len >= 0) { r = X509_alias_set1(x509, data, len); OPENSSL_free(data); if (!r) { X509_free(x509); return 0; } } } if (!sk_X509_push(ocerts, x509)) { X509_free(x509); return 0; } break; case NID_safeContentsBag: return parse_bags(PKCS12_SAFEBAG_get0_safes(bag), pass, passlen, pkey, ocerts, libctx, propq); default: return 1; } return 1; }
./openssl/crypto/pkcs12/p12_mutl.c
/* * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * HMAC 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/crypto.h> #include <openssl/hmac.h> #include <openssl/rand.h> #include <openssl/pkcs12.h> #include "p12_local.h" int PKCS12_mac_present(const PKCS12 *p12) { return p12->mac ? 1 : 0; } void PKCS12_get0_mac(const ASN1_OCTET_STRING **pmac, const X509_ALGOR **pmacalg, const ASN1_OCTET_STRING **psalt, const ASN1_INTEGER **piter, const PKCS12 *p12) { if (p12->mac) { X509_SIG_get0(p12->mac->dinfo, pmacalg, pmac); if (psalt) *psalt = p12->mac->salt; if (piter) *piter = p12->mac->iter; } else { if (pmac) *pmac = NULL; if (pmacalg) *pmacalg = NULL; if (psalt) *psalt = NULL; if (piter) *piter = NULL; } } #define TK26_MAC_KEY_LEN 32 static int pkcs12_gen_gost_mac_key(const char *pass, int passlen, const unsigned char *salt, int saltlen, int iter, int keylen, unsigned char *key, const EVP_MD *digest) { unsigned char out[96]; if (keylen != TK26_MAC_KEY_LEN) { return 0; } if (!PKCS5_PBKDF2_HMAC(pass, passlen, salt, saltlen, iter, digest, sizeof(out), out)) { return 0; } memcpy(key, out + sizeof(out) - TK26_MAC_KEY_LEN, TK26_MAC_KEY_LEN); OPENSSL_cleanse(out, sizeof(out)); return 1; } /* Generate a MAC */ static int pkcs12_gen_mac(PKCS12 *p12, const char *pass, int passlen, unsigned char *mac, unsigned int *maclen, int (*pkcs12_key_gen)(const char *pass, int passlen, unsigned char *salt, int slen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type)) { int ret = 0; const EVP_MD *md; EVP_MD *md_fetch; HMAC_CTX *hmac = NULL; unsigned char key[EVP_MAX_MD_SIZE], *salt; int saltlen, iter; char md_name[80]; int md_size = 0; int md_nid; const X509_ALGOR *macalg; const ASN1_OBJECT *macoid; if (!PKCS7_type_is_data(p12->authsafes)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CONTENT_TYPE_NOT_DATA); return 0; } salt = p12->mac->salt->data; saltlen = p12->mac->salt->length; if (p12->mac->iter == NULL) iter = 1; else iter = ASN1_INTEGER_get(p12->mac->iter); X509_SIG_get0(p12->mac->dinfo, &macalg, NULL); X509_ALGOR_get0(&macoid, NULL, NULL, macalg); if (OBJ_obj2txt(md_name, sizeof(md_name), macoid, 0) < 0) return 0; (void)ERR_set_mark(); md = md_fetch = EVP_MD_fetch(p12->authsafes->ctx.libctx, md_name, p12->authsafes->ctx.propq); if (md == NULL) md = EVP_get_digestbynid(OBJ_obj2nid(macoid)); if (md == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_PKCS12, PKCS12_R_UNKNOWN_DIGEST_ALGORITHM); return 0; } (void)ERR_pop_to_mark(); md_size = EVP_MD_get_size(md); md_nid = EVP_MD_get_type(md); if (md_size < 0) goto err; if ((md_nid == NID_id_GostR3411_94 || md_nid == NID_id_GostR3411_2012_256 || md_nid == NID_id_GostR3411_2012_512) && ossl_safe_getenv("LEGACY_GOST_PKCS12") == NULL) { md_size = TK26_MAC_KEY_LEN; if (!pkcs12_gen_gost_mac_key(pass, passlen, salt, saltlen, iter, md_size, key, md)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_KEY_GEN_ERROR); goto err; } } else { if (pkcs12_key_gen != NULL) { if (!(*pkcs12_key_gen)(pass, passlen, salt, saltlen, PKCS12_MAC_ID, iter, md_size, key, md)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_KEY_GEN_ERROR); goto err; } } else { /* Default to UTF-8 password */ if (!PKCS12_key_gen_utf8_ex(pass, passlen, salt, saltlen, PKCS12_MAC_ID, iter, md_size, key, md, p12->authsafes->ctx.libctx, p12->authsafes->ctx.propq)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_KEY_GEN_ERROR); goto err; } } } if ((hmac = HMAC_CTX_new()) == NULL || !HMAC_Init_ex(hmac, key, md_size, md, NULL) || !HMAC_Update(hmac, p12->authsafes->d.data->data, p12->authsafes->d.data->length) || !HMAC_Final(hmac, mac, maclen)) { goto err; } ret = 1; err: OPENSSL_cleanse(key, sizeof(key)); HMAC_CTX_free(hmac); EVP_MD_free(md_fetch); return ret; } int PKCS12_gen_mac(PKCS12 *p12, const char *pass, int passlen, unsigned char *mac, unsigned int *maclen) { return pkcs12_gen_mac(p12, pass, passlen, mac, maclen, NULL); } /* Verify the mac */ int PKCS12_verify_mac(PKCS12 *p12, const char *pass, int passlen) { unsigned char mac[EVP_MAX_MD_SIZE]; unsigned int maclen; const ASN1_OCTET_STRING *macoct; if (p12->mac == NULL) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_ABSENT); return 0; } if (!pkcs12_gen_mac(p12, pass, passlen, mac, &maclen, NULL)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_GENERATION_ERROR); return 0; } X509_SIG_get0(p12->mac->dinfo, NULL, &macoct); if ((maclen != (unsigned int)ASN1_STRING_length(macoct)) || CRYPTO_memcmp(mac, ASN1_STRING_get0_data(macoct), maclen) != 0) return 0; return 1; } /* Set a mac */ int PKCS12_set_mac(PKCS12 *p12, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, const EVP_MD *md_type) { unsigned char mac[EVP_MAX_MD_SIZE]; unsigned int maclen; ASN1_OCTET_STRING *macoct; if (md_type == NULL) /* No need to do a fetch as the md_type is used only to get a NID */ md_type = EVP_sha256(); if (!iter) iter = PKCS12_DEFAULT_ITER; if (PKCS12_setup_mac(p12, iter, salt, saltlen, md_type) == PKCS12_ERROR) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_SETUP_ERROR); return 0; } /* * Note that output mac is forced to UTF-8... */ if (!pkcs12_gen_mac(p12, pass, passlen, mac, &maclen, NULL)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_GENERATION_ERROR); return 0; } X509_SIG_getm(p12->mac->dinfo, NULL, &macoct); if (!ASN1_OCTET_STRING_set(macoct, mac, maclen)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_STRING_SET_ERROR); return 0; } return 1; } /* Set up a mac structure */ int PKCS12_setup_mac(PKCS12 *p12, int iter, unsigned char *salt, int saltlen, const EVP_MD *md_type) { X509_ALGOR *macalg; PKCS12_MAC_DATA_free(p12->mac); p12->mac = NULL; if ((p12->mac = PKCS12_MAC_DATA_new()) == NULL) return PKCS12_ERROR; if (iter > 1) { if ((p12->mac->iter = ASN1_INTEGER_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return 0; } if (!ASN1_INTEGER_set(p12->mac->iter, iter)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return 0; } } if (saltlen == 0) saltlen = PKCS12_SALT_LEN; else if (saltlen < 0) return 0; if ((p12->mac->salt->data = OPENSSL_malloc(saltlen)) == NULL) return 0; p12->mac->salt->length = saltlen; if (salt == NULL) { if (RAND_bytes_ex(p12->authsafes->ctx.libctx, p12->mac->salt->data, (size_t)saltlen, 0) <= 0) return 0; } else { memcpy(p12->mac->salt->data, salt, saltlen); } X509_SIG_getm(p12->mac->dinfo, &macalg, NULL); if (!X509_ALGOR_set0(macalg, OBJ_nid2obj(EVP_MD_get_type(md_type)), V_ASN1_NULL, NULL)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return 0; } return 1; }
./openssl/crypto/pkcs12/p12_asn.c
/* * Copyright 2000-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/pkcs12.h> #include "p12_local.h" #include "crypto/pkcs7.h" /* PKCS#12 ASN1 module */ ASN1_SEQUENCE(PKCS12) = { ASN1_SIMPLE(PKCS12, version, ASN1_INTEGER), ASN1_SIMPLE(PKCS12, authsafes, PKCS7), ASN1_OPT(PKCS12, mac, PKCS12_MAC_DATA) } ASN1_SEQUENCE_END(PKCS12) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(PKCS12, PKCS12, PKCS12) PKCS12 *PKCS12_new(void) { return (PKCS12 *)ASN1_item_new(ASN1_ITEM_rptr(PKCS12)); } void PKCS12_free(PKCS12 *p12) { if (p12 != NULL && p12->authsafes != NULL) { OPENSSL_free(p12->authsafes->ctx.propq); p12->authsafes->ctx.propq = NULL; } ASN1_item_free((ASN1_VALUE *)p12, ASN1_ITEM_rptr(PKCS12)); } ASN1_SEQUENCE(PKCS12_MAC_DATA) = { ASN1_SIMPLE(PKCS12_MAC_DATA, dinfo, X509_SIG), ASN1_SIMPLE(PKCS12_MAC_DATA, salt, ASN1_OCTET_STRING), ASN1_OPT(PKCS12_MAC_DATA, iter, ASN1_INTEGER) } ASN1_SEQUENCE_END(PKCS12_MAC_DATA) IMPLEMENT_ASN1_FUNCTIONS(PKCS12_MAC_DATA) ASN1_ADB_TEMPLATE(bag_default) = ASN1_EXP(PKCS12_BAGS, value.other, ASN1_ANY, 0); ASN1_ADB(PKCS12_BAGS) = { ADB_ENTRY(NID_x509Certificate, ASN1_EXP(PKCS12_BAGS, value.x509cert, ASN1_OCTET_STRING, 0)), ADB_ENTRY(NID_x509Crl, ASN1_EXP(PKCS12_BAGS, value.x509crl, ASN1_OCTET_STRING, 0)), ADB_ENTRY(NID_sdsiCertificate, ASN1_EXP(PKCS12_BAGS, value.sdsicert, ASN1_IA5STRING, 0)), } ASN1_ADB_END(PKCS12_BAGS, 0, type, 0, &bag_default_tt, NULL); ASN1_SEQUENCE(PKCS12_BAGS) = { ASN1_SIMPLE(PKCS12_BAGS, type, ASN1_OBJECT), ASN1_ADB_OBJECT(PKCS12_BAGS), } ASN1_SEQUENCE_END(PKCS12_BAGS) IMPLEMENT_ASN1_FUNCTIONS(PKCS12_BAGS) ASN1_ADB_TEMPLATE(safebag_default) = ASN1_EXP(PKCS12_SAFEBAG, value.other, ASN1_ANY, 0); ASN1_ADB(PKCS12_SAFEBAG) = { ADB_ENTRY(NID_keyBag, ASN1_EXP(PKCS12_SAFEBAG, value.keybag, PKCS8_PRIV_KEY_INFO, 0)), ADB_ENTRY(NID_pkcs8ShroudedKeyBag, ASN1_EXP(PKCS12_SAFEBAG, value.shkeybag, X509_SIG, 0)), ADB_ENTRY(NID_safeContentsBag, ASN1_EXP_SEQUENCE_OF(PKCS12_SAFEBAG, value.safes, PKCS12_SAFEBAG, 0)), ADB_ENTRY(NID_certBag, ASN1_EXP(PKCS12_SAFEBAG, value.bag, PKCS12_BAGS, 0)), ADB_ENTRY(NID_crlBag, ASN1_EXP(PKCS12_SAFEBAG, value.bag, PKCS12_BAGS, 0)), ADB_ENTRY(NID_secretBag, ASN1_EXP(PKCS12_SAFEBAG, value.bag, PKCS12_BAGS, 0)) } ASN1_ADB_END(PKCS12_SAFEBAG, 0, type, 0, &safebag_default_tt, NULL); ASN1_SEQUENCE(PKCS12_SAFEBAG) = { ASN1_SIMPLE(PKCS12_SAFEBAG, type, ASN1_OBJECT), ASN1_ADB_OBJECT(PKCS12_SAFEBAG), ASN1_SET_OF_OPT(PKCS12_SAFEBAG, attrib, X509_ATTRIBUTE) } ASN1_SEQUENCE_END(PKCS12_SAFEBAG) IMPLEMENT_ASN1_FUNCTIONS(PKCS12_SAFEBAG) /* SEQUENCE OF SafeBag */ ASN1_ITEM_TEMPLATE(PKCS12_SAFEBAGS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PKCS12_SAFEBAGS, PKCS12_SAFEBAG) ASN1_ITEM_TEMPLATE_END(PKCS12_SAFEBAGS) /* Authsafes: SEQUENCE OF PKCS7 */ ASN1_ITEM_TEMPLATE(PKCS12_AUTHSAFES) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PKCS12_AUTHSAFES, PKCS7) ASN1_ITEM_TEMPLATE_END(PKCS12_AUTHSAFES)
./openssl/crypto/pkcs12/p12_utl.c
/* * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/pkcs12.h> #include "p12_local.h" #include "crypto/pkcs7/pk7_local.h" /* Cheap and nasty Unicode stuff */ unsigned char *OPENSSL_asc2uni(const char *asc, int asclen, unsigned char **uni, int *unilen) { int ulen, i; unsigned char *unitmp; if (asclen == -1) asclen = strlen(asc); if (asclen < 0) return NULL; ulen = asclen * 2 + 2; if ((unitmp = OPENSSL_malloc(ulen)) == NULL) return NULL; for (i = 0; i < ulen - 2; i += 2) { unitmp[i] = 0; unitmp[i + 1] = asc[i >> 1]; } /* Make result double null terminated */ unitmp[ulen - 2] = 0; unitmp[ulen - 1] = 0; if (unilen) *unilen = ulen; if (uni) *uni = unitmp; return unitmp; } char *OPENSSL_uni2asc(const unsigned char *uni, int unilen) { int asclen, i; char *asctmp; /* string must contain an even number of bytes */ if (unilen & 1) return NULL; if (unilen < 0) return NULL; asclen = unilen / 2; /* If no terminating zero allow for one */ if (!unilen || uni[unilen - 1]) asclen++; uni++; if ((asctmp = OPENSSL_malloc(asclen)) == NULL) return NULL; for (i = 0; i < unilen; i += 2) asctmp[i >> 1] = uni[i]; asctmp[asclen - 1] = 0; return asctmp; } /* * OPENSSL_{utf82uni|uni2utf8} perform conversion between UTF-8 and * PKCS#12 BMPString format, which is specified as big-endian UTF-16. * One should keep in mind that even though BMPString is passed as * unsigned char *, it's not the kind of string you can exercise e.g. * strlen on. Caller also has to keep in mind that its length is * expressed not in number of UTF-16 characters, but in number of * bytes the string occupies, and treat it, the length, accordingly. */ unsigned char *OPENSSL_utf82uni(const char *asc, int asclen, unsigned char **uni, int *unilen) { int ulen, i, j; unsigned char *unitmp, *ret; unsigned long utf32chr = 0; if (asclen == -1) asclen = strlen(asc); for (ulen = 0, i = 0; i < asclen; i += j) { j = UTF8_getc((const unsigned char *)asc+i, asclen-i, &utf32chr); /* * Following condition is somewhat opportunistic is sense that * decoding failure is used as *indirect* indication that input * string might in fact be extended ASCII/ANSI/ISO-8859-X. The * fallback is taken in hope that it would allow to process * files created with previous OpenSSL version, which used the * naive OPENSSL_asc2uni all along. It might be worth noting * that probability of false positive depends on language. In * cases covered by ISO Latin 1 probability is very low, because * any printable non-ASCII alphabet letter followed by another * or any ASCII character will trigger failure and fallback. * In other cases situation can be intensified by the fact that * English letters are not part of alternative keyboard layout, * but even then there should be plenty of pairs that trigger * decoding failure... */ if (j < 0) return OPENSSL_asc2uni(asc, asclen, uni, unilen); if (utf32chr > 0x10FFFF) /* UTF-16 cap */ return NULL; if (utf32chr >= 0x10000) /* pair of UTF-16 characters */ ulen += 2*2; else /* or just one */ ulen += 2; } ulen += 2; /* for trailing UTF16 zero */ if ((ret = OPENSSL_malloc(ulen)) == NULL) return NULL; /* re-run the loop writing down UTF-16 characters in big-endian order */ for (unitmp = ret, i = 0; i < asclen; i += j) { j = UTF8_getc((const unsigned char *)asc+i, asclen-i, &utf32chr); if (utf32chr >= 0x10000) { /* pair if UTF-16 characters */ unsigned int hi, lo; utf32chr -= 0x10000; hi = 0xD800 + (utf32chr>>10); lo = 0xDC00 + (utf32chr&0x3ff); *unitmp++ = (unsigned char)(hi>>8); *unitmp++ = (unsigned char)(hi); *unitmp++ = (unsigned char)(lo>>8); *unitmp++ = (unsigned char)(lo); } else { /* or just one */ *unitmp++ = (unsigned char)(utf32chr>>8); *unitmp++ = (unsigned char)(utf32chr); } } /* Make result double null terminated */ *unitmp++ = 0; *unitmp++ = 0; if (unilen) *unilen = ulen; if (uni) *uni = ret; return ret; } static int bmp_to_utf8(char *str, const unsigned char *utf16, int len) { unsigned long utf32chr; if (len == 0) return 0; if (len < 2) return -1; /* pull UTF-16 character in big-endian order */ utf32chr = (utf16[0]<<8) | utf16[1]; if (utf32chr >= 0xD800 && utf32chr < 0xE000) { /* two chars */ unsigned int lo; if (len < 4) return -1; utf32chr -= 0xD800; utf32chr <<= 10; lo = (utf16[2]<<8) | utf16[3]; if (lo < 0xDC00 || lo >= 0xE000) return -1; utf32chr |= lo-0xDC00; utf32chr += 0x10000; } return UTF8_putc((unsigned char *)str, len > 4 ? 4 : len, utf32chr); } char *OPENSSL_uni2utf8(const unsigned char *uni, int unilen) { int asclen, i, j; char *asctmp; /* string must contain an even number of bytes */ if (unilen & 1) return NULL; for (asclen = 0, i = 0; i < unilen; ) { j = bmp_to_utf8(NULL, uni+i, unilen-i); /* * falling back to OPENSSL_uni2asc makes lesser sense [than * falling back to OPENSSL_asc2uni in OPENSSL_utf82uni above], * it's done rather to maintain symmetry... */ if (j < 0) return OPENSSL_uni2asc(uni, unilen); if (j == 4) i += 4; else i += 2; asclen += j; } /* If no terminating zero allow for one */ if (!unilen || (uni[unilen-2]||uni[unilen - 1])) asclen++; if ((asctmp = OPENSSL_malloc(asclen)) == NULL) return NULL; /* re-run the loop emitting UTF-8 string */ for (asclen = 0, i = 0; i < unilen; ) { j = bmp_to_utf8(asctmp+asclen, uni+i, unilen-i); if (j == 4) i += 4; else i += 2; asclen += j; } /* If no terminating zero write one */ if (!unilen || (uni[unilen-2]||uni[unilen - 1])) asctmp[asclen] = '\0'; return asctmp; } int i2d_PKCS12_bio(BIO *bp, const PKCS12 *p12) { return ASN1_item_i2d_bio(ASN1_ITEM_rptr(PKCS12), bp, p12); } #ifndef OPENSSL_NO_STDIO int i2d_PKCS12_fp(FILE *fp, const PKCS12 *p12) { return ASN1_item_i2d_fp(ASN1_ITEM_rptr(PKCS12), fp, p12); } #endif PKCS12 *d2i_PKCS12_bio(BIO *bp, PKCS12 **p12) { OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; const PKCS7_CTX *p7ctx = NULL; if (p12 != NULL) { p7ctx = ossl_pkcs12_get0_pkcs7ctx(*p12); if (p7ctx != NULL) { libctx = ossl_pkcs7_ctx_get0_libctx(p7ctx); propq = ossl_pkcs7_ctx_get0_propq(p7ctx); } } return ASN1_item_d2i_bio_ex(ASN1_ITEM_rptr(PKCS12), bp, p12, libctx, propq); } #ifndef OPENSSL_NO_STDIO PKCS12 *d2i_PKCS12_fp(FILE *fp, PKCS12 **p12) { OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; const PKCS7_CTX *p7ctx = NULL; if (p12 != NULL) { p7ctx = ossl_pkcs12_get0_pkcs7ctx(*p12); if (p7ctx != NULL) { libctx = ossl_pkcs7_ctx_get0_libctx(p7ctx); propq = ossl_pkcs7_ctx_get0_propq(p7ctx); } } return ASN1_item_d2i_fp_ex(ASN1_ITEM_rptr(PKCS12), fp, p12, libctx, propq); } #endif
./openssl/crypto/pkcs12/p12_add.c
/* * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/core.h> #include <openssl/core_names.h> #include <openssl/pkcs12.h> #include "p12_local.h" #include "crypto/pkcs7/pk7_local.h" /* Pack an object into an OCTET STRING and turn into a safebag */ PKCS12_SAFEBAG *PKCS12_item_pack_safebag(void *obj, const ASN1_ITEM *it, int nid1, int nid2) { PKCS12_BAGS *bag; PKCS12_SAFEBAG *safebag; if ((bag = PKCS12_BAGS_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } bag->type = OBJ_nid2obj(nid1); if (!ASN1_item_pack(obj, it, &bag->value.octet)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } if ((safebag = PKCS12_SAFEBAG_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } safebag->value.bag = bag; safebag->type = OBJ_nid2obj(nid2); return safebag; err: PKCS12_BAGS_free(bag); return NULL; } /* Turn a stack of SAFEBAGS into a PKCS#7 data Contentinfo */ PKCS7 *PKCS12_pack_p7data(STACK_OF(PKCS12_SAFEBAG) *sk) { PKCS7 *p7; if ((p7 = PKCS7_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } p7->type = OBJ_nid2obj(NID_pkcs7_data); if ((p7->d.data = ASN1_OCTET_STRING_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } if (!ASN1_item_pack(sk, ASN1_ITEM_rptr(PKCS12_SAFEBAGS), &p7->d.data)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CANT_PACK_STRUCTURE); goto err; } return p7; err: PKCS7_free(p7); return NULL; } /* Unpack SAFEBAGS from PKCS#7 data ContentInfo */ STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7data(PKCS7 *p7) { if (!PKCS7_type_is_data(p7)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CONTENT_TYPE_NOT_DATA); return NULL; } return ASN1_item_unpack_ex(p7->d.data, ASN1_ITEM_rptr(PKCS12_SAFEBAGS), ossl_pkcs7_ctx_get0_libctx(&p7->ctx), ossl_pkcs7_ctx_get0_propq(&p7->ctx)); } /* Turn a stack of SAFEBAGS into a PKCS#7 encrypted data ContentInfo */ PKCS7 *PKCS12_pack_p7encdata_ex(int pbe_nid, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, STACK_OF(PKCS12_SAFEBAG) *bags, OSSL_LIB_CTX *ctx, const char *propq) { PKCS7 *p7; X509_ALGOR *pbe; const EVP_CIPHER *pbe_ciph = NULL; EVP_CIPHER *pbe_ciph_fetch = NULL; if ((p7 = PKCS7_new_ex(ctx, propq)) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } if (!PKCS7_set_type(p7, NID_pkcs7_encrypted)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ERROR_SETTING_ENCRYPTED_DATA_TYPE); goto err; } ERR_set_mark(); pbe_ciph = pbe_ciph_fetch = EVP_CIPHER_fetch(ctx, OBJ_nid2sn(pbe_nid), propq); if (pbe_ciph == NULL) pbe_ciph = EVP_get_cipherbynid(pbe_nid); ERR_pop_to_mark(); if (pbe_ciph != NULL) { pbe = PKCS5_pbe2_set_iv_ex(pbe_ciph, iter, salt, saltlen, NULL, -1, ctx); } else { pbe = PKCS5_pbe_set_ex(pbe_nid, iter, salt, saltlen, ctx); } if (pbe == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } X509_ALGOR_free(p7->d.encrypted->enc_data->algorithm); p7->d.encrypted->enc_data->algorithm = pbe; ASN1_OCTET_STRING_free(p7->d.encrypted->enc_data->enc_data); if (!(p7->d.encrypted->enc_data->enc_data = PKCS12_item_i2d_encrypt_ex(pbe, ASN1_ITEM_rptr(PKCS12_SAFEBAGS), pass, passlen, bags, 1, ctx, propq))) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ENCRYPT_ERROR); goto err; } EVP_CIPHER_free(pbe_ciph_fetch); return p7; err: PKCS7_free(p7); EVP_CIPHER_free(pbe_ciph_fetch); return NULL; } PKCS7 *PKCS12_pack_p7encdata(int pbe_nid, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, STACK_OF(PKCS12_SAFEBAG) *bags) { return PKCS12_pack_p7encdata_ex(pbe_nid, pass, passlen, salt, saltlen, iter, bags, NULL, NULL); } STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7encdata(PKCS7 *p7, const char *pass, int passlen) { if (!PKCS7_type_is_encrypted(p7)) return NULL; return PKCS12_item_decrypt_d2i_ex(p7->d.encrypted->enc_data->algorithm, ASN1_ITEM_rptr(PKCS12_SAFEBAGS), pass, passlen, p7->d.encrypted->enc_data->enc_data, 1, p7->ctx.libctx, p7->ctx.propq); } PKCS8_PRIV_KEY_INFO *PKCS12_decrypt_skey_ex(const PKCS12_SAFEBAG *bag, const char *pass, int passlen, OSSL_LIB_CTX *ctx, const char *propq) { return PKCS8_decrypt_ex(bag->value.shkeybag, pass, passlen, ctx, propq); } PKCS8_PRIV_KEY_INFO *PKCS12_decrypt_skey(const PKCS12_SAFEBAG *bag, const char *pass, int passlen) { return PKCS12_decrypt_skey_ex(bag, pass, passlen, NULL, NULL); } int PKCS12_pack_authsafes(PKCS12 *p12, STACK_OF(PKCS7) *safes) { if (ASN1_item_pack(safes, ASN1_ITEM_rptr(PKCS12_AUTHSAFES), &p12->authsafes->d.data)) return 1; return 0; } STACK_OF(PKCS7) *PKCS12_unpack_authsafes(const PKCS12 *p12) { STACK_OF(PKCS7) *p7s; PKCS7_CTX *p7ctx; PKCS7 *p7; int i; if (!PKCS7_type_is_data(p12->authsafes)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CONTENT_TYPE_NOT_DATA); return NULL; } p7ctx = &p12->authsafes->ctx; p7s = ASN1_item_unpack_ex(p12->authsafes->d.data, ASN1_ITEM_rptr(PKCS12_AUTHSAFES), ossl_pkcs7_ctx_get0_libctx(p7ctx), ossl_pkcs7_ctx_get0_propq(p7ctx)); if (p7s != NULL) { for (i = 0; i < sk_PKCS7_num(p7s); i++) { p7 = sk_PKCS7_value(p7s, i); if (!ossl_pkcs7_ctx_propagate(p12->authsafes, p7)) goto err; } } return p7s; err: sk_PKCS7_free(p7s); return NULL; }
./openssl/crypto/chacha/chacha_enc.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 */ /* Adapted from the public domain code by D. Bernstein from SUPERCOP. */ #include <string.h> #include "internal/endian.h" #include "crypto/chacha.h" #include "crypto/ctype.h" typedef unsigned int u32; typedef unsigned char u8; typedef union { u32 u[16]; u8 c[64]; } chacha_buf; # define ROTATE(v, n) (((v) << (n)) | ((v) >> (32 - (n)))) # ifndef PEDANTIC # if defined(__GNUC__) && __GNUC__>=2 && \ !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) # if defined(__riscv_zbb) || defined(__riscv_zbkb) # if __riscv_xlen == 64 # undef ROTATE # define ROTATE(x, n) ({ u32 ret; \ asm ("roriw %0, %1, %2" \ : "=r"(ret) \ : "r"(x), "i"(32 - (n))); ret;}) # endif # if __riscv_xlen == 32 # undef ROTATE # define ROTATE(x, n) ({ u32 ret; \ asm ("rori %0, %1, %2" \ : "=r"(ret) \ : "r"(x), "i"(32 - (n))); ret;}) # endif # endif # endif # endif # define U32TO8_LITTLE(p, v) do { \ (p)[0] = (u8)(v >> 0); \ (p)[1] = (u8)(v >> 8); \ (p)[2] = (u8)(v >> 16); \ (p)[3] = (u8)(v >> 24); \ } while(0) /* QUARTERROUND updates a, b, c, d with a ChaCha "quarter" round. */ # define QUARTERROUND(a,b,c,d) ( \ x[a] += x[b], x[d] = ROTATE((x[d] ^ x[a]),16), \ x[c] += x[d], x[b] = ROTATE((x[b] ^ x[c]),12), \ x[a] += x[b], x[d] = ROTATE((x[d] ^ x[a]), 8), \ x[c] += x[d], x[b] = ROTATE((x[b] ^ x[c]), 7) ) /* chacha_core performs 20 rounds of ChaCha on the input words in * |input| and writes the 64 output bytes to |output|. */ static void chacha20_core(chacha_buf *output, const u32 input[16]) { u32 x[16]; int i; DECLARE_IS_ENDIAN; memcpy(x, input, sizeof(x)); for (i = 20; i > 0; i -= 2) { QUARTERROUND(0, 4, 8, 12); QUARTERROUND(1, 5, 9, 13); QUARTERROUND(2, 6, 10, 14); QUARTERROUND(3, 7, 11, 15); QUARTERROUND(0, 5, 10, 15); QUARTERROUND(1, 6, 11, 12); QUARTERROUND(2, 7, 8, 13); QUARTERROUND(3, 4, 9, 14); } if (IS_LITTLE_ENDIAN) { for (i = 0; i < 16; ++i) output->u[i] = x[i] + input[i]; } else { for (i = 0; i < 16; ++i) U32TO8_LITTLE(output->c + 4 * i, (x[i] + input[i])); } } #ifdef INCLUDE_C_CHACHA20 void ChaCha20_ctr32_c(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]) #else void ChaCha20_ctr32(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]) #endif { u32 input[16]; chacha_buf buf; size_t todo, i; /* sigma constant "expand 32-byte k" in little-endian encoding */ input[0] = ((u32)ossl_toascii('e')) | ((u32)ossl_toascii('x') << 8) | ((u32)ossl_toascii('p') << 16) | ((u32)ossl_toascii('a') << 24); input[1] = ((u32)ossl_toascii('n')) | ((u32)ossl_toascii('d') << 8) | ((u32)ossl_toascii(' ') << 16) | ((u32)ossl_toascii('3') << 24); input[2] = ((u32)ossl_toascii('2')) | ((u32)ossl_toascii('-') << 8) | ((u32)ossl_toascii('b') << 16) | ((u32)ossl_toascii('y') << 24); input[3] = ((u32)ossl_toascii('t')) | ((u32)ossl_toascii('e') << 8) | ((u32)ossl_toascii(' ') << 16) | ((u32)ossl_toascii('k') << 24); input[4] = key[0]; input[5] = key[1]; input[6] = key[2]; input[7] = key[3]; input[8] = key[4]; input[9] = key[5]; input[10] = key[6]; input[11] = key[7]; input[12] = counter[0]; input[13] = counter[1]; input[14] = counter[2]; input[15] = counter[3]; while (len > 0) { todo = sizeof(buf); if (len < todo) todo = len; chacha20_core(&buf, input); for (i = 0; i < todo; i++) out[i] = inp[i] ^ buf.c[i]; out += todo; inp += todo; len -= todo; /* * Advance 32-bit counter. Note that as subroutine is so to * say nonce-agnostic, this limited counter width doesn't * prevent caller from implementing wider counter. It would * simply take two calls split on counter overflow... */ input[12]++; } }
./openssl/crypto/chacha/chacha_ppc.c
/* * Copyright 2009-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdlib.h> #include <string.h> #include <openssl/opensslconf.h> #include "crypto/chacha.h" #include "crypto/ppc_arch.h" void ChaCha20_ctr32_int(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]); void ChaCha20_ctr32_vmx(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]); void ChaCha20_ctr32_vsx(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]); void ChaCha20_ctr32_vsx_p10(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]); void ChaCha20_ctr32(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]) { #if !defined(OPENSSL_SYS_AIX) && !defined(OPENSSL_SYS_MACOSX) OPENSSL_ppccap_P & PPC_BRD31 ? ChaCha20_ctr32_vsx_p10(out, inp, len, key, counter) : #endif OPENSSL_ppccap_P & PPC_CRYPTO207 ? ChaCha20_ctr32_vsx(out, inp, len, key, counter) : OPENSSL_ppccap_P & PPC_ALTIVEC ? ChaCha20_ctr32_vmx(out, inp, len, key, counter) : ChaCha20_ctr32_int(out, inp, len, key, counter); }
./openssl/crypto/chacha/chacha_riscv.c
/* * This file is dual-licensed, meaning that you can use it under your * choice of either of the following two licenses: * * Copyright 2023-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 * * or * * Copyright (c) 2023, Jerry Shih <jerry.shih@sifive.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <openssl/opensslconf.h> #include "crypto/chacha.h" #include "crypto/riscv_arch.h" void ChaCha20_ctr32_zvkb(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]); void ChaCha20_ctr32(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]) { if (RISCV_HAS_ZVKB() && riscv_vlen() >= 128) { ChaCha20_ctr32_zvkb(out, inp, len, key, counter); } else { ChaCha20_ctr32_c(out, inp, len, key, counter); } }
./openssl/crypto/http/http_client.c
/* * Copyright 2001-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Siemens AG 2018-2020 * * 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 <stdio.h> #include <stdlib.h> #include "crypto/ctype.h" #include <string.h> #include <openssl/asn1.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/httperr.h> #include <openssl/cmperr.h> #include <openssl/buffer.h> #include <openssl/http.h> #include <openssl/trace.h> #include "internal/sockets.h" #include "internal/common.h" /* for ossl_assert() */ #define HTTP_PREFIX "HTTP/" #define HTTP_VERSION_PATT "1." /* allow 1.x */ #define HTTP_VERSION_STR_LEN sizeof(HTTP_VERSION_PATT) /* == strlen("1.0") */ #define HTTP_PREFIX_VERSION HTTP_PREFIX""HTTP_VERSION_PATT #define HTTP_1_0 HTTP_PREFIX_VERSION"0" /* "HTTP/1.0" */ #define HTTP_LINE1_MINLEN (sizeof(HTTP_PREFIX_VERSION "x 200\n") - 1) #define HTTP_VERSION_MAX_REDIRECTIONS 50 #define HTTP_STATUS_CODE_OK 200 #define HTTP_STATUS_CODE_MOVED_PERMANENTLY 301 #define HTTP_STATUS_CODE_FOUND 302 /* Stateful HTTP request code, supporting blocking and non-blocking I/O */ /* Opaque HTTP request status structure */ struct ossl_http_req_ctx_st { int state; /* Current I/O state */ unsigned char *buf; /* Buffer to write request or read response */ int buf_size; /* Buffer size */ int free_wbio; /* wbio allocated internally, free with ctx */ BIO *wbio; /* BIO to write/send request to */ BIO *rbio; /* BIO to read/receive response from */ OSSL_HTTP_bio_cb_t upd_fn; /* Optional BIO update callback used for TLS */ void *upd_arg; /* Optional arg for update callback function */ int use_ssl; /* Use HTTPS */ char *proxy; /* Optional proxy name or URI */ char *server; /* Optional server hostname */ char *port; /* Optional server port */ BIO *mem; /* Mem BIO holding request header or response */ BIO *req; /* BIO holding the request provided by caller */ int method_POST; /* HTTP method is POST (else GET) */ int text; /* Request content type is (likely) text */ char *expected_ct; /* Optional expected Content-Type */ int expect_asn1; /* Response must be ASN.1-encoded */ unsigned char *pos; /* Current position sending data */ long len_to_send; /* Number of bytes still to send */ size_t resp_len; /* Length of response */ size_t max_resp_len; /* Maximum length of response, or 0 */ int keep_alive; /* Persistent conn. 0=no, 1=prefer, 2=require */ time_t max_time; /* Maximum end time of current transfer, or 0 */ time_t max_total_time; /* Maximum end time of total transfer, or 0 */ char *redirection_url; /* Location obtained from HTTP status 301/302 */ }; /* HTTP states */ #define OHS_NOREAD 0x1000 /* If set no reading should be performed */ #define OHS_ERROR (0 | OHS_NOREAD) /* Error condition */ #define OHS_ADD_HEADERS (1 | OHS_NOREAD) /* Adding header lines to request */ #define OHS_WRITE_INIT (2 | OHS_NOREAD) /* 1st call: ready to start send */ #define OHS_WRITE_HDR1 (3 | OHS_NOREAD) /* Request header to be sent */ #define OHS_WRITE_HDR (4 | OHS_NOREAD) /* Request header being sent */ #define OHS_WRITE_REQ (5 | OHS_NOREAD) /* Request content being sent */ #define OHS_FLUSH (6 | OHS_NOREAD) /* Request being flushed */ #define OHS_FIRSTLINE 1 /* First line of response being read */ #define OHS_HEADERS 2 /* MIME headers of response being read */ #define OHS_HEADERS_ERROR 3 /* MIME headers of resp. being read after error */ #define OHS_REDIRECT 4 /* MIME headers being read, expecting Location */ #define OHS_ASN1_HEADER 5 /* ASN1 sequence header (tag+length) being read */ #define OHS_ASN1_CONTENT 6 /* ASN1 content octets being read */ #define OHS_ASN1_DONE (7 | OHS_NOREAD) /* ASN1 content read completed */ #define OHS_STREAM (8 | OHS_NOREAD) /* HTTP content stream to be read */ /* Low-level HTTP API implementation */ OSSL_HTTP_REQ_CTX *OSSL_HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio, int buf_size) { OSSL_HTTP_REQ_CTX *rctx; if (wbio == NULL || rbio == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((rctx = OPENSSL_zalloc(sizeof(*rctx))) == NULL) return NULL; rctx->state = OHS_ERROR; rctx->buf_size = buf_size > 0 ? buf_size : OSSL_HTTP_DEFAULT_MAX_LINE_LEN; rctx->buf = OPENSSL_malloc(rctx->buf_size); rctx->wbio = wbio; rctx->rbio = rbio; if (rctx->buf == NULL) { OPENSSL_free(rctx); return NULL; } rctx->max_resp_len = OSSL_HTTP_DEFAULT_MAX_RESP_LEN; /* everything else is 0, e.g. rctx->len_to_send, or NULL, e.g. rctx->mem */ return rctx; } void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX *rctx) { if (rctx == NULL) return; /* * Use BIO_free_all() because bio_update_fn may prepend or append to cbio. * This also frees any (e.g., SSL/TLS) BIOs linked with bio and, * like BIO_reset(bio), calls SSL_shutdown() to notify/alert the peer. */ if (rctx->free_wbio) BIO_free_all(rctx->wbio); /* do not free rctx->rbio */ BIO_free(rctx->mem); BIO_free(rctx->req); OPENSSL_free(rctx->buf); OPENSSL_free(rctx->proxy); OPENSSL_free(rctx->server); OPENSSL_free(rctx->port); OPENSSL_free(rctx->expected_ct); OPENSSL_free(rctx); } BIO *OSSL_HTTP_REQ_CTX_get0_mem_bio(const OSSL_HTTP_REQ_CTX *rctx) { if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } return rctx->mem; } size_t OSSL_HTTP_REQ_CTX_get_resp_len(const OSSL_HTTP_REQ_CTX *rctx) { if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } return rctx->resp_len; } void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX *rctx, unsigned long len) { if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return; } rctx->max_resp_len = len != 0 ? (size_t)len : OSSL_HTTP_DEFAULT_MAX_RESP_LEN; } /* * Create request line using |rctx| and |path| (or "/" in case |path| is NULL). * Server name (and optional port) must be given if and only if * a plain HTTP proxy is used and |path| does not begin with 'http://'. */ int OSSL_HTTP_REQ_CTX_set_request_line(OSSL_HTTP_REQ_CTX *rctx, int method_POST, const char *server, const char *port, const char *path) { if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } BIO_free(rctx->mem); if ((rctx->mem = BIO_new(BIO_s_mem())) == NULL) return 0; rctx->method_POST = method_POST != 0; if (BIO_printf(rctx->mem, "%s ", rctx->method_POST ? "POST" : "GET") <= 0) return 0; if (server != NULL) { /* HTTP (but not HTTPS) proxy is used */ /* * Section 5.1.2 of RFC 1945 states that the absoluteURI form is only * allowed when using a proxy */ if (BIO_printf(rctx->mem, OSSL_HTTP_PREFIX"%s", server) <= 0) return 0; if (port != NULL && BIO_printf(rctx->mem, ":%s", port) <= 0) return 0; } /* Make sure path includes a forward slash (abs_path) */ if (path == NULL) { path = "/"; } else if (HAS_PREFIX(path, "http://")) { /* absoluteURI for proxy use */ if (server != NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } } else if (path[0] != '/' && BIO_printf(rctx->mem, "/") <= 0) { return 0; } /* * Add (the rest of) the path and the HTTP version, * which is fixed to 1.0 for straightforward implementation of keep-alive */ if (BIO_printf(rctx->mem, "%s "HTTP_1_0"\r\n", path) <= 0) return 0; rctx->resp_len = 0; rctx->state = OHS_ADD_HEADERS; return 1; } int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX *rctx, const char *name, const char *value) { if (rctx == NULL || name == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (rctx->mem == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (BIO_puts(rctx->mem, name) <= 0) return 0; if (value != NULL) { if (BIO_write(rctx->mem, ": ", 2) != 2) return 0; if (BIO_puts(rctx->mem, value) <= 0) return 0; } return BIO_write(rctx->mem, "\r\n", 2) == 2; } int OSSL_HTTP_REQ_CTX_set_expected(OSSL_HTTP_REQ_CTX *rctx, const char *content_type, int asn1, int timeout, int keep_alive) { if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (keep_alive != 0 && rctx->state != OHS_ERROR && rctx->state != OHS_ADD_HEADERS) { /* Cannot anymore set keep-alive in request header */ ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } OPENSSL_free(rctx->expected_ct); rctx->expected_ct = NULL; if (content_type != NULL && (rctx->expected_ct = OPENSSL_strdup(content_type)) == NULL) return 0; rctx->expect_asn1 = asn1; if (timeout >= 0) rctx->max_time = timeout > 0 ? time(NULL) + timeout : 0; else /* take over any |overall_timeout| arg of OSSL_HTTP_open(), else 0 */ rctx->max_time = rctx->max_total_time; rctx->keep_alive = keep_alive; return 1; } static int set1_content(OSSL_HTTP_REQ_CTX *rctx, const char *content_type, BIO *req) { long req_len = 0; #ifndef OPENSSL_NO_STDIO FILE *fp = NULL; #endif if (rctx == NULL || (req == NULL && content_type != NULL)) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (rctx->keep_alive != 0 && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Connection", "keep-alive")) return 0; BIO_free(rctx->req); rctx->req = NULL; if (req == NULL) return 1; if (!rctx->method_POST) { ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (content_type == NULL) { rctx->text = 1; /* assuming text by default, used just for tracing */ } else { if (OPENSSL_strncasecmp(content_type, "text/", 5) == 0) rctx->text = 1; if (BIO_printf(rctx->mem, "Content-Type: %s\r\n", content_type) <= 0) return 0; } /* * BIO_CTRL_INFO yields the data length at least for memory BIOs, but for * file-based BIOs it gives the current position, which is not what we need. */ if (BIO_method_type(req) == BIO_TYPE_FILE) { #ifndef OPENSSL_NO_STDIO if (BIO_get_fp(req, &fp) == 1 && fseek(fp, 0, SEEK_END) == 0) { req_len = ftell(fp); (void)fseek(fp, 0, SEEK_SET); } else { fp = NULL; } #endif } else { req_len = BIO_ctrl(req, BIO_CTRL_INFO, 0, NULL); /* * Streaming BIOs likely will not support querying the size at all, * and we assume we got a correct value if req_len > 0. */ } if (( #ifndef OPENSSL_NO_STDIO fp != NULL /* definitely correct req_len */ || #endif req_len > 0) && BIO_printf(rctx->mem, "Content-Length: %ld\r\n", req_len) < 0) return 0; if (!BIO_up_ref(req)) return 0; rctx->req = req; return 1; } int OSSL_HTTP_REQ_CTX_set1_req(OSSL_HTTP_REQ_CTX *rctx, const char *content_type, const ASN1_ITEM *it, const ASN1_VALUE *req) { BIO *mem = NULL; int res = 1; if (req != NULL) res = (mem = ASN1_item_i2d_mem_bio(it, req)) != NULL; res = res && set1_content(rctx, content_type, mem); BIO_free(mem); return res; } static int add1_headers(OSSL_HTTP_REQ_CTX *rctx, const STACK_OF(CONF_VALUE) *headers, const char *host) { int i; int add_host = host != NULL && *host != '\0'; CONF_VALUE *hdr; for (i = 0; i < sk_CONF_VALUE_num(headers); i++) { hdr = sk_CONF_VALUE_value(headers, i); if (add_host && OPENSSL_strcasecmp("host", hdr->name) == 0) add_host = 0; if (!OSSL_HTTP_REQ_CTX_add1_header(rctx, hdr->name, hdr->value)) return 0; } if (add_host && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Host", host)) return 0; return 1; } /* Create OSSL_HTTP_REQ_CTX structure using the values provided. */ static OSSL_HTTP_REQ_CTX *http_req_ctx_new(int free_wbio, BIO *wbio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, int use_ssl, const char *proxy, const char *server, const char *port, int buf_size, int overall_timeout) { OSSL_HTTP_REQ_CTX *rctx = OSSL_HTTP_REQ_CTX_new(wbio, rbio, buf_size); if (rctx == NULL) return NULL; rctx->free_wbio = free_wbio; rctx->upd_fn = bio_update_fn; rctx->upd_arg = arg; rctx->use_ssl = use_ssl; if (proxy != NULL && (rctx->proxy = OPENSSL_strdup(proxy)) == NULL) goto err; if (server != NULL && (rctx->server = OPENSSL_strdup(server)) == NULL) goto err; if (port != NULL && (rctx->port = OPENSSL_strdup(port)) == NULL) goto err; rctx->max_total_time = overall_timeout > 0 ? time(NULL) + overall_timeout : 0; return rctx; err: OSSL_HTTP_REQ_CTX_free(rctx); return NULL; } /* * Parse first HTTP response line. This should be like this: "HTTP/1.0 200 OK". * We need to obtain the status code and (optional) informational message. * Return any received HTTP response status code, or 0 on fatal error. */ static int parse_http_line1(char *line, int *found_keep_alive) { int i, retcode, err; char *code, *reason, *end; if (!CHECK_AND_SKIP_PREFIX(line, HTTP_PREFIX_VERSION)) goto err; /* above HTTP 1.0, connection persistence is the default */ *found_keep_alive = *line > '0'; /* Skip to first whitespace (past protocol info) */ for (code = line; *code != '\0' && !ossl_isspace(*code); code++) continue; if (*code == '\0') goto err; /* Skip past whitespace to start of response code */ while (*code != '\0' && ossl_isspace(*code)) code++; if (*code == '\0') goto err; /* Find end of response code: first whitespace after start of code */ for (reason = code; *reason != '\0' && !ossl_isspace(*reason); reason++) continue; if (*reason == '\0') goto err; /* Set end of response code and start of message */ *reason++ = '\0'; /* Attempt to parse numeric code */ retcode = strtoul(code, &end, 10); if (*end != '\0') goto err; /* Skip over any leading whitespace in message */ while (*reason != '\0' && ossl_isspace(*reason)) reason++; if (*reason != '\0') { /* * Finally zap any trailing whitespace in message (include CRLF) */ /* chop any trailing whitespace from reason */ /* We know reason has a non-whitespace character so this is OK */ for (end = reason + strlen(reason) - 1; ossl_isspace(*end); end--) *end = '\0'; } switch (retcode) { case HTTP_STATUS_CODE_OK: case HTTP_STATUS_CODE_MOVED_PERMANENTLY: case HTTP_STATUS_CODE_FOUND: return retcode; default: err = HTTP_R_RECEIVED_ERROR; if (retcode < 400) err = HTTP_R_STATUS_CODE_UNSUPPORTED; if (*reason == '\0') ERR_raise_data(ERR_LIB_HTTP, err, "code=%s", code); else ERR_raise_data(ERR_LIB_HTTP, err, "code=%s, reason=%s", code, reason); return retcode; } err: for (i = 0; i < 60 && line[i] != '\0'; i++) if (!ossl_isprint(line[i])) line[i] = ' '; line[i] = '\0'; ERR_raise_data(ERR_LIB_HTTP, HTTP_R_HEADER_PARSE_ERROR, "content=%s", line); return 0; } static int check_set_resp_len(OSSL_HTTP_REQ_CTX *rctx, size_t len) { if (rctx->max_resp_len != 0 && len > rctx->max_resp_len) { ERR_raise_data(ERR_LIB_HTTP, HTTP_R_MAX_RESP_LEN_EXCEEDED, "length=%zu, max=%zu", len, rctx->max_resp_len); return 0; } if (rctx->resp_len != 0 && rctx->resp_len != len) { ERR_raise_data(ERR_LIB_HTTP, HTTP_R_INCONSISTENT_CONTENT_LENGTH, "ASN.1 length=%zu, Content-Length=%zu", len, rctx->resp_len); return 0; } rctx->resp_len = len; return 1; } static int may_still_retry(time_t max_time, int *ptimeout) { time_t time_diff, now = time(NULL); if (max_time != 0) { if (max_time < now) { ERR_raise(ERR_LIB_HTTP, HTTP_R_RETRY_TIMEOUT); return 0; } time_diff = max_time - now; *ptimeout = time_diff > INT_MAX ? INT_MAX : (int)time_diff; } return 1; } /* * Try exchanging request and response via HTTP on (non-)blocking BIO in rctx. * Returns 1 on success, 0 on error or redirection, -1 on BIO_should_retry. */ int OSSL_HTTP_REQ_CTX_nbio(OSSL_HTTP_REQ_CTX *rctx) { int i, found_expected_ct = 0, found_keep_alive = 0; int got_text = 1; long n; size_t resp_len; const unsigned char *p; char *buf, *key, *value, *line_end = NULL; if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (rctx->mem == NULL || rctx->wbio == NULL || rctx->rbio == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } rctx->redirection_url = NULL; next_io: buf = (char *)rctx->buf; if ((rctx->state & OHS_NOREAD) == 0) { if (rctx->expect_asn1) { n = BIO_read(rctx->rbio, rctx->buf, rctx->buf_size); } else { (void)ERR_set_mark(); n = BIO_gets(rctx->rbio, buf, rctx->buf_size); if (n == -2) { /* some BIOs, such as SSL, do not support "gets" */ (void)ERR_pop_to_mark(); n = BIO_get_line(rctx->rbio, buf, rctx->buf_size); } else { (void)ERR_clear_last_mark(); } } if (n <= 0) { if (BIO_should_retry(rctx->rbio)) return -1; ERR_raise(ERR_LIB_HTTP, HTTP_R_FAILED_READING_DATA); return 0; } /* Write data to memory BIO */ if (BIO_write(rctx->mem, rctx->buf, n) != n) return 0; } switch (rctx->state) { case OHS_ADD_HEADERS: /* Last operation was adding headers: need a final \r\n */ if (BIO_write(rctx->mem, "\r\n", 2) != 2) { rctx->state = OHS_ERROR; return 0; } rctx->state = OHS_WRITE_INIT; /* fall through */ case OHS_WRITE_INIT: rctx->len_to_send = BIO_get_mem_data(rctx->mem, &rctx->pos); rctx->state = OHS_WRITE_HDR1; /* fall through */ case OHS_WRITE_HDR1: case OHS_WRITE_HDR: /* Copy some chunk of data from rctx->mem to rctx->wbio */ case OHS_WRITE_REQ: /* Copy some chunk of data from rctx->req to rctx->wbio */ if (rctx->len_to_send > 0) { size_t sz; if (!BIO_write_ex(rctx->wbio, rctx->pos, rctx->len_to_send, &sz)) { if (BIO_should_retry(rctx->wbio)) return -1; rctx->state = OHS_ERROR; return 0; } if (OSSL_TRACE_ENABLED(HTTP) && rctx->state == OHS_WRITE_HDR1) OSSL_TRACE(HTTP, "Sending request: [\n"); OSSL_TRACE_STRING(HTTP, rctx->state != OHS_WRITE_REQ || rctx->text, rctx->state != OHS_WRITE_REQ, rctx->pos, sz); if (rctx->state == OHS_WRITE_HDR1) rctx->state = OHS_WRITE_HDR; rctx->pos += sz; rctx->len_to_send -= sz; goto next_io; } if (rctx->state == OHS_WRITE_HDR) { (void)BIO_reset(rctx->mem); rctx->state = OHS_WRITE_REQ; } if (rctx->req != NULL && !BIO_eof(rctx->req)) { n = BIO_read(rctx->req, rctx->buf, rctx->buf_size); if (n <= 0) { if (BIO_should_retry(rctx->req)) return -1; ERR_raise(ERR_LIB_HTTP, HTTP_R_FAILED_READING_DATA); return 0; } rctx->pos = rctx->buf; rctx->len_to_send = n; goto next_io; } if (OSSL_TRACE_ENABLED(HTTP)) OSSL_TRACE(HTTP, "]\n"); rctx->state = OHS_FLUSH; /* fall through */ case OHS_FLUSH: i = BIO_flush(rctx->wbio); if (i > 0) { rctx->state = OHS_FIRSTLINE; goto next_io; } if (BIO_should_retry(rctx->wbio)) return -1; rctx->state = OHS_ERROR; return 0; case OHS_ERROR: return 0; case OHS_FIRSTLINE: case OHS_HEADERS: case OHS_REDIRECT: /* Attempt to read a line in */ next_line: /* * Due to strange memory BIO behavior with BIO_gets we have to check * there's a complete line in there before calling BIO_gets or we'll * just get a partial read. */ n = BIO_get_mem_data(rctx->mem, &p); if (n <= 0 || memchr(p, '\n', n) == 0) { if (n >= rctx->buf_size) { rctx->state = OHS_ERROR; return 0; } goto next_io; } n = BIO_gets(rctx->mem, buf, rctx->buf_size); if (n <= 0) { if (BIO_should_retry(rctx->mem)) goto next_io; rctx->state = OHS_ERROR; return 0; } /* Don't allow excessive lines */ if (n == rctx->buf_size) { ERR_raise(ERR_LIB_HTTP, HTTP_R_RESPONSE_LINE_TOO_LONG); rctx->state = OHS_ERROR; return 0; } /* dump all response header lines */ if (OSSL_TRACE_ENABLED(HTTP)) { if (rctx->state == OHS_FIRSTLINE) OSSL_TRACE(HTTP, "Received response header: [\n"); OSSL_TRACE1(HTTP, "%s", buf); } /* First line */ if (rctx->state == OHS_FIRSTLINE) { switch (parse_http_line1(buf, &found_keep_alive)) { case HTTP_STATUS_CODE_OK: rctx->state = OHS_HEADERS; goto next_line; case HTTP_STATUS_CODE_MOVED_PERMANENTLY: case HTTP_STATUS_CODE_FOUND: /* i.e., moved temporarily */ if (!rctx->method_POST) { /* method is GET */ rctx->state = OHS_REDIRECT; goto next_line; } ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED); /* redirection is not supported/recommended for POST */ /* fall through */ default: rctx->state = OHS_HEADERS_ERROR; goto next_line; /* continue parsing and reporting header */ } } key = buf; value = strchr(key, ':'); if (value != NULL) { *(value++) = '\0'; while (ossl_isspace(*value)) value++; line_end = strchr(value, '\r'); if (line_end == NULL) line_end = strchr(value, '\n'); if (line_end != NULL) *line_end = '\0'; } if (value != NULL && line_end != NULL) { if (rctx->state == OHS_REDIRECT && OPENSSL_strcasecmp(key, "Location") == 0) { rctx->redirection_url = value; return 0; } if (OPENSSL_strcasecmp(key, "Content-Type") == 0) { got_text = OPENSSL_strncasecmp(value, "text/", 5) == 0; if (rctx->state == OHS_HEADERS && rctx->expected_ct != NULL) { const char *semicolon; if (OPENSSL_strcasecmp(rctx->expected_ct, value) != 0 /* ignore past ';' unless expected_ct contains ';' */ && (strchr(rctx->expected_ct, ';') != NULL || (semicolon = strchr(value, ';')) == NULL || (size_t)(semicolon - value) != strlen(rctx->expected_ct) || OPENSSL_strncasecmp(rctx->expected_ct, value, semicolon - value) != 0)) { ERR_raise_data(ERR_LIB_HTTP, HTTP_R_UNEXPECTED_CONTENT_TYPE, "expected=%s, actual=%s", rctx->expected_ct, value); return 0; } found_expected_ct = 1; } } /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */ if (OPENSSL_strcasecmp(key, "Connection") == 0) { if (OPENSSL_strcasecmp(value, "keep-alive") == 0) found_keep_alive = 1; else if (OPENSSL_strcasecmp(value, "close") == 0) found_keep_alive = 0; } else if (OPENSSL_strcasecmp(key, "Content-Length") == 0) { resp_len = (size_t)strtoul(value, &line_end, 10); if (line_end == value || *line_end != '\0') { ERR_raise_data(ERR_LIB_HTTP, HTTP_R_ERROR_PARSING_CONTENT_LENGTH, "input=%s", value); return 0; } if (!check_set_resp_len(rctx, resp_len)) return 0; } } /* Look for blank line indicating end of headers */ for (p = rctx->buf; *p != '\0'; p++) { if (*p != '\r' && *p != '\n') break; } if (*p != '\0') /* not end of headers */ goto next_line; if (OSSL_TRACE_ENABLED(HTTP)) OSSL_TRACE(HTTP, "]\n"); if (rctx->keep_alive != 0 /* do not let server initiate keep_alive */ && !found_keep_alive /* otherwise there is no change */) { if (rctx->keep_alive == 2) { rctx->keep_alive = 0; ERR_raise(ERR_LIB_HTTP, HTTP_R_SERVER_CANCELED_CONNECTION); return 0; } rctx->keep_alive = 0; } if (rctx->state == OHS_HEADERS_ERROR) { if (OSSL_TRACE_ENABLED(HTTP)) { int printed_final_nl = 0; OSSL_TRACE(HTTP, "Received error response body: [\n"); while ((n = BIO_read(rctx->rbio, rctx->buf, rctx->buf_size)) > 0 || (OSSL_sleep(100), BIO_should_retry(rctx->rbio))) { OSSL_TRACE_STRING(HTTP, got_text, 1, rctx->buf, n); if (n > 0) printed_final_nl = rctx->buf[n - 1] == '\n'; } OSSL_TRACE1(HTTP, "%s]\n", printed_final_nl ? "" : "\n"); (void)printed_final_nl; /* avoid warning unless enable-trace */ } return 0; } if (rctx->expected_ct != NULL && !found_expected_ct) { ERR_raise_data(ERR_LIB_HTTP, HTTP_R_MISSING_CONTENT_TYPE, "expected=%s", rctx->expected_ct); return 0; } if (rctx->state == OHS_REDIRECT) { /* http status code indicated redirect but there was no Location */ ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_REDIRECT_LOCATION); return 0; } if (!rctx->expect_asn1) { rctx->state = OHS_STREAM; return 1; } rctx->state = OHS_ASN1_HEADER; /* Fall thru */ case OHS_ASN1_HEADER: /* * Now reading ASN1 header: can read at least 2 bytes which is enough * for ASN1 SEQUENCE header and either length field or at least the * length of the length field. */ n = BIO_get_mem_data(rctx->mem, &p); if (n < 2) goto next_io; /* Check it is an ASN1 SEQUENCE */ if (*p++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) { ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_ASN1_ENCODING); return 0; } /* Check out length field */ if ((*p & 0x80) != 0) { /* * If MSB set on initial length octet we can now always read 6 * octets: make sure we have them. */ if (n < 6) goto next_io; n = *p & 0x7F; /* Not NDEF or excessive length */ if (n == 0 || (n > 4)) { ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_PARSING_ASN1_LENGTH); return 0; } p++; resp_len = 0; for (i = 0; i < n; i++) { resp_len <<= 8; resp_len |= *p++; } resp_len += n + 2; } else { resp_len = *p + 2; } if (!check_set_resp_len(rctx, resp_len)) return 0; rctx->state = OHS_ASN1_CONTENT; /* Fall thru */ case OHS_ASN1_CONTENT: default: n = BIO_get_mem_data(rctx->mem, NULL); if (n < 0 || (size_t)n < rctx->resp_len) goto next_io; rctx->state = OHS_ASN1_DONE; return 1; } } int OSSL_HTTP_REQ_CTX_nbio_d2i(OSSL_HTTP_REQ_CTX *rctx, ASN1_VALUE **pval, const ASN1_ITEM *it) { const unsigned char *p; int rv; *pval = NULL; if ((rv = OSSL_HTTP_REQ_CTX_nbio(rctx)) != 1) return rv; *pval = ASN1_item_d2i(NULL, &p, BIO_get_mem_data(rctx->mem, &p), it); return *pval != NULL; } #ifndef OPENSSL_NO_SOCK /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */ static BIO *http_new_bio(const char *server /* optionally includes ":port" */, const char *server_port /* explicit server port */, int use_ssl, const char *proxy /* optionally includes ":port" */, const char *proxy_port /* explicit proxy port */) { const char *host = server; const char *port = server_port; BIO *cbio; if (!ossl_assert(server != NULL)) return NULL; if (proxy != NULL) { host = proxy; port = proxy_port; } if (port == NULL && strchr(host, ':') == NULL) port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT; cbio = BIO_new_connect(host /* optionally includes ":port" */); if (cbio == NULL) goto end; if (port != NULL) (void)BIO_set_conn_port(cbio, port); end: return cbio; } #endif /* OPENSSL_NO_SOCK */ /* Exchange request and response via HTTP on (non-)blocking BIO */ BIO *OSSL_HTTP_REQ_CTX_exchange(OSSL_HTTP_REQ_CTX *rctx) { int rv; if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } for (;;) { rv = OSSL_HTTP_REQ_CTX_nbio(rctx); if (rv != -1) break; /* BIO_should_retry was true */ /* will not actually wait if rctx->max_time == 0 */ if (BIO_wait(rctx->rbio, rctx->max_time, 100 /* milliseconds */) <= 0) return NULL; } if (rv == 0) { if (rctx->redirection_url == NULL) { /* an error occurred */ if (rctx->len_to_send > 0) ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_SENDING); else ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_RECEIVING); } return NULL; } return rctx->state == OHS_STREAM ? rctx->rbio : rctx->mem; } int OSSL_HTTP_is_alive(const OSSL_HTTP_REQ_CTX *rctx) { return rctx != NULL && rctx->keep_alive != 0; } /* High-level HTTP API implementation */ /* Initiate an HTTP session using bio, else use given server, proxy, etc. */ OSSL_HTTP_REQ_CTX *OSSL_HTTP_open(const char *server, const char *port, const char *proxy, const char *no_proxy, int use_ssl, BIO *bio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, int buf_size, int overall_timeout) { BIO *cbio; /* == bio if supplied, used as connection BIO if rbio is NULL */ OSSL_HTTP_REQ_CTX *rctx = NULL; if (use_ssl && bio_update_fn == NULL) { ERR_raise(ERR_LIB_HTTP, HTTP_R_TLS_NOT_ENABLED); return NULL; } if (rbio != NULL && (bio == NULL || bio_update_fn != NULL)) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } if (bio != NULL) { cbio = bio; if (proxy != NULL || no_proxy != NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } } else { #ifndef OPENSSL_NO_SOCK char *proxy_host = NULL, *proxy_port = NULL; if (server == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (port != NULL && *port == '\0') port = NULL; if (port == NULL && strchr(server, ':') == NULL) port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT; proxy = OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl); if (proxy != NULL && !OSSL_HTTP_parse_url(proxy, NULL /* use_ssl */, NULL /* user */, &proxy_host, &proxy_port, NULL /* num */, NULL /* path */, NULL, NULL)) return NULL; cbio = http_new_bio(server, port, use_ssl, proxy_host, proxy_port); OPENSSL_free(proxy_host); OPENSSL_free(proxy_port); if (cbio == NULL) return NULL; #else ERR_raise(ERR_LIB_HTTP, HTTP_R_SOCK_NOT_SUPPORTED); return NULL; #endif } (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */ if (rbio == NULL && BIO_do_connect_retry(cbio, overall_timeout, -1) <= 0) { if (bio == NULL) /* cbio was not provided by caller */ BIO_free_all(cbio); goto end; } /* now overall_timeout is guaranteed to be >= 0 */ /* adapt in order to fix callback design flaw, see #17088 */ /* callback can be used to wrap or prepend TLS session */ if (bio_update_fn != NULL) { BIO *orig_bio = cbio; cbio = (*bio_update_fn)(cbio, arg, 1 /* connect */, use_ssl != 0); if (cbio == NULL) { if (bio == NULL) /* cbio was not provided by caller */ BIO_free_all(orig_bio); goto end; } } rctx = http_req_ctx_new(bio == NULL, cbio, rbio != NULL ? rbio : cbio, bio_update_fn, arg, use_ssl, proxy, server, port, buf_size, overall_timeout); end: if (rctx != NULL) /* remove any spurious error queue entries by ssl_add_cert_chain() */ (void)ERR_pop_to_mark(); else (void)ERR_clear_last_mark(); return rctx; } int OSSL_HTTP_set1_request(OSSL_HTTP_REQ_CTX *rctx, const char *path, const STACK_OF(CONF_VALUE) *headers, const char *content_type, BIO *req, const char *expected_content_type, int expect_asn1, size_t max_resp_len, int timeout, int keep_alive) { int use_http_proxy; if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } use_http_proxy = rctx->proxy != NULL && !rctx->use_ssl; if (use_http_proxy && rctx->server == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } rctx->max_resp_len = max_resp_len; /* allows for 0: indefinite */ return OSSL_HTTP_REQ_CTX_set_request_line(rctx, req != NULL, use_http_proxy ? rctx->server : NULL, rctx->port, path) && add1_headers(rctx, headers, rctx->server) && OSSL_HTTP_REQ_CTX_set_expected(rctx, expected_content_type, expect_asn1, timeout, keep_alive) && set1_content(rctx, content_type, req); } /*- * Exchange single HTTP request and response according to rctx. * If rctx->method_POST then use POST, else use GET and ignore content_type. * The redirection_url output (freed by caller) parameter is used only for GET. */ BIO *OSSL_HTTP_exchange(OSSL_HTTP_REQ_CTX *rctx, char **redirection_url) { BIO *resp; if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (redirection_url != NULL) *redirection_url = NULL; /* do this beforehand to prevent dbl free */ resp = OSSL_HTTP_REQ_CTX_exchange(rctx); if (resp == NULL) { if (rctx->redirection_url != NULL) { if (redirection_url == NULL) ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED); else /* may be NULL if out of memory: */ *redirection_url = OPENSSL_strdup(rctx->redirection_url); } else { char buf[200]; unsigned long err = ERR_peek_error(); int lib = ERR_GET_LIB(err); int reason = ERR_GET_REASON(err); if (lib == ERR_LIB_SSL || lib == ERR_LIB_HTTP || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_TIMEOUT) || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_ERROR) #ifndef OPENSSL_NO_CMP || (lib == ERR_LIB_CMP && reason == CMP_R_POTENTIALLY_INVALID_CERTIFICATE) #endif ) { if (rctx->server != NULL) { BIO_snprintf(buf, sizeof(buf), "server=http%s://%s%s%s", rctx->use_ssl ? "s" : "", rctx->server, rctx->port != NULL ? ":" : "", rctx->port != NULL ? rctx->port : ""); ERR_add_error_data(1, buf); } if (rctx->proxy != NULL) ERR_add_error_data(2, " proxy=", rctx->proxy); if (err == 0) { BIO_snprintf(buf, sizeof(buf), " peer has disconnected%s", rctx->use_ssl ? " violating the protocol" : ", likely because it requires the use of TLS"); ERR_add_error_data(1, buf); } } } } if (resp != NULL && !BIO_up_ref(resp)) resp = NULL; return resp; } static int redirection_ok(int n_redir, const char *old_url, const char *new_url) { if (n_redir >= HTTP_VERSION_MAX_REDIRECTIONS) { ERR_raise(ERR_LIB_HTTP, HTTP_R_TOO_MANY_REDIRECTIONS); return 0; } if (*new_url == '/') /* redirection to same server => same protocol */ return 1; if (HAS_PREFIX(old_url, OSSL_HTTPS_NAME":") && !HAS_PREFIX(new_url, OSSL_HTTPS_NAME":")) { ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP); return 0; } return 1; } /* Get data via HTTP from server at given URL, potentially with redirection */ BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *no_proxy, BIO *bio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, int buf_size, const STACK_OF(CONF_VALUE) *headers, const char *expected_ct, int expect_asn1, size_t max_resp_len, int timeout) { char *current_url; int n_redirs = 0; char *host; char *port; char *path; int use_ssl; BIO *resp = NULL; time_t max_time = timeout > 0 ? time(NULL) + timeout : 0; if (url == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((current_url = OPENSSL_strdup(url)) == NULL) return NULL; for (;;) { OSSL_HTTP_REQ_CTX *rctx; char *redirection_url; if (!OSSL_HTTP_parse_url(current_url, &use_ssl, NULL /* user */, &host, &port, NULL /* port_num */, &path, NULL, NULL)) break; rctx = OSSL_HTTP_open(host, port, proxy, no_proxy, use_ssl, bio, rbio, bio_update_fn, arg, buf_size, timeout); new_rpath: redirection_url = NULL; if (rctx != NULL) { if (!OSSL_HTTP_set1_request(rctx, path, headers, NULL /* content_type */, NULL /* req */, expected_ct, expect_asn1, max_resp_len, -1 /* use same max time (timeout) */, 0 /* no keep_alive */)) { OSSL_HTTP_REQ_CTX_free(rctx); rctx = NULL; } else { resp = OSSL_HTTP_exchange(rctx, &redirection_url); } } OPENSSL_free(path); if (resp == NULL && redirection_url != NULL) { if (redirection_ok(++n_redirs, current_url, redirection_url) && may_still_retry(max_time, &timeout)) { (void)BIO_reset(bio); OPENSSL_free(current_url); current_url = redirection_url; if (*redirection_url == '/') { /* redirection to same server */ path = OPENSSL_strdup(redirection_url); if (path == NULL) { OPENSSL_free(host); OPENSSL_free(port); (void)OSSL_HTTP_close(rctx, 1); BIO_free(resp); OPENSSL_free(current_url); return NULL; } goto new_rpath; } OPENSSL_free(host); OPENSSL_free(port); (void)OSSL_HTTP_close(rctx, 1); continue; } /* if redirection not allowed, ignore it */ OPENSSL_free(redirection_url); } OPENSSL_free(host); OPENSSL_free(port); if (!OSSL_HTTP_close(rctx, resp != NULL)) { BIO_free(resp); resp = NULL; } break; } OPENSSL_free(current_url); return resp; } /* Exchange request and response over a connection managed via |prctx| */ BIO *OSSL_HTTP_transfer(OSSL_HTTP_REQ_CTX **prctx, const char *server, const char *port, const char *path, int use_ssl, const char *proxy, const char *no_proxy, BIO *bio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, int buf_size, const STACK_OF(CONF_VALUE) *headers, const char *content_type, BIO *req, const char *expected_ct, int expect_asn1, size_t max_resp_len, int timeout, int keep_alive) { OSSL_HTTP_REQ_CTX *rctx = prctx == NULL ? NULL : *prctx; BIO *resp = NULL; if (rctx == NULL) { rctx = OSSL_HTTP_open(server, port, proxy, no_proxy, use_ssl, bio, rbio, bio_update_fn, arg, buf_size, timeout); timeout = -1; /* Already set during opening the connection */ } if (rctx != NULL) { if (OSSL_HTTP_set1_request(rctx, path, headers, content_type, req, expected_ct, expect_asn1, max_resp_len, timeout, keep_alive)) resp = OSSL_HTTP_exchange(rctx, NULL); if (resp == NULL || !OSSL_HTTP_is_alive(rctx)) { if (!OSSL_HTTP_close(rctx, resp != NULL)) { BIO_free(resp); resp = NULL; } rctx = NULL; } } if (prctx != NULL) *prctx = rctx; return resp; } int OSSL_HTTP_close(OSSL_HTTP_REQ_CTX *rctx, int ok) { BIO *wbio; int ret = 1; /* callback can be used to finish TLS session and free its BIO */ if (rctx != NULL && rctx->upd_fn != NULL) { wbio = (*rctx->upd_fn)(rctx->wbio, rctx->upd_arg, 0 /* disconnect */, ok); ret = wbio != NULL; if (ret) rctx->wbio = wbio; } OSSL_HTTP_REQ_CTX_free(rctx); return ret; } /* BASE64 encoder used for encoding basic proxy authentication credentials */ static char *base64encode(const void *buf, size_t len) { int i; size_t outl; char *out; /* Calculate size of encoded data */ outl = (len / 3); if (len % 3 > 0) outl++; outl <<= 2; out = OPENSSL_malloc(outl + 1); if (out == NULL) return 0; i = EVP_EncodeBlock((unsigned char *)out, buf, len); if (!ossl_assert(0 <= i && (size_t)i <= outl)) { OPENSSL_free(out); return NULL; } return out; } /* * Promote the given connection BIO using the CONNECT method for a TLS proxy. * This is typically called by an app, so bio_err and prog are used unless NULL * to print additional diagnostic information in a user-oriented way. */ int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port, const char *proxyuser, const char *proxypass, int timeout, BIO *bio_err, const char *prog) { #undef BUF_SIZE #define BUF_SIZE (8 * 1024) char *mbuf = OPENSSL_malloc(BUF_SIZE); char *mbufp; int read_len = 0; int ret = 0; BIO *fbio = BIO_new(BIO_f_buffer()); int rv; time_t max_time = timeout > 0 ? time(NULL) + timeout : 0; if (bio == NULL || server == NULL || (bio_err != NULL && prog == NULL)) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); goto end; } if (port == NULL || *port == '\0') port = OSSL_HTTPS_PORT; if (mbuf == NULL || fbio == NULL) { BIO_printf(bio_err /* may be NULL */, "%s: out of memory", prog); goto end; } BIO_push(fbio, bio); BIO_printf(fbio, "CONNECT %s:%s "HTTP_1_0"\r\n", server, port); /* * Workaround for broken proxies which would otherwise close * the connection when entering tunnel mode (e.g., Squid 2.6) */ BIO_printf(fbio, "Proxy-Connection: Keep-Alive\r\n"); /* Support for basic (base64) proxy authentication */ if (proxyuser != NULL) { size_t len = strlen(proxyuser) + 1; char *proxyauth, *proxyauthenc = NULL; if (proxypass != NULL) len += strlen(proxypass); proxyauth = OPENSSL_malloc(len + 1); if (proxyauth == NULL) goto end; if (BIO_snprintf(proxyauth, len + 1, "%s:%s", proxyuser, proxypass != NULL ? proxypass : "") != (int)len) goto proxy_end; proxyauthenc = base64encode(proxyauth, len); if (proxyauthenc != NULL) { BIO_printf(fbio, "Proxy-Authorization: Basic %s\r\n", proxyauthenc); OPENSSL_clear_free(proxyauthenc, strlen(proxyauthenc)); } proxy_end: OPENSSL_clear_free(proxyauth, len); if (proxyauthenc == NULL) goto end; } /* Terminate the HTTP CONNECT request */ BIO_printf(fbio, "\r\n"); for (;;) { if (BIO_flush(fbio) != 0) break; /* potentially needs to be retried if BIO is non-blocking */ if (!BIO_should_retry(fbio)) break; } for (;;) { /* will not actually wait if timeout == 0 */ rv = BIO_wait(fbio, max_time, 100 /* milliseconds */); if (rv <= 0) { BIO_printf(bio_err, "%s: HTTP CONNECT %s\n", prog, rv == 0 ? "timed out" : "failed waiting for data"); goto end; } /*- * The first line is the HTTP response. * According to RFC 7230, it is formatted exactly like this: * HTTP/d.d ddd reason text\r\n */ read_len = BIO_gets(fbio, mbuf, BUF_SIZE); /* the BIO may not block, so we must wait for the 1st line to come in */ if (read_len < (int)HTTP_LINE1_MINLEN) continue; /* Check for HTTP/1.x */ mbufp = mbuf; if (!CHECK_AND_SKIP_PREFIX(mbufp, HTTP_PREFIX)) { ERR_raise(ERR_LIB_HTTP, HTTP_R_HEADER_PARSE_ERROR); BIO_printf(bio_err, "%s: HTTP CONNECT failed, non-HTTP response\n", prog); /* Wrong protocol, not even HTTP, so stop reading headers */ goto end; } if (!HAS_PREFIX(mbufp, HTTP_VERSION_PATT)) { ERR_raise(ERR_LIB_HTTP, HTTP_R_RECEIVED_WRONG_HTTP_VERSION); BIO_printf(bio_err, "%s: HTTP CONNECT failed, bad HTTP version %.*s\n", prog, (int)HTTP_VERSION_STR_LEN, mbufp); goto end; } mbufp += HTTP_VERSION_STR_LEN; /* RFC 7231 4.3.6: any 2xx status code is valid */ if (!HAS_PREFIX(mbufp, " 2")) { if (ossl_isspace(*mbufp)) mbufp++; /* chop any trailing whitespace */ while (read_len > 0 && ossl_isspace(mbuf[read_len - 1])) read_len--; mbuf[read_len] = '\0'; ERR_raise_data(ERR_LIB_HTTP, HTTP_R_CONNECT_FAILURE, "reason=%s", mbufp); BIO_printf(bio_err, "%s: HTTP CONNECT failed, reason=%s\n", prog, mbufp); goto end; } ret = 1; break; } /* Read past all following headers */ do { /* * This does not necessarily catch the case when the full * HTTP response came in more than a single TCP message. */ read_len = BIO_gets(fbio, mbuf, BUF_SIZE); } while (read_len > 2); end: if (fbio != NULL) { (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); } OPENSSL_free(mbuf); return ret; #undef BUF_SIZE }
./openssl/crypto/http/http_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/httperr.h> #include "crypto/httperr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA HTTP_str_reasons[] = { {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ASN1_LEN_EXCEEDS_MAX_RESP_LEN), "asn1 len exceeds max resp len"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_CONNECT_FAILURE), "connect failure"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ERROR_PARSING_ASN1_LENGTH), "error parsing asn1 length"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ERROR_PARSING_CONTENT_LENGTH), "error parsing content length"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ERROR_PARSING_URL), "error parsing url"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ERROR_RECEIVING), "error receiving"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ERROR_SENDING), "error sending"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_FAILED_READING_DATA), "failed reading data"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_HEADER_PARSE_ERROR), "header parse error"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_INCONSISTENT_CONTENT_LENGTH), "inconsistent content length"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_INVALID_PORT_NUMBER), "invalid port number"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_INVALID_URL_PATH), "invalid url path"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_INVALID_URL_SCHEME), "invalid url scheme"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_MAX_RESP_LEN_EXCEEDED), "max resp len exceeded"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_MISSING_ASN1_ENCODING), "missing asn1 encoding"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_MISSING_CONTENT_TYPE), "missing content type"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_MISSING_REDIRECT_LOCATION), "missing redirect location"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_RECEIVED_ERROR), "received error"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_RECEIVED_WRONG_HTTP_VERSION), "received wrong http version"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP), "redirection from https to http"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_REDIRECTION_NOT_ENABLED), "redirection not enabled"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_RESPONSE_LINE_TOO_LONG), "response line too long"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_RESPONSE_PARSE_ERROR), "response parse error"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_RETRY_TIMEOUT), "retry timeout"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_SERVER_CANCELED_CONNECTION), "server canceled connection"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_SOCK_NOT_SUPPORTED), "sock not supported"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_STATUS_CODE_UNSUPPORTED), "status code unsupported"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_TLS_NOT_ENABLED), "tls not enabled"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_TOO_MANY_REDIRECTIONS), "too many redirections"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_UNEXPECTED_CONTENT_TYPE), "unexpected content type"}, {0, NULL} }; #endif int ossl_err_load_HTTP_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(HTTP_str_reasons[0].error) == NULL) ERR_load_strings_const(HTTP_str_reasons); #endif return 1; }
./openssl/crypto/http/http_lib.c
/* * Copyright 2001-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> /* for sscanf() */ #include <string.h> #include <openssl/http.h> #include <openssl/httperr.h> #include <openssl/bio.h> /* for BIO_snprintf() */ #include <openssl/err.h> #include "internal/cryptlib.h" /* for ossl_assert() */ static void init_pstring(char **pstr) { if (pstr != NULL) { *pstr = NULL; } } static void init_pint(int *pint) { if (pint != NULL) { *pint = 0; } } static int copy_substring(char **dest, const char *start, const char *end) { return dest == NULL || (*dest = OPENSSL_strndup(start, end - start)) != NULL; } static void free_pstring(char **pstr) { if (pstr != NULL) { OPENSSL_free(*pstr); *pstr = NULL; } } int OSSL_parse_url(const char *url, char **pscheme, char **puser, char **phost, char **pport, int *pport_num, char **ppath, char **pquery, char **pfrag) { const char *p, *tmp; const char *scheme, *scheme_end; const char *user, *user_end; const char *host, *host_end; const char *port, *port_end; unsigned int portnum; const char *path, *path_end; const char *query, *query_end; const char *frag, *frag_end; init_pstring(pscheme); init_pstring(puser); init_pstring(phost); init_pstring(pport); init_pint(pport_num); init_pstring(ppath); init_pstring(pfrag); init_pstring(pquery); if (url == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* check for optional prefix "<scheme>://" */ scheme = scheme_end = url; p = strstr(url, "://"); if (p == NULL) { p = url; } else { scheme_end = p; if (scheme_end == scheme) goto parse_err; p += strlen("://"); } /* parse optional "userinfo@" */ user = user_end = host = p; host = strchr(p, '@'); if (host != NULL) user_end = host++; else host = p; /* parse hostname/address as far as needed here */ if (host[0] == '[') { /* IPv6 literal, which may include ':' */ host_end = strchr(host + 1, ']'); if (host_end == NULL) goto parse_err; p = ++host_end; } else { /* look for start of optional port, path, query, or fragment */ host_end = strchr(host, ':'); if (host_end == NULL) host_end = strchr(host, '/'); if (host_end == NULL) host_end = strchr(host, '?'); if (host_end == NULL) host_end = strchr(host, '#'); if (host_end == NULL) /* the remaining string is just the hostname */ host_end = host + strlen(host); p = host_end; } /* parse optional port specification starting with ':' */ port = "0"; /* default */ if (*p == ':') port = ++p; /* remaining port spec handling is also done for the default values */ /* make sure a decimal port number is given */ if (sscanf(port, "%u", &portnum) <= 0 || portnum > 65535) { ERR_raise_data(ERR_LIB_HTTP, HTTP_R_INVALID_PORT_NUMBER, "%s", port); goto err; } for (port_end = port; '0' <= *port_end && *port_end <= '9'; port_end++) ; if (port == p) /* port was given explicitly */ p += port_end - port; /* check for optional path starting with '/' or '?'. Else must start '#' */ path = p; if (*path != '\0' && *path != '/' && *path != '?' && *path != '#') { ERR_raise(ERR_LIB_HTTP, HTTP_R_INVALID_URL_PATH); goto parse_err; } path_end = query = query_end = frag = frag_end = path + strlen(path); /* parse optional "?query" */ tmp = strchr(p, '?'); if (tmp != NULL) { p = tmp; if (pquery != NULL) { path_end = p; query = p + 1; } } /* parse optional "#fragment" */ tmp = strchr(p, '#'); if (tmp != NULL) { if (query == path_end) /* we did not record a query component */ path_end = tmp; query_end = tmp; frag = tmp + 1; } if (!copy_substring(pscheme, scheme, scheme_end) || !copy_substring(phost, host, host_end) || !copy_substring(pport, port, port_end) || !copy_substring(puser, user, user_end) || !copy_substring(pquery, query, query_end) || !copy_substring(pfrag, frag, frag_end)) goto err; if (pport_num != NULL) *pport_num = (int)portnum; if (*path == '/') { if (!copy_substring(ppath, path, path_end)) goto err; } else if (ppath != NULL) { /* must prepend '/' */ size_t buflen = 1 + path_end - path + 1; if ((*ppath = OPENSSL_malloc(buflen)) == NULL) goto err; BIO_snprintf(*ppath, buflen, "/%s", path); } return 1; parse_err: ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_PARSING_URL); err: free_pstring(pscheme); free_pstring(puser); free_pstring(phost); free_pstring(pport); free_pstring(ppath); free_pstring(pquery); free_pstring(pfrag); return 0; } int OSSL_HTTP_parse_url(const char *url, int *pssl, char **puser, char **phost, char **pport, int *pport_num, char **ppath, char **pquery, char **pfrag) { char *scheme, *port; int ssl = 0, portnum; init_pstring(pport); if (pssl != NULL) *pssl = 0; if (!OSSL_parse_url(url, &scheme, puser, phost, &port, pport_num, ppath, pquery, pfrag)) return 0; /* check for optional HTTP scheme "http[s]" */ if (strcmp(scheme, OSSL_HTTPS_NAME) == 0) { ssl = 1; if (pssl != NULL) *pssl = ssl; } else if (*scheme != '\0' && strcmp(scheme, OSSL_HTTP_NAME) != 0) { ERR_raise(ERR_LIB_HTTP, HTTP_R_INVALID_URL_SCHEME); OPENSSL_free(scheme); OPENSSL_free(port); goto err; } OPENSSL_free(scheme); if (strcmp(port, "0") == 0) { /* set default port */ OPENSSL_free(port); port = ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT; if (!ossl_assert(sscanf(port, "%d", &portnum) == 1)) goto err; if (pport_num != NULL) *pport_num = portnum; if (pport != NULL) { *pport = OPENSSL_strdup(port); if (*pport == NULL) goto err; } } else { if (pport != NULL) *pport = port; else OPENSSL_free(port); } return 1; err: free_pstring(puser); free_pstring(phost); free_pstring(ppath); free_pstring(pquery); free_pstring(pfrag); return 0; } /* Respect no_proxy, taking default value from environment variable(s) */ static int use_proxy(const char *no_proxy, const char *server) { size_t sl; const char *found = NULL; if (!ossl_assert(server != NULL)) return 0; sl = strlen(server); /* * using environment variable names, both lowercase and uppercase variants, * compatible with other HTTP client implementations like wget, curl and git */ if (no_proxy == NULL) no_proxy = ossl_safe_getenv("no_proxy"); if (no_proxy == NULL) no_proxy = ossl_safe_getenv(OPENSSL_NO_PROXY); if (no_proxy != NULL) found = strstr(no_proxy, server); while (found != NULL && ((found != no_proxy && found[-1] != ' ' && found[-1] != ',') || (found[sl] != '\0' && found[sl] != ' ' && found[sl] != ','))) found = strstr(found + 1, server); return found == NULL; } /* Take default value from environment variable(s), respect no_proxy */ const char *OSSL_HTTP_adapt_proxy(const char *proxy, const char *no_proxy, const char *server, int use_ssl) { /* * using environment variable names, both lowercase and uppercase variants, * compatible with other HTTP client implementations like wget, curl and git */ if (proxy == NULL) proxy = ossl_safe_getenv(use_ssl ? "https_proxy" : "http_proxy"); if (proxy == NULL) proxy = ossl_safe_getenv(use_ssl ? OPENSSL_HTTP_PROXY : OPENSSL_HTTPS_PROXY); if (proxy == NULL || *proxy == '\0' || !use_proxy(no_proxy, server)) return NULL; return proxy; }
./openssl/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 */
./openssl/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 */
./openssl/crypto/dso/dso_lib.c
/* * Copyright 2000-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "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); }
./openssl/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 */
./openssl/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
./openssl/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 */
./openssl/crypto/dso/dso_local.h
/* * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include "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); };
./openssl/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; }
./openssl/crypto/bn/bn_lib.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <assert.h> #include <limits.h> #include "internal/cryptlib.h" #include "internal/endian.h" #include "bn_local.h" #include <openssl/opensslconf.h> #include "internal/constant_time.h" /* This stuff appears to be completely unused, so is deprecated */ #ifndef OPENSSL_NO_DEPRECATED_0_9_8 /*- * For a 32 bit machine * 2 - 4 == 128 * 3 - 8 == 256 * 4 - 16 == 512 * 5 - 32 == 1024 * 6 - 64 == 2048 * 7 - 128 == 4096 * 8 - 256 == 8192 */ static int bn_limit_bits = 0; static int bn_limit_num = 8; /* (1<<bn_limit_bits) */ static int bn_limit_bits_low = 0; static int bn_limit_num_low = 8; /* (1<<bn_limit_bits_low) */ static int bn_limit_bits_high = 0; static int bn_limit_num_high = 8; /* (1<<bn_limit_bits_high) */ static int bn_limit_bits_mont = 0; static int bn_limit_num_mont = 8; /* (1<<bn_limit_bits_mont) */ void BN_set_params(int mult, int high, int low, int mont) { if (mult >= 0) { if (mult > (int)(sizeof(int) * 8) - 1) mult = sizeof(int) * 8 - 1; bn_limit_bits = mult; bn_limit_num = 1 << mult; } if (high >= 0) { if (high > (int)(sizeof(int) * 8) - 1) high = sizeof(int) * 8 - 1; bn_limit_bits_high = high; bn_limit_num_high = 1 << high; } if (low >= 0) { if (low > (int)(sizeof(int) * 8) - 1) low = sizeof(int) * 8 - 1; bn_limit_bits_low = low; bn_limit_num_low = 1 << low; } if (mont >= 0) { if (mont > (int)(sizeof(int) * 8) - 1) mont = sizeof(int) * 8 - 1; bn_limit_bits_mont = mont; bn_limit_num_mont = 1 << mont; } } int BN_get_params(int which) { if (which == 0) return bn_limit_bits; else if (which == 1) return bn_limit_bits_high; else if (which == 2) return bn_limit_bits_low; else if (which == 3) return bn_limit_bits_mont; else return 0; } #endif const BIGNUM *BN_value_one(void) { static const BN_ULONG data_one = 1L; static const BIGNUM const_one = { (BN_ULONG *)&data_one, 1, 1, 0, BN_FLG_STATIC_DATA }; return &const_one; } /* * Old Visual Studio ARM compiler miscompiles BN_num_bits_word() * https://mta.openssl.org/pipermail/openssl-users/2018-August/008465.html */ #if defined(_MSC_VER) && defined(_ARM_) && defined(_WIN32_WCE) \ && _MSC_VER>=1400 && _MSC_VER<1501 # define MS_BROKEN_BN_num_bits_word # pragma optimize("", off) #endif int BN_num_bits_word(BN_ULONG l) { BN_ULONG x, mask; int bits = (l != 0); #if BN_BITS2 > 32 x = l >> 32; mask = (0 - x) & BN_MASK2; mask = (0 - (mask >> (BN_BITS2 - 1))); bits += 32 & mask; l ^= (x ^ l) & mask; #endif x = l >> 16; mask = (0 - x) & BN_MASK2; mask = (0 - (mask >> (BN_BITS2 - 1))); bits += 16 & mask; l ^= (x ^ l) & mask; x = l >> 8; mask = (0 - x) & BN_MASK2; mask = (0 - (mask >> (BN_BITS2 - 1))); bits += 8 & mask; l ^= (x ^ l) & mask; x = l >> 4; mask = (0 - x) & BN_MASK2; mask = (0 - (mask >> (BN_BITS2 - 1))); bits += 4 & mask; l ^= (x ^ l) & mask; x = l >> 2; mask = (0 - x) & BN_MASK2; mask = (0 - (mask >> (BN_BITS2 - 1))); bits += 2 & mask; l ^= (x ^ l) & mask; x = l >> 1; mask = (0 - x) & BN_MASK2; mask = (0 - (mask >> (BN_BITS2 - 1))); bits += 1 & mask; return bits; } #ifdef MS_BROKEN_BN_num_bits_word # pragma optimize("", on) #endif /* * This function still leaks `a->dmax`: it's caller's responsibility to * expand the input `a` in advance to a public length. */ static ossl_inline int bn_num_bits_consttime(const BIGNUM *a) { int j, ret; unsigned int mask, past_i; int i = a->top - 1; bn_check_top(a); for (j = 0, past_i = 0, ret = 0; j < a->dmax; j++) { mask = constant_time_eq_int(i, j); /* 0xff..ff if i==j, 0x0 otherwise */ ret += BN_BITS2 & (~mask & ~past_i); ret += BN_num_bits_word(a->d[j]) & mask; past_i |= mask; /* past_i will become 0xff..ff after i==j */ } /* * if BN_is_zero(a) => i is -1 and ret contains garbage, so we mask the * final result. */ mask = ~(constant_time_eq_int(i, ((int)-1))); return ret & mask; } int BN_num_bits(const BIGNUM *a) { int i = a->top - 1; bn_check_top(a); if (a->flags & BN_FLG_CONSTTIME) { /* * We assume that BIGNUMs flagged as CONSTTIME have also been expanded * so that a->dmax is not leaking secret information. * * In other words, it's the caller's responsibility to ensure `a` has * been preallocated in advance to a public length if we hit this * branch. * */ return bn_num_bits_consttime(a); } if (BN_is_zero(a)) return 0; return ((i * BN_BITS2) + BN_num_bits_word(a->d[i])); } static void bn_free_d(BIGNUM *a, int clear) { if (BN_get_flags(a, BN_FLG_SECURE)) OPENSSL_secure_clear_free(a->d, a->dmax * sizeof(a->d[0])); else if (clear != 0) OPENSSL_clear_free(a->d, a->dmax * sizeof(a->d[0])); else OPENSSL_free(a->d); } void BN_clear_free(BIGNUM *a) { if (a == NULL) return; if (a->d != NULL && !BN_get_flags(a, BN_FLG_STATIC_DATA)) bn_free_d(a, 1); if (BN_get_flags(a, BN_FLG_MALLOCED)) { OPENSSL_cleanse(a, sizeof(*a)); OPENSSL_free(a); } } void BN_free(BIGNUM *a) { if (a == NULL) return; if (!BN_get_flags(a, BN_FLG_STATIC_DATA)) bn_free_d(a, 0); if (a->flags & BN_FLG_MALLOCED) OPENSSL_free(a); } void bn_init(BIGNUM *a) { static BIGNUM nilbn; *a = nilbn; bn_check_top(a); } BIGNUM *BN_new(void) { BIGNUM *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; ret->flags = BN_FLG_MALLOCED; bn_check_top(ret); return ret; } BIGNUM *BN_secure_new(void) { BIGNUM *ret = BN_new(); if (ret != NULL) ret->flags |= BN_FLG_SECURE; return ret; } /* This is used by bn_expand2() */ /* The caller MUST check that words > b->dmax before calling this */ static BN_ULONG *bn_expand_internal(const BIGNUM *b, int words) { BN_ULONG *a = NULL; if (words > (INT_MAX / (4 * BN_BITS2))) { ERR_raise(ERR_LIB_BN, BN_R_BIGNUM_TOO_LONG); return NULL; } if (BN_get_flags(b, BN_FLG_STATIC_DATA)) { ERR_raise(ERR_LIB_BN, BN_R_EXPAND_ON_STATIC_BIGNUM_DATA); return NULL; } if (BN_get_flags(b, BN_FLG_SECURE)) a = OPENSSL_secure_zalloc(words * sizeof(*a)); else a = OPENSSL_zalloc(words * sizeof(*a)); if (a == NULL) return NULL; assert(b->top <= words); if (b->top > 0) memcpy(a, b->d, sizeof(*a) * b->top); return a; } /* * This is an internal function that should not be used in applications. It * ensures that 'b' has enough room for a 'words' word number and initialises * any unused part of b->d with leading zeros. It is mostly used by the * various BIGNUM routines. If there is an error, NULL is returned. If not, * 'b' is returned. */ BIGNUM *bn_expand2(BIGNUM *b, int words) { if (words > b->dmax) { BN_ULONG *a = bn_expand_internal(b, words); if (!a) return NULL; if (b->d != NULL) bn_free_d(b, 1); b->d = a; b->dmax = words; } return b; } BIGNUM *BN_dup(const BIGNUM *a) { BIGNUM *t; if (a == NULL) return NULL; bn_check_top(a); t = BN_get_flags(a, BN_FLG_SECURE) ? BN_secure_new() : BN_new(); if (t == NULL) return NULL; if (!BN_copy(t, a)) { BN_free(t); return NULL; } bn_check_top(t); return t; } BIGNUM *BN_copy(BIGNUM *a, const BIGNUM *b) { int bn_words; bn_check_top(b); bn_words = BN_get_flags(b, BN_FLG_CONSTTIME) ? b->dmax : b->top; if (a == b) return a; if (bn_wexpand(a, bn_words) == NULL) return NULL; if (b->top > 0) memcpy(a->d, b->d, sizeof(b->d[0]) * bn_words); a->neg = b->neg; a->top = b->top; a->flags |= b->flags & BN_FLG_FIXED_TOP; bn_check_top(a); return a; } #define FLAGS_DATA(flags) ((flags) & (BN_FLG_STATIC_DATA \ | BN_FLG_CONSTTIME \ | BN_FLG_SECURE \ | BN_FLG_FIXED_TOP)) #define FLAGS_STRUCT(flags) ((flags) & (BN_FLG_MALLOCED)) void BN_swap(BIGNUM *a, BIGNUM *b) { int flags_old_a, flags_old_b; BN_ULONG *tmp_d; int tmp_top, tmp_dmax, tmp_neg; bn_check_top(a); bn_check_top(b); flags_old_a = a->flags; flags_old_b = b->flags; tmp_d = a->d; tmp_top = a->top; tmp_dmax = a->dmax; tmp_neg = a->neg; a->d = b->d; a->top = b->top; a->dmax = b->dmax; a->neg = b->neg; b->d = tmp_d; b->top = tmp_top; b->dmax = tmp_dmax; b->neg = tmp_neg; a->flags = FLAGS_STRUCT(flags_old_a) | FLAGS_DATA(flags_old_b); b->flags = FLAGS_STRUCT(flags_old_b) | FLAGS_DATA(flags_old_a); bn_check_top(a); bn_check_top(b); } void BN_clear(BIGNUM *a) { if (a == NULL) return; bn_check_top(a); if (a->d != NULL) OPENSSL_cleanse(a->d, sizeof(*a->d) * a->dmax); a->neg = 0; a->top = 0; a->flags &= ~BN_FLG_FIXED_TOP; } BN_ULONG BN_get_word(const BIGNUM *a) { if (a->top > 1) return BN_MASK2; else if (a->top == 1) return a->d[0]; /* a->top == 0 */ return 0; } int BN_set_word(BIGNUM *a, BN_ULONG w) { bn_check_top(a); if (bn_expand(a, (int)sizeof(BN_ULONG) * 8) == NULL) return 0; a->neg = 0; a->d[0] = w; a->top = (w ? 1 : 0); a->flags &= ~BN_FLG_FIXED_TOP; bn_check_top(a); return 1; } typedef enum {BIG, LITTLE} endianness_t; typedef enum {SIGNED, UNSIGNED} signedness_t; static BIGNUM *bin2bn(const unsigned char *s, int len, BIGNUM *ret, endianness_t endianness, signedness_t signedness) { int inc; const unsigned char *s2; int inc2; int neg = 0, xor = 0, carry = 0; unsigned int i; unsigned int n; BIGNUM *bn = NULL; /* Negative length is not acceptable */ if (len < 0) return NULL; if (ret == NULL) ret = bn = BN_new(); if (ret == NULL) return NULL; bn_check_top(ret); /* * If the input has no bits, the number is considered zero. * This makes calls with s==NULL and len==0 safe. */ if (len == 0) { BN_clear(ret); return ret; } /* * The loop that does the work iterates from least to most * significant BIGNUM chunk, so we adapt parameters to transfer * input bytes accordingly. */ if (endianness == LITTLE) { s2 = s + len - 1; inc2 = -1; inc = 1; } else { s2 = s; inc2 = 1; inc = -1; s += len - 1; } /* Take note of the signedness of the input bytes*/ if (signedness == SIGNED) { neg = !!(*s2 & 0x80); xor = neg ? 0xff : 0x00; carry = neg; } /* * Skip leading sign extensions (the value of |xor|). * This is the only spot where |s2| and |inc2| are used. */ for ( ; len > 0 && *s2 == xor; s2 += inc2, len--) continue; /* * If there was a set of 0xff, we backtrack one byte unless the next * one has a sign bit, as the last 0xff is then part of the actual * number, rather then a mere sign extension. */ if (xor == 0xff) { if (len == 0 || !(*s2 & 0x80)) len++; } /* If it was all zeros, we're done */ if (len == 0) { ret->top = 0; return ret; } n = ((len - 1) / BN_BYTES) + 1; /* Number of resulting bignum chunks */ if (bn_wexpand(ret, (int)n) == NULL) { BN_free(bn); return NULL; } ret->top = n; ret->neg = neg; for (i = 0; n-- > 0; i++) { BN_ULONG l = 0; /* Accumulator */ unsigned int m = 0; /* Offset in a bignum chunk, in bits */ for (; len > 0 && m < BN_BYTES * 8; len--, s += inc, m += 8) { BN_ULONG byte_xored = *s ^ xor; BN_ULONG byte = (byte_xored + carry) & 0xff; carry = byte_xored > byte; /* Implicit 1 or 0 */ l |= (byte << m); } ret->d[i] = l; } /* * need to call this due to clear byte at top if avoiding having the top * bit set (-ve number) */ bn_correct_top(ret); return ret; } BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret) { return bin2bn(s, len, ret, BIG, UNSIGNED); } BIGNUM *BN_signed_bin2bn(const unsigned char *s, int len, BIGNUM *ret) { return bin2bn(s, len, ret, BIG, SIGNED); } static int bn2binpad(const BIGNUM *a, unsigned char *to, int tolen, endianness_t endianness, signedness_t signedness) { int inc; int n, n8; int xor = 0, carry = 0, ext = 0; size_t i, lasti, j, atop, mask; BN_ULONG l; /* * In case |a| is fixed-top, BN_num_bits can return bogus length, * but it's assumed that fixed-top inputs ought to be "nominated" * even for padded output, so it works out... */ n8 = BN_num_bits(a); n = (n8 + 7) / 8; /* This is what BN_num_bytes() does */ /* Take note of the signedness of the bignum */ if (signedness == SIGNED) { xor = a->neg ? 0xff : 0x00; carry = a->neg; /* * if |n * 8 == n|, then the MSbit is set, otherwise unset. * We must compensate with one extra byte if that doesn't * correspond to the signedness of the bignum with regards * to 2's complement. */ ext = (n * 8 == n8) ? !a->neg /* MSbit set on nonnegative bignum */ : a->neg; /* MSbit unset on negative bignum */ } if (tolen == -1) { tolen = n + ext; } else if (tolen < n + ext) { /* uncommon/unlike case */ BIGNUM temp = *a; bn_correct_top(&temp); n8 = BN_num_bits(&temp); n = (n8 + 7) / 8; /* This is what BN_num_bytes() does */ if (tolen < n + ext) return -1; } /* Swipe through whole available data and don't give away padded zero. */ atop = a->dmax * BN_BYTES; if (atop == 0) { if (tolen != 0) memset(to, '\0', tolen); return tolen; } /* * The loop that does the work iterates from least significant * to most significant BIGNUM limb, so we adapt parameters to * transfer output bytes accordingly. */ if (endianness == LITTLE) { inc = 1; } else { inc = -1; to += tolen - 1; /* Move to the last byte, not beyond */ } lasti = atop - 1; atop = a->top * BN_BYTES; for (i = 0, j = 0; j < (size_t)tolen; j++) { unsigned char byte, byte_xored; l = a->d[i / BN_BYTES]; mask = 0 - ((j - atop) >> (8 * sizeof(i) - 1)); byte = (unsigned char)(l >> (8 * (i % BN_BYTES)) & mask); byte_xored = byte ^ xor; *to = (unsigned char)(byte_xored + carry); carry = byte_xored > *to; /* Implicit 1 or 0 */ to += inc; i += (i - lasti) >> (8 * sizeof(i) - 1); /* stay on last limb */ } return tolen; } int BN_bn2binpad(const BIGNUM *a, unsigned char *to, int tolen) { if (tolen < 0) return -1; return bn2binpad(a, to, tolen, BIG, UNSIGNED); } int BN_signed_bn2bin(const BIGNUM *a, unsigned char *to, int tolen) { if (tolen < 0) return -1; return bn2binpad(a, to, tolen, BIG, SIGNED); } int BN_bn2bin(const BIGNUM *a, unsigned char *to) { return bn2binpad(a, to, -1, BIG, UNSIGNED); } BIGNUM *BN_lebin2bn(const unsigned char *s, int len, BIGNUM *ret) { return bin2bn(s, len, ret, LITTLE, UNSIGNED); } BIGNUM *BN_signed_lebin2bn(const unsigned char *s, int len, BIGNUM *ret) { return bin2bn(s, len, ret, LITTLE, SIGNED); } int BN_bn2lebinpad(const BIGNUM *a, unsigned char *to, int tolen) { if (tolen < 0) return -1; return bn2binpad(a, to, tolen, LITTLE, UNSIGNED); } int BN_signed_bn2lebin(const BIGNUM *a, unsigned char *to, int tolen) { if (tolen < 0) return -1; return bn2binpad(a, to, tolen, LITTLE, SIGNED); } BIGNUM *BN_native2bn(const unsigned char *s, int len, BIGNUM *ret) { DECLARE_IS_ENDIAN; if (IS_LITTLE_ENDIAN) return BN_lebin2bn(s, len, ret); return BN_bin2bn(s, len, ret); } BIGNUM *BN_signed_native2bn(const unsigned char *s, int len, BIGNUM *ret) { DECLARE_IS_ENDIAN; if (IS_LITTLE_ENDIAN) return BN_signed_lebin2bn(s, len, ret); return BN_signed_bin2bn(s, len, ret); } int BN_bn2nativepad(const BIGNUM *a, unsigned char *to, int tolen) { DECLARE_IS_ENDIAN; if (IS_LITTLE_ENDIAN) return BN_bn2lebinpad(a, to, tolen); return BN_bn2binpad(a, to, tolen); } int BN_signed_bn2native(const BIGNUM *a, unsigned char *to, int tolen) { DECLARE_IS_ENDIAN; if (IS_LITTLE_ENDIAN) return BN_signed_bn2lebin(a, to, tolen); return BN_signed_bn2bin(a, to, tolen); } int BN_ucmp(const BIGNUM *a, const BIGNUM *b) { int i; BN_ULONG t1, t2, *ap, *bp; bn_check_top(a); bn_check_top(b); i = a->top - b->top; if (i != 0) return i; ap = a->d; bp = b->d; for (i = a->top - 1; i >= 0; i--) { t1 = ap[i]; t2 = bp[i]; if (t1 != t2) return ((t1 > t2) ? 1 : -1); } return 0; } int BN_cmp(const BIGNUM *a, const BIGNUM *b) { int i; int gt, lt; BN_ULONG t1, t2; if ((a == NULL) || (b == NULL)) { if (a != NULL) return -1; else if (b != NULL) return 1; else return 0; } bn_check_top(a); bn_check_top(b); if (a->neg != b->neg) { if (a->neg) return -1; else return 1; } if (a->neg == 0) { gt = 1; lt = -1; } else { gt = -1; lt = 1; } if (a->top > b->top) return gt; if (a->top < b->top) return lt; for (i = a->top - 1; i >= 0; i--) { t1 = a->d[i]; t2 = b->d[i]; if (t1 > t2) return gt; if (t1 < t2) return lt; } return 0; } int BN_set_bit(BIGNUM *a, int n) { int i, j, k; if (n < 0) return 0; i = n / BN_BITS2; j = n % BN_BITS2; if (a->top <= i) { if (bn_wexpand(a, i + 1) == NULL) return 0; for (k = a->top; k < i + 1; k++) a->d[k] = 0; a->top = i + 1; a->flags &= ~BN_FLG_FIXED_TOP; } a->d[i] |= (((BN_ULONG)1) << j); bn_check_top(a); return 1; } int BN_clear_bit(BIGNUM *a, int n) { int i, j; bn_check_top(a); if (n < 0) return 0; i = n / BN_BITS2; j = n % BN_BITS2; if (a->top <= i) return 0; a->d[i] &= (~(((BN_ULONG)1) << j)); bn_correct_top(a); return 1; } int BN_is_bit_set(const BIGNUM *a, int n) { int i, j; bn_check_top(a); if (n < 0) return 0; i = n / BN_BITS2; j = n % BN_BITS2; if (a->top <= i) return 0; return (int)(((a->d[i]) >> j) & ((BN_ULONG)1)); } int BN_mask_bits(BIGNUM *a, int n) { int b, w; bn_check_top(a); if (n < 0) return 0; w = n / BN_BITS2; b = n % BN_BITS2; if (w >= a->top) return 0; if (b == 0) a->top = w; else { a->top = w + 1; a->d[w] &= ~(BN_MASK2 << b); } bn_correct_top(a); return 1; } void BN_set_negative(BIGNUM *a, int b) { if (b && !BN_is_zero(a)) a->neg = 1; else a->neg = 0; } int bn_cmp_words(const BN_ULONG *a, const BN_ULONG *b, int n) { int i; BN_ULONG aa, bb; if (n == 0) return 0; aa = a[n - 1]; bb = b[n - 1]; if (aa != bb) return ((aa > bb) ? 1 : -1); for (i = n - 2; i >= 0; i--) { aa = a[i]; bb = b[i]; if (aa != bb) return ((aa > bb) ? 1 : -1); } return 0; } /* * Here follows a specialised variants of bn_cmp_words(). It has the * capability of performing the operation on arrays of different sizes. The * sizes of those arrays is expressed through cl, which is the common length * ( basically, min(len(a),len(b)) ), and dl, which is the delta between the * two lengths, calculated as len(a)-len(b). All lengths are the number of * BN_ULONGs... */ int bn_cmp_part_words(const BN_ULONG *a, const BN_ULONG *b, int cl, int dl) { int n, i; n = cl - 1; if (dl < 0) { for (i = dl; i < 0; i++) { if (b[n - i] != 0) return -1; /* a < b */ } } if (dl > 0) { for (i = dl; i > 0; i--) { if (a[n + i] != 0) return 1; /* a > b */ } } return bn_cmp_words(a, b, cl); } /*- * Constant-time conditional swap of a and b. * a and b are swapped if condition is not 0. * nwords is the number of words to swap. * Assumes that at least nwords are allocated in both a and b. * Assumes that no more than nwords are used by either a or b. */ void BN_consttime_swap(BN_ULONG condition, BIGNUM *a, BIGNUM *b, int nwords) { BN_ULONG t; int i; bn_wcheck_size(a, nwords); bn_wcheck_size(b, nwords); condition = ((~condition & ((condition - 1))) >> (BN_BITS2 - 1)) - 1; t = (a->top ^ b->top) & condition; a->top ^= t; b->top ^= t; t = (a->neg ^ b->neg) & condition; a->neg ^= t; b->neg ^= t; /*- * BN_FLG_STATIC_DATA: indicates that data may not be written to. Intention * is actually to treat it as it's read-only data, and some (if not most) * of it does reside in read-only segment. In other words observation of * BN_FLG_STATIC_DATA in BN_consttime_swap should be treated as fatal * condition. It would either cause SEGV or effectively cause data * corruption. * * BN_FLG_MALLOCED: refers to BN structure itself, and hence must be * preserved. * * BN_FLG_SECURE: must be preserved, because it determines how x->d was * allocated and hence how to free it. * * BN_FLG_CONSTTIME: sufficient to mask and swap * * BN_FLG_FIXED_TOP: indicates that we haven't called bn_correct_top() on * the data, so the d array may be padded with additional 0 values (i.e. * top could be greater than the minimal value that it could be). We should * be swapping it */ #define BN_CONSTTIME_SWAP_FLAGS (BN_FLG_CONSTTIME | BN_FLG_FIXED_TOP) t = ((a->flags ^ b->flags) & BN_CONSTTIME_SWAP_FLAGS) & condition; a->flags ^= t; b->flags ^= t; /* conditionally swap the data */ for (i = 0; i < nwords; i++) { t = (a->d[i] ^ b->d[i]) & condition; a->d[i] ^= t; b->d[i] ^= t; } } #undef BN_CONSTTIME_SWAP_FLAGS /* Bits of security, see SP800-57 */ int BN_security_bits(int L, int N) { int secbits, bits; if (L >= 15360) secbits = 256; else if (L >= 7680) secbits = 192; else if (L >= 3072) secbits = 128; else if (L >= 2048) secbits = 112; else if (L >= 1024) secbits = 80; else return 0; if (N == -1) return secbits; bits = N / 2; if (bits < 80) return 0; return bits >= secbits ? secbits : bits; } void BN_zero_ex(BIGNUM *a) { a->neg = 0; a->top = 0; a->flags &= ~BN_FLG_FIXED_TOP; } int BN_abs_is_word(const BIGNUM *a, const BN_ULONG w) { return ((a->top == 1) && (a->d[0] == w)) || ((w == 0) && (a->top == 0)); } int BN_is_zero(const BIGNUM *a) { return a->top == 0; } int BN_is_one(const BIGNUM *a) { return BN_abs_is_word(a, 1) && !a->neg; } int BN_is_word(const BIGNUM *a, const BN_ULONG w) { return BN_abs_is_word(a, w) && (!w || !a->neg); } int BN_is_odd(const BIGNUM *a) { return (a->top > 0) && (a->d[0] & 1); } int BN_is_negative(const BIGNUM *a) { return (a->neg != 0); } int BN_to_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx) { return BN_mod_mul_montgomery(r, a, &(mont->RR), mont, ctx); } void BN_with_flags(BIGNUM *dest, const BIGNUM *b, int flags) { dest->d = b->d; dest->top = b->top; dest->dmax = b->dmax; dest->neg = b->neg; dest->flags = ((dest->flags & BN_FLG_MALLOCED) | (b->flags & ~BN_FLG_MALLOCED) | BN_FLG_STATIC_DATA | flags); } BN_GENCB *BN_GENCB_new(void) { BN_GENCB *ret; if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) return NULL; return ret; } void BN_GENCB_free(BN_GENCB *cb) { if (cb == NULL) return; OPENSSL_free(cb); } void BN_set_flags(BIGNUM *b, int n) { b->flags |= n; } int BN_get_flags(const BIGNUM *b, int n) { return b->flags & n; } /* Populate a BN_GENCB structure with an "old"-style callback */ void BN_GENCB_set_old(BN_GENCB *gencb, void (*callback) (int, int, void *), void *cb_arg) { BN_GENCB *tmp_gencb = gencb; tmp_gencb->ver = 1; tmp_gencb->arg = cb_arg; tmp_gencb->cb.cb_1 = callback; } /* Populate a BN_GENCB structure with a "new"-style callback */ void BN_GENCB_set(BN_GENCB *gencb, int (*callback) (int, int, BN_GENCB *), void *cb_arg) { BN_GENCB *tmp_gencb = gencb; tmp_gencb->ver = 2; tmp_gencb->arg = cb_arg; tmp_gencb->cb.cb_2 = callback; } void *BN_GENCB_get_arg(BN_GENCB *cb) { return cb->arg; } BIGNUM *bn_wexpand(BIGNUM *a, int words) { return (words <= a->dmax) ? a : bn_expand2(a, words); } void bn_correct_top_consttime(BIGNUM *a) { int j, atop; BN_ULONG limb; unsigned int mask; for (j = 0, atop = 0; j < a->dmax; j++) { limb = a->d[j]; limb |= 0 - limb; limb >>= BN_BITS2 - 1; limb = 0 - limb; mask = (unsigned int)limb; mask &= constant_time_msb(j - a->top); atop = constant_time_select_int(mask, j + 1, atop); } mask = constant_time_eq_int(atop, 0); a->top = atop; a->neg = constant_time_select_int(mask, 0, a->neg); a->flags &= ~BN_FLG_FIXED_TOP; } void bn_correct_top(BIGNUM *a) { BN_ULONG *ftl; int tmp_top = a->top; if (tmp_top > 0) { for (ftl = &(a->d[tmp_top]); tmp_top > 0; tmp_top--) { ftl--; if (*ftl != 0) break; } a->top = tmp_top; } if (a->top == 0) a->neg = 0; a->flags &= ~BN_FLG_FIXED_TOP; bn_pollute(a); }
./openssl/crypto/bn/bn_print.c
/* * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <openssl/bio.h> #include "bn_local.h" static const char Hex[] = "0123456789ABCDEF"; #ifndef OPENSSL_NO_STDIO int BN_print_fp(FILE *fp, const BIGNUM *a) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) return 0; BIO_set_fp(b, fp, BIO_NOCLOSE); ret = BN_print(b, a); BIO_free(b); return ret; } #endif int BN_print(BIO *bp, const BIGNUM *a) { int i, j, v, z = 0; int ret = 0; if ((a->neg) && BIO_write(bp, "-", 1) != 1) goto end; if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) goto end; for (i = a->top - 1; i >= 0; i--) { for (j = BN_BITS2 - 4; j >= 0; j -= 4) { /* strip leading zeros */ v = (int)((a->d[i] >> j) & 0x0f); if (z || v != 0) { if (BIO_write(bp, &Hex[v], 1) != 1) goto end; z = 1; } } } ret = 1; end: return ret; } char *BN_options(void) { static int init = 0; static char data[16]; if (!init) { init++; #ifdef BN_LLONG BIO_snprintf(data, sizeof(data), "bn(%zu,%zu)", sizeof(BN_ULLONG) * 8, sizeof(BN_ULONG) * 8); #else BIO_snprintf(data, sizeof(data), "bn(%zu,%zu)", sizeof(BN_ULONG) * 8, sizeof(BN_ULONG) * 8); #endif } return data; }
./openssl/crypto/bn/bn_div.c
/* * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <assert.h> #include <openssl/bn.h> #include "internal/cryptlib.h" #include "bn_local.h" /* The old slow way */ #if 0 int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx) { int i, nm, nd; int ret = 0; BIGNUM *D; bn_check_top(m); bn_check_top(d); if (BN_is_zero(d)) { ERR_raise(ERR_LIB_BN, BN_R_DIV_BY_ZERO); return 0; } if (BN_ucmp(m, d) < 0) { if (rem != NULL) { if (BN_copy(rem, m) == NULL) return 0; } if (dv != NULL) BN_zero(dv); return 1; } BN_CTX_start(ctx); D = BN_CTX_get(ctx); if (dv == NULL) dv = BN_CTX_get(ctx); if (rem == NULL) rem = BN_CTX_get(ctx); if (D == NULL || dv == NULL || rem == NULL) goto end; nd = BN_num_bits(d); nm = BN_num_bits(m); if (BN_copy(D, d) == NULL) goto end; if (BN_copy(rem, m) == NULL) goto end; /* * The next 2 are needed so we can do a dv->d[0]|=1 later since * BN_lshift1 will only work once there is a value :-) */ BN_zero(dv); if (bn_wexpand(dv, 1) == NULL) goto end; dv->top = 1; if (!BN_lshift(D, D, nm - nd)) goto end; for (i = nm - nd; i >= 0; i--) { if (!BN_lshift1(dv, dv)) goto end; if (BN_ucmp(rem, D) >= 0) { dv->d[0] |= 1; if (!BN_usub(rem, rem, D)) goto end; } /* CAN IMPROVE (and have now :=) */ if (!BN_rshift1(D, D)) goto end; } rem->neg = BN_is_zero(rem) ? 0 : m->neg; dv->neg = m->neg ^ d->neg; ret = 1; end: BN_CTX_end(ctx); return ret; } #else # if defined(BN_DIV3W) BN_ULONG bn_div_3_words(const BN_ULONG *m, BN_ULONG d1, BN_ULONG d0); # elif 0 /* * This is #if-ed away, because it's a reference for assembly implementations, * where it can and should be made constant-time. But if you want to test it, * just replace 0 with 1. */ # if BN_BITS2 == 64 && defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16 # undef BN_ULLONG # define BN_ULLONG uint128_t # define BN_LLONG # endif # ifdef BN_LLONG # define BN_DIV3W /* * Interface is somewhat quirky, |m| is pointer to most significant limb, * and less significant limb is referred at |m[-1]|. This means that caller * is responsible for ensuring that |m[-1]| is valid. Second condition that * has to be met is that |d0|'s most significant bit has to be set. Or in * other words divisor has to be "bit-aligned to the left." bn_div_fixed_top * does all this. The subroutine considers four limbs, two of which are * "overlapping," hence the name... */ static BN_ULONG bn_div_3_words(const BN_ULONG *m, BN_ULONG d1, BN_ULONG d0) { BN_ULLONG R = ((BN_ULLONG)m[0] << BN_BITS2) | m[-1]; BN_ULLONG D = ((BN_ULLONG)d0 << BN_BITS2) | d1; BN_ULONG Q = 0, mask; int i; for (i = 0; i < BN_BITS2; i++) { Q <<= 1; if (R >= D) { Q |= 1; R -= D; } D >>= 1; } mask = 0 - (Q >> (BN_BITS2 - 1)); /* does it overflow? */ Q <<= 1; Q |= (R >= D); return (Q | mask) & BN_MASK2; } # endif # endif static int bn_left_align(BIGNUM *num) { BN_ULONG *d = num->d, n, m, rmask; int top = num->top; int rshift = BN_num_bits_word(d[top - 1]), lshift, i; lshift = BN_BITS2 - rshift; rshift %= BN_BITS2; /* say no to undefined behaviour */ rmask = (BN_ULONG)0 - rshift; /* rmask = 0 - (rshift != 0) */ rmask |= rmask >> 8; for (i = 0, m = 0; i < top; i++) { n = d[i]; d[i] = ((n << lshift) | m) & BN_MASK2; m = (n >> rshift) & rmask; } return lshift; } # if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) \ && !defined(PEDANTIC) && !defined(BN_DIV3W) # if defined(__GNUC__) && __GNUC__>=2 # if defined(__i386) || defined (__i386__) /*- * There were two reasons for implementing this template: * - GNU C generates a call to a function (__udivdi3 to be exact) * in reply to ((((BN_ULLONG)n0)<<BN_BITS2)|n1)/d0 (I fail to * understand why...); * - divl doesn't only calculate quotient, but also leaves * remainder in %edx which we can definitely use here:-) */ # undef bn_div_words # define bn_div_words(n0,n1,d0) \ ({ asm volatile ( \ "divl %4" \ : "=a"(q), "=d"(rem) \ : "a"(n1), "d"(n0), "r"(d0) \ : "cc"); \ q; \ }) # define REMAINDER_IS_ALREADY_CALCULATED # elif defined(__x86_64) && defined(SIXTY_FOUR_BIT_LONG) /* * Same story here, but it's 128-bit by 64-bit division. Wow! */ # undef bn_div_words # define bn_div_words(n0,n1,d0) \ ({ asm volatile ( \ "divq %4" \ : "=a"(q), "=d"(rem) \ : "a"(n1), "d"(n0), "r"(d0) \ : "cc"); \ q; \ }) # define REMAINDER_IS_ALREADY_CALCULATED # endif /* __<cpu> */ # endif /* __GNUC__ */ # endif /* OPENSSL_NO_ASM */ /*- * BN_div computes dv := num / divisor, rounding towards * zero, and sets up rm such that dv*divisor + rm = num holds. * Thus: * dv->neg == num->neg ^ divisor->neg (unless the result is zero) * rm->neg == num->neg (unless the remainder is zero) * If 'dv' or 'rm' is NULL, the respective value is not returned. */ int BN_div(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor, BN_CTX *ctx) { int ret; if (BN_is_zero(divisor)) { ERR_raise(ERR_LIB_BN, BN_R_DIV_BY_ZERO); return 0; } /* * Invalid zero-padding would have particularly bad consequences so don't * just rely on bn_check_top() here (bn_check_top() works only for * BN_DEBUG builds) */ if (divisor->d[divisor->top - 1] == 0) { ERR_raise(ERR_LIB_BN, BN_R_NOT_INITIALIZED); return 0; } ret = bn_div_fixed_top(dv, rm, num, divisor, ctx); if (ret) { if (dv != NULL) bn_correct_top(dv); if (rm != NULL) bn_correct_top(rm); } return ret; } /* * It's argued that *length* of *significant* part of divisor is public. * Even if it's private modulus that is. Again, *length* is assumed * public, but not *value*. Former is likely to be pre-defined by * algorithm with bit granularity, though below subroutine is invariant * of limb length. Thanks to this assumption we can require that |divisor| * may not be zero-padded, yet claim this subroutine "constant-time"(*). * This is because zero-padded dividend, |num|, is tolerated, so that * caller can pass dividend of public length(*), but with smaller amount * of significant limbs. This naturally means that quotient, |dv|, would * contain correspongly less significant limbs as well, and will be zero- * padded accordingly. Returned remainder, |rm|, will have same bit length * as divisor, also zero-padded if needed. These actually leave sign bits * in ambiguous state. In sense that we try to avoid negative zeros, while * zero-padded zeros would retain sign. * * (*) "Constant-time-ness" has two pre-conditions: * * - availability of constant-time bn_div_3_words; * - dividend is at least as "wide" as divisor, limb-wise, zero-padded * if so required, which shouldn't be a privacy problem, because * divisor's length is considered public; */ int bn_div_fixed_top(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor, BN_CTX *ctx) { int norm_shift, i, j, loop; BIGNUM *tmp, *snum, *sdiv, *res; BN_ULONG *resp, *wnum, *wnumtop; BN_ULONG d0, d1; int num_n, div_n, num_neg; assert(divisor->top > 0 && divisor->d[divisor->top - 1] != 0); bn_check_top(num); bn_check_top(divisor); bn_check_top(dv); bn_check_top(rm); BN_CTX_start(ctx); res = (dv == NULL) ? BN_CTX_get(ctx) : dv; tmp = BN_CTX_get(ctx); snum = BN_CTX_get(ctx); sdiv = BN_CTX_get(ctx); if (sdiv == NULL) goto err; /* First we normalise the numbers */ if (!BN_copy(sdiv, divisor)) goto err; norm_shift = bn_left_align(sdiv); sdiv->neg = 0; /* * Note that bn_lshift_fixed_top's output is always one limb longer * than input, even when norm_shift is zero. This means that amount of * inner loop iterations is invariant of dividend value, and that one * doesn't need to compare dividend and divisor if they were originally * of the same bit length. */ if (!(bn_lshift_fixed_top(snum, num, norm_shift))) goto err; div_n = sdiv->top; num_n = snum->top; if (num_n <= div_n) { /* caller didn't pad dividend -> no constant-time guarantee... */ if (bn_wexpand(snum, div_n + 1) == NULL) goto err; memset(&(snum->d[num_n]), 0, (div_n - num_n + 1) * sizeof(BN_ULONG)); snum->top = num_n = div_n + 1; } loop = num_n - div_n; /* * Lets setup a 'window' into snum This is the part that corresponds to * the current 'area' being divided */ wnum = &(snum->d[loop]); wnumtop = &(snum->d[num_n - 1]); /* Get the top 2 words of sdiv */ d0 = sdiv->d[div_n - 1]; d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2]; /* Setup quotient */ if (!bn_wexpand(res, loop)) goto err; num_neg = num->neg; res->neg = (num_neg ^ divisor->neg); res->top = loop; res->flags |= BN_FLG_FIXED_TOP; resp = &(res->d[loop]); /* space for temp */ if (!bn_wexpand(tmp, (div_n + 1))) goto err; for (i = 0; i < loop; i++, wnumtop--) { BN_ULONG q, l0; /* * the first part of the loop uses the top two words of snum and sdiv * to calculate a BN_ULONG q such that | wnum - sdiv * q | < sdiv */ # if defined(BN_DIV3W) q = bn_div_3_words(wnumtop, d1, d0); # else BN_ULONG n0, n1, rem = 0; n0 = wnumtop[0]; n1 = wnumtop[-1]; if (n0 == d0) q = BN_MASK2; else { /* n0 < d0 */ BN_ULONG n2 = (wnumtop == wnum) ? 0 : wnumtop[-2]; # ifdef BN_LLONG BN_ULLONG t2; # if defined(BN_LLONG) && defined(BN_DIV2W) && !defined(bn_div_words) q = (BN_ULONG)(((((BN_ULLONG) n0) << BN_BITS2) | n1) / d0); # else q = bn_div_words(n0, n1, d0); # endif # ifndef REMAINDER_IS_ALREADY_CALCULATED /* * rem doesn't have to be BN_ULLONG. The least we * know it's less that d0, isn't it? */ rem = (n1 - q * d0) & BN_MASK2; # endif t2 = (BN_ULLONG) d1 *q; for (;;) { if (t2 <= ((((BN_ULLONG) rem) << BN_BITS2) | n2)) break; q--; rem += d0; if (rem < d0) break; /* don't let rem overflow */ t2 -= d1; } # else /* !BN_LLONG */ BN_ULONG t2l, t2h; q = bn_div_words(n0, n1, d0); # ifndef REMAINDER_IS_ALREADY_CALCULATED rem = (n1 - q * d0) & BN_MASK2; # endif # if defined(BN_UMULT_LOHI) BN_UMULT_LOHI(t2l, t2h, d1, q); # elif defined(BN_UMULT_HIGH) t2l = d1 * q; t2h = BN_UMULT_HIGH(d1, q); # else { BN_ULONG ql, qh; t2l = LBITS(d1); t2h = HBITS(d1); ql = LBITS(q); qh = HBITS(q); mul64(t2l, t2h, ql, qh); /* t2=(BN_ULLONG)d1*q; */ } # endif for (;;) { if ((t2h < rem) || ((t2h == rem) && (t2l <= n2))) break; q--; rem += d0; if (rem < d0) break; /* don't let rem overflow */ if (t2l < d1) t2h--; t2l -= d1; } # endif /* !BN_LLONG */ } # endif /* !BN_DIV3W */ l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q); tmp->d[div_n] = l0; wnum--; /* * ignore top values of the bignums just sub the two BN_ULONG arrays * with bn_sub_words */ l0 = bn_sub_words(wnum, wnum, tmp->d, div_n + 1); q -= l0; /* * Note: As we have considered only the leading two BN_ULONGs in * the calculation of q, sdiv * q might be greater than wnum (but * then (q-1) * sdiv is less or equal than wnum) */ for (l0 = 0 - l0, j = 0; j < div_n; j++) tmp->d[j] = sdiv->d[j] & l0; l0 = bn_add_words(wnum, wnum, tmp->d, div_n); (*wnumtop) += l0; assert((*wnumtop) == 0); /* store part of the result */ *--resp = q; } /* snum holds remainder, it's as wide as divisor */ snum->neg = num_neg; snum->top = div_n; snum->flags |= BN_FLG_FIXED_TOP; if (rm != NULL && bn_rshift_fixed_top(rm, snum, norm_shift) == 0) goto err; BN_CTX_end(ctx); return 1; err: bn_check_top(rm); BN_CTX_end(ctx); return 0; } #endif
./openssl/crypto/bn/bn_mont.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Details about Montgomery multiplication algorithms can be found at * http://security.ece.orst.edu/publications.html, e.g. * http://security.ece.orst.edu/koc/papers/j37acmon.pdf and * sections 3.8 and 4.2 in http://security.ece.orst.edu/koc/papers/r01rsasw.pdf */ #include "internal/cryptlib.h" #include "bn_local.h" #define MONT_WORD /* use the faster word-based algorithm */ #ifdef MONT_WORD static int bn_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont); #endif int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_MONT_CTX *mont, BN_CTX *ctx) { int ret = bn_mul_mont_fixed_top(r, a, b, mont, ctx); bn_correct_top(r); bn_check_top(r); return ret; } int bn_mul_mont_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_MONT_CTX *mont, BN_CTX *ctx) { BIGNUM *tmp; int ret = 0; int num = mont->N.top; #if defined(OPENSSL_BN_ASM_MONT) && defined(MONT_WORD) if (num > 1 && num <= BN_SOFT_LIMIT && a->top == num && b->top == num) { if (bn_wexpand(r, num) == NULL) return 0; if (bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num)) { r->neg = a->neg ^ b->neg; r->top = num; r->flags |= BN_FLG_FIXED_TOP; return 1; } } #endif if ((a->top + b->top) > 2 * num) return 0; BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) goto err; bn_check_top(tmp); if (a == b) { if (!bn_sqr_fixed_top(tmp, a, ctx)) goto err; } else { if (!bn_mul_fixed_top(tmp, a, b, ctx)) goto err; } /* reduce from aRR to aR */ #ifdef MONT_WORD if (!bn_from_montgomery_word(r, tmp, mont)) goto err; #else if (!BN_from_montgomery(r, tmp, mont, ctx)) goto err; #endif ret = 1; err: BN_CTX_end(ctx); return ret; } #ifdef MONT_WORD static int bn_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont) { BIGNUM *n; BN_ULONG *ap, *np, *rp, n0, v, carry; int nl, max, i; unsigned int rtop; n = &(mont->N); nl = n->top; if (nl == 0) { ret->top = 0; return 1; } max = (2 * nl); /* carry is stored separately */ if (bn_wexpand(r, max) == NULL) return 0; r->neg ^= n->neg; np = n->d; rp = r->d; /* clear the top words of T */ for (rtop = r->top, i = 0; i < max; i++) { v = (BN_ULONG)0 - ((i - rtop) >> (8 * sizeof(rtop) - 1)); rp[i] &= v; } r->top = max; r->flags |= BN_FLG_FIXED_TOP; n0 = mont->n0[0]; /* * Add multiples of |n| to |r| until R = 2^(nl * BN_BITS2) divides it. On * input, we had |r| < |n| * R, so now |r| < 2 * |n| * R. Note that |r| * includes |carry| which is stored separately. */ for (carry = 0, i = 0; i < nl; i++, rp++) { v = bn_mul_add_words(rp, np, nl, (rp[0] * n0) & BN_MASK2); v = (v + carry + rp[nl]) & BN_MASK2; carry |= (v != rp[nl]); carry &= (v <= rp[nl]); rp[nl] = v; } if (bn_wexpand(ret, nl) == NULL) return 0; ret->top = nl; ret->flags |= BN_FLG_FIXED_TOP; ret->neg = r->neg; rp = ret->d; /* * Shift |nl| words to divide by R. We have |ap| < 2 * |n|. Note that |ap| * includes |carry| which is stored separately. */ ap = &(r->d[nl]); carry -= bn_sub_words(rp, ap, np, nl); /* * |carry| is -1 if |ap| - |np| underflowed or zero if it did not. Note * |carry| cannot be 1. That would imply the subtraction did not fit in * |nl| words, and we know at most one subtraction is needed. */ for (i = 0; i < nl; i++) { rp[i] = (carry & ap[i]) | (~carry & rp[i]); ap[i] = 0; } return 1; } #endif /* MONT_WORD */ int BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx) { int retn; retn = bn_from_mont_fixed_top(ret, a, mont, ctx); bn_correct_top(ret); bn_check_top(ret); return retn; } int bn_from_mont_fixed_top(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx) { int retn = 0; #ifdef MONT_WORD BIGNUM *t; BN_CTX_start(ctx); if ((t = BN_CTX_get(ctx)) && BN_copy(t, a)) { retn = bn_from_montgomery_word(ret, t, mont); } BN_CTX_end(ctx); #else /* !MONT_WORD */ BIGNUM *t1, *t2; BN_CTX_start(ctx); t1 = BN_CTX_get(ctx); t2 = BN_CTX_get(ctx); if (t2 == NULL) goto err; if (!BN_copy(t1, a)) goto err; BN_mask_bits(t1, mont->ri); if (!BN_mul(t2, t1, &mont->Ni, ctx)) goto err; BN_mask_bits(t2, mont->ri); if (!BN_mul(t1, t2, &mont->N, ctx)) goto err; if (!BN_add(t2, a, t1)) goto err; if (!BN_rshift(ret, t2, mont->ri)) goto err; if (BN_ucmp(ret, &(mont->N)) >= 0) { if (!BN_usub(ret, ret, &(mont->N))) goto err; } retn = 1; bn_check_top(ret); err: BN_CTX_end(ctx); #endif /* MONT_WORD */ return retn; } int bn_to_mont_fixed_top(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx) { return bn_mul_mont_fixed_top(r, a, &(mont->RR), mont, ctx); } BN_MONT_CTX *BN_MONT_CTX_new(void) { BN_MONT_CTX *ret; if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) return NULL; BN_MONT_CTX_init(ret); ret->flags = BN_FLG_MALLOCED; return ret; } void BN_MONT_CTX_init(BN_MONT_CTX *ctx) { ctx->ri = 0; bn_init(&ctx->RR); bn_init(&ctx->N); bn_init(&ctx->Ni); ctx->n0[0] = ctx->n0[1] = 0; ctx->flags = 0; } void BN_MONT_CTX_free(BN_MONT_CTX *mont) { if (mont == NULL) return; BN_clear_free(&mont->RR); BN_clear_free(&mont->N); BN_clear_free(&mont->Ni); if (mont->flags & BN_FLG_MALLOCED) OPENSSL_free(mont); } int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx) { int i, ret = 0; BIGNUM *Ri, *R; if (BN_is_zero(mod)) return 0; BN_CTX_start(ctx); if ((Ri = BN_CTX_get(ctx)) == NULL) goto err; R = &(mont->RR); /* grab RR as a temp */ if (!BN_copy(&(mont->N), mod)) goto err; /* Set N */ if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0) BN_set_flags(&(mont->N), BN_FLG_CONSTTIME); mont->N.neg = 0; #ifdef MONT_WORD { BIGNUM tmod; BN_ULONG buf[2]; bn_init(&tmod); tmod.d = buf; tmod.dmax = 2; tmod.neg = 0; if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0) BN_set_flags(&tmod, BN_FLG_CONSTTIME); mont->ri = (BN_num_bits(mod) + (BN_BITS2 - 1)) / BN_BITS2 * BN_BITS2; # if defined(OPENSSL_BN_ASM_MONT) && (BN_BITS2<=32) /* * Only certain BN_BITS2<=32 platforms actually make use of n0[1], * and we could use the #else case (with a shorter R value) for the * others. However, currently only the assembler files do know which * is which. */ BN_zero(R); if (!(BN_set_bit(R, 2 * BN_BITS2))) goto err; tmod.top = 0; if ((buf[0] = mod->d[0])) tmod.top = 1; if ((buf[1] = mod->top > 1 ? mod->d[1] : 0)) tmod.top = 2; if (BN_is_one(&tmod)) BN_zero(Ri); else if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL) goto err; if (!BN_lshift(Ri, Ri, 2 * BN_BITS2)) goto err; /* R*Ri */ if (!BN_is_zero(Ri)) { if (!BN_sub_word(Ri, 1)) goto err; } else { /* if N mod word size == 1 */ if (bn_expand(Ri, (int)sizeof(BN_ULONG) * 2) == NULL) goto err; /* Ri-- (mod double word size) */ Ri->neg = 0; Ri->d[0] = BN_MASK2; Ri->d[1] = BN_MASK2; Ri->top = 2; } if (!BN_div(Ri, NULL, Ri, &tmod, ctx)) goto err; /* * Ni = (R*Ri-1)/N, keep only couple of least significant words: */ mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0; mont->n0[1] = (Ri->top > 1) ? Ri->d[1] : 0; # else BN_zero(R); if (!(BN_set_bit(R, BN_BITS2))) goto err; /* R */ buf[0] = mod->d[0]; /* tmod = N mod word size */ buf[1] = 0; tmod.top = buf[0] != 0 ? 1 : 0; /* Ri = R^-1 mod N */ if (BN_is_one(&tmod)) BN_zero(Ri); else if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL) goto err; if (!BN_lshift(Ri, Ri, BN_BITS2)) goto err; /* R*Ri */ if (!BN_is_zero(Ri)) { if (!BN_sub_word(Ri, 1)) goto err; } else { /* if N mod word size == 1 */ if (!BN_set_word(Ri, BN_MASK2)) goto err; /* Ri-- (mod word size) */ } if (!BN_div(Ri, NULL, Ri, &tmod, ctx)) goto err; /* * Ni = (R*Ri-1)/N, keep only least significant word: */ mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0; mont->n0[1] = 0; # endif } #else /* !MONT_WORD */ { /* bignum version */ mont->ri = BN_num_bits(&mont->N); BN_zero(R); if (!BN_set_bit(R, mont->ri)) goto err; /* R = 2^ri */ /* Ri = R^-1 mod N */ if ((BN_mod_inverse(Ri, R, &mont->N, ctx)) == NULL) goto err; if (!BN_lshift(Ri, Ri, mont->ri)) goto err; /* R*Ri */ if (!BN_sub_word(Ri, 1)) goto err; /* * Ni = (R*Ri-1) / N */ if (!BN_div(&(mont->Ni), NULL, Ri, &mont->N, ctx)) goto err; } #endif /* setup RR for conversions */ BN_zero(&(mont->RR)); if (!BN_set_bit(&(mont->RR), mont->ri * 2)) goto err; if (!BN_mod(&(mont->RR), &(mont->RR), &(mont->N), ctx)) goto err; for (i = mont->RR.top, ret = mont->N.top; i < ret; i++) mont->RR.d[i] = 0; mont->RR.top = ret; mont->RR.flags |= BN_FLG_FIXED_TOP; ret = 1; err: BN_CTX_end(ctx); return ret; } BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from) { if (to == from) return to; if (!BN_copy(&(to->RR), &(from->RR))) return NULL; if (!BN_copy(&(to->N), &(from->N))) return NULL; if (!BN_copy(&(to->Ni), &(from->Ni))) return NULL; to->ri = from->ri; to->n0[0] = from->n0[0]; to->n0[1] = from->n0[1]; return to; } BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_RWLOCK *lock, const BIGNUM *mod, BN_CTX *ctx) { BN_MONT_CTX *ret; if (!CRYPTO_THREAD_read_lock(lock)) return NULL; ret = *pmont; CRYPTO_THREAD_unlock(lock); if (ret) return ret; /* * We don't want to serialize globally while doing our lazy-init math in * BN_MONT_CTX_set. That punishes threads that are doing independent * things. Instead, punish the case where more than one thread tries to * lazy-init the same 'pmont', by having each do the lazy-init math work * independently and only use the one from the thread that wins the race * (the losers throw away the work they've done). */ ret = BN_MONT_CTX_new(); if (ret == NULL) return NULL; if (!BN_MONT_CTX_set(ret, mod, ctx)) { BN_MONT_CTX_free(ret); return NULL; } /* The locked compare-and-set, after the local work is done. */ if (!CRYPTO_THREAD_write_lock(lock)) { BN_MONT_CTX_free(ret); return NULL; } if (*pmont) { BN_MONT_CTX_free(ret); ret = *pmont; } else *pmont = ret; CRYPTO_THREAD_unlock(lock); return ret; }
./openssl/crypto/bn/bn_rand.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include "crypto/rand.h" #include "bn_local.h" #include <openssl/rand.h> #include <openssl/sha.h> #include <openssl/evp.h> typedef enum bnrand_flag_e { NORMAL, TESTING, PRIVATE } BNRAND_FLAG; static int bnrand(BNRAND_FLAG flag, BIGNUM *rnd, int bits, int top, int bottom, unsigned int strength, BN_CTX *ctx) { unsigned char *buf = NULL; int b, ret = 0, bit, bytes, mask; OSSL_LIB_CTX *libctx = ossl_bn_get_libctx(ctx); if (bits == 0) { if (top != BN_RAND_TOP_ANY || bottom != BN_RAND_BOTTOM_ANY) goto toosmall; BN_zero(rnd); return 1; } if (bits < 0 || (bits == 1 && top > 0)) goto toosmall; bytes = (bits + 7) / 8; bit = (bits - 1) % 8; mask = 0xff << (bit + 1); buf = OPENSSL_malloc(bytes); if (buf == NULL) goto err; /* make a random number and set the top and bottom bits */ b = flag == NORMAL ? RAND_bytes_ex(libctx, buf, bytes, strength) : RAND_priv_bytes_ex(libctx, buf, bytes, strength); if (b <= 0) goto err; if (flag == TESTING) { /* * generate patterns that are more likely to trigger BN library bugs */ int i; unsigned char c; for (i = 0; i < bytes; i++) { if (RAND_bytes_ex(libctx, &c, 1, strength) <= 0) goto err; if (c >= 128 && i > 0) buf[i] = buf[i - 1]; else if (c < 42) buf[i] = 0; else if (c < 84) buf[i] = 255; } } if (top >= 0) { if (top) { if (bit == 0) { buf[0] = 1; buf[1] |= 0x80; } else { buf[0] |= (3 << (bit - 1)); } } else { buf[0] |= (1 << bit); } } buf[0] &= ~mask; if (bottom) /* set bottom bit if requested */ buf[bytes - 1] |= 1; if (!BN_bin2bn(buf, bytes, rnd)) goto err; ret = 1; err: OPENSSL_clear_free(buf, bytes); bn_check_top(rnd); return ret; toosmall: ERR_raise(ERR_LIB_BN, BN_R_BITS_TOO_SMALL); return 0; } int BN_rand_ex(BIGNUM *rnd, int bits, int top, int bottom, unsigned int strength, BN_CTX *ctx) { return bnrand(NORMAL, rnd, bits, top, bottom, strength, ctx); } #ifndef FIPS_MODULE int BN_rand(BIGNUM *rnd, int bits, int top, int bottom) { return bnrand(NORMAL, rnd, bits, top, bottom, 0, NULL); } int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom) { return bnrand(TESTING, rnd, bits, top, bottom, 0, NULL); } #endif int BN_priv_rand_ex(BIGNUM *rnd, int bits, int top, int bottom, unsigned int strength, BN_CTX *ctx) { return bnrand(PRIVATE, rnd, bits, top, bottom, strength, ctx); } #ifndef FIPS_MODULE int BN_priv_rand(BIGNUM *rnd, int bits, int top, int bottom) { return bnrand(PRIVATE, rnd, bits, top, bottom, 0, NULL); } #endif /* random number r: 0 <= r < range */ static int bnrand_range(BNRAND_FLAG flag, BIGNUM *r, const BIGNUM *range, unsigned int strength, BN_CTX *ctx) { int n; int count = 100; if (r == NULL) { ERR_raise(ERR_LIB_BN, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (range->neg || BN_is_zero(range)) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_RANGE); return 0; } n = BN_num_bits(range); /* n > 0 */ /* BN_is_bit_set(range, n - 1) always holds */ if (n == 1) BN_zero(r); else if (!BN_is_bit_set(range, n - 2) && !BN_is_bit_set(range, n - 3)) { /* * range = 100..._2, so 3*range (= 11..._2) is exactly one bit longer * than range */ do { if (!bnrand(flag, r, n + 1, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY, strength, ctx)) return 0; /* * If r < 3*range, use r := r MOD range (which is either r, r - * range, or r - 2*range). Otherwise, iterate once more. Since * 3*range = 11..._2, each iteration succeeds with probability >= * .75. */ if (BN_cmp(r, range) >= 0) { if (!BN_sub(r, r, range)) return 0; if (BN_cmp(r, range) >= 0) if (!BN_sub(r, r, range)) return 0; } if (!--count) { ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS); return 0; } } while (BN_cmp(r, range) >= 0); } else { do { /* range = 11..._2 or range = 101..._2 */ if (!bnrand(flag, r, n, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY, 0, ctx)) return 0; if (!--count) { ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS); return 0; } } while (BN_cmp(r, range) >= 0); } bn_check_top(r); return 1; } int BN_rand_range_ex(BIGNUM *r, const BIGNUM *range, unsigned int strength, BN_CTX *ctx) { return bnrand_range(NORMAL, r, range, strength, ctx); } #ifndef FIPS_MODULE int BN_rand_range(BIGNUM *r, const BIGNUM *range) { return bnrand_range(NORMAL, r, range, 0, NULL); } #endif int BN_priv_rand_range_ex(BIGNUM *r, const BIGNUM *range, unsigned int strength, BN_CTX *ctx) { return bnrand_range(PRIVATE, r, range, strength, ctx); } #ifndef FIPS_MODULE int BN_priv_rand_range(BIGNUM *r, const BIGNUM *range) { return bnrand_range(PRIVATE, r, range, 0, NULL); } # ifndef OPENSSL_NO_DEPRECATED_3_0 int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom) { return BN_rand(rnd, bits, top, bottom); } int BN_pseudo_rand_range(BIGNUM *r, const BIGNUM *range) { return BN_rand_range(r, range); } # endif #endif /* * BN_generate_dsa_nonce generates a random number 0 <= out < range. Unlike * BN_rand_range, it also includes the contents of |priv| and |message| in * the generation so that an RNG failure isn't fatal as long as |priv| * remains secret. This is intended for use in DSA and ECDSA where an RNG * weakness leads directly to private key exposure unless this function is * used. */ int BN_generate_dsa_nonce(BIGNUM *out, const BIGNUM *range, const BIGNUM *priv, const unsigned char *message, size_t message_len, BN_CTX *ctx) { EVP_MD_CTX *mdctx = EVP_MD_CTX_new(); /* * We use 512 bits of random data per iteration to ensure that we have at * least |range| bits of randomness. */ unsigned char random_bytes[64]; unsigned char digest[SHA512_DIGEST_LENGTH]; unsigned done, todo; /* We generate |range|+8 bytes of random output. */ const unsigned num_k_bytes = BN_num_bytes(range) + 8; unsigned char private_bytes[96]; unsigned char *k_bytes = NULL; int ret = 0; EVP_MD *md = NULL; OSSL_LIB_CTX *libctx = ossl_bn_get_libctx(ctx); if (mdctx == NULL) goto err; k_bytes = OPENSSL_malloc(num_k_bytes); if (k_bytes == NULL) goto err; /* We copy |priv| into a local buffer to avoid exposing its length. */ if (BN_bn2binpad(priv, private_bytes, sizeof(private_bytes)) < 0) { /* * No reasonable DSA or ECDSA key should have a private key this * large and we don't handle this case in order to avoid leaking the * length of the private key. */ ERR_raise(ERR_LIB_BN, BN_R_PRIVATE_KEY_TOO_LARGE); goto err; } md = EVP_MD_fetch(libctx, "SHA512", NULL); if (md == NULL) { ERR_raise(ERR_LIB_BN, BN_R_NO_SUITABLE_DIGEST); goto err; } for (done = 0; done < num_k_bytes;) { if (RAND_priv_bytes_ex(libctx, random_bytes, sizeof(random_bytes), 0) <= 0) goto err; if (!EVP_DigestInit_ex(mdctx, md, NULL) || !EVP_DigestUpdate(mdctx, &done, sizeof(done)) || !EVP_DigestUpdate(mdctx, private_bytes, sizeof(private_bytes)) || !EVP_DigestUpdate(mdctx, message, message_len) || !EVP_DigestUpdate(mdctx, random_bytes, sizeof(random_bytes)) || !EVP_DigestFinal_ex(mdctx, digest, NULL)) goto err; todo = num_k_bytes - done; if (todo > SHA512_DIGEST_LENGTH) todo = SHA512_DIGEST_LENGTH; memcpy(k_bytes + done, digest, todo); done += todo; } if (!BN_bin2bn(k_bytes, num_k_bytes, out)) goto err; if (BN_mod(out, out, range, ctx) != 1) goto err; ret = 1; err: EVP_MD_CTX_free(mdctx); EVP_MD_free(md); OPENSSL_clear_free(k_bytes, num_k_bytes); OPENSSL_cleanse(digest, sizeof(digest)); OPENSSL_cleanse(random_bytes, sizeof(random_bytes)); OPENSSL_cleanse(private_bytes, sizeof(private_bytes)); return ret; }
./openssl/crypto/bn/bn_recp.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include "bn_local.h" void BN_RECP_CTX_init(BN_RECP_CTX *recp) { memset(recp, 0, sizeof(*recp)); bn_init(&(recp->N)); bn_init(&(recp->Nr)); } BN_RECP_CTX *BN_RECP_CTX_new(void) { BN_RECP_CTX *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; bn_init(&(ret->N)); bn_init(&(ret->Nr)); ret->flags = BN_FLG_MALLOCED; return ret; } void BN_RECP_CTX_free(BN_RECP_CTX *recp) { if (recp == NULL) return; BN_free(&recp->N); BN_free(&recp->Nr); if (recp->flags & BN_FLG_MALLOCED) OPENSSL_free(recp); } int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *d, BN_CTX *ctx) { if (BN_is_zero(d) || !BN_copy(&(recp->N), d)) return 0; BN_zero(&(recp->Nr)); recp->num_bits = BN_num_bits(d); recp->shift = 0; return 1; } int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y, BN_RECP_CTX *recp, BN_CTX *ctx) { int ret = 0; BIGNUM *a; const BIGNUM *ca; BN_CTX_start(ctx); if ((a = BN_CTX_get(ctx)) == NULL) goto err; if (y != NULL) { if (x == y) { if (!BN_sqr(a, x, ctx)) goto err; } else { if (!BN_mul(a, x, y, ctx)) goto err; } ca = a; } else ca = x; /* Just do the mod */ ret = BN_div_recp(NULL, r, ca, recp, ctx); err: BN_CTX_end(ctx); bn_check_top(r); return ret; } int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, BN_RECP_CTX *recp, BN_CTX *ctx) { int i, j, ret = 0; BIGNUM *a, *b, *d, *r; BN_CTX_start(ctx); d = (dv != NULL) ? dv : BN_CTX_get(ctx); r = (rem != NULL) ? rem : BN_CTX_get(ctx); a = BN_CTX_get(ctx); b = BN_CTX_get(ctx); if (b == NULL) goto err; if (BN_ucmp(m, &(recp->N)) < 0) { BN_zero(d); if (!BN_copy(r, m)) { BN_CTX_end(ctx); return 0; } BN_CTX_end(ctx); return 1; } /* * We want the remainder Given input of ABCDEF / ab we need multiply * ABCDEF by 3 digests of the reciprocal of ab */ /* i := max(BN_num_bits(m), 2*BN_num_bits(N)) */ i = BN_num_bits(m); j = recp->num_bits << 1; if (j > i) i = j; /* Nr := round(2^i / N) */ if (i != recp->shift) recp->shift = BN_reciprocal(&(recp->Nr), &(recp->N), i, ctx); /* BN_reciprocal could have returned -1 for an error */ if (recp->shift == -1) goto err; /*- * d := |round(round(m / 2^BN_num_bits(N)) * recp->Nr / 2^(i - BN_num_bits(N)))| * = |round(round(m / 2^BN_num_bits(N)) * round(2^i / N) / 2^(i - BN_num_bits(N)))| * <= |(m / 2^BN_num_bits(N)) * (2^i / N) * (2^BN_num_bits(N) / 2^i)| * = |m/N| */ if (!BN_rshift(a, m, recp->num_bits)) goto err; if (!BN_mul(b, a, &(recp->Nr), ctx)) goto err; if (!BN_rshift(d, b, i - recp->num_bits)) goto err; d->neg = 0; if (!BN_mul(b, &(recp->N), d, ctx)) goto err; if (!BN_usub(r, m, b)) goto err; r->neg = 0; j = 0; while (BN_ucmp(r, &(recp->N)) >= 0) { if (j++ > 2) { ERR_raise(ERR_LIB_BN, BN_R_BAD_RECIPROCAL); goto err; } if (!BN_usub(r, r, &(recp->N))) goto err; if (!BN_add_word(d, 1)) goto err; } r->neg = BN_is_zero(r) ? 0 : m->neg; d->neg = m->neg ^ recp->N.neg; ret = 1; err: BN_CTX_end(ctx); bn_check_top(dv); bn_check_top(rem); return ret; } /* * len is the expected size of the result We actually calculate with an extra * word of precision, so we can do faster division if the remainder is not * required. */ /* r := 2^len / m */ int BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx) { int ret = -1; BIGNUM *t; BN_CTX_start(ctx); if ((t = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_set_bit(t, len)) goto err; if (!BN_div(r, NULL, t, m, ctx)) goto err; ret = len; err: bn_check_top(r); BN_CTX_end(ctx); return ret; }
./openssl/crypto/bn/bn_intern.c
/* * Copyright 2014-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include "bn_local.h" /* * Determine the modified width-(w+1) Non-Adjacent Form (wNAF) of 'scalar'. * This is an array r[] of values that are either zero or odd with an * absolute value less than 2^w satisfying * scalar = \sum_j r[j]*2^j * where at most one of any w+1 consecutive digits is non-zero * with the exception that the most significant digit may be only * w-1 zeros away from that next non-zero digit. */ signed char *bn_compute_wNAF(const BIGNUM *scalar, int w, size_t *ret_len) { int window_val; signed char *r = NULL; int sign = 1; int bit, next_bit, mask; size_t len = 0, j; if (BN_is_zero(scalar)) { r = OPENSSL_malloc(1); if (r == NULL) goto err; r[0] = 0; *ret_len = 1; return r; } if (w <= 0 || w > 7) { /* 'signed char' can represent integers with * absolute values less than 2^7 */ ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } bit = 1 << w; /* at most 128 */ next_bit = bit << 1; /* at most 256 */ mask = next_bit - 1; /* at most 255 */ if (BN_is_negative(scalar)) { sign = -1; } if (scalar->d == NULL || scalar->top == 0) { ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } len = BN_num_bits(scalar); r = OPENSSL_malloc(len + 1); /* * Modified wNAF may be one digit longer than binary representation * (*ret_len will be set to the actual length, i.e. at most * BN_num_bits(scalar) + 1) */ if (r == NULL) goto err; window_val = scalar->d[0] & mask; j = 0; while ((window_val != 0) || (j + w + 1 < len)) { /* if j+w+1 >= len, * window_val will not * increase */ int digit = 0; /* 0 <= window_val <= 2^(w+1) */ if (window_val & 1) { /* 0 < window_val < 2^(w+1) */ if (window_val & bit) { digit = window_val - next_bit; /* -2^w < digit < 0 */ #if 1 /* modified wNAF */ if (j + w + 1 >= len) { /* * Special case for generating modified wNAFs: * no new bits will be added into window_val, * so using a positive digit here will decrease * the total length of the representation */ digit = window_val & (mask >> 1); /* 0 < digit < 2^w */ } #endif } else { digit = window_val; /* 0 < digit < 2^w */ } if (digit <= -bit || digit >= bit || !(digit & 1)) { ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } window_val -= digit; /* * now window_val is 0 or 2^(w+1) in standard wNAF generation; * for modified window NAFs, it may also be 2^w */ if (window_val != 0 && window_val != next_bit && window_val != bit) { ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } } r[j++] = sign * digit; window_val >>= 1; window_val += bit * BN_is_bit_set(scalar, j + w); if (window_val > next_bit) { ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } } if (j > len + 1) { ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } *ret_len = j; return r; err: OPENSSL_free(r); return NULL; } int bn_get_top(const BIGNUM *a) { return a->top; } int bn_get_dmax(const BIGNUM *a) { return a->dmax; } void bn_set_all_zero(BIGNUM *a) { int i; for (i = a->top; i < a->dmax; i++) a->d[i] = 0; } int bn_copy_words(BN_ULONG *out, const BIGNUM *in, int size) { if (in->top > size) return 0; memset(out, 0, sizeof(*out) * size); if (in->d != NULL) memcpy(out, in->d, sizeof(*out) * in->top); return 1; } BN_ULONG *bn_get_words(const BIGNUM *a) { return a->d; } void bn_set_static_words(BIGNUM *a, const BN_ULONG *words, int size) { /* * |const| qualifier omission is compensated by BN_FLG_STATIC_DATA * flag, which effectively means "read-only data". */ a->d = (BN_ULONG *)words; a->dmax = a->top = size; a->neg = 0; a->flags |= BN_FLG_STATIC_DATA; bn_correct_top(a); } int bn_set_words(BIGNUM *a, const BN_ULONG *words, int num_words) { if (bn_wexpand(a, num_words) == NULL) { ERR_raise(ERR_LIB_BN, ERR_R_BN_LIB); return 0; } memcpy(a->d, words, sizeof(BN_ULONG) * num_words); a->top = num_words; bn_correct_top(a); return 1; }
./openssl/crypto/bn/bn_prime.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include "bn_local.h" /* * The quick sieve algorithm approach to weeding out primes is Philip * Zimmermann's, as implemented in PGP. I have had a read of his comments * and implemented my own version. */ #include "bn_prime.h" static int probable_prime(BIGNUM *rnd, int bits, int safe, prime_t *mods, BN_CTX *ctx); static int probable_prime_dh(BIGNUM *rnd, int bits, int safe, prime_t *mods, const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx); static int bn_is_prime_int(const BIGNUM *w, int checks, BN_CTX *ctx, int do_trial_division, BN_GENCB *cb); #define square(x) ((BN_ULONG)(x) * (BN_ULONG)(x)) #if BN_BITS2 == 64 # define BN_DEF(lo, hi) (BN_ULONG)hi<<32|lo #else # define BN_DEF(lo, hi) lo, hi #endif /* * See SP800 89 5.3.3 (Step f) * The product of the set of primes ranging from 3 to 751 * Generated using process in test/bn_internal_test.c test_bn_small_factors(). * This includes 751 (which is not currently included in SP 800-89). */ static const BN_ULONG small_prime_factors[] = { BN_DEF(0x3ef4e3e1, 0xc4309333), BN_DEF(0xcd2d655f, 0x71161eb6), BN_DEF(0x0bf94862, 0x95e2238c), BN_DEF(0x24f7912b, 0x3eb233d3), BN_DEF(0xbf26c483, 0x6b55514b), BN_DEF(0x5a144871, 0x0a84d817), BN_DEF(0x9b82210a, 0x77d12fee), BN_DEF(0x97f050b3, 0xdb5b93c2), BN_DEF(0x4d6c026b, 0x4acad6b9), BN_DEF(0x54aec893, 0xeb7751f3), BN_DEF(0x36bc85c4, 0xdba53368), BN_DEF(0x7f5ec78e, 0xd85a1b28), BN_DEF(0x6b322244, 0x2eb072d8), BN_DEF(0x5e2b3aea, 0xbba51112), BN_DEF(0x0e2486bf, 0x36ed1a6c), BN_DEF(0xec0c5727, 0x5f270460), (BN_ULONG)0x000017b1 }; #define BN_SMALL_PRIME_FACTORS_TOP OSSL_NELEM(small_prime_factors) static const BIGNUM _bignum_small_prime_factors = { (BN_ULONG *)small_prime_factors, BN_SMALL_PRIME_FACTORS_TOP, BN_SMALL_PRIME_FACTORS_TOP, 0, BN_FLG_STATIC_DATA }; const BIGNUM *ossl_bn_get0_small_factors(void) { return &_bignum_small_prime_factors; } /* * Calculate the number of trial divisions that gives the best speed in * combination with Miller-Rabin prime test, based on the sized of the prime. */ static int calc_trial_divisions(int bits) { if (bits <= 512) return 64; else if (bits <= 1024) return 128; else if (bits <= 2048) return 384; else if (bits <= 4096) return 1024; return NUMPRIMES; } /* * Use a minimum of 64 rounds of Miller-Rabin, which should give a false * positive rate of 2^-128. If the size of the prime is larger than 2048 * the user probably wants a higher security level than 128, so switch * to 128 rounds giving a false positive rate of 2^-256. * Returns the number of rounds. */ static int bn_mr_min_checks(int bits) { if (bits > 2048) return 128; return 64; } int BN_GENCB_call(BN_GENCB *cb, int a, int b) { /* No callback means continue */ if (!cb) return 1; switch (cb->ver) { case 1: /* Deprecated-style callbacks */ if (!cb->cb.cb_1) return 1; cb->cb.cb_1(a, b, cb->arg); return 1; case 2: /* New-style callbacks */ return cb->cb.cb_2(a, b, cb); default: break; } /* Unrecognised callback type */ return 0; } int BN_generate_prime_ex2(BIGNUM *ret, int bits, int safe, const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb, BN_CTX *ctx) { BIGNUM *t; int found = 0; int i, j, c1 = 0; prime_t *mods = NULL; int checks = bn_mr_min_checks(bits); if (bits < 2) { /* There are no prime numbers this small. */ ERR_raise(ERR_LIB_BN, BN_R_BITS_TOO_SMALL); return 0; } else if (add == NULL && safe && bits < 6 && bits != 3) { /* * The smallest safe prime (7) is three bits. * But the following two safe primes with less than 6 bits (11, 23) * are unreachable for BN_rand with BN_RAND_TOP_TWO. */ ERR_raise(ERR_LIB_BN, BN_R_BITS_TOO_SMALL); return 0; } mods = OPENSSL_zalloc(sizeof(*mods) * NUMPRIMES); if (mods == NULL) return 0; BN_CTX_start(ctx); t = BN_CTX_get(ctx); if (t == NULL) goto err; loop: /* make a random number and set the top and bottom bits */ if (add == NULL) { if (!probable_prime(ret, bits, safe, mods, ctx)) goto err; } else { if (!probable_prime_dh(ret, bits, safe, mods, add, rem, ctx)) goto err; } if (!BN_GENCB_call(cb, 0, c1++)) /* aborted */ goto err; if (!safe) { i = bn_is_prime_int(ret, checks, ctx, 0, cb); if (i == -1) goto err; if (i == 0) goto loop; } else { /* * for "safe prime" generation, check that (p-1)/2 is prime. Since a * prime is odd, We just need to divide by 2 */ if (!BN_rshift1(t, ret)) goto err; for (i = 0; i < checks; i++) { j = bn_is_prime_int(ret, 1, ctx, 0, cb); if (j == -1) goto err; if (j == 0) goto loop; j = bn_is_prime_int(t, 1, ctx, 0, cb); if (j == -1) goto err; if (j == 0) goto loop; if (!BN_GENCB_call(cb, 2, c1 - 1)) goto err; /* We have a safe prime test pass */ } } /* we have a prime :-) */ found = 1; err: OPENSSL_free(mods); BN_CTX_end(ctx); bn_check_top(ret); return found; } #ifndef FIPS_MODULE int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe, const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb) { BN_CTX *ctx = BN_CTX_new(); int retval; if (ctx == NULL) return 0; retval = BN_generate_prime_ex2(ret, bits, safe, add, rem, cb, ctx); BN_CTX_free(ctx); return retval; } #endif #ifndef OPENSSL_NO_DEPRECATED_3_0 int BN_is_prime_ex(const BIGNUM *a, int checks, BN_CTX *ctx_passed, BN_GENCB *cb) { return ossl_bn_check_prime(a, checks, ctx_passed, 0, cb); } int BN_is_prime_fasttest_ex(const BIGNUM *w, int checks, BN_CTX *ctx, int do_trial_division, BN_GENCB *cb) { return ossl_bn_check_prime(w, checks, ctx, do_trial_division, cb); } #endif /* Wrapper around bn_is_prime_int that sets the minimum number of checks */ int ossl_bn_check_prime(const BIGNUM *w, int checks, BN_CTX *ctx, int do_trial_division, BN_GENCB *cb) { int min_checks = bn_mr_min_checks(BN_num_bits(w)); if (checks < min_checks) checks = min_checks; return bn_is_prime_int(w, checks, ctx, do_trial_division, cb); } /* * Use this only for key generation. * It always uses trial division. The number of checks * (MR rounds) passed in is used without being clamped to a minimum value. */ int ossl_bn_check_generated_prime(const BIGNUM *w, int checks, BN_CTX *ctx, BN_GENCB *cb) { return bn_is_prime_int(w, checks, ctx, 1, cb); } int BN_check_prime(const BIGNUM *p, BN_CTX *ctx, BN_GENCB *cb) { return ossl_bn_check_prime(p, 0, ctx, 1, cb); } /* * Tests that |w| is probably prime * See FIPS 186-4 C.3.1 Miller Rabin Probabilistic Primality Test. * * Returns 0 when composite, 1 when probable prime, -1 on error. */ static int bn_is_prime_int(const BIGNUM *w, int checks, BN_CTX *ctx, int do_trial_division, BN_GENCB *cb) { int i, status, ret = -1; #ifndef FIPS_MODULE BN_CTX *ctxlocal = NULL; #else if (ctx == NULL) return -1; #endif /* w must be bigger than 1 */ if (BN_cmp(w, BN_value_one()) <= 0) return 0; /* w must be odd */ if (BN_is_odd(w)) { /* Take care of the really small prime 3 */ if (BN_is_word(w, 3)) return 1; } else { /* 2 is the only even prime */ return BN_is_word(w, 2); } /* first look for small factors */ if (do_trial_division) { int trial_divisions = calc_trial_divisions(BN_num_bits(w)); for (i = 1; i < trial_divisions; i++) { BN_ULONG mod = BN_mod_word(w, primes[i]); if (mod == (BN_ULONG)-1) return -1; if (mod == 0) return BN_is_word(w, primes[i]); } if (!BN_GENCB_call(cb, 1, -1)) return -1; } #ifndef FIPS_MODULE if (ctx == NULL && (ctxlocal = ctx = BN_CTX_new()) == NULL) goto err; #endif if (!ossl_bn_miller_rabin_is_prime(w, checks, ctx, cb, 0, &status)) { ret = -1; goto err; } ret = (status == BN_PRIMETEST_PROBABLY_PRIME); err: #ifndef FIPS_MODULE BN_CTX_free(ctxlocal); #endif return ret; } /* * Refer to FIPS 186-4 C.3.2 Enhanced Miller-Rabin Probabilistic Primality Test. * OR C.3.1 Miller-Rabin Probabilistic Primality Test (if enhanced is zero). * The Step numbers listed in the code refer to the enhanced case. * * if enhanced is set, then status returns one of the following: * BN_PRIMETEST_PROBABLY_PRIME * BN_PRIMETEST_COMPOSITE_WITH_FACTOR * BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME * if enhanced is zero, then status returns either * BN_PRIMETEST_PROBABLY_PRIME or * BN_PRIMETEST_COMPOSITE * * returns 0 if there was an error, otherwise it returns 1. */ int ossl_bn_miller_rabin_is_prime(const BIGNUM *w, int iterations, BN_CTX *ctx, BN_GENCB *cb, int enhanced, int *status) { int i, j, a, ret = 0; BIGNUM *g, *w1, *w3, *x, *m, *z, *b; BN_MONT_CTX *mont = NULL; /* w must be odd */ if (!BN_is_odd(w)) return 0; BN_CTX_start(ctx); g = BN_CTX_get(ctx); w1 = BN_CTX_get(ctx); w3 = BN_CTX_get(ctx); x = BN_CTX_get(ctx); m = BN_CTX_get(ctx); z = BN_CTX_get(ctx); b = BN_CTX_get(ctx); if (!(b != NULL /* w1 := w - 1 */ && BN_copy(w1, w) && BN_sub_word(w1, 1) /* w3 := w - 3 */ && BN_copy(w3, w) && BN_sub_word(w3, 3))) goto err; /* check w is larger than 3, otherwise the random b will be too small */ if (BN_is_zero(w3) || BN_is_negative(w3)) goto err; /* (Step 1) Calculate largest integer 'a' such that 2^a divides w-1 */ a = 1; while (!BN_is_bit_set(w1, a)) a++; /* (Step 2) m = (w-1) / 2^a */ if (!BN_rshift(m, w1, a)) goto err; /* Montgomery setup for computations mod a */ mont = BN_MONT_CTX_new(); if (mont == NULL || !BN_MONT_CTX_set(mont, w, ctx)) goto err; if (iterations == 0) iterations = bn_mr_min_checks(BN_num_bits(w)); /* (Step 4) */ for (i = 0; i < iterations; ++i) { /* (Step 4.1) obtain a Random string of bits b where 1 < b < w-1 */ if (!BN_priv_rand_range_ex(b, w3, 0, ctx) || !BN_add_word(b, 2)) /* 1 < b < w-1 */ goto err; if (enhanced) { /* (Step 4.3) */ if (!BN_gcd(g, b, w, ctx)) goto err; /* (Step 4.4) */ if (!BN_is_one(g)) { *status = BN_PRIMETEST_COMPOSITE_WITH_FACTOR; ret = 1; goto err; } } /* (Step 4.5) z = b^m mod w */ if (!BN_mod_exp_mont(z, b, m, w, ctx, mont)) goto err; /* (Step 4.6) if (z = 1 or z = w-1) */ if (BN_is_one(z) || BN_cmp(z, w1) == 0) goto outer_loop; /* (Step 4.7) for j = 1 to a-1 */ for (j = 1; j < a ; ++j) { /* (Step 4.7.1 - 4.7.2) x = z. z = x^2 mod w */ if (!BN_copy(x, z) || !BN_mod_mul(z, x, x, w, ctx)) goto err; /* (Step 4.7.3) */ if (BN_cmp(z, w1) == 0) goto outer_loop; /* (Step 4.7.4) */ if (BN_is_one(z)) goto composite; } /* At this point z = b^((w-1)/2) mod w */ /* (Steps 4.8 - 4.9) x = z, z = x^2 mod w */ if (!BN_copy(x, z) || !BN_mod_mul(z, x, x, w, ctx)) goto err; /* (Step 4.10) */ if (BN_is_one(z)) goto composite; /* (Step 4.11) x = b^(w-1) mod w */ if (!BN_copy(x, z)) goto err; composite: if (enhanced) { /* (Step 4.1.2) g = GCD(x-1, w) */ if (!BN_sub_word(x, 1) || !BN_gcd(g, x, w, ctx)) goto err; /* (Steps 4.1.3 - 4.1.4) */ if (BN_is_one(g)) *status = BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME; else *status = BN_PRIMETEST_COMPOSITE_WITH_FACTOR; } else { *status = BN_PRIMETEST_COMPOSITE; } ret = 1; goto err; outer_loop: ; /* (Step 4.1.5) */ if (!BN_GENCB_call(cb, 1, i)) goto err; } /* (Step 5) */ *status = BN_PRIMETEST_PROBABLY_PRIME; ret = 1; err: BN_clear(g); BN_clear(w1); BN_clear(w3); BN_clear(x); BN_clear(m); BN_clear(z); BN_clear(b); BN_CTX_end(ctx); BN_MONT_CTX_free(mont); return ret; } /* * Generate a random number of |bits| bits that is probably prime by sieving. * If |safe| != 0, it generates a safe prime. * |mods| is a preallocated array that gets reused when called again. * * The probably prime is saved in |rnd|. * * Returns 1 on success and 0 on error. */ static int probable_prime(BIGNUM *rnd, int bits, int safe, prime_t *mods, BN_CTX *ctx) { int i; BN_ULONG delta; int trial_divisions = calc_trial_divisions(bits); BN_ULONG maxdelta = BN_MASK2 - primes[trial_divisions - 1]; again: if (!BN_priv_rand_ex(rnd, bits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ODD, 0, ctx)) return 0; if (safe && !BN_set_bit(rnd, 1)) return 0; /* we now have a random number 'rnd' to test. */ for (i = 1; i < trial_divisions; i++) { BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]); if (mod == (BN_ULONG)-1) return 0; mods[i] = (prime_t) mod; } delta = 0; loop: for (i = 1; i < trial_divisions; i++) { /* * check that rnd is a prime and also that * gcd(rnd-1,primes) == 1 (except for 2) * do the second check only if we are interested in safe primes * in the case that the candidate prime is a single word then * we check only the primes up to sqrt(rnd) */ if (bits <= 31 && delta <= 0x7fffffff && square(primes[i]) > BN_get_word(rnd) + delta) break; if (safe ? (mods[i] + delta) % primes[i] <= 1 : (mods[i] + delta) % primes[i] == 0) { delta += safe ? 4 : 2; if (delta > maxdelta) goto again; goto loop; } } if (!BN_add_word(rnd, delta)) return 0; if (BN_num_bits(rnd) != bits) goto again; bn_check_top(rnd); return 1; } /* * Generate a random number |rnd| of |bits| bits that is probably prime * and satisfies |rnd| % |add| == |rem| by sieving. * If |safe| != 0, it generates a safe prime. * |mods| is a preallocated array that gets reused when called again. * * Returns 1 on success and 0 on error. */ static int probable_prime_dh(BIGNUM *rnd, int bits, int safe, prime_t *mods, const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx) { int i, ret = 0; BIGNUM *t1; BN_ULONG delta; int trial_divisions = calc_trial_divisions(bits); BN_ULONG maxdelta = BN_MASK2 - primes[trial_divisions - 1]; BN_CTX_start(ctx); if ((t1 = BN_CTX_get(ctx)) == NULL) goto err; if (maxdelta > BN_MASK2 - BN_get_word(add)) maxdelta = BN_MASK2 - BN_get_word(add); again: if (!BN_rand_ex(rnd, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD, 0, ctx)) goto err; /* we need ((rnd-rem) % add) == 0 */ if (!BN_mod(t1, rnd, add, ctx)) goto err; if (!BN_sub(rnd, rnd, t1)) goto err; if (rem == NULL) { if (!BN_add_word(rnd, safe ? 3u : 1u)) goto err; } else { if (!BN_add(rnd, rnd, rem)) goto err; } if (BN_num_bits(rnd) < bits || BN_get_word(rnd) < (safe ? 5u : 3u)) { if (!BN_add(rnd, rnd, add)) goto err; } /* we now have a random number 'rnd' to test. */ for (i = 1; i < trial_divisions; i++) { BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]); if (mod == (BN_ULONG)-1) goto err; mods[i] = (prime_t) mod; } delta = 0; loop: for (i = 1; i < trial_divisions; i++) { /* check that rnd is a prime */ if (bits <= 31 && delta <= 0x7fffffff && square(primes[i]) > BN_get_word(rnd) + delta) break; /* rnd mod p == 1 implies q = (rnd-1)/2 is divisible by p */ if (safe ? (mods[i] + delta) % primes[i] <= 1 : (mods[i] + delta) % primes[i] == 0) { delta += BN_get_word(add); if (delta > maxdelta) goto again; goto loop; } } if (!BN_add_word(rnd, delta)) goto err; ret = 1; err: BN_CTX_end(ctx); bn_check_top(rnd); return ret; }
./openssl/crypto/bn/bn_const.c
/* * Copyright 2005-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/bn.h> #include "crypto/bn_dh.h" #define COPY_BN(dst, src) (dst != NULL) ? BN_copy(dst, &src) : BN_dup(&src) /*- * "First Oakley Default Group" from RFC2409, section 6.1. * * The prime is: 2^768 - 2 ^704 - 1 + 2^64 * { [2^638 pi] + 149686 } * * RFC2409 specifies a generator of 2. * RFC2412 specifies a generator of 22. */ BIGNUM *BN_get_rfc2409_prime_768(BIGNUM *bn) { static const unsigned char RFC2409_PRIME_768[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x3A, 0x36, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; return BN_bin2bn(RFC2409_PRIME_768, sizeof(RFC2409_PRIME_768), bn); } /*- * "Second Oakley Default Group" from RFC2409, section 6.2. * * The prime is: 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }. * * RFC2409 specifies a generator of 2. * RFC2412 specifies a generator of 22. */ BIGNUM *BN_get_rfc2409_prime_1024(BIGNUM *bn) { static const unsigned char RFC2409_PRIME_1024[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE6, 0x53, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; return BN_bin2bn(RFC2409_PRIME_1024, sizeof(RFC2409_PRIME_1024), bn); } /*- * "1536-bit MODP Group" from RFC3526, Section 2. * * The prime is: 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 } * * RFC3526 specifies a generator of 2. * RFC2312 specifies a generator of 22. */ BIGNUM *BN_get_rfc3526_prime_1536(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_1536_p); } /*- * "2048-bit MODP Group" from RFC3526, Section 3. * * The prime is: 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 } * * RFC3526 specifies a generator of 2. */ BIGNUM *BN_get_rfc3526_prime_2048(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_2048_p); } /*- * "3072-bit MODP Group" from RFC3526, Section 4. * * The prime is: 2^3072 - 2^3008 - 1 + 2^64 * { [2^2942 pi] + 1690314 } * * RFC3526 specifies a generator of 2. */ BIGNUM *BN_get_rfc3526_prime_3072(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_3072_p); } /*- * "4096-bit MODP Group" from RFC3526, Section 5. * * The prime is: 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 } * * RFC3526 specifies a generator of 2. */ BIGNUM *BN_get_rfc3526_prime_4096(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_4096_p); } /*- * "6144-bit MODP Group" from RFC3526, Section 6. * * The prime is: 2^6144 - 2^6080 - 1 + 2^64 * { [2^6014 pi] + 929484 } * * RFC3526 specifies a generator of 2. */ BIGNUM *BN_get_rfc3526_prime_6144(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_6144_p); } /*- * "8192-bit MODP Group" from RFC3526, Section 7. * * The prime is: 2^8192 - 2^8128 - 1 + 2^64 * { [2^8062 pi] + 4743158 } * * RFC3526 specifies a generator of 2. */ BIGNUM *BN_get_rfc3526_prime_8192(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_8192_p); }
./openssl/crypto/bn/bn_nist.c
/* * Copyright 2002-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 "bn_local.h" #include "internal/cryptlib.h" #define BN_NIST_192_TOP (192+BN_BITS2-1)/BN_BITS2 #define BN_NIST_224_TOP (224+BN_BITS2-1)/BN_BITS2 #define BN_NIST_256_TOP (256+BN_BITS2-1)/BN_BITS2 #define BN_NIST_384_TOP (384+BN_BITS2-1)/BN_BITS2 #define BN_NIST_521_TOP (521+BN_BITS2-1)/BN_BITS2 /* pre-computed tables are "carry-less" values of modulus*(i+1) */ #if BN_BITS2 == 64 static const BN_ULONG _nist_p_192[][BN_NIST_192_TOP] = { {0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFEULL, 0xFFFFFFFFFFFFFFFFULL}, {0xFFFFFFFFFFFFFFFEULL, 0xFFFFFFFFFFFFFFFDULL, 0xFFFFFFFFFFFFFFFFULL}, {0xFFFFFFFFFFFFFFFDULL, 0xFFFFFFFFFFFFFFFCULL, 0xFFFFFFFFFFFFFFFFULL} }; static const BN_ULONG _nist_p_192_sqr[] = { 0x0000000000000001ULL, 0x0000000000000002ULL, 0x0000000000000001ULL, 0xFFFFFFFFFFFFFFFEULL, 0xFFFFFFFFFFFFFFFDULL, 0xFFFFFFFFFFFFFFFFULL }; static const BN_ULONG _nist_p_224[][BN_NIST_224_TOP] = { {0x0000000000000001ULL, 0xFFFFFFFF00000000ULL, 0xFFFFFFFFFFFFFFFFULL, 0x00000000FFFFFFFFULL}, {0x0000000000000002ULL, 0xFFFFFFFE00000000ULL, 0xFFFFFFFFFFFFFFFFULL, 0x00000001FFFFFFFFULL} /* this one is * "carry-full" */ }; static const BN_ULONG _nist_p_224_sqr[] = { 0x0000000000000001ULL, 0xFFFFFFFE00000000ULL, 0xFFFFFFFFFFFFFFFFULL, 0x0000000200000000ULL, 0x0000000000000000ULL, 0xFFFFFFFFFFFFFFFEULL, 0xFFFFFFFFFFFFFFFFULL }; static const BN_ULONG _nist_p_256[][BN_NIST_256_TOP] = { {0xFFFFFFFFFFFFFFFFULL, 0x00000000FFFFFFFFULL, 0x0000000000000000ULL, 0xFFFFFFFF00000001ULL}, {0xFFFFFFFFFFFFFFFEULL, 0x00000001FFFFFFFFULL, 0x0000000000000000ULL, 0xFFFFFFFE00000002ULL}, {0xFFFFFFFFFFFFFFFDULL, 0x00000002FFFFFFFFULL, 0x0000000000000000ULL, 0xFFFFFFFD00000003ULL}, {0xFFFFFFFFFFFFFFFCULL, 0x00000003FFFFFFFFULL, 0x0000000000000000ULL, 0xFFFFFFFC00000004ULL}, {0xFFFFFFFFFFFFFFFBULL, 0x00000004FFFFFFFFULL, 0x0000000000000000ULL, 0xFFFFFFFB00000005ULL}, }; static const BN_ULONG _nist_p_256_sqr[] = { 0x0000000000000001ULL, 0xFFFFFFFE00000000ULL, 0xFFFFFFFFFFFFFFFFULL, 0x00000001FFFFFFFEULL, 0x00000001FFFFFFFEULL, 0x00000001FFFFFFFEULL, 0xFFFFFFFE00000001ULL, 0xFFFFFFFE00000002ULL }; static const BN_ULONG _nist_p_384[][BN_NIST_384_TOP] = { {0x00000000FFFFFFFFULL, 0xFFFFFFFF00000000ULL, 0xFFFFFFFFFFFFFFFEULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL}, {0x00000001FFFFFFFEULL, 0xFFFFFFFE00000000ULL, 0xFFFFFFFFFFFFFFFDULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL}, {0x00000002FFFFFFFDULL, 0xFFFFFFFD00000000ULL, 0xFFFFFFFFFFFFFFFCULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL}, {0x00000003FFFFFFFCULL, 0xFFFFFFFC00000000ULL, 0xFFFFFFFFFFFFFFFBULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL}, {0x00000004FFFFFFFBULL, 0xFFFFFFFB00000000ULL, 0xFFFFFFFFFFFFFFFAULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL}, }; static const BN_ULONG _nist_p_384_sqr[] = { 0xFFFFFFFE00000001ULL, 0x0000000200000000ULL, 0xFFFFFFFE00000000ULL, 0x0000000200000000ULL, 0x0000000000000001ULL, 0x0000000000000000ULL, 0x00000001FFFFFFFEULL, 0xFFFFFFFE00000000ULL, 0xFFFFFFFFFFFFFFFDULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL }; static const BN_ULONG _nist_p_521[] = { 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0x00000000000001FFULL }; static const BN_ULONG _nist_p_521_sqr[] = { 0x0000000000000001ULL, 0x0000000000000000ULL, 0x0000000000000000ULL, 0x0000000000000000ULL, 0x0000000000000000ULL, 0x0000000000000000ULL, 0x0000000000000000ULL, 0x0000000000000000ULL, 0xFFFFFFFFFFFFFC00ULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0x000000000003FFFFULL }; #elif BN_BITS2 == 32 static const BN_ULONG _nist_p_192[][BN_NIST_192_TOP] = { {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, {0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFD, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, {0xFFFFFFFD, 0xFFFFFFFF, 0xFFFFFFFC, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF} }; static const BN_ULONG _nist_p_192_sqr[] = { 0x00000001, 0x00000000, 0x00000002, 0x00000000, 0x00000001, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFD, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; static const BN_ULONG _nist_p_224[][BN_NIST_224_TOP] = { {0x00000001, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, {0x00000002, 0x00000000, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF} }; static const BN_ULONG _nist_p_224_sqr[] = { 0x00000001, 0x00000000, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000002, 0x00000000, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; static const BN_ULONG _nist_p_256[][BN_NIST_256_TOP] = { {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF}, {0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000001, 0x00000000, 0x00000000, 0x00000002, 0xFFFFFFFE}, {0xFFFFFFFD, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000002, 0x00000000, 0x00000000, 0x00000003, 0xFFFFFFFD}, {0xFFFFFFFC, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000003, 0x00000000, 0x00000000, 0x00000004, 0xFFFFFFFC}, {0xFFFFFFFB, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000004, 0x00000000, 0x00000000, 0x00000005, 0xFFFFFFFB}, }; static const BN_ULONG _nist_p_256_sqr[] = { 0x00000001, 0x00000000, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 0x00000001, 0xFFFFFFFE, 0x00000001, 0xFFFFFFFE, 0x00000001, 0x00000001, 0xFFFFFFFE, 0x00000002, 0xFFFFFFFE }; static const BN_ULONG _nist_p_384[][BN_NIST_384_TOP] = { {0xFFFFFFFF, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, {0xFFFFFFFE, 0x00000001, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, {0xFFFFFFFD, 0x00000002, 0x00000000, 0xFFFFFFFD, 0xFFFFFFFC, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, {0xFFFFFFFC, 0x00000003, 0x00000000, 0xFFFFFFFC, 0xFFFFFFFB, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, {0xFFFFFFFB, 0x00000004, 0x00000000, 0xFFFFFFFB, 0xFFFFFFFA, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, }; static const BN_ULONG _nist_p_384_sqr[] = { 0x00000001, 0xFFFFFFFE, 0x00000000, 0x00000002, 0x00000000, 0xFFFFFFFE, 0x00000000, 0x00000002, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFE, 0x00000001, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; static const BN_ULONG _nist_p_521[] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x000001FF }; static const BN_ULONG _nist_p_521_sqr[] = { 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFC00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0003FFFF }; #else # error "unsupported BN_BITS2" #endif static const BIGNUM ossl_bignum_nist_p_192 = { (BN_ULONG *)_nist_p_192[0], BN_NIST_192_TOP, BN_NIST_192_TOP, 0, BN_FLG_STATIC_DATA }; static const BIGNUM ossl_bignum_nist_p_224 = { (BN_ULONG *)_nist_p_224[0], BN_NIST_224_TOP, BN_NIST_224_TOP, 0, BN_FLG_STATIC_DATA }; static const BIGNUM ossl_bignum_nist_p_256 = { (BN_ULONG *)_nist_p_256[0], BN_NIST_256_TOP, BN_NIST_256_TOP, 0, BN_FLG_STATIC_DATA }; static const BIGNUM ossl_bignum_nist_p_384 = { (BN_ULONG *)_nist_p_384[0], BN_NIST_384_TOP, BN_NIST_384_TOP, 0, BN_FLG_STATIC_DATA }; static const BIGNUM ossl_bignum_nist_p_521 = { (BN_ULONG *)_nist_p_521, BN_NIST_521_TOP, BN_NIST_521_TOP, 0, BN_FLG_STATIC_DATA }; const BIGNUM *BN_get0_nist_prime_192(void) { return &ossl_bignum_nist_p_192; } const BIGNUM *BN_get0_nist_prime_224(void) { return &ossl_bignum_nist_p_224; } const BIGNUM *BN_get0_nist_prime_256(void) { return &ossl_bignum_nist_p_256; } const BIGNUM *BN_get0_nist_prime_384(void) { return &ossl_bignum_nist_p_384; } const BIGNUM *BN_get0_nist_prime_521(void) { return &ossl_bignum_nist_p_521; } /* * To avoid more recent compilers (specifically clang-14) from treating this * code as a violation of the strict aliasing conditions and omitting it, this * cannot be declared as a function. Moreover, the dst parameter cannot be * cached in a local since this no longer references the union and again falls * foul of the strict aliasing criteria. Refer to #18225 for the initial * diagnostics and llvm/llvm-project#55255 for the later discussions with the * LLVM developers. The problem boils down to if an array in the union is * converted to a pointer or if it is used directly. * * This function was inlined regardless, so there is no space cost to be * paid for making it a macro. */ #define nist_cp_bn_0(dst, src_in, top, max) \ { \ int ii; \ const BN_ULONG *src = src_in; \ \ for (ii = 0; ii < top; ii++) \ (dst)[ii] = src[ii]; \ for (; ii < max; ii++) \ (dst)[ii] = 0; \ } static void nist_cp_bn(BN_ULONG *dst, const BN_ULONG *src, int top) { int i; for (i = 0; i < top; i++) dst[i] = src[i]; } #if BN_BITS2 == 64 # define bn_cp_64(to, n, from, m) (to)[n] = (m>=0)?((from)[m]):0; # define bn_64_set_0(to, n) (to)[n] = (BN_ULONG)0; /* * two following macros are implemented under assumption that they * are called in a sequence with *ascending* n, i.e. as they are... */ # define bn_cp_32_naked(to, n, from, m) (((n)&1)?(to[(n)/2]|=((m)&1)?(from[(m)/2]&BN_MASK2h):(from[(m)/2]<<32))\ :(to[(n)/2] =((m)&1)?(from[(m)/2]>>32):(from[(m)/2]&BN_MASK2l))) # define bn_32_set_0(to, n) (((n)&1)?(to[(n)/2]&=BN_MASK2l):(to[(n)/2]=0)); # define bn_cp_32(to,n,from,m) ((m)>=0)?bn_cp_32_naked(to,n,from,m):bn_32_set_0(to,n) # if defined(L_ENDIAN) # if defined(__arch64__) # define NIST_INT64 long # else # define NIST_INT64 long long # endif # endif #else # define bn_cp_64(to, n, from, m) \ { \ bn_cp_32(to, (n)*2, from, (m)*2); \ bn_cp_32(to, (n)*2+1, from, (m)*2+1); \ } # define bn_64_set_0(to, n) \ { \ bn_32_set_0(to, (n)*2); \ bn_32_set_0(to, (n)*2+1); \ } # define bn_cp_32(to, n, from, m) (to)[n] = (m>=0)?((from)[m]):0; # define bn_32_set_0(to, n) (to)[n] = (BN_ULONG)0; # if defined(_WIN32) && !defined(__GNUC__) # define NIST_INT64 __int64 # elif defined(BN_LLONG) # define NIST_INT64 long long # endif #endif /* BN_BITS2 != 64 */ #ifdef NIST_INT64 /* Helpers to load/store a 32-bit word (uint32_t) from/into a memory * location and avoid potential aliasing issue. */ static ossl_inline uint32_t load_u32(const void *ptr) { uint32_t tmp; memcpy(&tmp, ptr, sizeof(tmp)); return tmp; } static ossl_inline void store_lo32(void *ptr, NIST_INT64 val) { /* A cast is needed for big-endian system: on a 32-bit BE system * NIST_INT64 may be defined as well if the compiler supports 64-bit * long long. */ uint32_t tmp = (uint32_t)val; memcpy(ptr, &tmp, sizeof(tmp)); } #endif /* NIST_INT64 */ #define nist_set_192(to, from, a1, a2, a3) \ { \ bn_cp_64(to, 0, from, (a3) - 3) \ bn_cp_64(to, 1, from, (a2) - 3) \ bn_cp_64(to, 2, from, (a1) - 3) \ } int BN_nist_mod_192(BIGNUM *r, const BIGNUM *a, const BIGNUM *field, BN_CTX *ctx) { int top = a->top, i; int carry; register BN_ULONG *r_d, *a_d = a->d; union { BN_ULONG bn[BN_NIST_192_TOP]; unsigned int ui[BN_NIST_192_TOP * sizeof(BN_ULONG) / sizeof(unsigned int)]; } buf; BN_ULONG c_d[BN_NIST_192_TOP], *res; static const BIGNUM ossl_bignum_nist_p_192_sqr = { (BN_ULONG *)_nist_p_192_sqr, OSSL_NELEM(_nist_p_192_sqr), OSSL_NELEM(_nist_p_192_sqr), 0, BN_FLG_STATIC_DATA }; field = &ossl_bignum_nist_p_192; /* just to make sure */ if (BN_is_negative(a) || BN_ucmp(a, &ossl_bignum_nist_p_192_sqr) >= 0) return BN_nnmod(r, a, field, ctx); i = BN_ucmp(field, a); if (i == 0) { BN_zero(r); return 1; } else if (i > 0) return (r == a) ? 1 : (BN_copy(r, a) != NULL); if (r != a) { if (!bn_wexpand(r, BN_NIST_192_TOP)) return 0; r_d = r->d; nist_cp_bn(r_d, a_d, BN_NIST_192_TOP); } else r_d = a_d; nist_cp_bn_0(buf.bn, a_d + BN_NIST_192_TOP, top - BN_NIST_192_TOP, BN_NIST_192_TOP); #if defined(NIST_INT64) { NIST_INT64 acc; /* accumulator */ unsigned int *rp = (unsigned int *)r_d; const unsigned int *bp = (const unsigned int *)buf.ui; acc = load_u32(&rp[0]); acc += bp[3 * 2 - 6]; acc += bp[5 * 2 - 6]; store_lo32(&rp[0], acc); acc >>= 32; acc += load_u32(&rp[1]); acc += bp[3 * 2 - 5]; acc += bp[5 * 2 - 5]; store_lo32(&rp[1], acc); acc >>= 32; acc += load_u32(&rp[2]); acc += bp[3 * 2 - 6]; acc += bp[4 * 2 - 6]; acc += bp[5 * 2 - 6]; store_lo32(&rp[2], acc); acc >>= 32; acc += load_u32(&rp[3]); acc += bp[3 * 2 - 5]; acc += bp[4 * 2 - 5]; acc += bp[5 * 2 - 5]; store_lo32(&rp[3], acc); acc >>= 32; acc += load_u32(&rp[4]); acc += bp[4 * 2 - 6]; acc += bp[5 * 2 - 6]; store_lo32(&rp[4], acc); acc >>= 32; acc += load_u32(&rp[5]); acc += bp[4 * 2 - 5]; acc += bp[5 * 2 - 5]; store_lo32(&rp[5], acc); carry = (int)(acc >> 32); } #else { BN_ULONG t_d[BN_NIST_192_TOP]; nist_set_192(t_d, buf.bn, 0, 3, 3); carry = (int)bn_add_words(r_d, r_d, t_d, BN_NIST_192_TOP); nist_set_192(t_d, buf.bn, 4, 4, 0); carry += (int)bn_add_words(r_d, r_d, t_d, BN_NIST_192_TOP); nist_set_192(t_d, buf.bn, 5, 5, 5) carry += (int)bn_add_words(r_d, r_d, t_d, BN_NIST_192_TOP); } #endif if (carry > 0) carry = (int)bn_sub_words(r_d, r_d, _nist_p_192[carry - 1], BN_NIST_192_TOP); else carry = 1; /* * we need 'if (carry==0 || result>=modulus) result-=modulus;' * as comparison implies subtraction, we can write * 'tmp=result-modulus; if (!carry || !borrow) result=tmp;' * this is what happens below, but without explicit if:-) a. */ res = (bn_sub_words(c_d, r_d, _nist_p_192[0], BN_NIST_192_TOP) && carry) ? r_d : c_d; nist_cp_bn(r_d, res, BN_NIST_192_TOP); r->top = BN_NIST_192_TOP; bn_correct_top(r); return 1; } typedef BN_ULONG (*bn_addsub_f) (BN_ULONG *, const BN_ULONG *, const BN_ULONG *, int); #define nist_set_224(to, from, a1, a2, a3, a4, a5, a6, a7) \ { \ bn_cp_32(to, 0, from, (a7) - 7) \ bn_cp_32(to, 1, from, (a6) - 7) \ bn_cp_32(to, 2, from, (a5) - 7) \ bn_cp_32(to, 3, from, (a4) - 7) \ bn_cp_32(to, 4, from, (a3) - 7) \ bn_cp_32(to, 5, from, (a2) - 7) \ bn_cp_32(to, 6, from, (a1) - 7) \ } int BN_nist_mod_224(BIGNUM *r, const BIGNUM *a, const BIGNUM *field, BN_CTX *ctx) { int top = a->top, i; int carry; BN_ULONG *r_d, *a_d = a->d; union { BN_ULONG bn[BN_NIST_224_TOP]; unsigned int ui[BN_NIST_224_TOP * sizeof(BN_ULONG) / sizeof(unsigned int)]; } buf; BN_ULONG c_d[BN_NIST_224_TOP], *res; bn_addsub_f adjust; static const BIGNUM ossl_bignum_nist_p_224_sqr = { (BN_ULONG *)_nist_p_224_sqr, OSSL_NELEM(_nist_p_224_sqr), OSSL_NELEM(_nist_p_224_sqr), 0, BN_FLG_STATIC_DATA }; field = &ossl_bignum_nist_p_224; /* just to make sure */ if (BN_is_negative(a) || BN_ucmp(a, &ossl_bignum_nist_p_224_sqr) >= 0) return BN_nnmod(r, a, field, ctx); i = BN_ucmp(field, a); if (i == 0) { BN_zero(r); return 1; } else if (i > 0) return (r == a) ? 1 : (BN_copy(r, a) != NULL); if (r != a) { if (!bn_wexpand(r, BN_NIST_224_TOP)) return 0; r_d = r->d; nist_cp_bn(r_d, a_d, BN_NIST_224_TOP); } else r_d = a_d; #if BN_BITS2==64 /* copy upper 256 bits of 448 bit number ... */ nist_cp_bn_0(c_d, a_d + (BN_NIST_224_TOP - 1), top - (BN_NIST_224_TOP - 1), BN_NIST_224_TOP); /* ... and right shift by 32 to obtain upper 224 bits */ nist_set_224(buf.bn, c_d, 14, 13, 12, 11, 10, 9, 8); /* truncate lower part to 224 bits too */ r_d[BN_NIST_224_TOP - 1] &= BN_MASK2l; #else nist_cp_bn_0(buf.bn, a_d + BN_NIST_224_TOP, top - BN_NIST_224_TOP, BN_NIST_224_TOP); #endif #if defined(NIST_INT64) && BN_BITS2!=64 { NIST_INT64 acc; /* accumulator */ unsigned int *rp = (unsigned int *)r_d; const unsigned int *bp = (const unsigned int *)buf.ui; acc = rp[0]; acc -= bp[7 - 7]; acc -= bp[11 - 7]; rp[0] = (unsigned int)acc; acc >>= 32; acc += rp[1]; acc -= bp[8 - 7]; acc -= bp[12 - 7]; rp[1] = (unsigned int)acc; acc >>= 32; acc += rp[2]; acc -= bp[9 - 7]; acc -= bp[13 - 7]; rp[2] = (unsigned int)acc; acc >>= 32; acc += rp[3]; acc += bp[7 - 7]; acc += bp[11 - 7]; acc -= bp[10 - 7]; rp[3] = (unsigned int)acc; acc >>= 32; acc += rp[4]; acc += bp[8 - 7]; acc += bp[12 - 7]; acc -= bp[11 - 7]; rp[4] = (unsigned int)acc; acc >>= 32; acc += rp[5]; acc += bp[9 - 7]; acc += bp[13 - 7]; acc -= bp[12 - 7]; rp[5] = (unsigned int)acc; acc >>= 32; acc += rp[6]; acc += bp[10 - 7]; acc -= bp[13 - 7]; rp[6] = (unsigned int)acc; carry = (int)(acc >> 32); # if BN_BITS2==64 rp[7] = carry; # endif } #else { BN_ULONG t_d[BN_NIST_224_TOP]; nist_set_224(t_d, buf.bn, 10, 9, 8, 7, 0, 0, 0); carry = (int)bn_add_words(r_d, r_d, t_d, BN_NIST_224_TOP); nist_set_224(t_d, buf.bn, 0, 13, 12, 11, 0, 0, 0); carry += (int)bn_add_words(r_d, r_d, t_d, BN_NIST_224_TOP); nist_set_224(t_d, buf.bn, 13, 12, 11, 10, 9, 8, 7); carry -= (int)bn_sub_words(r_d, r_d, t_d, BN_NIST_224_TOP); nist_set_224(t_d, buf.bn, 0, 0, 0, 0, 13, 12, 11); carry -= (int)bn_sub_words(r_d, r_d, t_d, BN_NIST_224_TOP); # if BN_BITS2==64 carry = (int)(r_d[BN_NIST_224_TOP - 1] >> 32); # endif } #endif adjust = bn_sub_words; if (carry > 0) { carry = (int)bn_sub_words(r_d, r_d, _nist_p_224[carry - 1], BN_NIST_224_TOP); #if BN_BITS2==64 carry = (int)(~(r_d[BN_NIST_224_TOP - 1] >> 32)) & 1; #endif } else if (carry < 0) { /* * it's a bit more complicated logic in this case. if bn_add_words * yields no carry, then result has to be adjusted by unconditionally * *adding* the modulus. but if it does, then result has to be * compared to the modulus and conditionally adjusted by * *subtracting* the latter. */ carry = (int)bn_add_words(r_d, r_d, _nist_p_224[-carry - 1], BN_NIST_224_TOP); adjust = carry ? bn_sub_words : bn_add_words; } else carry = 1; /* otherwise it's effectively same as in BN_nist_mod_192... */ res = ((*adjust) (c_d, r_d, _nist_p_224[0], BN_NIST_224_TOP) && carry) ? r_d : c_d; nist_cp_bn(r_d, res, BN_NIST_224_TOP); r->top = BN_NIST_224_TOP; bn_correct_top(r); return 1; } #define nist_set_256(to, from, a1, a2, a3, a4, a5, a6, a7, a8) \ { \ bn_cp_32(to, 0, from, (a8) - 8) \ bn_cp_32(to, 1, from, (a7) - 8) \ bn_cp_32(to, 2, from, (a6) - 8) \ bn_cp_32(to, 3, from, (a5) - 8) \ bn_cp_32(to, 4, from, (a4) - 8) \ bn_cp_32(to, 5, from, (a3) - 8) \ bn_cp_32(to, 6, from, (a2) - 8) \ bn_cp_32(to, 7, from, (a1) - 8) \ } int BN_nist_mod_256(BIGNUM *r, const BIGNUM *a, const BIGNUM *field, BN_CTX *ctx) { int i, top = a->top; int carry = 0; register BN_ULONG *a_d = a->d, *r_d; union { BN_ULONG bn[BN_NIST_256_TOP]; unsigned int ui[BN_NIST_256_TOP * sizeof(BN_ULONG) / sizeof(unsigned int)]; } buf; BN_ULONG c_d[BN_NIST_256_TOP], *res; bn_addsub_f adjust; static const BIGNUM ossl_bignum_nist_p_256_sqr = { (BN_ULONG *)_nist_p_256_sqr, OSSL_NELEM(_nist_p_256_sqr), OSSL_NELEM(_nist_p_256_sqr), 0, BN_FLG_STATIC_DATA }; field = &ossl_bignum_nist_p_256; /* just to make sure */ if (BN_is_negative(a) || BN_ucmp(a, &ossl_bignum_nist_p_256_sqr) >= 0) return BN_nnmod(r, a, field, ctx); i = BN_ucmp(field, a); if (i == 0) { BN_zero(r); return 1; } else if (i > 0) return (r == a) ? 1 : (BN_copy(r, a) != NULL); if (r != a) { if (!bn_wexpand(r, BN_NIST_256_TOP)) return 0; r_d = r->d; nist_cp_bn(r_d, a_d, BN_NIST_256_TOP); } else r_d = a_d; nist_cp_bn_0(buf.bn, a_d + BN_NIST_256_TOP, top - BN_NIST_256_TOP, BN_NIST_256_TOP); #if defined(NIST_INT64) { NIST_INT64 acc; /* accumulator */ unsigned int *rp = (unsigned int *)r_d; const unsigned int *bp = (const unsigned int *)buf.ui; acc = load_u32(&rp[0]); acc += bp[8 - 8]; acc += bp[9 - 8]; acc -= bp[11 - 8]; acc -= bp[12 - 8]; acc -= bp[13 - 8]; acc -= bp[14 - 8]; store_lo32(&rp[0], acc); acc >>= 32; acc += load_u32(&rp[1]); acc += bp[9 - 8]; acc += bp[10 - 8]; acc -= bp[12 - 8]; acc -= bp[13 - 8]; acc -= bp[14 - 8]; acc -= bp[15 - 8]; store_lo32(&rp[1], acc); acc >>= 32; acc += load_u32(&rp[2]); acc += bp[10 - 8]; acc += bp[11 - 8]; acc -= bp[13 - 8]; acc -= bp[14 - 8]; acc -= bp[15 - 8]; store_lo32(&rp[2], acc); acc >>= 32; acc += load_u32(&rp[3]); acc += bp[11 - 8]; acc += bp[11 - 8]; acc += bp[12 - 8]; acc += bp[12 - 8]; acc += bp[13 - 8]; acc -= bp[15 - 8]; acc -= bp[8 - 8]; acc -= bp[9 - 8]; store_lo32(&rp[3], acc); acc >>= 32; acc += load_u32(&rp[4]); acc += bp[12 - 8]; acc += bp[12 - 8]; acc += bp[13 - 8]; acc += bp[13 - 8]; acc += bp[14 - 8]; acc -= bp[9 - 8]; acc -= bp[10 - 8]; store_lo32(&rp[4], acc); acc >>= 32; acc += load_u32(&rp[5]); acc += bp[13 - 8]; acc += bp[13 - 8]; acc += bp[14 - 8]; acc += bp[14 - 8]; acc += bp[15 - 8]; acc -= bp[10 - 8]; acc -= bp[11 - 8]; store_lo32(&rp[5], acc); acc >>= 32; acc += load_u32(&rp[6]); acc += bp[14 - 8]; acc += bp[14 - 8]; acc += bp[15 - 8]; acc += bp[15 - 8]; acc += bp[14 - 8]; acc += bp[13 - 8]; acc -= bp[8 - 8]; acc -= bp[9 - 8]; store_lo32(&rp[6], acc); acc >>= 32; acc += load_u32(&rp[7]); acc += bp[15 - 8]; acc += bp[15 - 8]; acc += bp[15 - 8]; acc += bp[8 - 8]; acc -= bp[10 - 8]; acc -= bp[11 - 8]; acc -= bp[12 - 8]; acc -= bp[13 - 8]; store_lo32(&rp[7], acc); carry = (int)(acc >> 32); } #else { BN_ULONG t_d[BN_NIST_256_TOP]; /* * S1 */ nist_set_256(t_d, buf.bn, 15, 14, 13, 12, 11, 0, 0, 0); /* * S2 */ nist_set_256(c_d, buf.bn, 0, 15, 14, 13, 12, 0, 0, 0); carry = (int)bn_add_words(t_d, t_d, c_d, BN_NIST_256_TOP); /* left shift */ { register BN_ULONG *ap, t, c; ap = t_d; c = 0; for (i = BN_NIST_256_TOP; i != 0; --i) { t = *ap; *(ap++) = ((t << 1) | c) & BN_MASK2; c = (t & BN_TBIT) ? 1 : 0; } carry <<= 1; carry |= c; } carry += (int)bn_add_words(r_d, r_d, t_d, BN_NIST_256_TOP); /* * S3 */ nist_set_256(t_d, buf.bn, 15, 14, 0, 0, 0, 10, 9, 8); carry += (int)bn_add_words(r_d, r_d, t_d, BN_NIST_256_TOP); /* * S4 */ nist_set_256(t_d, buf.bn, 8, 13, 15, 14, 13, 11, 10, 9); carry += (int)bn_add_words(r_d, r_d, t_d, BN_NIST_256_TOP); /* * D1 */ nist_set_256(t_d, buf.bn, 10, 8, 0, 0, 0, 13, 12, 11); carry -= (int)bn_sub_words(r_d, r_d, t_d, BN_NIST_256_TOP); /* * D2 */ nist_set_256(t_d, buf.bn, 11, 9, 0, 0, 15, 14, 13, 12); carry -= (int)bn_sub_words(r_d, r_d, t_d, BN_NIST_256_TOP); /* * D3 */ nist_set_256(t_d, buf.bn, 12, 0, 10, 9, 8, 15, 14, 13); carry -= (int)bn_sub_words(r_d, r_d, t_d, BN_NIST_256_TOP); /* * D4 */ nist_set_256(t_d, buf.bn, 13, 0, 11, 10, 9, 0, 15, 14); carry -= (int)bn_sub_words(r_d, r_d, t_d, BN_NIST_256_TOP); } #endif /* see BN_nist_mod_224 for explanation */ adjust = bn_sub_words; if (carry > 0) carry = (int)bn_sub_words(r_d, r_d, _nist_p_256[carry - 1], BN_NIST_256_TOP); else if (carry < 0) { carry = (int)bn_add_words(r_d, r_d, _nist_p_256[-carry - 1], BN_NIST_256_TOP); adjust = carry ? bn_sub_words : bn_add_words; } else carry = 1; res = ((*adjust) (c_d, r_d, _nist_p_256[0], BN_NIST_256_TOP) && carry) ? r_d : c_d; nist_cp_bn(r_d, res, BN_NIST_256_TOP); r->top = BN_NIST_256_TOP; bn_correct_top(r); return 1; } #define nist_set_384(to,from,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12) \ { \ bn_cp_32(to, 0, from, (a12) - 12) \ bn_cp_32(to, 1, from, (a11) - 12) \ bn_cp_32(to, 2, from, (a10) - 12) \ bn_cp_32(to, 3, from, (a9) - 12) \ bn_cp_32(to, 4, from, (a8) - 12) \ bn_cp_32(to, 5, from, (a7) - 12) \ bn_cp_32(to, 6, from, (a6) - 12) \ bn_cp_32(to, 7, from, (a5) - 12) \ bn_cp_32(to, 8, from, (a4) - 12) \ bn_cp_32(to, 9, from, (a3) - 12) \ bn_cp_32(to, 10, from, (a2) - 12) \ bn_cp_32(to, 11, from, (a1) - 12) \ } int BN_nist_mod_384(BIGNUM *r, const BIGNUM *a, const BIGNUM *field, BN_CTX *ctx) { int i, top = a->top; int carry = 0; register BN_ULONG *r_d, *a_d = a->d; union { BN_ULONG bn[BN_NIST_384_TOP]; unsigned int ui[BN_NIST_384_TOP * sizeof(BN_ULONG) / sizeof(unsigned int)]; } buf; BN_ULONG c_d[BN_NIST_384_TOP], *res; bn_addsub_f adjust; static const BIGNUM ossl_bignum_nist_p_384_sqr = { (BN_ULONG *)_nist_p_384_sqr, OSSL_NELEM(_nist_p_384_sqr), OSSL_NELEM(_nist_p_384_sqr), 0, BN_FLG_STATIC_DATA }; field = &ossl_bignum_nist_p_384; /* just to make sure */ if (BN_is_negative(a) || BN_ucmp(a, &ossl_bignum_nist_p_384_sqr) >= 0) return BN_nnmod(r, a, field, ctx); i = BN_ucmp(field, a); if (i == 0) { BN_zero(r); return 1; } else if (i > 0) return (r == a) ? 1 : (BN_copy(r, a) != NULL); if (r != a) { if (!bn_wexpand(r, BN_NIST_384_TOP)) return 0; r_d = r->d; nist_cp_bn(r_d, a_d, BN_NIST_384_TOP); } else r_d = a_d; nist_cp_bn_0(buf.bn, a_d + BN_NIST_384_TOP, top - BN_NIST_384_TOP, BN_NIST_384_TOP); #if defined(NIST_INT64) { NIST_INT64 acc; /* accumulator */ unsigned int *rp = (unsigned int *)r_d; const unsigned int *bp = (const unsigned int *)buf.ui; acc = load_u32(&rp[0]); acc += bp[12 - 12]; acc += bp[21 - 12]; acc += bp[20 - 12]; acc -= bp[23 - 12]; store_lo32(&rp[0], acc); acc >>= 32; acc += load_u32(&rp[1]); acc += bp[13 - 12]; acc += bp[22 - 12]; acc += bp[23 - 12]; acc -= bp[12 - 12]; acc -= bp[20 - 12]; store_lo32(&rp[1], acc); acc >>= 32; acc += load_u32(&rp[2]); acc += bp[14 - 12]; acc += bp[23 - 12]; acc -= bp[13 - 12]; acc -= bp[21 - 12]; store_lo32(&rp[2], acc); acc >>= 32; acc += load_u32(&rp[3]); acc += bp[15 - 12]; acc += bp[12 - 12]; acc += bp[20 - 12]; acc += bp[21 - 12]; acc -= bp[14 - 12]; acc -= bp[22 - 12]; acc -= bp[23 - 12]; store_lo32(&rp[3], acc); acc >>= 32; acc += load_u32(&rp[4]); acc += bp[21 - 12]; acc += bp[21 - 12]; acc += bp[16 - 12]; acc += bp[13 - 12]; acc += bp[12 - 12]; acc += bp[20 - 12]; acc += bp[22 - 12]; acc -= bp[15 - 12]; acc -= bp[23 - 12]; acc -= bp[23 - 12]; store_lo32(&rp[4], acc); acc >>= 32; acc += load_u32(&rp[5]); acc += bp[22 - 12]; acc += bp[22 - 12]; acc += bp[17 - 12]; acc += bp[14 - 12]; acc += bp[13 - 12]; acc += bp[21 - 12]; acc += bp[23 - 12]; acc -= bp[16 - 12]; store_lo32(&rp[5], acc); acc >>= 32; acc += load_u32(&rp[6]); acc += bp[23 - 12]; acc += bp[23 - 12]; acc += bp[18 - 12]; acc += bp[15 - 12]; acc += bp[14 - 12]; acc += bp[22 - 12]; acc -= bp[17 - 12]; store_lo32(&rp[6], acc); acc >>= 32; acc += load_u32(&rp[7]); acc += bp[19 - 12]; acc += bp[16 - 12]; acc += bp[15 - 12]; acc += bp[23 - 12]; acc -= bp[18 - 12]; store_lo32(&rp[7], acc); acc >>= 32; acc += load_u32(&rp[8]); acc += bp[20 - 12]; acc += bp[17 - 12]; acc += bp[16 - 12]; acc -= bp[19 - 12]; store_lo32(&rp[8], acc); acc >>= 32; acc += load_u32(&rp[9]); acc += bp[21 - 12]; acc += bp[18 - 12]; acc += bp[17 - 12]; acc -= bp[20 - 12]; store_lo32(&rp[9], acc); acc >>= 32; acc += load_u32(&rp[10]); acc += bp[22 - 12]; acc += bp[19 - 12]; acc += bp[18 - 12]; acc -= bp[21 - 12]; store_lo32(&rp[10], acc); acc >>= 32; acc += load_u32(&rp[11]); acc += bp[23 - 12]; acc += bp[20 - 12]; acc += bp[19 - 12]; acc -= bp[22 - 12]; store_lo32(&rp[11], acc); carry = (int)(acc >> 32); } #else { BN_ULONG t_d[BN_NIST_384_TOP]; /* * S1 */ nist_set_256(t_d, buf.bn, 0, 0, 0, 0, 0, 23 - 4, 22 - 4, 21 - 4); /* left shift */ { register BN_ULONG *ap, t, c; ap = t_d; c = 0; for (i = 3; i != 0; --i) { t = *ap; *(ap++) = ((t << 1) | c) & BN_MASK2; c = (t & BN_TBIT) ? 1 : 0; } *ap = c; } carry = (int)bn_add_words(r_d + (128 / BN_BITS2), r_d + (128 / BN_BITS2), t_d, BN_NIST_256_TOP); /* * S2 */ carry += (int)bn_add_words(r_d, r_d, buf.bn, BN_NIST_384_TOP); /* * S3 */ nist_set_384(t_d, buf.bn, 20, 19, 18, 17, 16, 15, 14, 13, 12, 23, 22, 21); carry += (int)bn_add_words(r_d, r_d, t_d, BN_NIST_384_TOP); /* * S4 */ nist_set_384(t_d, buf.bn, 19, 18, 17, 16, 15, 14, 13, 12, 20, 0, 23, 0); carry += (int)bn_add_words(r_d, r_d, t_d, BN_NIST_384_TOP); /* * S5 */ nist_set_384(t_d, buf.bn, 0, 0, 0, 0, 23, 22, 21, 20, 0, 0, 0, 0); carry += (int)bn_add_words(r_d, r_d, t_d, BN_NIST_384_TOP); /* * S6 */ nist_set_384(t_d, buf.bn, 0, 0, 0, 0, 0, 0, 23, 22, 21, 0, 0, 20); carry += (int)bn_add_words(r_d, r_d, t_d, BN_NIST_384_TOP); /* * D1 */ nist_set_384(t_d, buf.bn, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 23); carry -= (int)bn_sub_words(r_d, r_d, t_d, BN_NIST_384_TOP); /* * D2 */ nist_set_384(t_d, buf.bn, 0, 0, 0, 0, 0, 0, 0, 23, 22, 21, 20, 0); carry -= (int)bn_sub_words(r_d, r_d, t_d, BN_NIST_384_TOP); /* * D3 */ nist_set_384(t_d, buf.bn, 0, 0, 0, 0, 0, 0, 0, 23, 23, 0, 0, 0); carry -= (int)bn_sub_words(r_d, r_d, t_d, BN_NIST_384_TOP); } #endif /* see BN_nist_mod_224 for explanation */ adjust = bn_sub_words; if (carry > 0) carry = (int)bn_sub_words(r_d, r_d, _nist_p_384[carry - 1], BN_NIST_384_TOP); else if (carry < 0) { carry = (int)bn_add_words(r_d, r_d, _nist_p_384[-carry - 1], BN_NIST_384_TOP); adjust = carry ? bn_sub_words : bn_add_words; } else carry = 1; res = ((*adjust) (c_d, r_d, _nist_p_384[0], BN_NIST_384_TOP) && carry) ? r_d : c_d; nist_cp_bn(r_d, res, BN_NIST_384_TOP); r->top = BN_NIST_384_TOP; bn_correct_top(r); return 1; } #define BN_NIST_521_RSHIFT (521%BN_BITS2) #define BN_NIST_521_LSHIFT (BN_BITS2-BN_NIST_521_RSHIFT) #define BN_NIST_521_TOP_MASK ((BN_ULONG)BN_MASK2>>BN_NIST_521_LSHIFT) int BN_nist_mod_521(BIGNUM *r, const BIGNUM *a, const BIGNUM *field, BN_CTX *ctx) { int top = a->top, i; BN_ULONG *r_d, *a_d = a->d, t_d[BN_NIST_521_TOP], val, tmp, *res; static const BIGNUM ossl_bignum_nist_p_521_sqr = { (BN_ULONG *)_nist_p_521_sqr, OSSL_NELEM(_nist_p_521_sqr), OSSL_NELEM(_nist_p_521_sqr), 0, BN_FLG_STATIC_DATA }; field = &ossl_bignum_nist_p_521; /* just to make sure */ if (BN_is_negative(a) || BN_ucmp(a, &ossl_bignum_nist_p_521_sqr) >= 0) return BN_nnmod(r, a, field, ctx); i = BN_ucmp(field, a); if (i == 0) { BN_zero(r); return 1; } else if (i > 0) return (r == a) ? 1 : (BN_copy(r, a) != NULL); if (r != a) { if (!bn_wexpand(r, BN_NIST_521_TOP)) return 0; r_d = r->d; nist_cp_bn(r_d, a_d, BN_NIST_521_TOP); } else r_d = a_d; /* upper 521 bits, copy ... */ nist_cp_bn_0(t_d, a_d + (BN_NIST_521_TOP - 1), top - (BN_NIST_521_TOP - 1), BN_NIST_521_TOP); /* ... and right shift */ for (val = t_d[0], i = 0; i < BN_NIST_521_TOP - 1; i++) { #if 0 /* * MSC ARM compiler [version 2013, presumably even earlier, * much earlier] miscompiles this code, but not one in * #else section. See RT#3541. */ tmp = val >> BN_NIST_521_RSHIFT; val = t_d[i + 1]; t_d[i] = (tmp | val << BN_NIST_521_LSHIFT) & BN_MASK2; #else t_d[i] = (val >> BN_NIST_521_RSHIFT | (tmp = t_d[i + 1]) << BN_NIST_521_LSHIFT) & BN_MASK2; val = tmp; #endif } t_d[i] = val >> BN_NIST_521_RSHIFT; /* lower 521 bits */ r_d[i] &= BN_NIST_521_TOP_MASK; bn_add_words(r_d, r_d, t_d, BN_NIST_521_TOP); res = bn_sub_words(t_d, r_d, _nist_p_521, BN_NIST_521_TOP) ? r_d : t_d; nist_cp_bn(r_d, res, BN_NIST_521_TOP); r->top = BN_NIST_521_TOP; bn_correct_top(r); return 1; } int (*BN_nist_mod_func(const BIGNUM *p)) (BIGNUM *r, const BIGNUM *a, const BIGNUM *field, BN_CTX *ctx) { if (BN_ucmp(&ossl_bignum_nist_p_192, p) == 0) return BN_nist_mod_192; if (BN_ucmp(&ossl_bignum_nist_p_224, p) == 0) return BN_nist_mod_224; if (BN_ucmp(&ossl_bignum_nist_p_256, p) == 0) return BN_nist_mod_256; if (BN_ucmp(&ossl_bignum_nist_p_384, p) == 0) return BN_nist_mod_384; if (BN_ucmp(&ossl_bignum_nist_p_521, p) == 0) return BN_nist_mod_521; return 0; }
./openssl/crypto/bn/bn_srp.c
/* * Copyright 2014-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 "bn_local.h" #include "internal/nelem.h" #ifndef OPENSSL_NO_SRP #include <openssl/srp.h> #include "crypto/bn_srp.h" # if (BN_BYTES == 8) # if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__) # define bn_pack4(a1,a2,a3,a4) ((a1##UI64<<48)|(a2##UI64<<32)|(a3##UI64<<16)|a4##UI64) # elif defined(__arch64__) # define bn_pack4(a1,a2,a3,a4) ((a1##UL<<48)|(a2##UL<<32)|(a3##UL<<16)|a4##UL) # else # define bn_pack4(a1,a2,a3,a4) ((a1##ULL<<48)|(a2##ULL<<32)|(a3##ULL<<16)|a4##ULL) # endif # elif (BN_BYTES == 4) # define bn_pack4(a1,a2,a3,a4) ((a3##UL<<16)|a4##UL), ((a1##UL<<16)|a2##UL) # else # error "unsupported BN_BYTES" # endif static const BN_ULONG bn_group_1024_value[] = { bn_pack4(0x9FC6, 0x1D2F, 0xC0EB, 0x06E3), bn_pack4(0xFD51, 0x38FE, 0x8376, 0x435B), bn_pack4(0x2FD4, 0xCBF4, 0x976E, 0xAA9A), bn_pack4(0x68ED, 0xBC3C, 0x0572, 0x6CC0), bn_pack4(0xC529, 0xF566, 0x660E, 0x57EC), bn_pack4(0x8255, 0x9B29, 0x7BCF, 0x1885), bn_pack4(0xCE8E, 0xF4AD, 0x69B1, 0x5D49), bn_pack4(0x5DC7, 0xD7B4, 0x6154, 0xD6B6), bn_pack4(0x8E49, 0x5C1D, 0x6089, 0xDAD1), bn_pack4(0xE0D5, 0xD8E2, 0x50B9, 0x8BE4), bn_pack4(0x383B, 0x4813, 0xD692, 0xC6E0), bn_pack4(0xD674, 0xDF74, 0x96EA, 0x81D3), bn_pack4(0x9EA2, 0x314C, 0x9C25, 0x6576), bn_pack4(0x6072, 0x6187, 0x75FF, 0x3C0B), bn_pack4(0x9C33, 0xF80A, 0xFA8F, 0xC5E8), bn_pack4(0xEEAF, 0x0AB9, 0xADB3, 0x8DD6) }; const BIGNUM ossl_bn_group_1024 = { (BN_ULONG *)bn_group_1024_value, OSSL_NELEM(bn_group_1024_value), OSSL_NELEM(bn_group_1024_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_1536_value[] = { bn_pack4(0xCF76, 0xE3FE, 0xD135, 0xF9BB), bn_pack4(0x1518, 0x0F93, 0x499A, 0x234D), bn_pack4(0x8CE7, 0xA28C, 0x2442, 0xC6F3), bn_pack4(0x5A02, 0x1FFF, 0x5E91, 0x479E), bn_pack4(0x7F8A, 0x2FE9, 0xB8B5, 0x292E), bn_pack4(0x837C, 0x264A, 0xE3A9, 0xBEB8), bn_pack4(0xE442, 0x734A, 0xF7CC, 0xB7AE), bn_pack4(0x6577, 0x2E43, 0x7D6C, 0x7F8C), bn_pack4(0xDB2F, 0xD53D, 0x24B7, 0xC486), bn_pack4(0x6EDF, 0x0195, 0x3934, 0x9627), bn_pack4(0x158B, 0xFD3E, 0x2B9C, 0x8CF5), bn_pack4(0x764E, 0x3F4B, 0x53DD, 0x9DA1), bn_pack4(0x4754, 0x8381, 0xDBC5, 0xB1FC), bn_pack4(0x9B60, 0x9E0B, 0xE3BA, 0xB63D), bn_pack4(0x8134, 0xB1C8, 0xB979, 0x8914), bn_pack4(0xDF02, 0x8A7C, 0xEC67, 0xF0D0), bn_pack4(0x80B6, 0x55BB, 0x9A22, 0xE8DC), bn_pack4(0x1558, 0x903B, 0xA0D0, 0xF843), bn_pack4(0x51C6, 0xA94B, 0xE460, 0x7A29), bn_pack4(0x5F4F, 0x5F55, 0x6E27, 0xCBDE), bn_pack4(0xBEEE, 0xA961, 0x4B19, 0xCC4D), bn_pack4(0xDBA5, 0x1DF4, 0x99AC, 0x4C80), bn_pack4(0xB1F1, 0x2A86, 0x17A4, 0x7BBB), bn_pack4(0x9DEF, 0x3CAF, 0xB939, 0x277A) }; const BIGNUM ossl_bn_group_1536 = { (BN_ULONG *)bn_group_1536_value, OSSL_NELEM(bn_group_1536_value), OSSL_NELEM(bn_group_1536_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_2048_value[] = { bn_pack4(0x0FA7, 0x111F, 0x9E4A, 0xFF73), bn_pack4(0x9B65, 0xE372, 0xFCD6, 0x8EF2), bn_pack4(0x35DE, 0x236D, 0x525F, 0x5475), bn_pack4(0x94B5, 0xC803, 0xD89F, 0x7AE4), bn_pack4(0x71AE, 0x35F8, 0xE9DB, 0xFBB6), bn_pack4(0x2A56, 0x98F3, 0xA8D0, 0xC382), bn_pack4(0x9CCC, 0x041C, 0x7BC3, 0x08D8), bn_pack4(0xAF87, 0x4E73, 0x03CE, 0x5329), bn_pack4(0x6160, 0x2790, 0x04E5, 0x7AE6), bn_pack4(0x032C, 0xFBDB, 0xF52F, 0xB378), bn_pack4(0x5EA7, 0x7A27, 0x75D2, 0xECFA), bn_pack4(0x5445, 0x23B5, 0x24B0, 0xD57D), bn_pack4(0x5B9D, 0x32E6, 0x88F8, 0x7748), bn_pack4(0xF1D2, 0xB907, 0x8717, 0x461A), bn_pack4(0x76BD, 0x207A, 0x436C, 0x6481), bn_pack4(0xCA97, 0xB43A, 0x23FB, 0x8016), bn_pack4(0x1D28, 0x1E44, 0x6B14, 0x773B), bn_pack4(0x7359, 0xD041, 0xD5C3, 0x3EA7), bn_pack4(0xA80D, 0x740A, 0xDBF4, 0xFF74), bn_pack4(0x55F9, 0x7993, 0xEC97, 0x5EEA), bn_pack4(0x2918, 0xA996, 0x2F0B, 0x93B8), bn_pack4(0x661A, 0x05FB, 0xD5FA, 0xAAE8), bn_pack4(0xCF60, 0x9517, 0x9A16, 0x3AB3), bn_pack4(0xE808, 0x3969, 0xEDB7, 0x67B0), bn_pack4(0xCD7F, 0x48A9, 0xDA04, 0xFD50), bn_pack4(0xD523, 0x12AB, 0x4B03, 0x310D), bn_pack4(0x8193, 0xE075, 0x7767, 0xA13D), bn_pack4(0xA373, 0x29CB, 0xB4A0, 0x99ED), bn_pack4(0xFC31, 0x9294, 0x3DB5, 0x6050), bn_pack4(0xAF72, 0xB665, 0x1987, 0xEE07), bn_pack4(0xF166, 0xDE5E, 0x1389, 0x582F), bn_pack4(0xAC6B, 0xDB41, 0x324A, 0x9A9B) }; const BIGNUM ossl_bn_group_2048 = { (BN_ULONG *)bn_group_2048_value, OSSL_NELEM(bn_group_2048_value), OSSL_NELEM(bn_group_2048_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_3072_value[] = { bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF), bn_pack4(0x4B82, 0xD120, 0xA93A, 0xD2CA), bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E), bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31), bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2), bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C), bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C), bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64), bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864), bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B), bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D), bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7), bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7), bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D), bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A), bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64), bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33), bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D), bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510), bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5), bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718), bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9), bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F), bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603), bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B), bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C), bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804), bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D), bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB), bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96), bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F), bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A), bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05), bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D), bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6), bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5), bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED), bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B), bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6), bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245), bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437), bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B), bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD), bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22), bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74), bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1), bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234), bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF) }; const BIGNUM ossl_bn_group_3072 = { (BN_ULONG *)bn_group_3072_value, OSSL_NELEM(bn_group_3072_value), OSSL_NELEM(bn_group_3072_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_4096_value[] = { bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF), bn_pack4(0x4DF4, 0x35C9, 0x3406, 0x3199), bn_pack4(0x86FF, 0xB7DC, 0x90A6, 0xC08F), bn_pack4(0x93B4, 0xEA98, 0x8D8F, 0xDDC1), bn_pack4(0xD006, 0x9127, 0xD5B0, 0x5AA9), bn_pack4(0xB81B, 0xDD76, 0x2170, 0x481C), bn_pack4(0x1F61, 0x2970, 0xCEE2, 0xD7AF), bn_pack4(0x233B, 0xA186, 0x515B, 0xE7ED), bn_pack4(0x99B2, 0x964F, 0xA090, 0xC3A2), bn_pack4(0x287C, 0x5947, 0x4E6B, 0xC05D), bn_pack4(0x2E8E, 0xFC14, 0x1FBE, 0xCAA6), bn_pack4(0xDBBB, 0xC2DB, 0x04DE, 0x8EF9), bn_pack4(0x2583, 0xE9CA, 0x2AD4, 0x4CE8), bn_pack4(0x1A94, 0x6834, 0xB615, 0x0BDA), bn_pack4(0x99C3, 0x2718, 0x6AF4, 0xE23C), bn_pack4(0x8871, 0x9A10, 0xBDBA, 0x5B26), bn_pack4(0x1A72, 0x3C12, 0xA787, 0xE6D7), bn_pack4(0x4B82, 0xD120, 0xA921, 0x0801), bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E), bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31), bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2), bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C), bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C), bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64), bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864), bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B), bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D), bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7), bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7), bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D), bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A), bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64), bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33), bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D), bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510), bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5), bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718), bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9), bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F), bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603), bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B), bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C), bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804), bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D), bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB), bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96), bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F), bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A), bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05), bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D), bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6), bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5), bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED), bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B), bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6), bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245), bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437), bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B), bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD), bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22), bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74), bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1), bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234), bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF) }; const BIGNUM ossl_bn_group_4096 = { (BN_ULONG *)bn_group_4096_value, OSSL_NELEM(bn_group_4096_value), OSSL_NELEM(bn_group_4096_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_6144_value[] = { bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF), bn_pack4(0xE694, 0xF91E, 0x6DCC, 0x4024), bn_pack4(0x12BF, 0x2D5B, 0x0B74, 0x74D6), bn_pack4(0x043E, 0x8F66, 0x3F48, 0x60EE), bn_pack4(0x387F, 0xE8D7, 0x6E3C, 0x0468), bn_pack4(0xDA56, 0xC9EC, 0x2EF2, 0x9632), bn_pack4(0xEB19, 0xCCB1, 0xA313, 0xD55C), bn_pack4(0xF550, 0xAA3D, 0x8A1F, 0xBFF0), bn_pack4(0x06A1, 0xD58B, 0xB7C5, 0xDA76), bn_pack4(0xA797, 0x15EE, 0xF29B, 0xE328), bn_pack4(0x14CC, 0x5ED2, 0x0F80, 0x37E0), bn_pack4(0xCC8F, 0x6D7E, 0xBF48, 0xE1D8), bn_pack4(0x4BD4, 0x07B2, 0x2B41, 0x54AA), bn_pack4(0x0F1D, 0x45B7, 0xFF58, 0x5AC5), bn_pack4(0x23A9, 0x7A7E, 0x36CC, 0x88BE), bn_pack4(0x59E7, 0xC97F, 0xBEC7, 0xE8F3), bn_pack4(0xB5A8, 0x4031, 0x900B, 0x1C9E), bn_pack4(0xD55E, 0x702F, 0x4698, 0x0C82), bn_pack4(0xF482, 0xD7CE, 0x6E74, 0xFEF6), bn_pack4(0xF032, 0xEA15, 0xD172, 0x1D03), bn_pack4(0x5983, 0xCA01, 0xC64B, 0x92EC), bn_pack4(0x6FB8, 0xF401, 0x378C, 0xD2BF), bn_pack4(0x3320, 0x5151, 0x2BD7, 0xAF42), bn_pack4(0xDB7F, 0x1447, 0xE6CC, 0x254B), bn_pack4(0x44CE, 0x6CBA, 0xCED4, 0xBB1B), bn_pack4(0xDA3E, 0xDBEB, 0xCF9B, 0x14ED), bn_pack4(0x1797, 0x27B0, 0x865A, 0x8918), bn_pack4(0xB06A, 0x53ED, 0x9027, 0xD831), bn_pack4(0xE5DB, 0x382F, 0x4130, 0x01AE), bn_pack4(0xF8FF, 0x9406, 0xAD9E, 0x530E), bn_pack4(0xC975, 0x1E76, 0x3DBA, 0x37BD), bn_pack4(0xC1D4, 0xDCB2, 0x6026, 0x46DE), bn_pack4(0x36C3, 0xFAB4, 0xD27C, 0x7026), bn_pack4(0x4DF4, 0x35C9, 0x3402, 0x8492), bn_pack4(0x86FF, 0xB7DC, 0x90A6, 0xC08F), bn_pack4(0x93B4, 0xEA98, 0x8D8F, 0xDDC1), bn_pack4(0xD006, 0x9127, 0xD5B0, 0x5AA9), bn_pack4(0xB81B, 0xDD76, 0x2170, 0x481C), bn_pack4(0x1F61, 0x2970, 0xCEE2, 0xD7AF), bn_pack4(0x233B, 0xA186, 0x515B, 0xE7ED), bn_pack4(0x99B2, 0x964F, 0xA090, 0xC3A2), bn_pack4(0x287C, 0x5947, 0x4E6B, 0xC05D), bn_pack4(0x2E8E, 0xFC14, 0x1FBE, 0xCAA6), bn_pack4(0xDBBB, 0xC2DB, 0x04DE, 0x8EF9), bn_pack4(0x2583, 0xE9CA, 0x2AD4, 0x4CE8), bn_pack4(0x1A94, 0x6834, 0xB615, 0x0BDA), bn_pack4(0x99C3, 0x2718, 0x6AF4, 0xE23C), bn_pack4(0x8871, 0x9A10, 0xBDBA, 0x5B26), bn_pack4(0x1A72, 0x3C12, 0xA787, 0xE6D7), bn_pack4(0x4B82, 0xD120, 0xA921, 0x0801), bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E), bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31), bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2), bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C), bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C), bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64), bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864), bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B), bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D), bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7), bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7), bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D), bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A), bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64), bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33), bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D), bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510), bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5), bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718), bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9), bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F), bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603), bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B), bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C), bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804), bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D), bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB), bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96), bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F), bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A), bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05), bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D), bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6), bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5), bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED), bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B), bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6), bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245), bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437), bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B), bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD), bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22), bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74), bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1), bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234), bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF) }; const BIGNUM ossl_bn_group_6144 = { (BN_ULONG *)bn_group_6144_value, OSSL_NELEM(bn_group_6144_value), OSSL_NELEM(bn_group_6144_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_8192_value[] = { bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF), bn_pack4(0x60C9, 0x80DD, 0x98ED, 0xD3DF), bn_pack4(0xC81F, 0x56E8, 0x80B9, 0x6E71), bn_pack4(0x9E30, 0x50E2, 0x7656, 0x94DF), bn_pack4(0x9558, 0xE447, 0x5677, 0xE9AA), bn_pack4(0xC919, 0x0DA6, 0xFC02, 0x6E47), bn_pack4(0x889A, 0x002E, 0xD5EE, 0x382B), bn_pack4(0x4009, 0x438B, 0x481C, 0x6CD7), bn_pack4(0x3590, 0x46F4, 0xEB87, 0x9F92), bn_pack4(0xFAF3, 0x6BC3, 0x1ECF, 0xA268), bn_pack4(0xB1D5, 0x10BD, 0x7EE7, 0x4D73), bn_pack4(0xF9AB, 0x4819, 0x5DED, 0x7EA1), bn_pack4(0x64F3, 0x1CC5, 0x0846, 0x851D), bn_pack4(0x4597, 0xE899, 0xA025, 0x5DC1), bn_pack4(0xDF31, 0x0EE0, 0x74AB, 0x6A36), bn_pack4(0x6D2A, 0x13F8, 0x3F44, 0xF82D), bn_pack4(0x062B, 0x3CF5, 0xB3A2, 0x78A6), bn_pack4(0x7968, 0x3303, 0xED5B, 0xDD3A), bn_pack4(0xFA9D, 0x4B7F, 0xA2C0, 0x87E8), bn_pack4(0x4BCB, 0xC886, 0x2F83, 0x85DD), bn_pack4(0x3473, 0xFC64, 0x6CEA, 0x306B), bn_pack4(0x13EB, 0x57A8, 0x1A23, 0xF0C7), bn_pack4(0x2222, 0x2E04, 0xA403, 0x7C07), bn_pack4(0xE3FD, 0xB8BE, 0xFC84, 0x8AD9), bn_pack4(0x238F, 0x16CB, 0xE39D, 0x652D), bn_pack4(0x3423, 0xB474, 0x2BF1, 0xC978), bn_pack4(0x3AAB, 0x639C, 0x5AE4, 0xF568), bn_pack4(0x2576, 0xF693, 0x6BA4, 0x2466), bn_pack4(0x741F, 0xA7BF, 0x8AFC, 0x47ED), bn_pack4(0x3BC8, 0x32B6, 0x8D9D, 0xD300), bn_pack4(0xD8BE, 0xC4D0, 0x73B9, 0x31BA), bn_pack4(0x3877, 0x7CB6, 0xA932, 0xDF8C), bn_pack4(0x74A3, 0x926F, 0x12FE, 0xE5E4), bn_pack4(0xE694, 0xF91E, 0x6DBE, 0x1159), bn_pack4(0x12BF, 0x2D5B, 0x0B74, 0x74D6), bn_pack4(0x043E, 0x8F66, 0x3F48, 0x60EE), bn_pack4(0x387F, 0xE8D7, 0x6E3C, 0x0468), bn_pack4(0xDA56, 0xC9EC, 0x2EF2, 0x9632), bn_pack4(0xEB19, 0xCCB1, 0xA313, 0xD55C), bn_pack4(0xF550, 0xAA3D, 0x8A1F, 0xBFF0), bn_pack4(0x06A1, 0xD58B, 0xB7C5, 0xDA76), bn_pack4(0xA797, 0x15EE, 0xF29B, 0xE328), bn_pack4(0x14CC, 0x5ED2, 0x0F80, 0x37E0), bn_pack4(0xCC8F, 0x6D7E, 0xBF48, 0xE1D8), bn_pack4(0x4BD4, 0x07B2, 0x2B41, 0x54AA), bn_pack4(0x0F1D, 0x45B7, 0xFF58, 0x5AC5), bn_pack4(0x23A9, 0x7A7E, 0x36CC, 0x88BE), bn_pack4(0x59E7, 0xC97F, 0xBEC7, 0xE8F3), bn_pack4(0xB5A8, 0x4031, 0x900B, 0x1C9E), bn_pack4(0xD55E, 0x702F, 0x4698, 0x0C82), bn_pack4(0xF482, 0xD7CE, 0x6E74, 0xFEF6), bn_pack4(0xF032, 0xEA15, 0xD172, 0x1D03), bn_pack4(0x5983, 0xCA01, 0xC64B, 0x92EC), bn_pack4(0x6FB8, 0xF401, 0x378C, 0xD2BF), bn_pack4(0x3320, 0x5151, 0x2BD7, 0xAF42), bn_pack4(0xDB7F, 0x1447, 0xE6CC, 0x254B), bn_pack4(0x44CE, 0x6CBA, 0xCED4, 0xBB1B), bn_pack4(0xDA3E, 0xDBEB, 0xCF9B, 0x14ED), bn_pack4(0x1797, 0x27B0, 0x865A, 0x8918), bn_pack4(0xB06A, 0x53ED, 0x9027, 0xD831), bn_pack4(0xE5DB, 0x382F, 0x4130, 0x01AE), bn_pack4(0xF8FF, 0x9406, 0xAD9E, 0x530E), bn_pack4(0xC975, 0x1E76, 0x3DBA, 0x37BD), bn_pack4(0xC1D4, 0xDCB2, 0x6026, 0x46DE), bn_pack4(0x36C3, 0xFAB4, 0xD27C, 0x7026), bn_pack4(0x4DF4, 0x35C9, 0x3402, 0x8492), bn_pack4(0x86FF, 0xB7DC, 0x90A6, 0xC08F), bn_pack4(0x93B4, 0xEA98, 0x8D8F, 0xDDC1), bn_pack4(0xD006, 0x9127, 0xD5B0, 0x5AA9), bn_pack4(0xB81B, 0xDD76, 0x2170, 0x481C), bn_pack4(0x1F61, 0x2970, 0xCEE2, 0xD7AF), bn_pack4(0x233B, 0xA186, 0x515B, 0xE7ED), bn_pack4(0x99B2, 0x964F, 0xA090, 0xC3A2), bn_pack4(0x287C, 0x5947, 0x4E6B, 0xC05D), bn_pack4(0x2E8E, 0xFC14, 0x1FBE, 0xCAA6), bn_pack4(0xDBBB, 0xC2DB, 0x04DE, 0x8EF9), bn_pack4(0x2583, 0xE9CA, 0x2AD4, 0x4CE8), bn_pack4(0x1A94, 0x6834, 0xB615, 0x0BDA), bn_pack4(0x99C3, 0x2718, 0x6AF4, 0xE23C), bn_pack4(0x8871, 0x9A10, 0xBDBA, 0x5B26), bn_pack4(0x1A72, 0x3C12, 0xA787, 0xE6D7), bn_pack4(0x4B82, 0xD120, 0xA921, 0x0801), bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E), bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31), bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2), bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C), bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C), bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64), bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864), bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B), bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D), bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7), bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7), bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D), bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A), bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64), bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33), bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D), bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510), bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5), bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718), bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9), bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F), bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603), bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B), bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C), bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804), bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D), bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB), bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96), bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F), bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A), bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05), bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D), bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6), bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5), bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED), bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B), bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6), bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245), bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437), bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B), bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD), bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22), bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74), bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1), bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234), bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF) }; const BIGNUM ossl_bn_group_8192 = { (BN_ULONG *)bn_group_8192_value, OSSL_NELEM(bn_group_8192_value), OSSL_NELEM(bn_group_8192_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_generator_19_value[] = { 19 }; const BIGNUM ossl_bn_generator_19 = { (BN_ULONG *)bn_generator_19_value, 1, 1, 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_generator_5_value[] = { 5 }; const BIGNUM ossl_bn_generator_5 = { (BN_ULONG *)bn_generator_5_value, 1, 1, 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_generator_2_value[] = { 2 }; const BIGNUM ossl_bn_generator_2 = { (BN_ULONG *)bn_generator_2_value, 1, 1, 0, BN_FLG_STATIC_DATA }; #endif
./openssl/crypto/bn/bn_blind.c
/* * Copyright 1998-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/opensslconf.h> #include "internal/cryptlib.h" #include "bn_local.h" #define BN_BLINDING_COUNTER 32 struct bn_blinding_st { BIGNUM *A; BIGNUM *Ai; BIGNUM *e; BIGNUM *mod; /* just a reference */ CRYPTO_THREAD_ID tid; int counter; unsigned long flags; BN_MONT_CTX *m_ctx; int (*bn_mod_exp) (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); CRYPTO_RWLOCK *lock; }; BN_BLINDING *BN_BLINDING_new(const BIGNUM *A, const BIGNUM *Ai, BIGNUM *mod) { BN_BLINDING *ret = NULL; bn_check_top(mod); if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { ERR_raise(ERR_LIB_BN, ERR_R_CRYPTO_LIB); OPENSSL_free(ret); return NULL; } BN_BLINDING_set_current_thread(ret); if (A != NULL) { if ((ret->A = BN_dup(A)) == NULL) goto err; } if (Ai != NULL) { if ((ret->Ai = BN_dup(Ai)) == NULL) goto err; } /* save a copy of mod in the BN_BLINDING structure */ if ((ret->mod = BN_dup(mod)) == NULL) goto err; if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0) BN_set_flags(ret->mod, BN_FLG_CONSTTIME); /* * Set the counter to the special value -1 to indicate that this is * never-used fresh blinding that does not need updating before first * use. */ ret->counter = -1; return ret; err: BN_BLINDING_free(ret); return NULL; } void BN_BLINDING_free(BN_BLINDING *r) { if (r == NULL) return; BN_free(r->A); BN_free(r->Ai); BN_free(r->e); BN_free(r->mod); CRYPTO_THREAD_lock_free(r->lock); OPENSSL_free(r); } int BN_BLINDING_update(BN_BLINDING *b, BN_CTX *ctx) { int ret = 0; if ((b->A == NULL) || (b->Ai == NULL)) { ERR_raise(ERR_LIB_BN, BN_R_NOT_INITIALIZED); goto err; } if (b->counter == -1) b->counter = 0; if (++b->counter == BN_BLINDING_COUNTER && b->e != NULL && !(b->flags & BN_BLINDING_NO_RECREATE)) { /* re-create blinding parameters */ if (!BN_BLINDING_create_param(b, NULL, NULL, ctx, NULL, NULL)) goto err; } else if (!(b->flags & BN_BLINDING_NO_UPDATE)) { if (b->m_ctx != NULL) { if (!bn_mul_mont_fixed_top(b->Ai, b->Ai, b->Ai, b->m_ctx, ctx) || !bn_mul_mont_fixed_top(b->A, b->A, b->A, b->m_ctx, ctx)) goto err; } else { if (!BN_mod_mul(b->Ai, b->Ai, b->Ai, b->mod, ctx) || !BN_mod_mul(b->A, b->A, b->A, b->mod, ctx)) goto err; } } ret = 1; err: if (b->counter == BN_BLINDING_COUNTER) b->counter = 0; return ret; } int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx) { return BN_BLINDING_convert_ex(n, NULL, b, ctx); } int BN_BLINDING_convert_ex(BIGNUM *n, BIGNUM *r, BN_BLINDING *b, BN_CTX *ctx) { int ret = 1; bn_check_top(n); if ((b->A == NULL) || (b->Ai == NULL)) { ERR_raise(ERR_LIB_BN, BN_R_NOT_INITIALIZED); return 0; } if (b->counter == -1) /* Fresh blinding, doesn't need updating. */ b->counter = 0; else if (!BN_BLINDING_update(b, ctx)) return 0; if (r != NULL && (BN_copy(r, b->Ai) == NULL)) return 0; if (b->m_ctx != NULL) ret = BN_mod_mul_montgomery(n, n, b->A, b->m_ctx, ctx); else ret = BN_mod_mul(n, n, b->A, b->mod, ctx); return ret; } int BN_BLINDING_invert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx) { return BN_BLINDING_invert_ex(n, NULL, b, ctx); } int BN_BLINDING_invert_ex(BIGNUM *n, const BIGNUM *r, BN_BLINDING *b, BN_CTX *ctx) { int ret; bn_check_top(n); if (r == NULL && (r = b->Ai) == NULL) { ERR_raise(ERR_LIB_BN, BN_R_NOT_INITIALIZED); return 0; } if (b->m_ctx != NULL) { /* ensure that BN_mod_mul_montgomery takes pre-defined path */ if (n->dmax >= r->top) { size_t i, rtop = r->top, ntop = n->top; BN_ULONG mask; for (i = 0; i < rtop; i++) { mask = (BN_ULONG)0 - ((i - ntop) >> (8 * sizeof(i) - 1)); n->d[i] &= mask; } mask = (BN_ULONG)0 - ((rtop - ntop) >> (8 * sizeof(ntop) - 1)); /* always true, if (rtop >= ntop) n->top = r->top; */ n->top = (int)(rtop & ~mask) | (ntop & mask); n->flags |= (BN_FLG_FIXED_TOP & ~mask); } ret = bn_mul_mont_fixed_top(n, n, r, b->m_ctx, ctx); bn_correct_top_consttime(n); } else { ret = BN_mod_mul(n, n, r, b->mod, ctx); } bn_check_top(n); return ret; } int BN_BLINDING_is_current_thread(BN_BLINDING *b) { return CRYPTO_THREAD_compare_id(CRYPTO_THREAD_get_current_id(), b->tid); } void BN_BLINDING_set_current_thread(BN_BLINDING *b) { b->tid = CRYPTO_THREAD_get_current_id(); } int BN_BLINDING_lock(BN_BLINDING *b) { return CRYPTO_THREAD_write_lock(b->lock); } int BN_BLINDING_unlock(BN_BLINDING *b) { return CRYPTO_THREAD_unlock(b->lock); } unsigned long BN_BLINDING_get_flags(const BN_BLINDING *b) { return b->flags; } void BN_BLINDING_set_flags(BN_BLINDING *b, unsigned long flags) { b->flags = flags; } BN_BLINDING *BN_BLINDING_create_param(BN_BLINDING *b, const BIGNUM *e, BIGNUM *m, BN_CTX *ctx, int (*bn_mod_exp) (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx), BN_MONT_CTX *m_ctx) { int retry_counter = 32; BN_BLINDING *ret = NULL; if (b == NULL) ret = BN_BLINDING_new(NULL, NULL, m); else ret = b; if (ret == NULL) goto err; if (ret->A == NULL && (ret->A = BN_new()) == NULL) goto err; if (ret->Ai == NULL && (ret->Ai = BN_new()) == NULL) goto err; if (e != NULL) { BN_free(ret->e); ret->e = BN_dup(e); } if (ret->e == NULL) goto err; if (bn_mod_exp != NULL) ret->bn_mod_exp = bn_mod_exp; if (m_ctx != NULL) ret->m_ctx = m_ctx; do { int rv; if (!BN_priv_rand_range_ex(ret->A, ret->mod, 0, ctx)) goto err; if (int_bn_mod_inverse(ret->Ai, ret->A, ret->mod, ctx, &rv)) break; /* * this should almost never happen for good RSA keys */ if (!rv) goto err; if (retry_counter-- == 0) { ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS); goto err; } } while (1); if (ret->bn_mod_exp != NULL && ret->m_ctx != NULL) { if (!ret->bn_mod_exp(ret->A, ret->A, ret->e, ret->mod, ctx, ret->m_ctx)) goto err; } else { if (!BN_mod_exp(ret->A, ret->A, ret->e, ret->mod, ctx)) goto err; } if (ret->m_ctx != NULL) { if (!bn_to_mont_fixed_top(ret->Ai, ret->Ai, ret->m_ctx, ctx) || !bn_to_mont_fixed_top(ret->A, ret->A, ret->m_ctx, ctx)) goto err; } return ret; err: if (b == NULL) { BN_BLINDING_free(ret); ret = NULL; } return ret; }
./openssl/crypto/bn/bn_exp.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include "internal/constant_time.h" #include "bn_local.h" #include <stdlib.h> #ifdef _WIN32 # include <malloc.h> # ifndef alloca # define alloca _alloca # endif #elif defined(__GNUC__) # ifndef alloca # define alloca(s) __builtin_alloca((s)) # endif #elif defined(__sun) # include <alloca.h> #endif #include "rsaz_exp.h" #undef SPARC_T4_MONT #if defined(OPENSSL_BN_ASM_MONT) && (defined(__sparc__) || defined(__sparc)) # include "crypto/sparc_arch.h" # define SPARC_T4_MONT #endif /* maximum precomputation table size for *variable* sliding windows */ #define TABLE_SIZE 32 /* * Beyond this limit the constant time code is disabled due to * the possible overflow in the computation of powerbufLen in * BN_mod_exp_mont_consttime. * When this limit is exceeded, the computation will be done using * non-constant time code, but it will take very long. */ #define BN_CONSTTIME_SIZE_LIMIT (INT_MAX / BN_BYTES / 256) /* this one works - simple but works */ int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { int i, bits, ret = 0; BIGNUM *v, *rr; if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 || BN_get_flags(a, BN_FLG_CONSTTIME) != 0) { /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ ERR_raise(ERR_LIB_BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } BN_CTX_start(ctx); rr = ((r == a) || (r == p)) ? BN_CTX_get(ctx) : r; v = BN_CTX_get(ctx); if (rr == NULL || v == NULL) goto err; if (BN_copy(v, a) == NULL) goto err; bits = BN_num_bits(p); if (BN_is_odd(p)) { if (BN_copy(rr, a) == NULL) goto err; } else { if (!BN_one(rr)) goto err; } for (i = 1; i < bits; i++) { if (!BN_sqr(v, v, ctx)) goto err; if (BN_is_bit_set(p, i)) { if (!BN_mul(rr, rr, v, ctx)) goto err; } } if (r != rr && BN_copy(r, rr) == NULL) goto err; ret = 1; err: BN_CTX_end(ctx); bn_check_top(r); return ret; } int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx) { int ret; bn_check_top(a); bn_check_top(p); bn_check_top(m); /*- * For even modulus m = 2^k*m_odd, it might make sense to compute * a^p mod m_odd and a^p mod 2^k separately (with Montgomery * exponentiation for the odd part), using appropriate exponent * reductions, and combine the results using the CRT. * * For now, we use Montgomery only if the modulus is odd; otherwise, * exponentiation using the reciprocal-based quick remaindering * algorithm is used. * * (Timing obtained with expspeed.c [computations a^p mod m * where a, p, m are of the same length: 256, 512, 1024, 2048, * 4096, 8192 bits], compared to the running time of the * standard algorithm: * * BN_mod_exp_mont 33 .. 40 % [AMD K6-2, Linux, debug configuration] * 55 .. 77 % [UltraSparc processor, but * debug-solaris-sparcv8-gcc conf.] * * BN_mod_exp_recp 50 .. 70 % [AMD K6-2, Linux, debug configuration] * 62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc] * * On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont * at 2048 and more bits, but at 512 and 1024 bits, it was * slower even than the standard algorithm! * * "Real" timings [linux-elf, solaris-sparcv9-gcc configurations] * should be obtained when the new Montgomery reduction code * has been integrated into OpenSSL.) */ #define MONT_MUL_MOD #define MONT_EXP_WORD #define RECP_MUL_MOD #ifdef MONT_MUL_MOD if (BN_is_odd(m)) { # ifdef MONT_EXP_WORD if (a->top == 1 && !a->neg && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0) && (BN_get_flags(a, BN_FLG_CONSTTIME) == 0) && (BN_get_flags(m, BN_FLG_CONSTTIME) == 0)) { BN_ULONG A = a->d[0]; ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL); } else # endif ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL); } else #endif #ifdef RECP_MUL_MOD { ret = BN_mod_exp_recp(r, a, p, m, ctx); } #else { ret = BN_mod_exp_simple(r, a, p, m, ctx); } #endif bn_check_top(r); return ret; } int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx) { int i, j, bits, ret = 0, wstart, wend, window; int start = 1; BIGNUM *aa; /* Table of variables obtained from 'ctx' */ BIGNUM *val[TABLE_SIZE]; BN_RECP_CTX recp; if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 || BN_get_flags(a, BN_FLG_CONSTTIME) != 0 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) { /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ ERR_raise(ERR_LIB_BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1, or x**0 mod -1 is still zero. */ if (BN_abs_is_word(m, 1)) { ret = 1; BN_zero(r); } else { ret = BN_one(r); } return ret; } BN_RECP_CTX_init(&recp); BN_CTX_start(ctx); aa = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); if (val[0] == NULL) goto err; if (m->neg) { /* ignore sign of 'm' */ if (!BN_copy(aa, m)) goto err; aa->neg = 0; if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0) goto err; } else { if (BN_RECP_CTX_set(&recp, m, ctx) <= 0) goto err; } if (!BN_nnmod(val[0], a, m, ctx)) goto err; /* 1 */ if (BN_is_zero(val[0])) { BN_zero(r); ret = 1; goto err; } window = BN_window_bits_for_exponent_size(bits); if (window > 1) { if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx)) goto err; /* 2 */ j = 1 << (window - 1); for (i = 1; i < j; i++) { if (((val[i] = BN_CTX_get(ctx)) == NULL) || !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx)) goto err; } } start = 1; /* This is used to avoid multiplication etc * when there is only the value '1' in the * buffer. */ wstart = bits - 1; /* The top bit of the window */ wend = 0; /* The bottom bit of the window */ if (r == p) { BIGNUM *p_dup = BN_CTX_get(ctx); if (p_dup == NULL || BN_copy(p_dup, p) == NULL) goto err; p = p_dup; } if (!BN_one(r)) goto err; for (;;) { int wvalue; /* The 'value' of the window */ if (BN_is_bit_set(p, wstart) == 0) { if (!start) if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) goto err; if (wstart == 0) break; wstart--; continue; } /* * We now have wstart on a 'set' bit, we now need to work out how bit * a window to do. To do this we need to scan forward until the last * set bit before the end of the window */ wvalue = 1; wend = 0; for (i = 1; i < window; i++) { if (wstart - i < 0) break; if (BN_is_bit_set(p, wstart - i)) { wvalue <<= (i - wend); wvalue |= 1; wend = i; } } /* wend is the size of the current window */ j = wend + 1; /* add the 'bytes above' */ if (!start) for (i = 0; i < j; i++) { if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) goto err; } /* wvalue will be an odd number < 2^window */ if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx)) goto err; /* move the 'window' down further */ wstart -= wend + 1; start = 0; if (wstart < 0) break; } ret = 1; err: BN_CTX_end(ctx); BN_RECP_CTX_free(&recp); bn_check_top(r); return ret; } int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) { int i, j, bits, ret = 0, wstart, wend, window; int start = 1; BIGNUM *d, *r; const BIGNUM *aa; /* Table of variables obtained from 'ctx' */ BIGNUM *val[TABLE_SIZE]; BN_MONT_CTX *mont = NULL; bn_check_top(a); bn_check_top(p); bn_check_top(m); if (!BN_is_odd(m)) { ERR_raise(ERR_LIB_BN, BN_R_CALLED_WITH_EVEN_MODULUS); return 0; } if (m->top <= BN_CONSTTIME_SIZE_LIMIT && (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 || BN_get_flags(a, BN_FLG_CONSTTIME) != 0 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0)) { return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont); } bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1, or x**0 mod -1 is still zero. */ if (BN_abs_is_word(m, 1)) { ret = 1; BN_zero(rr); } else { ret = BN_one(rr); } return ret; } BN_CTX_start(ctx); d = BN_CTX_get(ctx); r = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); if (val[0] == NULL) goto err; /* * If this is not done, things will break in the montgomery part */ if (in_mont != NULL) mont = in_mont; else { if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, m, ctx)) goto err; } if (a->neg || BN_ucmp(a, m) >= 0) { if (!BN_nnmod(val[0], a, m, ctx)) goto err; aa = val[0]; } else aa = a; if (!bn_to_mont_fixed_top(val[0], aa, mont, ctx)) goto err; /* 1 */ window = BN_window_bits_for_exponent_size(bits); if (window > 1) { if (!bn_mul_mont_fixed_top(d, val[0], val[0], mont, ctx)) goto err; /* 2 */ j = 1 << (window - 1); for (i = 1; i < j; i++) { if (((val[i] = BN_CTX_get(ctx)) == NULL) || !bn_mul_mont_fixed_top(val[i], val[i - 1], d, mont, ctx)) goto err; } } start = 1; /* This is used to avoid multiplication etc * when there is only the value '1' in the * buffer. */ wstart = bits - 1; /* The top bit of the window */ wend = 0; /* The bottom bit of the window */ #if 1 /* by Shay Gueron's suggestion */ j = m->top; /* borrow j */ if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) { if (bn_wexpand(r, j) == NULL) goto err; /* 2^(top*BN_BITS2) - m */ r->d[0] = (0 - m->d[0]) & BN_MASK2; for (i = 1; i < j; i++) r->d[i] = (~m->d[i]) & BN_MASK2; r->top = j; r->flags |= BN_FLG_FIXED_TOP; } else #endif if (!bn_to_mont_fixed_top(r, BN_value_one(), mont, ctx)) goto err; for (;;) { int wvalue; /* The 'value' of the window */ if (BN_is_bit_set(p, wstart) == 0) { if (!start) { if (!bn_mul_mont_fixed_top(r, r, r, mont, ctx)) goto err; } if (wstart == 0) break; wstart--; continue; } /* * We now have wstart on a 'set' bit, we now need to work out how bit * a window to do. To do this we need to scan forward until the last * set bit before the end of the window */ wvalue = 1; wend = 0; for (i = 1; i < window; i++) { if (wstart - i < 0) break; if (BN_is_bit_set(p, wstart - i)) { wvalue <<= (i - wend); wvalue |= 1; wend = i; } } /* wend is the size of the current window */ j = wend + 1; /* add the 'bytes above' */ if (!start) for (i = 0; i < j; i++) { if (!bn_mul_mont_fixed_top(r, r, r, mont, ctx)) goto err; } /* wvalue will be an odd number < 2^window */ if (!bn_mul_mont_fixed_top(r, r, val[wvalue >> 1], mont, ctx)) goto err; /* move the 'window' down further */ wstart -= wend + 1; start = 0; if (wstart < 0) break; } /* * Done with zero-padded intermediate BIGNUMs. Final BN_from_montgomery * removes padding [if any] and makes return value suitable for public * API consumer. */ #if defined(SPARC_T4_MONT) if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) { j = mont->N.top; /* borrow j */ val[0]->d[0] = 1; /* borrow val[0] */ for (i = 1; i < j; i++) val[0]->d[i] = 0; val[0]->top = j; if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx)) goto err; } else #endif if (!BN_from_montgomery(rr, r, mont, ctx)) goto err; ret = 1; err: if (in_mont == NULL) BN_MONT_CTX_free(mont); BN_CTX_end(ctx); bn_check_top(rr); return ret; } static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos) { BN_ULONG ret = 0; int wordpos; wordpos = bitpos / BN_BITS2; bitpos %= BN_BITS2; if (wordpos >= 0 && wordpos < a->top) { ret = a->d[wordpos] & BN_MASK2; if (bitpos) { ret >>= bitpos; if (++wordpos < a->top) ret |= a->d[wordpos] << (BN_BITS2 - bitpos); } } return ret & BN_MASK2; } /* * BN_mod_exp_mont_consttime() stores the precomputed powers in a specific * layout so that accessing any of these table values shows the same access * pattern as far as cache lines are concerned. The following functions are * used to transfer a BIGNUM from/to that table. */ static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top, unsigned char *buf, int idx, int window) { int i, j; int width = 1 << window; BN_ULONG *table = (BN_ULONG *)buf; if (top > b->top) top = b->top; /* this works because 'buf' is explicitly * zeroed */ for (i = 0, j = idx; i < top; i++, j += width) { table[j] = b->d[i]; } return 1; } static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top, unsigned char *buf, int idx, int window) { int i, j; int width = 1 << window; /* * We declare table 'volatile' in order to discourage compiler * from reordering loads from the table. Concern is that if * reordered in specific manner loads might give away the * information we are trying to conceal. Some would argue that * compiler can reorder them anyway, but it can as well be * argued that doing so would be violation of standard... */ volatile BN_ULONG *table = (volatile BN_ULONG *)buf; if (bn_wexpand(b, top) == NULL) return 0; if (window <= 3) { for (i = 0; i < top; i++, table += width) { BN_ULONG acc = 0; for (j = 0; j < width; j++) { acc |= table[j] & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1)); } b->d[i] = acc; } } else { int xstride = 1 << (window - 2); BN_ULONG y0, y1, y2, y3; i = idx >> (window - 2); /* equivalent of idx / xstride */ idx &= xstride - 1; /* equivalent of idx % xstride */ y0 = (BN_ULONG)0 - (constant_time_eq_int(i,0)&1); y1 = (BN_ULONG)0 - (constant_time_eq_int(i,1)&1); y2 = (BN_ULONG)0 - (constant_time_eq_int(i,2)&1); y3 = (BN_ULONG)0 - (constant_time_eq_int(i,3)&1); for (i = 0; i < top; i++, table += width) { BN_ULONG acc = 0; for (j = 0; j < xstride; j++) { acc |= ( (table[j + 0 * xstride] & y0) | (table[j + 1 * xstride] & y1) | (table[j + 2 * xstride] & y2) | (table[j + 3 * xstride] & y3) ) & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1)); } b->d[i] = acc; } } b->top = top; b->flags |= BN_FLG_FIXED_TOP; return 1; } /* * Given a pointer value, compute the next address that is a cache line * multiple. */ #define MOD_EXP_CTIME_ALIGN(x_) \ ((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK)))) /* * This variant of BN_mod_exp_mont() uses fixed windows and the special * precomputation memory layout to limit data-dependency to a minimum to * protect secret exponents (cf. the hyper-threading timing attacks pointed * out by Colin Percival, * http://www.daemonology.net/hyperthreading-considered-harmful/) */ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) { int i, bits, ret = 0, window, wvalue, wmask, window0; int top; BN_MONT_CTX *mont = NULL; int numPowers; unsigned char *powerbufFree = NULL; int powerbufLen = 0; unsigned char *powerbuf = NULL; BIGNUM tmp, am; #if defined(SPARC_T4_MONT) unsigned int t4 = 0; #endif bn_check_top(a); bn_check_top(p); bn_check_top(m); if (!BN_is_odd(m)) { ERR_raise(ERR_LIB_BN, BN_R_CALLED_WITH_EVEN_MODULUS); return 0; } top = m->top; if (top > BN_CONSTTIME_SIZE_LIMIT) { /* Prevent overflowing the powerbufLen computation below */ return BN_mod_exp_mont(rr, a, p, m, ctx, in_mont); } /* * Use all bits stored in |p|, rather than |BN_num_bits|, so we do not leak * whether the top bits are zero. */ bits = p->top * BN_BITS2; if (bits == 0) { /* x**0 mod 1, or x**0 mod -1 is still zero. */ if (BN_abs_is_word(m, 1)) { ret = 1; BN_zero(rr); } else { ret = BN_one(rr); } return ret; } BN_CTX_start(ctx); /* * Allocate a montgomery context if it was not supplied by the caller. If * this is not done, things will break in the montgomery part. */ if (in_mont != NULL) mont = in_mont; else { if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, m, ctx)) goto err; } if (a->neg || BN_ucmp(a, m) >= 0) { BIGNUM *reduced = BN_CTX_get(ctx); if (reduced == NULL || !BN_nnmod(reduced, a, m, ctx)) { goto err; } a = reduced; } #ifdef RSAZ_ENABLED /* * If the size of the operands allow it, perform the optimized * RSAZ exponentiation. For further information see * crypto/bn/rsaz_exp.c and accompanying assembly modules. */ if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024) && rsaz_avx2_eligible()) { if (NULL == bn_wexpand(rr, 16)) goto err; RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d, mont->n0[0]); rr->top = 16; rr->neg = 0; bn_correct_top(rr); ret = 1; goto err; } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) { if (NULL == bn_wexpand(rr, 8)) goto err; RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d); rr->top = 8; rr->neg = 0; bn_correct_top(rr); ret = 1; goto err; } #endif /* Get the window size to use with size of p. */ window = BN_window_bits_for_ctime_exponent_size(bits); #if defined(SPARC_T4_MONT) if (window >= 5 && (top & 15) == 0 && top <= 64 && (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) == (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0])) window = 5; else #endif #if defined(OPENSSL_BN_ASM_MONT5) if (window >= 5 && top <= BN_SOFT_LIMIT) { window = 5; /* ~5% improvement for RSA2048 sign, and even * for RSA4096 */ /* reserve space for mont->N.d[] copy */ powerbufLen += top * sizeof(mont->N.d[0]); } #endif (void)0; /* * Allocate a buffer large enough to hold all of the pre-computed powers * of am, am itself and tmp. */ numPowers = 1 << window; powerbufLen += sizeof(m->d[0]) * (top * numPowers + ((2 * top) > numPowers ? (2 * top) : numPowers)); #ifdef alloca if (powerbufLen < 3072) powerbufFree = alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH); else #endif if ((powerbufFree = OPENSSL_malloc(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH)) == NULL) goto err; powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree); memset(powerbuf, 0, powerbufLen); #ifdef alloca if (powerbufLen < 3072) powerbufFree = NULL; #endif /* lay down tmp and am right after powers table */ tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers); am.d = tmp.d + top; tmp.top = am.top = 0; tmp.dmax = am.dmax = top; tmp.neg = am.neg = 0; tmp.flags = am.flags = BN_FLG_STATIC_DATA; /* prepare a^0 in Montgomery domain */ #if 1 /* by Shay Gueron's suggestion */ if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) { /* 2^(top*BN_BITS2) - m */ tmp.d[0] = (0 - m->d[0]) & BN_MASK2; for (i = 1; i < top; i++) tmp.d[i] = (~m->d[i]) & BN_MASK2; tmp.top = top; } else #endif if (!bn_to_mont_fixed_top(&tmp, BN_value_one(), mont, ctx)) goto err; /* prepare a^1 in Montgomery domain */ if (!bn_to_mont_fixed_top(&am, a, mont, ctx)) goto err; if (top > BN_SOFT_LIMIT) goto fallback; #if defined(SPARC_T4_MONT) if (t4) { typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); static const bn_pwr5_mont_f pwr5_funcs[4] = { bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16, bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32 }; bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1]; typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); static const bn_mul_mont_f mul_funcs[4] = { bn_mul_mont_t4_8, bn_mul_mont_t4_16, bn_mul_mont_t4_24, bn_mul_mont_t4_32 }; bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1]; void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap, const void *table, const BN_ULONG *np, const BN_ULONG *n0, int num, int power); void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num, void *table, size_t power); void bn_gather5_t4(BN_ULONG *out, size_t num, void *table, size_t power); void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num); BN_ULONG *np = mont->N.d, *n0 = mont->n0; int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less * than 32 */ /* * BN_to_montgomery can contaminate words above .top [in * BN_DEBUG build... */ for (i = am.top; i < top; i++) am.d[i] = 0; for (i = tmp.top; i < top; i++) tmp.d[i] = 0; bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0); bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1); if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) && !(*mul_worker) (tmp.d, am.d, am.d, np, n0)) bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top); bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2); for (i = 3; i < 32; i++) { /* Calculate a^i = a^(i-1) * a */ if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) && !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0)) bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top); bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i); } /* switch to 64-bit domain */ np = alloca(top * sizeof(BN_ULONG)); top /= 2; bn_flip_t4(np, mont->N.d, top); /* * The exponent may not have a whole number of fixed-size windows. * To simplify the main loop, the initial window has between 1 and * full-window-size bits such that what remains is always a whole * number of windows */ window0 = (bits - 1) % 5 + 1; wmask = (1 << window0) - 1; bits -= window0; wvalue = bn_get_bits(p, bits) & wmask; bn_gather5_t4(tmp.d, top, powerbuf, wvalue); /* * Scan the exponent one window at a time starting from the most * significant bits. */ while (bits > 0) { if (bits < stride) stride = bits; bits -= stride; wvalue = bn_get_bits(p, bits); if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride)) continue; /* retry once and fall back */ if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride)) continue; bits += stride - 5; wvalue >>= stride - 5; wvalue &= 31; bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue); } bn_flip_t4(tmp.d, tmp.d, top); top *= 2; /* back to 32-bit domain */ tmp.top = top; bn_correct_top(&tmp); OPENSSL_cleanse(np, top * sizeof(BN_ULONG)); } else #endif #if defined(OPENSSL_BN_ASM_MONT5) if (window == 5 && top > 1) { /* * This optimization uses ideas from https://eprint.iacr.org/2011/239, * specifically optimization of cache-timing attack countermeasures, * pre-computation optimization, and Almost Montgomery Multiplication. * * The paper discusses a 4-bit window to optimize 512-bit modular * exponentiation, used in RSA-1024 with CRT, but RSA-1024 is no longer * important. * * |bn_mul_mont_gather5| and |bn_power5| implement the "almost" * reduction variant, so the values here may not be fully reduced. * They are bounded by R (i.e. they fit in |top| words), not |m|. * Additionally, we pass these "almost" reduced inputs into * |bn_mul_mont|, which implements the normal reduction variant. * Given those inputs, |bn_mul_mont| may not give reduced * output, but it will still produce "almost" reduced output. */ void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, const void *table, const BN_ULONG *np, const BN_ULONG *n0, int num, int power); void bn_scatter5(const BN_ULONG *inp, size_t num, void *table, size_t power); void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power); void bn_power5(BN_ULONG *rp, const BN_ULONG *ap, const void *table, const BN_ULONG *np, const BN_ULONG *n0, int num, int power); int bn_get_bits5(const BN_ULONG *ap, int off); BN_ULONG *n0 = mont->n0, *np; /* * BN_to_montgomery can contaminate words above .top [in * BN_DEBUG build... */ for (i = am.top; i < top; i++) am.d[i] = 0; for (i = tmp.top; i < top; i++) tmp.d[i] = 0; /* * copy mont->N.d[] to improve cache locality */ for (np = am.d + top, i = 0; i < top; i++) np[i] = mont->N.d[i]; bn_scatter5(tmp.d, top, powerbuf, 0); bn_scatter5(am.d, am.top, powerbuf, 1); bn_mul_mont(tmp.d, am.d, am.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, 2); # if 0 for (i = 3; i < 32; i++) { /* Calculate a^i = a^(i-1) * a */ bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); } # else /* same as above, but uses squaring for 1/2 of operations */ for (i = 4; i < 32; i *= 2) { bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, i); } for (i = 3; i < 8; i += 2) { int j; bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); for (j = 2 * i; j < 32; j *= 2) { bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, j); } } for (; i < 16; i += 2) { bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, 2 * i); } for (; i < 32; i += 2) { bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); } # endif /* * The exponent may not have a whole number of fixed-size windows. * To simplify the main loop, the initial window has between 1 and * full-window-size bits such that what remains is always a whole * number of windows */ window0 = (bits - 1) % 5 + 1; wmask = (1 << window0) - 1; bits -= window0; wvalue = bn_get_bits(p, bits) & wmask; bn_gather5(tmp.d, top, powerbuf, wvalue); /* * Scan the exponent one window at a time starting from the most * significant bits. */ if (top & 7) { while (bits > 0) { bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top, bn_get_bits5(p->d, bits -= 5)); } } else { while (bits > 0) { bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, bn_get_bits5(p->d, bits -= 5)); } } tmp.top = top; /* * The result is now in |tmp| in Montgomery form, but it may not be * fully reduced. This is within bounds for |BN_from_montgomery| * (tmp < R <= m*R) so it will, when converting from Montgomery form, * produce a fully reduced result. * * This differs from Figure 2 of the paper, which uses AMM(h, 1) to * convert from Montgomery form with unreduced output, followed by an * extra reduction step. In the paper's terminology, we replace * steps 9 and 10 with MM(h, 1). */ } else #endif { fallback: if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window)) goto err; /* * If the window size is greater than 1, then calculate * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even * powers could instead be computed as (a^(i/2))^2 to use the slight * performance advantage of sqr over mul). */ if (window > 1) { if (!bn_mul_mont_fixed_top(&tmp, &am, &am, mont, ctx)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2, window)) goto err; for (i = 3; i < numPowers; i++) { /* Calculate a^i = a^(i-1) * a */ if (!bn_mul_mont_fixed_top(&tmp, &am, &tmp, mont, ctx)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i, window)) goto err; } } /* * The exponent may not have a whole number of fixed-size windows. * To simplify the main loop, the initial window has between 1 and * full-window-size bits such that what remains is always a whole * number of windows */ window0 = (bits - 1) % window + 1; wmask = (1 << window0) - 1; bits -= window0; wvalue = bn_get_bits(p, bits) & wmask; if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue, window)) goto err; wmask = (1 << window) - 1; /* * Scan the exponent one window at a time starting from the most * significant bits. */ while (bits > 0) { /* Square the result window-size times */ for (i = 0; i < window; i++) if (!bn_mul_mont_fixed_top(&tmp, &tmp, &tmp, mont, ctx)) goto err; /* * Get a window's worth of bits from the exponent * This avoids calling BN_is_bit_set for each bit, which * is not only slower but also makes each bit vulnerable to * EM (and likely other) side-channel attacks like One&Done * (for details see "One&Done: A Single-Decryption EM-Based * Attack on OpenSSL's Constant-Time Blinded RSA" by M. Alam, * H. Khan, M. Dey, N. Sinha, R. Callan, A. Zajic, and * M. Prvulovic, in USENIX Security'18) */ bits -= window; wvalue = bn_get_bits(p, bits) & wmask; /* * Fetch the appropriate pre-computed value from the pre-buf */ if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue, window)) goto err; /* Multiply the result into the intermediate result */ if (!bn_mul_mont_fixed_top(&tmp, &tmp, &am, mont, ctx)) goto err; } } /* * Done with zero-padded intermediate BIGNUMs. Final BN_from_montgomery * removes padding [if any] and makes return value suitable for public * API consumer. */ #if defined(SPARC_T4_MONT) if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) { am.d[0] = 1; /* borrow am */ for (i = 1; i < top; i++) am.d[i] = 0; if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx)) goto err; } else #endif if (!BN_from_montgomery(rr, &tmp, mont, ctx)) goto err; ret = 1; err: if (in_mont == NULL) BN_MONT_CTX_free(mont); if (powerbuf != NULL) { OPENSSL_cleanse(powerbuf, powerbufLen); OPENSSL_free(powerbufFree); } BN_CTX_end(ctx); return ret; } int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) { BN_MONT_CTX *mont = NULL; int b, bits, ret = 0; int r_is_one; BN_ULONG w, next_w; BIGNUM *r, *t; BIGNUM *swap_tmp; #define BN_MOD_MUL_WORD(r, w, m) \ (BN_mul_word(r, (w)) && \ (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \ (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1)))) /* * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is * probably more overhead than always using BN_mod (which uses BN_copy if * a similar test returns true). */ /* * We can use BN_mod and do not need BN_nnmod because our accumulator is * never negative (the result of BN_mod does not depend on the sign of * the modulus). */ #define BN_TO_MONTGOMERY_WORD(r, w, mont) \ (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx)) if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) { /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ ERR_raise(ERR_LIB_BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } bn_check_top(p); bn_check_top(m); if (!BN_is_odd(m)) { ERR_raise(ERR_LIB_BN, BN_R_CALLED_WITH_EVEN_MODULUS); return 0; } if (m->top == 1) a %= m->d[0]; /* make sure that 'a' is reduced */ bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1, or x**0 mod -1 is still zero. */ if (BN_abs_is_word(m, 1)) { ret = 1; BN_zero(rr); } else { ret = BN_one(rr); } return ret; } if (a == 0) { BN_zero(rr); ret = 1; return ret; } BN_CTX_start(ctx); r = BN_CTX_get(ctx); t = BN_CTX_get(ctx); if (t == NULL) goto err; if (in_mont != NULL) mont = in_mont; else { if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, m, ctx)) goto err; } r_is_one = 1; /* except for Montgomery factor */ /* bits-1 >= 0 */ /* The result is accumulated in the product r*w. */ w = a; /* bit 'bits-1' of 'p' is always set */ for (b = bits - 2; b >= 0; b--) { /* First, square r*w. */ next_w = w * w; if ((next_w / w) != w) { /* overflow */ if (r_is_one) { if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) goto err; r_is_one = 0; } else { if (!BN_MOD_MUL_WORD(r, w, m)) goto err; } next_w = 1; } w = next_w; if (!r_is_one) { if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) goto err; } /* Second, multiply r*w by 'a' if exponent bit is set. */ if (BN_is_bit_set(p, b)) { next_w = w * a; if ((next_w / a) != w) { /* overflow */ if (r_is_one) { if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) goto err; r_is_one = 0; } else { if (!BN_MOD_MUL_WORD(r, w, m)) goto err; } next_w = a; } w = next_w; } } /* Finally, set r:=r*w. */ if (w != 1) { if (r_is_one) { if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) goto err; r_is_one = 0; } else { if (!BN_MOD_MUL_WORD(r, w, m)) goto err; } } if (r_is_one) { /* can happen only if a == 1 */ if (!BN_one(rr)) goto err; } else { if (!BN_from_montgomery(rr, r, mont, ctx)) goto err; } ret = 1; err: if (in_mont == NULL) BN_MONT_CTX_free(mont); BN_CTX_end(ctx); bn_check_top(rr); return ret; } /* The old fallback, simple version :-) */ int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx) { int i, j, bits, ret = 0, wstart, wend, window; int start = 1; BIGNUM *d; /* Table of variables obtained from 'ctx' */ BIGNUM *val[TABLE_SIZE]; if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 || BN_get_flags(a, BN_FLG_CONSTTIME) != 0 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) { /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ ERR_raise(ERR_LIB_BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (r == m) { ERR_raise(ERR_LIB_BN, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1, or x**0 mod -1 is still zero. */ if (BN_abs_is_word(m, 1)) { ret = 1; BN_zero(r); } else { ret = BN_one(r); } return ret; } BN_CTX_start(ctx); d = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); if (val[0] == NULL) goto err; if (!BN_nnmod(val[0], a, m, ctx)) goto err; /* 1 */ if (BN_is_zero(val[0])) { BN_zero(r); ret = 1; goto err; } window = BN_window_bits_for_exponent_size(bits); if (window > 1) { if (!BN_mod_mul(d, val[0], val[0], m, ctx)) goto err; /* 2 */ j = 1 << (window - 1); for (i = 1; i < j; i++) { if (((val[i] = BN_CTX_get(ctx)) == NULL) || !BN_mod_mul(val[i], val[i - 1], d, m, ctx)) goto err; } } start = 1; /* This is used to avoid multiplication etc * when there is only the value '1' in the * buffer. */ wstart = bits - 1; /* The top bit of the window */ wend = 0; /* The bottom bit of the window */ if (r == p) { BIGNUM *p_dup = BN_CTX_get(ctx); if (p_dup == NULL || BN_copy(p_dup, p) == NULL) goto err; p = p_dup; } if (!BN_one(r)) goto err; for (;;) { int wvalue; /* The 'value' of the window */ if (BN_is_bit_set(p, wstart) == 0) { if (!start) if (!BN_mod_mul(r, r, r, m, ctx)) goto err; if (wstart == 0) break; wstart--; continue; } /* * We now have wstart on a 'set' bit, we now need to work out how bit * a window to do. To do this we need to scan forward until the last * set bit before the end of the window */ wvalue = 1; wend = 0; for (i = 1; i < window; i++) { if (wstart - i < 0) break; if (BN_is_bit_set(p, wstart - i)) { wvalue <<= (i - wend); wvalue |= 1; wend = i; } } /* wend is the size of the current window */ j = wend + 1; /* add the 'bytes above' */ if (!start) for (i = 0; i < j; i++) { if (!BN_mod_mul(r, r, r, m, ctx)) goto err; } /* wvalue will be an odd number < 2^window */ if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx)) goto err; /* move the 'window' down further */ wstart -= wend + 1; start = 0; if (wstart < 0) break; } ret = 1; err: BN_CTX_end(ctx); bn_check_top(r); return ret; } /* * This is a variant of modular exponentiation optimization that does * parallel 2-primes exponentiation using 256-bit (AVX512VL) AVX512_IFMA ISA * in 52-bit binary redundant representation. * If such instructions are not available, or input data size is not supported, * it falls back to two BN_mod_exp_mont_consttime() calls. */ int BN_mod_exp_mont_consttime_x2(BIGNUM *rr1, const BIGNUM *a1, const BIGNUM *p1, const BIGNUM *m1, BN_MONT_CTX *in_mont1, BIGNUM *rr2, const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m2, BN_MONT_CTX *in_mont2, BN_CTX *ctx) { int ret = 0; #ifdef RSAZ_ENABLED BN_MONT_CTX *mont1 = NULL; BN_MONT_CTX *mont2 = NULL; if (ossl_rsaz_avx512ifma_eligible() && (((a1->top == 16) && (p1->top == 16) && (BN_num_bits(m1) == 1024) && (a2->top == 16) && (p2->top == 16) && (BN_num_bits(m2) == 1024)) || ((a1->top == 24) && (p1->top == 24) && (BN_num_bits(m1) == 1536) && (a2->top == 24) && (p2->top == 24) && (BN_num_bits(m2) == 1536)) || ((a1->top == 32) && (p1->top == 32) && (BN_num_bits(m1) == 2048) && (a2->top == 32) && (p2->top == 32) && (BN_num_bits(m2) == 2048)))) { int topn = a1->top; /* Modulus bits of |m1| and |m2| are equal */ int mod_bits = BN_num_bits(m1); if (bn_wexpand(rr1, topn) == NULL) goto err; if (bn_wexpand(rr2, topn) == NULL) goto err; /* Ensure that montgomery contexts are initialized */ if (in_mont1 != NULL) { mont1 = in_mont1; } else { if ((mont1 = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont1, m1, ctx)) goto err; } if (in_mont2 != NULL) { mont2 = in_mont2; } else { if ((mont2 = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont2, m2, ctx)) goto err; } ret = ossl_rsaz_mod_exp_avx512_x2(rr1->d, a1->d, p1->d, m1->d, mont1->RR.d, mont1->n0[0], rr2->d, a2->d, p2->d, m2->d, mont2->RR.d, mont2->n0[0], mod_bits); rr1->top = topn; rr1->neg = 0; bn_correct_top(rr1); bn_check_top(rr1); rr2->top = topn; rr2->neg = 0; bn_correct_top(rr2); bn_check_top(rr2); goto err; } #endif /* rr1 = a1^p1 mod m1 */ ret = BN_mod_exp_mont_consttime(rr1, a1, p1, m1, ctx, in_mont1); /* rr2 = a2^p2 mod m2 */ ret &= BN_mod_exp_mont_consttime(rr2, a2, p2, m2, ctx, in_mont2); #ifdef RSAZ_ENABLED err: if (in_mont2 == NULL) BN_MONT_CTX_free(mont2); if (in_mont1 == NULL) BN_MONT_CTX_free(mont1); #endif return ret; }
./openssl/crypto/bn/bn_kron.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 "internal/cryptlib.h" #include "bn_local.h" /* least significant word */ #define BN_lsw(n) (((n)->top == 0) ? (BN_ULONG) 0 : (n)->d[0]) /* Returns -2 for errors because both -1 and 0 are valid results. */ int BN_kronecker(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int i; int ret = -2; /* avoid 'uninitialized' warning */ int err = 0; BIGNUM *A, *B, *tmp; /*- * In 'tab', only odd-indexed entries are relevant: * For any odd BIGNUM n, * tab[BN_lsw(n) & 7] * is $(-1)^{(n^2-1)/8}$ (using TeX notation). * Note that the sign of n does not matter. */ static const int tab[8] = { 0, 1, 0, -1, 0, -1, 0, 1 }; bn_check_top(a); bn_check_top(b); BN_CTX_start(ctx); A = BN_CTX_get(ctx); B = BN_CTX_get(ctx); if (B == NULL) goto end; err = !BN_copy(A, a); if (err) goto end; err = !BN_copy(B, b); if (err) goto end; /* * Kronecker symbol, implemented according to Henri Cohen, * "A Course in Computational Algebraic Number Theory" * (algorithm 1.4.10). */ /* Cohen's step 1: */ if (BN_is_zero(B)) { ret = BN_abs_is_word(A, 1); goto end; } /* Cohen's step 2: */ if (!BN_is_odd(A) && !BN_is_odd(B)) { ret = 0; goto end; } /* now B is non-zero */ i = 0; while (!BN_is_bit_set(B, i)) i++; err = !BN_rshift(B, B, i); if (err) goto end; if (i & 1) { /* i is odd */ /* (thus B was even, thus A must be odd!) */ /* set 'ret' to $(-1)^{(A^2-1)/8}$ */ ret = tab[BN_lsw(A) & 7]; } else { /* i is even */ ret = 1; } if (B->neg) { B->neg = 0; if (A->neg) ret = -ret; } /* * now B is positive and odd, so what remains to be done is to compute * the Jacobi symbol (A/B) and multiply it by 'ret' */ while (1) { /* Cohen's step 3: */ /* B is positive and odd */ if (BN_is_zero(A)) { ret = BN_is_one(B) ? ret : 0; goto end; } /* now A is non-zero */ i = 0; while (!BN_is_bit_set(A, i)) i++; err = !BN_rshift(A, A, i); if (err) goto end; if (i & 1) { /* i is odd */ /* multiply 'ret' by $(-1)^{(B^2-1)/8}$ */ ret = ret * tab[BN_lsw(B) & 7]; } /* Cohen's step 4: */ /* multiply 'ret' by $(-1)^{(A-1)(B-1)/4}$ */ if ((A->neg ? ~BN_lsw(A) : BN_lsw(A)) & BN_lsw(B) & 2) ret = -ret; /* (A, B) := (B mod |A|, |A|) */ err = !BN_nnmod(B, B, A, ctx); if (err) goto end; tmp = A; A = B; B = tmp; tmp->neg = 0; } end: BN_CTX_end(ctx); if (err) return -2; else return ret; }
./openssl/crypto/bn/bn_ppc.c
/* * Copyright 2009-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/crypto.h> #include <openssl/bn.h> #include "crypto/ppc_arch.h" #include "bn_local.h" int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num) { int bn_mul_mont_int(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); int bn_mul4x_mont_int(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); int bn_mul_mont_fixed_n6(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); int bn_mul_mont_300_fixed_n6(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); if (num < 4) return 0; if ((num & 3) == 0) return bn_mul4x_mont_int(rp, ap, bp, np, n0, num); /* * There used to be [optional] call to bn_mul_mont_fpu64 here, * but above subroutine is faster on contemporary processors. * Formulation means that there might be old processors where * FPU code path would be faster, POWER6 perhaps, but there was * no opportunity to figure it out... */ #if defined(_ARCH_PPC64) && !defined(__ILP32__) if (num == 6) { if (OPENSSL_ppccap_P & PPC_MADD300) return bn_mul_mont_300_fixed_n6(rp, ap, bp, np, n0, num); else return bn_mul_mont_fixed_n6(rp, ap, bp, np, n0, num); } #endif return bn_mul_mont_int(rp, ap, bp, np, n0, num); }
./openssl/crypto/bn/bn_sqr.c
/* * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include "bn_local.h" /* r must not be a */ /* * I've just gone over this and it is now %20 faster on x86 - eay - 27 Jun 96 */ int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { int ret = bn_sqr_fixed_top(r, a, ctx); bn_correct_top(r); bn_check_top(r); return ret; } int bn_sqr_fixed_top(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { int max, al; int ret = 0; BIGNUM *tmp, *rr; bn_check_top(a); al = a->top; if (al <= 0) { r->top = 0; r->neg = 0; return 1; } BN_CTX_start(ctx); rr = (a != r) ? r : BN_CTX_get(ctx); tmp = BN_CTX_get(ctx); if (rr == NULL || tmp == NULL) goto err; max = 2 * al; /* Non-zero (from above) */ if (bn_wexpand(rr, max) == NULL) goto err; if (al == 4) { #ifndef BN_SQR_COMBA BN_ULONG t[8]; bn_sqr_normal(rr->d, a->d, 4, t); #else bn_sqr_comba4(rr->d, a->d); #endif } else if (al == 8) { #ifndef BN_SQR_COMBA BN_ULONG t[16]; bn_sqr_normal(rr->d, a->d, 8, t); #else bn_sqr_comba8(rr->d, a->d); #endif } else { #if defined(BN_RECURSION) if (al < BN_SQR_RECURSIVE_SIZE_NORMAL) { BN_ULONG t[BN_SQR_RECURSIVE_SIZE_NORMAL * 2]; bn_sqr_normal(rr->d, a->d, al, t); } else { int j, k; j = BN_num_bits_word((BN_ULONG)al); j = 1 << (j - 1); k = j + j; if (al == j) { if (bn_wexpand(tmp, k * 2) == NULL) goto err; bn_sqr_recursive(rr->d, a->d, al, tmp->d); } else { if (bn_wexpand(tmp, max) == NULL) goto err; bn_sqr_normal(rr->d, a->d, al, tmp->d); } } #else if (bn_wexpand(tmp, max) == NULL) goto err; bn_sqr_normal(rr->d, a->d, al, tmp->d); #endif } rr->neg = 0; rr->top = max; rr->flags |= BN_FLG_FIXED_TOP; if (r != rr && BN_copy(r, rr) == NULL) goto err; ret = 1; err: bn_check_top(rr); bn_check_top(tmp); BN_CTX_end(ctx); return ret; } /* tmp must have 2*n words */ void bn_sqr_normal(BN_ULONG *r, const BN_ULONG *a, int n, BN_ULONG *tmp) { int i, j, max; const BN_ULONG *ap; BN_ULONG *rp; max = n * 2; ap = a; rp = r; rp[0] = rp[max - 1] = 0; rp++; j = n; if (--j > 0) { ap++; rp[j] = bn_mul_words(rp, ap, j, ap[-1]); rp += 2; } for (i = n - 2; i > 0; i--) { j--; ap++; rp[j] = bn_mul_add_words(rp, ap, j, ap[-1]); rp += 2; } bn_add_words(r, r, r, max); /* There will not be a carry */ bn_sqr_words(tmp, a, n); bn_add_words(r, r, tmp, max); } #ifdef BN_RECURSION /*- * r is 2*n words in size, * a and b are both n words in size. (There's not actually a 'b' here ...) * n must be a power of 2. * We multiply and return the result. * t must be 2*n words in size * We calculate * a[0]*b[0] * a[0]*b[0]+a[1]*b[1]+(a[0]-a[1])*(b[1]-b[0]) * a[1]*b[1] */ void bn_sqr_recursive(BN_ULONG *r, const BN_ULONG *a, int n2, BN_ULONG *t) { int n = n2 / 2; int zero, c1; BN_ULONG ln, lo, *p; if (n2 == 4) { # ifndef BN_SQR_COMBA bn_sqr_normal(r, a, 4, t); # else bn_sqr_comba4(r, a); # endif return; } else if (n2 == 8) { # ifndef BN_SQR_COMBA bn_sqr_normal(r, a, 8, t); # else bn_sqr_comba8(r, a); # endif return; } if (n2 < BN_SQR_RECURSIVE_SIZE_NORMAL) { bn_sqr_normal(r, a, n2, t); return; } /* r=(a[0]-a[1])*(a[1]-a[0]) */ c1 = bn_cmp_words(a, &(a[n]), n); zero = 0; if (c1 > 0) bn_sub_words(t, a, &(a[n]), n); else if (c1 < 0) bn_sub_words(t, &(a[n]), a, n); else zero = 1; /* The result will always be negative unless it is zero */ p = &(t[n2 * 2]); if (!zero) bn_sqr_recursive(&(t[n2]), t, n, p); else memset(&t[n2], 0, sizeof(*t) * n2); bn_sqr_recursive(r, a, n, p); bn_sqr_recursive(&(r[n2]), &(a[n]), n, p); /*- * t[32] holds (a[0]-a[1])*(a[1]-a[0]), it is negative or zero * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) */ c1 = (int)(bn_add_words(t, r, &(r[n2]), n2)); /* t[32] is negative */ c1 -= (int)(bn_sub_words(&(t[n2]), t, &(t[n2]), n2)); /*- * t[32] holds (a[0]-a[1])*(a[1]-a[0])+(a[0]*a[0])+(a[1]*a[1]) * r[10] holds (a[0]*a[0]) * r[32] holds (a[1]*a[1]) * c1 holds the carry bits */ c1 += (int)(bn_add_words(&(r[n]), &(r[n]), &(t[n2]), n2)); if (c1) { p = &(r[n + n2]); lo = *p; ln = (lo + c1) & BN_MASK2; *p = ln; /* * The overflow will stop before we over write words we should not * overwrite */ if (ln < (BN_ULONG)c1) { do { p++; lo = *p; ln = (lo + 1) & BN_MASK2; *p = ln; } while (ln == 0); } } } #endif
./openssl/crypto/bn/bn_add.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include "bn_local.h" /* signed add of b to a. */ int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { int ret, r_neg, cmp_res; bn_check_top(a); bn_check_top(b); if (a->neg == b->neg) { r_neg = a->neg; ret = BN_uadd(r, a, b); } else { cmp_res = BN_ucmp(a, b); if (cmp_res > 0) { r_neg = a->neg; ret = BN_usub(r, a, b); } else if (cmp_res < 0) { r_neg = b->neg; ret = BN_usub(r, b, a); } else { r_neg = 0; BN_zero(r); ret = 1; } } r->neg = r_neg; bn_check_top(r); return ret; } /* signed sub of b from a. */ int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { int ret, r_neg, cmp_res; bn_check_top(a); bn_check_top(b); if (a->neg != b->neg) { r_neg = a->neg; ret = BN_uadd(r, a, b); } else { cmp_res = BN_ucmp(a, b); if (cmp_res > 0) { r_neg = a->neg; ret = BN_usub(r, a, b); } else if (cmp_res < 0) { r_neg = !b->neg; ret = BN_usub(r, b, a); } else { r_neg = 0; BN_zero(r); ret = 1; } } r->neg = r_neg; bn_check_top(r); return ret; } /* unsigned add of b to a, r can be equal to a or b. */ int BN_uadd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { int max, min, dif; const BN_ULONG *ap, *bp; BN_ULONG *rp, carry, t1, t2; bn_check_top(a); bn_check_top(b); if (a->top < b->top) { const BIGNUM *tmp; tmp = a; a = b; b = tmp; } max = a->top; min = b->top; dif = max - min; if (bn_wexpand(r, max + 1) == NULL) return 0; r->top = max; ap = a->d; bp = b->d; rp = r->d; carry = bn_add_words(rp, ap, bp, min); rp += min; ap += min; while (dif) { dif--; t1 = *(ap++); t2 = (t1 + carry) & BN_MASK2; *(rp++) = t2; carry &= (t2 == 0); } *rp = carry; r->top += carry; r->neg = 0; bn_check_top(r); return 1; } /* unsigned subtraction of b from a, a must be larger than b. */ int BN_usub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { int max, min, dif; BN_ULONG t1, t2, borrow, *rp; const BN_ULONG *ap, *bp; bn_check_top(a); bn_check_top(b); max = a->top; min = b->top; dif = max - min; if (dif < 0) { /* hmm... should not be happening */ ERR_raise(ERR_LIB_BN, BN_R_ARG2_LT_ARG3); return 0; } if (bn_wexpand(r, max) == NULL) return 0; ap = a->d; bp = b->d; rp = r->d; borrow = bn_sub_words(rp, ap, bp, min); ap += min; rp += min; while (dif) { dif--; t1 = *(ap++); t2 = (t1 - borrow) & BN_MASK2; *(rp++) = t2; borrow &= (t1 == 0); } while (max && *--rp == 0) max--; r->top = max; r->neg = 0; bn_pollute(r); return 1; }
./openssl/crypto/bn/bn_sqrt.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/cryptlib.h" #include "bn_local.h" BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) /* * Returns 'ret' such that ret^2 == a (mod p), using the Tonelli/Shanks * algorithm (cf. Henri Cohen, "A Course in Algebraic Computational Number * Theory", algorithm 1.5.1). 'p' must be prime, otherwise an error or * an incorrect "result" will be returned. */ { BIGNUM *ret = in; int err = 1; int r; BIGNUM *A, *b, *q, *t, *x, *y; int e, i, j; int used_ctx = 0; if (!BN_is_odd(p) || BN_abs_is_word(p, 1)) { if (BN_abs_is_word(p, 2)) { if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; if (!BN_set_word(ret, BN_is_bit_set(a, 0))) { if (ret != in) BN_free(ret); return NULL; } bn_check_top(ret); return ret; } ERR_raise(ERR_LIB_BN, BN_R_P_IS_NOT_PRIME); return NULL; } if (BN_is_zero(a) || BN_is_one(a)) { if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; if (!BN_set_word(ret, BN_is_one(a))) { if (ret != in) BN_free(ret); return NULL; } bn_check_top(ret); return ret; } BN_CTX_start(ctx); used_ctx = 1; A = BN_CTX_get(ctx); b = BN_CTX_get(ctx); q = BN_CTX_get(ctx); t = BN_CTX_get(ctx); x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); if (y == NULL) goto end; if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; /* A = a mod p */ if (!BN_nnmod(A, a, p, ctx)) goto end; /* now write |p| - 1 as 2^e*q where q is odd */ e = 1; while (!BN_is_bit_set(p, e)) e++; /* we'll set q later (if needed) */ if (e == 1) { /*- * The easy case: (|p|-1)/2 is odd, so 2 has an inverse * modulo (|p|-1)/2, and square roots can be computed * directly by modular exponentiation. * We have * 2 * (|p|+1)/4 == 1 (mod (|p|-1)/2), * so we can use exponent (|p|+1)/4, i.e. (|p|-3)/4 + 1. */ if (!BN_rshift(q, p, 2)) goto end; q->neg = 0; if (!BN_add_word(q, 1)) goto end; if (!BN_mod_exp(ret, A, q, p, ctx)) goto end; err = 0; goto vrfy; } if (e == 2) { /*- * |p| == 5 (mod 8) * * In this case 2 is always a non-square since * Legendre(2,p) = (-1)^((p^2-1)/8) for any odd prime. * So if a really is a square, then 2*a is a non-square. * Thus for * b := (2*a)^((|p|-5)/8), * i := (2*a)*b^2 * we have * i^2 = (2*a)^((1 + (|p|-5)/4)*2) * = (2*a)^((p-1)/2) * = -1; * so if we set * x := a*b*(i-1), * then * x^2 = a^2 * b^2 * (i^2 - 2*i + 1) * = a^2 * b^2 * (-2*i) * = a*(-i)*(2*a*b^2) * = a*(-i)*i * = a. * * (This is due to A.O.L. Atkin, * Subject: Square Roots and Cognate Matters modulo p=8n+5. * URL: https://listserv.nodak.edu/cgi-bin/wa.exe?A2=ind9211&L=NMBRTHRY&P=4026 * November 1992.) */ /* t := 2*a */ if (!BN_mod_lshift1_quick(t, A, p)) goto end; /* b := (2*a)^((|p|-5)/8) */ if (!BN_rshift(q, p, 3)) goto end; q->neg = 0; if (!BN_mod_exp(b, t, q, p, ctx)) goto end; /* y := b^2 */ if (!BN_mod_sqr(y, b, p, ctx)) goto end; /* t := (2*a)*b^2 - 1 */ if (!BN_mod_mul(t, t, y, p, ctx)) goto end; if (!BN_sub_word(t, 1)) goto end; /* x = a*b*t */ if (!BN_mod_mul(x, A, b, p, ctx)) goto end; if (!BN_mod_mul(x, x, t, p, ctx)) goto end; if (!BN_copy(ret, x)) goto end; err = 0; goto vrfy; } /* * e > 2, so we really have to use the Tonelli/Shanks algorithm. First, * find some y that is not a square. */ if (!BN_copy(q, p)) goto end; /* use 'q' as temp */ q->neg = 0; i = 2; do { /* * For efficiency, try small numbers first; if this fails, try random * numbers. */ if (i < 22) { if (!BN_set_word(y, i)) goto end; } else { if (!BN_priv_rand_ex(y, BN_num_bits(p), 0, 0, 0, ctx)) goto end; if (BN_ucmp(y, p) >= 0) { if (!(p->neg ? BN_add : BN_sub) (y, y, p)) goto end; } /* now 0 <= y < |p| */ if (BN_is_zero(y)) if (!BN_set_word(y, i)) goto end; } r = BN_kronecker(y, q, ctx); /* here 'q' is |p| */ if (r < -1) goto end; if (r == 0) { /* m divides p */ ERR_raise(ERR_LIB_BN, BN_R_P_IS_NOT_PRIME); goto end; } } while (r == 1 && ++i < 82); if (r != -1) { /* * Many rounds and still no non-square -- this is more likely a bug * than just bad luck. Even if p is not prime, we should have found * some y such that r == -1. */ ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS); goto end; } /* Here's our actual 'q': */ if (!BN_rshift(q, q, e)) goto end; /* * Now that we have some non-square, we can find an element of order 2^e * by computing its q'th power. */ if (!BN_mod_exp(y, y, q, p, ctx)) goto end; if (BN_is_one(y)) { ERR_raise(ERR_LIB_BN, BN_R_P_IS_NOT_PRIME); goto end; } /*- * Now we know that (if p is indeed prime) there is an integer * k, 0 <= k < 2^e, such that * * a^q * y^k == 1 (mod p). * * As a^q is a square and y is not, k must be even. * q+1 is even, too, so there is an element * * X := a^((q+1)/2) * y^(k/2), * * and it satisfies * * X^2 = a^q * a * y^k * = a, * * so it is the square root that we are looking for. */ /* t := (q-1)/2 (note that q is odd) */ if (!BN_rshift1(t, q)) goto end; /* x := a^((q-1)/2) */ if (BN_is_zero(t)) { /* special case: p = 2^e + 1 */ if (!BN_nnmod(t, A, p, ctx)) goto end; if (BN_is_zero(t)) { /* special case: a == 0 (mod p) */ BN_zero(ret); err = 0; goto end; } else if (!BN_one(x)) goto end; } else { if (!BN_mod_exp(x, A, t, p, ctx)) goto end; if (BN_is_zero(x)) { /* special case: a == 0 (mod p) */ BN_zero(ret); err = 0; goto end; } } /* b := a*x^2 (= a^q) */ if (!BN_mod_sqr(b, x, p, ctx)) goto end; if (!BN_mod_mul(b, b, A, p, ctx)) goto end; /* x := a*x (= a^((q+1)/2)) */ if (!BN_mod_mul(x, x, A, p, ctx)) goto end; while (1) { /*- * Now b is a^q * y^k for some even k (0 <= k < 2^E * where E refers to the original value of e, which we * don't keep in a variable), and x is a^((q+1)/2) * y^(k/2). * * We have a*b = x^2, * y^2^(e-1) = -1, * b^2^(e-1) = 1. */ if (BN_is_one(b)) { if (!BN_copy(ret, x)) goto end; err = 0; goto vrfy; } /* Find the smallest i, 0 < i < e, such that b^(2^i) = 1. */ for (i = 1; i < e; i++) { if (i == 1) { if (!BN_mod_sqr(t, b, p, ctx)) goto end; } else { if (!BN_mod_mul(t, t, t, p, ctx)) goto end; } if (BN_is_one(t)) break; } /* If not found, a is not a square or p is not prime. */ if (i >= e) { ERR_raise(ERR_LIB_BN, BN_R_NOT_A_SQUARE); goto end; } /* t := y^2^(e - i - 1) */ if (!BN_copy(t, y)) goto end; for (j = e - i - 1; j > 0; j--) { if (!BN_mod_sqr(t, t, p, ctx)) goto end; } if (!BN_mod_mul(y, t, t, p, ctx)) goto end; if (!BN_mod_mul(x, x, t, p, ctx)) goto end; if (!BN_mod_mul(b, b, y, p, ctx)) goto end; e = i; } vrfy: if (!err) { /* * verify the result -- the input might have been not a square (test * added in 0.9.8) */ if (!BN_mod_sqr(x, ret, p, ctx)) err = 1; if (!err && 0 != BN_cmp(x, A)) { ERR_raise(ERR_LIB_BN, BN_R_NOT_A_SQUARE); err = 1; } } end: if (err) { if (ret != in) BN_clear_free(ret); ret = NULL; } if (used_ctx) BN_CTX_end(ctx); bn_check_top(ret); return ret; }
./openssl/crypto/bn/rsaz_exp_x2.c
/* * Copyright 2020-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2020-2021, Intel Corporation. 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 * * * Originally written by Sergey Kirillov and Andrey Matyukov. * Special thanks to Ilya Albrekht for his valuable hints. * Intel Corporation * */ #include <openssl/opensslconf.h> #include <openssl/crypto.h> #include "rsaz_exp.h" #ifndef RSAZ_ENABLED NON_EMPTY_TRANSLATION_UNIT #else # include <assert.h> # include <string.h> # define ALIGN_OF(ptr, boundary) \ ((unsigned char *)(ptr) + (boundary - (((size_t)(ptr)) & (boundary - 1)))) /* Internal radix */ # define DIGIT_SIZE (52) /* 52-bit mask */ # define DIGIT_MASK ((uint64_t)0xFFFFFFFFFFFFF) # define BITS2WORD8_SIZE(x) (((x) + 7) >> 3) # define BITS2WORD64_SIZE(x) (((x) + 63) >> 6) /* Number of registers required to hold |digits_num| amount of qword digits */ # define NUMBER_OF_REGISTERS(digits_num, register_size) \ (((digits_num) * 64 + (register_size) - 1) / (register_size)) static ossl_inline uint64_t get_digit(const uint8_t *in, int in_len); static ossl_inline void put_digit(uint8_t *out, int out_len, uint64_t digit); static void to_words52(BN_ULONG *out, int out_len, const BN_ULONG *in, int in_bitsize); static void from_words52(BN_ULONG *bn_out, int out_bitsize, const BN_ULONG *in); static ossl_inline void set_bit(BN_ULONG *a, int idx); /* Number of |digit_size|-bit digits in |bitsize|-bit value */ static ossl_inline int number_of_digits(int bitsize, int digit_size) { return (bitsize + digit_size - 1) / digit_size; } /* * For details of the methods declared below please refer to * crypto/bn/asm/rsaz-avx512.pl * * Naming conventions: * amm = Almost Montgomery Multiplication * ams = Almost Montgomery Squaring * 52xZZ - data represented as array of ZZ digits in 52-bit radix * _x1_/_x2_ - 1 or 2 independent inputs/outputs * _ifma256 - uses 256-bit wide IFMA ISA (AVX512_IFMA256) */ void ossl_rsaz_amm52x20_x1_ifma256(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG k0); void ossl_rsaz_amm52x20_x2_ifma256(BN_ULONG *out, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, const BN_ULONG k0[2]); void ossl_extract_multiplier_2x20_win5(BN_ULONG *red_Y, const BN_ULONG *red_table, int red_table_idx1, int red_table_idx2); void ossl_rsaz_amm52x30_x1_ifma256(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG k0); void ossl_rsaz_amm52x30_x2_ifma256(BN_ULONG *out, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, const BN_ULONG k0[2]); void ossl_extract_multiplier_2x30_win5(BN_ULONG *red_Y, const BN_ULONG *red_table, int red_table_idx1, int red_table_idx2); void ossl_rsaz_amm52x40_x1_ifma256(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG k0); void ossl_rsaz_amm52x40_x2_ifma256(BN_ULONG *out, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, const BN_ULONG k0[2]); void ossl_extract_multiplier_2x40_win5(BN_ULONG *red_Y, const BN_ULONG *red_table, int red_table_idx1, int red_table_idx2); static int RSAZ_mod_exp_x2_ifma256(BN_ULONG *res, const BN_ULONG *base, const BN_ULONG *exp[2], const BN_ULONG *m, const BN_ULONG *rr, const BN_ULONG k0[2], int modulus_bitsize); /* * Dual Montgomery modular exponentiation using prime moduli of the * same bit size, optimized with AVX512 ISA. * * Input and output parameters for each exponentiation are independent and * denoted here by index |i|, i = 1..2. * * Input and output are all in regular 2^64 radix. * * Each moduli shall be |factor_size| bit size. * * Supported cases: * - 2x1024 * - 2x1536 * - 2x2048 * * [out] res|i| - result of modular exponentiation: array of qword values * in regular (2^64) radix. Size of array shall be enough * to hold |factor_size| bits. * [in] base|i| - base * [in] exp|i| - exponent * [in] m|i| - moduli * [in] rr|i| - Montgomery parameter RR = R^2 mod m|i| * [in] k0_|i| - Montgomery parameter k0 = -1/m|i| mod 2^64 * [in] factor_size - moduli bit size * * \return 0 in case of failure, * 1 in case of success. */ int ossl_rsaz_mod_exp_avx512_x2(BN_ULONG *res1, const BN_ULONG *base1, const BN_ULONG *exp1, const BN_ULONG *m1, const BN_ULONG *rr1, BN_ULONG k0_1, BN_ULONG *res2, const BN_ULONG *base2, const BN_ULONG *exp2, const BN_ULONG *m2, const BN_ULONG *rr2, BN_ULONG k0_2, int factor_size) { typedef void (*AMM)(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG k0); int ret = 0; /* * Number of word-size (BN_ULONG) digits to store exponent in redundant * representation. */ int exp_digits = number_of_digits(factor_size + 2, DIGIT_SIZE); int coeff_pow = 4 * (DIGIT_SIZE * exp_digits - factor_size); /* Number of YMM registers required to store exponent's digits */ int ymm_regs_num = NUMBER_OF_REGISTERS(exp_digits, 256 /* ymm bit size */); /* Capacity of the register set (in qwords) to store exponent */ int regs_capacity = ymm_regs_num * 4; BN_ULONG *base1_red, *m1_red, *rr1_red; BN_ULONG *base2_red, *m2_red, *rr2_red; BN_ULONG *coeff_red; BN_ULONG *storage = NULL; BN_ULONG *storage_aligned = NULL; int storage_len_bytes = 7 * regs_capacity * sizeof(BN_ULONG) + 64 /* alignment */; const BN_ULONG *exp[2] = {0}; BN_ULONG k0[2] = {0}; /* AMM = Almost Montgomery Multiplication */ AMM amm = NULL; switch (factor_size) { case 1024: amm = ossl_rsaz_amm52x20_x1_ifma256; break; case 1536: amm = ossl_rsaz_amm52x30_x1_ifma256; break; case 2048: amm = ossl_rsaz_amm52x40_x1_ifma256; break; default: goto err; } storage = (BN_ULONG *)OPENSSL_malloc(storage_len_bytes); if (storage == NULL) goto err; storage_aligned = (BN_ULONG *)ALIGN_OF(storage, 64); /* Memory layout for red(undant) representations */ base1_red = storage_aligned; base2_red = storage_aligned + 1 * regs_capacity; m1_red = storage_aligned + 2 * regs_capacity; m2_red = storage_aligned + 3 * regs_capacity; rr1_red = storage_aligned + 4 * regs_capacity; rr2_red = storage_aligned + 5 * regs_capacity; coeff_red = storage_aligned + 6 * regs_capacity; /* Convert base_i, m_i, rr_i, from regular to 52-bit radix */ to_words52(base1_red, regs_capacity, base1, factor_size); to_words52(base2_red, regs_capacity, base2, factor_size); to_words52(m1_red, regs_capacity, m1, factor_size); to_words52(m2_red, regs_capacity, m2, factor_size); to_words52(rr1_red, regs_capacity, rr1, factor_size); to_words52(rr2_red, regs_capacity, rr2, factor_size); /* * Compute target domain Montgomery converters RR' for each modulus * based on precomputed original domain's RR. * * RR -> RR' transformation steps: * (1) coeff = 2^k * (2) t = AMM(RR,RR) = RR^2 / R' mod m * (3) RR' = AMM(t, coeff) = RR^2 * 2^k / R'^2 mod m * where * k = 4 * (52 * digits52 - modlen) * R = 2^(64 * ceil(modlen/64)) mod m * RR = R^2 mod m * R' = 2^(52 * ceil(modlen/52)) mod m * * EX/ modlen = 1024: k = 64, RR = 2^2048 mod m, RR' = 2^2080 mod m */ memset(coeff_red, 0, exp_digits * sizeof(BN_ULONG)); /* (1) in reduced domain representation */ set_bit(coeff_red, 64 * (int)(coeff_pow / 52) + coeff_pow % 52); amm(rr1_red, rr1_red, rr1_red, m1_red, k0_1); /* (2) for m1 */ amm(rr1_red, rr1_red, coeff_red, m1_red, k0_1); /* (3) for m1 */ amm(rr2_red, rr2_red, rr2_red, m2_red, k0_2); /* (2) for m2 */ amm(rr2_red, rr2_red, coeff_red, m2_red, k0_2); /* (3) for m2 */ exp[0] = exp1; exp[1] = exp2; k0[0] = k0_1; k0[1] = k0_2; /* Dual (2-exps in parallel) exponentiation */ ret = RSAZ_mod_exp_x2_ifma256(rr1_red, base1_red, exp, m1_red, rr1_red, k0, factor_size); if (!ret) goto err; /* Convert rr_i back to regular radix */ from_words52(res1, factor_size, rr1_red); from_words52(res2, factor_size, rr2_red); /* bn_reduce_once_in_place expects number of BN_ULONG, not bit size */ factor_size /= sizeof(BN_ULONG) * 8; bn_reduce_once_in_place(res1, /*carry=*/0, m1, storage, factor_size); bn_reduce_once_in_place(res2, /*carry=*/0, m2, storage, factor_size); err: if (storage != NULL) { OPENSSL_cleanse(storage, storage_len_bytes); OPENSSL_free(storage); } return ret; } /* * Dual {1024,1536,2048}-bit w-ary modular exponentiation using prime moduli of * the same bit size using Almost Montgomery Multiplication, optimized with * AVX512_IFMA256 ISA. * * The parameter w (window size) = 5. * * [out] res - result of modular exponentiation: 2x{20,30,40} qword * values in 2^52 radix. * [in] base - base (2x{20,30,40} qword values in 2^52 radix) * [in] exp - array of 2 pointers to {16,24,32} qword values in 2^64 radix. * Exponent is not converted to redundant representation. * [in] m - moduli (2x{20,30,40} qword values in 2^52 radix) * [in] rr - Montgomery parameter for 2 moduli: * RR(1024) = 2^2080 mod m. * RR(1536) = 2^3120 mod m. * RR(2048) = 2^4160 mod m. * (2x{20,30,40} qword values in 2^52 radix) * [in] k0 - Montgomery parameter for 2 moduli: k0 = -1/m mod 2^64 * * \return (void). */ int RSAZ_mod_exp_x2_ifma256(BN_ULONG *out, const BN_ULONG *base, const BN_ULONG *exp[2], const BN_ULONG *m, const BN_ULONG *rr, const BN_ULONG k0[2], int modulus_bitsize) { typedef void (*DAMM)(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, const BN_ULONG k0[2]); typedef void (*DEXTRACT)(BN_ULONG *res, const BN_ULONG *red_table, int red_table_idx, int tbl_idx); int ret = 0; int idx; /* Exponent window size */ int exp_win_size = 5; int exp_win_mask = (1U << exp_win_size) - 1; /* * Number of digits (64-bit words) in redundant representation to handle * modulus bits */ int red_digits = 0; int exp_digits = 0; BN_ULONG *storage = NULL; BN_ULONG *storage_aligned = NULL; int storage_len_bytes = 0; /* Red(undant) result Y and multiplier X */ BN_ULONG *red_Y = NULL; /* [2][red_digits] */ BN_ULONG *red_X = NULL; /* [2][red_digits] */ /* Pre-computed table of base powers */ BN_ULONG *red_table = NULL; /* [1U << exp_win_size][2][red_digits] */ /* Expanded exponent */ BN_ULONG *expz = NULL; /* [2][exp_digits + 1] */ /* Dual AMM */ DAMM damm = NULL; /* Extractor from red_table */ DEXTRACT extract = NULL; /* * Squaring is done using multiplication now. That can be a subject of * optimization in future. */ # define DAMS(r,a,m,k0) damm((r),(a),(a),(m),(k0)) switch (modulus_bitsize) { case 1024: red_digits = 20; exp_digits = 16; damm = ossl_rsaz_amm52x20_x2_ifma256; extract = ossl_extract_multiplier_2x20_win5; break; case 1536: /* Extended with 2 digits padding to avoid mask ops in high YMM register */ red_digits = 30 + 2; exp_digits = 24; damm = ossl_rsaz_amm52x30_x2_ifma256; extract = ossl_extract_multiplier_2x30_win5; break; case 2048: red_digits = 40; exp_digits = 32; damm = ossl_rsaz_amm52x40_x2_ifma256; extract = ossl_extract_multiplier_2x40_win5; break; default: goto err; } storage_len_bytes = (2 * red_digits /* red_Y */ + 2 * red_digits /* red_X */ + 2 * red_digits * (1U << exp_win_size) /* red_table */ + 2 * (exp_digits + 1)) /* expz */ * sizeof(BN_ULONG) + 64; /* alignment */ storage = (BN_ULONG *)OPENSSL_zalloc(storage_len_bytes); if (storage == NULL) goto err; storage_aligned = (BN_ULONG *)ALIGN_OF(storage, 64); red_Y = storage_aligned; red_X = red_Y + 2 * red_digits; red_table = red_X + 2 * red_digits; expz = red_table + 2 * red_digits * (1U << exp_win_size); /* * Compute table of powers base^i, i = 0, ..., (2^EXP_WIN_SIZE) - 1 * table[0] = mont(x^0) = mont(1) * table[1] = mont(x^1) = mont(x) */ red_X[0 * red_digits] = 1; red_X[1 * red_digits] = 1; damm(&red_table[0 * 2 * red_digits], (const BN_ULONG*)red_X, rr, m, k0); damm(&red_table[1 * 2 * red_digits], base, rr, m, k0); for (idx = 1; idx < (int)((1U << exp_win_size) / 2); idx++) { DAMS(&red_table[(2 * idx + 0) * 2 * red_digits], &red_table[(1 * idx) * 2 * red_digits], m, k0); damm(&red_table[(2 * idx + 1) * 2 * red_digits], &red_table[(2 * idx) * 2 * red_digits], &red_table[1 * 2 * red_digits], m, k0); } /* Copy and expand exponents */ memcpy(&expz[0 * (exp_digits + 1)], exp[0], exp_digits * sizeof(BN_ULONG)); expz[1 * (exp_digits + 1) - 1] = 0; memcpy(&expz[1 * (exp_digits + 1)], exp[1], exp_digits * sizeof(BN_ULONG)); expz[2 * (exp_digits + 1) - 1] = 0; /* Exponentiation */ { const int rem = modulus_bitsize % exp_win_size; const BN_ULONG table_idx_mask = exp_win_mask; int exp_bit_no = modulus_bitsize - rem; int exp_chunk_no = exp_bit_no / 64; int exp_chunk_shift = exp_bit_no % 64; BN_ULONG red_table_idx_0, red_table_idx_1; /* * If rem == 0, then * exp_bit_no = modulus_bitsize - exp_win_size * However, this isn't possible because rem is { 1024, 1536, 2048 } % 5 * which is { 4, 1, 3 } respectively. * * If this assertion ever fails the fix above is easy. */ OPENSSL_assert(rem != 0); /* Process 1-st exp window - just init result */ red_table_idx_0 = expz[exp_chunk_no + 0 * (exp_digits + 1)]; red_table_idx_1 = expz[exp_chunk_no + 1 * (exp_digits + 1)]; /* * The function operates with fixed moduli sizes divisible by 64, * thus table index here is always in supported range [0, EXP_WIN_SIZE). */ red_table_idx_0 >>= exp_chunk_shift; red_table_idx_1 >>= exp_chunk_shift; extract(&red_Y[0 * red_digits], (const BN_ULONG*)red_table, (int)red_table_idx_0, (int)red_table_idx_1); /* Process other exp windows */ for (exp_bit_no -= exp_win_size; exp_bit_no >= 0; exp_bit_no -= exp_win_size) { /* Extract pre-computed multiplier from the table */ { BN_ULONG T; exp_chunk_no = exp_bit_no / 64; exp_chunk_shift = exp_bit_no % 64; { red_table_idx_0 = expz[exp_chunk_no + 0 * (exp_digits + 1)]; T = expz[exp_chunk_no + 1 + 0 * (exp_digits + 1)]; red_table_idx_0 >>= exp_chunk_shift; /* * Get additional bits from then next quadword * when 64-bit boundaries are crossed. */ if (exp_chunk_shift > 64 - exp_win_size) { T <<= (64 - exp_chunk_shift); red_table_idx_0 ^= T; } red_table_idx_0 &= table_idx_mask; } { red_table_idx_1 = expz[exp_chunk_no + 1 * (exp_digits + 1)]; T = expz[exp_chunk_no + 1 + 1 * (exp_digits + 1)]; red_table_idx_1 >>= exp_chunk_shift; /* * Get additional bits from then next quadword * when 64-bit boundaries are crossed. */ if (exp_chunk_shift > 64 - exp_win_size) { T <<= (64 - exp_chunk_shift); red_table_idx_1 ^= T; } red_table_idx_1 &= table_idx_mask; } extract(&red_X[0 * red_digits], (const BN_ULONG*)red_table, (int)red_table_idx_0, (int)red_table_idx_1); } /* Series of squaring */ DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); damm((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, (const BN_ULONG*)red_X, m, k0); } } /* * * NB: After the last AMM of exponentiation in Montgomery domain, the result * may be (modulus_bitsize + 1), but the conversion out of Montgomery domain * performs an AMM(x,1) which guarantees that the final result is less than * |m|, so no conditional subtraction is needed here. See [1] for details. * * [1] Gueron, S. Efficient software implementations of modular exponentiation. * DOI: 10.1007/s13389-012-0031-5 */ /* Convert result back in regular 2^52 domain */ memset(red_X, 0, 2 * red_digits * sizeof(BN_ULONG)); red_X[0 * red_digits] = 1; red_X[1 * red_digits] = 1; damm(out, (const BN_ULONG*)red_Y, (const BN_ULONG*)red_X, m, k0); ret = 1; err: if (storage != NULL) { /* Clear whole storage */ OPENSSL_cleanse(storage, storage_len_bytes); OPENSSL_free(storage); } #undef DAMS return ret; } static ossl_inline uint64_t get_digit(const uint8_t *in, int in_len) { uint64_t digit = 0; assert(in != NULL); assert(in_len <= 8); for (; in_len > 0; in_len--) { digit <<= 8; digit += (uint64_t)(in[in_len - 1]); } return digit; } /* * Convert array of words in regular (base=2^64) representation to array of * words in redundant (base=2^52) one. */ static void to_words52(BN_ULONG *out, int out_len, const BN_ULONG *in, int in_bitsize) { uint8_t *in_str = NULL; assert(out != NULL); assert(in != NULL); /* Check destination buffer capacity */ assert(out_len >= number_of_digits(in_bitsize, DIGIT_SIZE)); in_str = (uint8_t *)in; for (; in_bitsize >= (2 * DIGIT_SIZE); in_bitsize -= (2 * DIGIT_SIZE), out += 2) { uint64_t digit; memcpy(&digit, in_str, sizeof(digit)); out[0] = digit & DIGIT_MASK; in_str += 6; memcpy(&digit, in_str, sizeof(digit)); out[1] = (digit >> 4) & DIGIT_MASK; in_str += 7; out_len -= 2; } if (in_bitsize > DIGIT_SIZE) { uint64_t digit = get_digit(in_str, 7); out[0] = digit & DIGIT_MASK; in_str += 6; in_bitsize -= DIGIT_SIZE; digit = get_digit(in_str, BITS2WORD8_SIZE(in_bitsize)); out[1] = digit >> 4; out += 2; out_len -= 2; } else if (in_bitsize > 0) { out[0] = get_digit(in_str, BITS2WORD8_SIZE(in_bitsize)); out++; out_len--; } while (out_len > 0) { *out = 0; out_len--; out++; } } static ossl_inline void put_digit(uint8_t *out, int out_len, uint64_t digit) { assert(out != NULL); assert(out_len <= 8); for (; out_len > 0; out_len--) { *out++ = (uint8_t)(digit & 0xFF); digit >>= 8; } } /* * Convert array of words in redundant (base=2^52) representation to array of * words in regular (base=2^64) one. */ static void from_words52(BN_ULONG *out, int out_bitsize, const BN_ULONG *in) { int i; int out_len = BITS2WORD64_SIZE(out_bitsize); assert(out != NULL); assert(in != NULL); for (i = 0; i < out_len; i++) out[i] = 0; { uint8_t *out_str = (uint8_t *)out; for (; out_bitsize >= (2 * DIGIT_SIZE); out_bitsize -= (2 * DIGIT_SIZE), in += 2) { uint64_t digit; digit = in[0]; memcpy(out_str, &digit, sizeof(digit)); out_str += 6; digit = digit >> 48 | in[1] << 4; memcpy(out_str, &digit, sizeof(digit)); out_str += 7; } if (out_bitsize > DIGIT_SIZE) { put_digit(out_str, 7, in[0]); out_str += 6; out_bitsize -= DIGIT_SIZE; put_digit(out_str, BITS2WORD8_SIZE(out_bitsize), (in[1] << 4 | in[0] >> 48)); } else if (out_bitsize) { put_digit(out_str, BITS2WORD8_SIZE(out_bitsize), in[0]); } } } /* * Set bit at index |idx| in the words array |a|. * It does not do any boundaries checks, make sure the index is valid before * calling the function. */ static ossl_inline void set_bit(BN_ULONG *a, int idx) { assert(a != NULL); { int i, j; i = idx / BN_BITS2; j = idx % BN_BITS2; a[i] |= (((BN_ULONG)1) << j); } } #endif
./openssl/crypto/bn/bn_mul.c
/* * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <assert.h> #include "internal/cryptlib.h" #include "bn_local.h" #if defined(OPENSSL_NO_ASM) || !defined(OPENSSL_BN_ASM_PART_WORDS) /* * Here follows specialised variants of bn_add_words() and bn_sub_words(). * They have the property performing operations on arrays of different sizes. * The sizes of those arrays is expressed through cl, which is the common * length ( basically, min(len(a),len(b)) ), and dl, which is the delta * between the two lengths, calculated as len(a)-len(b). All lengths are the * number of BN_ULONGs... For the operations that require a result array as * parameter, it must have the length cl+abs(dl). These functions should * probably end up in bn_asm.c as soon as there are assembler counterparts * for the systems that use assembler files. */ BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, int cl, int dl) { BN_ULONG c, t; assert(cl >= 0); c = bn_sub_words(r, a, b, cl); if (dl == 0) return c; r += cl; a += cl; b += cl; if (dl < 0) { for (;;) { t = b[0]; r[0] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; t = b[1]; r[1] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; t = b[2]; r[2] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; t = b[3]; r[3] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; b += 4; r += 4; } } else { int save_dl = dl; while (c) { t = a[0]; r[0] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; t = a[1]; r[1] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; t = a[2]; r[2] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; t = a[3]; r[3] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; save_dl = dl; a += 4; r += 4; } if (dl > 0) { if (save_dl > dl) { switch (save_dl - dl) { case 1: r[1] = a[1]; if (--dl <= 0) break; /* fall through */ case 2: r[2] = a[2]; if (--dl <= 0) break; /* fall through */ case 3: r[3] = a[3]; if (--dl <= 0) break; } a += 4; r += 4; } } if (dl > 0) { for (;;) { r[0] = a[0]; if (--dl <= 0) break; r[1] = a[1]; if (--dl <= 0) break; r[2] = a[2]; if (--dl <= 0) break; r[3] = a[3]; if (--dl <= 0) break; a += 4; r += 4; } } } return c; } #endif #ifdef BN_RECURSION /* * Karatsuba recursive multiplication algorithm (cf. Knuth, The Art of * Computer Programming, Vol. 2) */ /*- * r is 2*n2 words in size, * a and b are both n2 words in size. * n2 must be a power of 2. * We multiply and return the result. * t must be 2*n2 words in size * We calculate * a[0]*b[0] * a[0]*b[0]+a[1]*b[1]+(a[0]-a[1])*(b[1]-b[0]) * a[1]*b[1] */ /* dnX may not be positive, but n2/2+dnX has to be */ void bn_mul_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, int dna, int dnb, BN_ULONG *t) { int n = n2 / 2, c1, c2; int tna = n + dna, tnb = n + dnb; unsigned int neg, zero; BN_ULONG ln, lo, *p; # ifdef BN_MUL_COMBA # if 0 if (n2 == 4) { bn_mul_comba4(r, a, b); return; } # endif /* * Only call bn_mul_comba 8 if n2 == 8 and the two arrays are complete * [steve] */ if (n2 == 8 && dna == 0 && dnb == 0) { bn_mul_comba8(r, a, b); return; } # endif /* BN_MUL_COMBA */ /* Else do normal multiply */ if (n2 < BN_MUL_RECURSIVE_SIZE_NORMAL) { bn_mul_normal(r, a, n2 + dna, b, n2 + dnb); if ((dna + dnb) < 0) memset(&r[2 * n2 + dna + dnb], 0, sizeof(BN_ULONG) * -(dna + dnb)); return; } /* r=(a[0]-a[1])*(b[1]-b[0]) */ c1 = bn_cmp_part_words(a, &(a[n]), tna, n - tna); c2 = bn_cmp_part_words(&(b[n]), b, tnb, tnb - n); zero = neg = 0; switch (c1 * 3 + c2) { case -4: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ break; case -3: zero = 1; break; case -2: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); /* + */ neg = 1; break; case -1: case 0: case 1: zero = 1; break; case 2: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); /* + */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ neg = 1; break; case 3: zero = 1; break; case 4: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); break; } # ifdef BN_MUL_COMBA if (n == 4 && dna == 0 && dnb == 0) { /* XXX: bn_mul_comba4 could take * extra args to do this well */ if (!zero) bn_mul_comba4(&(t[n2]), t, &(t[n])); else memset(&t[n2], 0, sizeof(*t) * 8); bn_mul_comba4(r, a, b); bn_mul_comba4(&(r[n2]), &(a[n]), &(b[n])); } else if (n == 8 && dna == 0 && dnb == 0) { /* XXX: bn_mul_comba8 could * take extra args to do * this well */ if (!zero) bn_mul_comba8(&(t[n2]), t, &(t[n])); else memset(&t[n2], 0, sizeof(*t) * 16); bn_mul_comba8(r, a, b); bn_mul_comba8(&(r[n2]), &(a[n]), &(b[n])); } else # endif /* BN_MUL_COMBA */ { p = &(t[n2 * 2]); if (!zero) bn_mul_recursive(&(t[n2]), t, &(t[n]), n, 0, 0, p); else memset(&t[n2], 0, sizeof(*t) * n2); bn_mul_recursive(r, a, b, n, 0, 0, p); bn_mul_recursive(&(r[n2]), &(a[n]), &(b[n]), n, dna, dnb, p); } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0]), c1 is the sign * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) */ c1 = (int)(bn_add_words(t, r, &(r[n2]), n2)); if (neg) { /* if t[32] is negative */ c1 -= (int)(bn_sub_words(&(t[n2]), t, &(t[n2]), n2)); } else { /* Might have a carry */ c1 += (int)(bn_add_words(&(t[n2]), &(t[n2]), t, n2)); } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0])+(a[0]*b[0])+(a[1]*b[1]) * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) * c1 holds the carry bits */ c1 += (int)(bn_add_words(&(r[n]), &(r[n]), &(t[n2]), n2)); if (c1) { p = &(r[n + n2]); lo = *p; ln = (lo + c1) & BN_MASK2; *p = ln; /* * The overflow will stop before we over write words we should not * overwrite */ if (ln < (BN_ULONG)c1) { do { p++; lo = *p; ln = (lo + 1) & BN_MASK2; *p = ln; } while (ln == 0); } } } /* * n+tn is the word length t needs to be n*4 is size, as does r */ /* tnX may not be negative but less than n */ void bn_mul_part_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n, int tna, int tnb, BN_ULONG *t) { int i, j, n2 = n * 2; int c1, c2, neg; BN_ULONG ln, lo, *p; if (n < 8) { bn_mul_normal(r, a, n + tna, b, n + tnb); return; } /* r=(a[0]-a[1])*(b[1]-b[0]) */ c1 = bn_cmp_part_words(a, &(a[n]), tna, n - tna); c2 = bn_cmp_part_words(&(b[n]), b, tnb, tnb - n); neg = 0; switch (c1 * 3 + c2) { case -4: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ break; case -3: case -2: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); /* + */ neg = 1; break; case -1: case 0: case 1: case 2: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); /* + */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ neg = 1; break; case 3: case 4: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); break; } /* * The zero case isn't yet implemented here. The speedup would probably * be negligible. */ # if 0 if (n == 4) { bn_mul_comba4(&(t[n2]), t, &(t[n])); bn_mul_comba4(r, a, b); bn_mul_normal(&(r[n2]), &(a[n]), tn, &(b[n]), tn); memset(&r[n2 + tn * 2], 0, sizeof(*r) * (n2 - tn * 2)); } else # endif if (n == 8) { bn_mul_comba8(&(t[n2]), t, &(t[n])); bn_mul_comba8(r, a, b); bn_mul_normal(&(r[n2]), &(a[n]), tna, &(b[n]), tnb); memset(&r[n2 + tna + tnb], 0, sizeof(*r) * (n2 - tna - tnb)); } else { p = &(t[n2 * 2]); bn_mul_recursive(&(t[n2]), t, &(t[n]), n, 0, 0, p); bn_mul_recursive(r, a, b, n, 0, 0, p); i = n / 2; /* * If there is only a bottom half to the number, just do it */ if (tna > tnb) j = tna - i; else j = tnb - i; if (j == 0) { bn_mul_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); memset(&r[n2 + i * 2], 0, sizeof(*r) * (n2 - i * 2)); } else if (j > 0) { /* eg, n == 16, i == 8 and tn == 11 */ bn_mul_part_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); memset(&(r[n2 + tna + tnb]), 0, sizeof(BN_ULONG) * (n2 - tna - tnb)); } else { /* (j < 0) eg, n == 16, i == 8 and tn == 5 */ memset(&r[n2], 0, sizeof(*r) * n2); if (tna < BN_MUL_RECURSIVE_SIZE_NORMAL && tnb < BN_MUL_RECURSIVE_SIZE_NORMAL) { bn_mul_normal(&(r[n2]), &(a[n]), tna, &(b[n]), tnb); } else { for (;;) { i /= 2; /* * these simplified conditions work exclusively because * difference between tna and tnb is 1 or 0 */ if (i < tna || i < tnb) { bn_mul_part_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); break; } else if (i == tna || i == tnb) { bn_mul_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); break; } } } } } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0]), c1 is the sign * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) */ c1 = (int)(bn_add_words(t, r, &(r[n2]), n2)); if (neg) { /* if t[32] is negative */ c1 -= (int)(bn_sub_words(&(t[n2]), t, &(t[n2]), n2)); } else { /* Might have a carry */ c1 += (int)(bn_add_words(&(t[n2]), &(t[n2]), t, n2)); } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0])+(a[0]*b[0])+(a[1]*b[1]) * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) * c1 holds the carry bits */ c1 += (int)(bn_add_words(&(r[n]), &(r[n]), &(t[n2]), n2)); if (c1) { p = &(r[n + n2]); lo = *p; ln = (lo + c1) & BN_MASK2; *p = ln; /* * The overflow will stop before we over write words we should not * overwrite */ if (ln < (BN_ULONG)c1) { do { p++; lo = *p; ln = (lo + 1) & BN_MASK2; *p = ln; } while (ln == 0); } } } /*- * a and b must be the same size, which is n2. * r needs to be n2 words and t needs to be n2*2 */ void bn_mul_low_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, BN_ULONG *t) { int n = n2 / 2; bn_mul_recursive(r, a, b, n, 0, 0, &(t[0])); if (n >= BN_MUL_LOW_RECURSIVE_SIZE_NORMAL) { bn_mul_low_recursive(&(t[0]), &(a[0]), &(b[n]), n, &(t[n2])); bn_add_words(&(r[n]), &(r[n]), &(t[0]), n); bn_mul_low_recursive(&(t[0]), &(a[n]), &(b[0]), n, &(t[n2])); bn_add_words(&(r[n]), &(r[n]), &(t[0]), n); } else { bn_mul_low_normal(&(t[0]), &(a[0]), &(b[n]), n); bn_mul_low_normal(&(t[n]), &(a[n]), &(b[0]), n); bn_add_words(&(r[n]), &(r[n]), &(t[0]), n); bn_add_words(&(r[n]), &(r[n]), &(t[n]), n); } } #endif /* BN_RECURSION */ int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = bn_mul_fixed_top(r, a, b, ctx); bn_correct_top(r); bn_check_top(r); return ret; } int bn_mul_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; int top, al, bl; BIGNUM *rr; #if defined(BN_MUL_COMBA) || defined(BN_RECURSION) int i; #endif #ifdef BN_RECURSION BIGNUM *t = NULL; int j = 0, k; #endif bn_check_top(a); bn_check_top(b); bn_check_top(r); al = a->top; bl = b->top; if ((al == 0) || (bl == 0)) { BN_zero(r); return 1; } top = al + bl; BN_CTX_start(ctx); if ((r == a) || (r == b)) { if ((rr = BN_CTX_get(ctx)) == NULL) goto err; } else rr = r; #if defined(BN_MUL_COMBA) || defined(BN_RECURSION) i = al - bl; #endif #ifdef BN_MUL_COMBA if (i == 0) { # if 0 if (al == 4) { if (bn_wexpand(rr, 8) == NULL) goto err; rr->top = 8; bn_mul_comba4(rr->d, a->d, b->d); goto end; } # endif if (al == 8) { if (bn_wexpand(rr, 16) == NULL) goto err; rr->top = 16; bn_mul_comba8(rr->d, a->d, b->d); goto end; } } #endif /* BN_MUL_COMBA */ #ifdef BN_RECURSION if ((al >= BN_MULL_SIZE_NORMAL) && (bl >= BN_MULL_SIZE_NORMAL)) { if (i >= -1 && i <= 1) { /* * Find out the power of two lower or equal to the longest of the * two numbers */ if (i >= 0) { j = BN_num_bits_word((BN_ULONG)al); } if (i == -1) { j = BN_num_bits_word((BN_ULONG)bl); } j = 1 << (j - 1); assert(j <= al || j <= bl); k = j + j; t = BN_CTX_get(ctx); if (t == NULL) goto err; if (al > j || bl > j) { if (bn_wexpand(t, k * 4) == NULL) goto err; if (bn_wexpand(rr, k * 4) == NULL) goto err; bn_mul_part_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d); } else { /* al <= j || bl <= j */ if (bn_wexpand(t, k * 2) == NULL) goto err; if (bn_wexpand(rr, k * 2) == NULL) goto err; bn_mul_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d); } rr->top = top; goto end; } } #endif /* BN_RECURSION */ if (bn_wexpand(rr, top) == NULL) goto err; rr->top = top; bn_mul_normal(rr->d, a->d, al, b->d, bl); #if defined(BN_MUL_COMBA) || defined(BN_RECURSION) end: #endif rr->neg = a->neg ^ b->neg; rr->flags |= BN_FLG_FIXED_TOP; if (r != rr && BN_copy(r, rr) == NULL) goto err; ret = 1; err: bn_check_top(r); BN_CTX_end(ctx); return ret; } void bn_mul_normal(BN_ULONG *r, BN_ULONG *a, int na, BN_ULONG *b, int nb) { BN_ULONG *rr; if (na < nb) { int itmp; BN_ULONG *ltmp; itmp = na; na = nb; nb = itmp; ltmp = a; a = b; b = ltmp; } rr = &(r[na]); if (nb <= 0) { (void)bn_mul_words(r, a, na, 0); return; } else rr[0] = bn_mul_words(r, a, na, b[0]); for (;;) { if (--nb <= 0) return; rr[1] = bn_mul_add_words(&(r[1]), a, na, b[1]); if (--nb <= 0) return; rr[2] = bn_mul_add_words(&(r[2]), a, na, b[2]); if (--nb <= 0) return; rr[3] = bn_mul_add_words(&(r[3]), a, na, b[3]); if (--nb <= 0) return; rr[4] = bn_mul_add_words(&(r[4]), a, na, b[4]); rr += 4; r += 4; b += 4; } } void bn_mul_low_normal(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n) { bn_mul_words(r, a, n, b[0]); for (;;) { if (--n <= 0) return; bn_mul_add_words(&(r[1]), a, n, b[1]); if (--n <= 0) return; bn_mul_add_words(&(r[2]), a, n, b[2]); if (--n <= 0) return; bn_mul_add_words(&(r[3]), a, n, b[3]); if (--n <= 0) return; bn_mul_add_words(&(r[4]), a, n, b[4]); r += 4; b += 4; } }
./openssl/crypto/bn/bn_asm.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <assert.h> #include <openssl/crypto.h> #include "internal/cryptlib.h" #include "bn_local.h" #if defined(BN_LLONG) || defined(BN_UMULT_HIGH) BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) { BN_ULONG c1 = 0; assert(num >= 0); if (num <= 0) return c1; # ifndef OPENSSL_SMALL_FOOTPRINT while (num & ~3) { mul_add(rp[0], ap[0], w, c1); mul_add(rp[1], ap[1], w, c1); mul_add(rp[2], ap[2], w, c1); mul_add(rp[3], ap[3], w, c1); ap += 4; rp += 4; num -= 4; } # endif while (num) { mul_add(rp[0], ap[0], w, c1); ap++; rp++; num--; } return c1; } BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) { BN_ULONG c1 = 0; assert(num >= 0); if (num <= 0) return c1; # ifndef OPENSSL_SMALL_FOOTPRINT while (num & ~3) { mul(rp[0], ap[0], w, c1); mul(rp[1], ap[1], w, c1); mul(rp[2], ap[2], w, c1); mul(rp[3], ap[3], w, c1); ap += 4; rp += 4; num -= 4; } # endif while (num) { mul(rp[0], ap[0], w, c1); ap++; rp++; num--; } return c1; } void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, int n) { assert(n >= 0); if (n <= 0) return; # ifndef OPENSSL_SMALL_FOOTPRINT while (n & ~3) { sqr(r[0], r[1], a[0]); sqr(r[2], r[3], a[1]); sqr(r[4], r[5], a[2]); sqr(r[6], r[7], a[3]); a += 4; r += 8; n -= 4; } # endif while (n) { sqr(r[0], r[1], a[0]); a++; r += 2; n--; } } #else /* !(defined(BN_LLONG) || * defined(BN_UMULT_HIGH)) */ BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) { BN_ULONG c = 0; BN_ULONG bl, bh; assert(num >= 0); if (num <= 0) return (BN_ULONG)0; bl = LBITS(w); bh = HBITS(w); # ifndef OPENSSL_SMALL_FOOTPRINT while (num & ~3) { mul_add(rp[0], ap[0], bl, bh, c); mul_add(rp[1], ap[1], bl, bh, c); mul_add(rp[2], ap[2], bl, bh, c); mul_add(rp[3], ap[3], bl, bh, c); ap += 4; rp += 4; num -= 4; } # endif while (num) { mul_add(rp[0], ap[0], bl, bh, c); ap++; rp++; num--; } return c; } BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) { BN_ULONG carry = 0; BN_ULONG bl, bh; assert(num >= 0); if (num <= 0) return (BN_ULONG)0; bl = LBITS(w); bh = HBITS(w); # ifndef OPENSSL_SMALL_FOOTPRINT while (num & ~3) { mul(rp[0], ap[0], bl, bh, carry); mul(rp[1], ap[1], bl, bh, carry); mul(rp[2], ap[2], bl, bh, carry); mul(rp[3], ap[3], bl, bh, carry); ap += 4; rp += 4; num -= 4; } # endif while (num) { mul(rp[0], ap[0], bl, bh, carry); ap++; rp++; num--; } return carry; } void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, int n) { assert(n >= 0); if (n <= 0) return; # ifndef OPENSSL_SMALL_FOOTPRINT while (n & ~3) { sqr64(r[0], r[1], a[0]); sqr64(r[2], r[3], a[1]); sqr64(r[4], r[5], a[2]); sqr64(r[6], r[7], a[3]); a += 4; r += 8; n -= 4; } # endif while (n) { sqr64(r[0], r[1], a[0]); a++; r += 2; n--; } } #endif /* !(defined(BN_LLONG) || * defined(BN_UMULT_HIGH)) */ #if defined(BN_LLONG) && defined(BN_DIV2W) BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d) { return ((BN_ULONG)(((((BN_ULLONG) h) << BN_BITS2) | l) / (BN_ULLONG) d)); } #else /* Divide h,l by d and return the result. */ /* I need to test this some more :-( */ BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d) { BN_ULONG dh, dl, q, ret = 0, th, tl, t; int i, count = 2; if (d == 0) return BN_MASK2; i = BN_num_bits_word(d); assert((i == BN_BITS2) || (h <= (BN_ULONG)1 << i)); i = BN_BITS2 - i; if (h >= d) h -= d; if (i) { d <<= i; h = (h << i) | (l >> (BN_BITS2 - i)); l <<= i; } dh = (d & BN_MASK2h) >> BN_BITS4; dl = (d & BN_MASK2l); for (;;) { if ((h >> BN_BITS4) == dh) q = BN_MASK2l; else q = h / dh; th = q * dh; tl = dl * q; for (;;) { t = h - th; if ((t & BN_MASK2h) || ((tl) <= ((t << BN_BITS4) | ((l & BN_MASK2h) >> BN_BITS4)))) break; q--; th -= dh; tl -= dl; } t = (tl >> BN_BITS4); tl = (tl << BN_BITS4) & BN_MASK2h; th += t; if (l < tl) th++; l -= tl; if (h < th) { h += d; q--; } h -= th; if (--count == 0) break; ret = q << BN_BITS4; h = ((h << BN_BITS4) | (l >> BN_BITS4)) & BN_MASK2; l = (l & BN_MASK2l) << BN_BITS4; } ret |= q; return ret; } #endif /* !defined(BN_LLONG) && defined(BN_DIV2W) */ #ifdef BN_LLONG BN_ULONG bn_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, int n) { BN_ULLONG ll = 0; assert(n >= 0); if (n <= 0) return (BN_ULONG)0; # ifndef OPENSSL_SMALL_FOOTPRINT while (n & ~3) { ll += (BN_ULLONG) a[0] + b[0]; r[0] = (BN_ULONG)ll & BN_MASK2; ll >>= BN_BITS2; ll += (BN_ULLONG) a[1] + b[1]; r[1] = (BN_ULONG)ll & BN_MASK2; ll >>= BN_BITS2; ll += (BN_ULLONG) a[2] + b[2]; r[2] = (BN_ULONG)ll & BN_MASK2; ll >>= BN_BITS2; ll += (BN_ULLONG) a[3] + b[3]; r[3] = (BN_ULONG)ll & BN_MASK2; ll >>= BN_BITS2; a += 4; b += 4; r += 4; n -= 4; } # endif while (n) { ll += (BN_ULLONG) a[0] + b[0]; r[0] = (BN_ULONG)ll & BN_MASK2; ll >>= BN_BITS2; a++; b++; r++; n--; } return (BN_ULONG)ll; } #else /* !BN_LLONG */ BN_ULONG bn_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, int n) { BN_ULONG c, l, t; assert(n >= 0); if (n <= 0) return (BN_ULONG)0; c = 0; # ifndef OPENSSL_SMALL_FOOTPRINT while (n & ~3) { t = a[0]; t = (t + c) & BN_MASK2; c = (t < c); l = (t + b[0]) & BN_MASK2; c += (l < t); r[0] = l; t = a[1]; t = (t + c) & BN_MASK2; c = (t < c); l = (t + b[1]) & BN_MASK2; c += (l < t); r[1] = l; t = a[2]; t = (t + c) & BN_MASK2; c = (t < c); l = (t + b[2]) & BN_MASK2; c += (l < t); r[2] = l; t = a[3]; t = (t + c) & BN_MASK2; c = (t < c); l = (t + b[3]) & BN_MASK2; c += (l < t); r[3] = l; a += 4; b += 4; r += 4; n -= 4; } # endif while (n) { t = a[0]; t = (t + c) & BN_MASK2; c = (t < c); l = (t + b[0]) & BN_MASK2; c += (l < t); r[0] = l; a++; b++; r++; n--; } return (BN_ULONG)c; } #endif /* !BN_LLONG */ BN_ULONG bn_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, int n) { BN_ULONG t1, t2; int c = 0; assert(n >= 0); if (n <= 0) return (BN_ULONG)0; #ifndef OPENSSL_SMALL_FOOTPRINT while (n & ~3) { t1 = a[0]; t2 = (t1 - c) & BN_MASK2; c = (t2 > t1); t1 = b[0]; t1 = (t2 - t1) & BN_MASK2; r[0] = t1; c += (t1 > t2); t1 = a[1]; t2 = (t1 - c) & BN_MASK2; c = (t2 > t1); t1 = b[1]; t1 = (t2 - t1) & BN_MASK2; r[1] = t1; c += (t1 > t2); t1 = a[2]; t2 = (t1 - c) & BN_MASK2; c = (t2 > t1); t1 = b[2]; t1 = (t2 - t1) & BN_MASK2; r[2] = t1; c += (t1 > t2); t1 = a[3]; t2 = (t1 - c) & BN_MASK2; c = (t2 > t1); t1 = b[3]; t1 = (t2 - t1) & BN_MASK2; r[3] = t1; c += (t1 > t2); a += 4; b += 4; r += 4; n -= 4; } #endif while (n) { t1 = a[0]; t2 = (t1 - c) & BN_MASK2; c = (t2 > t1); t1 = b[0]; t1 = (t2 - t1) & BN_MASK2; r[0] = t1; c += (t1 > t2); a++; b++; r++; n--; } return c; } #if defined(BN_MUL_COMBA) && !defined(OPENSSL_SMALL_FOOTPRINT) /* mul_add_c(a,b,c0,c1,c2) -- c+=a*b for three word number c=(c2,c1,c0) */ /* mul_add_c2(a,b,c0,c1,c2) -- c+=2*a*b for three word number c=(c2,c1,c0) */ /* sqr_add_c(a,i,c0,c1,c2) -- c+=a[i]^2 for three word number c=(c2,c1,c0) */ /* * sqr_add_c2(a,i,c0,c1,c2) -- c+=2*a[i]*a[j] for three word number * c=(c2,c1,c0) */ # ifdef BN_LLONG /* * Keep in mind that additions to multiplication result can not * overflow, because its high half cannot be all-ones. */ # define mul_add_c(a,b,c0,c1,c2) do { \ BN_ULONG hi; \ BN_ULLONG t = (BN_ULLONG)(a)*(b); \ t += c0; /* no carry */ \ c0 = (BN_ULONG)Lw(t); \ hi = (BN_ULONG)Hw(t); \ c1 = (c1+hi)&BN_MASK2; c2 += (c1<hi); \ } while(0) # define mul_add_c2(a,b,c0,c1,c2) do { \ BN_ULONG hi; \ BN_ULLONG t = (BN_ULLONG)(a)*(b); \ BN_ULLONG tt = t+c0; /* no carry */ \ c0 = (BN_ULONG)Lw(tt); \ hi = (BN_ULONG)Hw(tt); \ c1 = (c1+hi)&BN_MASK2; c2 += (c1<hi); \ t += c0; /* no carry */ \ c0 = (BN_ULONG)Lw(t); \ hi = (BN_ULONG)Hw(t); \ c1 = (c1+hi)&BN_MASK2; c2 += (c1<hi); \ } while(0) # define sqr_add_c(a,i,c0,c1,c2) do { \ BN_ULONG hi; \ BN_ULLONG t = (BN_ULLONG)a[i]*a[i]; \ t += c0; /* no carry */ \ c0 = (BN_ULONG)Lw(t); \ hi = (BN_ULONG)Hw(t); \ c1 = (c1+hi)&BN_MASK2; c2 += (c1<hi); \ } while(0) # define sqr_add_c2(a,i,j,c0,c1,c2) \ mul_add_c2((a)[i],(a)[j],c0,c1,c2) # elif defined(BN_UMULT_LOHI) /* * Keep in mind that additions to hi can not overflow, because * the high word of a multiplication result cannot be all-ones. */ # define mul_add_c(a,b,c0,c1,c2) do { \ BN_ULONG ta = (a), tb = (b); \ BN_ULONG lo, hi; \ BN_UMULT_LOHI(lo,hi,ta,tb); \ c0 += lo; hi += (c0<lo); \ c1 += hi; c2 += (c1<hi); \ } while(0) # define mul_add_c2(a,b,c0,c1,c2) do { \ BN_ULONG ta = (a), tb = (b); \ BN_ULONG lo, hi, tt; \ BN_UMULT_LOHI(lo,hi,ta,tb); \ c0 += lo; tt = hi + (c0<lo); \ c1 += tt; c2 += (c1<tt); \ c0 += lo; hi += (c0<lo); \ c1 += hi; c2 += (c1<hi); \ } while(0) # define sqr_add_c(a,i,c0,c1,c2) do { \ BN_ULONG ta = (a)[i]; \ BN_ULONG lo, hi; \ BN_UMULT_LOHI(lo,hi,ta,ta); \ c0 += lo; hi += (c0<lo); \ c1 += hi; c2 += (c1<hi); \ } while(0) # define sqr_add_c2(a,i,j,c0,c1,c2) \ mul_add_c2((a)[i],(a)[j],c0,c1,c2) # elif defined(BN_UMULT_HIGH) /* * Keep in mind that additions to hi can not overflow, because * the high word of a multiplication result cannot be all-ones. */ # define mul_add_c(a,b,c0,c1,c2) do { \ BN_ULONG ta = (a), tb = (b); \ BN_ULONG lo = ta * tb; \ BN_ULONG hi = BN_UMULT_HIGH(ta,tb); \ c0 += lo; hi += (c0<lo); \ c1 += hi; c2 += (c1<hi); \ } while(0) # define mul_add_c2(a,b,c0,c1,c2) do { \ BN_ULONG ta = (a), tb = (b), tt; \ BN_ULONG lo = ta * tb; \ BN_ULONG hi = BN_UMULT_HIGH(ta,tb); \ c0 += lo; tt = hi + (c0<lo); \ c1 += tt; c2 += (c1<tt); \ c0 += lo; hi += (c0<lo); \ c1 += hi; c2 += (c1<hi); \ } while(0) # define sqr_add_c(a,i,c0,c1,c2) do { \ BN_ULONG ta = (a)[i]; \ BN_ULONG lo = ta * ta; \ BN_ULONG hi = BN_UMULT_HIGH(ta,ta); \ c0 += lo; hi += (c0<lo); \ c1 += hi; c2 += (c1<hi); \ } while(0) # define sqr_add_c2(a,i,j,c0,c1,c2) \ mul_add_c2((a)[i],(a)[j],c0,c1,c2) # else /* !BN_LLONG */ /* * Keep in mind that additions to hi can not overflow, because * the high word of a multiplication result cannot be all-ones. */ # define mul_add_c(a,b,c0,c1,c2) do { \ BN_ULONG lo = LBITS(a), hi = HBITS(a); \ BN_ULONG bl = LBITS(b), bh = HBITS(b); \ mul64(lo,hi,bl,bh); \ c0 = (c0+lo)&BN_MASK2; hi += (c0<lo); \ c1 = (c1+hi)&BN_MASK2; c2 += (c1<hi); \ } while(0) # define mul_add_c2(a,b,c0,c1,c2) do { \ BN_ULONG tt; \ BN_ULONG lo = LBITS(a), hi = HBITS(a); \ BN_ULONG bl = LBITS(b), bh = HBITS(b); \ mul64(lo,hi,bl,bh); \ tt = hi; \ c0 = (c0+lo)&BN_MASK2; tt += (c0<lo); \ c1 = (c1+tt)&BN_MASK2; c2 += (c1<tt); \ c0 = (c0+lo)&BN_MASK2; hi += (c0<lo); \ c1 = (c1+hi)&BN_MASK2; c2 += (c1<hi); \ } while(0) # define sqr_add_c(a,i,c0,c1,c2) do { \ BN_ULONG lo, hi; \ sqr64(lo,hi,(a)[i]); \ c0 = (c0+lo)&BN_MASK2; hi += (c0<lo); \ c1 = (c1+hi)&BN_MASK2; c2 += (c1<hi); \ } while(0) # define sqr_add_c2(a,i,j,c0,c1,c2) \ mul_add_c2((a)[i],(a)[j],c0,c1,c2) # endif /* !BN_LLONG */ void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; mul_add_c(a[0], b[0], c1, c2, c3); r[0] = c1; c1 = 0; mul_add_c(a[0], b[1], c2, c3, c1); mul_add_c(a[1], b[0], c2, c3, c1); r[1] = c2; c2 = 0; mul_add_c(a[2], b[0], c3, c1, c2); mul_add_c(a[1], b[1], c3, c1, c2); mul_add_c(a[0], b[2], c3, c1, c2); r[2] = c3; c3 = 0; mul_add_c(a[0], b[3], c1, c2, c3); mul_add_c(a[1], b[2], c1, c2, c3); mul_add_c(a[2], b[1], c1, c2, c3); mul_add_c(a[3], b[0], c1, c2, c3); r[3] = c1; c1 = 0; mul_add_c(a[4], b[0], c2, c3, c1); mul_add_c(a[3], b[1], c2, c3, c1); mul_add_c(a[2], b[2], c2, c3, c1); mul_add_c(a[1], b[3], c2, c3, c1); mul_add_c(a[0], b[4], c2, c3, c1); r[4] = c2; c2 = 0; mul_add_c(a[0], b[5], c3, c1, c2); mul_add_c(a[1], b[4], c3, c1, c2); mul_add_c(a[2], b[3], c3, c1, c2); mul_add_c(a[3], b[2], c3, c1, c2); mul_add_c(a[4], b[1], c3, c1, c2); mul_add_c(a[5], b[0], c3, c1, c2); r[5] = c3; c3 = 0; mul_add_c(a[6], b[0], c1, c2, c3); mul_add_c(a[5], b[1], c1, c2, c3); mul_add_c(a[4], b[2], c1, c2, c3); mul_add_c(a[3], b[3], c1, c2, c3); mul_add_c(a[2], b[4], c1, c2, c3); mul_add_c(a[1], b[5], c1, c2, c3); mul_add_c(a[0], b[6], c1, c2, c3); r[6] = c1; c1 = 0; mul_add_c(a[0], b[7], c2, c3, c1); mul_add_c(a[1], b[6], c2, c3, c1); mul_add_c(a[2], b[5], c2, c3, c1); mul_add_c(a[3], b[4], c2, c3, c1); mul_add_c(a[4], b[3], c2, c3, c1); mul_add_c(a[5], b[2], c2, c3, c1); mul_add_c(a[6], b[1], c2, c3, c1); mul_add_c(a[7], b[0], c2, c3, c1); r[7] = c2; c2 = 0; mul_add_c(a[7], b[1], c3, c1, c2); mul_add_c(a[6], b[2], c3, c1, c2); mul_add_c(a[5], b[3], c3, c1, c2); mul_add_c(a[4], b[4], c3, c1, c2); mul_add_c(a[3], b[5], c3, c1, c2); mul_add_c(a[2], b[6], c3, c1, c2); mul_add_c(a[1], b[7], c3, c1, c2); r[8] = c3; c3 = 0; mul_add_c(a[2], b[7], c1, c2, c3); mul_add_c(a[3], b[6], c1, c2, c3); mul_add_c(a[4], b[5], c1, c2, c3); mul_add_c(a[5], b[4], c1, c2, c3); mul_add_c(a[6], b[3], c1, c2, c3); mul_add_c(a[7], b[2], c1, c2, c3); r[9] = c1; c1 = 0; mul_add_c(a[7], b[3], c2, c3, c1); mul_add_c(a[6], b[4], c2, c3, c1); mul_add_c(a[5], b[5], c2, c3, c1); mul_add_c(a[4], b[6], c2, c3, c1); mul_add_c(a[3], b[7], c2, c3, c1); r[10] = c2; c2 = 0; mul_add_c(a[4], b[7], c3, c1, c2); mul_add_c(a[5], b[6], c3, c1, c2); mul_add_c(a[6], b[5], c3, c1, c2); mul_add_c(a[7], b[4], c3, c1, c2); r[11] = c3; c3 = 0; mul_add_c(a[7], b[5], c1, c2, c3); mul_add_c(a[6], b[6], c1, c2, c3); mul_add_c(a[5], b[7], c1, c2, c3); r[12] = c1; c1 = 0; mul_add_c(a[6], b[7], c2, c3, c1); mul_add_c(a[7], b[6], c2, c3, c1); r[13] = c2; c2 = 0; mul_add_c(a[7], b[7], c3, c1, c2); r[14] = c3; r[15] = c1; } void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; mul_add_c(a[0], b[0], c1, c2, c3); r[0] = c1; c1 = 0; mul_add_c(a[0], b[1], c2, c3, c1); mul_add_c(a[1], b[0], c2, c3, c1); r[1] = c2; c2 = 0; mul_add_c(a[2], b[0], c3, c1, c2); mul_add_c(a[1], b[1], c3, c1, c2); mul_add_c(a[0], b[2], c3, c1, c2); r[2] = c3; c3 = 0; mul_add_c(a[0], b[3], c1, c2, c3); mul_add_c(a[1], b[2], c1, c2, c3); mul_add_c(a[2], b[1], c1, c2, c3); mul_add_c(a[3], b[0], c1, c2, c3); r[3] = c1; c1 = 0; mul_add_c(a[3], b[1], c2, c3, c1); mul_add_c(a[2], b[2], c2, c3, c1); mul_add_c(a[1], b[3], c2, c3, c1); r[4] = c2; c2 = 0; mul_add_c(a[2], b[3], c3, c1, c2); mul_add_c(a[3], b[2], c3, c1, c2); r[5] = c3; c3 = 0; mul_add_c(a[3], b[3], c1, c2, c3); r[6] = c1; r[7] = c2; } void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; sqr_add_c(a, 0, c1, c2, c3); r[0] = c1; c1 = 0; sqr_add_c2(a, 1, 0, c2, c3, c1); r[1] = c2; c2 = 0; sqr_add_c(a, 1, c3, c1, c2); sqr_add_c2(a, 2, 0, c3, c1, c2); r[2] = c3; c3 = 0; sqr_add_c2(a, 3, 0, c1, c2, c3); sqr_add_c2(a, 2, 1, c1, c2, c3); r[3] = c1; c1 = 0; sqr_add_c(a, 2, c2, c3, c1); sqr_add_c2(a, 3, 1, c2, c3, c1); sqr_add_c2(a, 4, 0, c2, c3, c1); r[4] = c2; c2 = 0; sqr_add_c2(a, 5, 0, c3, c1, c2); sqr_add_c2(a, 4, 1, c3, c1, c2); sqr_add_c2(a, 3, 2, c3, c1, c2); r[5] = c3; c3 = 0; sqr_add_c(a, 3, c1, c2, c3); sqr_add_c2(a, 4, 2, c1, c2, c3); sqr_add_c2(a, 5, 1, c1, c2, c3); sqr_add_c2(a, 6, 0, c1, c2, c3); r[6] = c1; c1 = 0; sqr_add_c2(a, 7, 0, c2, c3, c1); sqr_add_c2(a, 6, 1, c2, c3, c1); sqr_add_c2(a, 5, 2, c2, c3, c1); sqr_add_c2(a, 4, 3, c2, c3, c1); r[7] = c2; c2 = 0; sqr_add_c(a, 4, c3, c1, c2); sqr_add_c2(a, 5, 3, c3, c1, c2); sqr_add_c2(a, 6, 2, c3, c1, c2); sqr_add_c2(a, 7, 1, c3, c1, c2); r[8] = c3; c3 = 0; sqr_add_c2(a, 7, 2, c1, c2, c3); sqr_add_c2(a, 6, 3, c1, c2, c3); sqr_add_c2(a, 5, 4, c1, c2, c3); r[9] = c1; c1 = 0; sqr_add_c(a, 5, c2, c3, c1); sqr_add_c2(a, 6, 4, c2, c3, c1); sqr_add_c2(a, 7, 3, c2, c3, c1); r[10] = c2; c2 = 0; sqr_add_c2(a, 7, 4, c3, c1, c2); sqr_add_c2(a, 6, 5, c3, c1, c2); r[11] = c3; c3 = 0; sqr_add_c(a, 6, c1, c2, c3); sqr_add_c2(a, 7, 5, c1, c2, c3); r[12] = c1; c1 = 0; sqr_add_c2(a, 7, 6, c2, c3, c1); r[13] = c2; c2 = 0; sqr_add_c(a, 7, c3, c1, c2); r[14] = c3; r[15] = c1; } void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; sqr_add_c(a, 0, c1, c2, c3); r[0] = c1; c1 = 0; sqr_add_c2(a, 1, 0, c2, c3, c1); r[1] = c2; c2 = 0; sqr_add_c(a, 1, c3, c1, c2); sqr_add_c2(a, 2, 0, c3, c1, c2); r[2] = c3; c3 = 0; sqr_add_c2(a, 3, 0, c1, c2, c3); sqr_add_c2(a, 2, 1, c1, c2, c3); r[3] = c1; c1 = 0; sqr_add_c(a, 2, c2, c3, c1); sqr_add_c2(a, 3, 1, c2, c3, c1); r[4] = c2; c2 = 0; sqr_add_c2(a, 3, 2, c3, c1, c2); r[5] = c3; c3 = 0; sqr_add_c(a, 3, c1, c2, c3); r[6] = c1; r[7] = c2; } # ifdef OPENSSL_NO_ASM # ifdef OPENSSL_BN_ASM_MONT # include <alloca.h> /* * This is essentially reference implementation, which may or may not * result in performance improvement. E.g. on IA-32 this routine was * observed to give 40% faster rsa1024 private key operations and 10% * faster rsa4096 ones, while on AMD64 it improves rsa1024 sign only * by 10% and *worsens* rsa4096 sign by 15%. Once again, it's a * reference implementation, one to be used as starting point for * platform-specific assembler. Mentioned numbers apply to compiler * generated code compiled with and without -DOPENSSL_BN_ASM_MONT and * can vary not only from platform to platform, but even for compiler * versions. Assembler vs. assembler improvement coefficients can * [and are known to] differ and are to be documented elsewhere. */ int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0p, int num) { BN_ULONG c0, c1, ml, *tp, n0; # ifdef mul64 BN_ULONG mh; # endif volatile BN_ULONG *vp; int i = 0, j; # if 0 /* template for platform-specific * implementation */ if (ap == bp) return bn_sqr_mont(rp, ap, np, n0p, num); # endif vp = tp = alloca((num + 2) * sizeof(BN_ULONG)); n0 = *n0p; c0 = 0; ml = bp[0]; # ifdef mul64 mh = HBITS(ml); ml = LBITS(ml); for (j = 0; j < num; ++j) mul(tp[j], ap[j], ml, mh, c0); # else for (j = 0; j < num; ++j) mul(tp[j], ap[j], ml, c0); # endif tp[num] = c0; tp[num + 1] = 0; goto enter; for (i = 0; i < num; i++) { c0 = 0; ml = bp[i]; # ifdef mul64 mh = HBITS(ml); ml = LBITS(ml); for (j = 0; j < num; ++j) mul_add(tp[j], ap[j], ml, mh, c0); # else for (j = 0; j < num; ++j) mul_add(tp[j], ap[j], ml, c0); # endif c1 = (tp[num] + c0) & BN_MASK2; tp[num] = c1; tp[num + 1] = (c1 < c0 ? 1 : 0); enter: c1 = tp[0]; ml = (c1 * n0) & BN_MASK2; c0 = 0; # ifdef mul64 mh = HBITS(ml); ml = LBITS(ml); mul_add(c1, np[0], ml, mh, c0); # else mul_add(c1, ml, np[0], c0); # endif for (j = 1; j < num; j++) { c1 = tp[j]; # ifdef mul64 mul_add(c1, np[j], ml, mh, c0); # else mul_add(c1, ml, np[j], c0); # endif tp[j - 1] = c1 & BN_MASK2; } c1 = (tp[num] + c0) & BN_MASK2; tp[num - 1] = c1; tp[num] = tp[num + 1] + (c1 < c0 ? 1 : 0); } if (tp[num] != 0 || tp[num - 1] >= np[num - 1]) { c0 = bn_sub_words(rp, tp, np, num); if (tp[num] != 0 || c0 == 0) { for (i = 0; i < num + 2; i++) vp[i] = 0; return 1; } } for (i = 0; i < num; i++) rp[i] = tp[i], vp[i] = 0; vp[num] = 0; vp[num + 1] = 0; return 1; } # else /* * Return value of 0 indicates that multiplication/convolution was not * performed to signal the caller to fall down to alternative/original * code-path. */ int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num) { return 0; } # endif /* OPENSSL_BN_ASM_MONT */ # endif #else /* !BN_MUL_COMBA */ /* hmm... is it faster just to do a multiply? */ void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG t[8]; bn_sqr_normal(r, a, 4, t); } void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG t[16]; bn_sqr_normal(r, a, 8, t); } void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { r[4] = bn_mul_words(&(r[0]), a, 4, b[0]); r[5] = bn_mul_add_words(&(r[1]), a, 4, b[1]); r[6] = bn_mul_add_words(&(r[2]), a, 4, b[2]); r[7] = bn_mul_add_words(&(r[3]), a, 4, b[3]); } void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { r[8] = bn_mul_words(&(r[0]), a, 8, b[0]); r[9] = bn_mul_add_words(&(r[1]), a, 8, b[1]); r[10] = bn_mul_add_words(&(r[2]), a, 8, b[2]); r[11] = bn_mul_add_words(&(r[3]), a, 8, b[3]); r[12] = bn_mul_add_words(&(r[4]), a, 8, b[4]); r[13] = bn_mul_add_words(&(r[5]), a, 8, b[5]); r[14] = bn_mul_add_words(&(r[6]), a, 8, b[6]); r[15] = bn_mul_add_words(&(r[7]), a, 8, b[7]); } # ifdef OPENSSL_NO_ASM # ifdef OPENSSL_BN_ASM_MONT # include <alloca.h> int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0p, int num) { BN_ULONG c0, c1, *tp, n0 = *n0p; volatile BN_ULONG *vp; int i = 0, j; vp = tp = alloca((num + 2) * sizeof(BN_ULONG)); for (i = 0; i <= num; i++) tp[i] = 0; for (i = 0; i < num; i++) { c0 = bn_mul_add_words(tp, ap, num, bp[i]); c1 = (tp[num] + c0) & BN_MASK2; tp[num] = c1; tp[num + 1] = (c1 < c0 ? 1 : 0); c0 = bn_mul_add_words(tp, np, num, tp[0] * n0); c1 = (tp[num] + c0) & BN_MASK2; tp[num] = c1; tp[num + 1] += (c1 < c0 ? 1 : 0); for (j = 0; j <= num; j++) tp[j] = tp[j + 1]; } if (tp[num] != 0 || tp[num - 1] >= np[num - 1]) { c0 = bn_sub_words(rp, tp, np, num); if (tp[num] != 0 || c0 == 0) { for (i = 0; i < num + 2; i++) vp[i] = 0; return 1; } } for (i = 0; i < num; i++) rp[i] = tp[i], vp[i] = 0; vp[num] = 0; vp[num + 1] = 0; return 1; } # else int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num) { return 0; } # endif /* OPENSSL_BN_ASM_MONT */ # endif #endif /* !BN_MUL_COMBA */
./openssl/crypto/bn/bn_dh.c
/* * Copyright 2014-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 "bn_local.h" #include "internal/nelem.h" # include <openssl/dh.h> # include "crypto/bn_dh.h" # if BN_BITS2 == 64 # define BN_DEF(lo, hi) (BN_ULONG)hi << 32 | lo # else # define BN_DEF(lo, hi) lo, hi # endif /* DH parameters from RFC3526 */ # ifndef FIPS_MODULE /* * "1536-bit MODP Group" from RFC3526, Section 2. * * The prime is: 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 } * * RFC3526 specifies a generator of 2. * RFC2412 specifies a generator of 22. */ static const BN_ULONG modp_1536_p[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0xCA237327, 0xF1746C08), BN_DEF(0x4ABC9804, 0x670C354E), BN_DEF(0x7096966D, 0x9ED52907), BN_DEF(0x208552BB, 0x1C62F356), BN_DEF(0xDCA3AD96, 0x83655D23), BN_DEF(0xFD24CF5F, 0x69163FA8), BN_DEF(0x1C55D39A, 0x98DA4836), BN_DEF(0xA163BF05, 0xC2007CB8), BN_DEF(0xECE45B3D, 0x49286651), BN_DEF(0x7C4B1FE6, 0xAE9F2411), BN_DEF(0x5A899FA5, 0xEE386BFB), BN_DEF(0xF406B7ED, 0x0BFF5CB6), BN_DEF(0xA637ED6B, 0xF44C42E9), BN_DEF(0x625E7EC6, 0xE485B576), BN_DEF(0x6D51C245, 0x4FE1356D), BN_DEF(0xF25F1437, 0x302B0A6D), BN_DEF(0xCD3A431B, 0xEF9519B3), BN_DEF(0x8E3404DD, 0x514A0879), BN_DEF(0x3B139B22, 0x020BBEA6), BN_DEF(0x8A67CC74, 0x29024E08), BN_DEF(0x80DC1CD1, 0xC4C6628B), BN_DEF(0x2168C234, 0xC90FDAA2), BN_DEF(0xFFFFFFFF, 0xFFFFFFFF) }; /* q = (p - 1) / 2 */ static const BN_ULONG modp_1536_q[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0x6511B993, 0x78BA3604), BN_DEF(0x255E4C02, 0xB3861AA7), BN_DEF(0xB84B4B36, 0xCF6A9483), BN_DEF(0x1042A95D, 0x0E3179AB), BN_DEF(0xEE51D6CB, 0xC1B2AE91), BN_DEF(0x7E9267AF, 0x348B1FD4), BN_DEF(0x0E2AE9CD, 0xCC6D241B), BN_DEF(0x50B1DF82, 0xE1003E5C), BN_DEF(0xF6722D9E, 0x24943328), BN_DEF(0xBE258FF3, 0xD74F9208), BN_DEF(0xAD44CFD2, 0xF71C35FD), BN_DEF(0x7A035BF6, 0x85FFAE5B), BN_DEF(0xD31BF6B5, 0x7A262174), BN_DEF(0x312F3F63, 0xF242DABB), BN_DEF(0xB6A8E122, 0xA7F09AB6), BN_DEF(0xF92F8A1B, 0x98158536), BN_DEF(0xE69D218D, 0xF7CA8CD9), BN_DEF(0xC71A026E, 0x28A5043C), BN_DEF(0x1D89CD91, 0x0105DF53), BN_DEF(0x4533E63A, 0x94812704), BN_DEF(0xC06E0E68, 0x62633145), BN_DEF(0x10B4611A, 0xE487ED51), BN_DEF(0xFFFFFFFF, 0x7FFFFFFF) }; # endif /* FIPS_MODULE */ /*- * "2048-bit MODP Group" from RFC3526, Section 3. * * The prime is: 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 } * * RFC3526 specifies a generator of 2. */ static const BN_ULONG modp_2048_p[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0x8AACAA68, 0x15728E5A), BN_DEF(0x98FA0510, 0x15D22618), BN_DEF(0xEA956AE5, 0x3995497C), BN_DEF(0x95581718, 0xDE2BCBF6), BN_DEF(0x6F4C52C9, 0xB5C55DF0), BN_DEF(0xEC07A28F, 0x9B2783A2), BN_DEF(0x180E8603, 0xE39E772C), BN_DEF(0x2E36CE3B, 0x32905E46), BN_DEF(0xCA18217C, 0xF1746C08), BN_DEF(0x4ABC9804, 0x670C354E), BN_DEF(0x7096966D, 0x9ED52907), BN_DEF(0x208552BB, 0x1C62F356), BN_DEF(0xDCA3AD96, 0x83655D23), BN_DEF(0xFD24CF5F, 0x69163FA8), BN_DEF(0x1C55D39A, 0x98DA4836), BN_DEF(0xA163BF05, 0xC2007CB8), BN_DEF(0xECE45B3D, 0x49286651), BN_DEF(0x7C4B1FE6, 0xAE9F2411), BN_DEF(0x5A899FA5, 0xEE386BFB), BN_DEF(0xF406B7ED, 0x0BFF5CB6), BN_DEF(0xA637ED6B, 0xF44C42E9), BN_DEF(0x625E7EC6, 0xE485B576), BN_DEF(0x6D51C245, 0x4FE1356D), BN_DEF(0xF25F1437, 0x302B0A6D), BN_DEF(0xCD3A431B, 0xEF9519B3), BN_DEF(0x8E3404DD, 0x514A0879), BN_DEF(0x3B139B22, 0x020BBEA6), BN_DEF(0x8A67CC74, 0x29024E08), BN_DEF(0x80DC1CD1, 0xC4C6628B), BN_DEF(0x2168C234, 0xC90FDAA2), BN_DEF(0xFFFFFFFF, 0xFFFFFFFF) }; /* q = (p - 1) / 2 */ static const BN_ULONG modp_2048_q[] = { BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), BN_DEF(0x45565534, 0x0AB9472D), BN_DEF(0x4C7D0288, 0x8AE9130C), BN_DEF(0x754AB572, 0x1CCAA4BE), BN_DEF(0x4AAC0B8C, 0xEF15E5FB), BN_DEF(0x37A62964, 0xDAE2AEF8), BN_DEF(0x7603D147, 0xCD93C1D1), BN_DEF(0x0C074301, 0xF1CF3B96), BN_DEF(0x171B671D, 0x19482F23), BN_DEF(0x650C10BE, 0x78BA3604), BN_DEF(0x255E4C02, 0xB3861AA7), BN_DEF(0xB84B4B36, 0xCF6A9483), BN_DEF(0x1042A95D, 0x0E3179AB), BN_DEF(0xEE51D6CB, 0xC1B2AE91), BN_DEF(0x7E9267AF, 0x348B1FD4), BN_DEF(0x0E2AE9CD, 0xCC6D241B), BN_DEF(0x50B1DF82, 0xE1003E5C), BN_DEF(0xF6722D9E, 0x24943328), BN_DEF(0xBE258FF3, 0xD74F9208), BN_DEF(0xAD44CFD2, 0xF71C35FD), BN_DEF(0x7A035BF6, 0x85FFAE5B), BN_DEF(0xD31BF6B5, 0x7A262174), BN_DEF(0x312F3F63, 0xF242DABB), BN_DEF(0xB6A8E122, 0xA7F09AB6), BN_DEF(0xF92F8A1B, 0x98158536), BN_DEF(0xE69D218D, 0xF7CA8CD9), BN_DEF(0xC71A026E, 0x28A5043C), BN_DEF(0x1D89CD91, 0x0105DF53), BN_DEF(0x4533E63A, 0x94812704), BN_DEF(0xC06E0E68, 0x62633145), BN_DEF(0x10B4611A, 0xE487ED51), BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), }; /*- * "3072-bit MODP Group" from RFC3526, Section 4. * * The prime is: 2^3072 - 2^3008 - 1 + 2^64 * { [2^2942 pi] + 1690314 } * * RFC3526 specifies a generator of 2. */ static const BN_ULONG modp_3072_p[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0xA93AD2CA, 0x4B82D120), BN_DEF(0xE0FD108E, 0x43DB5BFC), BN_DEF(0x74E5AB31, 0x08E24FA0), BN_DEF(0xBAD946E2, 0x770988C0), BN_DEF(0x7A615D6C, 0xBBE11757), BN_DEF(0x177B200C, 0x521F2B18), BN_DEF(0x3EC86A64, 0xD8760273), BN_DEF(0xD98A0864, 0xF12FFA06), BN_DEF(0x1AD2EE6B, 0xCEE3D226), BN_DEF(0x4A25619D, 0x1E8C94E0), BN_DEF(0xDB0933D7, 0xABF5AE8C), BN_DEF(0xA6E1E4C7, 0xB3970F85), BN_DEF(0x5D060C7D, 0x8AEA7157), BN_DEF(0x58DBEF0A, 0xECFB8504), BN_DEF(0xDF1CBA64, 0xA85521AB), BN_DEF(0x04507A33, 0xAD33170D), BN_DEF(0x8AAAC42D, 0x15728E5A), BN_DEF(0x98FA0510, 0x15D22618), BN_DEF(0xEA956AE5, 0x3995497C), BN_DEF(0x95581718, 0xDE2BCBF6), BN_DEF(0x6F4C52C9, 0xB5C55DF0), BN_DEF(0xEC07A28F, 0x9B2783A2), BN_DEF(0x180E8603, 0xE39E772C), BN_DEF(0x2E36CE3B, 0x32905E46), BN_DEF(0xCA18217C, 0xF1746C08), BN_DEF(0x4ABC9804, 0x670C354E), BN_DEF(0x7096966D, 0x9ED52907), BN_DEF(0x208552BB, 0x1C62F356), BN_DEF(0xDCA3AD96, 0x83655D23), BN_DEF(0xFD24CF5F, 0x69163FA8), BN_DEF(0x1C55D39A, 0x98DA4836), BN_DEF(0xA163BF05, 0xC2007CB8), BN_DEF(0xECE45B3D, 0x49286651), BN_DEF(0x7C4B1FE6, 0xAE9F2411), BN_DEF(0x5A899FA5, 0xEE386BFB), BN_DEF(0xF406B7ED, 0x0BFF5CB6), BN_DEF(0xA637ED6B, 0xF44C42E9), BN_DEF(0x625E7EC6, 0xE485B576), BN_DEF(0x6D51C245, 0x4FE1356D), BN_DEF(0xF25F1437, 0x302B0A6D), BN_DEF(0xCD3A431B, 0xEF9519B3), BN_DEF(0x8E3404DD, 0x514A0879), BN_DEF(0x3B139B22, 0x020BBEA6), BN_DEF(0x8A67CC74, 0x29024E08), BN_DEF(0x80DC1CD1, 0xC4C6628B), BN_DEF(0x2168C234, 0xC90FDAA2), BN_DEF(0xFFFFFFFF, 0xFFFFFFFF) }; /* q = (p - 1) / 2 */ static const BN_ULONG modp_3072_q[] = { BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), BN_DEF(0x549D6965, 0x25C16890), BN_DEF(0x707E8847, 0xA1EDADFE), BN_DEF(0x3A72D598, 0x047127D0), BN_DEF(0x5D6CA371, 0x3B84C460), BN_DEF(0xBD30AEB6, 0x5DF08BAB), BN_DEF(0x0BBD9006, 0x290F958C), BN_DEF(0x9F643532, 0x6C3B0139), BN_DEF(0x6CC50432, 0xF897FD03), BN_DEF(0x0D697735, 0xE771E913), BN_DEF(0x2512B0CE, 0x8F464A70), BN_DEF(0x6D8499EB, 0xD5FAD746), BN_DEF(0xD370F263, 0xD9CB87C2), BN_DEF(0xAE83063E, 0x457538AB), BN_DEF(0x2C6DF785, 0x767DC282), BN_DEF(0xEF8E5D32, 0xD42A90D5), BN_DEF(0x82283D19, 0xD6998B86), BN_DEF(0x45556216, 0x0AB9472D), BN_DEF(0x4C7D0288, 0x8AE9130C), BN_DEF(0x754AB572, 0x1CCAA4BE), BN_DEF(0x4AAC0B8C, 0xEF15E5FB), BN_DEF(0x37A62964, 0xDAE2AEF8), BN_DEF(0x7603D147, 0xCD93C1D1), BN_DEF(0x0C074301, 0xF1CF3B96), BN_DEF(0x171B671D, 0x19482F23), BN_DEF(0x650C10BE, 0x78BA3604), BN_DEF(0x255E4C02, 0xB3861AA7), BN_DEF(0xB84B4B36, 0xCF6A9483), BN_DEF(0x1042A95D, 0x0E3179AB), BN_DEF(0xEE51D6CB, 0xC1B2AE91), BN_DEF(0x7E9267AF, 0x348B1FD4), BN_DEF(0x0E2AE9CD, 0xCC6D241B), BN_DEF(0x50B1DF82, 0xE1003E5C), BN_DEF(0xF6722D9E, 0x24943328), BN_DEF(0xBE258FF3, 0xD74F9208), BN_DEF(0xAD44CFD2, 0xF71C35FD), BN_DEF(0x7A035BF6, 0x85FFAE5B), BN_DEF(0xD31BF6B5, 0x7A262174), BN_DEF(0x312F3F63, 0xF242DABB), BN_DEF(0xB6A8E122, 0xA7F09AB6), BN_DEF(0xF92F8A1B, 0x98158536), BN_DEF(0xE69D218D, 0xF7CA8CD9), BN_DEF(0xC71A026E, 0x28A5043C), BN_DEF(0x1D89CD91, 0x0105DF53), BN_DEF(0x4533E63A, 0x94812704), BN_DEF(0xC06E0E68, 0x62633145), BN_DEF(0x10B4611A, 0xE487ED51), BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), }; /*- * "4096-bit MODP Group" from RFC3526, Section 5. * * The prime is: 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 } * * RFC3526 specifies a generator of 2. */ static const BN_ULONG modp_4096_p[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0x34063199, 0x4DF435C9), BN_DEF(0x90A6C08F, 0x86FFB7DC), BN_DEF(0x8D8FDDC1, 0x93B4EA98), BN_DEF(0xD5B05AA9, 0xD0069127), BN_DEF(0x2170481C, 0xB81BDD76), BN_DEF(0xCEE2D7AF, 0x1F612970), BN_DEF(0x515BE7ED, 0x233BA186), BN_DEF(0xA090C3A2, 0x99B2964F), BN_DEF(0x4E6BC05D, 0x287C5947), BN_DEF(0x1FBECAA6, 0x2E8EFC14), BN_DEF(0x04DE8EF9, 0xDBBBC2DB), BN_DEF(0x2AD44CE8, 0x2583E9CA), BN_DEF(0xB6150BDA, 0x1A946834), BN_DEF(0x6AF4E23C, 0x99C32718), BN_DEF(0xBDBA5B26, 0x88719A10), BN_DEF(0xA787E6D7, 0x1A723C12), BN_DEF(0xA9210801, 0x4B82D120), BN_DEF(0xE0FD108E, 0x43DB5BFC), BN_DEF(0x74E5AB31, 0x08E24FA0), BN_DEF(0xBAD946E2, 0x770988C0), BN_DEF(0x7A615D6C, 0xBBE11757), BN_DEF(0x177B200C, 0x521F2B18), BN_DEF(0x3EC86A64, 0xD8760273), BN_DEF(0xD98A0864, 0xF12FFA06), BN_DEF(0x1AD2EE6B, 0xCEE3D226), BN_DEF(0x4A25619D, 0x1E8C94E0), BN_DEF(0xDB0933D7, 0xABF5AE8C), BN_DEF(0xA6E1E4C7, 0xB3970F85), BN_DEF(0x5D060C7D, 0x8AEA7157), BN_DEF(0x58DBEF0A, 0xECFB8504), BN_DEF(0xDF1CBA64, 0xA85521AB), BN_DEF(0x04507A33, 0xAD33170D), BN_DEF(0x8AAAC42D, 0x15728E5A), BN_DEF(0x98FA0510, 0x15D22618), BN_DEF(0xEA956AE5, 0x3995497C), BN_DEF(0x95581718, 0xDE2BCBF6), BN_DEF(0x6F4C52C9, 0xB5C55DF0), BN_DEF(0xEC07A28F, 0x9B2783A2), BN_DEF(0x180E8603, 0xE39E772C), BN_DEF(0x2E36CE3B, 0x32905E46), BN_DEF(0xCA18217C, 0xF1746C08), BN_DEF(0x4ABC9804, 0x670C354E), BN_DEF(0x7096966D, 0x9ED52907), BN_DEF(0x208552BB, 0x1C62F356), BN_DEF(0xDCA3AD96, 0x83655D23), BN_DEF(0xFD24CF5F, 0x69163FA8), BN_DEF(0x1C55D39A, 0x98DA4836), BN_DEF(0xA163BF05, 0xC2007CB8), BN_DEF(0xECE45B3D, 0x49286651), BN_DEF(0x7C4B1FE6, 0xAE9F2411), BN_DEF(0x5A899FA5, 0xEE386BFB), BN_DEF(0xF406B7ED, 0x0BFF5CB6), BN_DEF(0xA637ED6B, 0xF44C42E9), BN_DEF(0x625E7EC6, 0xE485B576), BN_DEF(0x6D51C245, 0x4FE1356D), BN_DEF(0xF25F1437, 0x302B0A6D), BN_DEF(0xCD3A431B, 0xEF9519B3), BN_DEF(0x8E3404DD, 0x514A0879), BN_DEF(0x3B139B22, 0x020BBEA6), BN_DEF(0x8A67CC74, 0x29024E08), BN_DEF(0x80DC1CD1, 0xC4C6628B), BN_DEF(0x2168C234, 0xC90FDAA2), BN_DEF(0xFFFFFFFF, 0xFFFFFFFF) }; /* q = (p - 1) / 2 */ static const BN_ULONG modp_4096_q[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0x9A0318CC, 0xA6FA1AE4), BN_DEF(0x48536047, 0xC37FDBEE), BN_DEF(0x46C7EEE0, 0xC9DA754C), BN_DEF(0xEAD82D54, 0x68034893), BN_DEF(0x10B8240E, 0xDC0DEEBB), BN_DEF(0x67716BD7, 0x8FB094B8), BN_DEF(0x28ADF3F6, 0x119DD0C3), BN_DEF(0xD04861D1, 0xCCD94B27), BN_DEF(0xA735E02E, 0x143E2CA3), BN_DEF(0x0FDF6553, 0x97477E0A), BN_DEF(0x826F477C, 0x6DDDE16D), BN_DEF(0x156A2674, 0x12C1F4E5), BN_DEF(0x5B0A85ED, 0x0D4A341A), BN_DEF(0x357A711E, 0x4CE1938C), BN_DEF(0x5EDD2D93, 0xC438CD08), BN_DEF(0x53C3F36B, 0x8D391E09), BN_DEF(0x54908400, 0x25C16890), BN_DEF(0x707E8847, 0xA1EDADFE), BN_DEF(0x3A72D598, 0x047127D0), BN_DEF(0x5D6CA371, 0x3B84C460), BN_DEF(0xBD30AEB6, 0x5DF08BAB), BN_DEF(0x0BBD9006, 0x290F958C), BN_DEF(0x9F643532, 0x6C3B0139), BN_DEF(0x6CC50432, 0xF897FD03), BN_DEF(0x0D697735, 0xE771E913), BN_DEF(0x2512B0CE, 0x8F464A70), BN_DEF(0x6D8499EB, 0xD5FAD746), BN_DEF(0xD370F263, 0xD9CB87C2), BN_DEF(0xAE83063E, 0x457538AB), BN_DEF(0x2C6DF785, 0x767DC282), BN_DEF(0xEF8E5D32, 0xD42A90D5), BN_DEF(0x82283D19, 0xD6998B86), BN_DEF(0x45556216, 0x0AB9472D), BN_DEF(0x4C7D0288, 0x8AE9130C), BN_DEF(0x754AB572, 0x1CCAA4BE), BN_DEF(0x4AAC0B8C, 0xEF15E5FB), BN_DEF(0x37A62964, 0xDAE2AEF8), BN_DEF(0x7603D147, 0xCD93C1D1), BN_DEF(0x0C074301, 0xF1CF3B96), BN_DEF(0x171B671D, 0x19482F23), BN_DEF(0x650C10BE, 0x78BA3604), BN_DEF(0x255E4C02, 0xB3861AA7), BN_DEF(0xB84B4B36, 0xCF6A9483), BN_DEF(0x1042A95D, 0x0E3179AB), BN_DEF(0xEE51D6CB, 0xC1B2AE91), BN_DEF(0x7E9267AF, 0x348B1FD4), BN_DEF(0x0E2AE9CD, 0xCC6D241B), BN_DEF(0x50B1DF82, 0xE1003E5C), BN_DEF(0xF6722D9E, 0x24943328), BN_DEF(0xBE258FF3, 0xD74F9208), BN_DEF(0xAD44CFD2, 0xF71C35FD), BN_DEF(0x7A035BF6, 0x85FFAE5B), BN_DEF(0xD31BF6B5, 0x7A262174), BN_DEF(0x312F3F63, 0xF242DABB), BN_DEF(0xB6A8E122, 0xA7F09AB6), BN_DEF(0xF92F8A1B, 0x98158536), BN_DEF(0xE69D218D, 0xF7CA8CD9), BN_DEF(0xC71A026E, 0x28A5043C), BN_DEF(0x1D89CD91, 0x0105DF53), BN_DEF(0x4533E63A, 0x94812704), BN_DEF(0xC06E0E68, 0x62633145), BN_DEF(0x10B4611A, 0xE487ED51), BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), }; /*- * "6144-bit MODP Group" from RFC3526, Section 6. * * The prime is: 2^6144 - 2^6080 - 1 + 2^64 * { [2^6014 pi] + 929484 } * * RFC3526 specifies a generator of 2. */ static const BN_ULONG modp_6144_p[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0x6DCC4024, 0xE694F91E), BN_DEF(0x0B7474D6, 0x12BF2D5B), BN_DEF(0x3F4860EE, 0x043E8F66), BN_DEF(0x6E3C0468, 0x387FE8D7), BN_DEF(0x2EF29632, 0xDA56C9EC), BN_DEF(0xA313D55C, 0xEB19CCB1), BN_DEF(0x8A1FBFF0, 0xF550AA3D), BN_DEF(0xB7C5DA76, 0x06A1D58B), BN_DEF(0xF29BE328, 0xA79715EE), BN_DEF(0x0F8037E0, 0x14CC5ED2), BN_DEF(0xBF48E1D8, 0xCC8F6D7E), BN_DEF(0x2B4154AA, 0x4BD407B2), BN_DEF(0xFF585AC5, 0x0F1D45B7), BN_DEF(0x36CC88BE, 0x23A97A7E), BN_DEF(0xBEC7E8F3, 0x59E7C97F), BN_DEF(0x900B1C9E, 0xB5A84031), BN_DEF(0x46980C82, 0xD55E702F), BN_DEF(0x6E74FEF6, 0xF482D7CE), BN_DEF(0xD1721D03, 0xF032EA15), BN_DEF(0xC64B92EC, 0x5983CA01), BN_DEF(0x378CD2BF, 0x6FB8F401), BN_DEF(0x2BD7AF42, 0x33205151), BN_DEF(0xE6CC254B, 0xDB7F1447), BN_DEF(0xCED4BB1B, 0x44CE6CBA), BN_DEF(0xCF9B14ED, 0xDA3EDBEB), BN_DEF(0x865A8918, 0x179727B0), BN_DEF(0x9027D831, 0xB06A53ED), BN_DEF(0x413001AE, 0xE5DB382F), BN_DEF(0xAD9E530E, 0xF8FF9406), BN_DEF(0x3DBA37BD, 0xC9751E76), BN_DEF(0x602646DE, 0xC1D4DCB2), BN_DEF(0xD27C7026, 0x36C3FAB4), BN_DEF(0x34028492, 0x4DF435C9), BN_DEF(0x90A6C08F, 0x86FFB7DC), BN_DEF(0x8D8FDDC1, 0x93B4EA98), BN_DEF(0xD5B05AA9, 0xD0069127), BN_DEF(0x2170481C, 0xB81BDD76), BN_DEF(0xCEE2D7AF, 0x1F612970), BN_DEF(0x515BE7ED, 0x233BA186), BN_DEF(0xA090C3A2, 0x99B2964F), BN_DEF(0x4E6BC05D, 0x287C5947), BN_DEF(0x1FBECAA6, 0x2E8EFC14), BN_DEF(0x04DE8EF9, 0xDBBBC2DB), BN_DEF(0x2AD44CE8, 0x2583E9CA), BN_DEF(0xB6150BDA, 0x1A946834), BN_DEF(0x6AF4E23C, 0x99C32718), BN_DEF(0xBDBA5B26, 0x88719A10), BN_DEF(0xA787E6D7, 0x1A723C12), BN_DEF(0xA9210801, 0x4B82D120), BN_DEF(0xE0FD108E, 0x43DB5BFC), BN_DEF(0x74E5AB31, 0x08E24FA0), BN_DEF(0xBAD946E2, 0x770988C0), BN_DEF(0x7A615D6C, 0xBBE11757), BN_DEF(0x177B200C, 0x521F2B18), BN_DEF(0x3EC86A64, 0xD8760273), BN_DEF(0xD98A0864, 0xF12FFA06), BN_DEF(0x1AD2EE6B, 0xCEE3D226), BN_DEF(0x4A25619D, 0x1E8C94E0), BN_DEF(0xDB0933D7, 0xABF5AE8C), BN_DEF(0xA6E1E4C7, 0xB3970F85), BN_DEF(0x5D060C7D, 0x8AEA7157), BN_DEF(0x58DBEF0A, 0xECFB8504), BN_DEF(0xDF1CBA64, 0xA85521AB), BN_DEF(0x04507A33, 0xAD33170D), BN_DEF(0x8AAAC42D, 0x15728E5A), BN_DEF(0x98FA0510, 0x15D22618), BN_DEF(0xEA956AE5, 0x3995497C), BN_DEF(0x95581718, 0xDE2BCBF6), BN_DEF(0x6F4C52C9, 0xB5C55DF0), BN_DEF(0xEC07A28F, 0x9B2783A2), BN_DEF(0x180E8603, 0xE39E772C), BN_DEF(0x2E36CE3B, 0x32905E46), BN_DEF(0xCA18217C, 0xF1746C08), BN_DEF(0x4ABC9804, 0x670C354E), BN_DEF(0x7096966D, 0x9ED52907), BN_DEF(0x208552BB, 0x1C62F356), BN_DEF(0xDCA3AD96, 0x83655D23), BN_DEF(0xFD24CF5F, 0x69163FA8), BN_DEF(0x1C55D39A, 0x98DA4836), BN_DEF(0xA163BF05, 0xC2007CB8), BN_DEF(0xECE45B3D, 0x49286651), BN_DEF(0x7C4B1FE6, 0xAE9F2411), BN_DEF(0x5A899FA5, 0xEE386BFB), BN_DEF(0xF406B7ED, 0x0BFF5CB6), BN_DEF(0xA637ED6B, 0xF44C42E9), BN_DEF(0x625E7EC6, 0xE485B576), BN_DEF(0x6D51C245, 0x4FE1356D), BN_DEF(0xF25F1437, 0x302B0A6D), BN_DEF(0xCD3A431B, 0xEF9519B3), BN_DEF(0x8E3404DD, 0x514A0879), BN_DEF(0x3B139B22, 0x020BBEA6), BN_DEF(0x8A67CC74, 0x29024E08), BN_DEF(0x80DC1CD1, 0xC4C6628B), BN_DEF(0x2168C234, 0xC90FDAA2), BN_DEF(0xFFFFFFFF, 0xFFFFFFFF) }; /* q = (p - 1) / 2 */ static const BN_ULONG modp_6144_q[] = { BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), BN_DEF(0x36E62012, 0x734A7C8F), BN_DEF(0x85BA3A6B, 0x095F96AD), BN_DEF(0x1FA43077, 0x021F47B3), BN_DEF(0xB71E0234, 0x1C3FF46B), BN_DEF(0x17794B19, 0x6D2B64F6), BN_DEF(0xD189EAAE, 0x758CE658), BN_DEF(0xC50FDFF8, 0x7AA8551E), BN_DEF(0xDBE2ED3B, 0x0350EAC5), BN_DEF(0x794DF194, 0x53CB8AF7), BN_DEF(0x07C01BF0, 0x0A662F69), BN_DEF(0x5FA470EC, 0x6647B6BF), BN_DEF(0x15A0AA55, 0xA5EA03D9), BN_DEF(0xFFAC2D62, 0x078EA2DB), BN_DEF(0x1B66445F, 0x91D4BD3F), BN_DEF(0xDF63F479, 0x2CF3E4BF), BN_DEF(0xC8058E4F, 0x5AD42018), BN_DEF(0xA34C0641, 0x6AAF3817), BN_DEF(0x373A7F7B, 0xFA416BE7), BN_DEF(0xE8B90E81, 0x7819750A), BN_DEF(0xE325C976, 0xACC1E500), BN_DEF(0x9BC6695F, 0x37DC7A00), BN_DEF(0x95EBD7A1, 0x999028A8), BN_DEF(0xF36612A5, 0xEDBF8A23), BN_DEF(0x676A5D8D, 0xA267365D), BN_DEF(0xE7CD8A76, 0x6D1F6DF5), BN_DEF(0x432D448C, 0x8BCB93D8), BN_DEF(0xC813EC18, 0x583529F6), BN_DEF(0xA09800D7, 0x72ED9C17), BN_DEF(0x56CF2987, 0xFC7FCA03), BN_DEF(0x1EDD1BDE, 0x64BA8F3B), BN_DEF(0x3013236F, 0x60EA6E59), BN_DEF(0x693E3813, 0x1B61FD5A), BN_DEF(0x9A014249, 0xA6FA1AE4), BN_DEF(0x48536047, 0xC37FDBEE), BN_DEF(0x46C7EEE0, 0xC9DA754C), BN_DEF(0xEAD82D54, 0x68034893), BN_DEF(0x10B8240E, 0xDC0DEEBB), BN_DEF(0x67716BD7, 0x8FB094B8), BN_DEF(0x28ADF3F6, 0x119DD0C3), BN_DEF(0xD04861D1, 0xCCD94B27), BN_DEF(0xA735E02E, 0x143E2CA3), BN_DEF(0x0FDF6553, 0x97477E0A), BN_DEF(0x826F477C, 0x6DDDE16D), BN_DEF(0x156A2674, 0x12C1F4E5), BN_DEF(0x5B0A85ED, 0x0D4A341A), BN_DEF(0x357A711E, 0x4CE1938C), BN_DEF(0x5EDD2D93, 0xC438CD08), BN_DEF(0x53C3F36B, 0x8D391E09), BN_DEF(0x54908400, 0x25C16890), BN_DEF(0x707E8847, 0xA1EDADFE), BN_DEF(0x3A72D598, 0x047127D0), BN_DEF(0x5D6CA371, 0x3B84C460), BN_DEF(0xBD30AEB6, 0x5DF08BAB), BN_DEF(0x0BBD9006, 0x290F958C), BN_DEF(0x9F643532, 0x6C3B0139), BN_DEF(0x6CC50432, 0xF897FD03), BN_DEF(0x0D697735, 0xE771E913), BN_DEF(0x2512B0CE, 0x8F464A70), BN_DEF(0x6D8499EB, 0xD5FAD746), BN_DEF(0xD370F263, 0xD9CB87C2), BN_DEF(0xAE83063E, 0x457538AB), BN_DEF(0x2C6DF785, 0x767DC282), BN_DEF(0xEF8E5D32, 0xD42A90D5), BN_DEF(0x82283D19, 0xD6998B86), BN_DEF(0x45556216, 0x0AB9472D), BN_DEF(0x4C7D0288, 0x8AE9130C), BN_DEF(0x754AB572, 0x1CCAA4BE), BN_DEF(0x4AAC0B8C, 0xEF15E5FB), BN_DEF(0x37A62964, 0xDAE2AEF8), BN_DEF(0x7603D147, 0xCD93C1D1), BN_DEF(0x0C074301, 0xF1CF3B96), BN_DEF(0x171B671D, 0x19482F23), BN_DEF(0x650C10BE, 0x78BA3604), BN_DEF(0x255E4C02, 0xB3861AA7), BN_DEF(0xB84B4B36, 0xCF6A9483), BN_DEF(0x1042A95D, 0x0E3179AB), BN_DEF(0xEE51D6CB, 0xC1B2AE91), BN_DEF(0x7E9267AF, 0x348B1FD4), BN_DEF(0x0E2AE9CD, 0xCC6D241B), BN_DEF(0x50B1DF82, 0xE1003E5C), BN_DEF(0xF6722D9E, 0x24943328), BN_DEF(0xBE258FF3, 0xD74F9208), BN_DEF(0xAD44CFD2, 0xF71C35FD), BN_DEF(0x7A035BF6, 0x85FFAE5B), BN_DEF(0xD31BF6B5, 0x7A262174), BN_DEF(0x312F3F63, 0xF242DABB), BN_DEF(0xB6A8E122, 0xA7F09AB6), BN_DEF(0xF92F8A1B, 0x98158536), BN_DEF(0xE69D218D, 0xF7CA8CD9), BN_DEF(0xC71A026E, 0x28A5043C), BN_DEF(0x1D89CD91, 0x0105DF53), BN_DEF(0x4533E63A, 0x94812704), BN_DEF(0xC06E0E68, 0x62633145), BN_DEF(0x10B4611A, 0xE487ED51), BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), }; /* * "8192-bit MODP Group" from RFC3526, Section 7. * * The prime is: 2^8192 - 2^8128 - 1 + 2^64 * { [2^8062 pi] + 4743158 } * * RFC3526 specifies a generator of 2. */ static const BN_ULONG modp_8192_p[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0x98EDD3DF, 0x60C980DD), BN_DEF(0x80B96E71, 0xC81F56E8), BN_DEF(0x765694DF, 0x9E3050E2), BN_DEF(0x5677E9AA, 0x9558E447), BN_DEF(0xFC026E47, 0xC9190DA6), BN_DEF(0xD5EE382B, 0x889A002E), BN_DEF(0x481C6CD7, 0x4009438B), BN_DEF(0xEB879F92, 0x359046F4), BN_DEF(0x1ECFA268, 0xFAF36BC3), BN_DEF(0x7EE74D73, 0xB1D510BD), BN_DEF(0x5DED7EA1, 0xF9AB4819), BN_DEF(0x0846851D, 0x64F31CC5), BN_DEF(0xA0255DC1, 0x4597E899), BN_DEF(0x74AB6A36, 0xDF310EE0), BN_DEF(0x3F44F82D, 0x6D2A13F8), BN_DEF(0xB3A278A6, 0x062B3CF5), BN_DEF(0xED5BDD3A, 0x79683303), BN_DEF(0xA2C087E8, 0xFA9D4B7F), BN_DEF(0x2F8385DD, 0x4BCBC886), BN_DEF(0x6CEA306B, 0x3473FC64), BN_DEF(0x1A23F0C7, 0x13EB57A8), BN_DEF(0xA4037C07, 0x22222E04), BN_DEF(0xFC848AD9, 0xE3FDB8BE), BN_DEF(0xE39D652D, 0x238F16CB), BN_DEF(0x2BF1C978, 0x3423B474), BN_DEF(0x5AE4F568, 0x3AAB639C), BN_DEF(0x6BA42466, 0x2576F693), BN_DEF(0x8AFC47ED, 0x741FA7BF), BN_DEF(0x8D9DD300, 0x3BC832B6), BN_DEF(0x73B931BA, 0xD8BEC4D0), BN_DEF(0xA932DF8C, 0x38777CB6), BN_DEF(0x12FEE5E4, 0x74A3926F), BN_DEF(0x6DBE1159, 0xE694F91E), BN_DEF(0x0B7474D6, 0x12BF2D5B), BN_DEF(0x3F4860EE, 0x043E8F66), BN_DEF(0x6E3C0468, 0x387FE8D7), BN_DEF(0x2EF29632, 0xDA56C9EC), BN_DEF(0xA313D55C, 0xEB19CCB1), BN_DEF(0x8A1FBFF0, 0xF550AA3D), BN_DEF(0xB7C5DA76, 0x06A1D58B), BN_DEF(0xF29BE328, 0xA79715EE), BN_DEF(0x0F8037E0, 0x14CC5ED2), BN_DEF(0xBF48E1D8, 0xCC8F6D7E), BN_DEF(0x2B4154AA, 0x4BD407B2), BN_DEF(0xFF585AC5, 0x0F1D45B7), BN_DEF(0x36CC88BE, 0x23A97A7E), BN_DEF(0xBEC7E8F3, 0x59E7C97F), BN_DEF(0x900B1C9E, 0xB5A84031), BN_DEF(0x46980C82, 0xD55E702F), BN_DEF(0x6E74FEF6, 0xF482D7CE), BN_DEF(0xD1721D03, 0xF032EA15), BN_DEF(0xC64B92EC, 0x5983CA01), BN_DEF(0x378CD2BF, 0x6FB8F401), BN_DEF(0x2BD7AF42, 0x33205151), BN_DEF(0xE6CC254B, 0xDB7F1447), BN_DEF(0xCED4BB1B, 0x44CE6CBA), BN_DEF(0xCF9B14ED, 0xDA3EDBEB), BN_DEF(0x865A8918, 0x179727B0), BN_DEF(0x9027D831, 0xB06A53ED), BN_DEF(0x413001AE, 0xE5DB382F), BN_DEF(0xAD9E530E, 0xF8FF9406), BN_DEF(0x3DBA37BD, 0xC9751E76), BN_DEF(0x602646DE, 0xC1D4DCB2), BN_DEF(0xD27C7026, 0x36C3FAB4), BN_DEF(0x34028492, 0x4DF435C9), BN_DEF(0x90A6C08F, 0x86FFB7DC), BN_DEF(0x8D8FDDC1, 0x93B4EA98), BN_DEF(0xD5B05AA9, 0xD0069127), BN_DEF(0x2170481C, 0xB81BDD76), BN_DEF(0xCEE2D7AF, 0x1F612970), BN_DEF(0x515BE7ED, 0x233BA186), BN_DEF(0xA090C3A2, 0x99B2964F), BN_DEF(0x4E6BC05D, 0x287C5947), BN_DEF(0x1FBECAA6, 0x2E8EFC14), BN_DEF(0x04DE8EF9, 0xDBBBC2DB), BN_DEF(0x2AD44CE8, 0x2583E9CA), BN_DEF(0xB6150BDA, 0x1A946834), BN_DEF(0x6AF4E23C, 0x99C32718), BN_DEF(0xBDBA5B26, 0x88719A10), BN_DEF(0xA787E6D7, 0x1A723C12), BN_DEF(0xA9210801, 0x4B82D120), BN_DEF(0xE0FD108E, 0x43DB5BFC), BN_DEF(0x74E5AB31, 0x08E24FA0), BN_DEF(0xBAD946E2, 0x770988C0), BN_DEF(0x7A615D6C, 0xBBE11757), BN_DEF(0x177B200C, 0x521F2B18), BN_DEF(0x3EC86A64, 0xD8760273), BN_DEF(0xD98A0864, 0xF12FFA06), BN_DEF(0x1AD2EE6B, 0xCEE3D226), BN_DEF(0x4A25619D, 0x1E8C94E0), BN_DEF(0xDB0933D7, 0xABF5AE8C), BN_DEF(0xA6E1E4C7, 0xB3970F85), BN_DEF(0x5D060C7D, 0x8AEA7157), BN_DEF(0x58DBEF0A, 0xECFB8504), BN_DEF(0xDF1CBA64, 0xA85521AB), BN_DEF(0x04507A33, 0xAD33170D), BN_DEF(0x8AAAC42D, 0x15728E5A), BN_DEF(0x98FA0510, 0x15D22618), BN_DEF(0xEA956AE5, 0x3995497C), BN_DEF(0x95581718, 0xDE2BCBF6), BN_DEF(0x6F4C52C9, 0xB5C55DF0), BN_DEF(0xEC07A28F, 0x9B2783A2), BN_DEF(0x180E8603, 0xE39E772C), BN_DEF(0x2E36CE3B, 0x32905E46), BN_DEF(0xCA18217C, 0xF1746C08), BN_DEF(0x4ABC9804, 0x670C354E), BN_DEF(0x7096966D, 0x9ED52907), BN_DEF(0x208552BB, 0x1C62F356), BN_DEF(0xDCA3AD96, 0x83655D23), BN_DEF(0xFD24CF5F, 0x69163FA8), BN_DEF(0x1C55D39A, 0x98DA4836), BN_DEF(0xA163BF05, 0xC2007CB8), BN_DEF(0xECE45B3D, 0x49286651), BN_DEF(0x7C4B1FE6, 0xAE9F2411), BN_DEF(0x5A899FA5, 0xEE386BFB), BN_DEF(0xF406B7ED, 0x0BFF5CB6), BN_DEF(0xA637ED6B, 0xF44C42E9), BN_DEF(0x625E7EC6, 0xE485B576), BN_DEF(0x6D51C245, 0x4FE1356D), BN_DEF(0xF25F1437, 0x302B0A6D), BN_DEF(0xCD3A431B, 0xEF9519B3), BN_DEF(0x8E3404DD, 0x514A0879), BN_DEF(0x3B139B22, 0x020BBEA6), BN_DEF(0x8A67CC74, 0x29024E08), BN_DEF(0x80DC1CD1, 0xC4C6628B), BN_DEF(0x2168C234, 0xC90FDAA2), BN_DEF(0xFFFFFFFF, 0xFFFFFFFF) }; /* q = (p - 1) / 2 */ static const BN_ULONG modp_8192_q[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0xCC76E9EF, 0xB064C06E), BN_DEF(0x405CB738, 0xE40FAB74), BN_DEF(0x3B2B4A6F, 0x4F182871), BN_DEF(0xAB3BF4D5, 0xCAAC7223), BN_DEF(0x7E013723, 0xE48C86D3), BN_DEF(0x6AF71C15, 0xC44D0017), BN_DEF(0xA40E366B, 0x2004A1C5), BN_DEF(0x75C3CFC9, 0x1AC8237A), BN_DEF(0x8F67D134, 0xFD79B5E1), BN_DEF(0xBF73A6B9, 0xD8EA885E), BN_DEF(0xAEF6BF50, 0xFCD5A40C), BN_DEF(0x8423428E, 0xB2798E62), BN_DEF(0xD012AEE0, 0x22CBF44C), BN_DEF(0x3A55B51B, 0xEF988770), BN_DEF(0x1FA27C16, 0x369509FC), BN_DEF(0xD9D13C53, 0x03159E7A), BN_DEF(0xF6ADEE9D, 0x3CB41981), BN_DEF(0xD16043F4, 0xFD4EA5BF), BN_DEF(0x17C1C2EE, 0xA5E5E443), BN_DEF(0x36751835, 0x9A39FE32), BN_DEF(0x0D11F863, 0x89F5ABD4), BN_DEF(0x5201BE03, 0x91111702), BN_DEF(0x7E42456C, 0xF1FEDC5F), BN_DEF(0xF1CEB296, 0x11C78B65), BN_DEF(0x15F8E4BC, 0x1A11DA3A), BN_DEF(0x2D727AB4, 0x1D55B1CE), BN_DEF(0xB5D21233, 0x92BB7B49), BN_DEF(0xC57E23F6, 0x3A0FD3DF), BN_DEF(0x46CEE980, 0x1DE4195B), BN_DEF(0x39DC98DD, 0x6C5F6268), BN_DEF(0x54996FC6, 0x1C3BBE5B), BN_DEF(0x897F72F2, 0xBA51C937), BN_DEF(0x36DF08AC, 0x734A7C8F), BN_DEF(0x85BA3A6B, 0x095F96AD), BN_DEF(0x1FA43077, 0x021F47B3), BN_DEF(0xB71E0234, 0x1C3FF46B), BN_DEF(0x17794B19, 0x6D2B64F6), BN_DEF(0xD189EAAE, 0x758CE658), BN_DEF(0xC50FDFF8, 0x7AA8551E), BN_DEF(0xDBE2ED3B, 0x0350EAC5), BN_DEF(0x794DF194, 0x53CB8AF7), BN_DEF(0x07C01BF0, 0x0A662F69), BN_DEF(0x5FA470EC, 0x6647B6BF), BN_DEF(0x15A0AA55, 0xA5EA03D9), BN_DEF(0xFFAC2D62, 0x078EA2DB), BN_DEF(0x1B66445F, 0x91D4BD3F), BN_DEF(0xDF63F479, 0x2CF3E4BF), BN_DEF(0xC8058E4F, 0x5AD42018), BN_DEF(0xA34C0641, 0x6AAF3817), BN_DEF(0x373A7F7B, 0xFA416BE7), BN_DEF(0xE8B90E81, 0x7819750A), BN_DEF(0xE325C976, 0xACC1E500), BN_DEF(0x9BC6695F, 0x37DC7A00), BN_DEF(0x95EBD7A1, 0x999028A8), BN_DEF(0xF36612A5, 0xEDBF8A23), BN_DEF(0x676A5D8D, 0xA267365D), BN_DEF(0xE7CD8A76, 0x6D1F6DF5), BN_DEF(0x432D448C, 0x8BCB93D8), BN_DEF(0xC813EC18, 0x583529F6), BN_DEF(0xA09800D7, 0x72ED9C17), BN_DEF(0x56CF2987, 0xFC7FCA03), BN_DEF(0x1EDD1BDE, 0x64BA8F3B), BN_DEF(0x3013236F, 0x60EA6E59), BN_DEF(0x693E3813, 0x1B61FD5A), BN_DEF(0x9A014249, 0xA6FA1AE4), BN_DEF(0x48536047, 0xC37FDBEE), BN_DEF(0x46C7EEE0, 0xC9DA754C), BN_DEF(0xEAD82D54, 0x68034893), BN_DEF(0x10B8240E, 0xDC0DEEBB), BN_DEF(0x67716BD7, 0x8FB094B8), BN_DEF(0x28ADF3F6, 0x119DD0C3), BN_DEF(0xD04861D1, 0xCCD94B27), BN_DEF(0xA735E02E, 0x143E2CA3), BN_DEF(0x0FDF6553, 0x97477E0A), BN_DEF(0x826F477C, 0x6DDDE16D), BN_DEF(0x156A2674, 0x12C1F4E5), BN_DEF(0x5B0A85ED, 0x0D4A341A), BN_DEF(0x357A711E, 0x4CE1938C), BN_DEF(0x5EDD2D93, 0xC438CD08), BN_DEF(0x53C3F36B, 0x8D391E09), BN_DEF(0x54908400, 0x25C16890), BN_DEF(0x707E8847, 0xA1EDADFE), BN_DEF(0x3A72D598, 0x047127D0), BN_DEF(0x5D6CA371, 0x3B84C460), BN_DEF(0xBD30AEB6, 0x5DF08BAB), BN_DEF(0x0BBD9006, 0x290F958C), BN_DEF(0x9F643532, 0x6C3B0139), BN_DEF(0x6CC50432, 0xF897FD03), BN_DEF(0x0D697735, 0xE771E913), BN_DEF(0x2512B0CE, 0x8F464A70), BN_DEF(0x6D8499EB, 0xD5FAD746), BN_DEF(0xD370F263, 0xD9CB87C2), BN_DEF(0xAE83063E, 0x457538AB), BN_DEF(0x2C6DF785, 0x767DC282), BN_DEF(0xEF8E5D32, 0xD42A90D5), BN_DEF(0x82283D19, 0xD6998B86), BN_DEF(0x45556216, 0x0AB9472D), BN_DEF(0x4C7D0288, 0x8AE9130C), BN_DEF(0x754AB572, 0x1CCAA4BE), BN_DEF(0x4AAC0B8C, 0xEF15E5FB), BN_DEF(0x37A62964, 0xDAE2AEF8), BN_DEF(0x7603D147, 0xCD93C1D1), BN_DEF(0x0C074301, 0xF1CF3B96), BN_DEF(0x171B671D, 0x19482F23), BN_DEF(0x650C10BE, 0x78BA3604), BN_DEF(0x255E4C02, 0xB3861AA7), BN_DEF(0xB84B4B36, 0xCF6A9483), BN_DEF(0x1042A95D, 0x0E3179AB), BN_DEF(0xEE51D6CB, 0xC1B2AE91), BN_DEF(0x7E9267AF, 0x348B1FD4), BN_DEF(0x0E2AE9CD, 0xCC6D241B), BN_DEF(0x50B1DF82, 0xE1003E5C), BN_DEF(0xF6722D9E, 0x24943328), BN_DEF(0xBE258FF3, 0xD74F9208), BN_DEF(0xAD44CFD2, 0xF71C35FD), BN_DEF(0x7A035BF6, 0x85FFAE5B), BN_DEF(0xD31BF6B5, 0x7A262174), BN_DEF(0x312F3F63, 0xF242DABB), BN_DEF(0xB6A8E122, 0xA7F09AB6), BN_DEF(0xF92F8A1B, 0x98158536), BN_DEF(0xE69D218D, 0xF7CA8CD9), BN_DEF(0xC71A026E, 0x28A5043C), BN_DEF(0x1D89CD91, 0x0105DF53), BN_DEF(0x4533E63A, 0x94812704), BN_DEF(0xC06E0E68, 0x62633145), BN_DEF(0x10B4611A, 0xE487ED51), BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), }; /* DH parameters from RFC5114 */ static const BN_ULONG dh1024_160_p[] = { BN_DEF(0x2E4A4371, 0xDF1FB2BC), BN_DEF(0x6D4DA708, 0xE68CFDA7), BN_DEF(0x365C1A65, 0x45BF37DF), BN_DEF(0x0DC8B4BD, 0xA151AF5F), BN_DEF(0xF55BCCC0, 0xFAA31A4F), BN_DEF(0xE5644738, 0x4EFFD6FA), BN_DEF(0x219A7372, 0x98488E9C), BN_DEF(0x90C4BD70, 0xACCBDD7D), BN_DEF(0xD49B83BF, 0x24975C3C), BN_DEF(0xA9061123, 0x13ECB4AE), BN_DEF(0x2EE652C0, 0x9838EF1E), BN_DEF(0x75A23D18, 0x6073E286), BN_DEF(0x52D23B61, 0x9A6A9DCA), BN_DEF(0xFB06A3C6, 0x52C99FBC), BN_DEF(0xAE5D54EC, 0xDE92DE5E), BN_DEF(0xA080E01D, 0xB10B8F96) }; static const BN_ULONG dh1024_160_q[] = { BN_DEF(0x49462353, 0x64B7CB9D), BN_DEF(0x8ABA4E7D, 0x81A8DF27), (BN_ULONG)0xF518AA87 }; static const BN_ULONG dh1024_160_g[] = { BN_DEF(0x22B3B2E5, 0x855E6EEB), BN_DEF(0xF97C2A24, 0x858F4DCE), BN_DEF(0x18D08BC8, 0x2D779D59), BN_DEF(0x8E73AFA3, 0xD662A4D1), BN_DEF(0x69B6A28A, 0x1DBF0A01), BN_DEF(0x7A091F53, 0xA6A24C08), BN_DEF(0x63F80A76, 0x909D0D22), BN_DEF(0xB9A92EE1, 0xD7FBD7D3), BN_DEF(0x9E2749F4, 0x5E91547F), BN_DEF(0xB01B886A, 0x160217B4), BN_DEF(0x5504F213, 0x777E690F), BN_DEF(0x5C41564B, 0x266FEA1E), BN_DEF(0x14266D31, 0xD6406CFF), BN_DEF(0x58AC507F, 0xF8104DD2), BN_DEF(0xEFB99905, 0x6765A442), BN_DEF(0xC3FD3412, 0xA4D1CBD5) }; static const BN_ULONG dh2048_224_p[] = { BN_DEF(0x0C10E64F, 0x0AC4DFFE), BN_DEF(0x4E71B81C, 0xCF9DE538), BN_DEF(0xFFA31F71, 0x7EF363E2), BN_DEF(0x6B8E75B9, 0xE3FB73C1), BN_DEF(0x4BA80A29, 0xC9B53DCF), BN_DEF(0x16E79763, 0x23F10B0E), BN_DEF(0x13042E9B, 0xC52172E4), BN_DEF(0xC928B2B9, 0xBE60E69C), BN_DEF(0xB9E587E8, 0x80CD86A1), BN_DEF(0x98C641A4, 0x315D75E1), BN_DEF(0x44328387, 0xCDF93ACC), BN_DEF(0xDC0A486D, 0x15987D9A), BN_DEF(0x1FD5A074, 0x7310F712), BN_DEF(0xDE31EFDC, 0x278273C7), BN_DEF(0x415D9330, 0x1602E714), BN_DEF(0xBC8985DB, 0x81286130), BN_DEF(0x70918836, 0xB3BF8A31), BN_DEF(0xB9C49708, 0x6A00E0A0), BN_DEF(0x8BBC27BE, 0xC6BA0B2C), BN_DEF(0xED34DBF6, 0xC9F98D11), BN_DEF(0xB6C12207, 0x7AD5B7D0), BN_DEF(0x55B7394B, 0xD91E8FEF), BN_DEF(0xEFDA4DF8, 0x9037C9ED), BN_DEF(0xAD6AC212, 0x6D3F8152), BN_DEF(0x1274A0A6, 0x1DE6B85A), BN_DEF(0x309C180E, 0xEB3D688A), BN_DEF(0x7BA1DF15, 0xAF9A3C40), BN_DEF(0xF95A56DB, 0xE6FA141D), BN_DEF(0xB61D0A75, 0xB54B1597), BN_DEF(0x683B9FD1, 0xA20D64E5), BN_DEF(0x9559C51F, 0xD660FAA7), BN_DEF(0x9123A9D0, 0xAD107E1E) }; static const BN_ULONG dh2048_224_q[] = { BN_DEF(0xB36371EB, 0xBF389A99), BN_DEF(0x4738CEBC, 0x1F80535A), BN_DEF(0x99717710, 0xC58D93FE), (BN_ULONG)0x801C0D34 }; static const BN_ULONG dh2048_224_g[] = { BN_DEF(0x191F2BFA, 0x84B890D3), BN_DEF(0x2A7065B3, 0x81BC087F), BN_DEF(0xF6EC0179, 0x19C418E1), BN_DEF(0x71CFFF4C, 0x7B5A0F1C), BN_DEF(0x9B6AA4BD, 0xEDFE72FE), BN_DEF(0x94B30269, 0x81E1BCFE), BN_DEF(0x8D6C0191, 0x566AFBB4), BN_DEF(0x409D13CD, 0xB539CCE3), BN_DEF(0x5F2FF381, 0x6AA21E7F), BN_DEF(0x770589EF, 0xD9E263E4), BN_DEF(0xD19963DD, 0x10E183ED), BN_DEF(0x150B8EEB, 0xB70A8137), BN_DEF(0x28C8F8AC, 0x051AE3D4), BN_DEF(0x0C1AB15B, 0xBB77A86F), BN_DEF(0x16A330EF, 0x6E3025E3), BN_DEF(0xD6F83456, 0x19529A45), BN_DEF(0x118E98D1, 0xF180EB34), BN_DEF(0x50717CBE, 0xB5F6C6B2), BN_DEF(0xDA7460CD, 0x09939D54), BN_DEF(0x22EA1ED4, 0xE2471504), BN_DEF(0x521BC98A, 0xB8A762D0), BN_DEF(0x5AC1348B, 0xF4D02727), BN_DEF(0x1999024A, 0xC1766910), BN_DEF(0xA8D66AD7, 0xBE5E9001), BN_DEF(0x620A8652, 0xC57DB17C), BN_DEF(0x00C29F52, 0xAB739D77), BN_DEF(0xA70C4AFA, 0xDD921F01), BN_DEF(0x10B9A6F0, 0xA6824A4E), BN_DEF(0xCFE4FFE3, 0x74866A08), BN_DEF(0x89998CAF, 0x6CDEBE7B), BN_DEF(0x8FFDAC50, 0x9DF30B5C), BN_DEF(0x4F2D9AE3, 0xAC4032EF) }; static const BN_ULONG dh2048_256_p[] = { BN_DEF(0x1E1A1597, 0xDB094AE9), BN_DEF(0xD7EF09CA, 0x693877FA), BN_DEF(0x6E11715F, 0x6116D227), BN_DEF(0xC198AF12, 0xA4B54330), BN_DEF(0xD7014103, 0x75F26375), BN_DEF(0x54E710C3, 0xC3A3960A), BN_DEF(0xBD0BE621, 0xDED4010A), BN_DEF(0x89962856, 0xC0B857F6), BN_DEF(0x71506026, 0xB3CA3F79), BN_DEF(0xE6B486F6, 0x1CCACB83), BN_DEF(0x14056425, 0x67E144E5), BN_DEF(0xA41825D9, 0xF6A167B5), BN_DEF(0x96524D8E, 0x3AD83477), BN_DEF(0x51BFA4AB, 0xF13C6D9A), BN_DEF(0x35488A0E, 0x2D525267), BN_DEF(0xCAA6B790, 0xB63ACAE1), BN_DEF(0x81B23F76, 0x4FDB70C5), BN_DEF(0x12307F5C, 0xBC39A0BF), BN_DEF(0xB1E59BB8, 0xB941F54E), BN_DEF(0xD45F9088, 0x6C5BFC11), BN_DEF(0x4275BF7B, 0x22E0B1EF), BN_DEF(0x5B4758C0, 0x91F9E672), BN_DEF(0x6BCF67ED, 0x5A8A9D30), BN_DEF(0x97517ABD, 0x209E0C64), BN_DEF(0x830E9A7C, 0x3BF4296D), BN_DEF(0x34096FAA, 0x16C3D911), BN_DEF(0x61B2AA30, 0xFAF7DF45), BN_DEF(0xD61957D4, 0xE00DF8F1), BN_DEF(0x435E3B00, 0x5D2CEED4), BN_DEF(0x660DD0F2, 0x8CEEF608), BN_DEF(0x65195999, 0xFFBBD19C), BN_DEF(0xB4B6663C, 0x87A8E61D) }; static const BN_ULONG dh2048_256_q[] = { BN_DEF(0x64F5FBD3, 0xA308B0FE), BN_DEF(0x1EB3750B, 0x99B1A47D), BN_DEF(0x40129DA2, 0xB4479976), BN_DEF(0xA709A097, 0x8CF83642) }; static const BN_ULONG dh2048_256_g[] = { BN_DEF(0x6CC41659, 0x664B4C0F), BN_DEF(0xEF98C582, 0x5E2327CF), BN_DEF(0xD4795451, 0xD647D148), BN_DEF(0x90F00EF8, 0x2F630784), BN_DEF(0x1DB246C3, 0x184B523D), BN_DEF(0xCDC67EB6, 0xC7891428), BN_DEF(0x0DF92B52, 0x7FD02837), BN_DEF(0x64E0EC37, 0xB3353BBB), BN_DEF(0x57CD0915, 0xECD06E15), BN_DEF(0xDF016199, 0xB7D2BBD2), BN_DEF(0x052588B9, 0xC8484B1E), BN_DEF(0x13D3FE14, 0xDB2A3B73), BN_DEF(0xD182EA0A, 0xD052B985), BN_DEF(0xE83B9C80, 0xA4BD1BFF), BN_DEF(0xFB3F2E55, 0xDFC967C1), BN_DEF(0x767164E1, 0xB5045AF2), BN_DEF(0x6F2F9193, 0x1D14348F), BN_DEF(0x428EBC83, 0x64E67982), BN_DEF(0x82D6ED38, 0x8AC376D2), BN_DEF(0xAAB8A862, 0x777DE62A), BN_DEF(0xE9EC144B, 0xDDF463E5), BN_DEF(0xC77A57F2, 0x0196F931), BN_DEF(0x41000A65, 0xA55AE313), BN_DEF(0xC28CBB18, 0x901228F8), BN_DEF(0x7E8C6F62, 0xBC3773BF), BN_DEF(0x0C6B47B1, 0xBE3A6C1B), BN_DEF(0xAC0BB555, 0xFF4FED4A), BN_DEF(0x77BE463F, 0x10DBC150), BN_DEF(0x1A0BA125, 0x07F4793A), BN_DEF(0x21EF2054, 0x4CA7B18F), BN_DEF(0x60EDBD48, 0x2E775066), BN_DEF(0x73134D0B, 0x3FB32C9B) }; /* Primes from RFC 7919 */ static const BN_ULONG ffdhe2048_p[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0x61285C97, 0x886B4238), BN_DEF(0xC1B2EFFA, 0xC6F34A26), BN_DEF(0x7D1683B2, 0xC58EF183), BN_DEF(0x2EC22005, 0x3BB5FCBC), BN_DEF(0x4C6FAD73, 0xC3FE3B1B), BN_DEF(0xEEF28183, 0x8E4F1232), BN_DEF(0xE98583FF, 0x9172FE9C), BN_DEF(0x28342F61, 0xC03404CD), BN_DEF(0xCDF7E2EC, 0x9E02FCE1), BN_DEF(0xEE0A6D70, 0x0B07A7C8), BN_DEF(0x6372BB19, 0xAE56EDE7), BN_DEF(0xDE394DF4, 0x1D4F42A3), BN_DEF(0x60D7F468, 0xB96ADAB7), BN_DEF(0xB2C8E3FB, 0xD108A94B), BN_DEF(0xB324FB61, 0xBC0AB182), BN_DEF(0x483A797A, 0x30ACCA4F), BN_DEF(0x36ADE735, 0x1DF158A1), BN_DEF(0xF3EFE872, 0xE2A689DA), BN_DEF(0xE0E68B77, 0x984F0C70), BN_DEF(0x7F57C935, 0xB557135E), BN_DEF(0x3DED1AF3, 0x85636555), BN_DEF(0x5F066ED0, 0x2433F51F), BN_DEF(0xD5FD6561, 0xD3DF1ED5), BN_DEF(0xAEC4617A, 0xF681B202), BN_DEF(0x630C75D8, 0x7D2FE363), BN_DEF(0x249B3EF9, 0xCC939DCE), BN_DEF(0x146433FB, 0xA9E13641), BN_DEF(0xCE2D3695, 0xD8B9C583), BN_DEF(0x273D3CF1, 0xAFDC5620), BN_DEF(0xA2BB4A9A, 0xADF85458), BN_DEF(0xFFFFFFFF, 0xFFFFFFFF) }; /* q = (p - 1) / 2 */ static const BN_ULONG ffdhe2048_q[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0x30942E4B, 0x4435A11C), BN_DEF(0x60D977FD, 0x6379A513), BN_DEF(0xBE8B41D9, 0xE2C778C1), BN_DEF(0x17611002, 0x9DDAFE5E), BN_DEF(0xA637D6B9, 0xE1FF1D8D), BN_DEF(0x777940C1, 0xC7278919), BN_DEF(0x74C2C1FF, 0xC8B97F4E), BN_DEF(0x941A17B0, 0x601A0266), BN_DEF(0xE6FBF176, 0x4F017E70), BN_DEF(0x770536B8, 0x8583D3E4), BN_DEF(0xB1B95D8C, 0x572B76F3), BN_DEF(0xEF1CA6FA, 0x0EA7A151), BN_DEF(0xB06BFA34, 0xDCB56D5B), BN_DEF(0xD96471FD, 0xE88454A5), BN_DEF(0x59927DB0, 0x5E0558C1), BN_DEF(0xA41D3CBD, 0x98566527), BN_DEF(0x9B56F39A, 0x0EF8AC50), BN_DEF(0x79F7F439, 0xF15344ED), BN_DEF(0x707345BB, 0xCC278638), BN_DEF(0x3FABE49A, 0xDAAB89AF), BN_DEF(0x9EF68D79, 0x42B1B2AA), BN_DEF(0xAF833768, 0x9219FA8F), BN_DEF(0xEAFEB2B0, 0x69EF8F6A), BN_DEF(0x576230BD, 0x7B40D901), BN_DEF(0xB1863AEC, 0xBE97F1B1), BN_DEF(0x124D9F7C, 0xE649CEE7), BN_DEF(0x8A3219FD, 0xD4F09B20), BN_DEF(0xE7169B4A, 0xEC5CE2C1), BN_DEF(0x139E9E78, 0x57EE2B10), BN_DEF(0x515DA54D, 0xD6FC2A2C), BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), }; static const BN_ULONG ffdhe3072_p[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0x66C62E37, 0x25E41D2B), BN_DEF(0x3FD59D7C, 0x3C1B20EE), BN_DEF(0xFA53DDEF, 0x0ABCD06B), BN_DEF(0xD5C4484E, 0x1DBF9A42), BN_DEF(0x9B0DEADA, 0xABC52197), BN_DEF(0x22363A0D, 0xE86D2BC5), BN_DEF(0x9C9DF69E, 0x5CAE82AB), BN_DEF(0x71F54BFF, 0x64F2E21E), BN_DEF(0xE2D74DD3, 0xF4FD4452), BN_DEF(0xBC437944, 0xB4130C93), BN_DEF(0x85139270, 0xAEFE1309), BN_DEF(0xC186D91C, 0x598CB0FA), BN_DEF(0x91F7F7EE, 0x7AD91D26), BN_DEF(0xD6E6C907, 0x61B46FC9), BN_DEF(0xF99C0238, 0xBC34F4DE), BN_DEF(0x6519035B, 0xDE355B3B), BN_DEF(0x611FCFDC, 0x886B4238), BN_DEF(0xC1B2EFFA, 0xC6F34A26), BN_DEF(0x7D1683B2, 0xC58EF183), BN_DEF(0x2EC22005, 0x3BB5FCBC), BN_DEF(0x4C6FAD73, 0xC3FE3B1B), BN_DEF(0xEEF28183, 0x8E4F1232), BN_DEF(0xE98583FF, 0x9172FE9C), BN_DEF(0x28342F61, 0xC03404CD), BN_DEF(0xCDF7E2EC, 0x9E02FCE1), BN_DEF(0xEE0A6D70, 0x0B07A7C8), BN_DEF(0x6372BB19, 0xAE56EDE7), BN_DEF(0xDE394DF4, 0x1D4F42A3), BN_DEF(0x60D7F468, 0xB96ADAB7), BN_DEF(0xB2C8E3FB, 0xD108A94B), BN_DEF(0xB324FB61, 0xBC0AB182), BN_DEF(0x483A797A, 0x30ACCA4F), BN_DEF(0x36ADE735, 0x1DF158A1), BN_DEF(0xF3EFE872, 0xE2A689DA), BN_DEF(0xE0E68B77, 0x984F0C70), BN_DEF(0x7F57C935, 0xB557135E), BN_DEF(0x3DED1AF3, 0x85636555), BN_DEF(0x5F066ED0, 0x2433F51F), BN_DEF(0xD5FD6561, 0xD3DF1ED5), BN_DEF(0xAEC4617A, 0xF681B202), BN_DEF(0x630C75D8, 0x7D2FE363), BN_DEF(0x249B3EF9, 0xCC939DCE), BN_DEF(0x146433FB, 0xA9E13641), BN_DEF(0xCE2D3695, 0xD8B9C583), BN_DEF(0x273D3CF1, 0xAFDC5620), BN_DEF(0xA2BB4A9A, 0xADF85458), BN_DEF(0xFFFFFFFF, 0xFFFFFFFF) }; /* q = (p - 1) / 2 */ static const BN_ULONG ffdhe3072_q[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0xB363171B, 0x12F20E95), BN_DEF(0x1FEACEBE, 0x9E0D9077), BN_DEF(0xFD29EEF7, 0x055E6835), BN_DEF(0x6AE22427, 0x0EDFCD21), BN_DEF(0xCD86F56D, 0xD5E290CB), BN_DEF(0x911B1D06, 0x743695E2), BN_DEF(0xCE4EFB4F, 0xAE574155), BN_DEF(0x38FAA5FF, 0xB279710F), BN_DEF(0x716BA6E9, 0x7A7EA229), BN_DEF(0xDE21BCA2, 0x5A098649), BN_DEF(0xC289C938, 0x577F0984), BN_DEF(0x60C36C8E, 0x2CC6587D), BN_DEF(0x48FBFBF7, 0xBD6C8E93), BN_DEF(0xEB736483, 0x30DA37E4), BN_DEF(0x7CCE011C, 0xDE1A7A6F), BN_DEF(0xB28C81AD, 0x6F1AAD9D), BN_DEF(0x308FE7EE, 0x4435A11C), BN_DEF(0x60D977FD, 0x6379A513), BN_DEF(0xBE8B41D9, 0xE2C778C1), BN_DEF(0x17611002, 0x9DDAFE5E), BN_DEF(0xA637D6B9, 0xE1FF1D8D), BN_DEF(0x777940C1, 0xC7278919), BN_DEF(0x74C2C1FF, 0xC8B97F4E), BN_DEF(0x941A17B0, 0x601A0266), BN_DEF(0xE6FBF176, 0x4F017E70), BN_DEF(0x770536B8, 0x8583D3E4), BN_DEF(0xB1B95D8C, 0x572B76F3), BN_DEF(0xEF1CA6FA, 0x0EA7A151), BN_DEF(0xB06BFA34, 0xDCB56D5B), BN_DEF(0xD96471FD, 0xE88454A5), BN_DEF(0x59927DB0, 0x5E0558C1), BN_DEF(0xA41D3CBD, 0x98566527), BN_DEF(0x9B56F39A, 0x0EF8AC50), BN_DEF(0x79F7F439, 0xF15344ED), BN_DEF(0x707345BB, 0xCC278638), BN_DEF(0x3FABE49A, 0xDAAB89AF), BN_DEF(0x9EF68D79, 0x42B1B2AA), BN_DEF(0xAF833768, 0x9219FA8F), BN_DEF(0xEAFEB2B0, 0x69EF8F6A), BN_DEF(0x576230BD, 0x7B40D901), BN_DEF(0xB1863AEC, 0xBE97F1B1), BN_DEF(0x124D9F7C, 0xE649CEE7), BN_DEF(0x8A3219FD, 0xD4F09B20), BN_DEF(0xE7169B4A, 0xEC5CE2C1), BN_DEF(0x139E9E78, 0x57EE2B10), BN_DEF(0x515DA54D, 0xD6FC2A2C), BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), }; static const BN_ULONG ffdhe4096_p[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0x5E655F6A, 0xC68A007E), BN_DEF(0xF44182E1, 0x4DB5A851), BN_DEF(0x7F88A46B, 0x8EC9B55A), BN_DEF(0xCEC97DCF, 0x0A8291CD), BN_DEF(0xF98D0ACC, 0x2A4ECEA9), BN_DEF(0x7140003C, 0x1A1DB93D), BN_DEF(0x33CB8B7A, 0x092999A3), BN_DEF(0x71AD0038, 0x6DC778F9), BN_DEF(0x918130C4, 0xA907600A), BN_DEF(0x2D9E6832, 0xED6A1E01), BN_DEF(0xEFB4318A, 0x7135C886), BN_DEF(0x7E31CC7A, 0x87F55BA5), BN_DEF(0x55034004, 0x7763CF1D), BN_DEF(0xD69F6D18, 0xAC7D5F42), BN_DEF(0xE58857B6, 0x7930E9E4), BN_DEF(0x164DF4FB, 0x6E6F52C3), BN_DEF(0x669E1EF1, 0x25E41D2B), BN_DEF(0x3FD59D7C, 0x3C1B20EE), BN_DEF(0xFA53DDEF, 0x0ABCD06B), BN_DEF(0xD5C4484E, 0x1DBF9A42), BN_DEF(0x9B0DEADA, 0xABC52197), BN_DEF(0x22363A0D, 0xE86D2BC5), BN_DEF(0x9C9DF69E, 0x5CAE82AB), BN_DEF(0x71F54BFF, 0x64F2E21E), BN_DEF(0xE2D74DD3, 0xF4FD4452), BN_DEF(0xBC437944, 0xB4130C93), BN_DEF(0x85139270, 0xAEFE1309), BN_DEF(0xC186D91C, 0x598CB0FA), BN_DEF(0x91F7F7EE, 0x7AD91D26), BN_DEF(0xD6E6C907, 0x61B46FC9), BN_DEF(0xF99C0238, 0xBC34F4DE), BN_DEF(0x6519035B, 0xDE355B3B), BN_DEF(0x611FCFDC, 0x886B4238), BN_DEF(0xC1B2EFFA, 0xC6F34A26), BN_DEF(0x7D1683B2, 0xC58EF183), BN_DEF(0x2EC22005, 0x3BB5FCBC), BN_DEF(0x4C6FAD73, 0xC3FE3B1B), BN_DEF(0xEEF28183, 0x8E4F1232), BN_DEF(0xE98583FF, 0x9172FE9C), BN_DEF(0x28342F61, 0xC03404CD), BN_DEF(0xCDF7E2EC, 0x9E02FCE1), BN_DEF(0xEE0A6D70, 0x0B07A7C8), BN_DEF(0x6372BB19, 0xAE56EDE7), BN_DEF(0xDE394DF4, 0x1D4F42A3), BN_DEF(0x60D7F468, 0xB96ADAB7), BN_DEF(0xB2C8E3FB, 0xD108A94B), BN_DEF(0xB324FB61, 0xBC0AB182), BN_DEF(0x483A797A, 0x30ACCA4F), BN_DEF(0x36ADE735, 0x1DF158A1), BN_DEF(0xF3EFE872, 0xE2A689DA), BN_DEF(0xE0E68B77, 0x984F0C70), BN_DEF(0x7F57C935, 0xB557135E), BN_DEF(0x3DED1AF3, 0x85636555), BN_DEF(0x5F066ED0, 0x2433F51F), BN_DEF(0xD5FD6561, 0xD3DF1ED5), BN_DEF(0xAEC4617A, 0xF681B202), BN_DEF(0x630C75D8, 0x7D2FE363), BN_DEF(0x249B3EF9, 0xCC939DCE), BN_DEF(0x146433FB, 0xA9E13641), BN_DEF(0xCE2D3695, 0xD8B9C583), BN_DEF(0x273D3CF1, 0xAFDC5620), BN_DEF(0xA2BB4A9A, 0xADF85458), BN_DEF(0xFFFFFFFF, 0xFFFFFFFF) }; /* q = (p - 1) / 2 */ static const BN_ULONG ffdhe4096_q[] = { BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), BN_DEF(0x2F32AFB5, 0xE345003F), BN_DEF(0xFA20C170, 0xA6DAD428), BN_DEF(0x3FC45235, 0xC764DAAD), BN_DEF(0xE764BEE7, 0x054148E6), BN_DEF(0xFCC68566, 0x15276754), BN_DEF(0xB8A0001E, 0x0D0EDC9E), BN_DEF(0x99E5C5BD, 0x0494CCD1), BN_DEF(0xB8D6801C, 0x36E3BC7C), BN_DEF(0x48C09862, 0x5483B005), BN_DEF(0x96CF3419, 0x76B50F00), BN_DEF(0x77DA18C5, 0x389AE443), BN_DEF(0xBF18E63D, 0x43FAADD2), BN_DEF(0xAA81A002, 0x3BB1E78E), BN_DEF(0x6B4FB68C, 0x563EAFA1), BN_DEF(0x72C42BDB, 0xBC9874F2), BN_DEF(0x8B26FA7D, 0xB737A961), BN_DEF(0xB34F0F78, 0x12F20E95), BN_DEF(0x1FEACEBE, 0x9E0D9077), BN_DEF(0xFD29EEF7, 0x055E6835), BN_DEF(0x6AE22427, 0x0EDFCD21), BN_DEF(0xCD86F56D, 0xD5E290CB), BN_DEF(0x911B1D06, 0x743695E2), BN_DEF(0xCE4EFB4F, 0xAE574155), BN_DEF(0x38FAA5FF, 0xB279710F), BN_DEF(0x716BA6E9, 0x7A7EA229), BN_DEF(0xDE21BCA2, 0x5A098649), BN_DEF(0xC289C938, 0x577F0984), BN_DEF(0x60C36C8E, 0x2CC6587D), BN_DEF(0x48FBFBF7, 0xBD6C8E93), BN_DEF(0xEB736483, 0x30DA37E4), BN_DEF(0x7CCE011C, 0xDE1A7A6F), BN_DEF(0xB28C81AD, 0x6F1AAD9D), BN_DEF(0x308FE7EE, 0x4435A11C), BN_DEF(0x60D977FD, 0x6379A513), BN_DEF(0xBE8B41D9, 0xE2C778C1), BN_DEF(0x17611002, 0x9DDAFE5E), BN_DEF(0xA637D6B9, 0xE1FF1D8D), BN_DEF(0x777940C1, 0xC7278919), BN_DEF(0x74C2C1FF, 0xC8B97F4E), BN_DEF(0x941A17B0, 0x601A0266), BN_DEF(0xE6FBF176, 0x4F017E70), BN_DEF(0x770536B8, 0x8583D3E4), BN_DEF(0xB1B95D8C, 0x572B76F3), BN_DEF(0xEF1CA6FA, 0x0EA7A151), BN_DEF(0xB06BFA34, 0xDCB56D5B), BN_DEF(0xD96471FD, 0xE88454A5), BN_DEF(0x59927DB0, 0x5E0558C1), BN_DEF(0xA41D3CBD, 0x98566527), BN_DEF(0x9B56F39A, 0x0EF8AC50), BN_DEF(0x79F7F439, 0xF15344ED), BN_DEF(0x707345BB, 0xCC278638), BN_DEF(0x3FABE49A, 0xDAAB89AF), BN_DEF(0x9EF68D79, 0x42B1B2AA), BN_DEF(0xAF833768, 0x9219FA8F), BN_DEF(0xEAFEB2B0, 0x69EF8F6A), BN_DEF(0x576230BD, 0x7B40D901), BN_DEF(0xB1863AEC, 0xBE97F1B1), BN_DEF(0x124D9F7C, 0xE649CEE7), BN_DEF(0x8A3219FD, 0xD4F09B20), BN_DEF(0xE7169B4A, 0xEC5CE2C1), BN_DEF(0x139E9E78, 0x57EE2B10), BN_DEF(0x515DA54D, 0xD6FC2A2C), BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), }; static const BN_ULONG ffdhe6144_p[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0xD0E40E65, 0xA40E329C), BN_DEF(0x7938DAD4, 0xA41D570D), BN_DEF(0xD43161C1, 0x62A69526), BN_DEF(0x9ADB1E69, 0x3FDD4A8E), BN_DEF(0xDC6B80D6, 0x5B3B71F9), BN_DEF(0xC6272B04, 0xEC9D1810), BN_DEF(0xCACEF403, 0x8CCF2DD5), BN_DEF(0xC95B9117, 0xE49F5235), BN_DEF(0xB854338A, 0x505DC82D), BN_DEF(0x1562A846, 0x62292C31), BN_DEF(0x6AE77F5E, 0xD72B0374), BN_DEF(0x462D538C, 0xF9C9091B), BN_DEF(0x47A67CBE, 0x0AE8DB58), BN_DEF(0x22611682, 0xB3A739C1), BN_DEF(0x2A281BF6, 0xEEAAC023), BN_DEF(0x77CAF992, 0x94C6651E), BN_DEF(0x94B2BBC1, 0x763E4E4B), BN_DEF(0x0077D9B4, 0x587E38DA), BN_DEF(0x183023C3, 0x7FB29F8C), BN_DEF(0xF9E3A26E, 0x0ABEC1FF), BN_DEF(0x350511E3, 0xA00EF092), BN_DEF(0xDB6340D8, 0xB855322E), BN_DEF(0xA9A96910, 0xA52471F7), BN_DEF(0x4CFDB477, 0x388147FB), BN_DEF(0x4E46041F, 0x9B1F5C3E), BN_DEF(0xFCCFEC71, 0xCDAD0657), BN_DEF(0x4C701C3A, 0xB38E8C33), BN_DEF(0xB1C0FD4C, 0x917BDD64), BN_DEF(0x9B7624C8, 0x3BB45432), BN_DEF(0xCAF53EA6, 0x23BA4442), BN_DEF(0x38532A3A, 0x4E677D2C), BN_DEF(0x45036C7A, 0x0BFD64B6), BN_DEF(0x5E0DD902, 0xC68A007E), BN_DEF(0xF44182E1, 0x4DB5A851), BN_DEF(0x7F88A46B, 0x8EC9B55A), BN_DEF(0xCEC97DCF, 0x0A8291CD), BN_DEF(0xF98D0ACC, 0x2A4ECEA9), BN_DEF(0x7140003C, 0x1A1DB93D), BN_DEF(0x33CB8B7A, 0x092999A3), BN_DEF(0x71AD0038, 0x6DC778F9), BN_DEF(0x918130C4, 0xA907600A), BN_DEF(0x2D9E6832, 0xED6A1E01), BN_DEF(0xEFB4318A, 0x7135C886), BN_DEF(0x7E31CC7A, 0x87F55BA5), BN_DEF(0x55034004, 0x7763CF1D), BN_DEF(0xD69F6D18, 0xAC7D5F42), BN_DEF(0xE58857B6, 0x7930E9E4), BN_DEF(0x164DF4FB, 0x6E6F52C3), BN_DEF(0x669E1EF1, 0x25E41D2B), BN_DEF(0x3FD59D7C, 0x3C1B20EE), BN_DEF(0xFA53DDEF, 0x0ABCD06B), BN_DEF(0xD5C4484E, 0x1DBF9A42), BN_DEF(0x9B0DEADA, 0xABC52197), BN_DEF(0x22363A0D, 0xE86D2BC5), BN_DEF(0x9C9DF69E, 0x5CAE82AB), BN_DEF(0x71F54BFF, 0x64F2E21E), BN_DEF(0xE2D74DD3, 0xF4FD4452), BN_DEF(0xBC437944, 0xB4130C93), BN_DEF(0x85139270, 0xAEFE1309), BN_DEF(0xC186D91C, 0x598CB0FA), BN_DEF(0x91F7F7EE, 0x7AD91D26), BN_DEF(0xD6E6C907, 0x61B46FC9), BN_DEF(0xF99C0238, 0xBC34F4DE), BN_DEF(0x6519035B, 0xDE355B3B), BN_DEF(0x611FCFDC, 0x886B4238), BN_DEF(0xC1B2EFFA, 0xC6F34A26), BN_DEF(0x7D1683B2, 0xC58EF183), BN_DEF(0x2EC22005, 0x3BB5FCBC), BN_DEF(0x4C6FAD73, 0xC3FE3B1B), BN_DEF(0xEEF28183, 0x8E4F1232), BN_DEF(0xE98583FF, 0x9172FE9C), BN_DEF(0x28342F61, 0xC03404CD), BN_DEF(0xCDF7E2EC, 0x9E02FCE1), BN_DEF(0xEE0A6D70, 0x0B07A7C8), BN_DEF(0x6372BB19, 0xAE56EDE7), BN_DEF(0xDE394DF4, 0x1D4F42A3), BN_DEF(0x60D7F468, 0xB96ADAB7), BN_DEF(0xB2C8E3FB, 0xD108A94B), BN_DEF(0xB324FB61, 0xBC0AB182), BN_DEF(0x483A797A, 0x30ACCA4F), BN_DEF(0x36ADE735, 0x1DF158A1), BN_DEF(0xF3EFE872, 0xE2A689DA), BN_DEF(0xE0E68B77, 0x984F0C70), BN_DEF(0x7F57C935, 0xB557135E), BN_DEF(0x3DED1AF3, 0x85636555), BN_DEF(0x5F066ED0, 0x2433F51F), BN_DEF(0xD5FD6561, 0xD3DF1ED5), BN_DEF(0xAEC4617A, 0xF681B202), BN_DEF(0x630C75D8, 0x7D2FE363), BN_DEF(0x249B3EF9, 0xCC939DCE), BN_DEF(0x146433FB, 0xA9E13641), BN_DEF(0xCE2D3695, 0xD8B9C583), BN_DEF(0x273D3CF1, 0xAFDC5620), BN_DEF(0xA2BB4A9A, 0xADF85458), BN_DEF(0xFFFFFFFF, 0xFFFFFFFF) }; /* q = (p - 1) / 2 */ static const BN_ULONG ffdhe6144_q[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0x68720732, 0x5207194E), BN_DEF(0xBC9C6D6A, 0xD20EAB86), BN_DEF(0x6A18B0E0, 0xB1534A93), BN_DEF(0x4D6D8F34, 0x1FEEA547), BN_DEF(0xEE35C06B, 0x2D9DB8FC), BN_DEF(0x63139582, 0xF64E8C08), BN_DEF(0xE5677A01, 0xC66796EA), BN_DEF(0xE4ADC88B, 0x724FA91A), BN_DEF(0xDC2A19C5, 0x282EE416), BN_DEF(0x8AB15423, 0x31149618), BN_DEF(0x3573BFAF, 0x6B9581BA), BN_DEF(0xA316A9C6, 0x7CE4848D), BN_DEF(0x23D33E5F, 0x05746DAC), BN_DEF(0x91308B41, 0x59D39CE0), BN_DEF(0x95140DFB, 0x77556011), BN_DEF(0x3BE57CC9, 0xCA63328F), BN_DEF(0xCA595DE0, 0x3B1F2725), BN_DEF(0x003BECDA, 0xAC3F1C6D), BN_DEF(0x0C1811E1, 0x3FD94FC6), BN_DEF(0xFCF1D137, 0x855F60FF), BN_DEF(0x1A8288F1, 0x50077849), BN_DEF(0x6DB1A06C, 0x5C2A9917), BN_DEF(0xD4D4B488, 0xD29238FB), BN_DEF(0xA67EDA3B, 0x9C40A3FD), BN_DEF(0x2723020F, 0xCD8FAE1F), BN_DEF(0xFE67F638, 0x66D6832B), BN_DEF(0xA6380E1D, 0x59C74619), BN_DEF(0x58E07EA6, 0x48BDEEB2), BN_DEF(0x4DBB1264, 0x1DDA2A19), BN_DEF(0x657A9F53, 0x11DD2221), BN_DEF(0x1C29951D, 0x2733BE96), BN_DEF(0x2281B63D, 0x05FEB25B), BN_DEF(0x2F06EC81, 0xE345003F), BN_DEF(0xFA20C170, 0xA6DAD428), BN_DEF(0x3FC45235, 0xC764DAAD), BN_DEF(0xE764BEE7, 0x054148E6), BN_DEF(0xFCC68566, 0x15276754), BN_DEF(0xB8A0001E, 0x0D0EDC9E), BN_DEF(0x99E5C5BD, 0x0494CCD1), BN_DEF(0xB8D6801C, 0x36E3BC7C), BN_DEF(0x48C09862, 0x5483B005), BN_DEF(0x96CF3419, 0x76B50F00), BN_DEF(0x77DA18C5, 0x389AE443), BN_DEF(0xBF18E63D, 0x43FAADD2), BN_DEF(0xAA81A002, 0x3BB1E78E), BN_DEF(0x6B4FB68C, 0x563EAFA1), BN_DEF(0x72C42BDB, 0xBC9874F2), BN_DEF(0x8B26FA7D, 0xB737A961), BN_DEF(0xB34F0F78, 0x12F20E95), BN_DEF(0x1FEACEBE, 0x9E0D9077), BN_DEF(0xFD29EEF7, 0x055E6835), BN_DEF(0x6AE22427, 0x0EDFCD21), BN_DEF(0xCD86F56D, 0xD5E290CB), BN_DEF(0x911B1D06, 0x743695E2), BN_DEF(0xCE4EFB4F, 0xAE574155), BN_DEF(0x38FAA5FF, 0xB279710F), BN_DEF(0x716BA6E9, 0x7A7EA229), BN_DEF(0xDE21BCA2, 0x5A098649), BN_DEF(0xC289C938, 0x577F0984), BN_DEF(0x60C36C8E, 0x2CC6587D), BN_DEF(0x48FBFBF7, 0xBD6C8E93), BN_DEF(0xEB736483, 0x30DA37E4), BN_DEF(0x7CCE011C, 0xDE1A7A6F), BN_DEF(0xB28C81AD, 0x6F1AAD9D), BN_DEF(0x308FE7EE, 0x4435A11C), BN_DEF(0x60D977FD, 0x6379A513), BN_DEF(0xBE8B41D9, 0xE2C778C1), BN_DEF(0x17611002, 0x9DDAFE5E), BN_DEF(0xA637D6B9, 0xE1FF1D8D), BN_DEF(0x777940C1, 0xC7278919), BN_DEF(0x74C2C1FF, 0xC8B97F4E), BN_DEF(0x941A17B0, 0x601A0266), BN_DEF(0xE6FBF176, 0x4F017E70), BN_DEF(0x770536B8, 0x8583D3E4), BN_DEF(0xB1B95D8C, 0x572B76F3), BN_DEF(0xEF1CA6FA, 0x0EA7A151), BN_DEF(0xB06BFA34, 0xDCB56D5B), BN_DEF(0xD96471FD, 0xE88454A5), BN_DEF(0x59927DB0, 0x5E0558C1), BN_DEF(0xA41D3CBD, 0x98566527), BN_DEF(0x9B56F39A, 0x0EF8AC50), BN_DEF(0x79F7F439, 0xF15344ED), BN_DEF(0x707345BB, 0xCC278638), BN_DEF(0x3FABE49A, 0xDAAB89AF), BN_DEF(0x9EF68D79, 0x42B1B2AA), BN_DEF(0xAF833768, 0x9219FA8F), BN_DEF(0xEAFEB2B0, 0x69EF8F6A), BN_DEF(0x576230BD, 0x7B40D901), BN_DEF(0xB1863AEC, 0xBE97F1B1), BN_DEF(0x124D9F7C, 0xE649CEE7), BN_DEF(0x8A3219FD, 0xD4F09B20), BN_DEF(0xE7169B4A, 0xEC5CE2C1), BN_DEF(0x139E9E78, 0x57EE2B10), BN_DEF(0x515DA54D, 0xD6FC2A2C), BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), }; static const BN_ULONG ffdhe8192_p[] = { BN_DEF(0xFFFFFFFF, 0xFFFFFFFF), BN_DEF(0xC5C6424C, 0xD68C8BB7), BN_DEF(0x838FF88C, 0x011E2A94), BN_DEF(0xA9F4614E, 0x0822E506), BN_DEF(0xF7A8443D, 0x97D11D49), BN_DEF(0x30677F0D, 0xA6BBFDE5), BN_DEF(0xC1FE86FE, 0x2F741EF8), BN_DEF(0x5D71A87E, 0xFAFABE1C), BN_DEF(0xFBE58A30, 0xDED2FBAB), BN_DEF(0x72B0A66E, 0xB6855DFE), BN_DEF(0xBA8A4FE8, 0x1EFC8CE0), BN_DEF(0x3F2FA457, 0x83F81D4A), BN_DEF(0xA577E231, 0xA1FE3075), BN_DEF(0x88D9C0A0, 0xD5B80194), BN_DEF(0xAD9A95F9, 0x624816CD), BN_DEF(0x50C1217B, 0x99E9E316), BN_DEF(0x0E423CFC, 0x51AA691E), BN_DEF(0x3826E52C, 0x1C217E6C), BN_DEF(0x09703FEE, 0x51A8A931), BN_DEF(0x6A460E74, 0xBB709987), BN_DEF(0x9C86B022, 0x541FC68C), BN_DEF(0x46FD8251, 0x59160CC0), BN_DEF(0x35C35F5C, 0x2846C0BA), BN_DEF(0x8B758282, 0x54504AC7), BN_DEF(0xD2AF05E4, 0x29388839), BN_DEF(0xC01BD702, 0xCB2C0F1C), BN_DEF(0x7C932665, 0x555B2F74), BN_DEF(0xA3AB8829, 0x86B63142), BN_DEF(0xF64B10EF, 0x0B8CC3BD), BN_DEF(0xEDD1CC5E, 0x687FEB69), BN_DEF(0xC9509D43, 0xFDB23FCE), BN_DEF(0xD951AE64, 0x1E425A31), BN_DEF(0xF600C838, 0x36AD004C), BN_DEF(0xCFF46AAA, 0xA40E329C), BN_DEF(0x7938DAD4, 0xA41D570D), BN_DEF(0xD43161C1, 0x62A69526), BN_DEF(0x9ADB1E69, 0x3FDD4A8E), BN_DEF(0xDC6B80D6, 0x5B3B71F9), BN_DEF(0xC6272B04, 0xEC9D1810), BN_DEF(0xCACEF403, 0x8CCF2DD5), BN_DEF(0xC95B9117, 0xE49F5235), BN_DEF(0xB854338A, 0x505DC82D), BN_DEF(0x1562A846, 0x62292C31), BN_DEF(0x6AE77F5E, 0xD72B0374), BN_DEF(0x462D538C, 0xF9C9091B), BN_DEF(0x47A67CBE, 0x0AE8DB58), BN_DEF(0x22611682, 0xB3A739C1), BN_DEF(0x2A281BF6, 0xEEAAC023), BN_DEF(0x77CAF992, 0x94C6651E), BN_DEF(0x94B2BBC1, 0x763E4E4B), BN_DEF(0x0077D9B4, 0x587E38DA), BN_DEF(0x183023C3, 0x7FB29F8C), BN_DEF(0xF9E3A26E, 0x0ABEC1FF), BN_DEF(0x350511E3, 0xA00EF092), BN_DEF(0xDB6340D8, 0xB855322E), BN_DEF(0xA9A96910, 0xA52471F7), BN_DEF(0x4CFDB477, 0x388147FB), BN_DEF(0x4E46041F, 0x9B1F5C3E), BN_DEF(0xFCCFEC71, 0xCDAD0657), BN_DEF(0x4C701C3A, 0xB38E8C33), BN_DEF(0xB1C0FD4C, 0x917BDD64), BN_DEF(0x9B7624C8, 0x3BB45432), BN_DEF(0xCAF53EA6, 0x23BA4442), BN_DEF(0x38532A3A, 0x4E677D2C), BN_DEF(0x45036C7A, 0x0BFD64B6), BN_DEF(0x5E0DD902, 0xC68A007E), BN_DEF(0xF44182E1, 0x4DB5A851), BN_DEF(0x7F88A46B, 0x8EC9B55A), BN_DEF(0xCEC97DCF, 0x0A8291CD), BN_DEF(0xF98D0ACC, 0x2A4ECEA9), BN_DEF(0x7140003C, 0x1A1DB93D), BN_DEF(0x33CB8B7A, 0x092999A3), BN_DEF(0x71AD0038, 0x6DC778F9), BN_DEF(0x918130C4, 0xA907600A), BN_DEF(0x2D9E6832, 0xED6A1E01), BN_DEF(0xEFB4318A, 0x7135C886), BN_DEF(0x7E31CC7A, 0x87F55BA5), BN_DEF(0x55034004, 0x7763CF1D), BN_DEF(0xD69F6D18, 0xAC7D5F42), BN_DEF(0xE58857B6, 0x7930E9E4), BN_DEF(0x164DF4FB, 0x6E6F52C3), BN_DEF(0x669E1EF1, 0x25E41D2B), BN_DEF(0x3FD59D7C, 0x3C1B20EE), BN_DEF(0xFA53DDEF, 0x0ABCD06B), BN_DEF(0xD5C4484E, 0x1DBF9A42), BN_DEF(0x9B0DEADA, 0xABC52197), BN_DEF(0x22363A0D, 0xE86D2BC5), BN_DEF(0x9C9DF69E, 0x5CAE82AB), BN_DEF(0x71F54BFF, 0x64F2E21E), BN_DEF(0xE2D74DD3, 0xF4FD4452), BN_DEF(0xBC437944, 0xB4130C93), BN_DEF(0x85139270, 0xAEFE1309), BN_DEF(0xC186D91C, 0x598CB0FA), BN_DEF(0x91F7F7EE, 0x7AD91D26), BN_DEF(0xD6E6C907, 0x61B46FC9), BN_DEF(0xF99C0238, 0xBC34F4DE), BN_DEF(0x6519035B, 0xDE355B3B), BN_DEF(0x611FCFDC, 0x886B4238), BN_DEF(0xC1B2EFFA, 0xC6F34A26), BN_DEF(0x7D1683B2, 0xC58EF183), BN_DEF(0x2EC22005, 0x3BB5FCBC), BN_DEF(0x4C6FAD73, 0xC3FE3B1B), BN_DEF(0xEEF28183, 0x8E4F1232), BN_DEF(0xE98583FF, 0x9172FE9C), BN_DEF(0x28342F61, 0xC03404CD), BN_DEF(0xCDF7E2EC, 0x9E02FCE1), BN_DEF(0xEE0A6D70, 0x0B07A7C8), BN_DEF(0x6372BB19, 0xAE56EDE7), BN_DEF(0xDE394DF4, 0x1D4F42A3), BN_DEF(0x60D7F468, 0xB96ADAB7), BN_DEF(0xB2C8E3FB, 0xD108A94B), BN_DEF(0xB324FB61, 0xBC0AB182), BN_DEF(0x483A797A, 0x30ACCA4F), BN_DEF(0x36ADE735, 0x1DF158A1), BN_DEF(0xF3EFE872, 0xE2A689DA), BN_DEF(0xE0E68B77, 0x984F0C70), BN_DEF(0x7F57C935, 0xB557135E), BN_DEF(0x3DED1AF3, 0x85636555), BN_DEF(0x5F066ED0, 0x2433F51F), BN_DEF(0xD5FD6561, 0xD3DF1ED5), BN_DEF(0xAEC4617A, 0xF681B202), BN_DEF(0x630C75D8, 0x7D2FE363), BN_DEF(0x249B3EF9, 0xCC939DCE), BN_DEF(0x146433FB, 0xA9E13641), BN_DEF(0xCE2D3695, 0xD8B9C583), BN_DEF(0x273D3CF1, 0xAFDC5620), BN_DEF(0xA2BB4A9A, 0xADF85458), BN_DEF(0xFFFFFFFF, 0xFFFFFFFF) }; /* q = (p - 1) / 2 */ static const BN_ULONG ffdhe8192_q[] = { BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), BN_DEF(0xE2E32126, 0x6B4645DB), BN_DEF(0x41C7FC46, 0x008F154A), BN_DEF(0x54FA30A7, 0x84117283), BN_DEF(0xFBD4221E, 0xCBE88EA4), BN_DEF(0x9833BF86, 0x535DFEF2), BN_DEF(0x60FF437F, 0x17BA0F7C), BN_DEF(0x2EB8D43F, 0x7D7D5F0E), BN_DEF(0xFDF2C518, 0x6F697DD5), BN_DEF(0x39585337, 0x5B42AEFF), BN_DEF(0x5D4527F4, 0x8F7E4670), BN_DEF(0x1F97D22B, 0xC1FC0EA5), BN_DEF(0xD2BBF118, 0x50FF183A), BN_DEF(0x446CE050, 0xEADC00CA), BN_DEF(0xD6CD4AFC, 0xB1240B66), BN_DEF(0x286090BD, 0x4CF4F18B), BN_DEF(0x07211E7E, 0x28D5348F), BN_DEF(0x1C137296, 0x0E10BF36), BN_DEF(0x84B81FF7, 0x28D45498), BN_DEF(0xB523073A, 0x5DB84CC3), BN_DEF(0x4E435811, 0xAA0FE346), BN_DEF(0x237EC128, 0x2C8B0660), BN_DEF(0x1AE1AFAE, 0x1423605D), BN_DEF(0xC5BAC141, 0x2A282563), BN_DEF(0xE95782F2, 0x149C441C), BN_DEF(0x600DEB81, 0xE596078E), BN_DEF(0x3E499332, 0xAAAD97BA), BN_DEF(0x51D5C414, 0xC35B18A1), BN_DEF(0xFB258877, 0x05C661DE), BN_DEF(0xF6E8E62F, 0xB43FF5B4), BN_DEF(0x64A84EA1, 0x7ED91FE7), BN_DEF(0xECA8D732, 0x0F212D18), BN_DEF(0x7B00641C, 0x1B568026), BN_DEF(0x67FA3555, 0x5207194E), BN_DEF(0xBC9C6D6A, 0xD20EAB86), BN_DEF(0x6A18B0E0, 0xB1534A93), BN_DEF(0x4D6D8F34, 0x1FEEA547), BN_DEF(0xEE35C06B, 0x2D9DB8FC), BN_DEF(0x63139582, 0xF64E8C08), BN_DEF(0xE5677A01, 0xC66796EA), BN_DEF(0xE4ADC88B, 0x724FA91A), BN_DEF(0xDC2A19C5, 0x282EE416), BN_DEF(0x8AB15423, 0x31149618), BN_DEF(0x3573BFAF, 0x6B9581BA), BN_DEF(0xA316A9C6, 0x7CE4848D), BN_DEF(0x23D33E5F, 0x05746DAC), BN_DEF(0x91308B41, 0x59D39CE0), BN_DEF(0x95140DFB, 0x77556011), BN_DEF(0x3BE57CC9, 0xCA63328F), BN_DEF(0xCA595DE0, 0x3B1F2725), BN_DEF(0x003BECDA, 0xAC3F1C6D), BN_DEF(0x0C1811E1, 0x3FD94FC6), BN_DEF(0xFCF1D137, 0x855F60FF), BN_DEF(0x1A8288F1, 0x50077849), BN_DEF(0x6DB1A06C, 0x5C2A9917), BN_DEF(0xD4D4B488, 0xD29238FB), BN_DEF(0xA67EDA3B, 0x9C40A3FD), BN_DEF(0x2723020F, 0xCD8FAE1F), BN_DEF(0xFE67F638, 0x66D6832B), BN_DEF(0xA6380E1D, 0x59C74619), BN_DEF(0x58E07EA6, 0x48BDEEB2), BN_DEF(0x4DBB1264, 0x1DDA2A19), BN_DEF(0x657A9F53, 0x11DD2221), BN_DEF(0x1C29951D, 0x2733BE96), BN_DEF(0x2281B63D, 0x05FEB25B), BN_DEF(0x2F06EC81, 0xE345003F), BN_DEF(0xFA20C170, 0xA6DAD428), BN_DEF(0x3FC45235, 0xC764DAAD), BN_DEF(0xE764BEE7, 0x054148E6), BN_DEF(0xFCC68566, 0x15276754), BN_DEF(0xB8A0001E, 0x0D0EDC9E), BN_DEF(0x99E5C5BD, 0x0494CCD1), BN_DEF(0xB8D6801C, 0x36E3BC7C), BN_DEF(0x48C09862, 0x5483B005), BN_DEF(0x96CF3419, 0x76B50F00), BN_DEF(0x77DA18C5, 0x389AE443), BN_DEF(0xBF18E63D, 0x43FAADD2), BN_DEF(0xAA81A002, 0x3BB1E78E), BN_DEF(0x6B4FB68C, 0x563EAFA1), BN_DEF(0x72C42BDB, 0xBC9874F2), BN_DEF(0x8B26FA7D, 0xB737A961), BN_DEF(0xB34F0F78, 0x12F20E95), BN_DEF(0x1FEACEBE, 0x9E0D9077), BN_DEF(0xFD29EEF7, 0x055E6835), BN_DEF(0x6AE22427, 0x0EDFCD21), BN_DEF(0xCD86F56D, 0xD5E290CB), BN_DEF(0x911B1D06, 0x743695E2), BN_DEF(0xCE4EFB4F, 0xAE574155), BN_DEF(0x38FAA5FF, 0xB279710F), BN_DEF(0x716BA6E9, 0x7A7EA229), BN_DEF(0xDE21BCA2, 0x5A098649), BN_DEF(0xC289C938, 0x577F0984), BN_DEF(0x60C36C8E, 0x2CC6587D), BN_DEF(0x48FBFBF7, 0xBD6C8E93), BN_DEF(0xEB736483, 0x30DA37E4), BN_DEF(0x7CCE011C, 0xDE1A7A6F), BN_DEF(0xB28C81AD, 0x6F1AAD9D), BN_DEF(0x308FE7EE, 0x4435A11C), BN_DEF(0x60D977FD, 0x6379A513), BN_DEF(0xBE8B41D9, 0xE2C778C1), BN_DEF(0x17611002, 0x9DDAFE5E), BN_DEF(0xA637D6B9, 0xE1FF1D8D), BN_DEF(0x777940C1, 0xC7278919), BN_DEF(0x74C2C1FF, 0xC8B97F4E), BN_DEF(0x941A17B0, 0x601A0266), BN_DEF(0xE6FBF176, 0x4F017E70), BN_DEF(0x770536B8, 0x8583D3E4), BN_DEF(0xB1B95D8C, 0x572B76F3), BN_DEF(0xEF1CA6FA, 0x0EA7A151), BN_DEF(0xB06BFA34, 0xDCB56D5B), BN_DEF(0xD96471FD, 0xE88454A5), BN_DEF(0x59927DB0, 0x5E0558C1), BN_DEF(0xA41D3CBD, 0x98566527), BN_DEF(0x9B56F39A, 0x0EF8AC50), BN_DEF(0x79F7F439, 0xF15344ED), BN_DEF(0x707345BB, 0xCC278638), BN_DEF(0x3FABE49A, 0xDAAB89AF), BN_DEF(0x9EF68D79, 0x42B1B2AA), BN_DEF(0xAF833768, 0x9219FA8F), BN_DEF(0xEAFEB2B0, 0x69EF8F6A), BN_DEF(0x576230BD, 0x7B40D901), BN_DEF(0xB1863AEC, 0xBE97F1B1), BN_DEF(0x124D9F7C, 0xE649CEE7), BN_DEF(0x8A3219FD, 0xD4F09B20), BN_DEF(0xE7169B4A, 0xEC5CE2C1), BN_DEF(0x139E9E78, 0x57EE2B10), BN_DEF(0x515DA54D, 0xD6FC2A2C), BN_DEF(0xFFFFFFFF, 0x7FFFFFFF), }; /* Macro to make a BIGNUM from static data */ # define make_dh_bn(x) \ extern const BIGNUM ossl_bignum_##x; \ const BIGNUM ossl_bignum_##x = { \ (BN_ULONG *) x, \ OSSL_NELEM(x), \ OSSL_NELEM(x), \ 0, BN_FLG_STATIC_DATA }; static const BN_ULONG value_2 = 2; const BIGNUM ossl_bignum_const_2 = { (BN_ULONG *)&value_2, 1, 1, 0, BN_FLG_STATIC_DATA }; make_dh_bn(dh1024_160_p) make_dh_bn(dh1024_160_q) make_dh_bn(dh1024_160_g) make_dh_bn(dh2048_224_p) make_dh_bn(dh2048_224_q) make_dh_bn(dh2048_224_g) make_dh_bn(dh2048_256_p) make_dh_bn(dh2048_256_q) make_dh_bn(dh2048_256_g) make_dh_bn(ffdhe2048_p) make_dh_bn(ffdhe2048_q) make_dh_bn(ffdhe3072_p) make_dh_bn(ffdhe3072_q) make_dh_bn(ffdhe4096_p) make_dh_bn(ffdhe4096_q) make_dh_bn(ffdhe6144_p) make_dh_bn(ffdhe6144_q) make_dh_bn(ffdhe8192_p) make_dh_bn(ffdhe8192_q) # ifndef FIPS_MODULE make_dh_bn(modp_1536_p) make_dh_bn(modp_1536_q) # endif make_dh_bn(modp_2048_p) make_dh_bn(modp_2048_q) make_dh_bn(modp_3072_p) make_dh_bn(modp_3072_q) make_dh_bn(modp_4096_p) make_dh_bn(modp_4096_q) make_dh_bn(modp_6144_p) make_dh_bn(modp_6144_q) make_dh_bn(modp_8192_p) make_dh_bn(modp_8192_q)
./openssl/crypto/bn/bn_exp2.c
/* * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include "bn_local.h" #define TABLE_SIZE 32 int BN_mod_exp2_mont(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) { int i, j, bits, b, bits1, bits2, ret = 0, wpos1, wpos2, window1, window2, wvalue1, wvalue2; int r_is_one = 1; BIGNUM *d, *r; const BIGNUM *a_mod_m; /* Tables of variables obtained from 'ctx' */ BIGNUM *val1[TABLE_SIZE], *val2[TABLE_SIZE]; BN_MONT_CTX *mont = NULL; bn_check_top(a1); bn_check_top(p1); bn_check_top(a2); bn_check_top(p2); bn_check_top(m); if (!BN_is_odd(m)) { ERR_raise(ERR_LIB_BN, BN_R_CALLED_WITH_EVEN_MODULUS); return 0; } bits1 = BN_num_bits(p1); bits2 = BN_num_bits(p2); if ((bits1 == 0) && (bits2 == 0)) { ret = BN_one(rr); return ret; } bits = (bits1 > bits2) ? bits1 : bits2; BN_CTX_start(ctx); d = BN_CTX_get(ctx); r = BN_CTX_get(ctx); val1[0] = BN_CTX_get(ctx); val2[0] = BN_CTX_get(ctx); if (val2[0] == NULL) goto err; if (in_mont != NULL) mont = in_mont; else { if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, m, ctx)) goto err; } window1 = BN_window_bits_for_exponent_size(bits1); window2 = BN_window_bits_for_exponent_size(bits2); /* * Build table for a1: val1[i] := a1^(2*i + 1) mod m for i = 0 .. 2^(window1-1) */ if (a1->neg || BN_ucmp(a1, m) >= 0) { if (!BN_mod(val1[0], a1, m, ctx)) goto err; a_mod_m = val1[0]; } else a_mod_m = a1; if (BN_is_zero(a_mod_m)) { BN_zero(rr); ret = 1; goto err; } if (!BN_to_montgomery(val1[0], a_mod_m, mont, ctx)) goto err; if (window1 > 1) { if (!BN_mod_mul_montgomery(d, val1[0], val1[0], mont, ctx)) goto err; j = 1 << (window1 - 1); for (i = 1; i < j; i++) { if (((val1[i] = BN_CTX_get(ctx)) == NULL) || !BN_mod_mul_montgomery(val1[i], val1[i - 1], d, mont, ctx)) goto err; } } /* * Build table for a2: val2[i] := a2^(2*i + 1) mod m for i = 0 .. 2^(window2-1) */ if (a2->neg || BN_ucmp(a2, m) >= 0) { if (!BN_mod(val2[0], a2, m, ctx)) goto err; a_mod_m = val2[0]; } else a_mod_m = a2; if (BN_is_zero(a_mod_m)) { BN_zero(rr); ret = 1; goto err; } if (!BN_to_montgomery(val2[0], a_mod_m, mont, ctx)) goto err; if (window2 > 1) { if (!BN_mod_mul_montgomery(d, val2[0], val2[0], mont, ctx)) goto err; j = 1 << (window2 - 1); for (i = 1; i < j; i++) { if (((val2[i] = BN_CTX_get(ctx)) == NULL) || !BN_mod_mul_montgomery(val2[i], val2[i - 1], d, mont, ctx)) goto err; } } /* Now compute the power product, using independent windows. */ r_is_one = 1; wvalue1 = 0; /* The 'value' of the first window */ wvalue2 = 0; /* The 'value' of the second window */ wpos1 = 0; /* If wvalue1 > 0, the bottom bit of the * first window */ wpos2 = 0; /* If wvalue2 > 0, the bottom bit of the * second window */ if (!BN_to_montgomery(r, BN_value_one(), mont, ctx)) goto err; for (b = bits - 1; b >= 0; b--) { if (!r_is_one) { if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) goto err; } if (!wvalue1) if (BN_is_bit_set(p1, b)) { /* * consider bits b-window1+1 .. b for this window */ i = b - window1 + 1; while (!BN_is_bit_set(p1, i)) /* works for i<0 */ i++; wpos1 = i; wvalue1 = 1; for (i = b - 1; i >= wpos1; i--) { wvalue1 <<= 1; if (BN_is_bit_set(p1, i)) wvalue1++; } } if (!wvalue2) if (BN_is_bit_set(p2, b)) { /* * consider bits b-window2+1 .. b for this window */ i = b - window2 + 1; while (!BN_is_bit_set(p2, i)) i++; wpos2 = i; wvalue2 = 1; for (i = b - 1; i >= wpos2; i--) { wvalue2 <<= 1; if (BN_is_bit_set(p2, i)) wvalue2++; } } if (wvalue1 && b == wpos1) { /* wvalue1 is odd and < 2^window1 */ if (!BN_mod_mul_montgomery(r, r, val1[wvalue1 >> 1], mont, ctx)) goto err; wvalue1 = 0; r_is_one = 0; } if (wvalue2 && b == wpos2) { /* wvalue2 is odd and < 2^window2 */ if (!BN_mod_mul_montgomery(r, r, val2[wvalue2 >> 1], mont, ctx)) goto err; wvalue2 = 0; r_is_one = 0; } } if (!BN_from_montgomery(rr, r, mont, ctx)) goto err; ret = 1; err: if (in_mont == NULL) BN_MONT_CTX_free(mont); BN_CTX_end(ctx); bn_check_top(rr); return ret; }
./openssl/crypto/bn/bn_sparc.c
/* * Copyright 2005-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdlib.h> #include <openssl/bn.h> #include "internal/cryptlib.h" #include "crypto/sparc_arch.h" #include "bn_local.h" /* for definition of bn_mul_mont */ int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num) { int bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); int bn_mul_mont_fpu(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); int bn_mul_mont_int(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); if (!(num & 1) && num >= 6) { if ((num & 15) == 0 && num <= 64 && (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) == (CFR_MONTMUL | CFR_MONTSQR)) { typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0); static const bn_mul_mont_f funcs[4] = { bn_mul_mont_t4_8, bn_mul_mont_t4_16, bn_mul_mont_t4_24, bn_mul_mont_t4_32 }; bn_mul_mont_f worker = funcs[num / 16 - 1]; if ((*worker) (rp, ap, bp, np, n0)) return 1; /* retry once and fall back */ if ((*worker) (rp, ap, bp, np, n0)) return 1; return bn_mul_mont_vis3(rp, ap, bp, np, n0, num); } if ((OPENSSL_sparcv9cap_P[0] & SPARCV9_VIS3)) return bn_mul_mont_vis3(rp, ap, bp, np, n0, num); else if (num >= 8 && /* * bn_mul_mont_fpu doesn't use FMADD, we just use the * flag to detect when FPU path is preferable in cases * when current heuristics is unreliable. [it works * out because FMADD-capable processors where FPU * code path is undesirable are also VIS3-capable and * VIS3 code path takes precedence.] */ ( (OPENSSL_sparcv9cap_P[0] & SPARCV9_FMADD) || (OPENSSL_sparcv9cap_P[0] & (SPARCV9_PREFER_FPU | SPARCV9_VIS1)) == (SPARCV9_PREFER_FPU | SPARCV9_VIS1) )) return bn_mul_mont_fpu(rp, ap, bp, np, n0, num); } return bn_mul_mont_int(rp, ap, bp, np, n0, num); }
./openssl/crypto/bn/bn_rsa_fips186_4.c
/* * Copyright 2018-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2018-2019, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * According to NIST SP800-131A "Transitioning the use of cryptographic * algorithms and key lengths" Generation of 1024 bit RSA keys are no longer * allowed for signatures (Table 2) or key transport (Table 5). In the code * below any attempt to generate 1024 bit RSA keys will result in an error (Note * that digital signature verification can still use deprecated 1024 bit keys). * * FIPS 186-4 relies on the use of the auxiliary primes p1, p2, q1 and q2 that * must be generated before the module generates the RSA primes p and q. * Table B.1 in FIPS 186-4 specifies RSA modulus lengths of 2048 and * 3072 bits only, the min/max total length of the auxiliary primes. * FIPS 186-5 Table A.1 includes an additional entry for 4096 which has been * included here. */ #include <stdio.h> #include <openssl/bn.h> #include "bn_local.h" #include "crypto/bn.h" #include "internal/nelem.h" #if BN_BITS2 == 64 # define BN_DEF(lo, hi) (BN_ULONG)hi<<32|lo #else # define BN_DEF(lo, hi) lo, hi #endif /* 1 / sqrt(2) * 2^256, rounded up */ static const BN_ULONG inv_sqrt_2_val[] = { BN_DEF(0x83339916UL, 0xED17AC85UL), BN_DEF(0x893BA84CUL, 0x1D6F60BAUL), BN_DEF(0x754ABE9FUL, 0x597D89B3UL), BN_DEF(0xF9DE6484UL, 0xB504F333UL) }; const BIGNUM ossl_bn_inv_sqrt_2 = { (BN_ULONG *)inv_sqrt_2_val, OSSL_NELEM(inv_sqrt_2_val), OSSL_NELEM(inv_sqrt_2_val), 0, BN_FLG_STATIC_DATA }; /* * Refer to FIPS 186-5 Table B.1 for minimum rounds of Miller Rabin * required for generation of RSA aux primes (p1, p2, q1 and q2). */ static int bn_rsa_fips186_5_aux_prime_MR_rounds(int nbits) { if (nbits >= 4096) return 44; if (nbits >= 3072) return 41; if (nbits >= 2048) return 38; return 0; /* Error */ } /* * Refer to FIPS 186-5 Table B.1 for minimum rounds of Miller Rabin * required for generation of RSA primes (p and q) */ static int bn_rsa_fips186_5_prime_MR_rounds(int nbits) { if (nbits >= 3072) return 4; if (nbits >= 2048) return 5; return 0; /* Error */ } /* * FIPS 186-5 Table A.1. "Min length of auxiliary primes p1, p2, q1, q2". * (FIPS 186-5 has an entry for >= 4096 bits). * * Params: * nbits The key size in bits. * Returns: * The minimum size of the auxiliary primes or 0 if nbits is invalid. */ static int bn_rsa_fips186_5_aux_prime_min_size(int nbits) { if (nbits >= 4096) return 201; if (nbits >= 3072) return 171; if (nbits >= 2048) return 141; return 0; } /* * FIPS 186-5 Table A.1 "Max of len(p1) + len(p2) and * len(q1) + len(q2) for p,q Probable Primes". * (FIPS 186-5 has an entry for >= 4096 bits). * Params: * nbits The key size in bits. * Returns: * The maximum length or 0 if nbits is invalid. */ static int bn_rsa_fips186_5_aux_prime_max_sum_size_for_prob_primes(int nbits) { if (nbits >= 4096) return 2030; if (nbits >= 3072) return 1518; if (nbits >= 2048) return 1007; return 0; } /* * Find the first odd integer that is a probable prime. * * See section FIPS 186-4 B.3.6 (Steps 4.2/5.2). * * Params: * Xp1 The passed in starting point to find a probably prime. * p1 The returned probable prime (first odd integer >= Xp1) * ctx A BN_CTX object. * rounds The number of Miller Rabin rounds * cb An optional BIGNUM callback. * Returns: 1 on success otherwise it returns 0. */ static int bn_rsa_fips186_4_find_aux_prob_prime(const BIGNUM *Xp1, BIGNUM *p1, BN_CTX *ctx, int rounds, BN_GENCB *cb) { int ret = 0; int i = 0; int tmp = 0; if (BN_copy(p1, Xp1) == NULL) return 0; BN_set_flags(p1, BN_FLG_CONSTTIME); /* Find the first odd number >= Xp1 that is probably prime */ for (;;) { i++; BN_GENCB_call(cb, 0, i); /* MR test with trial division */ tmp = ossl_bn_check_generated_prime(p1, rounds, ctx, cb); if (tmp > 0) break; if (tmp < 0) goto err; /* Get next odd number */ if (!BN_add_word(p1, 2)) goto err; } BN_GENCB_call(cb, 2, i); ret = 1; err: return ret; } /* * Generate a probable prime (p or q). * * See FIPS 186-4 B.3.6 (Steps 4 & 5) * * Params: * p The returned probable prime. * Xpout An optionally returned random number used during generation of p. * p1, p2 The returned auxiliary primes. If NULL they are not returned. * Xp An optional passed in value (that is random number used during * generation of p). * Xp1, Xp2 Optional passed in values that are normally generated * internally. Used to find p1, p2. * nlen The bit length of the modulus (the key size). * e The public exponent. * ctx A BN_CTX object. * cb An optional BIGNUM callback. * Returns: 1 on success otherwise it returns 0. */ int ossl_bn_rsa_fips186_4_gen_prob_primes(BIGNUM *p, BIGNUM *Xpout, BIGNUM *p1, BIGNUM *p2, const BIGNUM *Xp, const BIGNUM *Xp1, const BIGNUM *Xp2, int nlen, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0; BIGNUM *p1i = NULL, *p2i = NULL, *Xp1i = NULL, *Xp2i = NULL; int bitlen, rounds; if (p == NULL || Xpout == NULL) return 0; BN_CTX_start(ctx); p1i = (p1 != NULL) ? p1 : BN_CTX_get(ctx); p2i = (p2 != NULL) ? p2 : BN_CTX_get(ctx); Xp1i = (Xp1 != NULL) ? (BIGNUM *)Xp1 : BN_CTX_get(ctx); Xp2i = (Xp2 != NULL) ? (BIGNUM *)Xp2 : BN_CTX_get(ctx); if (p1i == NULL || p2i == NULL || Xp1i == NULL || Xp2i == NULL) goto err; bitlen = bn_rsa_fips186_5_aux_prime_min_size(nlen); if (bitlen == 0) goto err; rounds = bn_rsa_fips186_5_aux_prime_MR_rounds(nlen); /* (Steps 4.1/5.1): Randomly generate Xp1 if it is not passed in */ if (Xp1 == NULL) { /* Set the top and bottom bits to make it odd and the correct size */ if (!BN_priv_rand_ex(Xp1i, bitlen, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD, 0, ctx)) goto err; } /* (Steps 4.1/5.1): Randomly generate Xp2 if it is not passed in */ if (Xp2 == NULL) { /* Set the top and bottom bits to make it odd and the correct size */ if (!BN_priv_rand_ex(Xp2i, bitlen, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD, 0, ctx)) goto err; } /* (Steps 4.2/5.2) - find first auxiliary probable primes */ if (!bn_rsa_fips186_4_find_aux_prob_prime(Xp1i, p1i, ctx, rounds, cb) || !bn_rsa_fips186_4_find_aux_prob_prime(Xp2i, p2i, ctx, rounds, cb)) goto err; /* (Table B.1) auxiliary prime Max length check */ if ((BN_num_bits(p1i) + BN_num_bits(p2i)) >= bn_rsa_fips186_5_aux_prime_max_sum_size_for_prob_primes(nlen)) goto err; /* (Steps 4.3/5.3) - generate prime */ if (!ossl_bn_rsa_fips186_4_derive_prime(p, Xpout, Xp, p1i, p2i, nlen, e, ctx, cb)) goto err; ret = 1; err: /* Zeroize any internally generated values that are not returned */ if (p1 == NULL) BN_clear(p1i); if (p2 == NULL) BN_clear(p2i); if (Xp1 == NULL) BN_clear(Xp1i); if (Xp2 == NULL) BN_clear(Xp2i); BN_CTX_end(ctx); return ret; } /* * Constructs a probable prime (a candidate for p or q) using 2 auxiliary * prime numbers and the Chinese Remainder Theorem. * * See FIPS 186-4 C.9 "Compute a Probable Prime Factor Based on Auxiliary * Primes". Used by FIPS 186-4 B.3.6 Section (4.3) for p and Section (5.3) for q. * * Params: * Y The returned prime factor (private_prime_factor) of the modulus n. * X The returned random number used during generation of the prime factor. * Xin An optional passed in value for X used for testing purposes. * r1 An auxiliary prime. * r2 An auxiliary prime. * nlen The desired length of n (the RSA modulus). * e The public exponent. * ctx A BN_CTX object. * cb An optional BIGNUM callback object. * Returns: 1 on success otherwise it returns 0. * Assumptions: * Y, X, r1, r2, e are not NULL. */ int ossl_bn_rsa_fips186_4_derive_prime(BIGNUM *Y, BIGNUM *X, const BIGNUM *Xin, const BIGNUM *r1, const BIGNUM *r2, int nlen, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0; int i, imax, rounds; int bits = nlen >> 1; BIGNUM *tmp, *R, *r1r2x2, *y1, *r1x2; BIGNUM *base, *range; BN_CTX_start(ctx); base = BN_CTX_get(ctx); range = BN_CTX_get(ctx); R = BN_CTX_get(ctx); tmp = BN_CTX_get(ctx); r1r2x2 = BN_CTX_get(ctx); y1 = BN_CTX_get(ctx); r1x2 = BN_CTX_get(ctx); if (r1x2 == NULL) goto err; if (Xin != NULL && BN_copy(X, Xin) == NULL) goto err; /* * We need to generate a random number X in the range * 1/sqrt(2) * 2^(nlen/2) <= X < 2^(nlen/2). * We can rewrite that as: * base = 1/sqrt(2) * 2^(nlen/2) * range = ((2^(nlen/2))) - (1/sqrt(2) * 2^(nlen/2)) * X = base + random(range) * We only have the first 256 bit of 1/sqrt(2) */ if (Xin == NULL) { if (bits < BN_num_bits(&ossl_bn_inv_sqrt_2)) goto err; if (!BN_lshift(base, &ossl_bn_inv_sqrt_2, bits - BN_num_bits(&ossl_bn_inv_sqrt_2)) || !BN_lshift(range, BN_value_one(), bits) || !BN_sub(range, range, base)) goto err; } /* * (Step 1) GCD(2r1, r2) = 1. * Note: This algorithm was doing a gcd(2r1, r2)=1 test before doing an * mod_inverse(2r1, r2) which are effectively the same operation. * (The algorithm assumed that the gcd test would be faster). Since the * mod_inverse is currently faster than calling the constant time * BN_gcd(), the call to BN_gcd() has been omitted. The inverse result * is used further down. */ if (!(BN_lshift1(r1x2, r1) && (BN_mod_inverse(tmp, r1x2, r2, ctx) != NULL) /* (Step 2) R = ((r2^-1 mod 2r1) * r2) - ((2r1^-1 mod r2)*2r1) */ && (BN_mod_inverse(R, r2, r1x2, ctx) != NULL) && BN_mul(R, R, r2, ctx) /* R = (r2^-1 mod 2r1) * r2 */ && BN_mul(tmp, tmp, r1x2, ctx) /* tmp = (2r1^-1 mod r2)*2r1 */ && BN_sub(R, R, tmp) /* Calculate 2r1r2 */ && BN_mul(r1r2x2, r1x2, r2, ctx))) goto err; /* Make positive by adding the modulus */ if (BN_is_negative(R) && !BN_add(R, R, r1r2x2)) goto err; /* * In FIPS 186-4 imax was set to 5 * nlen/2. * Analysis by Allen Roginsky * (See https://csrc.nist.gov/CSRC/media/Publications/fips/186/4/final/documents/comments-received-fips186-4-december-2015.pdf * page 68) indicates this has a 1 in 2 million chance of failure. * The number has been updated to 20 * nlen/2 as used in * FIPS186-5 Appendix B.9 Step 9. */ rounds = bn_rsa_fips186_5_prime_MR_rounds(nlen); imax = 20 * bits; /* max = 20/2 * nbits */ for (;;) { if (Xin == NULL) { /* * (Step 3) Choose Random X such that * sqrt(2) * 2^(nlen/2-1) <= Random X <= (2^(nlen/2)) - 1. */ if (!BN_priv_rand_range_ex(X, range, 0, ctx) || !BN_add(X, X, base)) goto err; } /* (Step 4) Y = X + ((R - X) mod 2r1r2) */ if (!BN_mod_sub(Y, R, X, r1r2x2, ctx) || !BN_add(Y, Y, X)) goto err; /* (Step 5) */ i = 0; for (;;) { /* (Step 6) */ if (BN_num_bits(Y) > bits) { if (Xin == NULL) break; /* Randomly Generated X so Go back to Step 3 */ else goto err; /* X is not random so it will always fail */ } BN_GENCB_call(cb, 0, 2); /* (Step 7) If GCD(Y-1) == 1 & Y is probably prime then return Y */ if (BN_copy(y1, Y) == NULL || !BN_sub_word(y1, 1)) goto err; if (BN_are_coprime(y1, e, ctx)) { int rv = ossl_bn_check_generated_prime(Y, rounds, ctx, cb); if (rv > 0) goto end; if (rv < 0) goto err; } /* (Step 8-10) */ if (++i >= imax) { ERR_raise(ERR_LIB_BN, BN_R_NO_PRIME_CANDIDATE); goto err; } if (!BN_add(Y, Y, r1r2x2)) goto err; } } end: ret = 1; BN_GENCB_call(cb, 3, 0); err: BN_clear(y1); BN_CTX_end(ctx); return ret; }
./openssl/crypto/bn/bn_prime.h
/* * WARNING: do not edit! * Generated by crypto/bn/bn_prime.pl * * Copyright 1998-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 */ typedef unsigned short prime_t; # define NUMPRIMES 2048 static const prime_t primes[2048] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973, 10007, 10009, 10037, 10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099, 10103, 10111, 10133, 10139, 10141, 10151, 10159, 10163, 10169, 10177, 10181, 10193, 10211, 10223, 10243, 10247, 10253, 10259, 10267, 10271, 10273, 10289, 10301, 10303, 10313, 10321, 10331, 10333, 10337, 10343, 10357, 10369, 10391, 10399, 10427, 10429, 10433, 10453, 10457, 10459, 10463, 10477, 10487, 10499, 10501, 10513, 10529, 10531, 10559, 10567, 10589, 10597, 10601, 10607, 10613, 10627, 10631, 10639, 10651, 10657, 10663, 10667, 10687, 10691, 10709, 10711, 10723, 10729, 10733, 10739, 10753, 10771, 10781, 10789, 10799, 10831, 10837, 10847, 10853, 10859, 10861, 10867, 10883, 10889, 10891, 10903, 10909, 10937, 10939, 10949, 10957, 10973, 10979, 10987, 10993, 11003, 11027, 11047, 11057, 11059, 11069, 11071, 11083, 11087, 11093, 11113, 11117, 11119, 11131, 11149, 11159, 11161, 11171, 11173, 11177, 11197, 11213, 11239, 11243, 11251, 11257, 11261, 11273, 11279, 11287, 11299, 11311, 11317, 11321, 11329, 11351, 11353, 11369, 11383, 11393, 11399, 11411, 11423, 11437, 11443, 11447, 11467, 11471, 11483, 11489, 11491, 11497, 11503, 11519, 11527, 11549, 11551, 11579, 11587, 11593, 11597, 11617, 11621, 11633, 11657, 11677, 11681, 11689, 11699, 11701, 11717, 11719, 11731, 11743, 11777, 11779, 11783, 11789, 11801, 11807, 11813, 11821, 11827, 11831, 11833, 11839, 11863, 11867, 11887, 11897, 11903, 11909, 11923, 11927, 11933, 11939, 11941, 11953, 11959, 11969, 11971, 11981, 11987, 12007, 12011, 12037, 12041, 12043, 12049, 12071, 12073, 12097, 12101, 12107, 12109, 12113, 12119, 12143, 12149, 12157, 12161, 12163, 12197, 12203, 12211, 12227, 12239, 12241, 12251, 12253, 12263, 12269, 12277, 12281, 12289, 12301, 12323, 12329, 12343, 12347, 12373, 12377, 12379, 12391, 12401, 12409, 12413, 12421, 12433, 12437, 12451, 12457, 12473, 12479, 12487, 12491, 12497, 12503, 12511, 12517, 12527, 12539, 12541, 12547, 12553, 12569, 12577, 12583, 12589, 12601, 12611, 12613, 12619, 12637, 12641, 12647, 12653, 12659, 12671, 12689, 12697, 12703, 12713, 12721, 12739, 12743, 12757, 12763, 12781, 12791, 12799, 12809, 12821, 12823, 12829, 12841, 12853, 12889, 12893, 12899, 12907, 12911, 12917, 12919, 12923, 12941, 12953, 12959, 12967, 12973, 12979, 12983, 13001, 13003, 13007, 13009, 13033, 13037, 13043, 13049, 13063, 13093, 13099, 13103, 13109, 13121, 13127, 13147, 13151, 13159, 13163, 13171, 13177, 13183, 13187, 13217, 13219, 13229, 13241, 13249, 13259, 13267, 13291, 13297, 13309, 13313, 13327, 13331, 13337, 13339, 13367, 13381, 13397, 13399, 13411, 13417, 13421, 13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499, 13513, 13523, 13537, 13553, 13567, 13577, 13591, 13597, 13613, 13619, 13627, 13633, 13649, 13669, 13679, 13681, 13687, 13691, 13693, 13697, 13709, 13711, 13721, 13723, 13729, 13751, 13757, 13759, 13763, 13781, 13789, 13799, 13807, 13829, 13831, 13841, 13859, 13873, 13877, 13879, 13883, 13901, 13903, 13907, 13913, 13921, 13931, 13933, 13963, 13967, 13997, 13999, 14009, 14011, 14029, 14033, 14051, 14057, 14071, 14081, 14083, 14087, 14107, 14143, 14149, 14153, 14159, 14173, 14177, 14197, 14207, 14221, 14243, 14249, 14251, 14281, 14293, 14303, 14321, 14323, 14327, 14341, 14347, 14369, 14387, 14389, 14401, 14407, 14411, 14419, 14423, 14431, 14437, 14447, 14449, 14461, 14479, 14489, 14503, 14519, 14533, 14537, 14543, 14549, 14551, 14557, 14561, 14563, 14591, 14593, 14621, 14627, 14629, 14633, 14639, 14653, 14657, 14669, 14683, 14699, 14713, 14717, 14723, 14731, 14737, 14741, 14747, 14753, 14759, 14767, 14771, 14779, 14783, 14797, 14813, 14821, 14827, 14831, 14843, 14851, 14867, 14869, 14879, 14887, 14891, 14897, 14923, 14929, 14939, 14947, 14951, 14957, 14969, 14983, 15013, 15017, 15031, 15053, 15061, 15073, 15077, 15083, 15091, 15101, 15107, 15121, 15131, 15137, 15139, 15149, 15161, 15173, 15187, 15193, 15199, 15217, 15227, 15233, 15241, 15259, 15263, 15269, 15271, 15277, 15287, 15289, 15299, 15307, 15313, 15319, 15329, 15331, 15349, 15359, 15361, 15373, 15377, 15383, 15391, 15401, 15413, 15427, 15439, 15443, 15451, 15461, 15467, 15473, 15493, 15497, 15511, 15527, 15541, 15551, 15559, 15569, 15581, 15583, 15601, 15607, 15619, 15629, 15641, 15643, 15647, 15649, 15661, 15667, 15671, 15679, 15683, 15727, 15731, 15733, 15737, 15739, 15749, 15761, 15767, 15773, 15787, 15791, 15797, 15803, 15809, 15817, 15823, 15859, 15877, 15881, 15887, 15889, 15901, 15907, 15913, 15919, 15923, 15937, 15959, 15971, 15973, 15991, 16001, 16007, 16033, 16057, 16061, 16063, 16067, 16069, 16073, 16087, 16091, 16097, 16103, 16111, 16127, 16139, 16141, 16183, 16187, 16189, 16193, 16217, 16223, 16229, 16231, 16249, 16253, 16267, 16273, 16301, 16319, 16333, 16339, 16349, 16361, 16363, 16369, 16381, 16411, 16417, 16421, 16427, 16433, 16447, 16451, 16453, 16477, 16481, 16487, 16493, 16519, 16529, 16547, 16553, 16561, 16567, 16573, 16603, 16607, 16619, 16631, 16633, 16649, 16651, 16657, 16661, 16673, 16691, 16693, 16699, 16703, 16729, 16741, 16747, 16759, 16763, 16787, 16811, 16823, 16829, 16831, 16843, 16871, 16879, 16883, 16889, 16901, 16903, 16921, 16927, 16931, 16937, 16943, 16963, 16979, 16981, 16987, 16993, 17011, 17021, 17027, 17029, 17033, 17041, 17047, 17053, 17077, 17093, 17099, 17107, 17117, 17123, 17137, 17159, 17167, 17183, 17189, 17191, 17203, 17207, 17209, 17231, 17239, 17257, 17291, 17293, 17299, 17317, 17321, 17327, 17333, 17341, 17351, 17359, 17377, 17383, 17387, 17389, 17393, 17401, 17417, 17419, 17431, 17443, 17449, 17467, 17471, 17477, 17483, 17489, 17491, 17497, 17509, 17519, 17539, 17551, 17569, 17573, 17579, 17581, 17597, 17599, 17609, 17623, 17627, 17657, 17659, 17669, 17681, 17683, 17707, 17713, 17729, 17737, 17747, 17749, 17761, 17783, 17789, 17791, 17807, 17827, 17837, 17839, 17851, 17863, };
./openssl/crypto/bn/bn_shift.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <assert.h> #include "internal/cryptlib.h" #include "bn_local.h" int BN_lshift1(BIGNUM *r, const BIGNUM *a) { register BN_ULONG *ap, *rp, t, c; int i; bn_check_top(r); bn_check_top(a); if (r != a) { r->neg = a->neg; if (bn_wexpand(r, a->top + 1) == NULL) return 0; r->top = a->top; } else { if (bn_wexpand(r, a->top + 1) == NULL) return 0; } ap = a->d; rp = r->d; c = 0; for (i = 0; i < a->top; i++) { t = *(ap++); *(rp++) = ((t << 1) | c) & BN_MASK2; c = t >> (BN_BITS2 - 1); } *rp = c; r->top += c; bn_check_top(r); return 1; } int BN_rshift1(BIGNUM *r, const BIGNUM *a) { BN_ULONG *ap, *rp, t, c; int i; bn_check_top(r); bn_check_top(a); if (BN_is_zero(a)) { BN_zero(r); return 1; } i = a->top; ap = a->d; if (a != r) { if (bn_wexpand(r, i) == NULL) return 0; r->neg = a->neg; } rp = r->d; r->top = i; t = ap[--i]; rp[i] = t >> 1; c = t << (BN_BITS2 - 1); r->top -= (t == 1); while (i > 0) { t = ap[--i]; rp[i] = ((t >> 1) & BN_MASK2) | c; c = t << (BN_BITS2 - 1); } if (!r->top) r->neg = 0; /* don't allow negative zero */ bn_check_top(r); return 1; } int BN_lshift(BIGNUM *r, const BIGNUM *a, int n) { int ret; if (n < 0) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_SHIFT); return 0; } ret = bn_lshift_fixed_top(r, a, n); bn_correct_top(r); bn_check_top(r); return ret; } /* * In respect to shift factor the execution time is invariant of * |n % BN_BITS2|, but not |n / BN_BITS2|. Or in other words pre-condition * for constant-time-ness is |n < BN_BITS2| or |n / BN_BITS2| being * non-secret. */ int bn_lshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n) { int i, nw; unsigned int lb, rb; BN_ULONG *t, *f; BN_ULONG l, m, rmask = 0; assert(n >= 0); bn_check_top(r); bn_check_top(a); nw = n / BN_BITS2; if (bn_wexpand(r, a->top + nw + 1) == NULL) return 0; if (a->top != 0) { lb = (unsigned int)n % BN_BITS2; rb = BN_BITS2 - lb; rb %= BN_BITS2; /* say no to undefined behaviour */ rmask = (BN_ULONG)0 - rb; /* rmask = 0 - (rb != 0) */ rmask |= rmask >> 8; f = &(a->d[0]); t = &(r->d[nw]); l = f[a->top - 1]; t[a->top] = (l >> rb) & rmask; for (i = a->top - 1; i > 0; i--) { m = l << lb; l = f[i - 1]; t[i] = (m | ((l >> rb) & rmask)) & BN_MASK2; } t[0] = (l << lb) & BN_MASK2; } else { /* shouldn't happen, but formally required */ r->d[nw] = 0; } if (nw != 0) memset(r->d, 0, sizeof(*t) * nw); r->neg = a->neg; r->top = a->top + nw + 1; r->flags |= BN_FLG_FIXED_TOP; return 1; } int BN_rshift(BIGNUM *r, const BIGNUM *a, int n) { int ret = 0; if (n < 0) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_SHIFT); return 0; } ret = bn_rshift_fixed_top(r, a, n); bn_correct_top(r); bn_check_top(r); return ret; } /* * In respect to shift factor the execution time is invariant of * |n % BN_BITS2|, but not |n / BN_BITS2|. Or in other words pre-condition * for constant-time-ness for sufficiently[!] zero-padded inputs is * |n < BN_BITS2| or |n / BN_BITS2| being non-secret. */ int bn_rshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n) { int i, top, nw; unsigned int lb, rb; BN_ULONG *t, *f; BN_ULONG l, m, mask; bn_check_top(r); bn_check_top(a); assert(n >= 0); nw = n / BN_BITS2; if (nw >= a->top) { /* shouldn't happen, but formally required */ BN_zero(r); return 1; } rb = (unsigned int)n % BN_BITS2; lb = BN_BITS2 - rb; lb %= BN_BITS2; /* say no to undefined behaviour */ mask = (BN_ULONG)0 - lb; /* mask = 0 - (lb != 0) */ mask |= mask >> 8; top = a->top - nw; if (r != a && bn_wexpand(r, top) == NULL) return 0; t = &(r->d[0]); f = &(a->d[nw]); l = f[0]; for (i = 0; i < top - 1; i++) { m = f[i + 1]; t[i] = (l >> rb) | ((m << lb) & mask); l = m; } t[i] = l >> rb; r->neg = a->neg; r->top = top; r->flags |= BN_FLG_FIXED_TOP; return 1; }
./openssl/crypto/bn/bn_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 */ /* * Support for deprecated functions goes here - static linkage will only * slurp this code if applications are using them directly. */ #include <openssl/opensslconf.h> #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include "bn_local.h" BIGNUM *BN_generate_prime(BIGNUM *ret, int bits, int safe, const BIGNUM *add, const BIGNUM *rem, void (*callback) (int, int, void *), void *cb_arg) { BN_GENCB cb; BIGNUM *rnd = NULL; BN_GENCB_set_old(&cb, callback, cb_arg); if (ret == NULL) { if ((rnd = BN_new()) == NULL) goto err; } else rnd = ret; if (!BN_generate_prime_ex(rnd, bits, safe, add, rem, &cb)) goto err; /* we have a prime :-) */ return rnd; err: BN_free(rnd); return NULL; } int BN_is_prime(const BIGNUM *a, int checks, void (*callback) (int, int, void *), BN_CTX *ctx_passed, void *cb_arg) { BN_GENCB cb; BN_GENCB_set_old(&cb, callback, cb_arg); return ossl_bn_check_prime(a, checks, ctx_passed, 0, &cb); } int BN_is_prime_fasttest(const BIGNUM *a, int checks, void (*callback) (int, int, void *), BN_CTX *ctx_passed, void *cb_arg, int do_trial_division) { BN_GENCB cb; BN_GENCB_set_old(&cb, callback, cb_arg); return ossl_bn_check_prime(a, checks, ctx_passed, do_trial_division, &cb); }
./openssl/crypto/bn/bn_mod.c
/* * Copyright 1998-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 "bn_local.h" int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx) { /* * like BN_mod, but returns non-negative remainder (i.e., 0 <= r < |d| * always holds) */ if (r == d) { ERR_raise(ERR_LIB_BN, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (!(BN_mod(r, m, d, ctx))) return 0; if (!r->neg) return 1; /* now -|d| < r < 0, so we have to set r := r + |d| */ return (d->neg ? BN_sub : BN_add) (r, r, d); } int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx) { if (!BN_add(r, a, b)) return 0; return BN_nnmod(r, r, m, ctx); } /* * BN_mod_add variant that may be used if both a and b are non-negative and * less than m. The original algorithm was * * if (!BN_uadd(r, a, b)) * return 0; * if (BN_ucmp(r, m) >= 0) * return BN_usub(r, r, m); * * which is replaced with addition, subtracting modulus, and conditional * move depending on whether or not subtraction borrowed. */ int bn_mod_add_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m) { size_t i, ai, bi, mtop = m->top; BN_ULONG storage[1024 / BN_BITS2]; BN_ULONG carry, temp, mask, *rp, *tp = storage; const BN_ULONG *ap, *bp; if (bn_wexpand(r, mtop) == NULL) return 0; if (mtop > sizeof(storage) / sizeof(storage[0])) { tp = OPENSSL_malloc(mtop * sizeof(BN_ULONG)); if (tp == NULL) return 0; } ap = a->d != NULL ? a->d : tp; bp = b->d != NULL ? b->d : tp; for (i = 0, ai = 0, bi = 0, carry = 0; i < mtop;) { mask = (BN_ULONG)0 - ((i - a->top) >> (8 * sizeof(i) - 1)); temp = ((ap[ai] & mask) + carry) & BN_MASK2; carry = (temp < carry); mask = (BN_ULONG)0 - ((i - b->top) >> (8 * sizeof(i) - 1)); tp[i] = ((bp[bi] & mask) + temp) & BN_MASK2; carry += (tp[i] < temp); i++; ai += (i - a->dmax) >> (8 * sizeof(i) - 1); bi += (i - b->dmax) >> (8 * sizeof(i) - 1); } rp = r->d; carry -= bn_sub_words(rp, tp, m->d, mtop); for (i = 0; i < mtop; i++) { rp[i] = (carry & tp[i]) | (~carry & rp[i]); ((volatile BN_ULONG *)tp)[i] = 0; } r->top = mtop; r->flags |= BN_FLG_FIXED_TOP; r->neg = 0; if (tp != storage) OPENSSL_free(tp); return 1; } int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m) { int ret = bn_mod_add_fixed_top(r, a, b, m); if (ret) bn_correct_top(r); return ret; } int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx) { if (!BN_sub(r, a, b)) return 0; return BN_nnmod(r, r, m, ctx); } /* * BN_mod_sub variant that may be used if both a and b are non-negative, * a is less than m, while b is of same bit width as m. It's implemented * as subtraction followed by two conditional additions. * * 0 <= a < m * 0 <= b < 2^w < 2*m * * after subtraction * * -2*m < r = a - b < m * * Thus it takes up to two conditional additions to make |r| positive. */ int bn_mod_sub_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m) { size_t i, ai, bi, mtop = m->top; BN_ULONG borrow, carry, ta, tb, mask, *rp; const BN_ULONG *ap, *bp; if (bn_wexpand(r, mtop) == NULL) return 0; rp = r->d; ap = a->d != NULL ? a->d : rp; bp = b->d != NULL ? b->d : rp; for (i = 0, ai = 0, bi = 0, borrow = 0; i < mtop;) { mask = (BN_ULONG)0 - ((i - a->top) >> (8 * sizeof(i) - 1)); ta = ap[ai] & mask; mask = (BN_ULONG)0 - ((i - b->top) >> (8 * sizeof(i) - 1)); tb = bp[bi] & mask; rp[i] = ta - tb - borrow; if (ta != tb) borrow = (ta < tb); i++; ai += (i - a->dmax) >> (8 * sizeof(i) - 1); bi += (i - b->dmax) >> (8 * sizeof(i) - 1); } ap = m->d; for (i = 0, mask = 0 - borrow, carry = 0; i < mtop; i++) { ta = ((ap[i] & mask) + carry) & BN_MASK2; carry = (ta < carry); rp[i] = (rp[i] + ta) & BN_MASK2; carry += (rp[i] < ta); } borrow -= carry; for (i = 0, mask = 0 - borrow, carry = 0; i < mtop; i++) { ta = ((ap[i] & mask) + carry) & BN_MASK2; carry = (ta < carry); rp[i] = (rp[i] + ta) & BN_MASK2; carry += (rp[i] < ta); } r->top = mtop; r->flags |= BN_FLG_FIXED_TOP; r->neg = 0; return 1; } /* * BN_mod_sub variant that may be used if both a and b are non-negative and * less than m */ int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m) { if (r == m) { ERR_raise(ERR_LIB_BN, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (!BN_sub(r, a, b)) return 0; if (r->neg) return BN_add(r, r, m); return 1; } /* slow but works */ int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx) { BIGNUM *t; int ret = 0; bn_check_top(a); bn_check_top(b); bn_check_top(m); BN_CTX_start(ctx); if ((t = BN_CTX_get(ctx)) == NULL) goto err; if (a == b) { if (!BN_sqr(t, a, ctx)) goto err; } else { if (!BN_mul(t, a, b, ctx)) goto err; } if (!BN_nnmod(r, t, m, ctx)) goto err; bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return ret; } int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) { if (!BN_sqr(r, a, ctx)) return 0; /* r->neg == 0, thus we don't need BN_nnmod */ return BN_mod(r, r, m, ctx); } int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) { if (!BN_lshift1(r, a)) return 0; bn_check_top(r); return BN_nnmod(r, r, m, ctx); } /* * BN_mod_lshift1 variant that may be used if a is non-negative and less than * m */ int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m) { if (!BN_lshift1(r, a)) return 0; bn_check_top(r); if (BN_cmp(r, m) >= 0) return BN_sub(r, r, m); return 1; } int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m, BN_CTX *ctx) { BIGNUM *abs_m = NULL; int ret; if (!BN_nnmod(r, a, m, ctx)) return 0; if (m->neg) { abs_m = BN_dup(m); if (abs_m == NULL) return 0; abs_m->neg = 0; } ret = BN_mod_lshift_quick(r, r, n, (abs_m ? abs_m : m)); bn_check_top(r); BN_free(abs_m); return ret; } /* * BN_mod_lshift variant that may be used if a is non-negative and less than * m */ int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m) { if (r != a) { if (BN_copy(r, a) == NULL) return 0; } while (n > 0) { int max_shift; /* 0 < r < m */ max_shift = BN_num_bits(m) - BN_num_bits(r); /* max_shift >= 0 */ if (max_shift < 0) { ERR_raise(ERR_LIB_BN, BN_R_INPUT_NOT_REDUCED); return 0; } if (max_shift > n) max_shift = n; if (max_shift) { if (!BN_lshift(r, r, max_shift)) return 0; n -= max_shift; } else { if (!BN_lshift1(r, r)) return 0; --n; } /* BN_num_bits(r) <= BN_num_bits(m) */ if (BN_cmp(r, m) >= 0) { if (!BN_sub(r, r, m)) return 0; } } bn_check_top(r); return 1; }
./openssl/crypto/bn/bn_mpi.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include "bn_local.h" int BN_bn2mpi(const BIGNUM *a, unsigned char *d) { int bits; int num = 0; int ext = 0; long l; bits = BN_num_bits(a); num = (bits + 7) / 8; if (bits > 0) { ext = ((bits & 0x07) == 0); } if (d == NULL) return (num + 4 + ext); l = num + ext; d[0] = (unsigned char)(l >> 24) & 0xff; d[1] = (unsigned char)(l >> 16) & 0xff; d[2] = (unsigned char)(l >> 8) & 0xff; d[3] = (unsigned char)(l) & 0xff; if (ext) d[4] = 0; num = BN_bn2bin(a, &(d[4 + ext])); if (a->neg) d[4] |= 0x80; return (num + 4 + ext); } BIGNUM *BN_mpi2bn(const unsigned char *d, int n, BIGNUM *ain) { long len; int neg = 0; BIGNUM *a = NULL; if (n < 4 || (d[0] & 0x80) != 0) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH); return NULL; } len = ((long)d[0] << 24) | ((long)d[1] << 16) | ((int)d[2] << 8) | (int) d[3]; if ((len + 4) != n) { ERR_raise(ERR_LIB_BN, BN_R_ENCODING_ERROR); return NULL; } if (ain == NULL) a = BN_new(); else a = ain; if (a == NULL) return NULL; if (len == 0) { a->neg = 0; a->top = 0; return a; } d += 4; if ((*d) & 0x80) neg = 1; if (BN_bin2bn(d, (int)len, a) == NULL) { if (ain == NULL) BN_free(a); return NULL; } a->neg = neg; if (neg) { BN_clear_bit(a, BN_num_bits(a) - 1); } bn_check_top(a); return a; }
./openssl/crypto/bn/rsaz_exp.h
/* * Copyright 2013-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2020, Intel Corporation. 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 * * Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) * (1) Intel Corporation, Israel Development Center, Haifa, Israel * (2) University of Haifa, Israel */ #ifndef OSSL_CRYPTO_BN_RSAZ_EXP_H # define OSSL_CRYPTO_BN_RSAZ_EXP_H # undef RSAZ_ENABLED # if defined(OPENSSL_BN_ASM_MONT) && \ (defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64)) # define RSAZ_ENABLED # include <openssl/bn.h> # include "internal/constant_time.h" # include "bn_local.h" void RSAZ_1024_mod_exp_avx2(BN_ULONG result[16], const BN_ULONG base_norm[16], const BN_ULONG exponent[16], const BN_ULONG m_norm[16], const BN_ULONG RR[16], BN_ULONG k0); int rsaz_avx2_eligible(void); void RSAZ_512_mod_exp(BN_ULONG result[8], const BN_ULONG base_norm[8], const BN_ULONG exponent[8], const BN_ULONG m_norm[8], BN_ULONG k0, const BN_ULONG RR[8]); int ossl_rsaz_avx512ifma_eligible(void); int ossl_rsaz_mod_exp_avx512_x2(BN_ULONG *res1, const BN_ULONG *base1, const BN_ULONG *exponent1, const BN_ULONG *m1, const BN_ULONG *RR1, BN_ULONG k0_1, BN_ULONG *res2, const BN_ULONG *base2, const BN_ULONG *exponent2, const BN_ULONG *m2, const BN_ULONG *RR2, BN_ULONG k0_2, int factor_size); static ossl_inline void bn_select_words(BN_ULONG *r, BN_ULONG mask, const BN_ULONG *a, const BN_ULONG *b, size_t num) { size_t i; for (i = 0; i < num; i++) { r[i] = constant_time_select_64(mask, a[i], b[i]); } } static ossl_inline BN_ULONG bn_reduce_once_in_place(BN_ULONG *r, BN_ULONG carry, const BN_ULONG *m, BN_ULONG *tmp, size_t num) { carry -= bn_sub_words(tmp, r, m, num); bn_select_words(r, carry, r /* tmp < 0 */, tmp /* tmp >= 0 */, num); return carry; } # endif #endif
./openssl/crypto/bn/bn_x931p.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 */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <openssl/bn.h> #include "bn_local.h" /* X9.31 routines for prime derivation */ /* * X9.31 prime derivation. This is used to generate the primes pi (p1, p2, * q1, q2) from a parameter Xpi by checking successive odd integers. */ static int bn_x931_derive_pi(BIGNUM *pi, const BIGNUM *Xpi, BN_CTX *ctx, BN_GENCB *cb) { int i = 0, is_prime; if (!BN_copy(pi, Xpi)) return 0; if (!BN_is_odd(pi) && !BN_add_word(pi, 1)) return 0; for (;;) { i++; BN_GENCB_call(cb, 0, i); /* NB 27 MR is specified in X9.31 */ is_prime = BN_check_prime(pi, ctx, cb); if (is_prime < 0) return 0; if (is_prime) break; if (!BN_add_word(pi, 2)) return 0; } BN_GENCB_call(cb, 2, i); return 1; } /* * This is the main X9.31 prime derivation function. From parameters Xp1, Xp2 * and Xp derive the prime p. If the parameters p1 or p2 are not NULL they * will be returned too: this is needed for testing. */ int BN_X931_derive_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, const BIGNUM *Xp, const BIGNUM *Xp1, const BIGNUM *Xp2, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0; BIGNUM *t, *p1p2, *pm1; /* Only even e supported */ if (!BN_is_odd(e)) return 0; BN_CTX_start(ctx); if (p1 == NULL) p1 = BN_CTX_get(ctx); if (p2 == NULL) p2 = BN_CTX_get(ctx); t = BN_CTX_get(ctx); p1p2 = BN_CTX_get(ctx); pm1 = BN_CTX_get(ctx); if (pm1 == NULL) goto err; if (!bn_x931_derive_pi(p1, Xp1, ctx, cb)) goto err; if (!bn_x931_derive_pi(p2, Xp2, ctx, cb)) goto err; if (!BN_mul(p1p2, p1, p2, ctx)) goto err; /* First set p to value of Rp */ if (!BN_mod_inverse(p, p2, p1, ctx)) goto err; if (!BN_mul(p, p, p2, ctx)) goto err; if (!BN_mod_inverse(t, p1, p2, ctx)) goto err; if (!BN_mul(t, t, p1, ctx)) goto err; if (!BN_sub(p, p, t)) goto err; if (p->neg && !BN_add(p, p, p1p2)) goto err; /* p now equals Rp */ if (!BN_mod_sub(p, p, Xp, p1p2, ctx)) goto err; if (!BN_add(p, p, Xp)) goto err; /* p now equals Yp0 */ for (;;) { int i = 1; BN_GENCB_call(cb, 0, i++); if (!BN_copy(pm1, p)) goto err; if (!BN_sub_word(pm1, 1)) goto err; if (!BN_gcd(t, pm1, e, ctx)) goto err; if (BN_is_one(t)) { /* * X9.31 specifies 8 MR and 1 Lucas test or any prime test * offering similar or better guarantees 50 MR is considerably * better. */ int r = BN_check_prime(p, ctx, cb); if (r < 0) goto err; if (r) break; } if (!BN_add(p, p, p1p2)) goto err; } BN_GENCB_call(cb, 3, 0); ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Generate pair of parameters Xp, Xq for X9.31 prime generation. Note: nbits * parameter is sum of number of bits in both. */ int BN_X931_generate_Xpq(BIGNUM *Xp, BIGNUM *Xq, int nbits, BN_CTX *ctx) { BIGNUM *t; int i; /* * Number of bits for each prime is of the form 512+128s for s = 0, 1, * ... */ if ((nbits < 1024) || (nbits & 0xff)) return 0; nbits >>= 1; /* * The random value Xp must be between sqrt(2) * 2^(nbits-1) and 2^nbits * - 1. By setting the top two bits we ensure that the lower bound is * exceeded. */ if (!BN_priv_rand_ex(Xp, nbits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ANY, 0, ctx)) return 0; BN_CTX_start(ctx); t = BN_CTX_get(ctx); if (t == NULL) goto err; for (i = 0; i < 1000; i++) { if (!BN_priv_rand_ex(Xq, nbits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ANY, 0, ctx)) goto err; /* Check that |Xp - Xq| > 2^(nbits - 100) */ if (!BN_sub(t, Xp, Xq)) goto err; if (BN_num_bits(t) > (nbits - 100)) break; } BN_CTX_end(ctx); if (i < 1000) return 1; return 0; err: BN_CTX_end(ctx); return 0; } /* * Generate primes using X9.31 algorithm. Of the values p, p1, p2, Xp1 and * Xp2 only 'p' needs to be non-NULL. If any of the others are not NULL the * relevant parameter will be stored in it. Due to the fact that |Xp - Xq| > * 2^(nbits - 100) must be satisfied Xp and Xq are generated using the * previous function and supplied as input. */ int BN_X931_generate_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, BIGNUM *Xp1, BIGNUM *Xp2, const BIGNUM *Xp, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0; BN_CTX_start(ctx); if (Xp1 == NULL) Xp1 = BN_CTX_get(ctx); if (Xp2 == NULL) Xp2 = BN_CTX_get(ctx); if (Xp1 == NULL || Xp2 == NULL) goto error; if (!BN_priv_rand_ex(Xp1, 101, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY, 0, ctx)) goto error; if (!BN_priv_rand_ex(Xp2, 101, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY, 0, ctx)) goto error; if (!BN_X931_derive_prime_ex(p, p1, p2, Xp, Xp1, Xp2, e, ctx, cb)) goto error; ret = 1; error: BN_CTX_end(ctx); return ret; }
./openssl/crypto/bn/bn_conv.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include "crypto/ctype.h" #include "bn_local.h" static const char Hex[] = "0123456789ABCDEF"; /* Must 'OPENSSL_free' the returned data */ char *BN_bn2hex(const BIGNUM *a) { int i, j, v, z = 0; char *buf; char *p; if (BN_is_zero(a)) return OPENSSL_strdup("0"); buf = OPENSSL_malloc(a->top * BN_BYTES * 2 + 2); if (buf == NULL) goto err; p = buf; if (a->neg) *p++ = '-'; for (i = a->top - 1; i >= 0; i--) { for (j = BN_BITS2 - 8; j >= 0; j -= 8) { /* strip leading zeros */ v = (int)((a->d[i] >> j) & 0xff); if (z || v != 0) { *p++ = Hex[v >> 4]; *p++ = Hex[v & 0x0f]; z = 1; } } } *p = '\0'; err: return buf; } #ifndef FIPS_MODULE /* No BIO_snprintf in FIPS_MODULE */ /* Must 'OPENSSL_free' the returned data */ char *BN_bn2dec(const BIGNUM *a) { int i = 0, num, ok = 0, n, tbytes; char *buf = NULL; char *p; BIGNUM *t = NULL; BN_ULONG *bn_data = NULL, *lp; int bn_data_num; /*- * get an upper bound for the length of the decimal integer * num <= (BN_num_bits(a) + 1) * log(2) * <= 3 * BN_num_bits(a) * 0.101 + log(2) + 1 (rounding error) * <= 3 * BN_num_bits(a) / 10 + 3 * BN_num_bits / 1000 + 1 + 1 */ i = BN_num_bits(a) * 3; num = (i / 10 + i / 1000 + 1) + 1; tbytes = num + 3; /* negative and terminator and one spare? */ bn_data_num = num / BN_DEC_NUM + 1; bn_data = OPENSSL_malloc(bn_data_num * sizeof(BN_ULONG)); buf = OPENSSL_malloc(tbytes); if (buf == NULL || bn_data == NULL) goto err; if ((t = BN_dup(a)) == NULL) goto err; p = buf; lp = bn_data; if (BN_is_zero(t)) { *p++ = '0'; *p++ = '\0'; } else { if (BN_is_negative(t)) *p++ = '-'; while (!BN_is_zero(t)) { if (lp - bn_data >= bn_data_num) goto err; *lp = BN_div_word(t, BN_DEC_CONV); if (*lp == (BN_ULONG)-1) goto err; lp++; } lp--; /* * We now have a series of blocks, BN_DEC_NUM chars in length, where * the last one needs truncation. The blocks need to be reversed in * order. */ n = BIO_snprintf(p, tbytes - (size_t)(p - buf), BN_DEC_FMT1, *lp); if (n < 0) goto err; p += n; while (lp != bn_data) { lp--; n = BIO_snprintf(p, tbytes - (size_t)(p - buf), BN_DEC_FMT2, *lp); if (n < 0) goto err; p += n; } } ok = 1; err: OPENSSL_free(bn_data); BN_free(t); if (ok) return buf; OPENSSL_free(buf); return NULL; } #endif int BN_hex2bn(BIGNUM **bn, const char *a) { BIGNUM *ret = NULL; BN_ULONG l = 0; int neg = 0, h, m, i, j, k, c; int num; if (a == NULL || *a == '\0') return 0; if (*a == '-') { neg = 1; a++; } for (i = 0; i <= INT_MAX / 4 && ossl_isxdigit(a[i]); i++) continue; if (i == 0 || i > INT_MAX / 4) return 0; num = i + neg; if (bn == NULL) return num; /* a is the start of the hex digits, and it is 'i' long */ if (*bn == NULL) { if ((ret = BN_new()) == NULL) return 0; } else { ret = *bn; if (BN_get_flags(ret, BN_FLG_STATIC_DATA)) { ERR_raise(ERR_LIB_BN, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } BN_zero(ret); } /* i is the number of hex digits */ if (bn_expand(ret, i * 4) == NULL) goto err; j = i; /* least significant 'hex' */ m = 0; h = 0; while (j > 0) { m = (BN_BYTES * 2 <= j) ? BN_BYTES * 2 : j; l = 0; for (;;) { c = a[j - m]; k = OPENSSL_hexchar2int(c); if (k < 0) k = 0; /* paranoia */ l = (l << 4) | k; if (--m <= 0) { ret->d[h++] = l; break; } } j -= BN_BYTES * 2; } ret->top = h; bn_correct_top(ret); *bn = ret; bn_check_top(ret); /* Don't set the negative flag if it's zero. */ if (ret->top != 0) ret->neg = neg; return num; err: if (*bn == NULL) BN_free(ret); return 0; } int BN_dec2bn(BIGNUM **bn, const char *a) { BIGNUM *ret = NULL; BN_ULONG l = 0; int neg = 0, i, j; int num; if (a == NULL || *a == '\0') return 0; if (*a == '-') { neg = 1; a++; } for (i = 0; i <= INT_MAX / 4 && ossl_isdigit(a[i]); i++) continue; if (i == 0 || i > INT_MAX / 4) goto err; num = i + neg; if (bn == NULL) return num; /* * a is the start of the digits, and it is 'i' long. We chop it into * BN_DEC_NUM digits at a time */ if (*bn == NULL) { if ((ret = BN_new()) == NULL) return 0; } else { ret = *bn; BN_zero(ret); } /* i is the number of digits, a bit of an over expand */ if (bn_expand(ret, i * 4) == NULL) goto err; j = BN_DEC_NUM - i % BN_DEC_NUM; if (j == BN_DEC_NUM) j = 0; l = 0; while (--i >= 0) { l *= 10; l += *a - '0'; a++; if (++j == BN_DEC_NUM) { if (!BN_mul_word(ret, BN_DEC_CONV) || !BN_add_word(ret, l)) goto err; l = 0; j = 0; } } bn_correct_top(ret); *bn = ret; bn_check_top(ret); /* Don't set the negative flag if it's zero. */ if (ret->top != 0) ret->neg = neg; return num; err: if (*bn == NULL) BN_free(ret); return 0; } int BN_asc2bn(BIGNUM **bn, const char *a) { const char *p = a; if (*p == '-') p++; if (p[0] == '0' && (p[1] == 'X' || p[1] == 'x')) { if (!BN_hex2bn(bn, p + 2)) return 0; } else { if (!BN_dec2bn(bn, p)) return 0; } /* Don't set the negative flag if it's zero. */ if (*a == '-' && (*bn)->top != 0) (*bn)->neg = 1; return 1; }
./openssl/crypto/bn/bn_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/bnerr.h> #include "crypto/bnerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA BN_str_reasons[] = { {ERR_PACK(ERR_LIB_BN, 0, BN_R_ARG2_LT_ARG3), "arg2 lt arg3"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_BAD_RECIPROCAL), "bad reciprocal"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_BIGNUM_TOO_LONG), "bignum too long"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_BITS_TOO_SMALL), "bits too small"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_CALLED_WITH_EVEN_MODULUS), "called with even modulus"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_DIV_BY_ZERO), "div by zero"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_ENCODING_ERROR), "encoding error"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_EXPAND_ON_STATIC_BIGNUM_DATA), "expand on static bignum data"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_INPUT_NOT_REDUCED), "input not reduced"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_INVALID_LENGTH), "invalid length"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_INVALID_RANGE), "invalid range"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_INVALID_SHIFT), "invalid shift"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NOT_A_SQUARE), "not a square"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NOT_INITIALIZED), "not initialized"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NO_INVERSE), "no inverse"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NO_PRIME_CANDIDATE), "no prime candidate"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NO_SOLUTION), "no solution"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NO_SUITABLE_DIGEST), "no suitable digest"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_PRIVATE_KEY_TOO_LARGE), "private key too large"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_P_IS_NOT_PRIME), "p is not prime"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_TOO_MANY_ITERATIONS), "too many iterations"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_TOO_MANY_TEMPORARY_VARIABLES), "too many temporary variables"}, {0, NULL} }; #endif int ossl_err_load_BN_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(BN_str_reasons[0].error) == NULL) ERR_load_strings_const(BN_str_reasons); #endif return 1; }
./openssl/crypto/bn/bn_gcd.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include "bn_local.h" /* * bn_mod_inverse_no_branch is a special version of BN_mod_inverse. It does * not contain branches that may leak sensitive information. * * This is a static function, we ensure all callers in this file pass valid * arguments: all passed pointers here are non-NULL. */ static ossl_inline BIGNUM *bn_mod_inverse_no_branch(BIGNUM *in, const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx, int *pnoinv) { BIGNUM *A, *B, *X, *Y, *M, *D, *T, *R = NULL; BIGNUM *ret = NULL; int sign; bn_check_top(a); bn_check_top(n); BN_CTX_start(ctx); A = BN_CTX_get(ctx); B = BN_CTX_get(ctx); X = BN_CTX_get(ctx); D = BN_CTX_get(ctx); M = BN_CTX_get(ctx); Y = BN_CTX_get(ctx); T = BN_CTX_get(ctx); if (T == NULL) goto err; if (in == NULL) R = BN_new(); else R = in; if (R == NULL) goto err; if (!BN_one(X)) goto err; BN_zero(Y); if (BN_copy(B, a) == NULL) goto err; if (BN_copy(A, n) == NULL) goto err; A->neg = 0; if (B->neg || (BN_ucmp(B, A) >= 0)) { /* * Turn BN_FLG_CONSTTIME flag on, so that when BN_div is invoked, * BN_div_no_branch will be called eventually. */ { BIGNUM local_B; bn_init(&local_B); BN_with_flags(&local_B, B, BN_FLG_CONSTTIME); if (!BN_nnmod(B, &local_B, A, ctx)) goto err; /* Ensure local_B goes out of scope before any further use of B */ } } sign = -1; /*- * From B = a mod |n|, A = |n| it follows that * * 0 <= B < A, * -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|). */ while (!BN_is_zero(B)) { BIGNUM *tmp; /*- * 0 < B < A, * (*) -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|) */ /* * Turn BN_FLG_CONSTTIME flag on, so that when BN_div is invoked, * BN_div_no_branch will be called eventually. */ { BIGNUM local_A; bn_init(&local_A); BN_with_flags(&local_A, A, BN_FLG_CONSTTIME); /* (D, M) := (A/B, A%B) ... */ if (!BN_div(D, M, &local_A, B, ctx)) goto err; /* Ensure local_A goes out of scope before any further use of A */ } /*- * Now * A = D*B + M; * thus we have * (**) sign*Y*a == D*B + M (mod |n|). */ tmp = A; /* keep the BIGNUM object, the value does not * matter */ /* (A, B) := (B, A mod B) ... */ A = B; B = M; /* ... so we have 0 <= B < A again */ /*- * Since the former M is now B and the former B is now A, * (**) translates into * sign*Y*a == D*A + B (mod |n|), * i.e. * sign*Y*a - D*A == B (mod |n|). * Similarly, (*) translates into * -sign*X*a == A (mod |n|). * * Thus, * sign*Y*a + D*sign*X*a == B (mod |n|), * i.e. * sign*(Y + D*X)*a == B (mod |n|). * * So if we set (X, Y, sign) := (Y + D*X, X, -sign), we arrive back at * -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|). * Note that X and Y stay non-negative all the time. */ if (!BN_mul(tmp, D, X, ctx)) goto err; if (!BN_add(tmp, tmp, Y)) goto err; M = Y; /* keep the BIGNUM object, the value does not * matter */ Y = X; X = tmp; sign = -sign; } /*- * The while loop (Euclid's algorithm) ends when * A == gcd(a,n); * we have * sign*Y*a == A (mod |n|), * where Y is non-negative. */ if (sign < 0) { if (!BN_sub(Y, n, Y)) goto err; } /* Now Y*a == A (mod |n|). */ if (BN_is_one(A)) { /* Y*a == 1 (mod |n|) */ if (!Y->neg && BN_ucmp(Y, n) < 0) { if (!BN_copy(R, Y)) goto err; } else { if (!BN_nnmod(R, Y, n, ctx)) goto err; } } else { *pnoinv = 1; /* caller sets the BN_R_NO_INVERSE error */ goto err; } ret = R; *pnoinv = 0; err: if ((ret == NULL) && (in == NULL)) BN_free(R); BN_CTX_end(ctx); bn_check_top(ret); return ret; } /* * This is an internal function, we assume all callers pass valid arguments: * all pointers passed here are assumed non-NULL. */ BIGNUM *int_bn_mod_inverse(BIGNUM *in, const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx, int *pnoinv) { BIGNUM *A, *B, *X, *Y, *M, *D, *T, *R = NULL; BIGNUM *ret = NULL; int sign; /* This is invalid input so we don't worry about constant time here */ if (BN_abs_is_word(n, 1) || BN_is_zero(n)) { *pnoinv = 1; return NULL; } *pnoinv = 0; if ((BN_get_flags(a, BN_FLG_CONSTTIME) != 0) || (BN_get_flags(n, BN_FLG_CONSTTIME) != 0)) { return bn_mod_inverse_no_branch(in, a, n, ctx, pnoinv); } bn_check_top(a); bn_check_top(n); BN_CTX_start(ctx); A = BN_CTX_get(ctx); B = BN_CTX_get(ctx); X = BN_CTX_get(ctx); D = BN_CTX_get(ctx); M = BN_CTX_get(ctx); Y = BN_CTX_get(ctx); T = BN_CTX_get(ctx); if (T == NULL) goto err; if (in == NULL) R = BN_new(); else R = in; if (R == NULL) goto err; if (!BN_one(X)) goto err; BN_zero(Y); if (BN_copy(B, a) == NULL) goto err; if (BN_copy(A, n) == NULL) goto err; A->neg = 0; if (B->neg || (BN_ucmp(B, A) >= 0)) { if (!BN_nnmod(B, B, A, ctx)) goto err; } sign = -1; /*- * From B = a mod |n|, A = |n| it follows that * * 0 <= B < A, * -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|). */ if (BN_is_odd(n) && (BN_num_bits(n) <= 2048)) { /* * Binary inversion algorithm; requires odd modulus. This is faster * than the general algorithm if the modulus is sufficiently small * (about 400 .. 500 bits on 32-bit systems, but much more on 64-bit * systems) */ int shift; while (!BN_is_zero(B)) { /*- * 0 < B < |n|, * 0 < A <= |n|, * (1) -sign*X*a == B (mod |n|), * (2) sign*Y*a == A (mod |n|) */ /* * Now divide B by the maximum possible power of two in the * integers, and divide X by the same value mod |n|. When we're * done, (1) still holds. */ shift = 0; while (!BN_is_bit_set(B, shift)) { /* note that 0 < B */ shift++; if (BN_is_odd(X)) { if (!BN_uadd(X, X, n)) goto err; } /* * now X is even, so we can easily divide it by two */ if (!BN_rshift1(X, X)) goto err; } if (shift > 0) { if (!BN_rshift(B, B, shift)) goto err; } /* * Same for A and Y. Afterwards, (2) still holds. */ shift = 0; while (!BN_is_bit_set(A, shift)) { /* note that 0 < A */ shift++; if (BN_is_odd(Y)) { if (!BN_uadd(Y, Y, n)) goto err; } /* now Y is even */ if (!BN_rshift1(Y, Y)) goto err; } if (shift > 0) { if (!BN_rshift(A, A, shift)) goto err; } /*- * We still have (1) and (2). * Both A and B are odd. * The following computations ensure that * * 0 <= B < |n|, * 0 < A < |n|, * (1) -sign*X*a == B (mod |n|), * (2) sign*Y*a == A (mod |n|), * * and that either A or B is even in the next iteration. */ if (BN_ucmp(B, A) >= 0) { /* -sign*(X + Y)*a == B - A (mod |n|) */ if (!BN_uadd(X, X, Y)) goto err; /* * NB: we could use BN_mod_add_quick(X, X, Y, n), but that * actually makes the algorithm slower */ if (!BN_usub(B, B, A)) goto err; } else { /* sign*(X + Y)*a == A - B (mod |n|) */ if (!BN_uadd(Y, Y, X)) goto err; /* * as above, BN_mod_add_quick(Y, Y, X, n) would slow things down */ if (!BN_usub(A, A, B)) goto err; } } } else { /* general inversion algorithm */ while (!BN_is_zero(B)) { BIGNUM *tmp; /*- * 0 < B < A, * (*) -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|) */ /* (D, M) := (A/B, A%B) ... */ if (BN_num_bits(A) == BN_num_bits(B)) { if (!BN_one(D)) goto err; if (!BN_sub(M, A, B)) goto err; } else if (BN_num_bits(A) == BN_num_bits(B) + 1) { /* A/B is 1, 2, or 3 */ if (!BN_lshift1(T, B)) goto err; if (BN_ucmp(A, T) < 0) { /* A < 2*B, so D=1 */ if (!BN_one(D)) goto err; if (!BN_sub(M, A, B)) goto err; } else { /* A >= 2*B, so D=2 or D=3 */ if (!BN_sub(M, A, T)) goto err; if (!BN_add(D, T, B)) goto err; /* use D (:= 3*B) as temp */ if (BN_ucmp(A, D) < 0) { /* A < 3*B, so D=2 */ if (!BN_set_word(D, 2)) goto err; /* * M (= A - 2*B) already has the correct value */ } else { /* only D=3 remains */ if (!BN_set_word(D, 3)) goto err; /* * currently M = A - 2*B, but we need M = A - 3*B */ if (!BN_sub(M, M, B)) goto err; } } } else { if (!BN_div(D, M, A, B, ctx)) goto err; } /*- * Now * A = D*B + M; * thus we have * (**) sign*Y*a == D*B + M (mod |n|). */ tmp = A; /* keep the BIGNUM object, the value does not matter */ /* (A, B) := (B, A mod B) ... */ A = B; B = M; /* ... so we have 0 <= B < A again */ /*- * Since the former M is now B and the former B is now A, * (**) translates into * sign*Y*a == D*A + B (mod |n|), * i.e. * sign*Y*a - D*A == B (mod |n|). * Similarly, (*) translates into * -sign*X*a == A (mod |n|). * * Thus, * sign*Y*a + D*sign*X*a == B (mod |n|), * i.e. * sign*(Y + D*X)*a == B (mod |n|). * * So if we set (X, Y, sign) := (Y + D*X, X, -sign), we arrive back at * -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|). * Note that X and Y stay non-negative all the time. */ /* * most of the time D is very small, so we can optimize tmp := D*X+Y */ if (BN_is_one(D)) { if (!BN_add(tmp, X, Y)) goto err; } else { if (BN_is_word(D, 2)) { if (!BN_lshift1(tmp, X)) goto err; } else if (BN_is_word(D, 4)) { if (!BN_lshift(tmp, X, 2)) goto err; } else if (D->top == 1) { if (!BN_copy(tmp, X)) goto err; if (!BN_mul_word(tmp, D->d[0])) goto err; } else { if (!BN_mul(tmp, D, X, ctx)) goto err; } if (!BN_add(tmp, tmp, Y)) goto err; } M = Y; /* keep the BIGNUM object, the value does not matter */ Y = X; X = tmp; sign = -sign; } } /*- * The while loop (Euclid's algorithm) ends when * A == gcd(a,n); * we have * sign*Y*a == A (mod |n|), * where Y is non-negative. */ if (sign < 0) { if (!BN_sub(Y, n, Y)) goto err; } /* Now Y*a == A (mod |n|). */ if (BN_is_one(A)) { /* Y*a == 1 (mod |n|) */ if (!Y->neg && BN_ucmp(Y, n) < 0) { if (!BN_copy(R, Y)) goto err; } else { if (!BN_nnmod(R, Y, n, ctx)) goto err; } } else { *pnoinv = 1; goto err; } ret = R; err: if ((ret == NULL) && (in == NULL)) BN_free(R); BN_CTX_end(ctx); bn_check_top(ret); return ret; } /* solves ax == 1 (mod n) */ BIGNUM *BN_mod_inverse(BIGNUM *in, const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx) { BN_CTX *new_ctx = NULL; BIGNUM *rv; int noinv = 0; if (ctx == NULL) { ctx = new_ctx = BN_CTX_new_ex(NULL); if (ctx == NULL) { ERR_raise(ERR_LIB_BN, ERR_R_BN_LIB); return NULL; } } rv = int_bn_mod_inverse(in, a, n, ctx, &noinv); if (noinv) ERR_raise(ERR_LIB_BN, BN_R_NO_INVERSE); BN_CTX_free(new_ctx); return rv; } /* * The numbers a and b are coprime if the only positive integer that is a * divisor of both of them is 1. * i.e. gcd(a,b) = 1. * * Coprimes have the property: b has a multiplicative inverse modulo a * i.e there is some value x such that bx = 1 (mod a). * * Testing the modulo inverse is currently much faster than the constant * time version of BN_gcd(). */ int BN_are_coprime(BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; BIGNUM *tmp; BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) goto end; ERR_set_mark(); BN_set_flags(a, BN_FLG_CONSTTIME); ret = (BN_mod_inverse(tmp, a, b, ctx) != NULL); /* Clear any errors (an error is returned if there is no inverse) */ ERR_pop_to_mark(); end: BN_CTX_end(ctx); return ret; } /*- * This function is based on the constant-time GCD work by Bernstein and Yang: * https://eprint.iacr.org/2019/266 * Generalized fast GCD function to allow even inputs. * The algorithm first finds the shared powers of 2 between * the inputs, and removes them, reducing at least one of the * inputs to an odd value. Then it proceeds to calculate the GCD. * Before returning the resulting GCD, we take care of adding * back the powers of two removed at the beginning. * Note 1: we assume the bit length of both inputs is public information, * since access to top potentially leaks this information. */ int BN_gcd(BIGNUM *r, const BIGNUM *in_a, const BIGNUM *in_b, BN_CTX *ctx) { BIGNUM *g, *temp = NULL; BN_ULONG mask = 0; int i, j, top, rlen, glen, m, bit = 1, delta = 1, cond = 0, shifts = 0, ret = 0; /* Note 2: zero input corner cases are not constant-time since they are * handled immediately. An attacker can run an attack under this * assumption without the need of side-channel information. */ if (BN_is_zero(in_b)) { ret = BN_copy(r, in_a) != NULL; r->neg = 0; return ret; } if (BN_is_zero(in_a)) { ret = BN_copy(r, in_b) != NULL; r->neg = 0; return ret; } bn_check_top(in_a); bn_check_top(in_b); BN_CTX_start(ctx); temp = BN_CTX_get(ctx); g = BN_CTX_get(ctx); /* make r != 0, g != 0 even, so BN_rshift is not a potential nop */ if (g == NULL || !BN_lshift1(g, in_b) || !BN_lshift1(r, in_a)) goto err; /* find shared powers of two, i.e. "shifts" >= 1 */ for (i = 0; i < r->dmax && i < g->dmax; i++) { mask = ~(r->d[i] | g->d[i]); for (j = 0; j < BN_BITS2; j++) { bit &= mask; shifts += bit; mask >>= 1; } } /* subtract shared powers of two; shifts >= 1 */ if (!BN_rshift(r, r, shifts) || !BN_rshift(g, g, shifts)) goto err; /* expand to biggest nword, with room for a possible extra word */ top = 1 + ((r->top >= g->top) ? r->top : g->top); if (bn_wexpand(r, top) == NULL || bn_wexpand(g, top) == NULL || bn_wexpand(temp, top) == NULL) goto err; /* re arrange inputs s.t. r is odd */ BN_consttime_swap((~r->d[0]) & 1, r, g, top); /* compute the number of iterations */ rlen = BN_num_bits(r); glen = BN_num_bits(g); m = 4 + 3 * ((rlen >= glen) ? rlen : glen); for (i = 0; i < m; i++) { /* conditionally flip signs if delta is positive and g is odd */ cond = ((unsigned int)-delta >> (8 * sizeof(delta) - 1)) & g->d[0] & 1 /* make sure g->top > 0 (i.e. if top == 0 then g == 0 always) */ & (~((unsigned int)(g->top - 1) >> (sizeof(g->top) * 8 - 1))); delta = (-cond & -delta) | ((cond - 1) & delta); r->neg ^= cond; /* swap */ BN_consttime_swap(cond, r, g, top); /* elimination step */ delta++; if (!BN_add(temp, g, r)) goto err; BN_consttime_swap(g->d[0] & 1 /* g is odd */ /* make sure g->top > 0 (i.e. if top == 0 then g == 0 always) */ & (~((unsigned int)(g->top - 1) >> (sizeof(g->top) * 8 - 1))), g, temp, top); if (!BN_rshift1(g, g)) goto err; } /* remove possible negative sign */ r->neg = 0; /* add powers of 2 removed, then correct the artificial shift */ if (!BN_lshift(r, r, shifts) || !BN_rshift1(r, r)) goto err; ret = 1; err: BN_CTX_end(ctx); bn_check_top(r); return ret; }
./openssl/crypto/bn/rsaz_exp.c
/* * Copyright 2013-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2012, Intel Corporation. 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 * * Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) * (1) Intel Corporation, Israel Development Center, Haifa, Israel * (2) University of Haifa, Israel */ #include <openssl/opensslconf.h> #include "internal/common.h" #include "rsaz_exp.h" #ifndef RSAZ_ENABLED NON_EMPTY_TRANSLATION_UNIT #else /* * See crypto/bn/asm/rsaz-avx2.pl for further details. */ void rsaz_1024_norm2red_avx2(void *red, const void *norm); void rsaz_1024_mul_avx2(void *ret, const void *a, const void *b, const void *n, BN_ULONG k); void rsaz_1024_sqr_avx2(void *ret, const void *a, const void *n, BN_ULONG k, int cnt); void rsaz_1024_scatter5_avx2(void *tbl, const void *val, int i); void rsaz_1024_gather5_avx2(void *val, const void *tbl, int i); void rsaz_1024_red2norm_avx2(void *norm, const void *red); #if defined(__SUNPRO_C) # pragma align 64(one,two80) #endif ALIGN64 static const BN_ULONG one[40] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; ALIGN64 static const BN_ULONG two80[40] = { 0, 0, 1 << 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; void RSAZ_1024_mod_exp_avx2(BN_ULONG result_norm[16], const BN_ULONG base_norm[16], const BN_ULONG exponent[16], const BN_ULONG m_norm[16], const BN_ULONG RR[16], BN_ULONG k0) { unsigned char storage[320 * 3 + 32 * 9 * 16 + 64]; /* 5.5KB */ unsigned char *p_str = storage + (64 - ((size_t)storage % 64)); unsigned char *a_inv, *m, *result; unsigned char *table_s = p_str + 320 * 3; unsigned char *R2 = table_s; /* borrow */ int index; int wvalue; BN_ULONG tmp[16]; if ((((size_t)p_str & 4095) + 320) >> 12) { result = p_str; a_inv = p_str + 320; m = p_str + 320 * 2; /* should not cross page */ } else { m = p_str; /* should not cross page */ result = p_str + 320; a_inv = p_str + 320 * 2; } rsaz_1024_norm2red_avx2(m, m_norm); rsaz_1024_norm2red_avx2(a_inv, base_norm); rsaz_1024_norm2red_avx2(R2, RR); rsaz_1024_mul_avx2(R2, R2, R2, m, k0); rsaz_1024_mul_avx2(R2, R2, two80, m, k0); /* table[0] = 1 */ rsaz_1024_mul_avx2(result, R2, one, m, k0); /* table[1] = a_inv^1 */ rsaz_1024_mul_avx2(a_inv, a_inv, R2, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 0); rsaz_1024_scatter5_avx2(table_s, a_inv, 1); /* table[2] = a_inv^2 */ rsaz_1024_sqr_avx2(result, a_inv, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 2); #if 0 /* this is almost 2x smaller and less than 1% slower */ for (index = 3; index < 32; index++) { rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, index); } #else /* table[4] = a_inv^4 */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 4); /* table[8] = a_inv^8 */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 8); /* table[16] = a_inv^16 */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 16); /* table[17] = a_inv^17 */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 17); /* table[3] */ rsaz_1024_gather5_avx2(result, table_s, 2); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 3); /* table[6] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 6); /* table[12] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 12); /* table[24] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 24); /* table[25] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 25); /* table[5] */ rsaz_1024_gather5_avx2(result, table_s, 4); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 5); /* table[10] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 10); /* table[20] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 20); /* table[21] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 21); /* table[7] */ rsaz_1024_gather5_avx2(result, table_s, 6); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 7); /* table[14] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 14); /* table[28] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 28); /* table[29] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 29); /* table[9] */ rsaz_1024_gather5_avx2(result, table_s, 8); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 9); /* table[18] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 18); /* table[19] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 19); /* table[11] */ rsaz_1024_gather5_avx2(result, table_s, 10); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 11); /* table[22] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 22); /* table[23] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 23); /* table[13] */ rsaz_1024_gather5_avx2(result, table_s, 12); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 13); /* table[26] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 26); /* table[27] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 27); /* table[15] */ rsaz_1024_gather5_avx2(result, table_s, 14); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 15); /* table[30] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 30); /* table[31] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 31); #endif /* load first window */ p_str = (unsigned char *)exponent; wvalue = p_str[127] >> 3; rsaz_1024_gather5_avx2(result, table_s, wvalue); index = 1014; while (index > -1) { /* loop for the remaining 127 windows */ rsaz_1024_sqr_avx2(result, result, m, k0, 5); wvalue = (p_str[(index / 8) + 1] << 8) | p_str[index / 8]; wvalue = (wvalue >> (index % 8)) & 31; index -= 5; rsaz_1024_gather5_avx2(a_inv, table_s, wvalue); /* borrow a_inv */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); } /* square four times */ rsaz_1024_sqr_avx2(result, result, m, k0, 4); wvalue = p_str[0] & 15; rsaz_1024_gather5_avx2(a_inv, table_s, wvalue); /* borrow a_inv */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); /* from Montgomery */ rsaz_1024_mul_avx2(result, result, one, m, k0); rsaz_1024_red2norm_avx2(result_norm, result); bn_reduce_once_in_place(result_norm, /*carry=*/0, m_norm, tmp, 16); OPENSSL_cleanse(storage, sizeof(storage)); OPENSSL_cleanse(tmp, sizeof(tmp)); } /* * See crypto/bn/rsaz-x86_64.pl for further details. */ void rsaz_512_mul(void *ret, const void *a, const void *b, const void *n, BN_ULONG k); void rsaz_512_mul_scatter4(void *ret, const void *a, const void *n, BN_ULONG k, const void *tbl, unsigned int power); void rsaz_512_mul_gather4(void *ret, const void *a, const void *tbl, const void *n, BN_ULONG k, unsigned int power); void rsaz_512_mul_by_one(void *ret, const void *a, const void *n, BN_ULONG k); void rsaz_512_sqr(void *ret, const void *a, const void *n, BN_ULONG k, int cnt); void rsaz_512_scatter4(void *tbl, const BN_ULONG *val, int power); void rsaz_512_gather4(BN_ULONG *val, const void *tbl, int power); void RSAZ_512_mod_exp(BN_ULONG result[8], const BN_ULONG base[8], const BN_ULONG exponent[8], const BN_ULONG m[8], BN_ULONG k0, const BN_ULONG RR[8]) { unsigned char storage[16 * 8 * 8 + 64 * 2 + 64]; /* 1.2KB */ unsigned char *table = storage + (64 - ((size_t)storage % 64)); BN_ULONG *a_inv = (BN_ULONG *)(table + 16 * 8 * 8); BN_ULONG *temp = (BN_ULONG *)(table + 16 * 8 * 8 + 8 * 8); unsigned char *p_str = (unsigned char *)exponent; int index; unsigned int wvalue; BN_ULONG tmp[8]; /* table[0] = 1_inv */ temp[0] = 0 - m[0]; temp[1] = ~m[1]; temp[2] = ~m[2]; temp[3] = ~m[3]; temp[4] = ~m[4]; temp[5] = ~m[5]; temp[6] = ~m[6]; temp[7] = ~m[7]; rsaz_512_scatter4(table, temp, 0); /* table [1] = a_inv^1 */ rsaz_512_mul(a_inv, base, RR, m, k0); rsaz_512_scatter4(table, a_inv, 1); /* table [2] = a_inv^2 */ rsaz_512_sqr(temp, a_inv, m, k0, 1); rsaz_512_scatter4(table, temp, 2); for (index = 3; index < 16; index++) rsaz_512_mul_scatter4(temp, a_inv, m, k0, table, index); /* load first window */ wvalue = p_str[63]; rsaz_512_gather4(temp, table, wvalue >> 4); rsaz_512_sqr(temp, temp, m, k0, 4); rsaz_512_mul_gather4(temp, temp, table, m, k0, wvalue & 0xf); for (index = 62; index >= 0; index--) { wvalue = p_str[index]; rsaz_512_sqr(temp, temp, m, k0, 4); rsaz_512_mul_gather4(temp, temp, table, m, k0, wvalue >> 4); rsaz_512_sqr(temp, temp, m, k0, 4); rsaz_512_mul_gather4(temp, temp, table, m, k0, wvalue & 0x0f); } /* from Montgomery */ rsaz_512_mul_by_one(result, temp, m, k0); bn_reduce_once_in_place(result, /*carry=*/0, m, tmp, 8); OPENSSL_cleanse(storage, sizeof(storage)); OPENSSL_cleanse(tmp, sizeof(tmp)); } #endif
./openssl/crypto/bn/bn_word.c
/* * 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 */ #include "internal/cryptlib.h" #include "bn_local.h" BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w) { #ifndef BN_LLONG BN_ULONG ret = 0; #else BN_ULLONG ret = 0; #endif int i; if (w == 0) return (BN_ULONG)-1; #ifndef BN_LLONG /* * If |w| is too long and we don't have BN_ULLONG then we need to fall * back to using BN_div_word */ if (w > ((BN_ULONG)1 << BN_BITS4)) { BIGNUM *tmp = BN_dup(a); if (tmp == NULL) return (BN_ULONG)-1; ret = BN_div_word(tmp, w); BN_free(tmp); return ret; } #endif bn_check_top(a); w &= BN_MASK2; for (i = a->top - 1; i >= 0; i--) { #ifndef BN_LLONG /* * We can assume here that | w <= ((BN_ULONG)1 << BN_BITS4) | and so * | ret < ((BN_ULONG)1 << BN_BITS4) | and therefore the shifts here are * safe and will not overflow */ ret = ((ret << BN_BITS4) | ((a->d[i] >> BN_BITS4) & BN_MASK2l)) % w; ret = ((ret << BN_BITS4) | (a->d[i] & BN_MASK2l)) % w; #else ret = (BN_ULLONG) (((ret << (BN_ULLONG) BN_BITS2) | a->d[i]) % (BN_ULLONG) w); #endif } return (BN_ULONG)ret; } BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) { BN_ULONG ret = 0; int i, j; bn_check_top(a); w &= BN_MASK2; if (!w) /* actually this an error (division by zero) */ return (BN_ULONG)-1; if (a->top == 0) return 0; /* normalize input (so bn_div_words doesn't complain) */ j = BN_BITS2 - BN_num_bits_word(w); w <<= j; if (!BN_lshift(a, a, j)) return (BN_ULONG)-1; for (i = a->top - 1; i >= 0; i--) { BN_ULONG l, d; l = a->d[i]; d = bn_div_words(ret, l, w); ret = (l - ((d * w) & BN_MASK2)) & BN_MASK2; a->d[i] = d; } if ((a->top > 0) && (a->d[a->top - 1] == 0)) a->top--; ret >>= j; if (!a->top) a->neg = 0; /* don't allow negative zero */ bn_check_top(a); return ret; } int BN_add_word(BIGNUM *a, BN_ULONG w) { BN_ULONG l; int i; bn_check_top(a); w &= BN_MASK2; /* degenerate case: w is zero */ if (!w) return 1; /* degenerate case: a is zero */ if (BN_is_zero(a)) return BN_set_word(a, w); /* handle 'a' when negative */ if (a->neg) { a->neg = 0; i = BN_sub_word(a, w); if (!BN_is_zero(a)) a->neg = !(a->neg); return i; } for (i = 0; w != 0 && i < a->top; i++) { a->d[i] = l = (a->d[i] + w) & BN_MASK2; w = (w > l) ? 1 : 0; } if (w && i == a->top) { if (bn_wexpand(a, a->top + 1) == NULL) return 0; a->top++; a->d[i] = w; } bn_check_top(a); return 1; } int BN_sub_word(BIGNUM *a, BN_ULONG w) { int i; bn_check_top(a); w &= BN_MASK2; /* degenerate case: w is zero */ if (!w) return 1; /* degenerate case: a is zero */ if (BN_is_zero(a)) { i = BN_set_word(a, w); if (i != 0) BN_set_negative(a, 1); return i; } /* handle 'a' when negative */ if (a->neg) { a->neg = 0; i = BN_add_word(a, w); a->neg = 1; return i; } if ((a->top == 1) && (a->d[0] < w)) { a->d[0] = w - a->d[0]; a->neg = 1; return 1; } i = 0; for (;;) { if (a->d[i] >= w) { a->d[i] -= w; break; } else { a->d[i] = (a->d[i] - w) & BN_MASK2; i++; w = 1; } } if ((a->d[i] == 0) && (i == (a->top - 1))) a->top--; bn_check_top(a); return 1; } int BN_mul_word(BIGNUM *a, BN_ULONG w) { BN_ULONG ll; bn_check_top(a); w &= BN_MASK2; if (a->top) { if (w == 0) BN_zero(a); else { ll = bn_mul_words(a->d, a->d, a->top, w); if (ll) { if (bn_wexpand(a, a->top + 1) == NULL) return 0; a->d[a->top++] = ll; } } } bn_check_top(a); return 1; }
./openssl/crypto/bn/bn_s390x.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "crypto/bn.h" #include "crypto/s390x_arch.h" #ifdef S390X_MOD_EXP # include <sys/types.h> # include <sys/stat.h> # include <fcntl.h> # include <asm/zcrypt.h> # include <sys/ioctl.h> # include <unistd.h> # include <errno.h> static int s390x_mod_exp_hw(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m) { struct ica_rsa_modexpo me; unsigned char *buffer; size_t size; int res = 0; if (OPENSSL_s390xcex == -1) return 0; size = BN_num_bytes(m); buffer = OPENSSL_zalloc(4 * size); if (buffer == NULL) return 0; me.inputdata = buffer; me.inputdatalength = size; me.outputdata = buffer + size; me.outputdatalength = size; me.b_key = buffer + 2 * size; me.n_modulus = buffer + 3 * size; if (BN_bn2binpad(a, me.inputdata, size) == -1 || BN_bn2binpad(p, me.b_key, size) == -1 || BN_bn2binpad(m, me.n_modulus, size) == -1) goto dealloc; if (ioctl(OPENSSL_s390xcex, ICARSAMODEXPO, &me) != -1) { if (BN_bin2bn(me.outputdata, size, r) != NULL) res = 1; } else if (errno == EBADF) { /*- * In this cases, someone (e.g. a sandbox) closed the fd. * Make sure to not further use this hardware acceleration. */ OPENSSL_s390xcex = -1; } dealloc: OPENSSL_clear_free(buffer, 4 * size); return res; } int s390x_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { if (s390x_mod_exp_hw(r, a, p, m) == 1) return 1; return BN_mod_exp_mont(r, a, p, m, ctx, m_ctx); } int s390x_crt(BIGNUM *r, const BIGNUM *i, const BIGNUM *p, const BIGNUM *q, const BIGNUM *dmp, const BIGNUM *dmq, const BIGNUM *iqmp) { struct ica_rsa_modexpo_crt crt; unsigned char *buffer, *part; size_t size, plen, qlen; int res = 0; if (OPENSSL_s390xcex == -1) return 0; /*- * Hardware-accelerated CRT can only deal with p>q. Fall back to * software in the (hopefully rare) other cases. */ if (BN_ucmp(p, q) != 1) return 0; plen = BN_num_bytes(p); qlen = BN_num_bytes(q); size = (plen > qlen ? plen : qlen); buffer = OPENSSL_zalloc(9 * size + 24); if (buffer == NULL) return 0; part = buffer; crt.inputdata = part; crt.inputdatalength = 2 * size; part += 2 * size; crt.outputdata = part; crt.outputdatalength = 2 * size; part += 2 * size; crt.bp_key = part; part += size + 8; crt.bq_key = part; part += size; crt.np_prime = part; part += size + 8; crt.nq_prime = part; part += size; crt.u_mult_inv = part; if (BN_bn2binpad(i, crt.inputdata, crt.inputdatalength) == -1 || BN_bn2binpad(p, crt.np_prime, size + 8) == -1 || BN_bn2binpad(q, crt.nq_prime, size) == -1 || BN_bn2binpad(dmp, crt.bp_key, size + 8) == -1 || BN_bn2binpad(dmq, crt.bq_key, size) == -1 || BN_bn2binpad(iqmp, crt.u_mult_inv, size + 8) == -1) goto dealloc; if (ioctl(OPENSSL_s390xcex, ICARSACRT, &crt) != -1) { if (BN_bin2bn(crt.outputdata, crt.outputdatalength, r) != NULL) res = 1; } else if (errno == EBADF) { /*- * In this cases, someone (e.g. a sandbox) closed the fd. * Make sure to not further use this hardware acceleration. */ OPENSSL_s390xcex = -1; } dealloc: OPENSSL_clear_free(buffer, 9 * size + 24); return res; } #else int s390x_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { return BN_mod_exp_mont(r, a, p, m, ctx, m_ctx); } int s390x_crt(BIGNUM *r, const BIGNUM *i, const BIGNUM *p, const BIGNUM *q, const BIGNUM *dmp, const BIGNUM *dmq, const BIGNUM *iqmp) { return 0; } #endif
./openssl/crypto/bn/bn_local.h
/* * 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 */ #ifndef OSSL_CRYPTO_BN_LOCAL_H # define OSSL_CRYPTO_BN_LOCAL_H /* * The EDK2 build doesn't use bn_conf.h; it sets THIRTY_TWO_BIT or * SIXTY_FOUR_BIT in its own environment since it doesn't re-run our * Configure script and needs to support both 32-bit and 64-bit. */ # include <openssl/opensslconf.h> # if !defined(OPENSSL_SYS_UEFI) # include "crypto/bn_conf.h" # endif # include "crypto/bn.h" # include "internal/cryptlib.h" # include "internal/numbers.h" /* * These preprocessor symbols control various aspects of the bignum headers * and library code. They're not defined by any "normal" configuration, as * they are intended for development and testing purposes. NB: defining * them can be useful for debugging application code as well as openssl * itself. BN_DEBUG - turn on various debugging alterations to the bignum * code BN_RAND_DEBUG - uses random poisoning of unused words to trip up * mismanagement of bignum internals. Enable BN_RAND_DEBUG is known to * break some of the OpenSSL tests. */ # if defined(BN_RAND_DEBUG) && !defined(BN_DEBUG) # define BN_DEBUG # endif # if defined(BN_RAND_DEBUG) # include <openssl/rand.h> # endif /* * This should limit the stack usage due to alloca to about 4K. * BN_SOFT_LIMIT is a soft limit equivalent to 2*OPENSSL_RSA_MAX_MODULUS_BITS. * Beyond that size bn_mul_mont is no longer used, and the constant time * assembler code is disabled, due to the blatant alloca and bn_mul_mont usage. * Note that bn_mul_mont does an alloca that is hidden away in assembly. * It is not recommended to do computations with numbers exceeding this limit, * since the result will be highly version dependent: * While the current OpenSSL version will use non-optimized, but safe code, * previous versions will use optimized code, that may crash due to unexpected * stack overflow, and future versions may very well turn this into a hard * limit. * Note however, that it is possible to override the size limit using * "./config -DBN_SOFT_LIMIT=<limit>" if necessary, and the O/S specific * stack limit is known and taken into consideration. */ # ifndef BN_SOFT_LIMIT # define BN_SOFT_LIMIT (4096 / BN_BYTES) # endif # ifndef OPENSSL_SMALL_FOOTPRINT # define BN_MUL_COMBA # define BN_SQR_COMBA # define BN_RECURSION # endif /* * This next option uses the C libraries (2 word)/(1 word) function. If it is * not defined, I use my C version (which is slower). The reason for this * flag is that when the particular C compiler library routine is used, and * the library is linked with a different compiler, the library is missing. * This mostly happens when the library is built with gcc and then linked * using normal cc. This would be a common occurrence because gcc normally * produces code that is 2 times faster than system compilers for the big * number stuff. For machines with only one compiler (or shared libraries), * this should be on. Again this in only really a problem on machines using * "long long's", are 32bit, and are not using my assembler code. */ # if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) || \ defined(OPENSSL_SYS_WIN32) || defined(linux) # define BN_DIV2W # endif /* * 64-bit processor with LP64 ABI */ # ifdef SIXTY_FOUR_BIT_LONG # define BN_ULLONG unsigned long long # define BN_BITS4 32 # define BN_MASK2 (0xffffffffffffffffL) # define BN_MASK2l (0xffffffffL) # define BN_MASK2h (0xffffffff00000000L) # define BN_MASK2h1 (0xffffffff80000000L) # define BN_DEC_CONV (10000000000000000000UL) # define BN_DEC_NUM 19 # define BN_DEC_FMT1 "%lu" # define BN_DEC_FMT2 "%019lu" # endif /* * 64-bit processor other than LP64 ABI */ # ifdef SIXTY_FOUR_BIT # undef BN_LLONG # undef BN_ULLONG # define BN_BITS4 32 # define BN_MASK2 (0xffffffffffffffffLL) # define BN_MASK2l (0xffffffffL) # define BN_MASK2h (0xffffffff00000000LL) # define BN_MASK2h1 (0xffffffff80000000LL) # define BN_DEC_CONV (10000000000000000000ULL) # define BN_DEC_NUM 19 # define BN_DEC_FMT1 "%llu" # define BN_DEC_FMT2 "%019llu" # endif # ifdef THIRTY_TWO_BIT # ifdef BN_LLONG # if defined(_WIN32) && !defined(__GNUC__) # define BN_ULLONG unsigned __int64 # else # define BN_ULLONG unsigned long long # endif # endif # define BN_BITS4 16 # define BN_MASK2 (0xffffffffL) # define BN_MASK2l (0xffff) # define BN_MASK2h1 (0xffff8000L) # define BN_MASK2h (0xffff0000L) # define BN_DEC_CONV (1000000000L) # define BN_DEC_NUM 9 # define BN_DEC_FMT1 "%u" # define BN_DEC_FMT2 "%09u" # endif /*- * Bignum consistency macros * There is one "API" macro, bn_fix_top(), for stripping leading zeroes from * bignum data after direct manipulations on the data. There is also an * "internal" macro, bn_check_top(), for verifying that there are no leading * zeroes. Unfortunately, some auditing is required due to the fact that * bn_fix_top() has become an overabused duct-tape because bignum data is * occasionally passed around in an inconsistent state. So the following * changes have been made to sort this out; * - bn_fix_top()s implementation has been moved to bn_correct_top() * - if BN_DEBUG isn't defined, bn_fix_top() maps to bn_correct_top(), and * bn_check_top() is as before. * - if BN_DEBUG *is* defined; * - bn_check_top() tries to pollute unused words even if the bignum 'top' is * consistent. (ed: only if BN_RAND_DEBUG is defined) * - bn_fix_top() maps to bn_check_top() rather than "fixing" anything. * The idea is to have debug builds flag up inconsistent bignums when they * occur. If that occurs in a bn_fix_top(), we examine the code in question; if * the use of bn_fix_top() was appropriate (ie. it follows directly after code * that manipulates the bignum) it is converted to bn_correct_top(), and if it * was not appropriate, we convert it permanently to bn_check_top() and track * down the cause of the bug. Eventually, no internal code should be using the * bn_fix_top() macro. External applications and libraries should try this with * their own code too, both in terms of building against the openssl headers * with BN_DEBUG defined *and* linking with a version of OpenSSL built with it * defined. This not only improves external code, it provides more test * coverage for openssl's own code. */ # ifdef BN_DEBUG /* * The new BN_FLG_FIXED_TOP flag marks vectors that were not treated with * bn_correct_top, in other words such vectors are permitted to have zeros * in most significant limbs. Such vectors are used internally to achieve * execution time invariance for critical operations with private keys. * It's BN_DEBUG-only flag, because user application is not supposed to * observe it anyway. Moreover, optimizing compiler would actually remove * all operations manipulating the bit in question in non-BN_DEBUG build. */ # define BN_FLG_FIXED_TOP 0x10000 # ifdef BN_RAND_DEBUG # define bn_pollute(a) \ do { \ const BIGNUM *_bnum1 = (a); \ if (_bnum1->top < _bnum1->dmax) { \ unsigned char _tmp_char; \ /* We cast away const without the compiler knowing, any \ * *genuinely* constant variables that aren't mutable \ * wouldn't be constructed with top!=dmax. */ \ BN_ULONG *_not_const; \ memcpy(&_not_const, &_bnum1->d, sizeof(_not_const)); \ (void)RAND_bytes(&_tmp_char, 1); /* Debug only - safe to ignore error return */\ memset(_not_const + _bnum1->top, _tmp_char, \ sizeof(*_not_const) * (_bnum1->dmax - _bnum1->top)); \ } \ } while(0) # else # define bn_pollute(a) # endif # define bn_check_top(a) \ do { \ const BIGNUM *_bnum2 = (a); \ if (_bnum2 != NULL) { \ int _top = _bnum2->top; \ (void)ossl_assert((_top == 0 && !_bnum2->neg) || \ (_top && ((_bnum2->flags & BN_FLG_FIXED_TOP) \ || _bnum2->d[_top - 1] != 0))); \ bn_pollute(_bnum2); \ } \ } while(0) # define bn_fix_top(a) bn_check_top(a) # define bn_check_size(bn, bits) bn_wcheck_size(bn, ((bits+BN_BITS2-1))/BN_BITS2) # define bn_wcheck_size(bn, words) \ do { \ const BIGNUM *_bnum2 = (bn); \ assert((words) <= (_bnum2)->dmax && \ (words) >= (_bnum2)->top); \ /* avoid unused variable warning with NDEBUG */ \ (void)(_bnum2); \ } while(0) # else /* !BN_DEBUG */ # define BN_FLG_FIXED_TOP 0 # define bn_pollute(a) # define bn_check_top(a) # define bn_fix_top(a) bn_correct_top(a) # define bn_check_size(bn, bits) # define bn_wcheck_size(bn, words) # endif BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w); BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w); void bn_sqr_words(BN_ULONG *rp, const BN_ULONG *ap, int num); BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d); BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, int num); BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, int num); struct bignum_st { BN_ULONG *d; /* * Pointer to an array of 'BN_BITS2' bit * chunks. These chunks are organised in * a least significant chunk first order. */ int top; /* Index of last used d +1. */ /* The next are internal book keeping for bn_expand. */ int dmax; /* Size of the d array. */ int neg; /* one if the number is negative */ int flags; }; /* Used for montgomery multiplication */ struct bn_mont_ctx_st { int ri; /* number of bits in R */ BIGNUM RR; /* used to convert to montgomery form, possibly zero-padded */ BIGNUM N; /* The modulus */ BIGNUM Ni; /* R*(1/R mod N) - N*Ni = 1 (Ni is only * stored for bignum algorithm) */ BN_ULONG n0[2]; /* least significant word(s) of Ni; (type * changed with 0.9.9, was "BN_ULONG n0;" * before) */ int flags; }; /* * Used for reciprocal division/mod functions It cannot be shared between * threads */ struct bn_recp_ctx_st { BIGNUM N; /* the divisor */ BIGNUM Nr; /* the reciprocal */ int num_bits; int shift; int flags; }; /* Used for slow "generation" functions. */ struct bn_gencb_st { unsigned int ver; /* To handle binary (in)compatibility */ void *arg; /* callback-specific data */ union { /* if (ver==1) - handles old style callbacks */ void (*cb_1) (int, int, void *); /* if (ver==2) - new callback style */ int (*cb_2) (int, int, BN_GENCB *); } cb; }; /*- * BN_window_bits_for_exponent_size -- macro for sliding window mod_exp functions * * * For window size 'w' (w >= 2) and a random 'b' bits exponent, * the number of multiplications is a constant plus on average * * 2^(w-1) + (b-w)/(w+1); * * here 2^(w-1) is for precomputing the table (we actually need * entries only for windows that have the lowest bit set), and * (b-w)/(w+1) is an approximation for the expected number of * w-bit windows, not counting the first one. * * Thus we should use * * w >= 6 if b > 671 * w = 5 if 671 > b > 239 * w = 4 if 239 > b > 79 * w = 3 if 79 > b > 23 * w <= 2 if 23 > b * * (with draws in between). Very small exponents are often selected * with low Hamming weight, so we use w = 1 for b <= 23. */ # define BN_window_bits_for_exponent_size(b) \ ((b) > 671 ? 6 : \ (b) > 239 ? 5 : \ (b) > 79 ? 4 : \ (b) > 23 ? 3 : 1) /* * BN_mod_exp_mont_consttime is based on the assumption that the L1 data cache * line width of the target processor is at least the following value. */ # define MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH ( 64 ) # define MOD_EXP_CTIME_MIN_CACHE_LINE_MASK (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - 1) /* * Window sizes optimized for fixed window size modular exponentiation * algorithm (BN_mod_exp_mont_consttime). To achieve the security goals of * BN_mode_exp_mont_consttime, the maximum size of the window must not exceed * log_2(MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH). Window size thresholds are * defined for cache line sizes of 32 and 64, cache line sizes where * log_2(32)=5 and log_2(64)=6 respectively. A window size of 7 should only be * used on processors that have a 128 byte or greater cache line size. */ # if MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 64 # define BN_window_bits_for_ctime_exponent_size(b) \ ((b) > 937 ? 6 : \ (b) > 306 ? 5 : \ (b) > 89 ? 4 : \ (b) > 22 ? 3 : 1) # define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE (6) # elif MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 32 # define BN_window_bits_for_ctime_exponent_size(b) \ ((b) > 306 ? 5 : \ (b) > 89 ? 4 : \ (b) > 22 ? 3 : 1) # define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE (5) # endif /* Pentium pro 16,16,16,32,64 */ /* Alpha 16,16,16,16.64 */ # define BN_MULL_SIZE_NORMAL (16)/* 32 */ # define BN_MUL_RECURSIVE_SIZE_NORMAL (16)/* 32 less than */ # define BN_SQR_RECURSIVE_SIZE_NORMAL (16)/* 32 */ # define BN_MUL_LOW_RECURSIVE_SIZE_NORMAL (32)/* 32 */ # define BN_MONT_CTX_SET_SIZE_WORD (64)/* 32 */ # if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) && !defined(PEDANTIC) /* * BN_UMULT_HIGH section. * If the compiler doesn't support 2*N integer type, then you have to * replace every N*N multiplication with 4 (N/2)*(N/2) accompanied by some * shifts and additions which unavoidably results in severe performance * penalties. Of course provided that the hardware is capable of producing * 2*N result... That's when you normally start considering assembler * implementation. However! It should be pointed out that some CPUs (e.g., * PowerPC, Alpha, and IA-64) provide *separate* instruction calculating * the upper half of the product placing the result into a general * purpose register. Now *if* the compiler supports inline assembler, * then it's not impossible to implement the "bignum" routines (and have * the compiler optimize 'em) exhibiting "native" performance in C. That's * what BN_UMULT_HIGH macro is about:-) Note that more recent compilers do * support 2*64 integer type, which is also used here. */ # if defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16 && \ (defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG)) # define BN_UMULT_HIGH(a,b) (((uint128_t)(a)*(b))>>64) # define BN_UMULT_LOHI(low,high,a,b) ({ \ uint128_t ret=(uint128_t)(a)*(b); \ (high)=ret>>64; (low)=ret; }) # elif defined(__alpha) && (defined(SIXTY_FOUR_BIT_LONG) || defined(SIXTY_FOUR_BIT)) # if defined(__DECC) # include <c_asm.h> # define BN_UMULT_HIGH(a,b) (BN_ULONG)asm("umulh %a0,%a1,%v0",(a),(b)) # elif defined(__GNUC__) && __GNUC__>=2 # define BN_UMULT_HIGH(a,b) ({ \ register BN_ULONG ret; \ asm ("umulh %1,%2,%0" \ : "=r"(ret) \ : "r"(a), "r"(b)); \ ret; }) # endif /* compiler */ # elif defined(_ARCH_PPC64) && defined(SIXTY_FOUR_BIT_LONG) # if defined(__GNUC__) && __GNUC__>=2 # define BN_UMULT_HIGH(a,b) ({ \ register BN_ULONG ret; \ asm ("mulhdu %0,%1,%2" \ : "=r"(ret) \ : "r"(a), "r"(b)); \ ret; }) # endif /* compiler */ # elif (defined(__x86_64) || defined(__x86_64__)) && \ (defined(SIXTY_FOUR_BIT_LONG) || defined(SIXTY_FOUR_BIT)) # if defined(__GNUC__) && __GNUC__>=2 # define BN_UMULT_HIGH(a,b) ({ \ register BN_ULONG ret,discard; \ asm ("mulq %3" \ : "=a"(discard),"=d"(ret) \ : "a"(a), "g"(b) \ : "cc"); \ ret; }) # define BN_UMULT_LOHI(low,high,a,b) \ asm ("mulq %3" \ : "=a"(low),"=d"(high) \ : "a"(a),"g"(b) \ : "cc"); # endif # elif (defined(_M_AMD64) || defined(_M_X64)) && defined(SIXTY_FOUR_BIT) # if defined(_MSC_VER) && _MSC_VER>=1400 unsigned __int64 __umulh(unsigned __int64 a, unsigned __int64 b); unsigned __int64 _umul128(unsigned __int64 a, unsigned __int64 b, unsigned __int64 *h); # pragma intrinsic(__umulh,_umul128) # define BN_UMULT_HIGH(a,b) __umulh((a),(b)) # define BN_UMULT_LOHI(low,high,a,b) ((low)=_umul128((a),(b),&(high))) # endif # elif defined(__mips) && (defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG)) # if defined(__GNUC__) && __GNUC__>=2 # define BN_UMULT_HIGH(a,b) ({ \ register BN_ULONG ret; \ asm ("dmultu %1,%2" \ : "=h"(ret) \ : "r"(a), "r"(b) : "l"); \ ret; }) # define BN_UMULT_LOHI(low,high,a,b) \ asm ("dmultu %2,%3" \ : "=l"(low),"=h"(high) \ : "r"(a), "r"(b)); # endif # elif defined(__aarch64__) && defined(SIXTY_FOUR_BIT_LONG) # if defined(__GNUC__) && __GNUC__>=2 # define BN_UMULT_HIGH(a,b) ({ \ register BN_ULONG ret; \ asm ("umulh %0,%1,%2" \ : "=r"(ret) \ : "r"(a), "r"(b)); \ ret; }) # endif # endif /* cpu */ # endif /* OPENSSL_NO_ASM */ # ifdef BN_RAND_DEBUG # define bn_clear_top2max(a) \ { \ int ind = (a)->dmax - (a)->top; \ BN_ULONG *ftl = &(a)->d[(a)->top-1]; \ for (; ind != 0; ind--) \ *(++ftl) = 0x0; \ } # else # define bn_clear_top2max(a) # endif # ifdef BN_LLONG /******************************************************************* * Using the long long type, has to be twice as wide as BN_ULONG... */ # define Lw(t) (((BN_ULONG)(t))&BN_MASK2) # define Hw(t) (((BN_ULONG)((t)>>BN_BITS2))&BN_MASK2) # define mul_add(r,a,w,c) { \ BN_ULLONG t; \ t=(BN_ULLONG)w * (a) + (r) + (c); \ (r)= Lw(t); \ (c)= Hw(t); \ } # define mul(r,a,w,c) { \ BN_ULLONG t; \ t=(BN_ULLONG)w * (a) + (c); \ (r)= Lw(t); \ (c)= Hw(t); \ } # define sqr(r0,r1,a) { \ BN_ULLONG t; \ t=(BN_ULLONG)(a)*(a); \ (r0)=Lw(t); \ (r1)=Hw(t); \ } # elif defined(BN_UMULT_LOHI) # define mul_add(r,a,w,c) { \ BN_ULONG high,low,ret,tmp=(a); \ ret = (r); \ BN_UMULT_LOHI(low,high,w,tmp); \ ret += (c); \ (c) = (ret<(c)); \ (c) += high; \ ret += low; \ (c) += (ret<low); \ (r) = ret; \ } # define mul(r,a,w,c) { \ BN_ULONG high,low,ret,ta=(a); \ BN_UMULT_LOHI(low,high,w,ta); \ ret = low + (c); \ (c) = high; \ (c) += (ret<low); \ (r) = ret; \ } # define sqr(r0,r1,a) { \ BN_ULONG tmp=(a); \ BN_UMULT_LOHI(r0,r1,tmp,tmp); \ } # elif defined(BN_UMULT_HIGH) # define mul_add(r,a,w,c) { \ BN_ULONG high,low,ret,tmp=(a); \ ret = (r); \ high= BN_UMULT_HIGH(w,tmp); \ ret += (c); \ low = (w) * tmp; \ (c) = (ret<(c)); \ (c) += high; \ ret += low; \ (c) += (ret<low); \ (r) = ret; \ } # define mul(r,a,w,c) { \ BN_ULONG high,low,ret,ta=(a); \ low = (w) * ta; \ high= BN_UMULT_HIGH(w,ta); \ ret = low + (c); \ (c) = high; \ (c) += (ret<low); \ (r) = ret; \ } # define sqr(r0,r1,a) { \ BN_ULONG tmp=(a); \ (r0) = tmp * tmp; \ (r1) = BN_UMULT_HIGH(tmp,tmp); \ } # else /************************************************************* * No long long type */ # define LBITS(a) ((a)&BN_MASK2l) # define HBITS(a) (((a)>>BN_BITS4)&BN_MASK2l) # define L2HBITS(a) (((a)<<BN_BITS4)&BN_MASK2) # define LLBITS(a) ((a)&BN_MASKl) # define LHBITS(a) (((a)>>BN_BITS2)&BN_MASKl) # define LL2HBITS(a) ((BN_ULLONG)((a)&BN_MASKl)<<BN_BITS2) # define mul64(l,h,bl,bh) \ { \ BN_ULONG m,m1,lt,ht; \ \ lt=l; \ ht=h; \ m =(bh)*(lt); \ lt=(bl)*(lt); \ m1=(bl)*(ht); \ ht =(bh)*(ht); \ m=(m+m1)&BN_MASK2; ht += L2HBITS((BN_ULONG)(m < m1)); \ ht+=HBITS(m); \ m1=L2HBITS(m); \ lt=(lt+m1)&BN_MASK2; ht += (lt < m1); \ (l)=lt; \ (h)=ht; \ } # define sqr64(lo,ho,in) \ { \ BN_ULONG l,h,m; \ \ h=(in); \ l=LBITS(h); \ h=HBITS(h); \ m =(l)*(h); \ l*=l; \ h*=h; \ h+=(m&BN_MASK2h1)>>(BN_BITS4-1); \ m =(m&BN_MASK2l)<<(BN_BITS4+1); \ l=(l+m)&BN_MASK2; h += (l < m); \ (lo)=l; \ (ho)=h; \ } # define mul_add(r,a,bl,bh,c) { \ BN_ULONG l,h; \ \ h= (a); \ l=LBITS(h); \ h=HBITS(h); \ mul64(l,h,(bl),(bh)); \ \ /* non-multiply part */ \ l=(l+(c))&BN_MASK2; h += (l < (c)); \ (c)=(r); \ l=(l+(c))&BN_MASK2; h += (l < (c)); \ (c)=h&BN_MASK2; \ (r)=l; \ } # define mul(r,a,bl,bh,c) { \ BN_ULONG l,h; \ \ h= (a); \ l=LBITS(h); \ h=HBITS(h); \ mul64(l,h,(bl),(bh)); \ \ /* non-multiply part */ \ l+=(c); h += ((l&BN_MASK2) < (c)); \ (c)=h&BN_MASK2; \ (r)=l&BN_MASK2; \ } # endif /* !BN_LLONG */ void BN_RECP_CTX_init(BN_RECP_CTX *recp); void BN_MONT_CTX_init(BN_MONT_CTX *ctx); void bn_init(BIGNUM *a); void bn_mul_normal(BN_ULONG *r, BN_ULONG *a, int na, BN_ULONG *b, int nb); void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b); void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b); void bn_sqr_normal(BN_ULONG *r, const BN_ULONG *a, int n, BN_ULONG *tmp); void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a); void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a); int bn_cmp_words(const BN_ULONG *a, const BN_ULONG *b, int n); int bn_cmp_part_words(const BN_ULONG *a, const BN_ULONG *b, int cl, int dl); void bn_mul_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, int dna, int dnb, BN_ULONG *t); void bn_mul_part_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n, int tna, int tnb, BN_ULONG *t); void bn_sqr_recursive(BN_ULONG *r, const BN_ULONG *a, int n2, BN_ULONG *t); void bn_mul_low_normal(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n); void bn_mul_low_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, BN_ULONG *t); BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, int cl, int dl); int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); void bn_correct_top_consttime(BIGNUM *a); BIGNUM *int_bn_mod_inverse(BIGNUM *in, const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx, int *noinv); static ossl_inline BIGNUM *bn_expand(BIGNUM *a, int bits) { if (bits > (INT_MAX - BN_BITS2 + 1)) return NULL; if (((bits+BN_BITS2-1)/BN_BITS2) <= (a)->dmax) return a; return bn_expand2((a),(bits+BN_BITS2-1)/BN_BITS2); } int ossl_bn_check_prime(const BIGNUM *w, int checks, BN_CTX *ctx, int do_trial_division, BN_GENCB *cb); #endif
./openssl/crypto/bn/bn_gf2m.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 */ #include <assert.h> #include <limits.h> #include <stdio.h> #include "internal/cryptlib.h" #include "bn_local.h" #ifndef OPENSSL_NO_EC2M /* * Maximum number of iterations before BN_GF2m_mod_solve_quad_arr should * fail. */ # define MAX_ITERATIONS 50 # define SQR_nibble(w) ((((w) & 8) << 3) \ | (((w) & 4) << 2) \ | (((w) & 2) << 1) \ | ((w) & 1)) /* Platform-specific macros to accelerate squaring. */ # if defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG) # define SQR1(w) \ SQR_nibble((w) >> 60) << 56 | SQR_nibble((w) >> 56) << 48 | \ SQR_nibble((w) >> 52) << 40 | SQR_nibble((w) >> 48) << 32 | \ SQR_nibble((w) >> 44) << 24 | SQR_nibble((w) >> 40) << 16 | \ SQR_nibble((w) >> 36) << 8 | SQR_nibble((w) >> 32) # define SQR0(w) \ SQR_nibble((w) >> 28) << 56 | SQR_nibble((w) >> 24) << 48 | \ SQR_nibble((w) >> 20) << 40 | SQR_nibble((w) >> 16) << 32 | \ SQR_nibble((w) >> 12) << 24 | SQR_nibble((w) >> 8) << 16 | \ SQR_nibble((w) >> 4) << 8 | SQR_nibble((w) ) # endif # ifdef THIRTY_TWO_BIT # define SQR1(w) \ SQR_nibble((w) >> 28) << 24 | SQR_nibble((w) >> 24) << 16 | \ SQR_nibble((w) >> 20) << 8 | SQR_nibble((w) >> 16) # define SQR0(w) \ SQR_nibble((w) >> 12) << 24 | SQR_nibble((w) >> 8) << 16 | \ SQR_nibble((w) >> 4) << 8 | SQR_nibble((w) ) # endif # if !defined(OPENSSL_BN_ASM_GF2m) /* * Product of two polynomials a, b each with degree < BN_BITS2 - 1, result is * a polynomial r with degree < 2 * BN_BITS - 1 The caller MUST ensure that * the variables have the right amount of space allocated. */ # ifdef THIRTY_TWO_BIT static void bn_GF2m_mul_1x1(BN_ULONG *r1, BN_ULONG *r0, const BN_ULONG a, const BN_ULONG b) { register BN_ULONG h, l, s; BN_ULONG tab[8], top2b = a >> 30; register BN_ULONG a1, a2, a4; a1 = a & (0x3FFFFFFF); a2 = a1 << 1; a4 = a2 << 1; tab[0] = 0; tab[1] = a1; tab[2] = a2; tab[3] = a1 ^ a2; tab[4] = a4; tab[5] = a1 ^ a4; tab[6] = a2 ^ a4; tab[7] = a1 ^ a2 ^ a4; s = tab[b & 0x7]; l = s; s = tab[b >> 3 & 0x7]; l ^= s << 3; h = s >> 29; s = tab[b >> 6 & 0x7]; l ^= s << 6; h ^= s >> 26; s = tab[b >> 9 & 0x7]; l ^= s << 9; h ^= s >> 23; s = tab[b >> 12 & 0x7]; l ^= s << 12; h ^= s >> 20; s = tab[b >> 15 & 0x7]; l ^= s << 15; h ^= s >> 17; s = tab[b >> 18 & 0x7]; l ^= s << 18; h ^= s >> 14; s = tab[b >> 21 & 0x7]; l ^= s << 21; h ^= s >> 11; s = tab[b >> 24 & 0x7]; l ^= s << 24; h ^= s >> 8; s = tab[b >> 27 & 0x7]; l ^= s << 27; h ^= s >> 5; s = tab[b >> 30]; l ^= s << 30; h ^= s >> 2; /* compensate for the top two bits of a */ if (top2b & 01) { l ^= b << 30; h ^= b >> 2; } if (top2b & 02) { l ^= b << 31; h ^= b >> 1; } *r1 = h; *r0 = l; } # endif # if defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG) static void bn_GF2m_mul_1x1(BN_ULONG *r1, BN_ULONG *r0, const BN_ULONG a, const BN_ULONG b) { register BN_ULONG h, l, s; BN_ULONG tab[16], top3b = a >> 61; register BN_ULONG a1, a2, a4, a8; a1 = a & (0x1FFFFFFFFFFFFFFFULL); a2 = a1 << 1; a4 = a2 << 1; a8 = a4 << 1; tab[0] = 0; tab[1] = a1; tab[2] = a2; tab[3] = a1 ^ a2; tab[4] = a4; tab[5] = a1 ^ a4; tab[6] = a2 ^ a4; tab[7] = a1 ^ a2 ^ a4; tab[8] = a8; tab[9] = a1 ^ a8; tab[10] = a2 ^ a8; tab[11] = a1 ^ a2 ^ a8; tab[12] = a4 ^ a8; tab[13] = a1 ^ a4 ^ a8; tab[14] = a2 ^ a4 ^ a8; tab[15] = a1 ^ a2 ^ a4 ^ a8; s = tab[b & 0xF]; l = s; s = tab[b >> 4 & 0xF]; l ^= s << 4; h = s >> 60; s = tab[b >> 8 & 0xF]; l ^= s << 8; h ^= s >> 56; s = tab[b >> 12 & 0xF]; l ^= s << 12; h ^= s >> 52; s = tab[b >> 16 & 0xF]; l ^= s << 16; h ^= s >> 48; s = tab[b >> 20 & 0xF]; l ^= s << 20; h ^= s >> 44; s = tab[b >> 24 & 0xF]; l ^= s << 24; h ^= s >> 40; s = tab[b >> 28 & 0xF]; l ^= s << 28; h ^= s >> 36; s = tab[b >> 32 & 0xF]; l ^= s << 32; h ^= s >> 32; s = tab[b >> 36 & 0xF]; l ^= s << 36; h ^= s >> 28; s = tab[b >> 40 & 0xF]; l ^= s << 40; h ^= s >> 24; s = tab[b >> 44 & 0xF]; l ^= s << 44; h ^= s >> 20; s = tab[b >> 48 & 0xF]; l ^= s << 48; h ^= s >> 16; s = tab[b >> 52 & 0xF]; l ^= s << 52; h ^= s >> 12; s = tab[b >> 56 & 0xF]; l ^= s << 56; h ^= s >> 8; s = tab[b >> 60]; l ^= s << 60; h ^= s >> 4; /* compensate for the top three bits of a */ if (top3b & 01) { l ^= b << 61; h ^= b >> 3; } if (top3b & 02) { l ^= b << 62; h ^= b >> 2; } if (top3b & 04) { l ^= b << 63; h ^= b >> 1; } *r1 = h; *r0 = l; } # endif /* * Product of two polynomials a, b each with degree < 2 * BN_BITS2 - 1, * result is a polynomial r with degree < 4 * BN_BITS2 - 1 The caller MUST * ensure that the variables have the right amount of space allocated. */ static void bn_GF2m_mul_2x2(BN_ULONG *r, const BN_ULONG a1, const BN_ULONG a0, const BN_ULONG b1, const BN_ULONG b0) { BN_ULONG m1, m0; /* r[3] = h1, r[2] = h0; r[1] = l1; r[0] = l0 */ bn_GF2m_mul_1x1(r + 3, r + 2, a1, b1); bn_GF2m_mul_1x1(r + 1, r, a0, b0); bn_GF2m_mul_1x1(&m1, &m0, a0 ^ a1, b0 ^ b1); /* Correction on m1 ^= l1 ^ h1; m0 ^= l0 ^ h0; */ r[2] ^= m1 ^ r[1] ^ r[3]; /* h0 ^= m1 ^ l1 ^ h1; */ r[1] = r[3] ^ r[2] ^ r[0] ^ m1 ^ m0; /* l1 ^= l0 ^ h0 ^ m0; */ } # else void bn_GF2m_mul_2x2(BN_ULONG *r, BN_ULONG a1, BN_ULONG a0, BN_ULONG b1, BN_ULONG b0); # endif /* * Add polynomials a and b and store result in r; r could be a or b, a and b * could be equal; r is the bitwise XOR of a and b. */ int BN_GF2m_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { int i; const BIGNUM *at, *bt; bn_check_top(a); bn_check_top(b); if (a->top < b->top) { at = b; bt = a; } else { at = a; bt = b; } if (bn_wexpand(r, at->top) == NULL) return 0; for (i = 0; i < bt->top; i++) { r->d[i] = at->d[i] ^ bt->d[i]; } for (; i < at->top; i++) { r->d[i] = at->d[i]; } r->top = at->top; bn_correct_top(r); return 1; } /*- * Some functions allow for representation of the irreducible polynomials * as an int[], say p. The irreducible f(t) is then of the form: * t^p[0] + t^p[1] + ... + t^p[k] * where m = p[0] > p[1] > ... > p[k] = 0. */ /* Performs modular reduction of a and store result in r. r could be a. */ int BN_GF2m_mod_arr(BIGNUM *r, const BIGNUM *a, const int p[]) { int j, k; int n, dN, d0, d1; BN_ULONG zz, *z; bn_check_top(a); if (p[0] == 0) { /* reduction mod 1 => return 0 */ BN_zero(r); return 1; } /* * Since the algorithm does reduction in the r value, if a != r, copy the * contents of a into r so we can do reduction in r. */ if (a != r) { if (!bn_wexpand(r, a->top)) return 0; for (j = 0; j < a->top; j++) { r->d[j] = a->d[j]; } r->top = a->top; } z = r->d; /* start reduction */ dN = p[0] / BN_BITS2; for (j = r->top - 1; j > dN;) { zz = z[j]; if (z[j] == 0) { j--; continue; } z[j] = 0; for (k = 1; p[k] != 0; k++) { /* reducing component t^p[k] */ n = p[0] - p[k]; d0 = n % BN_BITS2; d1 = BN_BITS2 - d0; n /= BN_BITS2; z[j - n] ^= (zz >> d0); if (d0) z[j - n - 1] ^= (zz << d1); } /* reducing component t^0 */ n = dN; d0 = p[0] % BN_BITS2; d1 = BN_BITS2 - d0; z[j - n] ^= (zz >> d0); if (d0) z[j - n - 1] ^= (zz << d1); } /* final round of reduction */ while (j == dN) { d0 = p[0] % BN_BITS2; zz = z[dN] >> d0; if (zz == 0) break; d1 = BN_BITS2 - d0; /* clear up the top d1 bits */ if (d0) z[dN] = (z[dN] << d1) >> d1; else z[dN] = 0; z[0] ^= zz; /* reduction t^0 component */ for (k = 1; p[k] != 0; k++) { BN_ULONG tmp_ulong; /* reducing component t^p[k] */ n = p[k] / BN_BITS2; d0 = p[k] % BN_BITS2; d1 = BN_BITS2 - d0; z[n] ^= (zz << d0); if (d0 && (tmp_ulong = zz >> d1)) z[n + 1] ^= tmp_ulong; } } bn_correct_top(r); return 1; } /* * Performs modular reduction of a by p and store result in r. r could be a. * This function calls down to the BN_GF2m_mod_arr implementation; this wrapper * function is only provided for convenience; for best performance, use the * BN_GF2m_mod_arr function. */ int BN_GF2m_mod(BIGNUM *r, const BIGNUM *a, const BIGNUM *p) { int ret = 0; int arr[6]; bn_check_top(a); bn_check_top(p); ret = BN_GF2m_poly2arr(p, arr, OSSL_NELEM(arr)); if (!ret || ret > (int)OSSL_NELEM(arr)) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH); return 0; } ret = BN_GF2m_mod_arr(r, a, arr); bn_check_top(r); return ret; } /* * Compute the product of two polynomials a and b, reduce modulo p, and store * the result in r. r could be a or b; a could be b. */ int BN_GF2m_mod_mul_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const int p[], BN_CTX *ctx) { int zlen, i, j, k, ret = 0; BIGNUM *s; BN_ULONG x1, x0, y1, y0, zz[4]; bn_check_top(a); bn_check_top(b); if (a == b) { return BN_GF2m_mod_sqr_arr(r, a, p, ctx); } BN_CTX_start(ctx); if ((s = BN_CTX_get(ctx)) == NULL) goto err; zlen = a->top + b->top + 4; if (!bn_wexpand(s, zlen)) goto err; s->top = zlen; for (i = 0; i < zlen; i++) s->d[i] = 0; for (j = 0; j < b->top; j += 2) { y0 = b->d[j]; y1 = ((j + 1) == b->top) ? 0 : b->d[j + 1]; for (i = 0; i < a->top; i += 2) { x0 = a->d[i]; x1 = ((i + 1) == a->top) ? 0 : a->d[i + 1]; bn_GF2m_mul_2x2(zz, x1, x0, y1, y0); for (k = 0; k < 4; k++) s->d[i + j + k] ^= zz[k]; } } bn_correct_top(s); if (BN_GF2m_mod_arr(r, s, p)) ret = 1; bn_check_top(r); err: BN_CTX_end(ctx); return ret; } /* * Compute the product of two polynomials a and b, reduce modulo p, and store * the result in r. r could be a or b; a could equal b. This function calls * down to the BN_GF2m_mod_mul_arr implementation; this wrapper function is * only provided for convenience; for best performance, use the * BN_GF2m_mod_mul_arr function. */ int BN_GF2m_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *p, BN_CTX *ctx) { int ret = 0; const int max = BN_num_bits(p) + 1; int *arr; bn_check_top(a); bn_check_top(b); bn_check_top(p); arr = OPENSSL_malloc(sizeof(*arr) * max); if (arr == NULL) return 0; ret = BN_GF2m_poly2arr(p, arr, max); if (!ret || ret > max) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH); goto err; } ret = BN_GF2m_mod_mul_arr(r, a, b, arr, ctx); bn_check_top(r); err: OPENSSL_free(arr); return ret; } /* Square a, reduce the result mod p, and store it in a. r could be a. */ int BN_GF2m_mod_sqr_arr(BIGNUM *r, const BIGNUM *a, const int p[], BN_CTX *ctx) { int i, ret = 0; BIGNUM *s; bn_check_top(a); BN_CTX_start(ctx); if ((s = BN_CTX_get(ctx)) == NULL) goto err; if (!bn_wexpand(s, 2 * a->top)) goto err; for (i = a->top - 1; i >= 0; i--) { s->d[2 * i + 1] = SQR1(a->d[i]); s->d[2 * i] = SQR0(a->d[i]); } s->top = 2 * a->top; bn_correct_top(s); if (!BN_GF2m_mod_arr(r, s, p)) goto err; bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Square a, reduce the result mod p, and store it in a. r could be a. This * function calls down to the BN_GF2m_mod_sqr_arr implementation; this * wrapper function is only provided for convenience; for best performance, * use the BN_GF2m_mod_sqr_arr function. */ int BN_GF2m_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { int ret = 0; const int max = BN_num_bits(p) + 1; int *arr; bn_check_top(a); bn_check_top(p); arr = OPENSSL_malloc(sizeof(*arr) * max); if (arr == NULL) return 0; ret = BN_GF2m_poly2arr(p, arr, max); if (!ret || ret > max) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH); goto err; } ret = BN_GF2m_mod_sqr_arr(r, a, arr, ctx); bn_check_top(r); err: OPENSSL_free(arr); return ret; } /* * Invert a, reduce modulo p, and store the result in r. r could be a. Uses * Modified Almost Inverse Algorithm (Algorithm 10) from Hankerson, D., * Hernandez, J.L., and Menezes, A. "Software Implementation of Elliptic * Curve Cryptography Over Binary Fields". */ static int BN_GF2m_mod_inv_vartime(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { BIGNUM *b, *c = NULL, *u = NULL, *v = NULL, *tmp; int ret = 0; bn_check_top(a); bn_check_top(p); BN_CTX_start(ctx); b = BN_CTX_get(ctx); c = BN_CTX_get(ctx); u = BN_CTX_get(ctx); v = BN_CTX_get(ctx); if (v == NULL) goto err; if (!BN_GF2m_mod(u, a, p)) goto err; if (BN_is_zero(u)) goto err; if (!BN_copy(v, p)) goto err; # if 0 if (!BN_one(b)) goto err; while (1) { while (!BN_is_odd(u)) { if (BN_is_zero(u)) goto err; if (!BN_rshift1(u, u)) goto err; if (BN_is_odd(b)) { if (!BN_GF2m_add(b, b, p)) goto err; } if (!BN_rshift1(b, b)) goto err; } if (BN_abs_is_word(u, 1)) break; if (BN_num_bits(u) < BN_num_bits(v)) { tmp = u; u = v; v = tmp; tmp = b; b = c; c = tmp; } if (!BN_GF2m_add(u, u, v)) goto err; if (!BN_GF2m_add(b, b, c)) goto err; } # else { int i; int ubits = BN_num_bits(u); int vbits = BN_num_bits(v); /* v is copy of p */ int top = p->top; BN_ULONG *udp, *bdp, *vdp, *cdp; if (!bn_wexpand(u, top)) goto err; udp = u->d; for (i = u->top; i < top; i++) udp[i] = 0; u->top = top; if (!bn_wexpand(b, top)) goto err; bdp = b->d; bdp[0] = 1; for (i = 1; i < top; i++) bdp[i] = 0; b->top = top; if (!bn_wexpand(c, top)) goto err; cdp = c->d; for (i = 0; i < top; i++) cdp[i] = 0; c->top = top; vdp = v->d; /* It pays off to "cache" *->d pointers, * because it allows optimizer to be more * aggressive. But we don't have to "cache" * p->d, because *p is declared 'const'... */ while (1) { while (ubits && !(udp[0] & 1)) { BN_ULONG u0, u1, b0, b1, mask; u0 = udp[0]; b0 = bdp[0]; mask = (BN_ULONG)0 - (b0 & 1); b0 ^= p->d[0] & mask; for (i = 0; i < top - 1; i++) { u1 = udp[i + 1]; udp[i] = ((u0 >> 1) | (u1 << (BN_BITS2 - 1))) & BN_MASK2; u0 = u1; b1 = bdp[i + 1] ^ (p->d[i + 1] & mask); bdp[i] = ((b0 >> 1) | (b1 << (BN_BITS2 - 1))) & BN_MASK2; b0 = b1; } udp[i] = u0 >> 1; bdp[i] = b0 >> 1; ubits--; } if (ubits <= BN_BITS2) { if (udp[0] == 0) /* poly was reducible */ goto err; if (udp[0] == 1) break; } if (ubits < vbits) { i = ubits; ubits = vbits; vbits = i; tmp = u; u = v; v = tmp; tmp = b; b = c; c = tmp; udp = vdp; vdp = v->d; bdp = cdp; cdp = c->d; } for (i = 0; i < top; i++) { udp[i] ^= vdp[i]; bdp[i] ^= cdp[i]; } if (ubits == vbits) { BN_ULONG ul; int utop = (ubits - 1) / BN_BITS2; while ((ul = udp[utop]) == 0 && utop) utop--; ubits = utop * BN_BITS2 + BN_num_bits_word(ul); } } bn_correct_top(b); } # endif if (!BN_copy(r, b)) goto err; bn_check_top(r); ret = 1; err: # ifdef BN_DEBUG /* BN_CTX_end would complain about the expanded form */ bn_correct_top(c); bn_correct_top(u); bn_correct_top(v); # endif BN_CTX_end(ctx); return ret; } /*- * Wrapper for BN_GF2m_mod_inv_vartime that blinds the input before calling. * This is not constant time. * But it does eliminate first order deduction on the input. */ int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { BIGNUM *b = NULL; int ret = 0; int numbits; BN_CTX_start(ctx); if ((b = BN_CTX_get(ctx)) == NULL) goto err; /* Fail on a non-sensical input p value */ numbits = BN_num_bits(p); if (numbits <= 1) goto err; /* generate blinding value */ do { if (!BN_priv_rand_ex(b, numbits - 1, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY, 0, ctx)) goto err; } while (BN_is_zero(b)); /* r := a * b */ if (!BN_GF2m_mod_mul(r, a, b, p, ctx)) goto err; /* r := 1/(a * b) */ if (!BN_GF2m_mod_inv_vartime(r, r, p, ctx)) goto err; /* r := b/(a * b) = 1/a */ if (!BN_GF2m_mod_mul(r, r, b, p, ctx)) goto err; ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Invert xx, reduce modulo p, and store the result in r. r could be xx. * This function calls down to the BN_GF2m_mod_inv implementation; this * wrapper function is only provided for convenience; for best performance, * use the BN_GF2m_mod_inv function. */ int BN_GF2m_mod_inv_arr(BIGNUM *r, const BIGNUM *xx, const int p[], BN_CTX *ctx) { BIGNUM *field; int ret = 0; bn_check_top(xx); BN_CTX_start(ctx); if ((field = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_GF2m_arr2poly(p, field)) goto err; ret = BN_GF2m_mod_inv(r, xx, field, ctx); bn_check_top(r); err: BN_CTX_end(ctx); return ret; } /* * Divide y by x, reduce modulo p, and store the result in r. r could be x * or y, x could equal y. */ int BN_GF2m_mod_div(BIGNUM *r, const BIGNUM *y, const BIGNUM *x, const BIGNUM *p, BN_CTX *ctx) { BIGNUM *xinv = NULL; int ret = 0; bn_check_top(y); bn_check_top(x); bn_check_top(p); BN_CTX_start(ctx); xinv = BN_CTX_get(ctx); if (xinv == NULL) goto err; if (!BN_GF2m_mod_inv(xinv, x, p, ctx)) goto err; if (!BN_GF2m_mod_mul(r, y, xinv, p, ctx)) goto err; bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Divide yy by xx, reduce modulo p, and store the result in r. r could be xx * * or yy, xx could equal yy. This function calls down to the * BN_GF2m_mod_div implementation; this wrapper function is only provided for * convenience; for best performance, use the BN_GF2m_mod_div function. */ int BN_GF2m_mod_div_arr(BIGNUM *r, const BIGNUM *yy, const BIGNUM *xx, const int p[], BN_CTX *ctx) { BIGNUM *field; int ret = 0; bn_check_top(yy); bn_check_top(xx); BN_CTX_start(ctx); if ((field = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_GF2m_arr2poly(p, field)) goto err; ret = BN_GF2m_mod_div(r, yy, xx, field, ctx); bn_check_top(r); err: BN_CTX_end(ctx); return ret; } /* * Compute the bth power of a, reduce modulo p, and store the result in r. r * could be a. Uses simple square-and-multiply algorithm A.5.1 from IEEE * P1363. */ int BN_GF2m_mod_exp_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const int p[], BN_CTX *ctx) { int ret = 0, i, n; BIGNUM *u; bn_check_top(a); bn_check_top(b); if (BN_is_zero(b)) return BN_one(r); if (BN_abs_is_word(b, 1)) return (BN_copy(r, a) != NULL); BN_CTX_start(ctx); if ((u = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_GF2m_mod_arr(u, a, p)) goto err; n = BN_num_bits(b) - 1; for (i = n - 1; i >= 0; i--) { if (!BN_GF2m_mod_sqr_arr(u, u, p, ctx)) goto err; if (BN_is_bit_set(b, i)) { if (!BN_GF2m_mod_mul_arr(u, u, a, p, ctx)) goto err; } } if (!BN_copy(r, u)) goto err; bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Compute the bth power of a, reduce modulo p, and store the result in r. r * could be a. This function calls down to the BN_GF2m_mod_exp_arr * implementation; this wrapper function is only provided for convenience; * for best performance, use the BN_GF2m_mod_exp_arr function. */ int BN_GF2m_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *p, BN_CTX *ctx) { int ret = 0; const int max = BN_num_bits(p) + 1; int *arr; bn_check_top(a); bn_check_top(b); bn_check_top(p); arr = OPENSSL_malloc(sizeof(*arr) * max); if (arr == NULL) return 0; ret = BN_GF2m_poly2arr(p, arr, max); if (!ret || ret > max) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH); goto err; } ret = BN_GF2m_mod_exp_arr(r, a, b, arr, ctx); bn_check_top(r); err: OPENSSL_free(arr); return ret; } /* * Compute the square root of a, reduce modulo p, and store the result in r. * r could be a. Uses exponentiation as in algorithm A.4.1 from IEEE P1363. */ int BN_GF2m_mod_sqrt_arr(BIGNUM *r, const BIGNUM *a, const int p[], BN_CTX *ctx) { int ret = 0; BIGNUM *u; bn_check_top(a); if (p[0] == 0) { /* reduction mod 1 => return 0 */ BN_zero(r); return 1; } BN_CTX_start(ctx); if ((u = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_set_bit(u, p[0] - 1)) goto err; ret = BN_GF2m_mod_exp_arr(r, a, u, p, ctx); bn_check_top(r); err: BN_CTX_end(ctx); return ret; } /* * Compute the square root of a, reduce modulo p, and store the result in r. * r could be a. This function calls down to the BN_GF2m_mod_sqrt_arr * implementation; this wrapper function is only provided for convenience; * for best performance, use the BN_GF2m_mod_sqrt_arr function. */ int BN_GF2m_mod_sqrt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { int ret = 0; const int max = BN_num_bits(p) + 1; int *arr; bn_check_top(a); bn_check_top(p); arr = OPENSSL_malloc(sizeof(*arr) * max); if (arr == NULL) return 0; ret = BN_GF2m_poly2arr(p, arr, max); if (!ret || ret > max) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH); goto err; } ret = BN_GF2m_mod_sqrt_arr(r, a, arr, ctx); bn_check_top(r); err: OPENSSL_free(arr); return ret; } /* * Find r such that r^2 + r = a mod p. r could be a. If no r exists returns * 0. Uses algorithms A.4.7 and A.4.6 from IEEE P1363. */ int BN_GF2m_mod_solve_quad_arr(BIGNUM *r, const BIGNUM *a_, const int p[], BN_CTX *ctx) { int ret = 0, count = 0, j; BIGNUM *a, *z, *rho, *w, *w2, *tmp; bn_check_top(a_); if (p[0] == 0) { /* reduction mod 1 => return 0 */ BN_zero(r); return 1; } BN_CTX_start(ctx); a = BN_CTX_get(ctx); z = BN_CTX_get(ctx); w = BN_CTX_get(ctx); if (w == NULL) goto err; if (!BN_GF2m_mod_arr(a, a_, p)) goto err; if (BN_is_zero(a)) { BN_zero(r); ret = 1; goto err; } if (p[0] & 0x1) { /* m is odd */ /* compute half-trace of a */ if (!BN_copy(z, a)) goto err; for (j = 1; j <= (p[0] - 1) / 2; j++) { if (!BN_GF2m_mod_sqr_arr(z, z, p, ctx)) goto err; if (!BN_GF2m_mod_sqr_arr(z, z, p, ctx)) goto err; if (!BN_GF2m_add(z, z, a)) goto err; } } else { /* m is even */ rho = BN_CTX_get(ctx); w2 = BN_CTX_get(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) goto err; do { if (!BN_priv_rand_ex(rho, p[0], BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY, 0, ctx)) goto err; if (!BN_GF2m_mod_arr(rho, rho, p)) goto err; BN_zero(z); if (!BN_copy(w, rho)) goto err; for (j = 1; j <= p[0] - 1; j++) { if (!BN_GF2m_mod_sqr_arr(z, z, p, ctx)) goto err; if (!BN_GF2m_mod_sqr_arr(w2, w, p, ctx)) goto err; if (!BN_GF2m_mod_mul_arr(tmp, w2, a, p, ctx)) goto err; if (!BN_GF2m_add(z, z, tmp)) goto err; if (!BN_GF2m_add(w, w2, rho)) goto err; } count++; } while (BN_is_zero(w) && (count < MAX_ITERATIONS)); if (BN_is_zero(w)) { ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS); goto err; } } if (!BN_GF2m_mod_sqr_arr(w, z, p, ctx)) goto err; if (!BN_GF2m_add(w, z, w)) goto err; if (BN_GF2m_cmp(w, a)) { ERR_raise(ERR_LIB_BN, BN_R_NO_SOLUTION); goto err; } if (!BN_copy(r, z)) goto err; bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Find r such that r^2 + r = a mod p. r could be a. If no r exists returns * 0. This function calls down to the BN_GF2m_mod_solve_quad_arr * implementation; this wrapper function is only provided for convenience; * for best performance, use the BN_GF2m_mod_solve_quad_arr function. */ int BN_GF2m_mod_solve_quad(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { int ret = 0; const int max = BN_num_bits(p) + 1; int *arr; bn_check_top(a); bn_check_top(p); arr = OPENSSL_malloc(sizeof(*arr) * max); if (arr == NULL) goto err; ret = BN_GF2m_poly2arr(p, arr, max); if (!ret || ret > max) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH); goto err; } ret = BN_GF2m_mod_solve_quad_arr(r, a, arr, ctx); bn_check_top(r); err: OPENSSL_free(arr); return ret; } /* * Convert the bit-string representation of a polynomial ( \sum_{i=0}^n a_i * * x^i) into an array of integers corresponding to the bits with non-zero * coefficient. Array is terminated with -1. Up to max elements of the array * will be filled. Return value is total number of array elements that would * be filled if array was large enough. */ int BN_GF2m_poly2arr(const BIGNUM *a, int p[], int max) { int i, j, k = 0; BN_ULONG mask; if (BN_is_zero(a)) return 0; for (i = a->top - 1; i >= 0; i--) { if (!a->d[i]) /* skip word if a->d[i] == 0 */ continue; mask = BN_TBIT; for (j = BN_BITS2 - 1; j >= 0; j--) { if (a->d[i] & mask) { if (k < max) p[k] = BN_BITS2 * i + j; k++; } mask >>= 1; } } if (k < max) { p[k] = -1; k++; } return k; } /* * Convert the coefficient array representation of a polynomial to a * bit-string. The array must be terminated by -1. */ int BN_GF2m_arr2poly(const int p[], BIGNUM *a) { int i; bn_check_top(a); BN_zero(a); for (i = 0; p[i] != -1; i++) { if (BN_set_bit(a, p[i]) == 0) return 0; } bn_check_top(a); return 1; } #endif
./openssl/crypto/bn/bn_ctx.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 <openssl/trace.h> #include "internal/cryptlib.h" #include "bn_local.h" /* How many bignums are in each "pool item"; */ #define BN_CTX_POOL_SIZE 16 /* The stack frame info is resizing, set a first-time expansion size; */ #define BN_CTX_START_FRAMES 32 /***********/ /* BN_POOL */ /***********/ /* A bundle of bignums that can be linked with other bundles */ typedef struct bignum_pool_item { /* The bignum values */ BIGNUM vals[BN_CTX_POOL_SIZE]; /* Linked-list admin */ struct bignum_pool_item *prev, *next; } BN_POOL_ITEM; /* A linked-list of bignums grouped in bundles */ typedef struct bignum_pool { /* Linked-list admin */ BN_POOL_ITEM *head, *current, *tail; /* Stack depth and allocation size */ unsigned used, size; } BN_POOL; static void BN_POOL_init(BN_POOL *); static void BN_POOL_finish(BN_POOL *); static BIGNUM *BN_POOL_get(BN_POOL *, int); static void BN_POOL_release(BN_POOL *, unsigned int); /************/ /* BN_STACK */ /************/ /* A wrapper to manage the "stack frames" */ typedef struct bignum_ctx_stack { /* Array of indexes into the bignum stack */ unsigned int *indexes; /* Number of stack frames, and the size of the allocated array */ unsigned int depth, size; } BN_STACK; static void BN_STACK_init(BN_STACK *); static void BN_STACK_finish(BN_STACK *); static int BN_STACK_push(BN_STACK *, unsigned int); static unsigned int BN_STACK_pop(BN_STACK *); /**********/ /* BN_CTX */ /**********/ /* The opaque BN_CTX type */ struct bignum_ctx { /* The bignum bundles */ BN_POOL pool; /* The "stack frames", if you will */ BN_STACK stack; /* The number of bignums currently assigned */ unsigned int used; /* Depth of stack overflow */ int err_stack; /* Block "gets" until an "end" (compatibility behaviour) */ int too_many; /* Flags. */ int flags; /* The library context */ OSSL_LIB_CTX *libctx; }; #ifndef FIPS_MODULE /* Debugging functionality */ static void ctxdbg(BIO *channel, const char *text, BN_CTX *ctx) { unsigned int bnidx = 0, fpidx = 0; BN_POOL_ITEM *item = ctx->pool.head; BN_STACK *stack = &ctx->stack; BIO_printf(channel, "%s\n", text); BIO_printf(channel, " (%16p): ", (void*)ctx); while (bnidx < ctx->used) { BIO_printf(channel, "%03x ", item->vals[bnidx++ % BN_CTX_POOL_SIZE].dmax); if (!(bnidx % BN_CTX_POOL_SIZE)) item = item->next; } BIO_printf(channel, "\n"); bnidx = 0; BIO_printf(channel, " %16s : ", ""); while (fpidx < stack->depth) { while (bnidx++ < stack->indexes[fpidx]) BIO_printf(channel, " "); BIO_printf(channel, "^^^ "); bnidx++; fpidx++; } BIO_printf(channel, "\n"); } # define CTXDBG(str, ctx) \ OSSL_TRACE_BEGIN(BN_CTX) { \ ctxdbg(trc_out, str, ctx); \ } OSSL_TRACE_END(BN_CTX) #else /* We do not want tracing in FIPS module */ # define CTXDBG(str, ctx) do {} while(0) #endif /* FIPS_MODULE */ BN_CTX *BN_CTX_new_ex(OSSL_LIB_CTX *ctx) { BN_CTX *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; /* Initialise the structure */ BN_POOL_init(&ret->pool); BN_STACK_init(&ret->stack); ret->libctx = ctx; return ret; } #ifndef FIPS_MODULE BN_CTX *BN_CTX_new(void) { return BN_CTX_new_ex(NULL); } #endif BN_CTX *BN_CTX_secure_new_ex(OSSL_LIB_CTX *ctx) { BN_CTX *ret = BN_CTX_new_ex(ctx); if (ret != NULL) ret->flags = BN_FLG_SECURE; return ret; } #ifndef FIPS_MODULE BN_CTX *BN_CTX_secure_new(void) { return BN_CTX_secure_new_ex(NULL); } #endif void BN_CTX_free(BN_CTX *ctx) { if (ctx == NULL) return; #ifndef FIPS_MODULE OSSL_TRACE_BEGIN(BN_CTX) { BN_POOL_ITEM *pool = ctx->pool.head; BIO_printf(trc_out, "BN_CTX_free(): stack-size=%d, pool-bignums=%d\n", ctx->stack.size, ctx->pool.size); BIO_printf(trc_out, " dmaxs: "); while (pool) { unsigned loop = 0; while (loop < BN_CTX_POOL_SIZE) BIO_printf(trc_out, "%02x ", pool->vals[loop++].dmax); pool = pool->next; } BIO_printf(trc_out, "\n"); } OSSL_TRACE_END(BN_CTX); #endif BN_STACK_finish(&ctx->stack); BN_POOL_finish(&ctx->pool); OPENSSL_free(ctx); } void BN_CTX_start(BN_CTX *ctx) { CTXDBG("ENTER BN_CTX_start()", ctx); /* If we're already overflowing ... */ if (ctx->err_stack || ctx->too_many) ctx->err_stack++; /* (Try to) get a new frame pointer */ else if (!BN_STACK_push(&ctx->stack, ctx->used)) { ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES); ctx->err_stack++; } CTXDBG("LEAVE BN_CTX_start()", ctx); } void BN_CTX_end(BN_CTX *ctx) { if (ctx == NULL) return; CTXDBG("ENTER BN_CTX_end()", ctx); if (ctx->err_stack) ctx->err_stack--; else { unsigned int fp = BN_STACK_pop(&ctx->stack); /* Does this stack frame have anything to release? */ if (fp < ctx->used) BN_POOL_release(&ctx->pool, ctx->used - fp); ctx->used = fp; /* Unjam "too_many" in case "get" had failed */ ctx->too_many = 0; } CTXDBG("LEAVE BN_CTX_end()", ctx); } BIGNUM *BN_CTX_get(BN_CTX *ctx) { BIGNUM *ret; CTXDBG("ENTER BN_CTX_get()", ctx); if (ctx->err_stack || ctx->too_many) return NULL; if ((ret = BN_POOL_get(&ctx->pool, ctx->flags)) == NULL) { /* * Setting too_many prevents repeated "get" attempts from cluttering * the error stack. */ ctx->too_many = 1; ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES); return NULL; } /* OK, make sure the returned bignum is "zero" */ BN_zero(ret); /* clear BN_FLG_CONSTTIME if leaked from previous frames */ ret->flags &= (~BN_FLG_CONSTTIME); ctx->used++; CTXDBG("LEAVE BN_CTX_get()", ctx); return ret; } OSSL_LIB_CTX *ossl_bn_get_libctx(BN_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->libctx; } /************/ /* BN_STACK */ /************/ static void BN_STACK_init(BN_STACK *st) { st->indexes = NULL; st->depth = st->size = 0; } static void BN_STACK_finish(BN_STACK *st) { OPENSSL_free(st->indexes); st->indexes = NULL; } static int BN_STACK_push(BN_STACK *st, unsigned int idx) { if (st->depth == st->size) { /* Need to expand */ unsigned int newsize = st->size ? (st->size * 3 / 2) : BN_CTX_START_FRAMES; unsigned int *newitems; if ((newitems = OPENSSL_malloc(sizeof(*newitems) * newsize)) == NULL) return 0; if (st->depth) memcpy(newitems, st->indexes, sizeof(*newitems) * st->depth); OPENSSL_free(st->indexes); st->indexes = newitems; st->size = newsize; } st->indexes[(st->depth)++] = idx; return 1; } static unsigned int BN_STACK_pop(BN_STACK *st) { return st->indexes[--(st->depth)]; } /***********/ /* BN_POOL */ /***********/ static void BN_POOL_init(BN_POOL *p) { p->head = p->current = p->tail = NULL; p->used = p->size = 0; } static void BN_POOL_finish(BN_POOL *p) { unsigned int loop; BIGNUM *bn; while (p->head) { for (loop = 0, bn = p->head->vals; loop++ < BN_CTX_POOL_SIZE; bn++) if (bn->d) BN_clear_free(bn); p->current = p->head->next; OPENSSL_free(p->head); p->head = p->current; } } static BIGNUM *BN_POOL_get(BN_POOL *p, int flag) { BIGNUM *bn; unsigned int loop; /* Full; allocate a new pool item and link it in. */ if (p->used == p->size) { BN_POOL_ITEM *item; if ((item = OPENSSL_malloc(sizeof(*item))) == NULL) return NULL; for (loop = 0, bn = item->vals; loop++ < BN_CTX_POOL_SIZE; bn++) { bn_init(bn); if ((flag & BN_FLG_SECURE) != 0) BN_set_flags(bn, BN_FLG_SECURE); } item->prev = p->tail; item->next = NULL; if (p->head == NULL) p->head = p->current = p->tail = item; else { p->tail->next = item; p->tail = item; p->current = item; } p->size += BN_CTX_POOL_SIZE; p->used++; /* Return the first bignum from the new pool */ return item->vals; } if (!p->used) p->current = p->head; else if ((p->used % BN_CTX_POOL_SIZE) == 0) p->current = p->current->next; return p->current->vals + ((p->used++) % BN_CTX_POOL_SIZE); } static void BN_POOL_release(BN_POOL *p, unsigned int num) { unsigned int offset = (p->used - 1) % BN_CTX_POOL_SIZE; p->used -= num; while (num--) { bn_check_top(p->current->vals + offset); if (offset == 0) { offset = BN_CTX_POOL_SIZE - 1; p->current = p->current->prev; } else offset--; } }
./openssl/crypto/bn/asm/x86_64-gcc.c
/* * Copyright 2002-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 "../bn_local.h" #if !(defined(__GNUC__) && __GNUC__>=2) # include "../bn_asm.c" /* kind of dirty hack for Sun Studio */ #else /*- * x86_64 BIGNUM accelerator version 0.1, December 2002. * * Implemented by Andy Polyakov <appro@openssl.org> for the OpenSSL * project. * * Rights for redistribution and usage in source and binary forms are * granted according to the License. Warranty of any kind is disclaimed. * * Q. Version 0.1? It doesn't sound like Andy, he used to assign real * versions, like 1.0... * A. Well, that's because this code is basically a quick-n-dirty * proof-of-concept hack. As you can see it's implemented with * inline assembler, which means that you're bound to GCC and that * there might be enough room for further improvement. * * Q. Why inline assembler? * A. x86_64 features own ABI which I'm not familiar with. This is * why I decided to let the compiler take care of subroutine * prologue/epilogue as well as register allocation. For reference. * Win64 implements different ABI for AMD64, different from Linux. * * Q. How much faster does it get? * A. 'apps/openssl speed rsa dsa' output with no-asm: * * sign verify sign/s verify/s * rsa 512 bits 0.0006s 0.0001s 1683.8 18456.2 * rsa 1024 bits 0.0028s 0.0002s 356.0 6407.0 * rsa 2048 bits 0.0172s 0.0005s 58.0 1957.8 * rsa 4096 bits 0.1155s 0.0018s 8.7 555.6 * sign verify sign/s verify/s * dsa 512 bits 0.0005s 0.0006s 2100.8 1768.3 * dsa 1024 bits 0.0014s 0.0018s 692.3 559.2 * dsa 2048 bits 0.0049s 0.0061s 204.7 165.0 * * 'apps/openssl speed rsa dsa' output with this module: * * sign verify sign/s verify/s * rsa 512 bits 0.0004s 0.0000s 2767.1 33297.9 * rsa 1024 bits 0.0012s 0.0001s 867.4 14674.7 * rsa 2048 bits 0.0061s 0.0002s 164.0 5270.0 * rsa 4096 bits 0.0384s 0.0006s 26.1 1650.8 * sign verify sign/s verify/s * dsa 512 bits 0.0002s 0.0003s 4442.2 3786.3 * dsa 1024 bits 0.0005s 0.0007s 1835.1 1497.4 * dsa 2048 bits 0.0016s 0.0020s 620.4 504.6 * * For the reference. IA-32 assembler implementation performs * very much like 64-bit code compiled with no-asm on the same * machine. */ # undef mul # undef mul_add /*- * "m"(a), "+m"(r) is the way to favor DirectPath µ-code; * "g"(0) let the compiler to decide where does it * want to keep the value of zero; */ # define mul_add(r,a,word,carry) do { \ register BN_ULONG high,low; \ asm ("mulq %3" \ : "=a"(low),"=d"(high) \ : "a"(word),"m"(a) \ : "cc"); \ asm ("addq %2,%0; adcq %3,%1" \ : "+r"(carry),"+d"(high)\ : "a"(low),"g"(0) \ : "cc"); \ asm ("addq %2,%0; adcq %3,%1" \ : "+m"(r),"+d"(high) \ : "r"(carry),"g"(0) \ : "cc"); \ carry=high; \ } while (0) # define mul(r,a,word,carry) do { \ register BN_ULONG high,low; \ asm ("mulq %3" \ : "=a"(low),"=d"(high) \ : "a"(word),"g"(a) \ : "cc"); \ asm ("addq %2,%0; adcq %3,%1" \ : "+r"(carry),"+d"(high)\ : "a"(low),"g"(0) \ : "cc"); \ (r)=carry, carry=high; \ } while (0) # undef sqr # define sqr(r0,r1,a) \ asm ("mulq %2" \ : "=a"(r0),"=d"(r1) \ : "a"(a) \ : "cc"); BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) { BN_ULONG c1 = 0; if (num <= 0) return c1; while (num & ~3) { mul_add(rp[0], ap[0], w, c1); mul_add(rp[1], ap[1], w, c1); mul_add(rp[2], ap[2], w, c1); mul_add(rp[3], ap[3], w, c1); ap += 4; rp += 4; num -= 4; } if (num) { mul_add(rp[0], ap[0], w, c1); if (--num == 0) return c1; mul_add(rp[1], ap[1], w, c1); if (--num == 0) return c1; mul_add(rp[2], ap[2], w, c1); return c1; } return c1; } BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) { BN_ULONG c1 = 0; if (num <= 0) return c1; while (num & ~3) { mul(rp[0], ap[0], w, c1); mul(rp[1], ap[1], w, c1); mul(rp[2], ap[2], w, c1); mul(rp[3], ap[3], w, c1); ap += 4; rp += 4; num -= 4; } if (num) { mul(rp[0], ap[0], w, c1); if (--num == 0) return c1; mul(rp[1], ap[1], w, c1); if (--num == 0) return c1; mul(rp[2], ap[2], w, c1); } return c1; } void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, int n) { if (n <= 0) return; while (n & ~3) { sqr(r[0], r[1], a[0]); sqr(r[2], r[3], a[1]); sqr(r[4], r[5], a[2]); sqr(r[6], r[7], a[3]); a += 4; r += 8; n -= 4; } if (n) { sqr(r[0], r[1], a[0]); if (--n == 0) return; sqr(r[2], r[3], a[1]); if (--n == 0) return; sqr(r[4], r[5], a[2]); } } BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d) { BN_ULONG ret, waste; asm("divq %4":"=a"(ret), "=d"(waste) : "a"(l), "d"(h), "r"(d) : "cc"); return ret; } BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, int n) { BN_ULONG ret; size_t i = 0; if (n <= 0) return 0; asm volatile (" subq %0,%0 \n" /* clear carry */ " jmp 1f \n" ".p2align 4 \n" "1: movq (%4,%2,8),%0 \n" " adcq (%5,%2,8),%0 \n" " movq %0,(%3,%2,8) \n" " lea 1(%2),%2 \n" " dec %1 \n" " jnz 1b \n" " sbbq %0,%0 \n" :"=&r" (ret), "+c"(n), "+r"(i) :"r"(rp), "r"(ap), "r"(bp) :"cc", "memory"); return ret & 1; } # ifndef SIMICS BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, int n) { BN_ULONG ret; size_t i = 0; if (n <= 0) return 0; asm volatile (" subq %0,%0 \n" /* clear borrow */ " jmp 1f \n" ".p2align 4 \n" "1: movq (%4,%2,8),%0 \n" " sbbq (%5,%2,8),%0 \n" " movq %0,(%3,%2,8) \n" " lea 1(%2),%2 \n" " dec %1 \n" " jnz 1b \n" " sbbq %0,%0 \n" :"=&r" (ret), "+c"(n), "+r"(i) :"r"(rp), "r"(ap), "r"(bp) :"cc", "memory"); return ret & 1; } # else /* Simics 1.4<7 has buggy sbbq:-( */ # define BN_MASK2 0xffffffffffffffffL BN_ULONG bn_sub_words(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n) { BN_ULONG t1, t2; int c = 0; if (n <= 0) return (BN_ULONG)0; for (;;) { t1 = a[0]; t2 = b[0]; r[0] = (t1 - t2 - c) & BN_MASK2; if (t1 != t2) c = (t1 < t2); if (--n <= 0) break; t1 = a[1]; t2 = b[1]; r[1] = (t1 - t2 - c) & BN_MASK2; if (t1 != t2) c = (t1 < t2); if (--n <= 0) break; t1 = a[2]; t2 = b[2]; r[2] = (t1 - t2 - c) & BN_MASK2; if (t1 != t2) c = (t1 < t2); if (--n <= 0) break; t1 = a[3]; t2 = b[3]; r[3] = (t1 - t2 - c) & BN_MASK2; if (t1 != t2) c = (t1 < t2); if (--n <= 0) break; a += 4; b += 4; r += 4; } return c; } # endif /* mul_add_c(a,b,c0,c1,c2) -- c+=a*b for three word number c=(c2,c1,c0) */ /* mul_add_c2(a,b,c0,c1,c2) -- c+=2*a*b for three word number c=(c2,c1,c0) */ /* sqr_add_c(a,i,c0,c1,c2) -- c+=a[i]^2 for three word number c=(c2,c1,c0) */ /* * sqr_add_c2(a,i,c0,c1,c2) -- c+=2*a[i]*a[j] for three word number * c=(c2,c1,c0) */ /* * Keep in mind that carrying into high part of multiplication result * can not overflow, because it cannot be all-ones. */ # if 0 /* original macros are kept for reference purposes */ # define mul_add_c(a,b,c0,c1,c2) do { \ BN_ULONG ta = (a), tb = (b); \ BN_ULONG lo, hi; \ BN_UMULT_LOHI(lo,hi,ta,tb); \ c0 += lo; hi += (c0<lo)?1:0; \ c1 += hi; c2 += (c1<hi)?1:0; \ } while(0) # define mul_add_c2(a,b,c0,c1,c2) do { \ BN_ULONG ta = (a), tb = (b); \ BN_ULONG lo, hi, tt; \ BN_UMULT_LOHI(lo,hi,ta,tb); \ c0 += lo; tt = hi+((c0<lo)?1:0); \ c1 += tt; c2 += (c1<tt)?1:0; \ c0 += lo; hi += (c0<lo)?1:0; \ c1 += hi; c2 += (c1<hi)?1:0; \ } while(0) # define sqr_add_c(a,i,c0,c1,c2) do { \ BN_ULONG ta = (a)[i]; \ BN_ULONG lo, hi; \ BN_UMULT_LOHI(lo,hi,ta,ta); \ c0 += lo; hi += (c0<lo)?1:0; \ c1 += hi; c2 += (c1<hi)?1:0; \ } while(0) # else # define mul_add_c(a,b,c0,c1,c2) do { \ BN_ULONG t1,t2; \ asm ("mulq %3" \ : "=a"(t1),"=d"(t2) \ : "a"(a),"m"(b) \ : "cc"); \ asm ("addq %3,%0; adcq %4,%1; adcq %5,%2" \ : "+r"(c0),"+r"(c1),"+r"(c2) \ : "r"(t1),"r"(t2),"g"(0) \ : "cc"); \ } while (0) # define sqr_add_c(a,i,c0,c1,c2) do { \ BN_ULONG t1,t2; \ asm ("mulq %2" \ : "=a"(t1),"=d"(t2) \ : "a"(a[i]) \ : "cc"); \ asm ("addq %3,%0; adcq %4,%1; adcq %5,%2" \ : "+r"(c0),"+r"(c1),"+r"(c2) \ : "r"(t1),"r"(t2),"g"(0) \ : "cc"); \ } while (0) # define mul_add_c2(a,b,c0,c1,c2) do { \ BN_ULONG t1,t2; \ asm ("mulq %3" \ : "=a"(t1),"=d"(t2) \ : "a"(a),"m"(b) \ : "cc"); \ asm ("addq %3,%0; adcq %4,%1; adcq %5,%2" \ : "+r"(c0),"+r"(c1),"+r"(c2) \ : "r"(t1),"r"(t2),"g"(0) \ : "cc"); \ asm ("addq %3,%0; adcq %4,%1; adcq %5,%2" \ : "+r"(c0),"+r"(c1),"+r"(c2) \ : "r"(t1),"r"(t2),"g"(0) \ : "cc"); \ } while (0) # endif # define sqr_add_c2(a,i,j,c0,c1,c2) \ mul_add_c2((a)[i],(a)[j],c0,c1,c2) void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; mul_add_c(a[0], b[0], c1, c2, c3); r[0] = c1; c1 = 0; mul_add_c(a[0], b[1], c2, c3, c1); mul_add_c(a[1], b[0], c2, c3, c1); r[1] = c2; c2 = 0; mul_add_c(a[2], b[0], c3, c1, c2); mul_add_c(a[1], b[1], c3, c1, c2); mul_add_c(a[0], b[2], c3, c1, c2); r[2] = c3; c3 = 0; mul_add_c(a[0], b[3], c1, c2, c3); mul_add_c(a[1], b[2], c1, c2, c3); mul_add_c(a[2], b[1], c1, c2, c3); mul_add_c(a[3], b[0], c1, c2, c3); r[3] = c1; c1 = 0; mul_add_c(a[4], b[0], c2, c3, c1); mul_add_c(a[3], b[1], c2, c3, c1); mul_add_c(a[2], b[2], c2, c3, c1); mul_add_c(a[1], b[3], c2, c3, c1); mul_add_c(a[0], b[4], c2, c3, c1); r[4] = c2; c2 = 0; mul_add_c(a[0], b[5], c3, c1, c2); mul_add_c(a[1], b[4], c3, c1, c2); mul_add_c(a[2], b[3], c3, c1, c2); mul_add_c(a[3], b[2], c3, c1, c2); mul_add_c(a[4], b[1], c3, c1, c2); mul_add_c(a[5], b[0], c3, c1, c2); r[5] = c3; c3 = 0; mul_add_c(a[6], b[0], c1, c2, c3); mul_add_c(a[5], b[1], c1, c2, c3); mul_add_c(a[4], b[2], c1, c2, c3); mul_add_c(a[3], b[3], c1, c2, c3); mul_add_c(a[2], b[4], c1, c2, c3); mul_add_c(a[1], b[5], c1, c2, c3); mul_add_c(a[0], b[6], c1, c2, c3); r[6] = c1; c1 = 0; mul_add_c(a[0], b[7], c2, c3, c1); mul_add_c(a[1], b[6], c2, c3, c1); mul_add_c(a[2], b[5], c2, c3, c1); mul_add_c(a[3], b[4], c2, c3, c1); mul_add_c(a[4], b[3], c2, c3, c1); mul_add_c(a[5], b[2], c2, c3, c1); mul_add_c(a[6], b[1], c2, c3, c1); mul_add_c(a[7], b[0], c2, c3, c1); r[7] = c2; c2 = 0; mul_add_c(a[7], b[1], c3, c1, c2); mul_add_c(a[6], b[2], c3, c1, c2); mul_add_c(a[5], b[3], c3, c1, c2); mul_add_c(a[4], b[4], c3, c1, c2); mul_add_c(a[3], b[5], c3, c1, c2); mul_add_c(a[2], b[6], c3, c1, c2); mul_add_c(a[1], b[7], c3, c1, c2); r[8] = c3; c3 = 0; mul_add_c(a[2], b[7], c1, c2, c3); mul_add_c(a[3], b[6], c1, c2, c3); mul_add_c(a[4], b[5], c1, c2, c3); mul_add_c(a[5], b[4], c1, c2, c3); mul_add_c(a[6], b[3], c1, c2, c3); mul_add_c(a[7], b[2], c1, c2, c3); r[9] = c1; c1 = 0; mul_add_c(a[7], b[3], c2, c3, c1); mul_add_c(a[6], b[4], c2, c3, c1); mul_add_c(a[5], b[5], c2, c3, c1); mul_add_c(a[4], b[6], c2, c3, c1); mul_add_c(a[3], b[7], c2, c3, c1); r[10] = c2; c2 = 0; mul_add_c(a[4], b[7], c3, c1, c2); mul_add_c(a[5], b[6], c3, c1, c2); mul_add_c(a[6], b[5], c3, c1, c2); mul_add_c(a[7], b[4], c3, c1, c2); r[11] = c3; c3 = 0; mul_add_c(a[7], b[5], c1, c2, c3); mul_add_c(a[6], b[6], c1, c2, c3); mul_add_c(a[5], b[7], c1, c2, c3); r[12] = c1; c1 = 0; mul_add_c(a[6], b[7], c2, c3, c1); mul_add_c(a[7], b[6], c2, c3, c1); r[13] = c2; c2 = 0; mul_add_c(a[7], b[7], c3, c1, c2); r[14] = c3; r[15] = c1; } void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; mul_add_c(a[0], b[0], c1, c2, c3); r[0] = c1; c1 = 0; mul_add_c(a[0], b[1], c2, c3, c1); mul_add_c(a[1], b[0], c2, c3, c1); r[1] = c2; c2 = 0; mul_add_c(a[2], b[0], c3, c1, c2); mul_add_c(a[1], b[1], c3, c1, c2); mul_add_c(a[0], b[2], c3, c1, c2); r[2] = c3; c3 = 0; mul_add_c(a[0], b[3], c1, c2, c3); mul_add_c(a[1], b[2], c1, c2, c3); mul_add_c(a[2], b[1], c1, c2, c3); mul_add_c(a[3], b[0], c1, c2, c3); r[3] = c1; c1 = 0; mul_add_c(a[3], b[1], c2, c3, c1); mul_add_c(a[2], b[2], c2, c3, c1); mul_add_c(a[1], b[3], c2, c3, c1); r[4] = c2; c2 = 0; mul_add_c(a[2], b[3], c3, c1, c2); mul_add_c(a[3], b[2], c3, c1, c2); r[5] = c3; c3 = 0; mul_add_c(a[3], b[3], c1, c2, c3); r[6] = c1; r[7] = c2; } void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; sqr_add_c(a, 0, c1, c2, c3); r[0] = c1; c1 = 0; sqr_add_c2(a, 1, 0, c2, c3, c1); r[1] = c2; c2 = 0; sqr_add_c(a, 1, c3, c1, c2); sqr_add_c2(a, 2, 0, c3, c1, c2); r[2] = c3; c3 = 0; sqr_add_c2(a, 3, 0, c1, c2, c3); sqr_add_c2(a, 2, 1, c1, c2, c3); r[3] = c1; c1 = 0; sqr_add_c(a, 2, c2, c3, c1); sqr_add_c2(a, 3, 1, c2, c3, c1); sqr_add_c2(a, 4, 0, c2, c3, c1); r[4] = c2; c2 = 0; sqr_add_c2(a, 5, 0, c3, c1, c2); sqr_add_c2(a, 4, 1, c3, c1, c2); sqr_add_c2(a, 3, 2, c3, c1, c2); r[5] = c3; c3 = 0; sqr_add_c(a, 3, c1, c2, c3); sqr_add_c2(a, 4, 2, c1, c2, c3); sqr_add_c2(a, 5, 1, c1, c2, c3); sqr_add_c2(a, 6, 0, c1, c2, c3); r[6] = c1; c1 = 0; sqr_add_c2(a, 7, 0, c2, c3, c1); sqr_add_c2(a, 6, 1, c2, c3, c1); sqr_add_c2(a, 5, 2, c2, c3, c1); sqr_add_c2(a, 4, 3, c2, c3, c1); r[7] = c2; c2 = 0; sqr_add_c(a, 4, c3, c1, c2); sqr_add_c2(a, 5, 3, c3, c1, c2); sqr_add_c2(a, 6, 2, c3, c1, c2); sqr_add_c2(a, 7, 1, c3, c1, c2); r[8] = c3; c3 = 0; sqr_add_c2(a, 7, 2, c1, c2, c3); sqr_add_c2(a, 6, 3, c1, c2, c3); sqr_add_c2(a, 5, 4, c1, c2, c3); r[9] = c1; c1 = 0; sqr_add_c(a, 5, c2, c3, c1); sqr_add_c2(a, 6, 4, c2, c3, c1); sqr_add_c2(a, 7, 3, c2, c3, c1); r[10] = c2; c2 = 0; sqr_add_c2(a, 7, 4, c3, c1, c2); sqr_add_c2(a, 6, 5, c3, c1, c2); r[11] = c3; c3 = 0; sqr_add_c(a, 6, c1, c2, c3); sqr_add_c2(a, 7, 5, c1, c2, c3); r[12] = c1; c1 = 0; sqr_add_c2(a, 7, 6, c2, c3, c1); r[13] = c2; c2 = 0; sqr_add_c(a, 7, c3, c1, c2); r[14] = c3; r[15] = c1; } void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; sqr_add_c(a, 0, c1, c2, c3); r[0] = c1; c1 = 0; sqr_add_c2(a, 1, 0, c2, c3, c1); r[1] = c2; c2 = 0; sqr_add_c(a, 1, c3, c1, c2); sqr_add_c2(a, 2, 0, c3, c1, c2); r[2] = c3; c3 = 0; sqr_add_c2(a, 3, 0, c1, c2, c3); sqr_add_c2(a, 2, 1, c1, c2, c3); r[3] = c1; c1 = 0; sqr_add_c(a, 2, c2, c3, c1); sqr_add_c2(a, 3, 1, c2, c3, c1); r[4] = c2; c2 = 0; sqr_add_c2(a, 3, 2, c3, c1, c2); r[5] = c3; c3 = 0; sqr_add_c(a, 3, c1, c2, c3); r[6] = c1; r[7] = c2; } #endif
./openssl/crypto/bf/bf_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 */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/blowfish.h> #include "bf_local.h" /* * Blowfish as implemented from 'Blowfish: Springer-Verlag paper' (From * LECTURE NOTES IN COMPUTER SCIENCE 809, FAST SOFTWARE ENCRYPTION, CAMBRIDGE * SECURITY WORKSHOP, CAMBRIDGE, U.K., DECEMBER 9-11, 1993) */ #if (BF_ROUNDS != 16) && (BF_ROUNDS != 20) # error If you set BF_ROUNDS to some value other than 16 or 20, you will have \ to modify the code. #endif void BF_encrypt(BF_LONG *data, const BF_KEY *key) { register BF_LONG l, r; register const BF_LONG *p, *s; p = key->P; s = &(key->S[0]); l = data[0]; r = data[1]; l ^= p[0]; BF_ENC(r, l, s, p[1]); BF_ENC(l, r, s, p[2]); BF_ENC(r, l, s, p[3]); BF_ENC(l, r, s, p[4]); BF_ENC(r, l, s, p[5]); BF_ENC(l, r, s, p[6]); BF_ENC(r, l, s, p[7]); BF_ENC(l, r, s, p[8]); BF_ENC(r, l, s, p[9]); BF_ENC(l, r, s, p[10]); BF_ENC(r, l, s, p[11]); BF_ENC(l, r, s, p[12]); BF_ENC(r, l, s, p[13]); BF_ENC(l, r, s, p[14]); BF_ENC(r, l, s, p[15]); BF_ENC(l, r, s, p[16]); # if BF_ROUNDS == 20 BF_ENC(r, l, s, p[17]); BF_ENC(l, r, s, p[18]); BF_ENC(r, l, s, p[19]); BF_ENC(l, r, s, p[20]); # endif r ^= p[BF_ROUNDS + 1]; data[1] = l & 0xffffffffU; data[0] = r & 0xffffffffU; } void BF_decrypt(BF_LONG *data, const BF_KEY *key) { register BF_LONG l, r; register const BF_LONG *p, *s; p = key->P; s = &(key->S[0]); l = data[0]; r = data[1]; l ^= p[BF_ROUNDS + 1]; # if BF_ROUNDS == 20 BF_ENC(r, l, s, p[20]); BF_ENC(l, r, s, p[19]); BF_ENC(r, l, s, p[18]); BF_ENC(l, r, s, p[17]); # endif BF_ENC(r, l, s, p[16]); BF_ENC(l, r, s, p[15]); BF_ENC(r, l, s, p[14]); BF_ENC(l, r, s, p[13]); BF_ENC(r, l, s, p[12]); BF_ENC(l, r, s, p[11]); BF_ENC(r, l, s, p[10]); BF_ENC(l, r, s, p[9]); BF_ENC(r, l, s, p[8]); BF_ENC(l, r, s, p[7]); BF_ENC(r, l, s, p[6]); BF_ENC(l, r, s, p[5]); BF_ENC(r, l, s, p[4]); BF_ENC(l, r, s, p[3]); BF_ENC(r, l, s, p[2]); BF_ENC(l, r, s, p[1]); r ^= p[0]; data[1] = l & 0xffffffffU; data[0] = r & 0xffffffffU; } void BF_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, const BF_KEY *schedule, unsigned char *ivec, int encrypt) { register BF_LONG tin0, tin1; register BF_LONG tout0, tout1, xor0, xor1; register long l = length; BF_LONG tin[2]; if (encrypt) { n2l(ivec, tout0); n2l(ivec, tout1); ivec -= 8; for (l -= 8; l >= 0; l -= 8) { n2l(in, tin0); n2l(in, tin1); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; BF_encrypt(tin, schedule); tout0 = tin[0]; tout1 = tin[1]; l2n(tout0, out); l2n(tout1, out); } if (l != -8) { n2ln(in, tin0, tin1, l + 8); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; BF_encrypt(tin, schedule); tout0 = tin[0]; tout1 = tin[1]; l2n(tout0, out); l2n(tout1, out); } l2n(tout0, ivec); l2n(tout1, ivec); } else { n2l(ivec, xor0); n2l(ivec, xor1); ivec -= 8; for (l -= 8; l >= 0; l -= 8) { n2l(in, tin0); n2l(in, tin1); tin[0] = tin0; tin[1] = tin1; BF_decrypt(tin, schedule); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2n(tout0, out); l2n(tout1, out); xor0 = tin0; xor1 = tin1; } if (l != -8) { n2l(in, tin0); n2l(in, tin1); tin[0] = tin0; tin[1] = tin1; BF_decrypt(tin, schedule); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2nn(tout0, tout1, out, l + 8); xor0 = tin0; xor1 = tin1; } l2n(xor0, ivec); l2n(xor1, ivec); } tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; tin[0] = tin[1] = 0; }
./openssl/crypto/bf/bf_ofb64.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 */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/blowfish.h> #include "bf_local.h" /* * The input and output encrypted as though 64bit ofb mode is being used. * The extra state information to record how much of the 64bit block we have * used is contained in *num; */ void BF_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, const BF_KEY *schedule, unsigned char *ivec, int *num) { register BF_LONG v0, v1, t; register int n = *num; register long l = length; unsigned char d[8]; register char *dp; BF_LONG ti[2]; unsigned char *iv; int save = 0; iv = (unsigned char *)ivec; n2l(iv, v0); n2l(iv, v1); ti[0] = v0; ti[1] = v1; dp = (char *)d; l2n(v0, dp); l2n(v1, dp); while (l--) { if (n == 0) { BF_encrypt((BF_LONG *)ti, schedule); dp = (char *)d; t = ti[0]; l2n(t, dp); t = ti[1]; l2n(t, dp); save++; } *(out++) = *(in++) ^ d[n]; n = (n + 1) & 0x07; } if (save) { v0 = ti[0]; v1 = ti[1]; iv = (unsigned char *)ivec; l2n(v0, iv); l2n(v1, iv); } t = v0 = v1 = ti[0] = ti[1] = 0; *num = n; }
./openssl/crypto/bf/bf_pi.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 */ static const BF_KEY bf_init = { { 0x243f6a88L, 0x85a308d3L, 0x13198a2eL, 0x03707344L, 0xa4093822L, 0x299f31d0L, 0x082efa98L, 0xec4e6c89L, 0x452821e6L, 0x38d01377L, 0xbe5466cfL, 0x34e90c6cL, 0xc0ac29b7L, 0xc97c50ddL, 0x3f84d5b5L, 0xb5470917L, 0x9216d5d9L, 0x8979fb1b}, { 0xd1310ba6L, 0x98dfb5acL, 0x2ffd72dbL, 0xd01adfb7L, 0xb8e1afedL, 0x6a267e96L, 0xba7c9045L, 0xf12c7f99L, 0x24a19947L, 0xb3916cf7L, 0x0801f2e2L, 0x858efc16L, 0x636920d8L, 0x71574e69L, 0xa458fea3L, 0xf4933d7eL, 0x0d95748fL, 0x728eb658L, 0x718bcd58L, 0x82154aeeL, 0x7b54a41dL, 0xc25a59b5L, 0x9c30d539L, 0x2af26013L, 0xc5d1b023L, 0x286085f0L, 0xca417918L, 0xb8db38efL, 0x8e79dcb0L, 0x603a180eL, 0x6c9e0e8bL, 0xb01e8a3eL, 0xd71577c1L, 0xbd314b27L, 0x78af2fdaL, 0x55605c60L, 0xe65525f3L, 0xaa55ab94L, 0x57489862L, 0x63e81440L, 0x55ca396aL, 0x2aab10b6L, 0xb4cc5c34L, 0x1141e8ceL, 0xa15486afL, 0x7c72e993L, 0xb3ee1411L, 0x636fbc2aL, 0x2ba9c55dL, 0x741831f6L, 0xce5c3e16L, 0x9b87931eL, 0xafd6ba33L, 0x6c24cf5cL, 0x7a325381L, 0x28958677L, 0x3b8f4898L, 0x6b4bb9afL, 0xc4bfe81bL, 0x66282193L, 0x61d809ccL, 0xfb21a991L, 0x487cac60L, 0x5dec8032L, 0xef845d5dL, 0xe98575b1L, 0xdc262302L, 0xeb651b88L, 0x23893e81L, 0xd396acc5L, 0x0f6d6ff3L, 0x83f44239L, 0x2e0b4482L, 0xa4842004L, 0x69c8f04aL, 0x9e1f9b5eL, 0x21c66842L, 0xf6e96c9aL, 0x670c9c61L, 0xabd388f0L, 0x6a51a0d2L, 0xd8542f68L, 0x960fa728L, 0xab5133a3L, 0x6eef0b6cL, 0x137a3be4L, 0xba3bf050L, 0x7efb2a98L, 0xa1f1651dL, 0x39af0176L, 0x66ca593eL, 0x82430e88L, 0x8cee8619L, 0x456f9fb4L, 0x7d84a5c3L, 0x3b8b5ebeL, 0xe06f75d8L, 0x85c12073L, 0x401a449fL, 0x56c16aa6L, 0x4ed3aa62L, 0x363f7706L, 0x1bfedf72L, 0x429b023dL, 0x37d0d724L, 0xd00a1248L, 0xdb0fead3L, 0x49f1c09bL, 0x075372c9L, 0x80991b7bL, 0x25d479d8L, 0xf6e8def7L, 0xe3fe501aL, 0xb6794c3bL, 0x976ce0bdL, 0x04c006baL, 0xc1a94fb6L, 0x409f60c4L, 0x5e5c9ec2L, 0x196a2463L, 0x68fb6fafL, 0x3e6c53b5L, 0x1339b2ebL, 0x3b52ec6fL, 0x6dfc511fL, 0x9b30952cL, 0xcc814544L, 0xaf5ebd09L, 0xbee3d004L, 0xde334afdL, 0x660f2807L, 0x192e4bb3L, 0xc0cba857L, 0x45c8740fL, 0xd20b5f39L, 0xb9d3fbdbL, 0x5579c0bdL, 0x1a60320aL, 0xd6a100c6L, 0x402c7279L, 0x679f25feL, 0xfb1fa3ccL, 0x8ea5e9f8L, 0xdb3222f8L, 0x3c7516dfL, 0xfd616b15L, 0x2f501ec8L, 0xad0552abL, 0x323db5faL, 0xfd238760L, 0x53317b48L, 0x3e00df82L, 0x9e5c57bbL, 0xca6f8ca0L, 0x1a87562eL, 0xdf1769dbL, 0xd542a8f6L, 0x287effc3L, 0xac6732c6L, 0x8c4f5573L, 0x695b27b0L, 0xbbca58c8L, 0xe1ffa35dL, 0xb8f011a0L, 0x10fa3d98L, 0xfd2183b8L, 0x4afcb56cL, 0x2dd1d35bL, 0x9a53e479L, 0xb6f84565L, 0xd28e49bcL, 0x4bfb9790L, 0xe1ddf2daL, 0xa4cb7e33L, 0x62fb1341L, 0xcee4c6e8L, 0xef20cadaL, 0x36774c01L, 0xd07e9efeL, 0x2bf11fb4L, 0x95dbda4dL, 0xae909198L, 0xeaad8e71L, 0x6b93d5a0L, 0xd08ed1d0L, 0xafc725e0L, 0x8e3c5b2fL, 0x8e7594b7L, 0x8ff6e2fbL, 0xf2122b64L, 0x8888b812L, 0x900df01cL, 0x4fad5ea0L, 0x688fc31cL, 0xd1cff191L, 0xb3a8c1adL, 0x2f2f2218L, 0xbe0e1777L, 0xea752dfeL, 0x8b021fa1L, 0xe5a0cc0fL, 0xb56f74e8L, 0x18acf3d6L, 0xce89e299L, 0xb4a84fe0L, 0xfd13e0b7L, 0x7cc43b81L, 0xd2ada8d9L, 0x165fa266L, 0x80957705L, 0x93cc7314L, 0x211a1477L, 0xe6ad2065L, 0x77b5fa86L, 0xc75442f5L, 0xfb9d35cfL, 0xebcdaf0cL, 0x7b3e89a0L, 0xd6411bd3L, 0xae1e7e49L, 0x00250e2dL, 0x2071b35eL, 0x226800bbL, 0x57b8e0afL, 0x2464369bL, 0xf009b91eL, 0x5563911dL, 0x59dfa6aaL, 0x78c14389L, 0xd95a537fL, 0x207d5ba2L, 0x02e5b9c5L, 0x83260376L, 0x6295cfa9L, 0x11c81968L, 0x4e734a41L, 0xb3472dcaL, 0x7b14a94aL, 0x1b510052L, 0x9a532915L, 0xd60f573fL, 0xbc9bc6e4L, 0x2b60a476L, 0x81e67400L, 0x08ba6fb5L, 0x571be91fL, 0xf296ec6bL, 0x2a0dd915L, 0xb6636521L, 0xe7b9f9b6L, 0xff34052eL, 0xc5855664L, 0x53b02d5dL, 0xa99f8fa1L, 0x08ba4799L, 0x6e85076aL, 0x4b7a70e9L, 0xb5b32944L, 0xdb75092eL, 0xc4192623L, 0xad6ea6b0L, 0x49a7df7dL, 0x9cee60b8L, 0x8fedb266L, 0xecaa8c71L, 0x699a17ffL, 0x5664526cL, 0xc2b19ee1L, 0x193602a5L, 0x75094c29L, 0xa0591340L, 0xe4183a3eL, 0x3f54989aL, 0x5b429d65L, 0x6b8fe4d6L, 0x99f73fd6L, 0xa1d29c07L, 0xefe830f5L, 0x4d2d38e6L, 0xf0255dc1L, 0x4cdd2086L, 0x8470eb26L, 0x6382e9c6L, 0x021ecc5eL, 0x09686b3fL, 0x3ebaefc9L, 0x3c971814L, 0x6b6a70a1L, 0x687f3584L, 0x52a0e286L, 0xb79c5305L, 0xaa500737L, 0x3e07841cL, 0x7fdeae5cL, 0x8e7d44ecL, 0x5716f2b8L, 0xb03ada37L, 0xf0500c0dL, 0xf01c1f04L, 0x0200b3ffL, 0xae0cf51aL, 0x3cb574b2L, 0x25837a58L, 0xdc0921bdL, 0xd19113f9L, 0x7ca92ff6L, 0x94324773L, 0x22f54701L, 0x3ae5e581L, 0x37c2dadcL, 0xc8b57634L, 0x9af3dda7L, 0xa9446146L, 0x0fd0030eL, 0xecc8c73eL, 0xa4751e41L, 0xe238cd99L, 0x3bea0e2fL, 0x3280bba1L, 0x183eb331L, 0x4e548b38L, 0x4f6db908L, 0x6f420d03L, 0xf60a04bfL, 0x2cb81290L, 0x24977c79L, 0x5679b072L, 0xbcaf89afL, 0xde9a771fL, 0xd9930810L, 0xb38bae12L, 0xdccf3f2eL, 0x5512721fL, 0x2e6b7124L, 0x501adde6L, 0x9f84cd87L, 0x7a584718L, 0x7408da17L, 0xbc9f9abcL, 0xe94b7d8cL, 0xec7aec3aL, 0xdb851dfaL, 0x63094366L, 0xc464c3d2L, 0xef1c1847L, 0x3215d908L, 0xdd433b37L, 0x24c2ba16L, 0x12a14d43L, 0x2a65c451L, 0x50940002L, 0x133ae4ddL, 0x71dff89eL, 0x10314e55L, 0x81ac77d6L, 0x5f11199bL, 0x043556f1L, 0xd7a3c76bL, 0x3c11183bL, 0x5924a509L, 0xf28fe6edL, 0x97f1fbfaL, 0x9ebabf2cL, 0x1e153c6eL, 0x86e34570L, 0xeae96fb1L, 0x860e5e0aL, 0x5a3e2ab3L, 0x771fe71cL, 0x4e3d06faL, 0x2965dcb9L, 0x99e71d0fL, 0x803e89d6L, 0x5266c825L, 0x2e4cc978L, 0x9c10b36aL, 0xc6150ebaL, 0x94e2ea78L, 0xa5fc3c53L, 0x1e0a2df4L, 0xf2f74ea7L, 0x361d2b3dL, 0x1939260fL, 0x19c27960L, 0x5223a708L, 0xf71312b6L, 0xebadfe6eL, 0xeac31f66L, 0xe3bc4595L, 0xa67bc883L, 0xb17f37d1L, 0x018cff28L, 0xc332ddefL, 0xbe6c5aa5L, 0x65582185L, 0x68ab9802L, 0xeecea50fL, 0xdb2f953bL, 0x2aef7dadL, 0x5b6e2f84L, 0x1521b628L, 0x29076170L, 0xecdd4775L, 0x619f1510L, 0x13cca830L, 0xeb61bd96L, 0x0334fe1eL, 0xaa0363cfL, 0xb5735c90L, 0x4c70a239L, 0xd59e9e0bL, 0xcbaade14L, 0xeecc86bcL, 0x60622ca7L, 0x9cab5cabL, 0xb2f3846eL, 0x648b1eafL, 0x19bdf0caL, 0xa02369b9L, 0x655abb50L, 0x40685a32L, 0x3c2ab4b3L, 0x319ee9d5L, 0xc021b8f7L, 0x9b540b19L, 0x875fa099L, 0x95f7997eL, 0x623d7da8L, 0xf837889aL, 0x97e32d77L, 0x11ed935fL, 0x16681281L, 0x0e358829L, 0xc7e61fd6L, 0x96dedfa1L, 0x7858ba99L, 0x57f584a5L, 0x1b227263L, 0x9b83c3ffL, 0x1ac24696L, 0xcdb30aebL, 0x532e3054L, 0x8fd948e4L, 0x6dbc3128L, 0x58ebf2efL, 0x34c6ffeaL, 0xfe28ed61L, 0xee7c3c73L, 0x5d4a14d9L, 0xe864b7e3L, 0x42105d14L, 0x203e13e0L, 0x45eee2b6L, 0xa3aaabeaL, 0xdb6c4f15L, 0xfacb4fd0L, 0xc742f442L, 0xef6abbb5L, 0x654f3b1dL, 0x41cd2105L, 0xd81e799eL, 0x86854dc7L, 0xe44b476aL, 0x3d816250L, 0xcf62a1f2L, 0x5b8d2646L, 0xfc8883a0L, 0xc1c7b6a3L, 0x7f1524c3L, 0x69cb7492L, 0x47848a0bL, 0x5692b285L, 0x095bbf00L, 0xad19489dL, 0x1462b174L, 0x23820e00L, 0x58428d2aL, 0x0c55f5eaL, 0x1dadf43eL, 0x233f7061L, 0x3372f092L, 0x8d937e41L, 0xd65fecf1L, 0x6c223bdbL, 0x7cde3759L, 0xcbee7460L, 0x4085f2a7L, 0xce77326eL, 0xa6078084L, 0x19f8509eL, 0xe8efd855L, 0x61d99735L, 0xa969a7aaL, 0xc50c06c2L, 0x5a04abfcL, 0x800bcadcL, 0x9e447a2eL, 0xc3453484L, 0xfdd56705L, 0x0e1e9ec9L, 0xdb73dbd3L, 0x105588cdL, 0x675fda79L, 0xe3674340L, 0xc5c43465L, 0x713e38d8L, 0x3d28f89eL, 0xf16dff20L, 0x153e21e7L, 0x8fb03d4aL, 0xe6e39f2bL, 0xdb83adf7L, 0xe93d5a68L, 0x948140f7L, 0xf64c261cL, 0x94692934L, 0x411520f7L, 0x7602d4f7L, 0xbcf46b2eL, 0xd4a20068L, 0xd4082471L, 0x3320f46aL, 0x43b7d4b7L, 0x500061afL, 0x1e39f62eL, 0x97244546L, 0x14214f74L, 0xbf8b8840L, 0x4d95fc1dL, 0x96b591afL, 0x70f4ddd3L, 0x66a02f45L, 0xbfbc09ecL, 0x03bd9785L, 0x7fac6dd0L, 0x31cb8504L, 0x96eb27b3L, 0x55fd3941L, 0xda2547e6L, 0xabca0a9aL, 0x28507825L, 0x530429f4L, 0x0a2c86daL, 0xe9b66dfbL, 0x68dc1462L, 0xd7486900L, 0x680ec0a4L, 0x27a18deeL, 0x4f3ffea2L, 0xe887ad8cL, 0xb58ce006L, 0x7af4d6b6L, 0xaace1e7cL, 0xd3375fecL, 0xce78a399L, 0x406b2a42L, 0x20fe9e35L, 0xd9f385b9L, 0xee39d7abL, 0x3b124e8bL, 0x1dc9faf7L, 0x4b6d1856L, 0x26a36631L, 0xeae397b2L, 0x3a6efa74L, 0xdd5b4332L, 0x6841e7f7L, 0xca7820fbL, 0xfb0af54eL, 0xd8feb397L, 0x454056acL, 0xba489527L, 0x55533a3aL, 0x20838d87L, 0xfe6ba9b7L, 0xd096954bL, 0x55a867bcL, 0xa1159a58L, 0xcca92963L, 0x99e1db33L, 0xa62a4a56L, 0x3f3125f9L, 0x5ef47e1cL, 0x9029317cL, 0xfdf8e802L, 0x04272f70L, 0x80bb155cL, 0x05282ce3L, 0x95c11548L, 0xe4c66d22L, 0x48c1133fL, 0xc70f86dcL, 0x07f9c9eeL, 0x41041f0fL, 0x404779a4L, 0x5d886e17L, 0x325f51ebL, 0xd59bc0d1L, 0xf2bcc18fL, 0x41113564L, 0x257b7834L, 0x602a9c60L, 0xdff8e8a3L, 0x1f636c1bL, 0x0e12b4c2L, 0x02e1329eL, 0xaf664fd1L, 0xcad18115L, 0x6b2395e0L, 0x333e92e1L, 0x3b240b62L, 0xeebeb922L, 0x85b2a20eL, 0xe6ba0d99L, 0xde720c8cL, 0x2da2f728L, 0xd0127845L, 0x95b794fdL, 0x647d0862L, 0xe7ccf5f0L, 0x5449a36fL, 0x877d48faL, 0xc39dfd27L, 0xf33e8d1eL, 0x0a476341L, 0x992eff74L, 0x3a6f6eabL, 0xf4f8fd37L, 0xa812dc60L, 0xa1ebddf8L, 0x991be14cL, 0xdb6e6b0dL, 0xc67b5510L, 0x6d672c37L, 0x2765d43bL, 0xdcd0e804L, 0xf1290dc7L, 0xcc00ffa3L, 0xb5390f92L, 0x690fed0bL, 0x667b9ffbL, 0xcedb7d9cL, 0xa091cf0bL, 0xd9155ea3L, 0xbb132f88L, 0x515bad24L, 0x7b9479bfL, 0x763bd6ebL, 0x37392eb3L, 0xcc115979L, 0x8026e297L, 0xf42e312dL, 0x6842ada7L, 0xc66a2b3bL, 0x12754cccL, 0x782ef11cL, 0x6a124237L, 0xb79251e7L, 0x06a1bbe6L, 0x4bfb6350L, 0x1a6b1018L, 0x11caedfaL, 0x3d25bdd8L, 0xe2e1c3c9L, 0x44421659L, 0x0a121386L, 0xd90cec6eL, 0xd5abea2aL, 0x64af674eL, 0xda86a85fL, 0xbebfe988L, 0x64e4c3feL, 0x9dbc8057L, 0xf0f7c086L, 0x60787bf8L, 0x6003604dL, 0xd1fd8346L, 0xf6381fb0L, 0x7745ae04L, 0xd736fcccL, 0x83426b33L, 0xf01eab71L, 0xb0804187L, 0x3c005e5fL, 0x77a057beL, 0xbde8ae24L, 0x55464299L, 0xbf582e61L, 0x4e58f48fL, 0xf2ddfda2L, 0xf474ef38L, 0x8789bdc2L, 0x5366f9c3L, 0xc8b38e74L, 0xb475f255L, 0x46fcd9b9L, 0x7aeb2661L, 0x8b1ddf84L, 0x846a0e79L, 0x915f95e2L, 0x466e598eL, 0x20b45770L, 0x8cd55591L, 0xc902de4cL, 0xb90bace1L, 0xbb8205d0L, 0x11a86248L, 0x7574a99eL, 0xb77f19b6L, 0xe0a9dc09L, 0x662d09a1L, 0xc4324633L, 0xe85a1f02L, 0x09f0be8cL, 0x4a99a025L, 0x1d6efe10L, 0x1ab93d1dL, 0x0ba5a4dfL, 0xa186f20fL, 0x2868f169L, 0xdcb7da83L, 0x573906feL, 0xa1e2ce9bL, 0x4fcd7f52L, 0x50115e01L, 0xa70683faL, 0xa002b5c4L, 0x0de6d027L, 0x9af88c27L, 0x773f8641L, 0xc3604c06L, 0x61a806b5L, 0xf0177a28L, 0xc0f586e0L, 0x006058aaL, 0x30dc7d62L, 0x11e69ed7L, 0x2338ea63L, 0x53c2dd94L, 0xc2c21634L, 0xbbcbee56L, 0x90bcb6deL, 0xebfc7da1L, 0xce591d76L, 0x6f05e409L, 0x4b7c0188L, 0x39720a3dL, 0x7c927c24L, 0x86e3725fL, 0x724d9db9L, 0x1ac15bb4L, 0xd39eb8fcL, 0xed545578L, 0x08fca5b5L, 0xd83d7cd3L, 0x4dad0fc4L, 0x1e50ef5eL, 0xb161e6f8L, 0xa28514d9L, 0x6c51133cL, 0x6fd5c7e7L, 0x56e14ec4L, 0x362abfceL, 0xddc6c837L, 0xd79a3234L, 0x92638212L, 0x670efa8eL, 0x406000e0L, 0x3a39ce37L, 0xd3faf5cfL, 0xabc27737L, 0x5ac52d1bL, 0x5cb0679eL, 0x4fa33742L, 0xd3822740L, 0x99bc9bbeL, 0xd5118e9dL, 0xbf0f7315L, 0xd62d1c7eL, 0xc700c47bL, 0xb78c1b6bL, 0x21a19045L, 0xb26eb1beL, 0x6a366eb4L, 0x5748ab2fL, 0xbc946e79L, 0xc6a376d2L, 0x6549c2c8L, 0x530ff8eeL, 0x468dde7dL, 0xd5730a1dL, 0x4cd04dc6L, 0x2939bbdbL, 0xa9ba4650L, 0xac9526e8L, 0xbe5ee304L, 0xa1fad5f0L, 0x6a2d519aL, 0x63ef8ce2L, 0x9a86ee22L, 0xc089c2b8L, 0x43242ef6L, 0xa51e03aaL, 0x9cf2d0a4L, 0x83c061baL, 0x9be96a4dL, 0x8fe51550L, 0xba645bd6L, 0x2826a2f9L, 0xa73a3ae1L, 0x4ba99586L, 0xef5562e9L, 0xc72fefd3L, 0xf752f7daL, 0x3f046f69L, 0x77fa0a59L, 0x80e4a915L, 0x87b08601L, 0x9b09e6adL, 0x3b3ee593L, 0xe990fd5aL, 0x9e34d797L, 0x2cf0b7d9L, 0x022b8b51L, 0x96d5ac3aL, 0x017da67dL, 0xd1cf3ed6L, 0x7c7d2d28L, 0x1f9f25cfL, 0xadf2b89bL, 0x5ad6b472L, 0x5a88f54cL, 0xe029ac71L, 0xe019a5e6L, 0x47b0acfdL, 0xed93fa9bL, 0xe8d3c48dL, 0x283b57ccL, 0xf8d56629L, 0x79132e28L, 0x785f0191L, 0xed756055L, 0xf7960e44L, 0xe3d35e8cL, 0x15056dd4L, 0x88f46dbaL, 0x03a16125L, 0x0564f0bdL, 0xc3eb9e15L, 0x3c9057a2L, 0x97271aecL, 0xa93a072aL, 0x1b3f6d9bL, 0x1e6321f5L, 0xf59c66fbL, 0x26dcf319L, 0x7533d928L, 0xb155fdf5L, 0x03563482L, 0x8aba3cbbL, 0x28517711L, 0xc20ad9f8L, 0xabcc5167L, 0xccad925fL, 0x4de81751L, 0x3830dc8eL, 0x379d5862L, 0x9320f991L, 0xea7a90c2L, 0xfb3e7bceL, 0x5121ce64L, 0x774fbe32L, 0xa8b6e37eL, 0xc3293d46L, 0x48de5369L, 0x6413e680L, 0xa2ae0810L, 0xdd6db224L, 0x69852dfdL, 0x09072166L, 0xb39a460aL, 0x6445c0ddL, 0x586cdecfL, 0x1c20c8aeL, 0x5bbef7ddL, 0x1b588d40L, 0xccd2017fL, 0x6bb4e3bbL, 0xdda26a7eL, 0x3a59ff45L, 0x3e350a44L, 0xbcb4cdd5L, 0x72eacea8L, 0xfa6484bbL, 0x8d6612aeL, 0xbf3c6f47L, 0xd29be463L, 0x542f5d9eL, 0xaec2771bL, 0xf64e6370L, 0x740e0d8dL, 0xe75b1357L, 0xf8721671L, 0xaf537d5dL, 0x4040cb08L, 0x4eb4e2ccL, 0x34d2466aL, 0x0115af84L, 0xe1b00428L, 0x95983a1dL, 0x06b89fb4L, 0xce6ea048L, 0x6f3f3b82L, 0x3520ab82L, 0x011a1d4bL, 0x277227f8L, 0x611560b1L, 0xe7933fdcL, 0xbb3a792bL, 0x344525bdL, 0xa08839e1L, 0x51ce794bL, 0x2f32c9b7L, 0xa01fbac9L, 0xe01cc87eL, 0xbcc7d1f6L, 0xcf0111c3L, 0xa1e8aac7L, 0x1a908749L, 0xd44fbd9aL, 0xd0dadecbL, 0xd50ada38L, 0x0339c32aL, 0xc6913667L, 0x8df9317cL, 0xe0b12b4fL, 0xf79e59b7L, 0x43f5bb3aL, 0xf2d519ffL, 0x27d9459cL, 0xbf97222cL, 0x15e6fc2aL, 0x0f91fc71L, 0x9b941525L, 0xfae59361L, 0xceb69cebL, 0xc2a86459L, 0x12baa8d1L, 0xb6c1075eL, 0xe3056a0cL, 0x10d25065L, 0xcb03a442L, 0xe0ec6e0eL, 0x1698db3bL, 0x4c98a0beL, 0x3278e964L, 0x9f1f9532L, 0xe0d392dfL, 0xd3a0342bL, 0x8971f21eL, 0x1b0a7441L, 0x4ba3348cL, 0xc5be7120L, 0xc37632d8L, 0xdf359f8dL, 0x9b992f2eL, 0xe60b6f47L, 0x0fe3f11dL, 0xe54cda54L, 0x1edad891L, 0xce6279cfL, 0xcd3e7e6fL, 0x1618b166L, 0xfd2c1d05L, 0x848fd2c5L, 0xf6fb2299L, 0xf523f357L, 0xa6327623L, 0x93a83531L, 0x56cccd02L, 0xacf08162L, 0x5a75ebb5L, 0x6e163697L, 0x88d273ccL, 0xde966292L, 0x81b949d0L, 0x4c50901bL, 0x71c65614L, 0xe6c6c7bdL, 0x327a140aL, 0x45e1d006L, 0xc3f27b9aL, 0xc9aa53fdL, 0x62a80f00L, 0xbb25bfe2L, 0x35bdd2f6L, 0x71126905L, 0xb2040222L, 0xb6cbcf7cL, 0xcd769c2bL, 0x53113ec0L, 0x1640e3d3L, 0x38abbd60L, 0x2547adf0L, 0xba38209cL, 0xf746ce76L, 0x77afa1c5L, 0x20756060L, 0x85cbfe4eL, 0x8ae88dd8L, 0x7aaaf9b0L, 0x4cf9aa7eL, 0x1948c25cL, 0x02fb8a8cL, 0x01c36ae4L, 0xd6ebe1f9L, 0x90d4f869L, 0xa65cdea0L, 0x3f09252dL, 0xc208e69fL, 0xb74e6132L, 0xce77e25bL, 0x578fdfe3L, 0x3ac372e6L, } };
./openssl/crypto/bf/bf_skey.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 */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include <openssl/blowfish.h> #include "bf_local.h" #include "bf_pi.h" void BF_set_key(BF_KEY *key, int len, const unsigned char *data) { int i; BF_LONG *p, ri, in[2]; const unsigned char *d, *end; memcpy(key, &bf_init, sizeof(BF_KEY)); p = key->P; if (len > ((BF_ROUNDS + 2) * 4)) len = (BF_ROUNDS + 2) * 4; d = data; end = &(data[len]); for (i = 0; i < (BF_ROUNDS + 2); i++) { ri = *(d++); if (d >= end) d = data; ri <<= 8; ri |= *(d++); if (d >= end) d = data; ri <<= 8; ri |= *(d++); if (d >= end) d = data; ri <<= 8; ri |= *(d++); if (d >= end) d = data; p[i] ^= ri; } in[0] = 0L; in[1] = 0L; for (i = 0; i < (BF_ROUNDS + 2); i += 2) { BF_encrypt(in, key); p[i] = in[0]; p[i + 1] = in[1]; } p = key->S; for (i = 0; i < 4 * 256; i += 2) { BF_encrypt(in, key); p[i] = in[0]; p[i + 1] = in[1]; } }
./openssl/crypto/bf/bf_ecb.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 */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/blowfish.h> #include "bf_local.h" #include <openssl/opensslv.h> /* * Blowfish as implemented from 'Blowfish: Springer-Verlag paper' (From * LECTURE NOTES IN COMPUTER SCIENCE 809, FAST SOFTWARE ENCRYPTION, CAMBRIDGE * SECURITY WORKSHOP, CAMBRIDGE, U.K., DECEMBER 9-11, 1993) */ const char *BF_options(void) { return "blowfish(ptr)"; } void BF_ecb_encrypt(const unsigned char *in, unsigned char *out, const BF_KEY *key, int encrypt) { BF_LONG l, d[2]; n2l(in, l); d[0] = l; n2l(in, l); d[1] = l; if (encrypt) BF_encrypt(d, key); else BF_decrypt(d, key); l = d[0]; l2n(l, out); l = d[1]; l2n(l, out); l = d[0] = d[1] = 0; }
./openssl/crypto/bf/bf_local.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 */ #ifndef OSSL_CRYPTO_BF_LOCAL_H # define OSSL_CRYPTO_BF_LOCAL_H # include <openssl/opensslconf.h> /* NOTE - c is not incremented as per n2l */ # define n2ln(c,l1,l2,n) { \ c+=n; \ l1=l2=0; \ switch (n) { \ case 8: l2 =((unsigned long)(*(--(c)))) ; \ /* fall through */ \ case 7: l2|=((unsigned long)(*(--(c))))<< 8; \ /* fall through */ \ case 6: l2|=((unsigned long)(*(--(c))))<<16; \ /* fall through */ \ case 5: l2|=((unsigned long)(*(--(c))))<<24; \ /* fall through */ \ case 4: l1 =((unsigned long)(*(--(c)))) ; \ /* fall through */ \ case 3: l1|=((unsigned long)(*(--(c))))<< 8; \ /* fall through */ \ case 2: l1|=((unsigned long)(*(--(c))))<<16; \ /* fall through */ \ case 1: l1|=((unsigned long)(*(--(c))))<<24; \ } \ } /* NOTE - c is not incremented as per l2n */ # define l2nn(l1,l2,c,n) { \ c+=n; \ switch (n) { \ case 8: *(--(c))=(unsigned char)(((l2) )&0xff); \ /* fall through */ \ case 7: *(--(c))=(unsigned char)(((l2)>> 8)&0xff); \ /* fall through */ \ case 6: *(--(c))=(unsigned char)(((l2)>>16)&0xff); \ /* fall through */ \ case 5: *(--(c))=(unsigned char)(((l2)>>24)&0xff); \ /* fall through */ \ case 4: *(--(c))=(unsigned char)(((l1) )&0xff); \ /* fall through */ \ case 3: *(--(c))=(unsigned char)(((l1)>> 8)&0xff); \ /* fall through */ \ case 2: *(--(c))=(unsigned char)(((l1)>>16)&0xff); \ /* fall through */ \ case 1: *(--(c))=(unsigned char)(((l1)>>24)&0xff); \ } \ } # undef n2l # define n2l(c,l) (l =((unsigned long)(*((c)++)))<<24L, \ l|=((unsigned long)(*((c)++)))<<16L, \ l|=((unsigned long)(*((c)++)))<< 8L, \ l|=((unsigned long)(*((c)++)))) # undef l2n # define l2n(l,c) (*((c)++)=(unsigned char)(((l)>>24L)&0xff), \ *((c)++)=(unsigned char)(((l)>>16L)&0xff), \ *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \ *((c)++)=(unsigned char)(((l) )&0xff)) /* * This is actually a big endian algorithm, the most significant byte is used * to lookup array 0 */ # define BF_ENC(LL,R,S,P) ( \ LL^=P, \ LL^=((( S[ ((R>>24)&0xff)] + \ S[0x0100+((R>>16)&0xff)])^ \ S[0x0200+((R>> 8)&0xff)])+ \ S[0x0300+((R )&0xff)])&0xffffffffU \ ) #endif
./openssl/crypto/bf/bf_cfb64.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 */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/blowfish.h> #include "bf_local.h" /* * The input and output encrypted as though 64bit cfb mode is being used. * The extra state information to record how much of the 64bit block we have * used is contained in *num; */ void BF_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, const BF_KEY *schedule, unsigned char *ivec, int *num, int encrypt) { register BF_LONG v0, v1, t; register int n = *num; register long l = length; BF_LONG ti[2]; unsigned char *iv, c, cc; iv = (unsigned char *)ivec; if (encrypt) { while (l--) { if (n == 0) { n2l(iv, v0); ti[0] = v0; n2l(iv, v1); ti[1] = v1; BF_encrypt((BF_LONG *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2n(t, iv); t = ti[1]; l2n(t, iv); iv = (unsigned char *)ivec; } c = *(in++) ^ iv[n]; *(out++) = c; iv[n] = c; n = (n + 1) & 0x07; } } else { while (l--) { if (n == 0) { n2l(iv, v0); ti[0] = v0; n2l(iv, v1); ti[1] = v1; BF_encrypt((BF_LONG *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2n(t, iv); t = ti[1]; l2n(t, iv); iv = (unsigned char *)ivec; } cc = *(in++); c = iv[n]; iv[n] = cc; *(out++) = c ^ cc; n = (n + 1) & 0x07; } } v0 = v1 = ti[0] = ti[1] = t = c = cc = 0; *num = n; }
./openssl/crypto/rand/rand_deprecated.c
/* * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/e_os.h" #include <openssl/macros.h> #include <openssl/rand.h> #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # include <windows.h> # if OPENSSL_API_COMPAT < 0x10100000L # define DEPRECATED_RAND_FUNCTIONS_DEFINED int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam) { RAND_poll(); return RAND_status(); } void RAND_screen(void) { RAND_poll(); } # endif #endif #ifndef DEPRECATED_RAND_FUNCTIONS_DEFINED NON_EMPTY_TRANSLATION_UNIT #endif
./openssl/crypto/rand/randfile.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 */ #if defined (__TANDEM) && defined (_SPT_MODEL_) /* * These definitions have to come first in SPT due to scoping of the * declarations in c99 associated with SPT use of stat. */ # include <sys/types.h> # include <sys/stat.h> #endif #include "internal/cryptlib.h" #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/crypto.h> #include <openssl/rand.h> #include <openssl/buffer.h> #ifdef OPENSSL_SYS_VMS # include <unixio.h> #endif #include <sys/types.h> #ifndef OPENSSL_NO_POSIX_IO # include <sys/stat.h> # include <fcntl.h> # if defined(_WIN32) && !defined(_WIN32_WCE) # include <windows.h> # include <io.h> # define stat _stat # define chmod _chmod # define open _open # define fdopen _fdopen # define fstat _fstat # define fileno _fileno # endif #endif /* * Following should not be needed, and we could have been stricter * and demand S_IS*. But some systems just don't comply... Formally * below macros are "anatomically incorrect", because normally they * would look like ((m) & MASK == TYPE), but since MASK availability * is as questionable, we settle for this poor-man fallback... */ # if !defined(S_ISREG) # define S_ISREG(m) ((m) & S_IFREG) # endif #define RAND_BUF_SIZE 1024 #define RFILE ".rnd" #ifdef OPENSSL_SYS_VMS /* * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically) * to make sure the FILE* is a 32-bit pointer no matter what. We know that * stdio functions return this type (a study of stdio.h proves it). * * This declaration is a nasty hack to get around vms' extension to fopen for * passing in sharing options being disabled by /STANDARD=ANSI89 */ static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) = (__FILE_ptr32 (*)(const char *, const char *, ...))fopen; # define VMS_OPEN_ATTRS \ "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0" # define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS) #endif /* * Note that these functions are intended for seed files only. Entropy * devices and EGD sockets are handled in rand_unix.c If |bytes| is * -1 read the complete file; otherwise read the specified amount. */ int RAND_load_file(const char *file, long bytes) { /* * The load buffer size exceeds the chunk size by the comfortable amount * of 'RAND_DRBG_STRENGTH' bytes (not bits!). This is done on purpose * to avoid calling RAND_add() with a small final chunk. Instead, such * a small final chunk will be added together with the previous chunk * (unless it's the only one). */ #define RAND_LOAD_BUF_SIZE (RAND_BUF_SIZE + RAND_DRBG_STRENGTH) unsigned char buf[RAND_LOAD_BUF_SIZE]; #ifndef OPENSSL_NO_POSIX_IO struct stat sb; #endif int i, n, ret = 0; FILE *in; if (bytes == 0) return 0; if ((in = openssl_fopen(file, "rb")) == NULL) { ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE, "Filename=%s", file); return -1; } #ifndef OPENSSL_NO_POSIX_IO if (fstat(fileno(in), &sb) < 0) { ERR_raise_data(ERR_LIB_RAND, RAND_R_INTERNAL_ERROR, "Filename=%s", file); fclose(in); return -1; } if (bytes < 0) { if (S_ISREG(sb.st_mode)) bytes = sb.st_size; else bytes = RAND_DRBG_STRENGTH; } #endif /* * On VMS, setbuf() will only take 32-bit pointers, and a compilation * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here. * However, we trust that the C RTL will never give us a FILE pointer * above the first 4 GB of memory, so we simply turn off the warning * temporarily. */ #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma environment save # pragma message disable maylosedata2 #endif /* * Don't buffer, because even if |file| is regular file, we have * no control over the buffer, so why would we want a copy of its * contents lying around? */ setbuf(in, NULL); #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma environment restore #endif for (;;) { if (bytes > 0) n = (bytes <= RAND_LOAD_BUF_SIZE) ? (int)bytes : RAND_BUF_SIZE; else n = RAND_LOAD_BUF_SIZE; i = fread(buf, 1, n, in); #ifdef EINTR if (ferror(in) && errno == EINTR) { clearerr(in); if (i == 0) continue; } #endif if (i == 0) break; RAND_add(buf, i, (double)i); ret += i; /* If given a bytecount, and we did it, break. */ if (bytes > 0 && (bytes -= i) <= 0) break; } OPENSSL_cleanse(buf, sizeof(buf)); fclose(in); if (!RAND_status()) { ERR_raise_data(ERR_LIB_RAND, RAND_R_RESEED_ERROR, "Filename=%s", file); return -1; } return ret; } int RAND_write_file(const char *file) { unsigned char buf[RAND_BUF_SIZE]; int ret = -1; FILE *out = NULL; #ifndef OPENSSL_NO_POSIX_IO struct stat sb; if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) { ERR_raise_data(ERR_LIB_RAND, RAND_R_NOT_A_REGULAR_FILE, "Filename=%s", file); return -1; } #endif /* Collect enough random data. */ if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1) return -1; #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \ !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS) { # ifndef O_BINARY # define O_BINARY 0 # endif /* * chmod(..., 0600) is too late to protect the file, permissions * should be restrictive from the start */ int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600); if (fd != -1) out = fdopen(fd, "wb"); } #endif #ifdef OPENSSL_SYS_VMS /* * VMS NOTE: Prior versions of this routine created a _new_ version of * the rand file for each call into this routine, then deleted all * existing versions named ;-1, and finally renamed the current version * as ';1'. Under concurrent usage, this resulted in an RMS race * condition in rename() which could orphan files (see vms message help * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares * the top-level version of the rand file. Note that there may still be * conditions where the top-level rand file is locked. If so, this code * will then create a new version of the rand file. Without the delete * and rename code, this can result in ascending file versions that stop * at version 32767, and this routine will then return an error. The * remedy for this is to recode the calling application to avoid * concurrent use of the rand file, or synchronize usage at the * application level. Also consider whether or not you NEED a persistent * rand file in a concurrent use situation. */ out = openssl_fopen(file, "rb+"); #endif if (out == NULL) out = openssl_fopen(file, "wb"); if (out == NULL) { ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE, "Filename=%s", file); return -1; } #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO) /* * Yes it's late to do this (see above comment), but better than nothing. */ chmod(file, 0600); #endif ret = fwrite(buf, 1, RAND_BUF_SIZE, out); fclose(out); OPENSSL_cleanse(buf, RAND_BUF_SIZE); return ret; } const char *RAND_file_name(char *buf, size_t size) { char *s = NULL; size_t len; int use_randfile = 1; #if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE) DWORD envlen; WCHAR *var; /* Look up various environment variables. */ if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) { use_randfile = 0; if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0 && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE", NULL, 0)) == 0) envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0); } /* If we got a value, allocate space to hold it and then get it. */ if (envlen != 0) { int sz; WCHAR *val = _alloca(envlen * sizeof(WCHAR)); if (GetEnvironmentVariableW(var, val, envlen) < envlen && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0, NULL, NULL)) != 0) { s = _alloca(sz); if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz, NULL, NULL) == 0) s = NULL; } } #else if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') { use_randfile = 0; s = ossl_safe_getenv("HOME"); } #endif #ifdef DEFAULT_HOME if (!use_randfile && s == NULL) s = DEFAULT_HOME; #endif if (s == NULL || *s == '\0') return NULL; len = strlen(s); if (use_randfile) { if (len + 1 >= size) return NULL; strcpy(buf, s); } else { if (len + 1 + strlen(RFILE) + 1 >= size) return NULL; strcpy(buf, s); #ifndef OPENSSL_SYS_VMS strcat(buf, "/"); #endif strcat(buf, RFILE); } return buf; }
./openssl/crypto/rand/prov_seed.c
/* * Copyright 2020-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "rand_local.h" #include "crypto/evp.h" #include "crypto/rand.h" #include "crypto/rand_pool.h" #include "internal/core.h" #include <openssl/core_dispatch.h> #include <openssl/err.h> size_t ossl_rand_get_entropy(ossl_unused OSSL_LIB_CTX *ctx, unsigned char **pout, int entropy, size_t min_len, size_t max_len) { size_t ret = 0; size_t entropy_available; RAND_POOL *pool; pool = ossl_rand_pool_new(entropy, 1, min_len, max_len); if (pool == NULL) { ERR_raise(ERR_LIB_RAND, ERR_R_RAND_LIB); return 0; } /* Get entropy by polling system entropy sources. */ entropy_available = ossl_pool_acquire_entropy(pool); if (entropy_available > 0) { ret = ossl_rand_pool_length(pool); *pout = ossl_rand_pool_detach(pool); } ossl_rand_pool_free(pool); return ret; } size_t ossl_rand_get_user_entropy(OSSL_LIB_CTX *ctx, unsigned char **pout, int entropy, size_t min_len, size_t max_len) { EVP_RAND_CTX *rng = ossl_rand_get0_seed_noncreating(ctx); if (rng != NULL && evp_rand_can_seed(rng)) return evp_rand_get_seed(rng, pout, entropy, min_len, max_len, 0, NULL, 0); else return ossl_rand_get_entropy(ctx, pout, entropy, min_len, max_len); } void ossl_rand_cleanup_entropy(ossl_unused OSSL_LIB_CTX *ctx, unsigned char *buf, size_t len) { OPENSSL_secure_clear_free(buf, len); } void ossl_rand_cleanup_user_entropy(OSSL_LIB_CTX *ctx, unsigned char *buf, size_t len) { EVP_RAND_CTX *rng = ossl_rand_get0_seed_noncreating(ctx); if (rng != NULL && evp_rand_can_seed(rng)) evp_rand_clear_seed(rng, buf, len); else OPENSSL_secure_clear_free(buf, len); } size_t ossl_rand_get_nonce(ossl_unused OSSL_LIB_CTX *ctx, unsigned char **pout, size_t min_len, ossl_unused size_t max_len, const void *salt, size_t salt_len) { size_t ret = 0; RAND_POOL *pool; pool = ossl_rand_pool_new(0, 0, min_len, max_len); if (pool == NULL) { ERR_raise(ERR_LIB_RAND, ERR_R_RAND_LIB); return 0; } if (!ossl_pool_add_nonce_data(pool)) goto err; if (salt != NULL && !ossl_rand_pool_add(pool, salt, salt_len, 0)) goto err; ret = ossl_rand_pool_length(pool); *pout = ossl_rand_pool_detach(pool); err: ossl_rand_pool_free(pool); return ret; } size_t ossl_rand_get_user_nonce(OSSL_LIB_CTX *ctx, unsigned char **pout, size_t min_len, size_t max_len, const void *salt, size_t salt_len) { unsigned char *buf; EVP_RAND_CTX *rng = ossl_rand_get0_seed_noncreating(ctx); if (rng == NULL) return ossl_rand_get_nonce(ctx, pout, min_len, max_len, salt, salt_len); if ((buf = OPENSSL_malloc(min_len)) == NULL) return 0; if (!EVP_RAND_generate(rng, buf, min_len, 0, 0, salt, salt_len)) { OPENSSL_free(buf); return 0; } *pout = buf; return min_len; } void ossl_rand_cleanup_nonce(ossl_unused OSSL_LIB_CTX *ctx, unsigned char *buf, size_t len) { OPENSSL_clear_free(buf, len); } void ossl_rand_cleanup_user_nonce(ossl_unused OSSL_LIB_CTX *ctx, unsigned char *buf, size_t len) { OPENSSL_clear_free(buf, len); }
./openssl/crypto/rand/rand_uniform.c
/* * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "crypto/rand.h" #include "internal/common.h" /* * Implementation an optimal random integer in a range function. * * Essentially it boils down to incrementally generating a fixed point * number on the interval [0, 1) and multiplying this number by the upper * range limit. Once it is certain what the fractional part contributes to * the integral part of the product, the algorithm has produced a definitive * result. * * Refer: https://github.com/apple/swift/pull/39143 for a fuller description * of the algorithm. */ uint32_t ossl_rand_uniform_uint32(OSSL_LIB_CTX *ctx, uint32_t upper, int *err) { uint32_t i, f; /* integer and fractional parts */ uint32_t f2, rand; /* extra fractional part and random material */ uint64_t prod; /* temporary holding double width product */ const int max_followup_iterations = 10; int j; if (!ossl_assert(upper > 0)) { *err = 0; return 0; } if (ossl_unlikely(upper == 1)) return 0; /* Get 32 bits of entropy */ if (RAND_bytes_ex(ctx, (unsigned char *)&rand, sizeof(rand), 0) <= 0) { *err = 1; return 0; } /* * We are generating a fixed point number on the interval [0, 1). * Multiplying this by the range gives us a number on [0, upper). * The high word of the multiplication result represents the integral * part we want. The lower word is the fractional part. We can early exit if * if the fractional part is small enough that no carry from the next lower * word can cause an overflow and carry into the integer part. This * happens when the fractional part is bounded by 2^32 - upper which * can be simplified to just -upper (as an unsigned integer). */ prod = (uint64_t)upper * rand; i = prod >> 32; f = prod & 0xffffffff; if (ossl_likely(f <= 1 + ~upper)) /* 1+~upper == -upper but compilers whine */ return i; /* * We're in the position where the carry from the next word *might* cause * a carry to the integral part. The process here is to generate the next * word, multiply it by the range and add that to the current word. If * it overflows, the carry propagates to the integer part (return i+1). * If it can no longer overflow regardless of further lower order bits, * we are done (return i). If there is still a chance of overflow, we * repeat the process with the next lower word. * * Each *bit* of randomness has a probability of one half of terminating * this process, so each each word beyond the first has a probability * of 2^-32 of not terminating the process. That is, we're extremely * likely to stop very rapidly. */ for (j = 0; j < max_followup_iterations; j++) { if (RAND_bytes_ex(ctx, (unsigned char *)&rand, sizeof(rand), 0) <= 0) { *err = 1; return 0; } prod = (uint64_t)upper * rand; f2 = prod >> 32; f += f2; /* On overflow, add the carry to our result */ if (f < f2) return i + 1; /* For not all 1 bits, there is no carry so return the result */ if (ossl_likely(f != 0xffffffff)) return i; /* setup for the next word of randomness */ f = prod & 0xffffffff; } /* * If we get here, we've consumed 32 * max_followup_iterations + 32 bits * with no firm decision, this gives a bias with probability < 2^-(32*n), * which is likely acceptable. */ return i; } uint32_t ossl_rand_range_uint32(OSSL_LIB_CTX *ctx, uint32_t lower, uint32_t upper, int *err) { if (!ossl_assert(lower < upper)) { *err = 1; return 0; } return lower + ossl_rand_uniform_uint32(ctx, upper - lower, err); }
./openssl/crypto/rand/rand_pool.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/opensslconf.h> #include "crypto/rand.h" #include <openssl/engine.h> #include "internal/thread_once.h" #include "crypto/rand_pool.h" /* * Allocate memory and initialize a new random pool */ RAND_POOL *ossl_rand_pool_new(int entropy_requested, int secure, size_t min_len, size_t max_len) { RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool)); size_t min_alloc_size = RAND_POOL_MIN_ALLOCATION(secure); if (pool == NULL) return NULL; pool->min_len = min_len; pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ? RAND_POOL_MAX_LENGTH : max_len; pool->alloc_len = min_len < min_alloc_size ? min_alloc_size : min_len; if (pool->alloc_len > pool->max_len) pool->alloc_len = pool->max_len; if (secure) pool->buffer = OPENSSL_secure_zalloc(pool->alloc_len); else pool->buffer = OPENSSL_zalloc(pool->alloc_len); if (pool->buffer == NULL) goto err; pool->entropy_requested = entropy_requested; pool->secure = secure; return pool; err: OPENSSL_free(pool); return NULL; } /* * Attach new random pool to the given buffer * * This function is intended to be used only for feeding random data * provided by RAND_add() and RAND_seed() into the <master> DRBG. */ RAND_POOL *ossl_rand_pool_attach(const unsigned char *buffer, size_t len, size_t entropy) { RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool)); if (pool == NULL) return NULL; /* * The const needs to be cast away, but attached buffers will not be * modified (in contrary to allocated buffers which are zeroed and * freed in the end). */ pool->buffer = (unsigned char *) buffer; pool->len = len; pool->attached = 1; pool->min_len = pool->max_len = pool->alloc_len = pool->len; pool->entropy = entropy; return pool; } /* * Free |pool|, securely erasing its buffer. */ void ossl_rand_pool_free(RAND_POOL *pool) { if (pool == NULL) return; /* * Although it would be advisable from a cryptographical viewpoint, * we are not allowed to clear attached buffers, since they are passed * to ossl_rand_pool_attach() as `const unsigned char*`. * (see corresponding comment in ossl_rand_pool_attach()). */ if (!pool->attached) { if (pool->secure) OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len); else OPENSSL_clear_free(pool->buffer, pool->alloc_len); } OPENSSL_free(pool); } /* * Return the |pool|'s buffer to the caller (readonly). */ const unsigned char *ossl_rand_pool_buffer(RAND_POOL *pool) { return pool->buffer; } /* * Return the |pool|'s entropy to the caller. */ size_t ossl_rand_pool_entropy(RAND_POOL *pool) { return pool->entropy; } /* * Return the |pool|'s buffer length to the caller. */ size_t ossl_rand_pool_length(RAND_POOL *pool) { return pool->len; } /* * Detach the |pool| buffer and return it to the caller. * It's the responsibility of the caller to free the buffer * using OPENSSL_secure_clear_free() or to re-attach it * again to the pool using ossl_rand_pool_reattach(). */ unsigned char *ossl_rand_pool_detach(RAND_POOL *pool) { unsigned char *ret = pool->buffer; pool->buffer = NULL; pool->entropy = 0; return ret; } /* * Re-attach the |pool| buffer. It is only allowed to pass * the |buffer| which was previously detached from the same pool. */ void ossl_rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer) { pool->buffer = buffer; OPENSSL_cleanse(pool->buffer, pool->len); pool->len = 0; } /* * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one * need to obtain at least |bits| bits of entropy? */ #define ENTROPY_TO_BYTES(bits, entropy_factor) \ (((bits) * (entropy_factor) + 7) / 8) /* * Checks whether the |pool|'s entropy is available to the caller. * This is the case when entropy count and buffer length are high enough. * Returns * * |entropy| if the entropy count and buffer size is large enough * 0 otherwise */ size_t ossl_rand_pool_entropy_available(RAND_POOL *pool) { if (pool->entropy < pool->entropy_requested) return 0; if (pool->len < pool->min_len) return 0; return pool->entropy; } /* * Returns the (remaining) amount of entropy needed to fill * the random pool. */ size_t ossl_rand_pool_entropy_needed(RAND_POOL *pool) { if (pool->entropy < pool->entropy_requested) return pool->entropy_requested - pool->entropy; return 0; } /* Increase the allocation size -- not usable for an attached pool */ static int rand_pool_grow(RAND_POOL *pool, size_t len) { if (len > pool->alloc_len - pool->len) { unsigned char *p; const size_t limit = pool->max_len / 2; size_t newlen = pool->alloc_len; if (pool->attached || len > pool->max_len - pool->len) { ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); return 0; } do newlen = newlen < limit ? newlen * 2 : pool->max_len; while (len > newlen - pool->len); if (pool->secure) p = OPENSSL_secure_zalloc(newlen); else p = OPENSSL_zalloc(newlen); if (p == NULL) return 0; memcpy(p, pool->buffer, pool->len); if (pool->secure) OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len); else OPENSSL_clear_free(pool->buffer, pool->alloc_len); pool->buffer = p; pool->alloc_len = newlen; } return 1; } /* * Returns the number of bytes needed to fill the pool, assuming * the input has 1 / |entropy_factor| entropy bits per data bit. * In case of an error, 0 is returned. */ size_t ossl_rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor) { size_t bytes_needed; size_t entropy_needed = ossl_rand_pool_entropy_needed(pool); if (entropy_factor < 1) { ERR_raise(ERR_LIB_RAND, RAND_R_ARGUMENT_OUT_OF_RANGE); return 0; } bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor); if (bytes_needed > pool->max_len - pool->len) { /* not enough space left */ ERR_raise_data(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW, "entropy_factor=%u, entropy_needed=%zu, bytes_needed=%zu," "pool->max_len=%zu, pool->len=%zu", entropy_factor, entropy_needed, bytes_needed, pool->max_len, pool->len); return 0; } if (pool->len < pool->min_len && bytes_needed < pool->min_len - pool->len) /* to meet the min_len requirement */ bytes_needed = pool->min_len - pool->len; /* * Make sure the buffer is large enough for the requested amount * of data. This guarantees that existing code patterns where * ossl_rand_pool_add_begin, ossl_rand_pool_add_end or ossl_rand_pool_add * are used to collect entropy data without any error handling * whatsoever, continue to be valid. * Furthermore if the allocation here fails once, make sure that * we don't fall back to a less secure or even blocking random source, * as that could happen by the existing code patterns. * This is not a concern for additional data, therefore that * is not needed if rand_pool_grow fails in other places. */ if (!rand_pool_grow(pool, bytes_needed)) { /* persistent error for this pool */ pool->max_len = pool->len = 0; return 0; } return bytes_needed; } /* Returns the remaining number of bytes available */ size_t ossl_rand_pool_bytes_remaining(RAND_POOL *pool) { return pool->max_len - pool->len; } /* * Add random bytes to the random pool. * * It is expected that the |buffer| contains |len| bytes of * random input which contains at least |entropy| bits of * randomness. * * Returns 1 if the added amount is adequate, otherwise 0 */ int ossl_rand_pool_add(RAND_POOL *pool, const unsigned char *buffer, size_t len, size_t entropy) { if (len > pool->max_len - pool->len) { ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_INPUT_TOO_LONG); return 0; } if (pool->buffer == NULL) { ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); return 0; } if (len > 0) { /* * This is to protect us from accidentally passing the buffer * returned from ossl_rand_pool_add_begin. * The check for alloc_len makes sure we do not compare the * address of the end of the allocated memory to something * different, since that comparison would have an * indeterminate result. */ if (pool->alloc_len > pool->len && pool->buffer + pool->len == buffer) { ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); return 0; } /* * We have that only for cases when a pool is used to collect * additional data. * For entropy data, as long as the allocation request stays within * the limits given by ossl_rand_pool_bytes_needed this rand_pool_grow * below is guaranteed to succeed, thus no allocation happens. */ if (!rand_pool_grow(pool, len)) return 0; memcpy(pool->buffer + pool->len, buffer, len); pool->len += len; pool->entropy += entropy; } return 1; } /* * Start to add random bytes to the random pool in-place. * * Reserves the next |len| bytes for adding random bytes in-place * and returns a pointer to the buffer. * The caller is allowed to copy up to |len| bytes into the buffer. * If |len| == 0 this is considered a no-op and a NULL pointer * is returned without producing an error message. * * After updating the buffer, ossl_rand_pool_add_end() needs to be called * to finish the update operation (see next comment). */ unsigned char *ossl_rand_pool_add_begin(RAND_POOL *pool, size_t len) { if (len == 0) return NULL; if (len > pool->max_len - pool->len) { ERR_raise(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW); return NULL; } if (pool->buffer == NULL) { ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); return NULL; } /* * As long as the allocation request stays within the limits given * by ossl_rand_pool_bytes_needed this rand_pool_grow below is guaranteed * to succeed, thus no allocation happens. * We have that only for cases when a pool is used to collect * additional data. Then the buffer might need to grow here, * and of course the caller is responsible to check the return * value of this function. */ if (!rand_pool_grow(pool, len)) return NULL; return pool->buffer + pool->len; } /* * Finish to add random bytes to the random pool in-place. * * Finishes an in-place update of the random pool started by * ossl_rand_pool_add_begin() (see previous comment). * It is expected that |len| bytes of random input have been added * to the buffer which contain at least |entropy| bits of randomness. * It is allowed to add less bytes than originally reserved. */ int ossl_rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy) { if (len > pool->alloc_len - pool->len) { ERR_raise(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW); return 0; } if (len > 0) { pool->len += len; pool->entropy += entropy; } return 1; }
./openssl/crypto/rand/rand_lib.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/err.h> #include <openssl/opensslconf.h> #include <openssl/core_names.h> #include "internal/cryptlib.h" #include "internal/thread_once.h" #include "crypto/rand.h" #include "crypto/cryptlib.h" #include "rand_local.h" #include "crypto/context.h" #ifndef FIPS_MODULE # include <stdio.h> # include <time.h> # include <limits.h> # include <openssl/conf.h> # include <openssl/trace.h> # include <openssl/engine.h> # include "crypto/rand_pool.h" # include "prov/seeding.h" # include "internal/e_os.h" # include "internal/property.h" # ifndef OPENSSL_NO_ENGINE /* non-NULL if default_RAND_meth is ENGINE-provided */ static ENGINE *funct_ref; static CRYPTO_RWLOCK *rand_engine_lock; # endif # ifndef OPENSSL_NO_DEPRECATED_3_0 static CRYPTO_RWLOCK *rand_meth_lock; static const RAND_METHOD *default_RAND_meth; # endif static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT; static int rand_inited = 0; DEFINE_RUN_ONCE_STATIC(do_rand_init) { # ifndef OPENSSL_NO_ENGINE rand_engine_lock = CRYPTO_THREAD_lock_new(); if (rand_engine_lock == NULL) return 0; # endif # ifndef OPENSSL_NO_DEPRECATED_3_0 rand_meth_lock = CRYPTO_THREAD_lock_new(); if (rand_meth_lock == NULL) goto err; # endif if (!ossl_rand_pool_init()) goto err; rand_inited = 1; return 1; err: # ifndef OPENSSL_NO_DEPRECATED_3_0 CRYPTO_THREAD_lock_free(rand_meth_lock); rand_meth_lock = NULL; # endif # ifndef OPENSSL_NO_ENGINE CRYPTO_THREAD_lock_free(rand_engine_lock); rand_engine_lock = NULL; # endif return 0; } void ossl_rand_cleanup_int(void) { # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *meth = default_RAND_meth; if (!rand_inited) return; if (meth != NULL && meth->cleanup != NULL) meth->cleanup(); RAND_set_rand_method(NULL); # endif ossl_rand_pool_cleanup(); # ifndef OPENSSL_NO_ENGINE CRYPTO_THREAD_lock_free(rand_engine_lock); rand_engine_lock = NULL; # endif # ifndef OPENSSL_NO_DEPRECATED_3_0 CRYPTO_THREAD_lock_free(rand_meth_lock); rand_meth_lock = NULL; # endif ossl_release_default_drbg_ctx(); rand_inited = 0; } /* * RAND_close_seed_files() ensures that any seed file descriptors are * closed after use. This only applies to libcrypto/default provider, * it does not apply to other providers. */ void RAND_keep_random_devices_open(int keep) { if (RUN_ONCE(&rand_init, do_rand_init)) ossl_rand_pool_keep_random_devices_open(keep); } /* * RAND_poll() reseeds the default RNG using random input * * The random input is obtained from polling various entropy * sources which depend on the operating system and are * configurable via the --with-rand-seed configure option. */ int RAND_poll(void) { static const char salt[] = "polling"; # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *meth = RAND_get_rand_method(); int ret = meth == RAND_OpenSSL(); if (meth == NULL) return 0; if (!ret) { /* fill random pool and seed the current legacy RNG */ RAND_POOL *pool = ossl_rand_pool_new(RAND_DRBG_STRENGTH, 1, (RAND_DRBG_STRENGTH + 7) / 8, RAND_POOL_MAX_LENGTH); if (pool == NULL) return 0; if (ossl_pool_acquire_entropy(pool) == 0) goto err; if (meth->add == NULL || meth->add(ossl_rand_pool_buffer(pool), ossl_rand_pool_length(pool), (ossl_rand_pool_entropy(pool) / 8.0)) == 0) goto err; ret = 1; err: ossl_rand_pool_free(pool); return ret; } # endif RAND_seed(salt, sizeof(salt)); return 1; } # ifndef OPENSSL_NO_DEPRECATED_3_0 static int rand_set_rand_method_internal(const RAND_METHOD *meth, ossl_unused ENGINE *e) { if (!RUN_ONCE(&rand_init, do_rand_init)) return 0; if (!CRYPTO_THREAD_write_lock(rand_meth_lock)) return 0; # ifndef OPENSSL_NO_ENGINE ENGINE_finish(funct_ref); funct_ref = e; # endif default_RAND_meth = meth; CRYPTO_THREAD_unlock(rand_meth_lock); return 1; } int RAND_set_rand_method(const RAND_METHOD *meth) { return rand_set_rand_method_internal(meth, NULL); } const RAND_METHOD *RAND_get_rand_method(void) { const RAND_METHOD *tmp_meth = NULL; if (!RUN_ONCE(&rand_init, do_rand_init)) return NULL; if (!CRYPTO_THREAD_read_lock(rand_meth_lock)) return NULL; tmp_meth = default_RAND_meth; CRYPTO_THREAD_unlock(rand_meth_lock); if (tmp_meth != NULL) return tmp_meth; if (!CRYPTO_THREAD_write_lock(rand_meth_lock)) return NULL; if (default_RAND_meth == NULL) { # ifndef OPENSSL_NO_ENGINE ENGINE *e; /* If we have an engine that can do RAND, use it. */ if ((e = ENGINE_get_default_RAND()) != NULL && (tmp_meth = ENGINE_get_RAND(e)) != NULL) { funct_ref = e; default_RAND_meth = tmp_meth; } else { ENGINE_finish(e); default_RAND_meth = &ossl_rand_meth; } # else default_RAND_meth = &ossl_rand_meth; # endif } tmp_meth = default_RAND_meth; CRYPTO_THREAD_unlock(rand_meth_lock); return tmp_meth; } # if !defined(OPENSSL_NO_ENGINE) int RAND_set_rand_engine(ENGINE *engine) { const RAND_METHOD *tmp_meth = NULL; if (!RUN_ONCE(&rand_init, do_rand_init)) return 0; if (engine != NULL) { if (!ENGINE_init(engine)) return 0; tmp_meth = ENGINE_get_RAND(engine); if (tmp_meth == NULL) { ENGINE_finish(engine); return 0; } } if (!CRYPTO_THREAD_write_lock(rand_engine_lock)) { ENGINE_finish(engine); return 0; } /* This function releases any prior ENGINE so call it first */ rand_set_rand_method_internal(tmp_meth, engine); CRYPTO_THREAD_unlock(rand_engine_lock); return 1; } # endif # endif /* OPENSSL_NO_DEPRECATED_3_0 */ void RAND_seed(const void *buf, int num) { EVP_RAND_CTX *drbg; # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth->seed != NULL) { meth->seed(buf, num); return; } # endif drbg = RAND_get0_primary(NULL); if (drbg != NULL && num > 0) EVP_RAND_reseed(drbg, 0, NULL, 0, buf, num); } void RAND_add(const void *buf, int num, double randomness) { EVP_RAND_CTX *drbg; # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth->add != NULL) { meth->add(buf, num, randomness); return; } # endif drbg = RAND_get0_primary(NULL); if (drbg != NULL && num > 0) # ifdef OPENSSL_RAND_SEED_NONE /* Without an entropy source, we have to rely on the user */ EVP_RAND_reseed(drbg, 0, buf, num, NULL, 0); # else /* With an entropy source, we downgrade this to additional input */ EVP_RAND_reseed(drbg, 0, NULL, 0, buf, num); # endif } # if !defined(OPENSSL_NO_DEPRECATED_1_1_0) int RAND_pseudo_bytes(unsigned char *buf, int num) { const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth->pseudorand != NULL) return meth->pseudorand(buf, num); ERR_raise(ERR_LIB_RAND, RAND_R_FUNC_NOT_IMPLEMENTED); return -1; } # endif int RAND_status(void) { EVP_RAND_CTX *rand; # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth != RAND_OpenSSL()) return meth->status != NULL ? meth->status() : 0; # endif if ((rand = RAND_get0_primary(NULL)) == NULL) return 0; return EVP_RAND_get_state(rand) == EVP_RAND_STATE_READY; } # else /* !FIPS_MODULE */ # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *RAND_get_rand_method(void) { return NULL; } # endif #endif /* !FIPS_MODULE */ /* * This function is not part of RAND_METHOD, so if we're not using * the default method, then just call RAND_bytes(). Otherwise make * sure we're instantiated and use the private DRBG. */ int RAND_priv_bytes_ex(OSSL_LIB_CTX *ctx, unsigned char *buf, size_t num, unsigned int strength) { EVP_RAND_CTX *rand; #if !defined(OPENSSL_NO_DEPRECATED_3_0) && !defined(FIPS_MODULE) const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth != RAND_OpenSSL()) { if (meth->bytes != NULL) return meth->bytes(buf, num); ERR_raise(ERR_LIB_RAND, RAND_R_FUNC_NOT_IMPLEMENTED); return -1; } #endif rand = RAND_get0_private(ctx); if (rand != NULL) return EVP_RAND_generate(rand, buf, num, strength, 0, NULL, 0); return 0; } int RAND_priv_bytes(unsigned char *buf, int num) { if (num < 0) return 0; return RAND_priv_bytes_ex(NULL, buf, (size_t)num, 0); } int RAND_bytes_ex(OSSL_LIB_CTX *ctx, unsigned char *buf, size_t num, unsigned int strength) { EVP_RAND_CTX *rand; #if !defined(OPENSSL_NO_DEPRECATED_3_0) && !defined(FIPS_MODULE) const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth != RAND_OpenSSL()) { if (meth->bytes != NULL) return meth->bytes(buf, num); ERR_raise(ERR_LIB_RAND, RAND_R_FUNC_NOT_IMPLEMENTED); return -1; } #endif rand = RAND_get0_public(ctx); if (rand != NULL) return EVP_RAND_generate(rand, buf, num, strength, 0, NULL, 0); return 0; } int RAND_bytes(unsigned char *buf, int num) { if (num < 0) return 0; return RAND_bytes_ex(NULL, buf, (size_t)num, 0); } typedef struct rand_global_st { /* * The three shared DRBG instances * * There are three shared DRBG instances: <primary>, <public>, and * <private>. The <public> and <private> DRBGs are secondary ones. * These are used for non-secret (e.g. nonces) and secret * (e.g. private keys) data respectively. */ CRYPTO_RWLOCK *lock; EVP_RAND_CTX *seed; /* * The <primary> DRBG * * Not used directly by the application, only for reseeding the two other * DRBGs. It reseeds itself by pulling either randomness from os entropy * sources or by consuming randomness which was added by RAND_add(). * * The <primary> DRBG is a global instance which is accessed concurrently by * all threads. The necessary locking is managed automatically by its child * DRBG instances during reseeding. */ EVP_RAND_CTX *primary; /* * The <public> DRBG * * Used by default for generating random bytes using RAND_bytes(). * * The <public> secondary DRBG is thread-local, i.e., there is one instance * per thread. */ CRYPTO_THREAD_LOCAL public; /* * The <private> DRBG * * Used by default for generating private keys using RAND_priv_bytes() * * The <private> secondary DRBG is thread-local, i.e., there is one * instance per thread. */ CRYPTO_THREAD_LOCAL private; /* Which RNG is being used by default and it's configuration settings */ char *rng_name; char *rng_cipher; char *rng_digest; char *rng_propq; /* Allow the randomness source to be changed */ char *seed_name; char *seed_propq; } RAND_GLOBAL; /* * Initialize the OSSL_LIB_CTX global DRBGs on first use. * Returns the allocated global data on success or NULL on failure. */ void *ossl_rand_ctx_new(OSSL_LIB_CTX *libctx) { RAND_GLOBAL *dgbl = OPENSSL_zalloc(sizeof(*dgbl)); if (dgbl == NULL) return NULL; #ifndef FIPS_MODULE /* * We need to ensure that base libcrypto thread handling has been * initialised. */ OPENSSL_init_crypto(OPENSSL_INIT_BASE_ONLY, NULL); #endif dgbl->lock = CRYPTO_THREAD_lock_new(); if (dgbl->lock == NULL) goto err1; if (!CRYPTO_THREAD_init_local(&dgbl->private, NULL)) goto err1; if (!CRYPTO_THREAD_init_local(&dgbl->public, NULL)) goto err2; return dgbl; err2: CRYPTO_THREAD_cleanup_local(&dgbl->private); err1: CRYPTO_THREAD_lock_free(dgbl->lock); OPENSSL_free(dgbl); return NULL; } void ossl_rand_ctx_free(void *vdgbl) { RAND_GLOBAL *dgbl = vdgbl; if (dgbl == NULL) return; CRYPTO_THREAD_lock_free(dgbl->lock); CRYPTO_THREAD_cleanup_local(&dgbl->private); CRYPTO_THREAD_cleanup_local(&dgbl->public); EVP_RAND_CTX_free(dgbl->primary); EVP_RAND_CTX_free(dgbl->seed); OPENSSL_free(dgbl->rng_name); OPENSSL_free(dgbl->rng_cipher); OPENSSL_free(dgbl->rng_digest); OPENSSL_free(dgbl->rng_propq); OPENSSL_free(dgbl->seed_name); OPENSSL_free(dgbl->seed_propq); OPENSSL_free(dgbl); } static RAND_GLOBAL *rand_get_global(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_INDEX); } static void rand_delete_thread_state(void *arg) { OSSL_LIB_CTX *ctx = arg; RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *rand; if (dgbl == NULL) return; rand = CRYPTO_THREAD_get_local(&dgbl->public); CRYPTO_THREAD_set_local(&dgbl->public, NULL); EVP_RAND_CTX_free(rand); rand = CRYPTO_THREAD_get_local(&dgbl->private); CRYPTO_THREAD_set_local(&dgbl->private, NULL); EVP_RAND_CTX_free(rand); } #ifndef FIPS_MODULE static EVP_RAND_CTX *rand_new_seed(OSSL_LIB_CTX *libctx) { EVP_RAND *rand; RAND_GLOBAL *dgbl = rand_get_global(libctx); EVP_RAND_CTX *ctx = NULL; const char *propq; char *name, *props = NULL; size_t props_len; OSSL_PROPERTY_LIST *pl1, *pl2, *pl3 = NULL; if (dgbl == NULL) return NULL; propq = dgbl->seed_propq; if (dgbl->seed_name != NULL) { name = dgbl->seed_name; } else { /* * Default to our internal seed source. This isn't part of the FIPS * provider so we need to override any FIPS properties. */ if (propq == NULL || *propq == '\0') { propq = "-fips"; } else { pl1 = ossl_parse_query(libctx, propq, 1); if (pl1 == NULL) { ERR_raise(ERR_LIB_RAND, RAND_R_INVALID_PROPERTY_QUERY); return NULL; } pl2 = ossl_parse_query(libctx, "-fips", 1); if (pl2 == NULL) { ossl_property_free(pl1); ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); return NULL; } pl3 = ossl_property_merge(pl2, pl1); ossl_property_free(pl1); ossl_property_free(pl2); if (pl3 == NULL) { ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); return NULL; } props_len = ossl_property_list_to_string(libctx, pl3, NULL, 0); if (props_len == 0) { /* Shouldn't happen since we added a query element */ ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); goto err; } else { props = OPENSSL_malloc(props_len); if (props == NULL) { ERR_raise(ERR_LIB_RAND, ERR_R_MALLOC_FAILURE); goto err; } if (ossl_property_list_to_string(libctx, pl3, props, props_len) == 0) { ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); goto err; } ossl_property_free(pl3); pl3 = NULL; propq = props; } } name = "SEED-SRC"; } rand = EVP_RAND_fetch(libctx, name, propq); if (rand == NULL) { ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_FETCH_DRBG); goto err; } ctx = EVP_RAND_CTX_new(rand, NULL); EVP_RAND_free(rand); if (ctx == NULL) { ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_CREATE_DRBG); goto err; } if (!EVP_RAND_instantiate(ctx, 0, 0, NULL, 0, NULL)) { ERR_raise(ERR_LIB_RAND, RAND_R_ERROR_INSTANTIATING_DRBG); goto err; } OPENSSL_free(props); return ctx; err: EVP_RAND_CTX_free(ctx); ossl_property_free(pl3); OPENSSL_free(props); return NULL; } EVP_RAND_CTX *ossl_rand_get0_seed_noncreating(OSSL_LIB_CTX *ctx) { RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *ret; if (dgbl == NULL) return NULL; if (!CRYPTO_THREAD_read_lock(dgbl->lock)) return NULL; ret = dgbl->seed; CRYPTO_THREAD_unlock(dgbl->lock); return ret; } #endif static EVP_RAND_CTX *rand_new_drbg(OSSL_LIB_CTX *libctx, EVP_RAND_CTX *parent, unsigned int reseed_interval, time_t reseed_time_interval, int use_df) { EVP_RAND *rand; RAND_GLOBAL *dgbl = rand_get_global(libctx); EVP_RAND_CTX *ctx; OSSL_PARAM params[8], *p = params; const OSSL_PARAM *settables; char *name, *cipher; if (dgbl == NULL) return NULL; name = dgbl->rng_name != NULL ? dgbl->rng_name : "CTR-DRBG"; rand = EVP_RAND_fetch(libctx, name, dgbl->rng_propq); if (rand == NULL) { ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_FETCH_DRBG); return NULL; } ctx = EVP_RAND_CTX_new(rand, parent); EVP_RAND_free(rand); if (ctx == NULL) { ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_CREATE_DRBG); return NULL; } settables = EVP_RAND_CTX_settable_params(ctx); if (OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_CIPHER)) { cipher = dgbl->rng_cipher != NULL ? dgbl->rng_cipher : "AES-256-CTR"; *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_CIPHER, cipher, 0); } if (dgbl->rng_digest != NULL && OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_DIGEST)) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_DIGEST, dgbl->rng_digest, 0); if (dgbl->rng_propq != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_PROPERTIES, dgbl->rng_propq, 0); if (OSSL_PARAM_locate_const(settables, OSSL_ALG_PARAM_MAC)) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_MAC, "HMAC", 0); if (OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_USE_DF)) *p++ = OSSL_PARAM_construct_int(OSSL_DRBG_PARAM_USE_DF, &use_df); *p++ = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_REQUESTS, &reseed_interval); *p++ = OSSL_PARAM_construct_time_t(OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL, &reseed_time_interval); *p = OSSL_PARAM_construct_end(); if (!EVP_RAND_instantiate(ctx, 0, 0, NULL, 0, params)) { ERR_raise(ERR_LIB_RAND, RAND_R_ERROR_INSTANTIATING_DRBG); EVP_RAND_CTX_free(ctx); return NULL; } return ctx; } /* * Get the primary random generator. * Returns pointer to its EVP_RAND_CTX on success, NULL on failure. * */ EVP_RAND_CTX *RAND_get0_primary(OSSL_LIB_CTX *ctx) { RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *ret; if (dgbl == NULL) return NULL; if (!CRYPTO_THREAD_read_lock(dgbl->lock)) return NULL; ret = dgbl->primary; CRYPTO_THREAD_unlock(dgbl->lock); if (ret != NULL) return ret; if (!CRYPTO_THREAD_write_lock(dgbl->lock)) return NULL; ret = dgbl->primary; if (ret != NULL) { CRYPTO_THREAD_unlock(dgbl->lock); return ret; } #ifndef FIPS_MODULE if (dgbl->seed == NULL) { ERR_set_mark(); dgbl->seed = rand_new_seed(ctx); ERR_pop_to_mark(); } #endif ret = dgbl->primary = rand_new_drbg(ctx, dgbl->seed, PRIMARY_RESEED_INTERVAL, PRIMARY_RESEED_TIME_INTERVAL, 1); /* * The primary DRBG may be shared between multiple threads so we must * enable locking. */ if (ret != NULL && !EVP_RAND_enable_locking(ret)) { ERR_raise(ERR_LIB_EVP, EVP_R_UNABLE_TO_ENABLE_LOCKING); EVP_RAND_CTX_free(ret); ret = dgbl->primary = NULL; } CRYPTO_THREAD_unlock(dgbl->lock); return ret; } /* * Get the public random generator. * Returns pointer to its EVP_RAND_CTX on success, NULL on failure. */ EVP_RAND_CTX *RAND_get0_public(OSSL_LIB_CTX *ctx) { RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *rand, *primary; if (dgbl == NULL) return NULL; rand = CRYPTO_THREAD_get_local(&dgbl->public); if (rand == NULL) { primary = RAND_get0_primary(ctx); if (primary == NULL) return NULL; ctx = ossl_lib_ctx_get_concrete(ctx); /* * If the private is also NULL then this is the first time we've * used this thread. */ if (CRYPTO_THREAD_get_local(&dgbl->private) == NULL && !ossl_init_thread_start(NULL, ctx, rand_delete_thread_state)) return NULL; rand = rand_new_drbg(ctx, primary, SECONDARY_RESEED_INTERVAL, SECONDARY_RESEED_TIME_INTERVAL, 0); CRYPTO_THREAD_set_local(&dgbl->public, rand); } return rand; } /* * Get the private random generator. * Returns pointer to its EVP_RAND_CTX on success, NULL on failure. */ EVP_RAND_CTX *RAND_get0_private(OSSL_LIB_CTX *ctx) { RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *rand, *primary; if (dgbl == NULL) return NULL; rand = CRYPTO_THREAD_get_local(&dgbl->private); if (rand == NULL) { primary = RAND_get0_primary(ctx); if (primary == NULL) return NULL; ctx = ossl_lib_ctx_get_concrete(ctx); /* * If the public is also NULL then this is the first time we've * used this thread. */ if (CRYPTO_THREAD_get_local(&dgbl->public) == NULL && !ossl_init_thread_start(NULL, ctx, rand_delete_thread_state)) return NULL; rand = rand_new_drbg(ctx, primary, SECONDARY_RESEED_INTERVAL, SECONDARY_RESEED_TIME_INTERVAL, 0); CRYPTO_THREAD_set_local(&dgbl->private, rand); } return rand; } #ifdef FIPS_MODULE EVP_RAND_CTX *ossl_rand_get0_private_noncreating(OSSL_LIB_CTX *ctx) { RAND_GLOBAL *dgbl = rand_get_global(ctx); if (dgbl == NULL) return NULL; return CRYPTO_THREAD_get_local(&dgbl->private); } #endif int RAND_set0_public(OSSL_LIB_CTX *ctx, EVP_RAND_CTX *rand) { RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *old; int r; if (dgbl == NULL) return 0; old = CRYPTO_THREAD_get_local(&dgbl->public); if ((r = CRYPTO_THREAD_set_local(&dgbl->public, rand)) > 0) EVP_RAND_CTX_free(old); return r; } int RAND_set0_private(OSSL_LIB_CTX *ctx, EVP_RAND_CTX *rand) { RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *old; int r; if (dgbl == NULL) return 0; old = CRYPTO_THREAD_get_local(&dgbl->private); if ((r = CRYPTO_THREAD_set_local(&dgbl->private, rand)) > 0) EVP_RAND_CTX_free(old); return r; } #ifndef FIPS_MODULE static int random_set_string(char **p, const char *s) { char *d = NULL; if (s != NULL) { d = OPENSSL_strdup(s); if (d == NULL) return 0; } OPENSSL_free(*p); *p = d; return 1; } /* * Load the DRBG definitions from a configuration file. */ static int random_conf_init(CONF_IMODULE *md, const CONF *cnf) { STACK_OF(CONF_VALUE) *elist; CONF_VALUE *cval; RAND_GLOBAL *dgbl = rand_get_global(NCONF_get0_libctx((CONF *)cnf)); int i, r = 1; OSSL_TRACE1(CONF, "Loading random module: section %s\n", CONF_imodule_get_value(md)); /* Value is a section containing RANDOM configuration */ elist = NCONF_get_section(cnf, CONF_imodule_get_value(md)); if (elist == NULL) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_RANDOM_SECTION_ERROR); return 0; } if (dgbl == NULL) return 0; for (i = 0; i < sk_CONF_VALUE_num(elist); i++) { cval = sk_CONF_VALUE_value(elist, i); if (OPENSSL_strcasecmp(cval->name, "random") == 0) { if (!random_set_string(&dgbl->rng_name, cval->value)) return 0; } else if (OPENSSL_strcasecmp(cval->name, "cipher") == 0) { if (!random_set_string(&dgbl->rng_cipher, cval->value)) return 0; } else if (OPENSSL_strcasecmp(cval->name, "digest") == 0) { if (!random_set_string(&dgbl->rng_digest, cval->value)) return 0; } else if (OPENSSL_strcasecmp(cval->name, "properties") == 0) { if (!random_set_string(&dgbl->rng_propq, cval->value)) return 0; } else if (OPENSSL_strcasecmp(cval->name, "seed") == 0) { if (!random_set_string(&dgbl->seed_name, cval->value)) return 0; } else if (OPENSSL_strcasecmp(cval->name, "seed_properties") == 0) { if (!random_set_string(&dgbl->seed_propq, cval->value)) return 0; } else { ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_UNKNOWN_NAME_IN_RANDOM_SECTION, "name=%s, value=%s", cval->name, cval->value); r = 0; } } return r; } static void random_conf_deinit(CONF_IMODULE *md) { OSSL_TRACE(CONF, "Cleaned up random\n"); } void ossl_random_add_conf_module(void) { OSSL_TRACE(CONF, "Adding config module 'random'\n"); CONF_module_add("random", random_conf_init, random_conf_deinit); } int RAND_set_DRBG_type(OSSL_LIB_CTX *ctx, const char *drbg, const char *propq, const char *cipher, const char *digest) { RAND_GLOBAL *dgbl = rand_get_global(ctx); if (dgbl == NULL) return 0; if (dgbl->primary != NULL) { ERR_raise(ERR_LIB_CRYPTO, RAND_R_ALREADY_INSTANTIATED); return 0; } return random_set_string(&dgbl->rng_name, drbg) && random_set_string(&dgbl->rng_propq, propq) && random_set_string(&dgbl->rng_cipher, cipher) && random_set_string(&dgbl->rng_digest, digest); } int RAND_set_seed_source_type(OSSL_LIB_CTX *ctx, const char *seed, const char *propq) { RAND_GLOBAL *dgbl = rand_get_global(ctx); if (dgbl == NULL) return 0; if (dgbl->seed != NULL) { ERR_raise(ERR_LIB_CRYPTO, RAND_R_ALREADY_INSTANTIATED); return 0; } return random_set_string(&dgbl->seed_name, seed) && random_set_string(&dgbl->seed_propq, propq); } #endif
./openssl/crypto/rand/rand_local.h
/* * 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 */ #ifndef OSSL_CRYPTO_RAND_LOCAL_H # define OSSL_CRYPTO_RAND_LOCAL_H # include <openssl/aes.h> # include <openssl/evp.h> # include <openssl/sha.h> # include <openssl/hmac.h> # include <openssl/ec.h> # include <openssl/rand.h> # include "internal/tsan_assist.h" # include "crypto/rand.h" /* Default reseed intervals */ # define PRIMARY_RESEED_INTERVAL (1 << 8) # define SECONDARY_RESEED_INTERVAL (1 << 16) # define PRIMARY_RESEED_TIME_INTERVAL (60 * 60) /* 1 hour */ # define SECONDARY_RESEED_TIME_INTERVAL (7 * 60) /* 7 minutes */ # ifndef FIPS_MODULE /* The global RAND method, and the global buffer and DRBG instance. */ extern RAND_METHOD ossl_rand_meth; # endif #endif
./openssl/crypto/rand/rand_meth.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 */ #include <openssl/evp.h> #include <openssl/rand.h> #include "rand_local.h" /* Implements the default OpenSSL RAND_add() method */ static int drbg_add(const void *buf, int num, double randomness) { EVP_RAND_CTX *drbg = RAND_get0_primary(NULL); if (drbg == NULL || num <= 0) return 0; return EVP_RAND_reseed(drbg, 0, NULL, 0, buf, num); } /* Implements the default OpenSSL RAND_seed() method */ static int drbg_seed(const void *buf, int num) { return drbg_add(buf, num, num); } /* Implements the default OpenSSL RAND_status() method */ static int drbg_status(void) { EVP_RAND_CTX *drbg = RAND_get0_primary(NULL); if (drbg == NULL) return 0; return EVP_RAND_get_state(drbg) == EVP_RAND_STATE_READY ? 1 : 0; } /* Implements the default OpenSSL RAND_bytes() method */ static int drbg_bytes(unsigned char *out, int count) { EVP_RAND_CTX *drbg = RAND_get0_public(NULL); if (drbg == NULL) return 0; return EVP_RAND_generate(drbg, out, count, 0, 0, NULL, 0); } RAND_METHOD ossl_rand_meth = { drbg_seed, drbg_bytes, NULL, drbg_add, drbg_bytes, drbg_status }; RAND_METHOD *RAND_OpenSSL(void) { return &ossl_rand_meth; }
./openssl/crypto/rand/rand_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/randerr.h> #include "crypto/randerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA RAND_str_reasons[] = { {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ADDITIONAL_INPUT_TOO_LONG), "additional input too long"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ALREADY_INSTANTIATED), "already instantiated"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ARGUMENT_OUT_OF_RANGE), "argument out of range"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_CANNOT_OPEN_FILE), "Cannot open file"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_DRBG_ALREADY_INITIALIZED), "drbg already initialized"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_DRBG_NOT_INITIALISED), "drbg not initialised"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ENTROPY_INPUT_TOO_LONG), "entropy input too long"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ENTROPY_OUT_OF_RANGE), "entropy out of range"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED), "error entropy pool was ignored"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_INITIALISING_DRBG), "error initialising drbg"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_INSTANTIATING_DRBG), "error instantiating drbg"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_ADDITIONAL_INPUT), "error retrieving additional input"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_ENTROPY), "error retrieving entropy"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_NONCE), "error retrieving nonce"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FAILED_TO_CREATE_LOCK), "failed to create lock"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FUNC_NOT_IMPLEMENTED), "Function not implemented"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FWRITE_ERROR), "Error writing file"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_GENERATE_ERROR), "generate error"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_INSUFFICIENT_DRBG_STRENGTH), "insufficient drbg strength"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_INTERNAL_ERROR), "internal error"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_INVALID_PROPERTY_QUERY), "invalid property query"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_IN_ERROR_STATE), "in error state"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NOT_A_REGULAR_FILE), "Not a regular file"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NOT_INSTANTIATED), "not instantiated"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED), "no drbg implementation selected"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PARENT_LOCKING_NOT_ENABLED), "parent locking not enabled"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PARENT_STRENGTH_TOO_WEAK), "parent strength too weak"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PERSONALISATION_STRING_TOO_LONG), "personalisation string too long"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PREDICTION_RESISTANCE_NOT_SUPPORTED), "prediction resistance not supported"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PRNG_NOT_SEEDED), "PRNG not seeded"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_RANDOM_POOL_OVERFLOW), "random pool overflow"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_RANDOM_POOL_UNDERFLOW), "random pool underflow"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG), "request too large for drbg"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_RESEED_ERROR), "reseed error"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_SELFTEST_FAILURE), "selftest failure"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_TOO_LITTLE_NONCE_REQUESTED), "too little nonce requested"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_TOO_MUCH_NONCE_REQUESTED), "too much nonce requested"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNABLE_TO_CREATE_DRBG), "unable to create drbg"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNABLE_TO_FETCH_DRBG), "unable to fetch drbg"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNABLE_TO_GET_PARENT_RESEED_PROP_COUNTER), "unable to get parent reseed prop counter"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNABLE_TO_GET_PARENT_STRENGTH), "unable to get parent strength"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNABLE_TO_LOCK_PARENT), "unable to lock parent"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNSUPPORTED_DRBG_FLAGS), "unsupported drbg flags"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNSUPPORTED_DRBG_TYPE), "unsupported drbg type"}, {0, NULL} }; #endif int ossl_err_load_RAND_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(RAND_str_reasons[0].error) == NULL) ERR_load_strings_const(RAND_str_reasons); #endif return 1; }
./openssl/crypto/rand/rand_egd.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 <openssl/opensslconf.h> #include <openssl/crypto.h> #include <openssl/e_os2.h> #include <openssl/rand.h> /* * Query an EGD */ #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_VOS) || defined(OPENSSL_SYS_UEFI) int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes) { return -1; } int RAND_egd(const char *path) { return -1; } int RAND_egd_bytes(const char *path, int bytes) { return -1; } #else # include <unistd.h> # include <stddef.h> # include <sys/types.h> # include <sys/socket.h> # ifndef NO_SYS_UN_H # include <sys/un.h> # else struct sockaddr_un { short sun_family; /* AF_UNIX */ char sun_path[108]; /* path name (gag) */ }; # endif /* NO_SYS_UN_H */ # include <string.h> # include <errno.h> # if defined(OPENSSL_SYS_TANDEM) /* * HPNS: * * This code forces the use of compatibility mode if required on HPE NonStop * when coreutils PRNGD is used and then restores the previous mode * after establishing the socket. This is not required on x86 where hardware * randomization should be used instead of EGD available as of OpenSSL 3.0. * Use --with-rand-seed=rdcpu when configuring x86 with 3.0 and above. * * Needs review: * * The better long-term solution is to either run two EGD's each in one of * the two modes or revise the EGD code to listen on two different sockets * (each in one of the two modes) or use the hardware randomizer. */ _variable int hpns_socket(int family, int type, int protocol, char* transport) { int socket_rc; char current_transport[20]; # define AF_UNIX_PORTABILITY "$ZAFN2" # define AF_UNIX_COMPATIBILITY "$ZPLS" if (!_arg_present(transport) || transport == NULL || transport[0] == '\0') return socket(family, type, protocol); socket_transport_name_get(AF_UNIX, current_transport, 20); if (strcmp(current_transport, transport) == 0) return socket(family, type, protocol); /* set the requested socket transport */ if (socket_transport_name_set(AF_UNIX, transport)) return -1; socket_rc = socket(family, type, protocol); /* set mode back to what it was */ if (socket_transport_name_set(AF_UNIX, current_transport)) return -1; return socket_rc; } /*#define socket(a,b,c,...) hpns_socket(a,b,c,__VA_ARGS__) */ static int hpns_connect_attempt = 0; # endif /* defined(OPENSSL_SYS_HPNS) */ int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes) { FILE *fp = NULL; struct sockaddr_un addr; int mybuffer, ret = -1, i, numbytes, fd; unsigned char tempbuf[255]; if (bytes > (int)sizeof(tempbuf)) return -1; /* Make socket. */ memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; if (strlen(path) >= sizeof(addr.sun_path)) return -1; strcpy(addr.sun_path, path); i = offsetof(struct sockaddr_un, sun_path) + strlen(path); #if defined(OPENSSL_SYS_TANDEM) fd = hpns_socket(AF_UNIX, SOCK_STREAM, 0, AF_UNIX_COMPATIBILITY); #else fd = socket(AF_UNIX, SOCK_STREAM, 0); #endif if (fd == -1 || (fp = fdopen(fd, "r+")) == NULL) return -1; setbuf(fp, NULL); /* Try to connect */ for (;;) { if (connect(fd, (struct sockaddr *)&addr, i) == 0) break; # ifdef EISCONN if (errno == EISCONN) break; # endif switch (errno) { # ifdef EINTR case EINTR: # endif # ifdef EAGAIN case EAGAIN: # endif # ifdef EINPROGRESS case EINPROGRESS: # endif # ifdef EALREADY case EALREADY: # endif /* No error, try again */ break; default: # if defined(OPENSSL_SYS_TANDEM) if (hpns_connect_attempt == 0) { /* try the other kind of AF_UNIX socket */ close(fd); fd = hpns_socket(AF_UNIX, SOCK_STREAM, 0, AF_UNIX_PORTABILITY); if (fd == -1) return -1; ++hpns_connect_attempt; break; /* try the connect again */ } # endif ret = -1; goto err; } } /* Make request, see how many bytes we can get back. */ tempbuf[0] = 1; tempbuf[1] = bytes; if (fwrite(tempbuf, sizeof(char), 2, fp) != 2 || fflush(fp) == EOF) goto err; if (fread(tempbuf, sizeof(char), 1, fp) != 1 || tempbuf[0] == 0) goto err; numbytes = tempbuf[0]; /* Which buffer are we using? */ mybuffer = buf == NULL; if (mybuffer) buf = tempbuf; /* Read bytes. */ i = fread(buf, sizeof(char), numbytes, fp); if (i < numbytes) goto err; ret = numbytes; if (mybuffer) RAND_add(tempbuf, i, i); err: if (fp != NULL) fclose(fp); return ret; } int RAND_egd_bytes(const char *path, int bytes) { int num; num = RAND_query_egd_bytes(path, NULL, bytes); if (num < 0) return -1; if (RAND_status() != 1) return -1; return num; } int RAND_egd(const char *path) { return RAND_egd_bytes(path, 255); } #endif
./openssl/crypto/camellia/cmll_cbc.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 */ /* * Camellia low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/camellia.h> #include <openssl/modes.h> void Camellia_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len, const CAMELLIA_KEY *key, unsigned char *ivec, const int enc) { if (enc) CRYPTO_cbc128_encrypt(in, out, len, key, ivec, (block128_f) Camellia_encrypt); else CRYPTO_cbc128_decrypt(in, out, len, key, ivec, (block128_f) Camellia_decrypt); }
./openssl/crypto/camellia/cmll_misc.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 */ /* * Camellia low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/opensslv.h> #include <openssl/camellia.h> #include "cmll_local.h" int Camellia_set_key(const unsigned char *userKey, const int bits, CAMELLIA_KEY *key) { if (!userKey || !key) return -1; if (bits != 128 && bits != 192 && bits != 256) return -2; key->grand_rounds = Camellia_Ekeygen(bits, userKey, key->u.rd_key); return 0; } void Camellia_encrypt(const unsigned char *in, unsigned char *out, const CAMELLIA_KEY *key) { Camellia_EncryptBlock_Rounds(key->grand_rounds, in, key->u.rd_key, out); } void Camellia_decrypt(const unsigned char *in, unsigned char *out, const CAMELLIA_KEY *key) { Camellia_DecryptBlock_Rounds(key->grand_rounds, in, key->u.rd_key, out); }