file_path
stringlengths
19
75
code
stringlengths
279
1.37M
./openssl/crypto/rsa/rsa_pss.c
/* * Copyright 2005-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <openssl/sha.h> #include "rsa_local.h" static const unsigned char zeroes[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; #if defined(_MSC_VER) && defined(_ARM_) # pragma optimize("g", off) #endif int RSA_verify_PKCS1_PSS(RSA *rsa, const unsigned char *mHash, const EVP_MD *Hash, const unsigned char *EM, int sLen) { return RSA_verify_PKCS1_PSS_mgf1(rsa, mHash, Hash, NULL, EM, sLen); } int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash, const EVP_MD *Hash, const EVP_MD *mgf1Hash, const unsigned char *EM, int sLen) { int i; int ret = 0; int hLen, maskedDBLen, MSBits, emLen; const unsigned char *H; unsigned char *DB = NULL; EVP_MD_CTX *ctx = EVP_MD_CTX_new(); unsigned char H_[EVP_MAX_MD_SIZE]; if (ctx == NULL) goto err; if (mgf1Hash == NULL) mgf1Hash = Hash; hLen = EVP_MD_get_size(Hash); if (hLen < 0) goto err; /*- * Negative sLen has special meanings: * -1 sLen == hLen * -2 salt length is autorecovered from signature * -3 salt length is maximized * -4 salt length is autorecovered from signature * -N reserved */ if (sLen == RSA_PSS_SALTLEN_DIGEST) { sLen = hLen; } else if (sLen < RSA_PSS_SALTLEN_AUTO_DIGEST_MAX) { ERR_raise(ERR_LIB_RSA, RSA_R_SLEN_CHECK_FAILED); goto err; } MSBits = (BN_num_bits(rsa->n) - 1) & 0x7; emLen = RSA_size(rsa); if (EM[0] & (0xFF << MSBits)) { ERR_raise(ERR_LIB_RSA, RSA_R_FIRST_OCTET_INVALID); goto err; } if (MSBits == 0) { EM++; emLen--; } if (emLen < hLen + 2) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE); goto err; } if (sLen == RSA_PSS_SALTLEN_MAX) { sLen = emLen - hLen - 2; } else if (sLen > emLen - hLen - 2) { /* sLen can be small negative */ ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE); goto err; } if (EM[emLen - 1] != 0xbc) { ERR_raise(ERR_LIB_RSA, RSA_R_LAST_OCTET_INVALID); goto err; } maskedDBLen = emLen - hLen - 1; H = EM + maskedDBLen; DB = OPENSSL_malloc(maskedDBLen); if (DB == NULL) goto err; if (PKCS1_MGF1(DB, maskedDBLen, H, hLen, mgf1Hash) < 0) goto err; for (i = 0; i < maskedDBLen; i++) DB[i] ^= EM[i]; if (MSBits) DB[0] &= 0xFF >> (8 - MSBits); for (i = 0; DB[i] == 0 && i < (maskedDBLen - 1); i++) ; if (DB[i++] != 0x1) { ERR_raise(ERR_LIB_RSA, RSA_R_SLEN_RECOVERY_FAILED); goto err; } if (sLen != RSA_PSS_SALTLEN_AUTO && sLen != RSA_PSS_SALTLEN_AUTO_DIGEST_MAX && (maskedDBLen - i) != sLen) { ERR_raise_data(ERR_LIB_RSA, RSA_R_SLEN_CHECK_FAILED, "expected: %d retrieved: %d", sLen, maskedDBLen - i); goto err; } if (!EVP_DigestInit_ex(ctx, Hash, NULL) || !EVP_DigestUpdate(ctx, zeroes, sizeof(zeroes)) || !EVP_DigestUpdate(ctx, mHash, hLen)) goto err; if (maskedDBLen - i) { if (!EVP_DigestUpdate(ctx, DB + i, maskedDBLen - i)) goto err; } if (!EVP_DigestFinal_ex(ctx, H_, NULL)) goto err; if (memcmp(H_, H, hLen)) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); ret = 0; } else { ret = 1; } err: OPENSSL_free(DB); EVP_MD_CTX_free(ctx); return ret; } int RSA_padding_add_PKCS1_PSS(RSA *rsa, unsigned char *EM, const unsigned char *mHash, const EVP_MD *Hash, int sLen) { return RSA_padding_add_PKCS1_PSS_mgf1(rsa, EM, mHash, Hash, NULL, sLen); } int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM, const unsigned char *mHash, const EVP_MD *Hash, const EVP_MD *mgf1Hash, int sLen) { int i; int ret = 0; int hLen, maskedDBLen, MSBits, emLen; unsigned char *H, *salt = NULL, *p; EVP_MD_CTX *ctx = NULL; int sLenMax = -1; if (mgf1Hash == NULL) mgf1Hash = Hash; hLen = EVP_MD_get_size(Hash); if (hLen < 0) goto err; /*- * Negative sLen has special meanings: * -1 sLen == hLen * -2 salt length is maximized * -3 same as above (on signing) * -4 salt length is min(hLen, maximum salt length) * -N reserved */ /* FIPS 186-4 section 5 "The RSA Digital Signature Algorithm", subsection * 5.5 "PKCS #1" says: "For RSASSA-PSS […] the length (in bytes) of the * salt (sLen) shall satisfy 0 <= sLen <= hLen, where hLen is the length of * the hash function output block (in bytes)." * * Provide a way to use at most the digest length, so that the default does * not violate FIPS 186-4. */ if (sLen == RSA_PSS_SALTLEN_DIGEST) { sLen = hLen; } else if (sLen == RSA_PSS_SALTLEN_MAX_SIGN || sLen == RSA_PSS_SALTLEN_AUTO) { sLen = RSA_PSS_SALTLEN_MAX; } else if (sLen == RSA_PSS_SALTLEN_AUTO_DIGEST_MAX) { sLen = RSA_PSS_SALTLEN_MAX; sLenMax = hLen; } else if (sLen < RSA_PSS_SALTLEN_AUTO_DIGEST_MAX) { ERR_raise(ERR_LIB_RSA, RSA_R_SLEN_CHECK_FAILED); goto err; } MSBits = (BN_num_bits(rsa->n) - 1) & 0x7; emLen = RSA_size(rsa); if (MSBits == 0) { *EM++ = 0; emLen--; } if (emLen < hLen + 2) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); goto err; } if (sLen == RSA_PSS_SALTLEN_MAX) { sLen = emLen - hLen - 2; if (sLenMax >= 0 && sLen > sLenMax) sLen = sLenMax; } else if (sLen > emLen - hLen - 2) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); goto err; } if (sLen > 0) { salt = OPENSSL_malloc(sLen); if (salt == NULL) goto err; if (RAND_bytes_ex(rsa->libctx, salt, sLen, 0) <= 0) goto err; } maskedDBLen = emLen - hLen - 1; H = EM + maskedDBLen; ctx = EVP_MD_CTX_new(); if (ctx == NULL) goto err; if (!EVP_DigestInit_ex(ctx, Hash, NULL) || !EVP_DigestUpdate(ctx, zeroes, sizeof(zeroes)) || !EVP_DigestUpdate(ctx, mHash, hLen)) goto err; if (sLen && !EVP_DigestUpdate(ctx, salt, sLen)) goto err; if (!EVP_DigestFinal_ex(ctx, H, NULL)) goto err; /* Generate dbMask in place then perform XOR on it */ if (PKCS1_MGF1(EM, maskedDBLen, H, hLen, mgf1Hash)) goto err; p = EM; /* * Initial PS XORs with all zeroes which is a NOP so just update pointer. * Note from a test above this value is guaranteed to be non-negative. */ p += emLen - sLen - hLen - 2; *p++ ^= 0x1; if (sLen > 0) { for (i = 0; i < sLen; i++) *p++ ^= salt[i]; } if (MSBits) EM[0] &= 0xFF >> (8 - MSBits); /* H is already in place so just set final 0xbc */ EM[emLen - 1] = 0xbc; ret = 1; err: EVP_MD_CTX_free(ctx); OPENSSL_clear_free(salt, (size_t)sLen); /* salt != NULL implies sLen > 0 */ return ret; } /* * The defaults for PSS restrictions are defined in RFC 8017, A.2.3 RSASSA-PSS * (https://tools.ietf.org/html/rfc8017#appendix-A.2.3): * * If the default values of the hashAlgorithm, maskGenAlgorithm, and * trailerField fields of RSASSA-PSS-params are used, then the algorithm * identifier will have the following value: * * rSASSA-PSS-Default-Identifier RSASSA-AlgorithmIdentifier ::= { * algorithm id-RSASSA-PSS, * parameters RSASSA-PSS-params : { * hashAlgorithm sha1, * maskGenAlgorithm mgf1SHA1, * saltLength 20, * trailerField trailerFieldBC * } * } * * RSASSA-AlgorithmIdentifier ::= AlgorithmIdentifier { * {PKCS1Algorithms} * } */ static const RSA_PSS_PARAMS_30 default_RSASSA_PSS_params = { NID_sha1, /* default hashAlgorithm */ { NID_mgf1, /* default maskGenAlgorithm */ NID_sha1 /* default MGF1 hash */ }, 20, /* default saltLength */ 1 /* default trailerField (0xBC) */ }; int ossl_rsa_pss_params_30_set_defaults(RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return 0; *rsa_pss_params = default_RSASSA_PSS_params; return 1; } int ossl_rsa_pss_params_30_is_unrestricted(const RSA_PSS_PARAMS_30 *rsa_pss_params) { static RSA_PSS_PARAMS_30 pss_params_cmp = { 0, }; return rsa_pss_params == NULL || memcmp(rsa_pss_params, &pss_params_cmp, sizeof(*rsa_pss_params)) == 0; } int ossl_rsa_pss_params_30_copy(RSA_PSS_PARAMS_30 *to, const RSA_PSS_PARAMS_30 *from) { memcpy(to, from, sizeof(*to)); return 1; } int ossl_rsa_pss_params_30_set_hashalg(RSA_PSS_PARAMS_30 *rsa_pss_params, int hashalg_nid) { if (rsa_pss_params == NULL) return 0; rsa_pss_params->hash_algorithm_nid = hashalg_nid; return 1; } int ossl_rsa_pss_params_30_set_maskgenhashalg(RSA_PSS_PARAMS_30 *rsa_pss_params, int maskgenhashalg_nid) { if (rsa_pss_params == NULL) return 0; rsa_pss_params->mask_gen.hash_algorithm_nid = maskgenhashalg_nid; return 1; } int ossl_rsa_pss_params_30_set_saltlen(RSA_PSS_PARAMS_30 *rsa_pss_params, int saltlen) { if (rsa_pss_params == NULL) return 0; rsa_pss_params->salt_len = saltlen; return 1; } int ossl_rsa_pss_params_30_set_trailerfield(RSA_PSS_PARAMS_30 *rsa_pss_params, int trailerfield) { if (rsa_pss_params == NULL) return 0; rsa_pss_params->trailer_field = trailerfield; return 1; } int ossl_rsa_pss_params_30_hashalg(const RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return default_RSASSA_PSS_params.hash_algorithm_nid; return rsa_pss_params->hash_algorithm_nid; } int ossl_rsa_pss_params_30_maskgenalg(const RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return default_RSASSA_PSS_params.mask_gen.algorithm_nid; return rsa_pss_params->mask_gen.algorithm_nid; } int ossl_rsa_pss_params_30_maskgenhashalg(const RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return default_RSASSA_PSS_params.hash_algorithm_nid; return rsa_pss_params->mask_gen.hash_algorithm_nid; } int ossl_rsa_pss_params_30_saltlen(const RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return default_RSASSA_PSS_params.salt_len; return rsa_pss_params->salt_len; } int ossl_rsa_pss_params_30_trailerfield(const RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return default_RSASSA_PSS_params.trailer_field; return rsa_pss_params->trailer_field; } #if defined(_MSC_VER) # pragma optimize("",on) #endif
./openssl/crypto/rsa/rsa_local.h
/* * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_CRYPTO_RSA_LOCAL_H #define OSSL_CRYPTO_RSA_LOCAL_H #include "internal/refcount.h" #include "crypto/rsa.h" #define RSA_MAX_PRIME_NUM 5 typedef struct rsa_prime_info_st { BIGNUM *r; BIGNUM *d; BIGNUM *t; /* save product of primes prior to this one */ BIGNUM *pp; BN_MONT_CTX *m; } RSA_PRIME_INFO; DECLARE_ASN1_ITEM(RSA_PRIME_INFO) DEFINE_STACK_OF(RSA_PRIME_INFO) #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) struct rsa_acvp_test_st { /* optional inputs */ BIGNUM *Xp1; BIGNUM *Xp2; BIGNUM *Xq1; BIGNUM *Xq2; BIGNUM *Xp; BIGNUM *Xq; /* optional outputs */ BIGNUM *p1; BIGNUM *p2; BIGNUM *q1; BIGNUM *q2; }; #endif struct rsa_st { /* * #legacy * The first field is used to pickup errors where this is passed * instead of an EVP_PKEY. It is always zero. * THIS MUST REMAIN THE FIRST FIELD. */ int dummy_zero; OSSL_LIB_CTX *libctx; int32_t version; const RSA_METHOD *meth; /* functional reference if 'meth' is ENGINE-provided */ ENGINE *engine; BIGNUM *n; BIGNUM *e; BIGNUM *d; BIGNUM *p; BIGNUM *q; BIGNUM *dmp1; BIGNUM *dmq1; BIGNUM *iqmp; /* * If a PSS only key this contains the parameter restrictions. * There are two structures for the same thing, used in different cases. */ /* This is used uniquely by OpenSSL provider implementations. */ RSA_PSS_PARAMS_30 pss_params; #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) RSA_ACVP_TEST *acvp_test; #endif #ifndef FIPS_MODULE /* This is used uniquely by rsa_ameth.c and rsa_pmeth.c. */ RSA_PSS_PARAMS *pss; /* for multi-prime RSA, defined in RFC 8017 */ STACK_OF(RSA_PRIME_INFO) *prime_infos; /* Be careful using this if the RSA structure is shared */ CRYPTO_EX_DATA ex_data; #endif CRYPTO_REF_COUNT references; int flags; /* Used to cache montgomery values */ BN_MONT_CTX *_method_mod_n; BN_MONT_CTX *_method_mod_p; BN_MONT_CTX *_method_mod_q; BN_BLINDING *blinding; BN_BLINDING *mt_blinding; CRYPTO_RWLOCK *lock; int dirty_cnt; }; struct rsa_meth_st { char *name; int (*rsa_pub_enc) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding); int (*rsa_pub_dec) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding); int (*rsa_priv_enc) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding); int (*rsa_priv_dec) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding); /* Can be null */ int (*rsa_mod_exp) (BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); /* Can be null */ int (*bn_mod_exp) (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); /* called at new */ int (*init) (RSA *rsa); /* called at free */ int (*finish) (RSA *rsa); /* RSA_METHOD_FLAG_* things */ int flags; /* may be needed! */ char *app_data; /* * New sign and verify functions: some libraries don't allow arbitrary * data to be signed/verified: this allows them to be used. Note: for * this to work the RSA_public_decrypt() and RSA_private_encrypt() should * *NOT* be used. RSA_sign(), RSA_verify() should be used instead. */ int (*rsa_sign) (int type, const unsigned char *m, unsigned int m_length, unsigned char *sigret, unsigned int *siglen, const RSA *rsa); int (*rsa_verify) (int dtype, const unsigned char *m, unsigned int m_length, const unsigned char *sigbuf, unsigned int siglen, const RSA *rsa); /* * If this callback is NULL, the builtin software RSA key-gen will be * used. This is for behavioural compatibility whilst the code gets * rewired, but one day it would be nice to assume there are no such * things as "builtin software" implementations. */ int (*rsa_keygen) (RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); int (*rsa_multi_prime_keygen) (RSA *rsa, int bits, int primes, BIGNUM *e, BN_GENCB *cb); }; /* Macros to test if a pkey or ctx is for a PSS key */ #define pkey_is_pss(pkey) (pkey->ameth->pkey_id == EVP_PKEY_RSA_PSS) #define pkey_ctx_is_pss(ctx) (ctx->pmeth->pkey_id == EVP_PKEY_RSA_PSS) int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes, BIGNUM *e_value, STACK_OF(BIGNUM) *factors, STACK_OF(BIGNUM) *exps, STACK_OF(BIGNUM) *coeffs); RSA_PSS_PARAMS *ossl_rsa_pss_params_create(const EVP_MD *sigmd, const EVP_MD *mgf1md, int saltlen); int ossl_rsa_pss_get_param(const RSA_PSS_PARAMS *pss, const EVP_MD **pmd, const EVP_MD **pmgf1md, int *psaltlen); /* internal function to clear and free multi-prime parameters */ void ossl_rsa_multip_info_free_ex(RSA_PRIME_INFO *pinfo); void ossl_rsa_multip_info_free(RSA_PRIME_INFO *pinfo); RSA_PRIME_INFO *ossl_rsa_multip_info_new(void); int ossl_rsa_multip_calc_product(RSA *rsa); int ossl_rsa_multip_cap(int bits); int ossl_rsa_sp800_56b_validate_strength(int nbits, int strength); int ossl_rsa_check_pminusq_diff(BIGNUM *diff, const BIGNUM *p, const BIGNUM *q, int nbits); int ossl_rsa_get_lcm(BN_CTX *ctx, const BIGNUM *p, const BIGNUM *q, BIGNUM *lcm, BIGNUM *gcd, BIGNUM *p1, BIGNUM *q1, BIGNUM *p1q1); int ossl_rsa_check_public_exponent(const BIGNUM *e); int ossl_rsa_check_private_exponent(const RSA *rsa, int nbits, BN_CTX *ctx); int ossl_rsa_check_prime_factor(BIGNUM *p, BIGNUM *e, int nbits, BN_CTX *ctx); int ossl_rsa_check_prime_factor_range(const BIGNUM *p, int nbits, BN_CTX *ctx); int ossl_rsa_check_crt_components(const RSA *rsa, BN_CTX *ctx); int ossl_rsa_sp800_56b_pairwise_test(RSA *rsa, BN_CTX *ctx); int ossl_rsa_sp800_56b_check_public(const RSA *rsa); int ossl_rsa_sp800_56b_check_private(const RSA *rsa); int ossl_rsa_sp800_56b_check_keypair(const RSA *rsa, const BIGNUM *efixed, int strength, int nbits); int ossl_rsa_sp800_56b_generate_key(RSA *rsa, int nbits, const BIGNUM *efixed, BN_GENCB *cb); int ossl_rsa_sp800_56b_derive_params_from_pq(RSA *rsa, int nbits, const BIGNUM *e, BN_CTX *ctx); int ossl_rsa_fips186_4_gen_prob_primes(RSA *rsa, RSA_ACVP_TEST *test, int nbits, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb); int ossl_rsa_padding_add_PKCS1_type_2_ex(OSSL_LIB_CTX *libctx, unsigned char *to, int tlen, const unsigned char *from, int flen); #endif /* OSSL_CRYPTO_RSA_LOCAL_H */
./openssl/crypto/rsa/rsa_sign.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/objects.h> #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MD2 # include <openssl/md2.h> /* uses MD2_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_MD4 # include <openssl/md4.h> /* uses MD4_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_MD5 # include <openssl/md5.h> /* uses MD5_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_MDC2 # include <openssl/mdc2.h> /* uses MDC2_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_RMD160 # include <openssl/ripemd.h> /* uses RIPEMD160_DIGEST_LENGTH */ # endif #endif #include <openssl/sha.h> /* uses SHA???_DIGEST_LENGTH */ #include "crypto/rsa.h" #include "rsa_local.h" /* * The general purpose ASN1 code is not available inside the FIPS provider. * To remove the dependency RSASSA-PKCS1-v1_5 DigestInfo encodings can be * treated as a special case by pregenerating the required ASN1 encoding. * This encoding will also be shared by the default provider. * * The EMSA-PKCS1-v1_5 encoding method includes an ASN.1 value of type * DigestInfo, where the type DigestInfo has the syntax * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithm, * digest OCTET STRING * } * * DigestAlgorithm ::= AlgorithmIdentifier { * {PKCS1-v1-5DigestAlgorithms} * } * * The AlgorithmIdentifier is a sequence containing the digest OID and * parameters (a value of type NULL). * * The ENCODE_DIGESTINFO_SHA() and ENCODE_DIGESTINFO_MD() macros define an * initialized array containing the DER encoded DigestInfo for the specified * SHA or MD digest. The content of the OCTET STRING is not included. * |name| is the digest name. * |n| is last byte in the encoded OID for the digest. * |sz| is the digest length in bytes. It must not be greater than 110. */ #define ASN1_SEQUENCE 0x30 #define ASN1_OCTET_STRING 0x04 #define ASN1_NULL 0x05 #define ASN1_OID 0x06 /* SHA OIDs are of the form: (2 16 840 1 101 3 4 2 |n|) */ #define ENCODE_DIGESTINFO_SHA(name, n, sz) \ static const unsigned char digestinfo_##name##_der[] = { \ ASN1_SEQUENCE, 0x11 + sz, \ ASN1_SEQUENCE, 0x0d, \ ASN1_OID, 0x09, 2 * 40 + 16, 0x86, 0x48, 1, 101, 3, 4, 2, n, \ ASN1_NULL, 0x00, \ ASN1_OCTET_STRING, sz \ }; /* MD2, MD4 and MD5 OIDs are of the form: (1 2 840 113549 2 |n|) */ #define ENCODE_DIGESTINFO_MD(name, n, sz) \ static const unsigned char digestinfo_##name##_der[] = { \ ASN1_SEQUENCE, 0x10 + sz, \ ASN1_SEQUENCE, 0x0c, \ ASN1_OID, 0x08, 1 * 40 + 2, 0x86, 0x48, 0x86, 0xf7, 0x0d, 2, n, \ ASN1_NULL, 0x00, \ ASN1_OCTET_STRING, sz \ }; #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MD2 ENCODE_DIGESTINFO_MD(md2, 0x02, MD2_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD4 ENCODE_DIGESTINFO_MD(md4, 0x03, MD4_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD5 ENCODE_DIGESTINFO_MD(md5, 0x05, MD5_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MDC2 /* MDC-2 (2 5 8 3 101) */ static const unsigned char digestinfo_mdc2_der[] = { ASN1_SEQUENCE, 0x0c + MDC2_DIGEST_LENGTH, ASN1_SEQUENCE, 0x08, ASN1_OID, 0x04, 2 * 40 + 5, 8, 3, 101, ASN1_NULL, 0x00, ASN1_OCTET_STRING, MDC2_DIGEST_LENGTH }; # endif # ifndef OPENSSL_NO_RMD160 /* RIPEMD160 (1 3 36 3 2 1) */ static const unsigned char digestinfo_ripemd160_der[] = { ASN1_SEQUENCE, 0x0d + RIPEMD160_DIGEST_LENGTH, ASN1_SEQUENCE, 0x09, ASN1_OID, 0x05, 1 * 40 + 3, 36, 3, 2, 1, ASN1_NULL, 0x00, ASN1_OCTET_STRING, RIPEMD160_DIGEST_LENGTH }; # endif #endif /* FIPS_MODULE */ /* SHA-1 (1 3 14 3 2 26) */ static const unsigned char digestinfo_sha1_der[] = { ASN1_SEQUENCE, 0x0d + SHA_DIGEST_LENGTH, ASN1_SEQUENCE, 0x09, ASN1_OID, 0x05, 1 * 40 + 3, 14, 3, 2, 26, ASN1_NULL, 0x00, ASN1_OCTET_STRING, SHA_DIGEST_LENGTH }; ENCODE_DIGESTINFO_SHA(sha256, 0x01, SHA256_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha384, 0x02, SHA384_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha512, 0x03, SHA512_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha224, 0x04, SHA224_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha512_224, 0x05, SHA224_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha512_256, 0x06, SHA256_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_224, 0x07, SHA224_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_256, 0x08, SHA256_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_384, 0x09, SHA384_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_512, 0x0a, SHA512_DIGEST_LENGTH) #define MD_CASE(name) \ case NID_##name: \ *len = sizeof(digestinfo_##name##_der); \ return digestinfo_##name##_der; const unsigned char *ossl_rsa_digestinfo_encoding(int md_nid, size_t *len) { switch (md_nid) { #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MDC2 MD_CASE(mdc2) # endif # ifndef OPENSSL_NO_MD2 MD_CASE(md2) # endif # ifndef OPENSSL_NO_MD4 MD_CASE(md4) # endif # ifndef OPENSSL_NO_MD5 MD_CASE(md5) # endif # ifndef OPENSSL_NO_RMD160 MD_CASE(ripemd160) # endif #endif /* FIPS_MODULE */ MD_CASE(sha1) MD_CASE(sha224) MD_CASE(sha256) MD_CASE(sha384) MD_CASE(sha512) MD_CASE(sha512_224) MD_CASE(sha512_256) MD_CASE(sha3_224) MD_CASE(sha3_256) MD_CASE(sha3_384) MD_CASE(sha3_512) default: return NULL; } } #define MD_NID_CASE(name, sz) \ case NID_##name: \ return sz; static int digest_sz_from_nid(int nid) { switch (nid) { #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MDC2 MD_NID_CASE(mdc2, MDC2_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD2 MD_NID_CASE(md2, MD2_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD4 MD_NID_CASE(md4, MD4_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD5 MD_NID_CASE(md5, MD5_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_RMD160 MD_NID_CASE(ripemd160, RIPEMD160_DIGEST_LENGTH) # endif #endif /* FIPS_MODULE */ MD_NID_CASE(sha1, SHA_DIGEST_LENGTH) MD_NID_CASE(sha224, SHA224_DIGEST_LENGTH) MD_NID_CASE(sha256, SHA256_DIGEST_LENGTH) MD_NID_CASE(sha384, SHA384_DIGEST_LENGTH) MD_NID_CASE(sha512, SHA512_DIGEST_LENGTH) MD_NID_CASE(sha512_224, SHA224_DIGEST_LENGTH) MD_NID_CASE(sha512_256, SHA256_DIGEST_LENGTH) MD_NID_CASE(sha3_224, SHA224_DIGEST_LENGTH) MD_NID_CASE(sha3_256, SHA256_DIGEST_LENGTH) MD_NID_CASE(sha3_384, SHA384_DIGEST_LENGTH) MD_NID_CASE(sha3_512, SHA512_DIGEST_LENGTH) default: return 0; } } /* Size of an SSL signature: MD5+SHA1 */ #define SSL_SIG_LENGTH 36 /* * Encodes a DigestInfo prefix of hash |type| and digest |m|, as * described in EMSA-PKCS1-v1_5-ENCODE, RFC 3447 section 9.2 step 2. This * encodes the DigestInfo (T and tLen) but does not add the padding. * * On success, it returns one and sets |*out| to a newly allocated buffer * containing the result and |*out_len| to its length. The caller must free * |*out| with OPENSSL_free(). Otherwise, it returns zero. */ static int encode_pkcs1(unsigned char **out, size_t *out_len, int type, const unsigned char *m, size_t m_len) { size_t di_prefix_len, dig_info_len; const unsigned char *di_prefix; unsigned char *dig_info; if (type == NID_undef) { ERR_raise(ERR_LIB_RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE); return 0; } di_prefix = ossl_rsa_digestinfo_encoding(type, &di_prefix_len); if (di_prefix == NULL) { ERR_raise(ERR_LIB_RSA, RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD); return 0; } dig_info_len = di_prefix_len + m_len; dig_info = OPENSSL_malloc(dig_info_len); if (dig_info == NULL) return 0; memcpy(dig_info, di_prefix, di_prefix_len); memcpy(dig_info + di_prefix_len, m, m_len); *out = dig_info; *out_len = dig_info_len; return 1; } int RSA_sign(int type, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, RSA *rsa) { int encrypt_len, ret = 0; size_t encoded_len = 0; unsigned char *tmps = NULL; const unsigned char *encoded = NULL; #ifndef FIPS_MODULE if (rsa->meth->rsa_sign != NULL) return rsa->meth->rsa_sign(type, m, m_len, sigret, siglen, rsa) > 0; #endif /* FIPS_MODULE */ /* Compute the encoded digest. */ if (type == NID_md5_sha1) { /* * NID_md5_sha1 corresponds to the MD5/SHA1 combination in TLS 1.1 and * earlier. It has no DigestInfo wrapper but otherwise is * RSASSA-PKCS1-v1_5. */ if (m_len != SSL_SIG_LENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MESSAGE_LENGTH); return 0; } encoded_len = SSL_SIG_LENGTH; encoded = m; } else { if (!encode_pkcs1(&tmps, &encoded_len, type, m, m_len)) goto err; encoded = tmps; } if (encoded_len + RSA_PKCS1_PADDING_SIZE > (size_t)RSA_size(rsa)) { ERR_raise(ERR_LIB_RSA, RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY); goto err; } encrypt_len = RSA_private_encrypt((int)encoded_len, encoded, sigret, rsa, RSA_PKCS1_PADDING); if (encrypt_len <= 0) goto err; *siglen = encrypt_len; ret = 1; err: OPENSSL_clear_free(tmps, encoded_len); return ret; } /* * Verify an RSA signature in |sigbuf| using |rsa|. * |type| is the NID of the digest algorithm to use. * If |rm| is NULL, it verifies the signature for digest |m|, otherwise * it recovers the digest from the signature, writing the digest to |rm| and * the length to |*prm_len|. * * It returns one on successful verification or zero otherwise. */ int ossl_rsa_verify(int type, const unsigned char *m, unsigned int m_len, unsigned char *rm, size_t *prm_len, const unsigned char *sigbuf, size_t siglen, RSA *rsa) { int len, ret = 0; size_t decrypt_len, encoded_len = 0; unsigned char *decrypt_buf = NULL, *encoded = NULL; if (siglen != (size_t)RSA_size(rsa)) { ERR_raise(ERR_LIB_RSA, RSA_R_WRONG_SIGNATURE_LENGTH); return 0; } /* Recover the encoded digest. */ decrypt_buf = OPENSSL_malloc(siglen); if (decrypt_buf == NULL) goto err; len = RSA_public_decrypt((int)siglen, sigbuf, decrypt_buf, rsa, RSA_PKCS1_PADDING); if (len <= 0) goto err; decrypt_len = len; #ifndef FIPS_MODULE if (type == NID_md5_sha1) { /* * NID_md5_sha1 corresponds to the MD5/SHA1 combination in TLS 1.1 and * earlier. It has no DigestInfo wrapper but otherwise is * RSASSA-PKCS1-v1_5. */ if (decrypt_len != SSL_SIG_LENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } if (rm != NULL) { memcpy(rm, decrypt_buf, SSL_SIG_LENGTH); *prm_len = SSL_SIG_LENGTH; } else { if (m_len != SSL_SIG_LENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MESSAGE_LENGTH); goto err; } if (memcmp(decrypt_buf, m, SSL_SIG_LENGTH) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } } } else if (type == NID_mdc2 && decrypt_len == 2 + 16 && decrypt_buf[0] == 0x04 && decrypt_buf[1] == 0x10) { /* * Oddball MDC2 case: signature can be OCTET STRING. check for correct * tag and length octets. */ if (rm != NULL) { memcpy(rm, decrypt_buf + 2, 16); *prm_len = 16; } else { if (m_len != 16) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MESSAGE_LENGTH); goto err; } if (memcmp(m, decrypt_buf + 2, 16) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } } } else #endif /* FIPS_MODULE */ { /* * If recovering the digest, extract a digest-sized output from the end * of |decrypt_buf| for |encode_pkcs1|, then compare the decryption * output as in a standard verification. */ if (rm != NULL) { len = digest_sz_from_nid(type); if (len <= 0) goto err; m_len = (unsigned int)len; if (m_len > decrypt_len) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_DIGEST_LENGTH); goto err; } m = decrypt_buf + decrypt_len - m_len; } /* Construct the encoded digest and ensure it matches. */ if (!encode_pkcs1(&encoded, &encoded_len, type, m, m_len)) goto err; if (encoded_len != decrypt_len || memcmp(encoded, decrypt_buf, encoded_len) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } /* Output the recovered digest. */ if (rm != NULL) { memcpy(rm, m, m_len); *prm_len = m_len; } } ret = 1; err: OPENSSL_clear_free(encoded, encoded_len); OPENSSL_clear_free(decrypt_buf, siglen); return ret; } int RSA_verify(int type, const unsigned char *m, unsigned int m_len, const unsigned char *sigbuf, unsigned int siglen, RSA *rsa) { if (rsa->meth->rsa_verify != NULL) return rsa->meth->rsa_verify(type, m, m_len, sigbuf, siglen, rsa); return ossl_rsa_verify(type, m, m_len, NULL, NULL, sigbuf, siglen, rsa); }
./openssl/crypto/rsa/rsa_sp800_56b_check.c
/* * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2018-2019, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/bn.h> #include "crypto/bn.h" #include "rsa_local.h" /* * Part of the RSA keypair test. * Check the Chinese Remainder Theorem components are valid. * * See SP800-5bBr1 * 6.4.1.2.3: rsakpv1-crt Step 7 * 6.4.1.3.3: rsakpv2-crt Step 7 */ int ossl_rsa_check_crt_components(const RSA *rsa, BN_CTX *ctx) { int ret = 0; BIGNUM *r = NULL, *p1 = NULL, *q1 = NULL; /* check if only some of the crt components are set */ if (rsa->dmp1 == NULL || rsa->dmq1 == NULL || rsa->iqmp == NULL) { if (rsa->dmp1 != NULL || rsa->dmq1 != NULL || rsa->iqmp != NULL) return 0; return 1; /* return ok if all components are NULL */ } BN_CTX_start(ctx); r = BN_CTX_get(ctx); p1 = BN_CTX_get(ctx); q1 = BN_CTX_get(ctx); if (q1 != NULL) { BN_set_flags(r, BN_FLG_CONSTTIME); BN_set_flags(p1, BN_FLG_CONSTTIME); BN_set_flags(q1, BN_FLG_CONSTTIME); ret = 1; } else { ret = 0; } ret = ret /* p1 = p -1 */ && (BN_copy(p1, rsa->p) != NULL) && BN_sub_word(p1, 1) /* q1 = q - 1 */ && (BN_copy(q1, rsa->q) != NULL) && BN_sub_word(q1, 1) /* (a) 1 < dP < (p – 1). */ && (BN_cmp(rsa->dmp1, BN_value_one()) > 0) && (BN_cmp(rsa->dmp1, p1) < 0) /* (b) 1 < dQ < (q - 1). */ && (BN_cmp(rsa->dmq1, BN_value_one()) > 0) && (BN_cmp(rsa->dmq1, q1) < 0) /* (c) 1 < qInv < p */ && (BN_cmp(rsa->iqmp, BN_value_one()) > 0) && (BN_cmp(rsa->iqmp, rsa->p) < 0) /* (d) 1 = (dP . e) mod (p - 1)*/ && BN_mod_mul(r, rsa->dmp1, rsa->e, p1, ctx) && BN_is_one(r) /* (e) 1 = (dQ . e) mod (q - 1) */ && BN_mod_mul(r, rsa->dmq1, rsa->e, q1, ctx) && BN_is_one(r) /* (f) 1 = (qInv . q) mod p */ && BN_mod_mul(r, rsa->iqmp, rsa->q, rsa->p, ctx) && BN_is_one(r); BN_clear(r); BN_clear(p1); BN_clear(q1); BN_CTX_end(ctx); return ret; } /* * Part of the RSA keypair test. * Check that (√2)(2^(nbits/2 - 1) <= p <= 2^(nbits/2) - 1 * * See SP800-5bBr1 6.4.1.2.1 Part 5 (c) & (g) - used for both p and q. * * (√2)(2^(nbits/2 - 1) = (√2/2)(2^(nbits/2)) */ int ossl_rsa_check_prime_factor_range(const BIGNUM *p, int nbits, BN_CTX *ctx) { int ret = 0; BIGNUM *low; int shift; nbits >>= 1; shift = nbits - BN_num_bits(&ossl_bn_inv_sqrt_2); /* Upper bound check */ if (BN_num_bits(p) != nbits) return 0; BN_CTX_start(ctx); low = BN_CTX_get(ctx); if (low == NULL) goto err; /* set low = (√2)(2^(nbits/2 - 1) */ if (!BN_copy(low, &ossl_bn_inv_sqrt_2)) goto err; if (shift >= 0) { /* * We don't have all the bits. ossl_bn_inv_sqrt_2 contains a rounded up * value, so there is a very low probability that we'll reject a valid * value. */ if (!BN_lshift(low, low, shift)) goto err; } else if (!BN_rshift(low, low, -shift)) { goto err; } if (BN_cmp(p, low) <= 0) goto err; ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Part of the RSA keypair test. * Check the prime factor (for either p or q) * i.e: p is prime AND GCD(p - 1, e) = 1 * * See SP800-56Br1 6.4.1.2.3 Step 5 (a to d) & (e to h). */ int ossl_rsa_check_prime_factor(BIGNUM *p, BIGNUM *e, int nbits, BN_CTX *ctx) { int ret = 0; BIGNUM *p1 = NULL, *gcd = NULL; /* (Steps 5 a-b) prime test */ if (BN_check_prime(p, ctx, NULL) != 1 /* (Step 5c) (√2)(2^(nbits/2 - 1) <= p <= 2^(nbits/2 - 1) */ || ossl_rsa_check_prime_factor_range(p, nbits, ctx) != 1) return 0; BN_CTX_start(ctx); p1 = BN_CTX_get(ctx); gcd = BN_CTX_get(ctx); if (gcd != NULL) { BN_set_flags(p1, BN_FLG_CONSTTIME); BN_set_flags(gcd, BN_FLG_CONSTTIME); ret = 1; } else { ret = 0; } ret = ret /* (Step 5d) GCD(p-1, e) = 1 */ && (BN_copy(p1, p) != NULL) && BN_sub_word(p1, 1) && BN_gcd(gcd, p1, e, ctx) && BN_is_one(gcd); BN_clear(p1); BN_CTX_end(ctx); return ret; } /* * See SP800-56Br1 6.4.1.2.3 Part 6(a-b) Check the private exponent d * satisfies: * (Step 6a) 2^(nBit/2) < d < LCM(p–1, q–1). * (Step 6b) 1 = (d*e) mod LCM(p–1, q–1) */ int ossl_rsa_check_private_exponent(const RSA *rsa, int nbits, BN_CTX *ctx) { int ret; BIGNUM *r, *p1, *q1, *lcm, *p1q1, *gcd; /* (Step 6a) 2^(nbits/2) < d */ if (BN_num_bits(rsa->d) <= (nbits >> 1)) return 0; BN_CTX_start(ctx); r = BN_CTX_get(ctx); p1 = BN_CTX_get(ctx); q1 = BN_CTX_get(ctx); lcm = BN_CTX_get(ctx); p1q1 = BN_CTX_get(ctx); gcd = BN_CTX_get(ctx); if (gcd != NULL) { BN_set_flags(r, BN_FLG_CONSTTIME); BN_set_flags(p1, BN_FLG_CONSTTIME); BN_set_flags(q1, BN_FLG_CONSTTIME); BN_set_flags(lcm, BN_FLG_CONSTTIME); BN_set_flags(p1q1, BN_FLG_CONSTTIME); BN_set_flags(gcd, BN_FLG_CONSTTIME); ret = 1; } else { ret = 0; } ret = (ret /* LCM(p - 1, q - 1) */ && (ossl_rsa_get_lcm(ctx, rsa->p, rsa->q, lcm, gcd, p1, q1, p1q1) == 1) /* (Step 6a) d < LCM(p - 1, q - 1) */ && (BN_cmp(rsa->d, lcm) < 0) /* (Step 6b) 1 = (e . d) mod LCM(p - 1, q - 1) */ && BN_mod_mul(r, rsa->e, rsa->d, lcm, ctx) && BN_is_one(r)); BN_clear(r); BN_clear(p1); BN_clear(q1); BN_clear(lcm); BN_clear(gcd); BN_CTX_end(ctx); return ret; } /* * Check exponent is odd. * For FIPS also check the bit length is in the range [17..256] */ int ossl_rsa_check_public_exponent(const BIGNUM *e) { #ifdef FIPS_MODULE int bitlen; bitlen = BN_num_bits(e); return (BN_is_odd(e) && bitlen > 16 && bitlen < 257); #else /* Allow small exponents larger than 1 for legacy purposes */ return BN_is_odd(e) && BN_cmp(e, BN_value_one()) > 0; #endif /* FIPS_MODULE */ } /* * SP800-56Br1 6.4.1.2.1 (Step 5i): |p - q| > 2^(nbits/2 - 100) * i.e- numbits(p-q-1) > (nbits/2 -100) */ int ossl_rsa_check_pminusq_diff(BIGNUM *diff, const BIGNUM *p, const BIGNUM *q, int nbits) { int bitlen = (nbits >> 1) - 100; if (!BN_sub(diff, p, q)) return -1; BN_set_negative(diff, 0); if (BN_is_zero(diff)) return 0; if (!BN_sub_word(diff, 1)) return -1; return (BN_num_bits(diff) > bitlen); } /* * return LCM(p-1, q-1) * * Caller should ensure that lcm, gcd, p1, q1, p1q1 are flagged with * BN_FLG_CONSTTIME. */ int ossl_rsa_get_lcm(BN_CTX *ctx, const BIGNUM *p, const BIGNUM *q, BIGNUM *lcm, BIGNUM *gcd, BIGNUM *p1, BIGNUM *q1, BIGNUM *p1q1) { return BN_sub(p1, p, BN_value_one()) /* p-1 */ && BN_sub(q1, q, BN_value_one()) /* q-1 */ && BN_mul(p1q1, p1, q1, ctx) /* (p-1)(q-1) */ && BN_gcd(gcd, p1, q1, ctx) && BN_div(lcm, NULL, p1q1, gcd, ctx); /* LCM((p-1, q-1)) */ } /* * SP800-56Br1 6.4.2.2 Partial Public Key Validation for RSA refers to * SP800-89 5.3.3 (Explicit) Partial Public Key Validation for RSA * caveat is that the modulus must be as specified in SP800-56Br1 */ int ossl_rsa_sp800_56b_check_public(const RSA *rsa) { int ret = 0, status; int nbits; BN_CTX *ctx = NULL; BIGNUM *gcd = NULL; if (rsa->n == NULL || rsa->e == NULL) return 0; nbits = BN_num_bits(rsa->n); if (nbits > OPENSSL_RSA_MAX_MODULUS_BITS) { ERR_raise(ERR_LIB_RSA, RSA_R_MODULUS_TOO_LARGE); return 0; } #ifdef FIPS_MODULE /* * (Step a): modulus must be 2048 or 3072 (caveat from SP800-56Br1) * NOTE: changed to allow keys >= 2048 */ if (!ossl_rsa_sp800_56b_validate_strength(nbits, -1)) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_KEY_LENGTH); return 0; } #endif if (!BN_is_odd(rsa->n)) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MODULUS); return 0; } /* (Steps b-c): 2^16 < e < 2^256, n and e must be odd */ if (!ossl_rsa_check_public_exponent(rsa->e)) { ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE); return 0; } ctx = BN_CTX_new_ex(rsa->libctx); gcd = BN_new(); if (ctx == NULL || gcd == NULL) goto err; /* (Steps d-f): * The modulus is composite, but not a power of a prime. * The modulus has no factors smaller than 752. */ if (!BN_gcd(gcd, rsa->n, ossl_bn_get0_small_factors(), ctx) || !BN_is_one(gcd)) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MODULUS); goto err; } /* Highest number of MR rounds from FIPS 186-5 Section B.3 Table B.1 */ ret = ossl_bn_miller_rabin_is_prime(rsa->n, 5, ctx, NULL, 1, &status); #ifdef FIPS_MODULE if (ret != 1 || status != BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME) { #else if (ret != 1 || (status != BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME && (nbits >= RSA_MIN_MODULUS_BITS || status != BN_PRIMETEST_COMPOSITE_WITH_FACTOR))) { #endif ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MODULUS); ret = 0; goto err; } ret = 1; err: BN_free(gcd); BN_CTX_free(ctx); return ret; } /* * Perform validation of the RSA private key to check that 0 < D < N. */ int ossl_rsa_sp800_56b_check_private(const RSA *rsa) { if (rsa->d == NULL || rsa->n == NULL) return 0; return BN_cmp(rsa->d, BN_value_one()) >= 0 && BN_cmp(rsa->d, rsa->n) < 0; } /* * RSA key pair validation. * * SP800-56Br1. * 6.4.1.2 "RSAKPV1 Family: RSA Key - Pair Validation with a Fixed Exponent" * 6.4.1.3 "RSAKPV2 Family: RSA Key - Pair Validation with a Random Exponent" * * It uses: * 6.4.1.2.3 "rsakpv1 - crt" * 6.4.1.3.3 "rsakpv2 - crt" */ int ossl_rsa_sp800_56b_check_keypair(const RSA *rsa, const BIGNUM *efixed, int strength, int nbits) { int ret = 0; BN_CTX *ctx = NULL; BIGNUM *r = NULL; if (rsa->p == NULL || rsa->q == NULL || rsa->e == NULL || rsa->d == NULL || rsa->n == NULL) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_REQUEST); return 0; } /* (Step 1): Check Ranges */ if (!ossl_rsa_sp800_56b_validate_strength(nbits, strength)) return 0; /* If the exponent is known */ if (efixed != NULL) { /* (2): Check fixed exponent matches public exponent. */ if (BN_cmp(efixed, rsa->e) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_REQUEST); return 0; } } /* (Step 1.c): e is odd integer 65537 <= e < 2^256 */ if (!ossl_rsa_check_public_exponent(rsa->e)) { /* exponent out of range */ ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE); return 0; } /* (Step 3.b): check the modulus */ if (nbits != BN_num_bits(rsa->n)) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_KEYPAIR); return 0; } /* (Step 3.c): check that the modulus length is a positive even integer */ if (nbits <= 0 || (nbits & 0x1)) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_KEYPAIR); return 0; } ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) return 0; BN_CTX_start(ctx); r = BN_CTX_get(ctx); if (r == NULL || !BN_mul(r, rsa->p, rsa->q, ctx)) goto err; /* (Step 4.c): Check n = pq */ if (BN_cmp(rsa->n, r) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_REQUEST); goto err; } /* (Step 5): check prime factors p & q */ ret = ossl_rsa_check_prime_factor(rsa->p, rsa->e, nbits, ctx) && ossl_rsa_check_prime_factor(rsa->q, rsa->e, nbits, ctx) && (ossl_rsa_check_pminusq_diff(r, rsa->p, rsa->q, nbits) > 0) /* (Step 6): Check the private exponent d */ && ossl_rsa_check_private_exponent(rsa, nbits, ctx) /* 6.4.1.2.3 (Step 7): Check the CRT components */ && ossl_rsa_check_crt_components(rsa, ctx); if (ret != 1) ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_KEYPAIR); err: BN_clear(r); BN_CTX_end(ctx); BN_CTX_free(ctx); return ret; }
./openssl/crypto/rsa/rsa_acvp_test_params.c
/* * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> /* memcpy */ #include <openssl/core_names.h> #include <openssl/param_build.h> #include "crypto/rsa.h" #include "rsa_local.h" int ossl_rsa_acvp_test_gen_params_new(OSSL_PARAM **dst, const OSSL_PARAM src[]) { const OSSL_PARAM *p, *s; OSSL_PARAM *d, *alloc = NULL; int ret = 1; static const OSSL_PARAM settable[] = { OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XP, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XP1, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XP2, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XQ, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XQ1, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XQ2, NULL, 0), OSSL_PARAM_END }; /* Assume the first element is a required field if this feature is used */ p = OSSL_PARAM_locate_const(src, settable[0].key); if (p == NULL) return 1; /* Zeroing here means the terminator is always set at the end */ alloc = OPENSSL_zalloc(sizeof(settable)); if (alloc == NULL) return 0; d = alloc; for (s = settable; s->key != NULL; ++s) { /* If src contains a key from settable then copy the src to the dest */ p = OSSL_PARAM_locate_const(src, s->key); if (p != NULL) { *d = *s; /* shallow copy from the static settable[] */ d->data_size = p->data_size; d->data = OPENSSL_memdup(p->data, p->data_size); if (d->data == NULL) ret = 0; ++d; } } if (ret == 0) { ossl_rsa_acvp_test_gen_params_free(alloc); alloc = NULL; } if (*dst != NULL) ossl_rsa_acvp_test_gen_params_free(*dst); *dst = alloc; return ret; } void ossl_rsa_acvp_test_gen_params_free(OSSL_PARAM *dst) { OSSL_PARAM *p; if (dst == NULL) return; for (p = dst; p->key != NULL; ++p) { OPENSSL_free(p->data); p->data = NULL; } OPENSSL_free(dst); } int ossl_rsa_acvp_test_set_params(RSA *r, const OSSL_PARAM params[]) { RSA_ACVP_TEST *t; const OSSL_PARAM *p; if (r->acvp_test != NULL) { ossl_rsa_acvp_test_free(r->acvp_test); r->acvp_test = NULL; } t = OPENSSL_zalloc(sizeof(*t)); if (t == NULL) return 0; /* Set the input parameters */ if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XP1)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xp1)) goto err; if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XP2)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xp2)) goto err; if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XP)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xp)) goto err; if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XQ1)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xq1)) goto err; if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XQ2)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xq2)) goto err; if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XQ)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xq)) goto err; /* Setup the output parameters */ t->p1 = BN_new(); t->p2 = BN_new(); t->q1 = BN_new(); t->q2 = BN_new(); r->acvp_test = t; return 1; err: ossl_rsa_acvp_test_free(t); return 0; } int ossl_rsa_acvp_test_get_params(RSA *r, OSSL_PARAM params[]) { RSA_ACVP_TEST *t; OSSL_PARAM *p; if (r == NULL) return 0; t = r->acvp_test; if (t != NULL) { if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_RSA_TEST_P1)) != NULL && !OSSL_PARAM_set_BN(p, t->p1)) return 0; if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_RSA_TEST_P2)) != NULL && !OSSL_PARAM_set_BN(p, t->p2)) return 0; if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_RSA_TEST_Q1)) != NULL && !OSSL_PARAM_set_BN(p, t->q1)) return 0; if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_RSA_TEST_Q2)) != NULL && !OSSL_PARAM_set_BN(p, t->q2)) return 0; } return 1; } void ossl_rsa_acvp_test_free(RSA_ACVP_TEST *t) { if (t != NULL) { BN_free(t->Xp1); BN_free(t->Xp2); BN_free(t->Xp); BN_free(t->Xq1); BN_free(t->Xq2); BN_free(t->Xq); BN_free(t->p1); BN_free(t->p2); BN_free(t->q1); BN_free(t->q2); OPENSSL_free(t); } }
./openssl/crypto/rsa/rsa_ameth.c
/* * Copyright 2006-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> #include <openssl/bn.h> #include <openssl/core_names.h> #include <openssl/param_build.h> #include "crypto/asn1.h" #include "crypto/evp.h" #include "crypto/rsa.h" #include "rsa_local.h" /* Set any parameters associated with pkey */ static int rsa_param_encode(const EVP_PKEY *pkey, ASN1_STRING **pstr, int *pstrtype) { const RSA *rsa = pkey->pkey.rsa; *pstr = NULL; /* If RSA it's just NULL type */ if (RSA_test_flags(rsa, RSA_FLAG_TYPE_MASK) != RSA_FLAG_TYPE_RSASSAPSS) { *pstrtype = V_ASN1_NULL; return 1; } /* If no PSS parameters we omit parameters entirely */ if (rsa->pss == NULL) { *pstrtype = V_ASN1_UNDEF; return 1; } /* Encode PSS parameters */ if (ASN1_item_pack(rsa->pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), pstr) == NULL) return 0; *pstrtype = V_ASN1_SEQUENCE; return 1; } /* Decode any parameters and set them in RSA structure */ static int rsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) { unsigned char *penc = NULL; int penclen; ASN1_STRING *str; int strtype; if (!rsa_param_encode(pkey, &str, &strtype)) return 0; penclen = i2d_RSAPublicKey(pkey->pkey.rsa, &penc); if (penclen <= 0) { ASN1_STRING_free(str); return 0; } if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(pkey->ameth->pkey_id), strtype, str, penc, penclen)) return 1; OPENSSL_free(penc); ASN1_STRING_free(str); return 0; } static int rsa_pub_decode(EVP_PKEY *pkey, const X509_PUBKEY *pubkey) { const unsigned char *p; int pklen; X509_ALGOR *alg; RSA *rsa = NULL; if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &alg, pubkey)) return 0; if ((rsa = d2i_RSAPublicKey(NULL, &p, pklen)) == NULL) return 0; if (!ossl_rsa_param_decode(rsa, alg)) { RSA_free(rsa); return 0; } RSA_clear_flags(rsa, RSA_FLAG_TYPE_MASK); switch (pkey->ameth->pkey_id) { case EVP_PKEY_RSA: RSA_set_flags(rsa, RSA_FLAG_TYPE_RSA); break; case EVP_PKEY_RSA_PSS: RSA_set_flags(rsa, RSA_FLAG_TYPE_RSASSAPSS); break; default: /* Leave the type bits zero */ break; } if (!EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa)) { RSA_free(rsa); return 0; } return 1; } static int rsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { /* * Don't check the public/private key, this is mostly for smart * cards. */ if (((RSA_flags(a->pkey.rsa) & RSA_METHOD_FLAG_NO_CHECK)) || (RSA_flags(b->pkey.rsa) & RSA_METHOD_FLAG_NO_CHECK)) { return 1; } if (BN_cmp(b->pkey.rsa->n, a->pkey.rsa->n) != 0 || BN_cmp(b->pkey.rsa->e, a->pkey.rsa->e) != 0) return 0; return 1; } static int old_rsa_priv_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { RSA *rsa; if ((rsa = d2i_RSAPrivateKey(NULL, pder, derlen)) == NULL) return 0; EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa); return 1; } static int old_rsa_priv_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_RSAPrivateKey(pkey->pkey.rsa, pder); } static int rsa_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey) { unsigned char *rk = NULL; int rklen; ASN1_STRING *str; int strtype; if (!rsa_param_encode(pkey, &str, &strtype)) return 0; rklen = i2d_RSAPrivateKey(pkey->pkey.rsa, &rk); if (rklen <= 0) { ERR_raise(ERR_LIB_RSA, ERR_R_ASN1_LIB); ASN1_STRING_free(str); return 0; } if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(pkey->ameth->pkey_id), 0, strtype, str, rk, rklen)) { ERR_raise(ERR_LIB_RSA, ERR_R_ASN1_LIB); ASN1_STRING_free(str); OPENSSL_clear_free(rk, rklen); return 0; } return 1; } static int rsa_priv_decode(EVP_PKEY *pkey, const PKCS8_PRIV_KEY_INFO *p8) { int ret = 0; RSA *rsa = ossl_rsa_key_from_pkcs8(p8, NULL, NULL); if (rsa != NULL) { ret = 1; EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa); } return ret; } static int int_rsa_size(const EVP_PKEY *pkey) { return RSA_size(pkey->pkey.rsa); } static int rsa_bits(const EVP_PKEY *pkey) { return BN_num_bits(pkey->pkey.rsa->n); } static int rsa_security_bits(const EVP_PKEY *pkey) { return RSA_security_bits(pkey->pkey.rsa); } static void int_rsa_free(EVP_PKEY *pkey) { RSA_free(pkey->pkey.rsa); } static int rsa_pss_param_print(BIO *bp, int pss_key, RSA_PSS_PARAMS *pss, int indent) { int rv = 0; X509_ALGOR *maskHash = NULL; if (!BIO_indent(bp, indent, 128)) goto err; if (pss_key) { if (pss == NULL) { if (BIO_puts(bp, "No PSS parameter restrictions\n") <= 0) return 0; return 1; } else { if (BIO_puts(bp, "PSS parameter restrictions:") <= 0) return 0; } } else if (pss == NULL) { if (BIO_puts(bp, "(INVALID PSS PARAMETERS)\n") <= 0) return 0; return 1; } if (BIO_puts(bp, "\n") <= 0) goto err; if (pss_key) indent += 2; if (!BIO_indent(bp, indent, 128)) goto err; if (BIO_puts(bp, "Hash Algorithm: ") <= 0) goto err; if (pss->hashAlgorithm) { if (i2a_ASN1_OBJECT(bp, pss->hashAlgorithm->algorithm) <= 0) goto err; } else if (BIO_puts(bp, "sha1 (default)") <= 0) { goto err; } if (BIO_puts(bp, "\n") <= 0) goto err; if (!BIO_indent(bp, indent, 128)) goto err; if (BIO_puts(bp, "Mask Algorithm: ") <= 0) goto err; if (pss->maskGenAlgorithm) { if (i2a_ASN1_OBJECT(bp, pss->maskGenAlgorithm->algorithm) <= 0) goto err; if (BIO_puts(bp, " with ") <= 0) goto err; maskHash = ossl_x509_algor_mgf1_decode(pss->maskGenAlgorithm); if (maskHash != NULL) { if (i2a_ASN1_OBJECT(bp, maskHash->algorithm) <= 0) goto err; } else if (BIO_puts(bp, "INVALID") <= 0) { goto err; } } else if (BIO_puts(bp, "mgf1 with sha1 (default)") <= 0) { goto err; } BIO_puts(bp, "\n"); if (!BIO_indent(bp, indent, 128)) goto err; if (BIO_printf(bp, "%s Salt Length: 0x", pss_key ? "Minimum" : "") <= 0) goto err; if (pss->saltLength) { if (i2a_ASN1_INTEGER(bp, pss->saltLength) <= 0) goto err; } else if (BIO_puts(bp, "14 (default)") <= 0) { goto err; } BIO_puts(bp, "\n"); if (!BIO_indent(bp, indent, 128)) goto err; if (BIO_puts(bp, "Trailer Field: 0x") <= 0) goto err; if (pss->trailerField) { if (i2a_ASN1_INTEGER(bp, pss->trailerField) <= 0) goto err; } else if (BIO_puts(bp, "01 (default)") <= 0) { goto err; } BIO_puts(bp, "\n"); rv = 1; err: X509_ALGOR_free(maskHash); return rv; } static int pkey_rsa_print(BIO *bp, const EVP_PKEY *pkey, int off, int priv) { const RSA *x = pkey->pkey.rsa; char *str; const char *s; int ret = 0, mod_len = 0, ex_primes; if (x->n != NULL) mod_len = BN_num_bits(x->n); ex_primes = sk_RSA_PRIME_INFO_num(x->prime_infos); if (!BIO_indent(bp, off, 128)) goto err; if (BIO_printf(bp, "%s ", pkey_is_pss(pkey) ? "RSA-PSS" : "RSA") <= 0) goto err; if (priv && x->d) { if (BIO_printf(bp, "Private-Key: (%d bit, %d primes)\n", mod_len, ex_primes <= 0 ? 2 : ex_primes + 2) <= 0) goto err; str = "modulus:"; s = "publicExponent:"; } else { if (BIO_printf(bp, "Public-Key: (%d bit)\n", mod_len) <= 0) goto err; str = "Modulus:"; s = "Exponent:"; } if (!ASN1_bn_print(bp, str, x->n, NULL, off)) goto err; if (!ASN1_bn_print(bp, s, x->e, NULL, off)) goto err; if (priv) { int i; if (!ASN1_bn_print(bp, "privateExponent:", x->d, NULL, off)) goto err; if (!ASN1_bn_print(bp, "prime1:", x->p, NULL, off)) goto err; if (!ASN1_bn_print(bp, "prime2:", x->q, NULL, off)) goto err; if (!ASN1_bn_print(bp, "exponent1:", x->dmp1, NULL, off)) goto err; if (!ASN1_bn_print(bp, "exponent2:", x->dmq1, NULL, off)) goto err; if (!ASN1_bn_print(bp, "coefficient:", x->iqmp, NULL, off)) goto err; for (i = 0; i < sk_RSA_PRIME_INFO_num(x->prime_infos); i++) { /* print multi-prime info */ BIGNUM *bn = NULL; RSA_PRIME_INFO *pinfo; int j; pinfo = sk_RSA_PRIME_INFO_value(x->prime_infos, i); for (j = 0; j < 3; j++) { if (!BIO_indent(bp, off, 128)) goto err; switch (j) { case 0: if (BIO_printf(bp, "prime%d:", i + 3) <= 0) goto err; bn = pinfo->r; break; case 1: if (BIO_printf(bp, "exponent%d:", i + 3) <= 0) goto err; bn = pinfo->d; break; case 2: if (BIO_printf(bp, "coefficient%d:", i + 3) <= 0) goto err; bn = pinfo->t; break; default: break; } if (!ASN1_bn_print(bp, "", bn, NULL, off)) goto err; } } } if (pkey_is_pss(pkey) && !rsa_pss_param_print(bp, 1, x->pss, off)) goto err; ret = 1; err: return ret; } static int rsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return pkey_rsa_print(bp, pkey, indent, 0); } static int rsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return pkey_rsa_print(bp, pkey, indent, 1); } static int rsa_sig_print(BIO *bp, const X509_ALGOR *sigalg, const ASN1_STRING *sig, int indent, ASN1_PCTX *pctx) { if (OBJ_obj2nid(sigalg->algorithm) == EVP_PKEY_RSA_PSS) { int rv; RSA_PSS_PARAMS *pss = ossl_rsa_pss_decode(sigalg); rv = rsa_pss_param_print(bp, 0, pss, indent); RSA_PSS_PARAMS_free(pss); if (!rv) return 0; } else if (BIO_puts(bp, "\n") <= 0) { return 0; } if (sig) return X509_signature_dump(bp, sig, indent); return 1; } static int rsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) { const EVP_MD *md; const EVP_MD *mgf1md; int min_saltlen; switch (op) { case ASN1_PKEY_CTRL_DEFAULT_MD_NID: if (pkey->pkey.rsa->pss != NULL) { if (!ossl_rsa_pss_get_param(pkey->pkey.rsa->pss, &md, &mgf1md, &min_saltlen)) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); return 0; } *(int *)arg2 = EVP_MD_get_type(md); /* Return of 2 indicates this MD is mandatory */ return 2; } *(int *)arg2 = NID_sha256; return 1; default: return -2; } } /* * Convert EVP_PKEY_CTX in PSS mode into corresponding algorithm parameter, * suitable for setting an AlgorithmIdentifier. */ static RSA_PSS_PARAMS *rsa_ctx_to_pss(EVP_PKEY_CTX *pkctx) { const EVP_MD *sigmd, *mgf1md; EVP_PKEY *pk = EVP_PKEY_CTX_get0_pkey(pkctx); int saltlen; int saltlenMax = -1; if (EVP_PKEY_CTX_get_signature_md(pkctx, &sigmd) <= 0) return NULL; if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0) return NULL; if (EVP_PKEY_CTX_get_rsa_pss_saltlen(pkctx, &saltlen) <= 0) return NULL; if (saltlen == RSA_PSS_SALTLEN_DIGEST) { saltlen = EVP_MD_get_size(sigmd); } else if (saltlen == RSA_PSS_SALTLEN_AUTO_DIGEST_MAX) { /* FIPS 186-4 section 5 "The RSA Digital Signature Algorithm", * subsection 5.5 "PKCS #1" says: "For RSASSA-PSS […] the length (in * bytes) of the salt (sLen) shall satisfy 0 <= sLen <= hLen, where * hLen is the length of the hash function output block (in bytes)." * * Provide a way to use at most the digest length, so that the default * does not violate FIPS 186-4. */ saltlen = RSA_PSS_SALTLEN_MAX; saltlenMax = EVP_MD_get_size(sigmd); } if (saltlen == RSA_PSS_SALTLEN_MAX || saltlen == RSA_PSS_SALTLEN_AUTO) { saltlen = EVP_PKEY_get_size(pk) - EVP_MD_get_size(sigmd) - 2; if ((EVP_PKEY_get_bits(pk) & 0x7) == 1) saltlen--; if (saltlen < 0) return NULL; if (saltlenMax >= 0 && saltlen > saltlenMax) saltlen = saltlenMax; } return ossl_rsa_pss_params_create(sigmd, mgf1md, saltlen); } RSA_PSS_PARAMS *ossl_rsa_pss_params_create(const EVP_MD *sigmd, const EVP_MD *mgf1md, int saltlen) { RSA_PSS_PARAMS *pss = RSA_PSS_PARAMS_new(); if (pss == NULL) goto err; if (saltlen != 20) { pss->saltLength = ASN1_INTEGER_new(); if (pss->saltLength == NULL) goto err; if (!ASN1_INTEGER_set(pss->saltLength, saltlen)) goto err; } if (!ossl_x509_algor_new_from_md(&pss->hashAlgorithm, sigmd)) goto err; if (mgf1md == NULL) mgf1md = sigmd; if (!ossl_x509_algor_md_to_mgf1(&pss->maskGenAlgorithm, mgf1md)) goto err; if (!ossl_x509_algor_new_from_md(&pss->maskHash, mgf1md)) goto err; return pss; err: RSA_PSS_PARAMS_free(pss); return NULL; } ASN1_STRING *ossl_rsa_ctx_to_pss_string(EVP_PKEY_CTX *pkctx) { RSA_PSS_PARAMS *pss = rsa_ctx_to_pss(pkctx); ASN1_STRING *os; if (pss == NULL) return NULL; os = ASN1_item_pack(pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), NULL); RSA_PSS_PARAMS_free(pss); return os; } /* * From PSS AlgorithmIdentifier set public key parameters. If pkey isn't NULL * then the EVP_MD_CTX is setup and initialised. If it is NULL parameters are * passed to pkctx instead. */ int ossl_rsa_pss_to_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pkctx, const X509_ALGOR *sigalg, EVP_PKEY *pkey) { int rv = -1; int saltlen; const EVP_MD *mgf1md = NULL, *md = NULL; RSA_PSS_PARAMS *pss; /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) { ERR_raise(ERR_LIB_RSA, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } /* Decode PSS parameters */ pss = ossl_rsa_pss_decode(sigalg); if (!ossl_rsa_pss_get_param(pss, &md, &mgf1md, &saltlen)) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PSS_PARAMETERS); goto err; } /* We have all parameters now set up context */ if (pkey) { if (!EVP_DigestVerifyInit(ctx, &pkctx, md, NULL, pkey)) goto err; } else { const EVP_MD *checkmd; if (EVP_PKEY_CTX_get_signature_md(pkctx, &checkmd) <= 0) goto err; if (EVP_MD_get_type(md) != EVP_MD_get_type(checkmd)) { ERR_raise(ERR_LIB_RSA, RSA_R_DIGEST_DOES_NOT_MATCH); goto err; } } if (EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_PSS_PADDING) <= 0) goto err; if (EVP_PKEY_CTX_set_rsa_pss_saltlen(pkctx, saltlen) <= 0) goto err; if (EVP_PKEY_CTX_set_rsa_mgf1_md(pkctx, mgf1md) <= 0) goto err; /* Carry on */ rv = 1; err: RSA_PSS_PARAMS_free(pss); return rv; } static int rsa_pss_verify_param(const EVP_MD **pmd, const EVP_MD **pmgf1md, int *psaltlen, int *ptrailerField) { if (psaltlen != NULL && *psaltlen < 0) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_SALT_LENGTH); return 0; } /* * low-level routines support only trailer field 0xbc (value 1) and * PKCS#1 says we should reject any other value anyway. */ if (ptrailerField != NULL && *ptrailerField != 1) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_TRAILER); return 0; } return 1; } int ossl_rsa_pss_get_param(const RSA_PSS_PARAMS *pss, const EVP_MD **pmd, const EVP_MD **pmgf1md, int *psaltlen) { /* * Callers do not care about the trailer field, and yet, we must * pass it from get_param to verify_param, since the latter checks * its value. * * When callers start caring, it's a simple thing to add another * argument to this function. */ int trailerField = 0; return ossl_rsa_pss_get_param_unverified(pss, pmd, pmgf1md, psaltlen, &trailerField) && rsa_pss_verify_param(pmd, pmgf1md, psaltlen, &trailerField); } /* * Customised RSA item verification routine. This is called when a signature * is encountered requiring special handling. We currently only handle PSS. */ static int rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, const void *asn, const X509_ALGOR *sigalg, const ASN1_BIT_STRING *sig, EVP_PKEY *pkey) { /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) { ERR_raise(ERR_LIB_RSA, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } if (ossl_rsa_pss_to_ctx(ctx, NULL, sigalg, pkey) > 0) { /* Carry on */ return 2; } return -1; } static int rsa_item_sign(EVP_MD_CTX *ctx, const ASN1_ITEM *it, const void *asn, X509_ALGOR *alg1, X509_ALGOR *alg2, ASN1_BIT_STRING *sig) { int pad_mode; EVP_PKEY_CTX *pkctx = EVP_MD_CTX_get_pkey_ctx(ctx); if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0) return 0; if (pad_mode == RSA_PKCS1_PADDING) return 2; if (pad_mode == RSA_PKCS1_PSS_PADDING) { unsigned char aid[128]; size_t aid_len = 0; OSSL_PARAM params[2]; if (evp_pkey_ctx_is_legacy(pkctx)) { /* No provider -> we cannot query it for algorithm ID. */ ASN1_STRING *os1 = NULL; os1 = ossl_rsa_ctx_to_pss_string(pkctx); if (os1 == NULL) return 0; /* Duplicate parameters if we have to */ if (alg2 != NULL) { ASN1_STRING *os2 = ASN1_STRING_dup(os1); if (os2 == NULL) { ASN1_STRING_free(os1); return 0; } if (!X509_ALGOR_set0(alg2, OBJ_nid2obj(EVP_PKEY_RSA_PSS), V_ASN1_SEQUENCE, os2)) { ASN1_STRING_free(os1); ASN1_STRING_free(os2); return 0; } } if (!X509_ALGOR_set0(alg1, OBJ_nid2obj(EVP_PKEY_RSA_PSS), V_ASN1_SEQUENCE, os1)) { ASN1_STRING_free(os1); return 0; } return 3; } params[0] = OSSL_PARAM_construct_octet_string( OSSL_SIGNATURE_PARAM_ALGORITHM_ID, aid, sizeof(aid)); params[1] = OSSL_PARAM_construct_end(); if (EVP_PKEY_CTX_get_params(pkctx, params) <= 0) return 0; if ((aid_len = params[0].return_size) == 0) return 0; if (alg1 != NULL) { const unsigned char *pp = aid; if (d2i_X509_ALGOR(&alg1, &pp, aid_len) == NULL) return 0; } if (alg2 != NULL) { const unsigned char *pp = aid; if (d2i_X509_ALGOR(&alg2, &pp, aid_len) == NULL) return 0; } return 3; } return 2; } static int rsa_sig_info_set(X509_SIG_INFO *siginf, const X509_ALGOR *sigalg, const ASN1_STRING *sig) { int rv = 0; int mdnid, saltlen; uint32_t flags; const EVP_MD *mgf1md = NULL, *md = NULL; RSA_PSS_PARAMS *pss; int secbits; /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) return 0; /* Decode PSS parameters */ pss = ossl_rsa_pss_decode(sigalg); if (!ossl_rsa_pss_get_param(pss, &md, &mgf1md, &saltlen)) goto err; mdnid = EVP_MD_get_type(md); /* * For TLS need SHA256, SHA384 or SHA512, digest and MGF1 digest must * match and salt length must equal digest size */ if ((mdnid == NID_sha256 || mdnid == NID_sha384 || mdnid == NID_sha512) && mdnid == EVP_MD_get_type(mgf1md) && saltlen == EVP_MD_get_size(md)) flags = X509_SIG_INFO_TLS; else flags = 0; /* Note: security bits half number of digest bits */ secbits = EVP_MD_get_size(md) * 4; /* * SHA1 and MD5 are known to be broken. Reduce security bits so that * they're no longer accepted at security level 1. The real values don't * really matter as long as they're lower than 80, which is our security * level 1. * https://eprint.iacr.org/2020/014 puts a chosen-prefix attack for SHA1 at * 2^63.4 * https://documents.epfl.ch/users/l/le/lenstra/public/papers/lat.pdf * puts a chosen-prefix attack for MD5 at 2^39. */ if (mdnid == NID_sha1) secbits = 64; else if (mdnid == NID_md5_sha1) secbits = 68; else if (mdnid == NID_md5) secbits = 39; X509_SIG_INFO_set(siginf, mdnid, EVP_PKEY_RSA_PSS, secbits, flags); rv = 1; err: RSA_PSS_PARAMS_free(pss); return rv; } static int rsa_pkey_check(const EVP_PKEY *pkey) { return RSA_check_key_ex(pkey->pkey.rsa, NULL); } static size_t rsa_pkey_dirty_cnt(const EVP_PKEY *pkey) { return pkey->pkey.rsa->dirty_cnt; } /* * There is no need to do RSA_test_flags(rsa, RSA_FLAG_TYPE_RSASSAPSS) * checks in this method since the caller tests EVP_KEYMGMT_is_a() first. */ static int rsa_int_export_to(const EVP_PKEY *from, int rsa_type, void *to_keydata, OSSL_FUNC_keymgmt_import_fn *importer, OSSL_LIB_CTX *libctx, const char *propq) { RSA *rsa = from->pkey.rsa; OSSL_PARAM_BLD *tmpl = OSSL_PARAM_BLD_new(); OSSL_PARAM *params = NULL; int selection = 0; int rv = 0; if (tmpl == NULL) return 0; /* Public parameters must always be present */ if (RSA_get0_n(rsa) == NULL || RSA_get0_e(rsa) == NULL) goto err; if (!ossl_rsa_todata(rsa, tmpl, NULL, 1)) goto err; selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY; if (RSA_get0_d(rsa) != NULL) selection |= OSSL_KEYMGMT_SELECT_PRIVATE_KEY; if (rsa->pss != NULL) { const EVP_MD *md = NULL, *mgf1md = NULL; int md_nid, mgf1md_nid, saltlen, trailerfield; RSA_PSS_PARAMS_30 pss_params; if (!ossl_rsa_pss_get_param_unverified(rsa->pss, &md, &mgf1md, &saltlen, &trailerfield)) goto err; md_nid = EVP_MD_get_type(md); mgf1md_nid = EVP_MD_get_type(mgf1md); if (!ossl_rsa_pss_params_30_set_defaults(&pss_params) || !ossl_rsa_pss_params_30_set_hashalg(&pss_params, md_nid) || !ossl_rsa_pss_params_30_set_maskgenhashalg(&pss_params, mgf1md_nid) || !ossl_rsa_pss_params_30_set_saltlen(&pss_params, saltlen) || !ossl_rsa_pss_params_30_todata(&pss_params, tmpl, NULL)) goto err; selection |= OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS; } if ((params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) goto err; /* We export, the provider imports */ rv = importer(to_keydata, selection, params); err: OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(tmpl); return rv; } static int rsa_int_import_from(const OSSL_PARAM params[], void *vpctx, int rsa_type) { EVP_PKEY_CTX *pctx = vpctx; EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pctx); RSA *rsa = ossl_rsa_new_with_ctx(pctx->libctx); RSA_PSS_PARAMS_30 rsa_pss_params = { 0, }; int pss_defaults_set = 0; int ok = 0; if (rsa == NULL) { ERR_raise(ERR_LIB_DH, ERR_R_RSA_LIB); return 0; } RSA_clear_flags(rsa, RSA_FLAG_TYPE_MASK); RSA_set_flags(rsa, rsa_type); if (!ossl_rsa_pss_params_30_fromdata(&rsa_pss_params, &pss_defaults_set, params, pctx->libctx)) goto err; switch (rsa_type) { case RSA_FLAG_TYPE_RSA: /* * Were PSS parameters filled in? * In that case, something's wrong */ if (!ossl_rsa_pss_params_30_is_unrestricted(&rsa_pss_params)) goto err; break; case RSA_FLAG_TYPE_RSASSAPSS: /* * Were PSS parameters filled in? In that case, create the old * RSA_PSS_PARAMS structure. Otherwise, this is an unrestricted key. */ if (!ossl_rsa_pss_params_30_is_unrestricted(&rsa_pss_params)) { /* Create the older RSA_PSS_PARAMS from RSA_PSS_PARAMS_30 data */ int mdnid = ossl_rsa_pss_params_30_hashalg(&rsa_pss_params); int mgf1mdnid = ossl_rsa_pss_params_30_maskgenhashalg(&rsa_pss_params); int saltlen = ossl_rsa_pss_params_30_saltlen(&rsa_pss_params); const EVP_MD *md = EVP_get_digestbynid(mdnid); const EVP_MD *mgf1md = EVP_get_digestbynid(mgf1mdnid); if ((rsa->pss = ossl_rsa_pss_params_create(md, mgf1md, saltlen)) == NULL) goto err; } break; default: /* RSA key sub-types we don't know how to handle yet */ goto err; } if (!ossl_rsa_fromdata(rsa, params, 1)) goto err; switch (rsa_type) { case RSA_FLAG_TYPE_RSA: ok = EVP_PKEY_assign_RSA(pkey, rsa); break; case RSA_FLAG_TYPE_RSASSAPSS: ok = EVP_PKEY_assign(pkey, EVP_PKEY_RSA_PSS, rsa); break; } err: if (!ok) RSA_free(rsa); return ok; } static int rsa_pkey_export_to(const EVP_PKEY *from, void *to_keydata, OSSL_FUNC_keymgmt_import_fn *importer, OSSL_LIB_CTX *libctx, const char *propq) { return rsa_int_export_to(from, RSA_FLAG_TYPE_RSA, to_keydata, importer, libctx, propq); } static int rsa_pss_pkey_export_to(const EVP_PKEY *from, void *to_keydata, OSSL_FUNC_keymgmt_import_fn *importer, OSSL_LIB_CTX *libctx, const char *propq) { return rsa_int_export_to(from, RSA_FLAG_TYPE_RSASSAPSS, to_keydata, importer, libctx, propq); } static int rsa_pkey_import_from(const OSSL_PARAM params[], void *vpctx) { return rsa_int_import_from(params, vpctx, RSA_FLAG_TYPE_RSA); } static int rsa_pss_pkey_import_from(const OSSL_PARAM params[], void *vpctx) { return rsa_int_import_from(params, vpctx, RSA_FLAG_TYPE_RSASSAPSS); } static int rsa_pkey_copy(EVP_PKEY *to, EVP_PKEY *from) { RSA *rsa = from->pkey.rsa; RSA *dupkey = NULL; int ret; if (rsa != NULL) { dupkey = ossl_rsa_dup(rsa, OSSL_KEYMGMT_SELECT_ALL); if (dupkey == NULL) return 0; } ret = EVP_PKEY_assign(to, from->type, dupkey); if (!ret) RSA_free(dupkey); return ret; } const EVP_PKEY_ASN1_METHOD ossl_rsa_asn1_meths[2] = { { EVP_PKEY_RSA, EVP_PKEY_RSA, ASN1_PKEY_SIGPARAM_NULL, "RSA", "OpenSSL RSA method", rsa_pub_decode, rsa_pub_encode, rsa_pub_cmp, rsa_pub_print, rsa_priv_decode, rsa_priv_encode, rsa_priv_print, int_rsa_size, rsa_bits, rsa_security_bits, 0, 0, 0, 0, 0, 0, rsa_sig_print, int_rsa_free, rsa_pkey_ctrl, old_rsa_priv_decode, old_rsa_priv_encode, rsa_item_verify, rsa_item_sign, rsa_sig_info_set, rsa_pkey_check, 0, 0, 0, 0, 0, 0, rsa_pkey_dirty_cnt, rsa_pkey_export_to, rsa_pkey_import_from, rsa_pkey_copy }, { EVP_PKEY_RSA2, EVP_PKEY_RSA, ASN1_PKEY_ALIAS} }; const EVP_PKEY_ASN1_METHOD ossl_rsa_pss_asn1_meth = { EVP_PKEY_RSA_PSS, EVP_PKEY_RSA_PSS, ASN1_PKEY_SIGPARAM_NULL, "RSA-PSS", "OpenSSL RSA-PSS method", rsa_pub_decode, rsa_pub_encode, rsa_pub_cmp, rsa_pub_print, rsa_priv_decode, rsa_priv_encode, rsa_priv_print, int_rsa_size, rsa_bits, rsa_security_bits, 0, 0, 0, 0, 0, 0, rsa_sig_print, int_rsa_free, rsa_pkey_ctrl, 0, 0, rsa_item_verify, rsa_item_sign, rsa_sig_info_set, rsa_pkey_check, 0, 0, 0, 0, 0, 0, rsa_pkey_dirty_cnt, rsa_pss_pkey_export_to, rsa_pss_pkey_import_from, rsa_pkey_copy };
./openssl/crypto/rsa/rsa_x931.c
/* * Copyright 2005-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 */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/objects.h> int RSA_padding_add_X931(unsigned char *to, int tlen, const unsigned char *from, int flen) { int j; unsigned char *p; /* * Absolute minimum amount of padding is 1 header nibble, 1 padding * nibble and 2 trailer bytes: but 1 hash if is already in 'from'. */ j = tlen - flen - 2; if (j < 0) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); return -1; } p = (unsigned char *)to; /* If no padding start and end nibbles are in one byte */ if (j == 0) { *p++ = 0x6A; } else { *p++ = 0x6B; if (j > 1) { memset(p, 0xBB, j - 1); p += j - 1; } *p++ = 0xBA; } memcpy(p, from, (unsigned int)flen); p += flen; *p = 0xCC; return 1; } int RSA_padding_check_X931(unsigned char *to, int tlen, const unsigned char *from, int flen, int num) { int i = 0, j; const unsigned char *p; p = from; if ((num != flen) || ((*p != 0x6A) && (*p != 0x6B))) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_HEADER); return -1; } if (*p++ == 0x6B) { j = flen - 3; for (i = 0; i < j; i++) { unsigned char c = *p++; if (c == 0xBA) break; if (c != 0xBB) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING); return -1; } } j -= i; if (i == 0) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING); return -1; } } else { j = flen - 2; } if (p[j] != 0xCC) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_TRAILER); return -1; } memcpy(to, p, (unsigned int)j); return j; } /* Translate between X931 hash ids and NIDs */ int RSA_X931_hash_id(int nid) { switch (nid) { case NID_sha1: return 0x33; case NID_sha256: return 0x34; case NID_sha384: return 0x36; case NID_sha512: return 0x35; } return -1; }
./openssl/crypto/rsa/rsa_asn1.c
/* * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/x509.h> #include <openssl/asn1t.h> #include "rsa_local.h" /* * Override the default free and new methods, * and calculate helper products for multi-prime * RSA keys. */ static int rsa_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_NEW_PRE) { *pval = (ASN1_VALUE *)RSA_new(); if (*pval != NULL) return 2; return 0; } else if (operation == ASN1_OP_FREE_PRE) { RSA_free((RSA *)*pval); *pval = NULL; return 2; } else if (operation == ASN1_OP_D2I_POST) { if (((RSA *)*pval)->version != RSA_ASN1_VERSION_MULTI) { /* not a multi-prime key, skip */ return 1; } return (ossl_rsa_multip_calc_product((RSA *)*pval) == 1) ? 2 : 0; } return 1; } /* Based on definitions in RFC 8017 appendix A.1.2 */ ASN1_SEQUENCE(RSA_PRIME_INFO) = { ASN1_SIMPLE(RSA_PRIME_INFO, r, CBIGNUM), ASN1_SIMPLE(RSA_PRIME_INFO, d, CBIGNUM), ASN1_SIMPLE(RSA_PRIME_INFO, t, CBIGNUM), } ASN1_SEQUENCE_END(RSA_PRIME_INFO) ASN1_SEQUENCE_cb(RSAPrivateKey, rsa_cb) = { ASN1_EMBED(RSA, version, INT32), ASN1_SIMPLE(RSA, n, BIGNUM), ASN1_SIMPLE(RSA, e, BIGNUM), ASN1_SIMPLE(RSA, d, CBIGNUM), ASN1_SIMPLE(RSA, p, CBIGNUM), ASN1_SIMPLE(RSA, q, CBIGNUM), ASN1_SIMPLE(RSA, dmp1, CBIGNUM), ASN1_SIMPLE(RSA, dmq1, CBIGNUM), ASN1_SIMPLE(RSA, iqmp, CBIGNUM), ASN1_SEQUENCE_OF_OPT(RSA, prime_infos, RSA_PRIME_INFO) } ASN1_SEQUENCE_END_cb(RSA, RSAPrivateKey) ASN1_SEQUENCE_cb(RSAPublicKey, rsa_cb) = { ASN1_SIMPLE(RSA, n, BIGNUM), ASN1_SIMPLE(RSA, e, BIGNUM), } ASN1_SEQUENCE_END_cb(RSA, RSAPublicKey) /* Free up maskHash */ static int rsa_pss_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_FREE_PRE) { RSA_PSS_PARAMS *pss = (RSA_PSS_PARAMS *)*pval; X509_ALGOR_free(pss->maskHash); } return 1; } ASN1_SEQUENCE_cb(RSA_PSS_PARAMS, rsa_pss_cb) = { ASN1_EXP_OPT(RSA_PSS_PARAMS, hashAlgorithm, X509_ALGOR,0), ASN1_EXP_OPT(RSA_PSS_PARAMS, maskGenAlgorithm, X509_ALGOR,1), ASN1_EXP_OPT(RSA_PSS_PARAMS, saltLength, ASN1_INTEGER,2), ASN1_EXP_OPT(RSA_PSS_PARAMS, trailerField, ASN1_INTEGER,3) } ASN1_SEQUENCE_END_cb(RSA_PSS_PARAMS, RSA_PSS_PARAMS) IMPLEMENT_ASN1_FUNCTIONS(RSA_PSS_PARAMS) IMPLEMENT_ASN1_DUP_FUNCTION(RSA_PSS_PARAMS) /* Free up maskHash */ static int rsa_oaep_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_FREE_PRE) { RSA_OAEP_PARAMS *oaep = (RSA_OAEP_PARAMS *)*pval; X509_ALGOR_free(oaep->maskHash); } return 1; } ASN1_SEQUENCE_cb(RSA_OAEP_PARAMS, rsa_oaep_cb) = { ASN1_EXP_OPT(RSA_OAEP_PARAMS, hashFunc, X509_ALGOR, 0), ASN1_EXP_OPT(RSA_OAEP_PARAMS, maskGenFunc, X509_ALGOR, 1), ASN1_EXP_OPT(RSA_OAEP_PARAMS, pSourceFunc, X509_ALGOR, 2), } ASN1_SEQUENCE_END_cb(RSA_OAEP_PARAMS, RSA_OAEP_PARAMS) IMPLEMENT_ASN1_FUNCTIONS(RSA_OAEP_PARAMS) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(RSA, RSAPrivateKey, RSAPrivateKey) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(RSA, RSAPublicKey, RSAPublicKey) RSA *RSAPublicKey_dup(const RSA *rsa) { return ASN1_item_dup(ASN1_ITEM_rptr(RSAPublicKey), rsa); } RSA *RSAPrivateKey_dup(const RSA *rsa) { return ASN1_item_dup(ASN1_ITEM_rptr(RSAPrivateKey), rsa); }
./openssl/crypto/rsa/rsa_prn.c
/* * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA 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/rsa.h> #include <openssl/evp.h> #ifndef OPENSSL_NO_STDIO int RSA_print_fp(FILE *fp, const RSA *x, int off) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = RSA_print(b, x, off); BIO_free(b); return ret; } #endif int RSA_print(BIO *bp, const RSA *x, int off) { EVP_PKEY *pk; int ret; pk = EVP_PKEY_new(); if (pk == NULL) return 0; ret = EVP_PKEY_set1_RSA(pk, (RSA *)x); if (ret) ret = EVP_PKEY_print_private(bp, pk, off, NULL); EVP_PKEY_free(pk); return ret; }
./openssl/crypto/rsa/rsa_gen.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 */ /* * NB: these functions have been "upgraded", the deprecated versions (which * are compatibility wrappers using these functions) are in rsa_depr.c. - * Geoff */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/self_test.h> #include "prov/providercommon.h" #include "rsa_local.h" static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg); static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb, int pairwise_test); /* * NB: this wrapper would normally be placed in rsa_lib.c and the static * implementation would probably be in rsa_eay.c. Nonetheless, is kept here * so that we don't introduce a new linker dependency. Eg. any application * that wasn't previously linking object code related to key-generation won't * have to now just because key-generation is part of RSA_METHOD. */ int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { if (rsa->meth->rsa_keygen != NULL) return rsa->meth->rsa_keygen(rsa, bits, e_value, cb); return RSA_generate_multi_prime_key(rsa, bits, RSA_DEFAULT_PRIME_NUM, e_value, cb); } int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb) { #ifndef FIPS_MODULE /* multi-prime is only supported with the builtin key generation */ if (rsa->meth->rsa_multi_prime_keygen != NULL) { return rsa->meth->rsa_multi_prime_keygen(rsa, bits, primes, e_value, cb); } else if (rsa->meth->rsa_keygen != NULL) { /* * However, if rsa->meth implements only rsa_keygen, then we * have to honour it in 2-prime case and assume that it wouldn't * know what to do with multi-prime key generated by builtin * subroutine... */ if (primes == 2) return rsa->meth->rsa_keygen(rsa, bits, e_value, cb); else return 0; } #endif /* FIPS_MODULE */ return rsa_keygen(rsa->libctx, rsa, bits, primes, e_value, cb, 0); } DEFINE_STACK_OF(BIGNUM) /* * Given input values, q, p, n, d and e, derive the exponents * and coefficients for each prime in this key, placing the result * on their respective exps and coeffs stacks */ #ifndef FIPS_MODULE int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes, BIGNUM *e_value, STACK_OF(BIGNUM) *factors, STACK_OF(BIGNUM) *exps, STACK_OF(BIGNUM) *coeffs) { STACK_OF(BIGNUM) *pplist = NULL, *pdlist = NULL; BIGNUM *factor = NULL, *newpp = NULL, *newpd = NULL; BIGNUM *dval = NULL, *newexp = NULL, *newcoeff = NULL; BIGNUM *p = NULL, *q = NULL; BIGNUM *dmp1 = NULL, *dmq1 = NULL, *iqmp = NULL; BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL; BN_CTX *ctx = NULL; BIGNUM *tmp = NULL; int i; int ret = 0; ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) goto err; BN_CTX_start(ctx); pplist = sk_BIGNUM_new_null(); if (pplist == NULL) goto err; pdlist = sk_BIGNUM_new_null(); if (pdlist == NULL) goto err; r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); if (r2 == NULL) goto err; BN_set_flags(r0, BN_FLG_CONSTTIME); BN_set_flags(r1, BN_FLG_CONSTTIME); BN_set_flags(r2, BN_FLG_CONSTTIME); if (BN_copy(r1, rsa->n) == NULL) goto err; p = sk_BIGNUM_value(factors, 0); q = sk_BIGNUM_value(factors, 1); /* Build list of partial products of primes */ for (i = 0; i < sk_BIGNUM_num(factors); i++) { switch (i) { case 0: /* our first prime, p */ if (!BN_sub(r2, p, BN_value_one())) goto err; BN_set_flags(r2, BN_FLG_CONSTTIME); if (BN_mod_inverse(r1, r2, rsa->e, ctx) == NULL) goto err; break; case 1: /* second prime q */ if (!BN_mul(r1, p, q, ctx)) goto err; tmp = BN_dup(r1); if (tmp == NULL) goto err; if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist))) goto err; break; default: factor = sk_BIGNUM_value(factors, i); /* all other primes */ if (!BN_mul(r1, r1, factor, ctx)) goto err; tmp = BN_dup(r1); if (tmp == NULL) goto err; if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist))) goto err; break; } } /* build list of relative d values */ /* p -1 */ if (!BN_sub(r1, p, BN_value_one())) goto err; if (!BN_sub(r2, q, BN_value_one())) goto err; if (!BN_mul(r0, r1, r2, ctx)) goto err; for (i = 2; i < sk_BIGNUM_num(factors); i++) { factor = sk_BIGNUM_value(factors, i); dval = BN_new(); if (dval == NULL) goto err; BN_set_flags(dval, BN_FLG_CONSTTIME); if (!BN_sub(dval, factor, BN_value_one())) goto err; if (!BN_mul(r0, r0, dval, ctx)) goto err; if (!sk_BIGNUM_insert(pdlist, dval, sk_BIGNUM_num(pdlist))) goto err; } /* Calculate dmp1, dmq1 and additional exponents */ dmp1 = BN_secure_new(); if (dmp1 == NULL) goto err; dmq1 = BN_secure_new(); if (dmq1 == NULL) goto err; if (!BN_mod(dmp1, rsa->d, r1, ctx)) goto err; if (!sk_BIGNUM_insert(exps, dmp1, sk_BIGNUM_num(exps))) goto err; dmp1 = NULL; if (!BN_mod(dmq1, rsa->d, r2, ctx)) goto err; if (!sk_BIGNUM_insert(exps, dmq1, sk_BIGNUM_num(exps))) goto err; dmq1 = NULL; for (i = 2; i < sk_BIGNUM_num(factors); i++) { newpd = sk_BIGNUM_value(pdlist, i - 2); newexp = BN_new(); if (newexp == NULL) goto err; if (!BN_mod(newexp, rsa->d, newpd, ctx)) { BN_free(newexp); goto err; } if (!sk_BIGNUM_insert(exps, newexp, sk_BIGNUM_num(exps))) goto err; } /* Calculate iqmp and additional coefficients */ iqmp = BN_new(); if (iqmp == NULL) goto err; if (BN_mod_inverse(iqmp, sk_BIGNUM_value(factors, 1), sk_BIGNUM_value(factors, 0), ctx) == NULL) goto err; if (!sk_BIGNUM_insert(coeffs, iqmp, sk_BIGNUM_num(coeffs))) goto err; iqmp = NULL; for (i = 2; i < sk_BIGNUM_num(factors); i++) { newpp = sk_BIGNUM_value(pplist, i - 2); newcoeff = BN_new(); if (newcoeff == NULL) goto err; if (BN_mod_inverse(newcoeff, newpp, sk_BIGNUM_value(factors, i), ctx) == NULL) { BN_free(newcoeff); goto err; } if (!sk_BIGNUM_insert(coeffs, newcoeff, sk_BIGNUM_num(coeffs))) goto err; } ret = 1; err: sk_BIGNUM_pop_free(pplist, BN_free); sk_BIGNUM_pop_free(pdlist, BN_free); BN_CTX_end(ctx); BN_CTX_free(ctx); BN_clear_free(dmp1); BN_clear_free(dmq1); BN_clear_free(iqmp); return ret; } static int rsa_multiprime_keygen(RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb) { BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *tmp, *tmp2, *prime; int n = 0, bitsr[RSA_MAX_PRIME_NUM], bitse = 0; int i = 0, quo = 0, rmd = 0, adj = 0, retries = 0; RSA_PRIME_INFO *pinfo = NULL; STACK_OF(RSA_PRIME_INFO) *prime_infos = NULL; STACK_OF(BIGNUM) *factors = NULL; STACK_OF(BIGNUM) *exps = NULL; STACK_OF(BIGNUM) *coeffs = NULL; BN_CTX *ctx = NULL; BN_ULONG bitst = 0; unsigned long error = 0; int ok = -1; if (bits < RSA_MIN_MODULUS_BITS) { ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } if (e_value == NULL) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_E_VALUE); return 0; } /* A bad value for e can cause infinite loops */ if (!ossl_rsa_check_public_exponent(e_value)) { ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE); return 0; } if (primes < RSA_DEFAULT_PRIME_NUM || primes > ossl_rsa_multip_cap(bits)) { ERR_raise(ERR_LIB_RSA, RSA_R_KEY_PRIME_NUM_INVALID); return 0; } factors = sk_BIGNUM_new_null(); if (factors == NULL) return 0; exps = sk_BIGNUM_new_null(); if (exps == NULL) goto err; coeffs = sk_BIGNUM_new_null(); if (coeffs == NULL) goto err; ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); if (r2 == NULL) goto err; /* divide bits into 'primes' pieces evenly */ quo = bits / primes; rmd = bits % primes; for (i = 0; i < primes; i++) bitsr[i] = (i < rmd) ? quo + 1 : quo; rsa->dirty_cnt++; /* We need the RSA components non-NULL */ if (!rsa->n && ((rsa->n = BN_new()) == NULL)) goto err; if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->d, BN_FLG_CONSTTIME); if (!rsa->e && ((rsa->e = BN_new()) == NULL)) goto err; if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->p, BN_FLG_CONSTTIME); if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->q, BN_FLG_CONSTTIME); /* initialize multi-prime components */ if (primes > RSA_DEFAULT_PRIME_NUM) { rsa->version = RSA_ASN1_VERSION_MULTI; prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2); if (prime_infos == NULL) goto err; if (rsa->prime_infos != NULL) { /* could this happen? */ sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos, ossl_rsa_multip_info_free); } rsa->prime_infos = prime_infos; /* prime_info from 2 to |primes| -1 */ for (i = 2; i < primes; i++) { pinfo = ossl_rsa_multip_info_new(); if (pinfo == NULL) goto err; (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo); } } if (BN_copy(rsa->e, e_value) == NULL) goto err; /* generate p, q and other primes (if any) */ for (i = 0; i < primes; i++) { adj = 0; retries = 0; if (i == 0) { prime = rsa->p; } else if (i == 1) { prime = rsa->q; } else { pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); prime = pinfo->r; } BN_set_flags(prime, BN_FLG_CONSTTIME); for (;;) { redo: if (!BN_generate_prime_ex2(prime, bitsr[i] + adj, 0, NULL, NULL, cb, ctx)) goto err; /* * prime should not be equal to p, q, r_3... * (those primes prior to this one) */ { int j; for (j = 0; j < i; j++) { BIGNUM *prev_prime; if (j == 0) prev_prime = rsa->p; else if (j == 1) prev_prime = rsa->q; else prev_prime = sk_RSA_PRIME_INFO_value(prime_infos, j - 2)->r; if (!BN_cmp(prime, prev_prime)) { goto redo; } } } if (!BN_sub(r2, prime, BN_value_one())) goto err; ERR_set_mark(); BN_set_flags(r2, BN_FLG_CONSTTIME); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } bitse += bitsr[i]; /* calculate n immediately to see if it's sufficient */ if (i == 1) { /* we get at least 2 primes */ if (!BN_mul(r1, rsa->p, rsa->q, ctx)) goto err; } else if (i != 0) { /* modulus n = p * q * r_3 * r_4 ... */ if (!BN_mul(r1, rsa->n, prime, ctx)) goto err; } else { /* i == 0, do nothing */ if (!BN_GENCB_call(cb, 3, i)) goto err; tmp = BN_dup(prime); if (tmp == NULL) goto err; if (!sk_BIGNUM_insert(factors, tmp, sk_BIGNUM_num(factors))) goto err; continue; } /* * if |r1|, product of factors so far, is not as long as expected * (by checking the first 4 bits are less than 0x9 or greater than * 0xF). If so, re-generate the last prime. * * NOTE: This actually can't happen in two-prime case, because of * the way factors are generated. * * Besides, another consideration is, for multi-prime case, even the * length modulus is as long as expected, the modulus could start at * 0x8, which could be utilized to distinguish a multi-prime private * key by using the modulus in a certificate. This is also covered * by checking the length should not be less than 0x9. */ if (!BN_rshift(r2, r1, bitse - 4)) goto err; bitst = BN_get_word(r2); if (bitst < 0x9 || bitst > 0xF) { /* * For keys with more than 4 primes, we attempt longer factor to * meet length requirement. * * Otherwise, we just re-generate the prime with the same length. * * This strategy has the following goals: * * 1. 1024-bit factors are efficient when using 3072 and 4096-bit key * 2. stay the same logic with normal 2-prime key */ bitse -= bitsr[i]; if (!BN_GENCB_call(cb, 2, n++)) goto err; if (primes > 4) { if (bitst < 0x9) adj++; else adj--; } else if (retries == 4) { /* * re-generate all primes from scratch, mainly used * in 4 prime case to avoid long loop. Max retry times * is set to 4. */ i = -1; bitse = 0; sk_BIGNUM_pop_free(factors, BN_clear_free); factors = sk_BIGNUM_new_null(); if (factors == NULL) goto err; continue; } retries++; goto redo; } /* save product of primes for further use, for multi-prime only */ if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL) goto err; if (BN_copy(rsa->n, r1) == NULL) goto err; if (!BN_GENCB_call(cb, 3, i)) goto err; tmp = BN_dup(prime); if (tmp == NULL) goto err; if (!sk_BIGNUM_insert(factors, tmp, sk_BIGNUM_num(factors))) goto err; } if (BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; /* mirror this in our factor stack */ if (!sk_BIGNUM_insert(factors, sk_BIGNUM_delete(factors, 0), 1)) goto err; } /* calculate d */ /* p - 1 */ if (!BN_sub(r1, rsa->p, BN_value_one())) goto err; /* q - 1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; /* (p - 1)(q - 1) */ if (!BN_mul(r0, r1, r2, ctx)) goto err; /* multi-prime */ for (i = 2; i < primes; i++) { pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); /* save r_i - 1 to pinfo->d temporarily */ if (!BN_sub(pinfo->d, pinfo->r, BN_value_one())) goto err; if (!BN_mul(r0, r0, pinfo->d, ctx)) goto err; } BN_set_flags(r0, BN_FLG_CONSTTIME); if (BN_mod_inverse(rsa->d, rsa->e, r0, ctx) == NULL) { goto err; /* d */ } /* derive any missing exponents and coefficients */ if (!ossl_rsa_multiprime_derive(rsa, bits, primes, e_value, factors, exps, coeffs)) goto err; /* * first 2 factors/exps are already tracked in p/q/dmq1/dmp1 * and the first coeff is in iqmp, so pop those off the stack * Note, the first 2 factors/exponents are already tracked by p and q * assign dmp1/dmq1 and iqmp * the remaining pinfo values are separately allocated, so copy and delete * those */ BN_clear_free(sk_BIGNUM_delete(factors, 0)); BN_clear_free(sk_BIGNUM_delete(factors, 0)); rsa->dmp1 = sk_BIGNUM_delete(exps, 0); rsa->dmq1 = sk_BIGNUM_delete(exps, 0); rsa->iqmp = sk_BIGNUM_delete(coeffs, 0); for (i = 2; i < primes; i++) { pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); tmp = sk_BIGNUM_delete(factors, 0); BN_copy(pinfo->r, tmp); BN_clear_free(tmp); tmp = sk_BIGNUM_delete(exps, 0); tmp2 = BN_copy(pinfo->d, tmp); BN_clear_free(tmp); if (tmp2 == NULL) goto err; tmp = sk_BIGNUM_delete(coeffs, 0); tmp2 = BN_copy(pinfo->t, tmp); BN_clear_free(tmp); if (tmp2 == NULL) goto err; } ok = 1; err: sk_BIGNUM_free(factors); sk_BIGNUM_free(exps); sk_BIGNUM_free(coeffs); if (ok == -1) { ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB); ok = 0; } BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; } #endif /* FIPS_MODULE */ static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb, int pairwise_test) { int ok = 0; #ifdef FIPS_MODULE ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb); pairwise_test = 1; /* FIPS MODE needs to always run the pairwise test */ #else /* * Only multi-prime keys or insecure keys with a small key length or a * public exponent <= 2^16 will use the older rsa_multiprime_keygen(). */ if (primes == 2 && bits >= 2048 && (e_value == NULL || BN_num_bits(e_value) > 16)) ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb); else ok = rsa_multiprime_keygen(rsa, bits, primes, e_value, cb); #endif /* FIPS_MODULE */ if (pairwise_test && ok > 0) { OSSL_CALLBACK *stcb = NULL; void *stcbarg = NULL; OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg); ok = rsa_keygen_pairwise_test(rsa, stcb, stcbarg); if (!ok) { ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT); /* Clear intermediate results */ BN_clear_free(rsa->d); BN_clear_free(rsa->p); BN_clear_free(rsa->q); BN_clear_free(rsa->dmp1); BN_clear_free(rsa->dmq1); BN_clear_free(rsa->iqmp); rsa->d = NULL; rsa->p = NULL; rsa->q = NULL; rsa->dmp1 = NULL; rsa->dmq1 = NULL; rsa->iqmp = NULL; } } return ok; } /* * For RSA key generation it is not known whether the key pair will be used * for key transport or signatures. FIPS 140-2 IG 9.9 states that in this case * either a signature verification OR an encryption operation may be used to * perform the pairwise consistency check. The simpler encrypt/decrypt operation * has been chosen for this case. */ static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg) { int ret = 0; unsigned int ciphertxt_len; unsigned char *ciphertxt = NULL; const unsigned char plaintxt[16] = {0}; unsigned char *decoded = NULL; unsigned int decoded_len; unsigned int plaintxt_len = (unsigned int)sizeof(plaintxt_len); int padding = RSA_PKCS1_PADDING; OSSL_SELF_TEST *st = NULL; st = OSSL_SELF_TEST_new(cb, cbarg); if (st == NULL) goto err; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT, OSSL_SELF_TEST_DESC_PCT_RSA_PKCS1); ciphertxt_len = RSA_size(rsa); /* * RSA_private_encrypt() and RSA_private_decrypt() requires the 'to' * parameter to be a maximum of RSA_size() - allocate space for both. */ ciphertxt = OPENSSL_zalloc(ciphertxt_len * 2); if (ciphertxt == NULL) goto err; decoded = ciphertxt + ciphertxt_len; ciphertxt_len = RSA_public_encrypt(plaintxt_len, plaintxt, ciphertxt, rsa, padding); if (ciphertxt_len <= 0) goto err; if (ciphertxt_len == plaintxt_len && memcmp(ciphertxt, plaintxt, plaintxt_len) == 0) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, ciphertxt); decoded_len = RSA_private_decrypt(ciphertxt_len, ciphertxt, decoded, rsa, padding); if (decoded_len != plaintxt_len || memcmp(decoded, plaintxt, decoded_len) != 0) goto err; ret = 1; err: OSSL_SELF_TEST_onend(st, ret); OSSL_SELF_TEST_free(st); OPENSSL_free(ciphertxt); return ret; }
./openssl/crypto/rsa/rsa_backend.c
/* * Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <string.h> #include <openssl/core_names.h> #include <openssl/params.h> #include <openssl/err.h> #include <openssl/evp.h> #ifndef FIPS_MODULE # include <openssl/x509.h> # include "crypto/asn1.h" #endif #include "internal/sizes.h" #include "internal/param_build_set.h" #include "crypto/rsa.h" #include "rsa_local.h" /* * The intention with the "backend" source file is to offer backend support * for legacy backends (EVP_PKEY_ASN1_METHOD and EVP_PKEY_METHOD) and provider * implementations alike. */ DEFINE_STACK_OF(BIGNUM) static int collect_numbers(STACK_OF(BIGNUM) *numbers, const OSSL_PARAM params[], const char *names[]) { const OSSL_PARAM *p = NULL; int i; if (numbers == NULL) return 0; for (i = 0; names[i] != NULL; i++) { p = OSSL_PARAM_locate_const(params, names[i]); if (p != NULL) { BIGNUM *tmp = NULL; if (!OSSL_PARAM_get_BN(p, &tmp)) return 0; if (sk_BIGNUM_push(numbers, tmp) == 0) { BN_clear_free(tmp); return 0; } } } return 1; } int ossl_rsa_fromdata(RSA *rsa, const OSSL_PARAM params[], int include_private) { const OSSL_PARAM *param_n, *param_e, *param_d = NULL; const OSSL_PARAM *param_p, *param_q = NULL; const OSSL_PARAM *param_derive = NULL; BIGNUM *p = NULL, *q = NULL, *n = NULL, *e = NULL, *d = NULL; STACK_OF(BIGNUM) *factors = NULL, *exps = NULL, *coeffs = NULL; int is_private = 0; int derive_from_pq = 0; BN_CTX *ctx = NULL; if (rsa == NULL) return 0; param_n = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_N); param_e = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_E); if ((param_n == NULL || !OSSL_PARAM_get_BN(param_n, &n)) || (param_e == NULL || !OSSL_PARAM_get_BN(param_e, &e))) { ERR_raise(ERR_LIB_RSA, ERR_R_PASSED_NULL_PARAMETER); goto err; } if (include_private) { param_derive = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_DERIVE_FROM_PQ); if ((param_derive != NULL) && !OSSL_PARAM_get_int(param_derive, &derive_from_pq)) goto err; param_d = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_D); if (param_d != NULL && !OSSL_PARAM_get_BN(param_d, &d)) { ERR_raise(ERR_LIB_RSA, ERR_R_PASSED_NULL_PARAMETER); goto err; } if (derive_from_pq) { ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) goto err; /* we need at minimum p, q */ param_p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_FACTOR1); param_q = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_FACTOR2); if ((param_p == NULL || !OSSL_PARAM_get_BN(param_p, &p)) || (param_q == NULL || !OSSL_PARAM_get_BN(param_q, &q))) { ERR_raise(ERR_LIB_RSA, ERR_R_PASSED_NULL_PARAMETER); goto err; } } } is_private = (d != NULL); if (!RSA_set0_key(rsa, n, e, d)) goto err; n = e = d = NULL; if (is_private) { if (!collect_numbers(factors = sk_BIGNUM_new_null(), params, ossl_rsa_mp_factor_names) || !collect_numbers(exps = sk_BIGNUM_new_null(), params, ossl_rsa_mp_exp_names) || !collect_numbers(coeffs = sk_BIGNUM_new_null(), params, ossl_rsa_mp_coeff_names)) goto err; if (derive_from_pq && sk_BIGNUM_num(exps) == 0 && sk_BIGNUM_num(coeffs) == 0) { /* * If we want to use crt to derive our exponents/coefficients, we * need to have at least 2 factors */ if (sk_BIGNUM_num(factors) < 2) { ERR_raise(ERR_LIB_RSA, ERR_R_PASSED_NULL_PARAMETER); goto err; } /* * if we have more than two factors, n and d must also have * been provided */ if (sk_BIGNUM_num(factors) > 2 && (param_n == NULL || param_d == NULL)) { ERR_raise(ERR_LIB_RSA, ERR_R_PASSED_NULL_PARAMETER); goto err; } /* build our exponents and coefficients here */ if (sk_BIGNUM_num(factors) == 2) { /* for 2 factors we can use the sp800 functions to do this */ if (!RSA_set0_factors(rsa, sk_BIGNUM_value(factors, 0), sk_BIGNUM_value(factors, 1))) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } /* * once consumed by RSA_set0_factors, pop those off the stack * so we don't free them below */ sk_BIGNUM_pop(factors); sk_BIGNUM_pop(factors); /* * Note: Because we only have 2 factors here, there will be no * additional pinfo fields to hold additional factors, and * since we set our key and 2 factors above we can skip * the call to ossl_rsa_set0_all_params */ if (!ossl_rsa_sp800_56b_derive_params_from_pq(rsa, RSA_bits(rsa), NULL, ctx)) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } } else { #ifndef FIPS_MODULE /* * in the multiprime case we have to generate exps/coeffs here * for each additional prime */ if (!ossl_rsa_multiprime_derive(rsa, RSA_bits(rsa), sk_BIGNUM_num(factors), rsa->e, factors, exps, coeffs)) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } /* * Now we should have all our factors, exponents and * coefficients */ if (!ossl_rsa_set0_all_params(rsa, factors, exps, coeffs)) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } #else /* multiprime case is disallowed in FIPS mode, raise an error */ ERR_raise(ERR_LIB_RSA, ERR_R_UNSUPPORTED); goto err; #endif } } else { /* * It's ok if this private key just has n, e and d * but only if we're not using derive_from_pq */ if (sk_BIGNUM_num(factors) != 0 && !ossl_rsa_set0_all_params(rsa, factors, exps, coeffs)) goto err; } /* sanity check to ensure we used everything in our stacks */ if (sk_BIGNUM_num(factors) != 0 || sk_BIGNUM_num(exps) != 0 || sk_BIGNUM_num(coeffs) != 0) { ERR_raise_data(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR, "There are %d, %d, %d elements left on our factors, exps, coeffs stacks\n", sk_BIGNUM_num(factors), sk_BIGNUM_num(exps), sk_BIGNUM_num(coeffs)); goto err; } } BN_clear_free(p); BN_clear_free(q); sk_BIGNUM_free(factors); sk_BIGNUM_free(exps); sk_BIGNUM_free(coeffs); BN_CTX_free(ctx); return 1; err: BN_free(n); BN_free(e); BN_free(d); sk_BIGNUM_pop_free(factors, BN_clear_free); sk_BIGNUM_pop_free(exps, BN_clear_free); sk_BIGNUM_pop_free(coeffs, BN_clear_free); BN_CTX_free(ctx); return 0; } DEFINE_SPECIAL_STACK_OF_CONST(BIGNUM_const, BIGNUM) int ossl_rsa_todata(RSA *rsa, OSSL_PARAM_BLD *bld, OSSL_PARAM params[], int include_private) { int ret = 0; const BIGNUM *rsa_d = NULL, *rsa_n = NULL, *rsa_e = NULL; STACK_OF(BIGNUM_const) *factors = sk_BIGNUM_const_new_null(); STACK_OF(BIGNUM_const) *exps = sk_BIGNUM_const_new_null(); STACK_OF(BIGNUM_const) *coeffs = sk_BIGNUM_const_new_null(); if (rsa == NULL || factors == NULL || exps == NULL || coeffs == NULL) goto err; RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); ossl_rsa_get0_all_params(rsa, factors, exps, coeffs); if (!ossl_param_build_set_bn(bld, params, OSSL_PKEY_PARAM_RSA_N, rsa_n) || !ossl_param_build_set_bn(bld, params, OSSL_PKEY_PARAM_RSA_E, rsa_e)) goto err; /* Check private key data integrity */ if (include_private && rsa_d != NULL) { if (!ossl_param_build_set_bn(bld, params, OSSL_PKEY_PARAM_RSA_D, rsa_d) || !ossl_param_build_set_multi_key_bn(bld, params, ossl_rsa_mp_factor_names, factors) || !ossl_param_build_set_multi_key_bn(bld, params, ossl_rsa_mp_exp_names, exps) || !ossl_param_build_set_multi_key_bn(bld, params, ossl_rsa_mp_coeff_names, coeffs)) goto err; } #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) /* The acvp test results are not meant for export so check for bld == NULL */ if (bld == NULL) ossl_rsa_acvp_test_get_params(rsa, params); #endif ret = 1; err: sk_BIGNUM_const_free(factors); sk_BIGNUM_const_free(exps); sk_BIGNUM_const_free(coeffs); return ret; } int ossl_rsa_pss_params_30_todata(const RSA_PSS_PARAMS_30 *pss, OSSL_PARAM_BLD *bld, OSSL_PARAM params[]) { if (!ossl_rsa_pss_params_30_is_unrestricted(pss)) { int hashalg_nid = ossl_rsa_pss_params_30_hashalg(pss); int maskgenalg_nid = ossl_rsa_pss_params_30_maskgenalg(pss); int maskgenhashalg_nid = ossl_rsa_pss_params_30_maskgenhashalg(pss); int saltlen = ossl_rsa_pss_params_30_saltlen(pss); int default_hashalg_nid = ossl_rsa_pss_params_30_hashalg(NULL); int default_maskgenalg_nid = ossl_rsa_pss_params_30_maskgenalg(NULL); int default_maskgenhashalg_nid = ossl_rsa_pss_params_30_maskgenhashalg(NULL); const char *mdname = (hashalg_nid == default_hashalg_nid ? NULL : ossl_rsa_oaeppss_nid2name(hashalg_nid)); const char *mgfname = (maskgenalg_nid == default_maskgenalg_nid ? NULL : ossl_rsa_oaeppss_nid2name(maskgenalg_nid)); const char *mgf1mdname = (maskgenhashalg_nid == default_maskgenhashalg_nid ? NULL : ossl_rsa_oaeppss_nid2name(maskgenhashalg_nid)); const char *key_md = OSSL_PKEY_PARAM_RSA_DIGEST; const char *key_mgf = OSSL_PKEY_PARAM_RSA_MASKGENFUNC; const char *key_mgf1_md = OSSL_PKEY_PARAM_RSA_MGF1_DIGEST; const char *key_saltlen = OSSL_PKEY_PARAM_RSA_PSS_SALTLEN; /* * To ensure that the key isn't seen as unrestricted by the recipient, * we make sure that at least one PSS-related parameter is passed, even * if it has a default value; saltlen. */ if ((mdname != NULL && !ossl_param_build_set_utf8_string(bld, params, key_md, mdname)) || (mgfname != NULL && !ossl_param_build_set_utf8_string(bld, params, key_mgf, mgfname)) || (mgf1mdname != NULL && !ossl_param_build_set_utf8_string(bld, params, key_mgf1_md, mgf1mdname)) || (!ossl_param_build_set_int(bld, params, key_saltlen, saltlen))) return 0; } return 1; } int ossl_rsa_pss_params_30_fromdata(RSA_PSS_PARAMS_30 *pss_params, int *defaults_set, const OSSL_PARAM params[], OSSL_LIB_CTX *libctx) { const OSSL_PARAM *param_md, *param_mgf, *param_mgf1md, *param_saltlen; const OSSL_PARAM *param_propq; const char *propq = NULL; EVP_MD *md = NULL, *mgf1md = NULL; int saltlen; int ret = 0; if (pss_params == NULL) return 0; param_propq = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_DIGEST_PROPS); param_md = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_DIGEST); param_mgf = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_MASKGENFUNC); param_mgf1md = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_MGF1_DIGEST); param_saltlen = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_PSS_SALTLEN); if (param_propq != NULL) { if (param_propq->data_type == OSSL_PARAM_UTF8_STRING) propq = param_propq->data; } /* * If we get any of the parameters, we know we have at least some * restrictions, so we start by setting default values, and let each * parameter override their specific restriction data. */ if (!*defaults_set && (param_md != NULL || param_mgf != NULL || param_mgf1md != NULL || param_saltlen != NULL)) { if (!ossl_rsa_pss_params_30_set_defaults(pss_params)) return 0; *defaults_set = 1; } if (param_mgf != NULL) { int default_maskgenalg_nid = ossl_rsa_pss_params_30_maskgenalg(NULL); const char *mgfname = NULL; if (param_mgf->data_type == OSSL_PARAM_UTF8_STRING) mgfname = param_mgf->data; else if (!OSSL_PARAM_get_utf8_ptr(param_mgf, &mgfname)) return 0; if (OPENSSL_strcasecmp(param_mgf->data, ossl_rsa_mgf_nid2name(default_maskgenalg_nid)) != 0) return 0; } /* * We're only interested in the NIDs that correspond to the MDs, so the * exact propquery is unimportant in the EVP_MD_fetch() calls below. */ if (param_md != NULL) { const char *mdname = NULL; if (param_md->data_type == OSSL_PARAM_UTF8_STRING) mdname = param_md->data; else if (!OSSL_PARAM_get_utf8_ptr(param_mgf, &mdname)) goto err; if ((md = EVP_MD_fetch(libctx, mdname, propq)) == NULL || !ossl_rsa_pss_params_30_set_hashalg(pss_params, ossl_rsa_oaeppss_md2nid(md))) goto err; } if (param_mgf1md != NULL) { const char *mgf1mdname = NULL; if (param_mgf1md->data_type == OSSL_PARAM_UTF8_STRING) mgf1mdname = param_mgf1md->data; else if (!OSSL_PARAM_get_utf8_ptr(param_mgf, &mgf1mdname)) goto err; if ((mgf1md = EVP_MD_fetch(libctx, mgf1mdname, propq)) == NULL || !ossl_rsa_pss_params_30_set_maskgenhashalg( pss_params, ossl_rsa_oaeppss_md2nid(mgf1md))) goto err; } if (param_saltlen != NULL) { if (!OSSL_PARAM_get_int(param_saltlen, &saltlen) || !ossl_rsa_pss_params_30_set_saltlen(pss_params, saltlen)) goto err; } ret = 1; err: EVP_MD_free(md); EVP_MD_free(mgf1md); return ret; } int ossl_rsa_is_foreign(const RSA *rsa) { #ifndef FIPS_MODULE if (rsa->engine != NULL || RSA_get_method(rsa) != RSA_PKCS1_OpenSSL()) return 1; #endif return 0; } static ossl_inline int rsa_bn_dup_check(BIGNUM **out, const BIGNUM *f) { if (f != NULL && (*out = BN_dup(f)) == NULL) return 0; return 1; } RSA *ossl_rsa_dup(const RSA *rsa, int selection) { RSA *dupkey = NULL; #ifndef FIPS_MODULE int pnum, i; #endif /* Do not try to duplicate foreign RSA keys */ if (ossl_rsa_is_foreign(rsa)) return NULL; if ((dupkey = ossl_rsa_new_with_ctx(rsa->libctx)) == NULL) return NULL; /* public key */ if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) { if (!rsa_bn_dup_check(&dupkey->n, rsa->n)) goto err; if (!rsa_bn_dup_check(&dupkey->e, rsa->e)) goto err; } if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) { /* private key */ if (!rsa_bn_dup_check(&dupkey->d, rsa->d)) goto err; /* factors and crt params */ if (!rsa_bn_dup_check(&dupkey->p, rsa->p)) goto err; if (!rsa_bn_dup_check(&dupkey->q, rsa->q)) goto err; if (!rsa_bn_dup_check(&dupkey->dmp1, rsa->dmp1)) goto err; if (!rsa_bn_dup_check(&dupkey->dmq1, rsa->dmq1)) goto err; if (!rsa_bn_dup_check(&dupkey->iqmp, rsa->iqmp)) goto err; } dupkey->version = rsa->version; dupkey->flags = rsa->flags; /* we always copy the PSS parameters regardless of selection */ dupkey->pss_params = rsa->pss_params; #ifndef FIPS_MODULE /* multiprime */ if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0 && (pnum = sk_RSA_PRIME_INFO_num(rsa->prime_infos)) > 0) { dupkey->prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, pnum); if (dupkey->prime_infos == NULL) goto err; for (i = 0; i < pnum; i++) { const RSA_PRIME_INFO *pinfo = NULL; RSA_PRIME_INFO *duppinfo = NULL; if ((duppinfo = OPENSSL_zalloc(sizeof(*duppinfo))) == NULL) goto err; /* push first so cleanup in error case works */ (void)sk_RSA_PRIME_INFO_push(dupkey->prime_infos, duppinfo); pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i); if (!rsa_bn_dup_check(&duppinfo->r, pinfo->r)) goto err; if (!rsa_bn_dup_check(&duppinfo->d, pinfo->d)) goto err; if (!rsa_bn_dup_check(&duppinfo->t, pinfo->t)) goto err; } if (!ossl_rsa_multip_calc_product(dupkey)) goto err; } if (rsa->pss != NULL) { dupkey->pss = RSA_PSS_PARAMS_dup(rsa->pss); if (rsa->pss->maskGenAlgorithm != NULL && dupkey->pss->maskGenAlgorithm == NULL) { dupkey->pss->maskHash = ossl_x509_algor_mgf1_decode(rsa->pss->maskGenAlgorithm); if (dupkey->pss->maskHash == NULL) goto err; } } if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_RSA, &dupkey->ex_data, &rsa->ex_data)) goto err; #endif return dupkey; err: RSA_free(dupkey); return NULL; } #ifndef FIPS_MODULE RSA_PSS_PARAMS *ossl_rsa_pss_decode(const X509_ALGOR *alg) { RSA_PSS_PARAMS *pss; pss = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_PSS_PARAMS), alg->parameter); if (pss == NULL) return NULL; if (pss->maskGenAlgorithm != NULL) { pss->maskHash = ossl_x509_algor_mgf1_decode(pss->maskGenAlgorithm); if (pss->maskHash == NULL) { RSA_PSS_PARAMS_free(pss); return NULL; } } return pss; } static int ossl_rsa_sync_to_pss_params_30(RSA *rsa) { const RSA_PSS_PARAMS *legacy_pss = NULL; RSA_PSS_PARAMS_30 *pss = NULL; if (rsa != NULL && (legacy_pss = RSA_get0_pss_params(rsa)) != NULL && (pss = ossl_rsa_get0_pss_params_30(rsa)) != NULL) { const EVP_MD *md = NULL, *mgf1md = NULL; int md_nid, mgf1md_nid, saltlen, trailerField; RSA_PSS_PARAMS_30 pss_params; /* * We don't care about the validity of the fields here, we just * want to synchronise values. Verifying here makes it impossible * to even read a key with invalid values, making it hard to test * a bad situation. * * Other routines use ossl_rsa_pss_get_param(), so the values will * be checked, eventually. */ if (!ossl_rsa_pss_get_param_unverified(legacy_pss, &md, &mgf1md, &saltlen, &trailerField)) return 0; md_nid = EVP_MD_get_type(md); mgf1md_nid = EVP_MD_get_type(mgf1md); if (!ossl_rsa_pss_params_30_set_defaults(&pss_params) || !ossl_rsa_pss_params_30_set_hashalg(&pss_params, md_nid) || !ossl_rsa_pss_params_30_set_maskgenhashalg(&pss_params, mgf1md_nid) || !ossl_rsa_pss_params_30_set_saltlen(&pss_params, saltlen) || !ossl_rsa_pss_params_30_set_trailerfield(&pss_params, trailerField)) return 0; *pss = pss_params; } return 1; } int ossl_rsa_pss_get_param_unverified(const RSA_PSS_PARAMS *pss, const EVP_MD **pmd, const EVP_MD **pmgf1md, int *psaltlen, int *ptrailerField) { RSA_PSS_PARAMS_30 pss_params; /* Get the defaults from the ONE place */ (void)ossl_rsa_pss_params_30_set_defaults(&pss_params); if (pss == NULL) return 0; *pmd = ossl_x509_algor_get_md(pss->hashAlgorithm); if (*pmd == NULL) return 0; *pmgf1md = ossl_x509_algor_get_md(pss->maskHash); if (*pmgf1md == NULL) return 0; if (pss->saltLength) *psaltlen = ASN1_INTEGER_get(pss->saltLength); else *psaltlen = ossl_rsa_pss_params_30_saltlen(&pss_params); if (pss->trailerField) *ptrailerField = ASN1_INTEGER_get(pss->trailerField); else *ptrailerField = ossl_rsa_pss_params_30_trailerfield(&pss_params); return 1; } int ossl_rsa_param_decode(RSA *rsa, const X509_ALGOR *alg) { RSA_PSS_PARAMS *pss; const ASN1_OBJECT *algoid; const void *algp; int algptype; X509_ALGOR_get0(&algoid, &algptype, &algp, alg); if (OBJ_obj2nid(algoid) != EVP_PKEY_RSA_PSS) return 1; if (algptype == V_ASN1_UNDEF) return 1; if (algptype != V_ASN1_SEQUENCE) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PSS_PARAMETERS); return 0; } if ((pss = ossl_rsa_pss_decode(alg)) == NULL || !ossl_rsa_set0_pss_params(rsa, pss)) { RSA_PSS_PARAMS_free(pss); return 0; } if (!ossl_rsa_sync_to_pss_params_30(rsa)) return 0; return 1; } RSA *ossl_rsa_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *libctx, const char *propq) { const unsigned char *p; RSA *rsa; int pklen; const X509_ALGOR *alg; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &alg, p8inf)) return 0; rsa = d2i_RSAPrivateKey(NULL, &p, pklen); if (rsa == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_RSA_LIB); return NULL; } if (!ossl_rsa_param_decode(rsa, alg)) { RSA_free(rsa); return NULL; } RSA_clear_flags(rsa, RSA_FLAG_TYPE_MASK); switch (OBJ_obj2nid(alg->algorithm)) { case EVP_PKEY_RSA: RSA_set_flags(rsa, RSA_FLAG_TYPE_RSA); break; case EVP_PKEY_RSA_PSS: RSA_set_flags(rsa, RSA_FLAG_TYPE_RSASSAPSS); break; default: /* Leave the type bits zero */ break; } return rsa; } #endif
./openssl/crypto/rsa/rsa_mp.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 BaishanCloud. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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 <openssl/err.h> #include "rsa_local.h" void ossl_rsa_multip_info_free_ex(RSA_PRIME_INFO *pinfo) { /* free pp and pinfo only */ BN_clear_free(pinfo->pp); OPENSSL_free(pinfo); } void ossl_rsa_multip_info_free(RSA_PRIME_INFO *pinfo) { /* free an RSA_PRIME_INFO structure */ BN_clear_free(pinfo->r); BN_clear_free(pinfo->d); BN_clear_free(pinfo->t); ossl_rsa_multip_info_free_ex(pinfo); } RSA_PRIME_INFO *ossl_rsa_multip_info_new(void) { RSA_PRIME_INFO *pinfo; /* create an RSA_PRIME_INFO structure */ if ((pinfo = OPENSSL_zalloc(sizeof(RSA_PRIME_INFO))) == NULL) return NULL; if ((pinfo->r = BN_secure_new()) == NULL) goto err; if ((pinfo->d = BN_secure_new()) == NULL) goto err; if ((pinfo->t = BN_secure_new()) == NULL) goto err; if ((pinfo->pp = BN_secure_new()) == NULL) goto err; return pinfo; err: BN_free(pinfo->r); BN_free(pinfo->d); BN_free(pinfo->t); BN_free(pinfo->pp); OPENSSL_free(pinfo); return NULL; } /* Refill products of primes */ int ossl_rsa_multip_calc_product(RSA *rsa) { RSA_PRIME_INFO *pinfo; BIGNUM *p1 = NULL, *p2 = NULL; BN_CTX *ctx = NULL; int i, rv = 0, ex_primes; if ((ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos)) <= 0) { /* invalid */ goto err; } if ((ctx = BN_CTX_new()) == NULL) goto err; /* calculate pinfo->pp = p * q for first 'extra' prime */ p1 = rsa->p; p2 = rsa->q; for (i = 0; i < ex_primes; i++) { pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i); if (pinfo->pp == NULL) { pinfo->pp = BN_secure_new(); if (pinfo->pp == NULL) goto err; } if (!BN_mul(pinfo->pp, p1, p2, ctx)) goto err; /* save previous one */ p1 = pinfo->pp; p2 = pinfo->r; } rv = 1; err: BN_CTX_free(ctx); return rv; } int ossl_rsa_multip_cap(int bits) { int cap = 5; if (bits < 1024) cap = 2; else if (bits < 4096) cap = 3; else if (bits < 8192) cap = 4; if (cap > RSA_MAX_PRIME_NUM) cap = RSA_MAX_PRIME_NUM; return cap; }
./openssl/crypto/rsa/rsa_meth.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <string.h> #include "rsa_local.h" #include <openssl/err.h> RSA_METHOD *RSA_meth_new(const char *name, int flags) { RSA_METHOD *meth = OPENSSL_zalloc(sizeof(*meth)); if (meth != NULL) { meth->flags = flags; meth->name = OPENSSL_strdup(name); if (meth->name != NULL) return meth; OPENSSL_free(meth); } return NULL; } void RSA_meth_free(RSA_METHOD *meth) { if (meth != NULL) { OPENSSL_free(meth->name); OPENSSL_free(meth); } } RSA_METHOD *RSA_meth_dup(const RSA_METHOD *meth) { RSA_METHOD *ret = OPENSSL_malloc(sizeof(*ret)); if (ret != NULL) { memcpy(ret, meth, sizeof(*meth)); ret->name = OPENSSL_strdup(meth->name); if (ret->name != NULL) return ret; OPENSSL_free(ret); } return NULL; } const char *RSA_meth_get0_name(const RSA_METHOD *meth) { return meth->name; } int RSA_meth_set1_name(RSA_METHOD *meth, const char *name) { char *tmpname = OPENSSL_strdup(name); if (tmpname == NULL) return 0; OPENSSL_free(meth->name); meth->name = tmpname; return 1; } int RSA_meth_get_flags(const RSA_METHOD *meth) { return meth->flags; } int RSA_meth_set_flags(RSA_METHOD *meth, int flags) { meth->flags = flags; return 1; } void *RSA_meth_get0_app_data(const RSA_METHOD *meth) { return meth->app_data; } int RSA_meth_set0_app_data(RSA_METHOD *meth, void *app_data) { meth->app_data = app_data; return 1; } int (*RSA_meth_get_pub_enc(const RSA_METHOD *meth)) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return meth->rsa_pub_enc; } int RSA_meth_set_pub_enc(RSA_METHOD *meth, int (*pub_enc) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)) { meth->rsa_pub_enc = pub_enc; return 1; } int (*RSA_meth_get_pub_dec(const RSA_METHOD *meth)) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return meth->rsa_pub_dec; } int RSA_meth_set_pub_dec(RSA_METHOD *meth, int (*pub_dec) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)) { meth->rsa_pub_dec = pub_dec; return 1; } int (*RSA_meth_get_priv_enc(const RSA_METHOD *meth)) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return meth->rsa_priv_enc; } int RSA_meth_set_priv_enc(RSA_METHOD *meth, int (*priv_enc) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)) { meth->rsa_priv_enc = priv_enc; return 1; } int (*RSA_meth_get_priv_dec(const RSA_METHOD *meth)) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return meth->rsa_priv_dec; } int RSA_meth_set_priv_dec(RSA_METHOD *meth, int (*priv_dec) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)) { meth->rsa_priv_dec = priv_dec; return 1; } /* Can be null */ int (*RSA_meth_get_mod_exp(const RSA_METHOD *meth)) (BIGNUM *r0, const BIGNUM *i, RSA *rsa, BN_CTX *ctx) { return meth->rsa_mod_exp; } int RSA_meth_set_mod_exp(RSA_METHOD *meth, int (*mod_exp) (BIGNUM *r0, const BIGNUM *i, RSA *rsa, BN_CTX *ctx)) { meth->rsa_mod_exp = mod_exp; return 1; } /* Can be null */ int (*RSA_meth_get_bn_mod_exp(const RSA_METHOD *meth)) (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { return meth->bn_mod_exp; } int RSA_meth_set_bn_mod_exp(RSA_METHOD *meth, int (*bn_mod_exp) (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)) { meth->bn_mod_exp = bn_mod_exp; return 1; } /* called at new */ int (*RSA_meth_get_init(const RSA_METHOD *meth)) (RSA *rsa) { return meth->init; } int RSA_meth_set_init(RSA_METHOD *meth, int (*init) (RSA *rsa)) { meth->init = init; return 1; } /* called at free */ int (*RSA_meth_get_finish(const RSA_METHOD *meth)) (RSA *rsa) { return meth->finish; } int RSA_meth_set_finish(RSA_METHOD *meth, int (*finish) (RSA *rsa)) { meth->finish = finish; return 1; } int (*RSA_meth_get_sign(const RSA_METHOD *meth)) (int type, const unsigned char *m, unsigned int m_length, unsigned char *sigret, unsigned int *siglen, const RSA *rsa) { return meth->rsa_sign; } int RSA_meth_set_sign(RSA_METHOD *meth, int (*sign) (int type, const unsigned char *m, unsigned int m_length, unsigned char *sigret, unsigned int *siglen, const RSA *rsa)) { meth->rsa_sign = sign; return 1; } int (*RSA_meth_get_verify(const RSA_METHOD *meth)) (int dtype, const unsigned char *m, unsigned int m_length, const unsigned char *sigbuf, unsigned int siglen, const RSA *rsa) { return meth->rsa_verify; } int RSA_meth_set_verify(RSA_METHOD *meth, int (*verify) (int dtype, const unsigned char *m, unsigned int m_length, const unsigned char *sigbuf, unsigned int siglen, const RSA *rsa)) { meth->rsa_verify = verify; return 1; } int (*RSA_meth_get_keygen(const RSA_METHOD *meth)) (RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb) { return meth->rsa_keygen; } int RSA_meth_set_keygen(RSA_METHOD *meth, int (*keygen) (RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb)) { meth->rsa_keygen = keygen; return 1; } int (*RSA_meth_get_multi_prime_keygen(const RSA_METHOD *meth)) (RSA *rsa, int bits, int primes, BIGNUM *e, BN_GENCB *cb) { return meth->rsa_multi_prime_keygen; } int RSA_meth_set_multi_prime_keygen(RSA_METHOD *meth, int (*keygen) (RSA *rsa, int bits, int primes, BIGNUM *e, BN_GENCB *cb)) { meth->rsa_multi_prime_keygen = keygen; return 1; }
./openssl/crypto/rsa/rsa_crpt.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 */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <openssl/crypto.h> #include "internal/cryptlib.h" #include "crypto/bn.h" #include <openssl/rand.h> #include "rsa_local.h" int RSA_bits(const RSA *r) { return BN_num_bits(r->n); } int RSA_size(const RSA *r) { return BN_num_bytes(r->n); } int RSA_public_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return rsa->meth->rsa_pub_enc(flen, from, to, rsa, padding); } int RSA_private_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return rsa->meth->rsa_priv_enc(flen, from, to, rsa, padding); } int RSA_private_decrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return rsa->meth->rsa_priv_dec(flen, from, to, rsa, padding); } int RSA_public_decrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return rsa->meth->rsa_pub_dec(flen, from, to, rsa, padding); } int RSA_flags(const RSA *r) { return r == NULL ? 0 : r->meth->flags; } void RSA_blinding_off(RSA *rsa) { BN_BLINDING_free(rsa->blinding); rsa->blinding = NULL; rsa->flags &= ~RSA_FLAG_BLINDING; rsa->flags |= RSA_FLAG_NO_BLINDING; } int RSA_blinding_on(RSA *rsa, BN_CTX *ctx) { int ret = 0; if (rsa->blinding != NULL) RSA_blinding_off(rsa); rsa->blinding = RSA_setup_blinding(rsa, ctx); if (rsa->blinding == NULL) goto err; rsa->flags |= RSA_FLAG_BLINDING; rsa->flags &= ~RSA_FLAG_NO_BLINDING; ret = 1; err: return ret; } static BIGNUM *rsa_get_public_exp(const BIGNUM *d, const BIGNUM *p, const BIGNUM *q, BN_CTX *ctx) { BIGNUM *ret = NULL, *r0, *r1, *r2; if (d == NULL || p == NULL || q == NULL) return NULL; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); if (r2 == NULL) goto err; if (!BN_sub(r1, p, BN_value_one())) goto err; if (!BN_sub(r2, q, BN_value_one())) goto err; if (!BN_mul(r0, r1, r2, ctx)) goto err; ret = BN_mod_inverse(NULL, d, r0, ctx); err: BN_CTX_end(ctx); return ret; } BN_BLINDING *RSA_setup_blinding(RSA *rsa, BN_CTX *in_ctx) { BIGNUM *e; BN_CTX *ctx; BN_BLINDING *ret = NULL; if (in_ctx == NULL) { if ((ctx = BN_CTX_new_ex(rsa->libctx)) == NULL) return 0; } else { ctx = in_ctx; } BN_CTX_start(ctx); e = BN_CTX_get(ctx); if (e == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB); goto err; } if (rsa->e == NULL) { e = rsa_get_public_exp(rsa->d, rsa->p, rsa->q, ctx); if (e == NULL) { ERR_raise(ERR_LIB_RSA, RSA_R_NO_PUBLIC_EXPONENT); goto err; } } else { e = rsa->e; } { BIGNUM *n = BN_new(); if (n == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB); goto err; } BN_with_flags(n, rsa->n, BN_FLG_CONSTTIME); ret = BN_BLINDING_create_param(NULL, e, n, ctx, rsa->meth->bn_mod_exp, rsa->_method_mod_n); /* We MUST free n before any further use of rsa->n */ BN_free(n); } if (ret == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB); goto err; } BN_BLINDING_set_current_thread(ret); err: BN_CTX_end(ctx); if (ctx != in_ctx) BN_CTX_free(ctx); if (e != rsa->e) BN_free(e); return ret; }
./openssl/crypto/rsa/rsa_sp800_56b_gen.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 */ #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/core.h> #include <openssl/evp.h> #include <openssl/rand.h> #include "crypto/bn.h" #include "crypto/security_bits.h" #include "rsa_local.h" #define RSA_FIPS1864_MIN_KEYGEN_KEYSIZE 2048 #define RSA_FIPS1864_MIN_KEYGEN_STRENGTH 112 /* * Generate probable primes 'p' & 'q'. See FIPS 186-4 Section B.3.6 * "Generation of Probable Primes with Conditions Based on Auxiliary Probable * Primes". * * Params: * rsa Object used to store primes p & q. * test Object used for CAVS testing only.that contains.. * p1, p2 The returned auxiliary primes for p. * If NULL they are not returned. * Xp An optional passed in value (that is random number used during * generation of p). * Xp1, Xp2 Optionally passed in randomly generated numbers from which * auxiliary primes p1 & p2 are calculated. If NULL these values * are generated internally. * q1, q2 The returned auxiliary primes for q. * If NULL they are not returned. * Xq An optional passed in value (that is random number used during * generation of q). * Xq1, Xq2 Optionally passed in randomly generated numbers from which * auxiliary primes q1 & q2 are calculated. If NULL these values * are generated internally. * nbits The key size in bits (The size of the modulus n). * e The public exponent. * ctx A BN_CTX object. * cb An optional BIGNUM callback. * Returns: 1 if successful, or 0 otherwise. * Notes: * p1, p2, q1, q2 are returned if they are not NULL. * Xp, Xp1, Xp2, Xq, Xq1, Xq2 are optionally passed in. * (Required for CAVS testing). */ int ossl_rsa_fips186_4_gen_prob_primes(RSA *rsa, RSA_ACVP_TEST *test, int nbits, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0, ok; /* Temp allocated BIGNUMS */ BIGNUM *Xpo = NULL, *Xqo = NULL, *tmp = NULL; /* Intermediate BIGNUMS that can be returned for testing */ BIGNUM *p1 = NULL, *p2 = NULL; BIGNUM *q1 = NULL, *q2 = NULL; /* Intermediate BIGNUMS that can be input for testing */ BIGNUM *Xp = NULL, *Xp1 = NULL, *Xp2 = NULL; BIGNUM *Xq = NULL, *Xq1 = NULL, *Xq2 = NULL; #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) if (test != NULL) { Xp1 = test->Xp1; Xp2 = test->Xp2; Xq1 = test->Xq1; Xq2 = test->Xq2; Xp = test->Xp; Xq = test->Xq; p1 = test->p1; p2 = test->p2; q1 = test->q1; q2 = test->q2; } #endif /* (Step 1) Check key length * NOTE: SP800-131A Rev1 Disallows key lengths of < 2048 bits for RSA * Signature Generation and Key Agree/Transport. */ if (nbits < RSA_FIPS1864_MIN_KEYGEN_KEYSIZE) { ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } if (!ossl_rsa_check_public_exponent(e)) { ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE); return 0; } /* (Step 3) Determine strength and check rand generator strength is ok - * this step is redundant because the generator always returns a higher * strength than is required. */ BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); Xpo = BN_CTX_get(ctx); Xqo = BN_CTX_get(ctx); if (tmp == NULL || Xpo == NULL || Xqo == NULL) goto err; BN_set_flags(Xpo, BN_FLG_CONSTTIME); BN_set_flags(Xqo, BN_FLG_CONSTTIME); if (rsa->p == NULL) rsa->p = BN_secure_new(); if (rsa->q == NULL) rsa->q = BN_secure_new(); if (rsa->p == NULL || rsa->q == NULL) goto err; BN_set_flags(rsa->p, BN_FLG_CONSTTIME); BN_set_flags(rsa->q, BN_FLG_CONSTTIME); /* (Step 4) Generate p, Xp */ if (!ossl_bn_rsa_fips186_4_gen_prob_primes(rsa->p, Xpo, p1, p2, Xp, Xp1, Xp2, nbits, e, ctx, cb)) goto err; for (;;) { /* (Step 5) Generate q, Xq*/ if (!ossl_bn_rsa_fips186_4_gen_prob_primes(rsa->q, Xqo, q1, q2, Xq, Xq1, Xq2, nbits, e, ctx, cb)) goto err; /* (Step 6) |Xp - Xq| > 2^(nbitlen/2 - 100) */ ok = ossl_rsa_check_pminusq_diff(tmp, Xpo, Xqo, nbits); if (ok < 0) goto err; if (ok == 0) continue; /* (Step 6) |p - q| > 2^(nbitlen/2 - 100) */ ok = ossl_rsa_check_pminusq_diff(tmp, rsa->p, rsa->q, nbits); if (ok < 0) goto err; if (ok == 0) continue; break; /* successfully finished */ } rsa->dirty_cnt++; ret = 1; err: /* Zeroize any internally generated values that are not returned */ if (Xpo != NULL) BN_clear(Xpo); if (Xqo != NULL) BN_clear(Xqo); BN_clear(tmp); BN_CTX_end(ctx); return ret; } /* * Validates the RSA key size based on the target strength. * See SP800-56Br1 6.3.1.1 (Steps 1a-1b) * * Params: * nbits The key size in bits. * strength The target strength in bits. -1 means the target * strength is unknown. * Returns: 1 if the key size matches the target strength, or 0 otherwise. */ int ossl_rsa_sp800_56b_validate_strength(int nbits, int strength) { int s = (int)ossl_ifc_ffc_compute_security_bits(nbits); #ifdef FIPS_MODULE if (s < RSA_FIPS1864_MIN_KEYGEN_STRENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MODULUS); return 0; } #endif if (strength != -1 && s != strength) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_STRENGTH); return 0; } return 1; } /* * Validate that the random bit generator is of sufficient strength to generate * a key of the specified length. */ static int rsa_validate_rng_strength(EVP_RAND_CTX *rng, int nbits) { if (rng == NULL) return 0; #ifdef FIPS_MODULE /* * This should become mainstream once similar tests are added to the other * key generations and once there is a way to disable these checks. */ if (EVP_RAND_get_strength(rng) < ossl_ifc_ffc_compute_security_bits(nbits)) { ERR_raise(ERR_LIB_RSA, RSA_R_RANDOMNESS_SOURCE_STRENGTH_INSUFFICIENT); return 0; } #endif return 1; } /* * * Using p & q, calculate other required parameters such as n, d. * as well as the CRT parameters dP, dQ, qInv. * * See SP800-56Br1 * 6.3.1.1 rsakpg1 - basic (Steps 3-4) * 6.3.1.3 rsakpg1 - crt (Step 5) * * Params: * rsa An rsa object. * nbits The key size. * e The public exponent. * ctx A BN_CTX object. * Notes: * There is a small chance that the generated d will be too small. * Returns: -1 = error, * 0 = d is too small, * 1 = success. * * SP800-56b key generation always passes a non NULL value for e. * For other purposes, if e is NULL then it is assumed that e, n and d are * already set in the RSA key and do not need to be recalculated. */ int ossl_rsa_sp800_56b_derive_params_from_pq(RSA *rsa, int nbits, const BIGNUM *e, BN_CTX *ctx) { int ret = -1; BIGNUM *p1, *q1, *lcm, *p1q1, *gcd; BN_CTX_start(ctx); p1 = BN_CTX_get(ctx); q1 = BN_CTX_get(ctx); lcm = BN_CTX_get(ctx); p1q1 = BN_CTX_get(ctx); gcd = BN_CTX_get(ctx); if (gcd == NULL) goto err; BN_set_flags(p1, BN_FLG_CONSTTIME); BN_set_flags(q1, BN_FLG_CONSTTIME); BN_set_flags(lcm, BN_FLG_CONSTTIME); BN_set_flags(p1q1, BN_FLG_CONSTTIME); BN_set_flags(gcd, BN_FLG_CONSTTIME); /* LCM((p-1, q-1)) */ if (ossl_rsa_get_lcm(ctx, rsa->p, rsa->q, lcm, gcd, p1, q1, p1q1) != 1) goto err; /* * if e is provided as a parameter, don't recompute e, d or n */ if (e != NULL) { /* copy e */ BN_free(rsa->e); rsa->e = BN_dup(e); if (rsa->e == NULL) goto err; BN_clear_free(rsa->d); /* (Step 3) d = (e^-1) mod (LCM(p-1, q-1)) */ rsa->d = BN_secure_new(); if (rsa->d == NULL) goto err; BN_set_flags(rsa->d, BN_FLG_CONSTTIME); if (BN_mod_inverse(rsa->d, e, lcm, ctx) == NULL) goto err; /* (Step 3) return an error if d is too small */ if (BN_num_bits(rsa->d) <= (nbits >> 1)) { ret = 0; goto err; } /* (Step 4) n = pq */ if (rsa->n == NULL) rsa->n = BN_new(); if (rsa->n == NULL || !BN_mul(rsa->n, rsa->p, rsa->q, ctx)) goto err; } /* (Step 5a) dP = d mod (p-1) */ if (rsa->dmp1 == NULL) rsa->dmp1 = BN_secure_new(); if (rsa->dmp1 == NULL) goto err; BN_set_flags(rsa->dmp1, BN_FLG_CONSTTIME); if (!BN_mod(rsa->dmp1, rsa->d, p1, ctx)) goto err; /* (Step 5b) dQ = d mod (q-1) */ if (rsa->dmq1 == NULL) rsa->dmq1 = BN_secure_new(); if (rsa->dmq1 == NULL) goto err; BN_set_flags(rsa->dmq1, BN_FLG_CONSTTIME); if (!BN_mod(rsa->dmq1, rsa->d, q1, ctx)) goto err; /* (Step 5c) qInv = (inverse of q) mod p */ BN_free(rsa->iqmp); rsa->iqmp = BN_secure_new(); if (rsa->iqmp == NULL) goto err; BN_set_flags(rsa->iqmp, BN_FLG_CONSTTIME); if (BN_mod_inverse(rsa->iqmp, rsa->q, rsa->p, ctx) == NULL) goto err; rsa->dirty_cnt++; ret = 1; err: if (ret != 1) { BN_free(rsa->e); rsa->e = NULL; BN_free(rsa->d); rsa->d = NULL; BN_free(rsa->n); rsa->n = NULL; BN_free(rsa->iqmp); rsa->iqmp = NULL; BN_free(rsa->dmq1); rsa->dmq1 = NULL; BN_free(rsa->dmp1); rsa->dmp1 = NULL; } BN_clear(p1); BN_clear(q1); BN_clear(lcm); BN_clear(p1q1); BN_clear(gcd); BN_CTX_end(ctx); return ret; } /* * Generate a SP800-56B RSA key. * * See SP800-56Br1 6.3.1 "RSA Key-Pair Generation with a Fixed Public Exponent" * 6.3.1.1 rsakpg1 - basic * 6.3.1.3 rsakpg1 - crt * * See also FIPS 186-4 Section B.3.6 * "Generation of Probable Primes with Conditions Based on Auxiliary * Probable Primes." * * Params: * rsa The rsa object. * nbits The intended key size in bits. * efixed The public exponent. If NULL a default of 65537 is used. * cb An optional BIGNUM callback. * Returns: 1 if successfully generated otherwise it returns 0. */ int ossl_rsa_sp800_56b_generate_key(RSA *rsa, int nbits, const BIGNUM *efixed, BN_GENCB *cb) { int ret = 0; int ok; BN_CTX *ctx = NULL; BIGNUM *e = NULL; RSA_ACVP_TEST *info = NULL; BIGNUM *tmp; #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) info = rsa->acvp_test; #endif /* (Steps 1a-1b) : Currently ignores the strength check */ if (!ossl_rsa_sp800_56b_validate_strength(nbits, -1)) return 0; /* Check that the RNG is capable of generating a key this large */ if (!rsa_validate_rng_strength(RAND_get0_private(rsa->libctx), nbits)) return 0; ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) return 0; /* Set default if e is not passed in */ if (efixed == NULL) { e = BN_new(); if (e == NULL || !BN_set_word(e, 65537)) goto err; } else { e = (BIGNUM *)efixed; } /* (Step 1c) fixed exponent is checked later .*/ for (;;) { /* (Step 2) Generate prime factors */ if (!ossl_rsa_fips186_4_gen_prob_primes(rsa, info, nbits, e, ctx, cb)) goto err; /* p>q check and skipping in case of acvp test */ if (info == NULL && BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } /* (Steps 3-5) Compute params d, n, dP, dQ, qInv */ ok = ossl_rsa_sp800_56b_derive_params_from_pq(rsa, nbits, e, ctx); if (ok < 0) goto err; if (ok > 0) break; /* Gets here if computed d is too small - so try again */ } /* (Step 6) Do pairwise test - optional validity test has been omitted */ ret = ossl_rsa_sp800_56b_pairwise_test(rsa, ctx); err: if (efixed == NULL) BN_free(e); BN_CTX_free(ctx); return ret; } /* * See SP800-56Br1 6.3.1.3 (Step 6) Perform a pair-wise consistency test by * verifying that: k = (k^e)^d mod n for some integer k where 1 < k < n-1. * * Returns 1 if the RSA key passes the pairwise test or 0 if it fails. */ int ossl_rsa_sp800_56b_pairwise_test(RSA *rsa, BN_CTX *ctx) { int ret = 0; BIGNUM *k, *tmp; BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); k = BN_CTX_get(ctx); if (k == NULL) goto err; BN_set_flags(k, BN_FLG_CONSTTIME); ret = (BN_set_word(k, 2) && BN_mod_exp(tmp, k, rsa->e, rsa->n, ctx) && BN_mod_exp(tmp, tmp, rsa->d, rsa->n, ctx) && BN_cmp(k, tmp) == 0); if (ret == 0) ERR_raise(ERR_LIB_RSA, RSA_R_PAIRWISE_TEST_FAILURE); err: BN_CTX_end(ctx); return ret; }
./openssl/crypto/rsa/rsa_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/rsaerr.h> #include "crypto/rsaerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA RSA_str_reasons[] = { {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_ALGORITHM_MISMATCH), "algorithm mismatch"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_E_VALUE), "bad e value"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_FIXED_HEADER_DECRYPT), "bad fixed header decrypt"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_PAD_BYTE_COUNT), "bad pad byte count"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_SIGNATURE), "bad signature"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BLOCK_TYPE_IS_NOT_01), "block type is not 01"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BLOCK_TYPE_IS_NOT_02), "block type is not 02"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_GREATER_THAN_MOD_LEN), "data greater than mod len"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_LARGE), "data too large"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE), "data too large for key size"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_LARGE_FOR_MODULUS), "data too large for modulus"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_SMALL), "data too small"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE), "data too small for key size"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DIGEST_DOES_NOT_MATCH), "digest does not match"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DIGEST_NOT_ALLOWED), "digest not allowed"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY), "digest too big for rsa key"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DMP1_NOT_CONGRUENT_TO_D), "dmp1 not congruent to d"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DMQ1_NOT_CONGRUENT_TO_D), "dmq1 not congruent to d"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_D_E_NOT_CONGRUENT_TO_1), "d e not congruent to 1"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_FIRST_OCTET_INVALID), "first octet invalid"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE), "illegal or unsupported padding mode"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_DIGEST), "invalid digest"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_DIGEST_LENGTH), "invalid digest length"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_HEADER), "invalid header"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_KEYPAIR), "invalid keypair"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_KEY_LENGTH), "invalid key length"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_LABEL), "invalid label"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_LENGTH), "invalid length"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_MESSAGE_LENGTH), "invalid message length"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_MGF1_MD), "invalid mgf1 md"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_MODULUS), "invalid modulus"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_MULTI_PRIME_KEY), "invalid multi prime key"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_OAEP_PARAMETERS), "invalid oaep parameters"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PADDING), "invalid padding"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PADDING_MODE), "invalid padding mode"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PSS_PARAMETERS), "invalid pss parameters"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PSS_SALTLEN), "invalid pss saltlen"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_REQUEST), "invalid request"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_SALT_LENGTH), "invalid salt length"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_STRENGTH), "invalid strength"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_TRAILER), "invalid trailer"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_X931_DIGEST), "invalid x931 digest"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_IQMP_NOT_INVERSE_OF_Q), "iqmp not inverse of q"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_KEY_PRIME_NUM_INVALID), "key prime num invalid"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_KEY_SIZE_TOO_SMALL), "key size too small"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_LAST_OCTET_INVALID), "last octet invalid"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MGF1_DIGEST_NOT_ALLOWED), "mgf1 digest not allowed"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MISSING_PRIVATE_KEY), "missing private key"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MODULUS_TOO_LARGE), "modulus too large"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MP_COEFFICIENT_NOT_INVERSE_OF_R), "mp coefficient not inverse of r"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MP_EXPONENT_NOT_CONGRUENT_TO_D), "mp exponent not congruent to d"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MP_R_NOT_PRIME), "mp r not prime"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_NO_PUBLIC_EXPONENT), "no public exponent"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_NULL_BEFORE_BLOCK_MISSING), "null before block missing"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_N_DOES_NOT_EQUAL_PRODUCT_OF_PRIMES), "n does not equal product of primes"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_N_DOES_NOT_EQUAL_P_Q), "n does not equal p q"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_OAEP_DECODING_ERROR), "oaep decoding error"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE), "operation not supported for this keytype"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PADDING_CHECK_FAILED), "padding check failed"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PAIRWISE_TEST_FAILURE), "pairwise test failure"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PKCS_DECODING_ERROR), "pkcs decoding error"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PSS_SALTLEN_TOO_SMALL), "pss saltlen too small"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PUB_EXPONENT_OUT_OF_RANGE), "pub exponent out of range"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_P_NOT_PRIME), "p not prime"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_Q_NOT_PRIME), "q not prime"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_RANDOMNESS_SOURCE_STRENGTH_INSUFFICIENT), "randomness source strength insufficient"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED), "rsa operations not supported"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_SLEN_CHECK_FAILED), "salt length check failed"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_SLEN_RECOVERY_FAILED), "salt length recovery failed"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_SSLV3_ROLLBACK_ATTACK), "sslv3 rollback attack"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD), "the asn1 object identifier is not known for this md"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_ALGORITHM_TYPE), "unknown algorithm type"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_DIGEST), "unknown digest"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_MASK_DIGEST), "unknown mask digest"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_PADDING_TYPE), "unknown padding type"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_ENCRYPTION_TYPE), "unsupported encryption type"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_LABEL_SOURCE), "unsupported label source"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_MASK_ALGORITHM), "unsupported mask algorithm"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_MASK_PARAMETER), "unsupported mask parameter"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_SIGNATURE_TYPE), "unsupported signature type"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_VALUE_MISSING), "value missing"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_WRONG_SIGNATURE_LENGTH), "wrong signature length"}, {0, NULL} }; #endif int ossl_err_load_RSA_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(RSA_str_reasons[0].error) == NULL) ERR_load_strings_const(RSA_str_reasons); #endif return 1; }
./openssl/crypto/rsa/rsa_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 */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/crypto.h> #include <openssl/core_names.h> #ifndef FIPS_MODULE # include <openssl/engine.h> #endif #include <openssl/evp.h> #include <openssl/param_build.h> #include "internal/cryptlib.h" #include "internal/refcount.h" #include "crypto/bn.h" #include "crypto/evp.h" #include "crypto/rsa.h" #include "crypto/security_bits.h" #include "rsa_local.h" static RSA *rsa_new_intern(ENGINE *engine, OSSL_LIB_CTX *libctx); #ifndef FIPS_MODULE RSA *RSA_new(void) { return rsa_new_intern(NULL, NULL); } const RSA_METHOD *RSA_get_method(const RSA *rsa) { return rsa->meth; } int RSA_set_method(RSA *rsa, const RSA_METHOD *meth) { /* * NB: The caller is specifically setting a method, so it's not up to us * to deal with which ENGINE it comes from. */ const RSA_METHOD *mtmp; mtmp = rsa->meth; if (mtmp->finish) mtmp->finish(rsa); #ifndef OPENSSL_NO_ENGINE ENGINE_finish(rsa->engine); rsa->engine = NULL; #endif rsa->meth = meth; if (meth->init) meth->init(rsa); return 1; } RSA *RSA_new_method(ENGINE *engine) { return rsa_new_intern(engine, NULL); } #endif RSA *ossl_rsa_new_with_ctx(OSSL_LIB_CTX *libctx) { return rsa_new_intern(NULL, libctx); } static RSA *rsa_new_intern(ENGINE *engine, OSSL_LIB_CTX *libctx) { RSA *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_CRYPTO_LIB); OPENSSL_free(ret); return NULL; } if (!CRYPTO_NEW_REF(&ret->references, 1)) { CRYPTO_THREAD_lock_free(ret->lock); OPENSSL_free(ret); return NULL; } ret->libctx = libctx; ret->meth = RSA_get_default_method(); #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) ret->flags = ret->meth->flags & ~RSA_FLAG_NON_FIPS_ALLOW; if (engine) { if (!ENGINE_init(engine)) { ERR_raise(ERR_LIB_RSA, ERR_R_ENGINE_LIB); goto err; } ret->engine = engine; } else { ret->engine = ENGINE_get_default_RSA(); } if (ret->engine) { ret->meth = ENGINE_get_RSA(ret->engine); if (ret->meth == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_ENGINE_LIB); goto err; } } #endif ret->flags = ret->meth->flags & ~RSA_FLAG_NON_FIPS_ALLOW; #ifndef FIPS_MODULE if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_RSA, ret, &ret->ex_data)) { goto err; } #endif if ((ret->meth->init != NULL) && !ret->meth->init(ret)) { ERR_raise(ERR_LIB_RSA, ERR_R_INIT_FAIL); goto err; } return ret; err: RSA_free(ret); return NULL; } void RSA_free(RSA *r) { int i; if (r == NULL) return; CRYPTO_DOWN_REF(&r->references, &i); REF_PRINT_COUNT("RSA", r); if (i > 0) return; REF_ASSERT_ISNT(i < 0); if (r->meth != NULL && r->meth->finish != NULL) r->meth->finish(r); #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE) ENGINE_finish(r->engine); #endif #ifndef FIPS_MODULE CRYPTO_free_ex_data(CRYPTO_EX_INDEX_RSA, r, &r->ex_data); #endif CRYPTO_THREAD_lock_free(r->lock); CRYPTO_FREE_REF(&r->references); BN_free(r->n); BN_free(r->e); BN_clear_free(r->d); BN_clear_free(r->p); BN_clear_free(r->q); BN_clear_free(r->dmp1); BN_clear_free(r->dmq1); BN_clear_free(r->iqmp); #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) ossl_rsa_acvp_test_free(r->acvp_test); #endif #ifndef FIPS_MODULE RSA_PSS_PARAMS_free(r->pss); sk_RSA_PRIME_INFO_pop_free(r->prime_infos, ossl_rsa_multip_info_free); #endif BN_BLINDING_free(r->blinding); BN_BLINDING_free(r->mt_blinding); OPENSSL_free(r); } int RSA_up_ref(RSA *r) { int i; if (CRYPTO_UP_REF(&r->references, &i) <= 0) return 0; REF_PRINT_COUNT("RSA", r); REF_ASSERT_ISNT(i < 2); return i > 1 ? 1 : 0; } OSSL_LIB_CTX *ossl_rsa_get0_libctx(RSA *r) { return r->libctx; } void ossl_rsa_set0_libctx(RSA *r, OSSL_LIB_CTX *libctx) { r->libctx = libctx; } #ifndef FIPS_MODULE int RSA_set_ex_data(RSA *r, int idx, void *arg) { return CRYPTO_set_ex_data(&r->ex_data, idx, arg); } void *RSA_get_ex_data(const RSA *r, int idx) { return CRYPTO_get_ex_data(&r->ex_data, idx); } #endif /* * Define a scaling constant for our fixed point arithmetic. * This value must be a power of two because the base two logarithm code * makes this assumption. The exponent must also be a multiple of three so * that the scale factor has an exact cube root. Finally, the scale factor * should not be so large that a multiplication of two scaled numbers * overflows a 64 bit unsigned integer. */ static const unsigned int scale = 1 << 18; static const unsigned int cbrt_scale = 1 << (2 * 18 / 3); /* Define some constants, none exceed 32 bits */ static const unsigned int log_2 = 0x02c5c8; /* scale * log(2) */ static const unsigned int log_e = 0x05c551; /* scale * log2(M_E) */ static const unsigned int c1_923 = 0x07b126; /* scale * 1.923 */ static const unsigned int c4_690 = 0x12c28f; /* scale * 4.690 */ /* * Multiply two scaled integers together and rescale the result. */ static ossl_inline uint64_t mul2(uint64_t a, uint64_t b) { return a * b / scale; } /* * Calculate the cube root of a 64 bit scaled integer. * Although the cube root of a 64 bit number does fit into a 32 bit unsigned * integer, this is not guaranteed after scaling, so this function has a * 64 bit return. This uses the shifting nth root algorithm with some * algebraic simplifications. */ static uint64_t icbrt64(uint64_t x) { uint64_t r = 0; uint64_t b; int s; for (s = 63; s >= 0; s -= 3) { r <<= 1; b = 3 * r * (r + 1) + 1; if ((x >> s) >= b) { x -= b << s; r++; } } return r * cbrt_scale; } /* * Calculate the natural logarithm of a 64 bit scaled integer. * This is done by calculating a base two logarithm and scaling. * The maximum logarithm (base 2) is 64 and this reduces base e, so * a 32 bit result should not overflow. The argument passed must be * greater than unity so we don't need to handle negative results. */ static uint32_t ilog_e(uint64_t v) { uint32_t i, r = 0; /* * Scale down the value into the range 1 .. 2. * * If fractional numbers need to be processed, another loop needs * to go here that checks v < scale and if so multiplies it by 2 and * reduces r by scale. This also means making r signed. */ while (v >= 2 * scale) { v >>= 1; r += scale; } for (i = scale / 2; i != 0; i /= 2) { v = mul2(v, v); if (v >= 2 * scale) { v >>= 1; r += i; } } r = (r * (uint64_t)scale) / log_e; return r; } /* * NIST SP 800-56B rev 2 Appendix D: Maximum Security Strength Estimates for IFC * Modulus Lengths. * * Note that this formula is also referred to in SP800-56A rev3 Appendix D: * for FFC safe prime groups for modp and ffdhe. * After Table 25 and Table 26 it refers to * "The maximum security strength estimates were calculated using the formula in * Section 7.5 of the FIPS 140 IG and rounded to the nearest multiple of eight * bits". * * The formula is: * * E = \frac{1.923 \sqrt[3]{nBits \cdot log_e(2)} * \cdot(log_e(nBits \cdot log_e(2))^{2/3} - 4.69}{log_e(2)} * The two cube roots are merged together here. */ uint16_t ossl_ifc_ffc_compute_security_bits(int n) { uint64_t x; uint32_t lx; uint16_t y, cap; /* * Look for common values as listed in standards. * These values are not exactly equal to the results from the formulae in * the standards but are defined to be canonical. */ switch (n) { case 2048: /* SP 800-56B rev 2 Appendix D and FIPS 140-2 IG 7.5 */ return 112; case 3072: /* SP 800-56B rev 2 Appendix D and FIPS 140-2 IG 7.5 */ return 128; case 4096: /* SP 800-56B rev 2 Appendix D */ return 152; case 6144: /* SP 800-56B rev 2 Appendix D */ return 176; case 7680: /* FIPS 140-2 IG 7.5 */ return 192; case 8192: /* SP 800-56B rev 2 Appendix D */ return 200; case 15360: /* FIPS 140-2 IG 7.5 */ return 256; } /* * The first incorrect result (i.e. not accurate or off by one low) occurs * for n = 699668. The true value here is 1200. Instead of using this n * as the check threshold, the smallest n such that the correct result is * 1200 is used instead. */ if (n >= 687737) return 1200; if (n < 8) return 0; /* * To ensure that the output is non-decreasing with respect to n, * a cap needs to be applied to the two values where the function over * estimates the strength (according to the above fast path). */ if (n <= 7680) cap = 192; else if (n <= 15360) cap = 256; else cap = 1200; x = n * (uint64_t)log_2; lx = ilog_e(x); y = (uint16_t)((mul2(c1_923, icbrt64(mul2(mul2(x, lx), lx))) - c4_690) / log_2); y = (y + 4) & ~7; if (y > cap) y = cap; return y; } int RSA_security_bits(const RSA *rsa) { int bits = BN_num_bits(rsa->n); #ifndef FIPS_MODULE if (rsa->version == RSA_ASN1_VERSION_MULTI) { /* This ought to mean that we have private key at hand. */ int ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos); if (ex_primes <= 0 || (ex_primes + 2) > ossl_rsa_multip_cap(bits)) return 0; } #endif return ossl_ifc_ffc_compute_security_bits(bits); } int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d) { /* If the fields n and e in r are NULL, the corresponding input * parameters MUST be non-NULL for n and e. d may be * left NULL (in case only the public key is used). */ if ((r->n == NULL && n == NULL) || (r->e == NULL && e == NULL)) return 0; if (n != NULL) { BN_free(r->n); r->n = n; } if (e != NULL) { BN_free(r->e); r->e = e; } if (d != NULL) { BN_clear_free(r->d); r->d = d; BN_set_flags(r->d, BN_FLG_CONSTTIME); } r->dirty_cnt++; return 1; } int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q) { /* If the fields p and q in r are NULL, the corresponding input * parameters MUST be non-NULL. */ if ((r->p == NULL && p == NULL) || (r->q == NULL && q == NULL)) return 0; if (p != NULL) { BN_clear_free(r->p); r->p = p; BN_set_flags(r->p, BN_FLG_CONSTTIME); } if (q != NULL) { BN_clear_free(r->q); r->q = q; BN_set_flags(r->q, BN_FLG_CONSTTIME); } r->dirty_cnt++; return 1; } int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp) { /* If the fields dmp1, dmq1 and iqmp in r are NULL, the corresponding input * parameters MUST be non-NULL. */ if ((r->dmp1 == NULL && dmp1 == NULL) || (r->dmq1 == NULL && dmq1 == NULL) || (r->iqmp == NULL && iqmp == NULL)) return 0; if (dmp1 != NULL) { BN_clear_free(r->dmp1); r->dmp1 = dmp1; BN_set_flags(r->dmp1, BN_FLG_CONSTTIME); } if (dmq1 != NULL) { BN_clear_free(r->dmq1); r->dmq1 = dmq1; BN_set_flags(r->dmq1, BN_FLG_CONSTTIME); } if (iqmp != NULL) { BN_clear_free(r->iqmp); r->iqmp = iqmp; BN_set_flags(r->iqmp, BN_FLG_CONSTTIME); } r->dirty_cnt++; return 1; } #ifndef FIPS_MODULE /* * Is it better to export RSA_PRIME_INFO structure * and related functions to let user pass a triplet? */ int RSA_set0_multi_prime_params(RSA *r, BIGNUM *primes[], BIGNUM *exps[], BIGNUM *coeffs[], int pnum) { STACK_OF(RSA_PRIME_INFO) *prime_infos, *old = NULL; RSA_PRIME_INFO *pinfo; int i; if (primes == NULL || exps == NULL || coeffs == NULL || pnum == 0) return 0; prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, pnum); if (prime_infos == NULL) return 0; if (r->prime_infos != NULL) old = r->prime_infos; for (i = 0; i < pnum; i++) { pinfo = ossl_rsa_multip_info_new(); if (pinfo == NULL) goto err; if (primes[i] != NULL && exps[i] != NULL && coeffs[i] != NULL) { BN_clear_free(pinfo->r); BN_clear_free(pinfo->d); BN_clear_free(pinfo->t); pinfo->r = primes[i]; pinfo->d = exps[i]; pinfo->t = coeffs[i]; BN_set_flags(pinfo->r, BN_FLG_CONSTTIME); BN_set_flags(pinfo->d, BN_FLG_CONSTTIME); BN_set_flags(pinfo->t, BN_FLG_CONSTTIME); } else { ossl_rsa_multip_info_free(pinfo); goto err; } (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo); } r->prime_infos = prime_infos; if (!ossl_rsa_multip_calc_product(r)) { r->prime_infos = old; goto err; } if (old != NULL) { /* * This is hard to deal with, since the old infos could * also be set by this function and r, d, t should not * be freed in that case. So currently, stay consistent * with other *set0* functions: just free it... */ sk_RSA_PRIME_INFO_pop_free(old, ossl_rsa_multip_info_free); } r->version = RSA_ASN1_VERSION_MULTI; r->dirty_cnt++; return 1; err: /* r, d, t should not be freed */ sk_RSA_PRIME_INFO_pop_free(prime_infos, ossl_rsa_multip_info_free_ex); return 0; } #endif void RSA_get0_key(const RSA *r, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d) { if (n != NULL) *n = r->n; if (e != NULL) *e = r->e; if (d != NULL) *d = r->d; } void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q) { if (p != NULL) *p = r->p; if (q != NULL) *q = r->q; } #ifndef FIPS_MODULE int RSA_get_multi_prime_extra_count(const RSA *r) { int pnum; pnum = sk_RSA_PRIME_INFO_num(r->prime_infos); if (pnum <= 0) pnum = 0; return pnum; } int RSA_get0_multi_prime_factors(const RSA *r, const BIGNUM *primes[]) { int pnum, i; RSA_PRIME_INFO *pinfo; if ((pnum = RSA_get_multi_prime_extra_count(r)) == 0) return 0; /* * return other primes * it's caller's responsibility to allocate oth_primes[pnum] */ for (i = 0; i < pnum; i++) { pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i); primes[i] = pinfo->r; } return 1; } #endif void RSA_get0_crt_params(const RSA *r, const BIGNUM **dmp1, const BIGNUM **dmq1, const BIGNUM **iqmp) { if (dmp1 != NULL) *dmp1 = r->dmp1; if (dmq1 != NULL) *dmq1 = r->dmq1; if (iqmp != NULL) *iqmp = r->iqmp; } #ifndef FIPS_MODULE int RSA_get0_multi_prime_crt_params(const RSA *r, const BIGNUM *exps[], const BIGNUM *coeffs[]) { int pnum; if ((pnum = RSA_get_multi_prime_extra_count(r)) == 0) return 0; /* return other primes */ if (exps != NULL || coeffs != NULL) { RSA_PRIME_INFO *pinfo; int i; /* it's the user's job to guarantee the buffer length */ for (i = 0; i < pnum; i++) { pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i); if (exps != NULL) exps[i] = pinfo->d; if (coeffs != NULL) coeffs[i] = pinfo->t; } } return 1; } #endif const BIGNUM *RSA_get0_n(const RSA *r) { return r->n; } const BIGNUM *RSA_get0_e(const RSA *r) { return r->e; } const BIGNUM *RSA_get0_d(const RSA *r) { return r->d; } const BIGNUM *RSA_get0_p(const RSA *r) { return r->p; } const BIGNUM *RSA_get0_q(const RSA *r) { return r->q; } const BIGNUM *RSA_get0_dmp1(const RSA *r) { return r->dmp1; } const BIGNUM *RSA_get0_dmq1(const RSA *r) { return r->dmq1; } const BIGNUM *RSA_get0_iqmp(const RSA *r) { return r->iqmp; } const RSA_PSS_PARAMS *RSA_get0_pss_params(const RSA *r) { #ifdef FIPS_MODULE return NULL; #else return r->pss; #endif } /* Internal */ int ossl_rsa_set0_pss_params(RSA *r, RSA_PSS_PARAMS *pss) { #ifdef FIPS_MODULE return 0; #else RSA_PSS_PARAMS_free(r->pss); r->pss = pss; return 1; #endif } /* Internal */ RSA_PSS_PARAMS_30 *ossl_rsa_get0_pss_params_30(RSA *r) { return &r->pss_params; } void RSA_clear_flags(RSA *r, int flags) { r->flags &= ~flags; } int RSA_test_flags(const RSA *r, int flags) { return r->flags & flags; } void RSA_set_flags(RSA *r, int flags) { r->flags |= flags; } int RSA_get_version(RSA *r) { /* { two-prime(0), multi(1) } */ return r->version; } #ifndef FIPS_MODULE ENGINE *RSA_get0_engine(const RSA *r) { return r->engine; } int RSA_pkey_ctx_ctrl(EVP_PKEY_CTX *ctx, int optype, int cmd, int p1, void *p2) { /* If key type not RSA or RSA-PSS return error */ if (ctx != NULL && ctx->pmeth != NULL && ctx->pmeth->pkey_id != EVP_PKEY_RSA && ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS) return -1; return EVP_PKEY_CTX_ctrl(ctx, -1, optype, cmd, p1, p2); } #endif DEFINE_STACK_OF(BIGNUM) /* * Note: This function deletes values from the parameter * stack values as they are consumed and set in the RSA key. */ int ossl_rsa_set0_all_params(RSA *r, STACK_OF(BIGNUM) *primes, STACK_OF(BIGNUM) *exps, STACK_OF(BIGNUM) *coeffs) { #ifndef FIPS_MODULE STACK_OF(RSA_PRIME_INFO) *prime_infos, *old_infos = NULL; #endif int pnum; if (primes == NULL || exps == NULL || coeffs == NULL) return 0; pnum = sk_BIGNUM_num(primes); /* we need at least 2 primes */ if (pnum < 2) return 0; if (!RSA_set0_factors(r, sk_BIGNUM_value(primes, 0), sk_BIGNUM_value(primes, 1))) return 0; /* * if we managed to set everything above, remove those elements from the * stack * Note, we do this after the above all to ensure that we have taken * ownership of all the elements in the RSA key to avoid memory leaks * we also use delete 0 here as we are grabbing items from the end of the * stack rather than the start, otherwise we could use pop */ sk_BIGNUM_delete(primes, 0); sk_BIGNUM_delete(primes, 0); if (pnum == sk_BIGNUM_num(exps) && pnum == sk_BIGNUM_num(coeffs) + 1) { if (!RSA_set0_crt_params(r, sk_BIGNUM_value(exps, 0), sk_BIGNUM_value(exps, 1), sk_BIGNUM_value(coeffs, 0))) return 0; /* as above, once we consume the above params, delete them from the list */ sk_BIGNUM_delete(exps, 0); sk_BIGNUM_delete(exps, 0); sk_BIGNUM_delete(coeffs, 0); } #ifndef FIPS_MODULE old_infos = r->prime_infos; #endif if (pnum > 2) { #ifndef FIPS_MODULE int i; prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, pnum); if (prime_infos == NULL) return 0; for (i = 2; i < pnum; i++) { BIGNUM *prime = sk_BIGNUM_pop(primes); BIGNUM *exp = sk_BIGNUM_pop(exps); BIGNUM *coeff = sk_BIGNUM_pop(coeffs); RSA_PRIME_INFO *pinfo = NULL; if (!ossl_assert(prime != NULL && exp != NULL && coeff != NULL)) goto err; /* Using ossl_rsa_multip_info_new() is wasteful, so allocate directly */ if ((pinfo = OPENSSL_zalloc(sizeof(*pinfo))) == NULL) goto err; pinfo->r = prime; pinfo->d = exp; pinfo->t = coeff; BN_set_flags(pinfo->r, BN_FLG_CONSTTIME); BN_set_flags(pinfo->d, BN_FLG_CONSTTIME); BN_set_flags(pinfo->t, BN_FLG_CONSTTIME); (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo); } r->prime_infos = prime_infos; if (!ossl_rsa_multip_calc_product(r)) { r->prime_infos = old_infos; goto err; } #else return 0; #endif } #ifndef FIPS_MODULE if (old_infos != NULL) { /* * This is hard to deal with, since the old infos could * also be set by this function and r, d, t should not * be freed in that case. So currently, stay consistent * with other *set0* functions: just free it... */ sk_RSA_PRIME_INFO_pop_free(old_infos, ossl_rsa_multip_info_free); } #endif r->version = pnum > 2 ? RSA_ASN1_VERSION_MULTI : RSA_ASN1_VERSION_DEFAULT; r->dirty_cnt++; return 1; #ifndef FIPS_MODULE err: /* r, d, t should not be freed */ sk_RSA_PRIME_INFO_pop_free(prime_infos, ossl_rsa_multip_info_free_ex); return 0; #endif } DEFINE_SPECIAL_STACK_OF_CONST(BIGNUM_const, BIGNUM) int ossl_rsa_get0_all_params(RSA *r, STACK_OF(BIGNUM_const) *primes, STACK_OF(BIGNUM_const) *exps, STACK_OF(BIGNUM_const) *coeffs) { #ifndef FIPS_MODULE RSA_PRIME_INFO *pinfo; int i, pnum; #endif if (r == NULL) return 0; /* If |p| is NULL, there are no CRT parameters */ if (RSA_get0_p(r) == NULL) return 1; sk_BIGNUM_const_push(primes, RSA_get0_p(r)); sk_BIGNUM_const_push(primes, RSA_get0_q(r)); sk_BIGNUM_const_push(exps, RSA_get0_dmp1(r)); sk_BIGNUM_const_push(exps, RSA_get0_dmq1(r)); sk_BIGNUM_const_push(coeffs, RSA_get0_iqmp(r)); #ifndef FIPS_MODULE pnum = RSA_get_multi_prime_extra_count(r); for (i = 0; i < pnum; i++) { pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i); sk_BIGNUM_const_push(primes, pinfo->r); sk_BIGNUM_const_push(exps, pinfo->d); sk_BIGNUM_const_push(coeffs, pinfo->t); } #endif return 1; } #ifndef FIPS_MODULE /* Helpers to set or get diverse hash algorithm names */ static int int_set_rsa_md_name(EVP_PKEY_CTX *ctx, /* For checks */ int keytype, int optype, /* For EVP_PKEY_CTX_set_params() */ const char *mdkey, const char *mdname, const char *propkey, const char *mdprops) { OSSL_PARAM params[3], *p = params; if (ctx == NULL || mdname == NULL || (ctx->operation & optype) == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* If key type not RSA return error */ switch (keytype) { case -1: if (!EVP_PKEY_CTX_is_a(ctx, "RSA") && !EVP_PKEY_CTX_is_a(ctx, "RSA-PSS")) return -1; break; default: if (!EVP_PKEY_CTX_is_a(ctx, evp_pkey_type2name(keytype))) return -1; break; } /* Cast away the const. This is read only so should be safe */ *p++ = OSSL_PARAM_construct_utf8_string(mdkey, (char *)mdname, 0); if (evp_pkey_ctx_is_provided(ctx) && mdprops != NULL) { /* Cast away the const. This is read only so should be safe */ *p++ = OSSL_PARAM_construct_utf8_string(propkey, (char *)mdprops, 0); } *p++ = OSSL_PARAM_construct_end(); return evp_pkey_ctx_set_params_strict(ctx, params); } /* Helpers to set or get diverse hash algorithm names */ static int int_get_rsa_md_name(EVP_PKEY_CTX *ctx, /* For checks */ int keytype, int optype, /* For EVP_PKEY_CTX_get_params() */ const char *mdkey, char *mdname, size_t mdnamesize) { OSSL_PARAM params[2], *p = params; if (ctx == NULL || mdname == NULL || (ctx->operation & optype) == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* If key type not RSA return error */ switch (keytype) { case -1: if (!EVP_PKEY_CTX_is_a(ctx, "RSA") && !EVP_PKEY_CTX_is_a(ctx, "RSA-PSS")) return -1; break; default: if (!EVP_PKEY_CTX_is_a(ctx, evp_pkey_type2name(keytype))) return -1; break; } /* Cast away the const. This is read only so should be safe */ *p++ = OSSL_PARAM_construct_utf8_string(mdkey, (char *)mdname, mdnamesize); *p++ = OSSL_PARAM_construct_end(); return evp_pkey_ctx_get_params_strict(ctx, params); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_rsa_padding(EVP_PKEY_CTX *ctx, int pad_mode) { return RSA_pkey_ctx_ctrl(ctx, -1, EVP_PKEY_CTRL_RSA_PADDING, pad_mode, NULL); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_get_rsa_padding(EVP_PKEY_CTX *ctx, int *pad_mode) { return RSA_pkey_ctx_ctrl(ctx, -1, EVP_PKEY_CTRL_GET_RSA_PADDING, 0, pad_mode); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_rsa_pss_keygen_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_MD, 0, (void *)(md)); } int EVP_PKEY_CTX_set_rsa_pss_keygen_md_name(EVP_PKEY_CTX *ctx, const char *mdname, const char *mdprops) { return int_set_rsa_md_name(ctx, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, OSSL_PKEY_PARAM_RSA_DIGEST, mdname, OSSL_PKEY_PARAM_RSA_DIGEST_PROPS, mdprops); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { /* If key type not RSA return error */ if (!EVP_PKEY_CTX_is_a(ctx, "RSA")) return -1; return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_OAEP_MD, 0, (void *)(md)); } int EVP_PKEY_CTX_set_rsa_oaep_md_name(EVP_PKEY_CTX *ctx, const char *mdname, const char *mdprops) { return int_set_rsa_md_name(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, mdname, OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST_PROPS, mdprops); } int EVP_PKEY_CTX_get_rsa_oaep_md_name(EVP_PKEY_CTX *ctx, char *name, size_t namesize) { return int_get_rsa_md_name(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, name, namesize); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_get_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD **md) { /* If key type not RSA return error */ if (!EVP_PKEY_CTX_is_a(ctx, "RSA")) return -1; return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_GET_RSA_OAEP_MD, 0, (void *)md); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { return RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_MGF1_MD, 0, (void *)(md)); } int EVP_PKEY_CTX_set_rsa_mgf1_md_name(EVP_PKEY_CTX *ctx, const char *mdname, const char *mdprops) { return int_set_rsa_md_name(ctx, -1, EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG, OSSL_PKEY_PARAM_MGF1_DIGEST, mdname, OSSL_PKEY_PARAM_MGF1_PROPERTIES, mdprops); } int EVP_PKEY_CTX_get_rsa_mgf1_md_name(EVP_PKEY_CTX *ctx, char *name, size_t namesize) { return int_get_rsa_md_name(ctx, -1, EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG, OSSL_PKEY_PARAM_MGF1_DIGEST, name, namesize); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_MGF1_MD, 0, (void *)(md)); } int EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md_name(EVP_PKEY_CTX *ctx, const char *mdname) { return int_set_rsa_md_name(ctx, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, OSSL_PKEY_PARAM_MGF1_DIGEST, mdname, NULL, NULL); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_get_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD **md) { return RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_GET_RSA_MGF1_MD, 0, (void *)(md)); } int EVP_PKEY_CTX_set0_rsa_oaep_label(EVP_PKEY_CTX *ctx, void *label, int llen) { OSSL_PARAM rsa_params[2], *p = rsa_params; const char *empty = ""; /* * Needed as we swap label with empty if it is NULL, and label is * freed at the end of this function. */ void *plabel = label; int ret; if (ctx == NULL || !EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* If key type not RSA return error */ if (!EVP_PKEY_CTX_is_a(ctx, "RSA")) return -1; /* Accept NULL for backward compatibility */ if (label == NULL && llen == 0) plabel = (void *)empty; /* Cast away the const. This is read only so should be safe */ *p++ = OSSL_PARAM_construct_octet_string(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, (void *)plabel, (size_t)llen); *p++ = OSSL_PARAM_construct_end(); ret = evp_pkey_ctx_set_params_strict(ctx, rsa_params); if (ret <= 0) return ret; /* Ownership is supposed to be transferred to the callee. */ OPENSSL_free(label); return 1; } int EVP_PKEY_CTX_get0_rsa_oaep_label(EVP_PKEY_CTX *ctx, unsigned char **label) { OSSL_PARAM rsa_params[2], *p = rsa_params; size_t labellen; if (ctx == NULL || !EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* If key type not RSA return error */ if (!EVP_PKEY_CTX_is_a(ctx, "RSA")) return -1; *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, (void **)label, 0); *p++ = OSSL_PARAM_construct_end(); if (!EVP_PKEY_CTX_get_params(ctx, rsa_params)) return -1; labellen = rsa_params[0].return_size; if (labellen > INT_MAX) return -1; return (int)labellen; } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_set_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int saltlen) { /* * For some reason, the optype was set to this: * * EVP_PKEY_OP_SIGN|EVP_PKEY_OP_VERIFY * * However, we do use RSA-PSS with the whole gamut of diverse signature * and verification operations, so the optype gets upgraded to this: * * EVP_PKEY_OP_TYPE_SIG */ return RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_RSA_PSS_SALTLEN, saltlen, NULL); } /* * This one is currently implemented as an EVP_PKEY_CTX_ctrl() wrapper, * simply because that's easier. */ int EVP_PKEY_CTX_get_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int *saltlen) { /* * Because of circumstances, the optype is updated from: * * EVP_PKEY_OP_SIGN|EVP_PKEY_OP_VERIFY * * to: * * EVP_PKEY_OP_TYPE_SIG */ return RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN, 0, saltlen); } int EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen(EVP_PKEY_CTX *ctx, int saltlen) { OSSL_PARAM pad_params[2], *p = pad_params; 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 (!EVP_PKEY_CTX_is_a(ctx, "RSA-PSS")) return -1; *p++ = OSSL_PARAM_construct_int(OSSL_SIGNATURE_PARAM_PSS_SALTLEN, &saltlen); *p++ = OSSL_PARAM_construct_end(); return evp_pkey_ctx_set_params_strict(ctx, pad_params); } int EVP_PKEY_CTX_set_rsa_keygen_bits(EVP_PKEY_CTX *ctx, int bits) { OSSL_PARAM params[2], *p = params; size_t bits2 = bits; if (ctx == NULL || !EVP_PKEY_CTX_IS_GEN_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* If key type not RSA return error */ if (!EVP_PKEY_CTX_is_a(ctx, "RSA") && !EVP_PKEY_CTX_is_a(ctx, "RSA-PSS")) return -1; *p++ = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_RSA_BITS, &bits2); *p++ = OSSL_PARAM_construct_end(); return evp_pkey_ctx_set_params_strict(ctx, params); } int EVP_PKEY_CTX_set_rsa_keygen_pubexp(EVP_PKEY_CTX *ctx, BIGNUM *pubexp) { int ret = RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, 0, pubexp); /* * Satisfy memory semantics for pre-3.0 callers of * EVP_PKEY_CTX_set_rsa_keygen_pubexp(): their expectation is that input * pubexp BIGNUM becomes managed by the EVP_PKEY_CTX on success. */ if (ret > 0 && evp_pkey_ctx_is_provided(ctx)) { BN_free(ctx->rsa_pubexp); ctx->rsa_pubexp = pubexp; } return ret; } int EVP_PKEY_CTX_set1_rsa_keygen_pubexp(EVP_PKEY_CTX *ctx, BIGNUM *pubexp) { int ret = 0; /* * When we're dealing with a provider, there's no need to duplicate * pubexp, as it gets copied when transforming to an OSSL_PARAM anyway. */ if (evp_pkey_ctx_is_legacy(ctx)) { pubexp = BN_dup(pubexp); if (pubexp == NULL) return 0; } ret = EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, 0, pubexp); if (evp_pkey_ctx_is_legacy(ctx) && ret <= 0) BN_free(pubexp); return ret; } int EVP_PKEY_CTX_set_rsa_keygen_primes(EVP_PKEY_CTX *ctx, int primes) { OSSL_PARAM params[2], *p = params; size_t primes2 = primes; if (ctx == NULL || !EVP_PKEY_CTX_IS_GEN_OP(ctx)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } /* If key type not RSA return error */ if (!EVP_PKEY_CTX_is_a(ctx, "RSA") && !EVP_PKEY_CTX_is_a(ctx, "RSA-PSS")) return -1; *p++ = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_RSA_PRIMES, &primes2); *p++ = OSSL_PARAM_construct_end(); return evp_pkey_ctx_set_params_strict(ctx, params); } #endif
./openssl/crypto/rc2/rc2ofb64.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 */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc2.h> #include "rc2_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 RC2_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, RC2_KEY *schedule, unsigned char *ivec, int *num) { register unsigned long v0, v1, t; register int n = *num; register long l = length; unsigned char d[8]; register char *dp; unsigned long ti[2]; unsigned char *iv; int save = 0; iv = (unsigned char *)ivec; c2l(iv, v0); c2l(iv, v1); ti[0] = v0; ti[1] = v1; dp = (char *)d; l2c(v0, dp); l2c(v1, dp); while (l--) { if (n == 0) { RC2_encrypt((unsigned long *)ti, schedule); dp = (char *)d; t = ti[0]; l2c(t, dp); t = ti[1]; l2c(t, dp); save++; } *(out++) = *(in++) ^ d[n]; n = (n + 1) & 0x07; } if (save) { v0 = ti[0]; v1 = ti[1]; iv = (unsigned char *)ivec; l2c(v0, iv); l2c(v1, iv); } t = v0 = v1 = ti[0] = ti[1] = 0; *num = n; }
./openssl/crypto/rc2/rc2_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 */ #undef c2l #define c2l(c,l) (l =((unsigned long)(*((c)++))) , \ l|=((unsigned long)(*((c)++)))<< 8L, \ l|=((unsigned long)(*((c)++)))<<16L, \ l|=((unsigned long)(*((c)++)))<<24L) /* NOTE - c is not incremented as per c2l */ #undef c2ln #define c2ln(c,l1,l2,n) { \ c+=n; \ l1=l2=0; \ switch (n) { \ case 8: l2 =((unsigned long)(*(--(c))))<<24L; \ /* fall through */ \ case 7: l2|=((unsigned long)(*(--(c))))<<16L; \ /* fall through */ \ case 6: l2|=((unsigned long)(*(--(c))))<< 8L; \ /* fall through */ \ case 5: l2|=((unsigned long)(*(--(c)))); \ /* fall through */ \ case 4: l1 =((unsigned long)(*(--(c))))<<24L; \ /* fall through */ \ case 3: l1|=((unsigned long)(*(--(c))))<<16L; \ /* fall through */ \ case 2: l1|=((unsigned long)(*(--(c))))<< 8L; \ /* fall through */ \ case 1: l1|=((unsigned long)(*(--(c)))); \ } \ } #undef l2c #define l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \ *((c)++)=(unsigned char)(((l)>>16L)&0xff), \ *((c)++)=(unsigned char)(((l)>>24L)&0xff)) /* NOTE - c is not incremented as per l2c */ #undef l2cn #define l2cn(l1,l2,c,n) { \ c+=n; \ switch (n) { \ case 8: *(--(c))=(unsigned char)(((l2)>>24L)&0xff); \ /* fall through */ \ case 7: *(--(c))=(unsigned char)(((l2)>>16L)&0xff); \ /* fall through */ \ case 6: *(--(c))=(unsigned char)(((l2)>> 8L)&0xff); \ /* fall through */ \ case 5: *(--(c))=(unsigned char)(((l2) )&0xff); \ /* fall through */ \ case 4: *(--(c))=(unsigned char)(((l1)>>24L)&0xff); \ /* fall through */ \ case 3: *(--(c))=(unsigned char)(((l1)>>16L)&0xff); \ /* fall through */ \ case 2: *(--(c))=(unsigned char)(((l1)>> 8L)&0xff); \ /* fall through */ \ case 1: *(--(c))=(unsigned char)(((l1) )&0xff); \ } \ }
./openssl/crypto/rc2/rc2_cbc.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 */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc2.h> #include "rc2_local.h" void RC2_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, RC2_KEY *ks, unsigned char *iv, int encrypt) { register unsigned long tin0, tin1; register unsigned long tout0, tout1, xor0, xor1; register long l = length; unsigned long tin[2]; if (encrypt) { c2l(iv, tout0); c2l(iv, tout1); iv -= 8; for (l -= 8; l >= 0; l -= 8) { c2l(in, tin0); c2l(in, tin1); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; RC2_encrypt(tin, ks); tout0 = tin[0]; l2c(tout0, out); tout1 = tin[1]; l2c(tout1, out); } if (l != -8) { c2ln(in, tin0, tin1, l + 8); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; RC2_encrypt(tin, ks); tout0 = tin[0]; l2c(tout0, out); tout1 = tin[1]; l2c(tout1, out); } l2c(tout0, iv); l2c(tout1, iv); } else { c2l(iv, xor0); c2l(iv, xor1); iv -= 8; for (l -= 8; l >= 0; l -= 8) { c2l(in, tin0); tin[0] = tin0; c2l(in, tin1); tin[1] = tin1; RC2_decrypt(tin, ks); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2c(tout0, out); l2c(tout1, out); xor0 = tin0; xor1 = tin1; } if (l != -8) { c2l(in, tin0); tin[0] = tin0; c2l(in, tin1); tin[1] = tin1; RC2_decrypt(tin, ks); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2cn(tout0, tout1, out, l + 8); xor0 = tin0; xor1 = tin1; } l2c(xor0, iv); l2c(xor1, iv); } tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; tin[0] = tin[1] = 0; } void RC2_encrypt(unsigned long *d, RC2_KEY *key) { int i, n; register RC2_INT *p0, *p1; register RC2_INT x0, x1, x2, x3, t; unsigned long l; l = d[0]; x0 = (RC2_INT) l & 0xffff; x1 = (RC2_INT) (l >> 16L); l = d[1]; x2 = (RC2_INT) l & 0xffff; x3 = (RC2_INT) (l >> 16L); n = 3; i = 5; p0 = p1 = &(key->data[0]); for (;;) { t = (x0 + (x1 & ~x3) + (x2 & x3) + *(p0++)) & 0xffff; x0 = (t << 1) | (t >> 15); t = (x1 + (x2 & ~x0) + (x3 & x0) + *(p0++)) & 0xffff; x1 = (t << 2) | (t >> 14); t = (x2 + (x3 & ~x1) + (x0 & x1) + *(p0++)) & 0xffff; x2 = (t << 3) | (t >> 13); t = (x3 + (x0 & ~x2) + (x1 & x2) + *(p0++)) & 0xffff; x3 = (t << 5) | (t >> 11); if (--i == 0) { if (--n == 0) break; i = (n == 2) ? 6 : 5; x0 += p1[x3 & 0x3f]; x1 += p1[x0 & 0x3f]; x2 += p1[x1 & 0x3f]; x3 += p1[x2 & 0x3f]; } } d[0] = (unsigned long)(x0 & 0xffff) | ((unsigned long)(x1 & 0xffff) << 16L); d[1] = (unsigned long)(x2 & 0xffff) | ((unsigned long)(x3 & 0xffff) << 16L); } void RC2_decrypt(unsigned long *d, RC2_KEY *key) { int i, n; register RC2_INT *p0, *p1; register RC2_INT x0, x1, x2, x3, t; unsigned long l; l = d[0]; x0 = (RC2_INT) l & 0xffff; x1 = (RC2_INT) (l >> 16L); l = d[1]; x2 = (RC2_INT) l & 0xffff; x3 = (RC2_INT) (l >> 16L); n = 3; i = 5; p0 = &(key->data[63]); p1 = &(key->data[0]); for (;;) { t = ((x3 << 11) | (x3 >> 5)) & 0xffff; x3 = (t - (x0 & ~x2) - (x1 & x2) - *(p0--)) & 0xffff; t = ((x2 << 13) | (x2 >> 3)) & 0xffff; x2 = (t - (x3 & ~x1) - (x0 & x1) - *(p0--)) & 0xffff; t = ((x1 << 14) | (x1 >> 2)) & 0xffff; x1 = (t - (x2 & ~x0) - (x3 & x0) - *(p0--)) & 0xffff; t = ((x0 << 15) | (x0 >> 1)) & 0xffff; x0 = (t - (x1 & ~x3) - (x2 & x3) - *(p0--)) & 0xffff; if (--i == 0) { if (--n == 0) break; i = (n == 2) ? 6 : 5; x3 = (x3 - p1[x2 & 0x3f]) & 0xffff; x2 = (x2 - p1[x1 & 0x3f]) & 0xffff; x1 = (x1 - p1[x0 & 0x3f]) & 0xffff; x0 = (x0 - p1[x3 & 0x3f]) & 0xffff; } } d[0] = (unsigned long)(x0 & 0xffff) | ((unsigned long)(x1 & 0xffff) << 16L); d[1] = (unsigned long)(x2 & 0xffff) | ((unsigned long)(x3 & 0xffff) << 16L); }
./openssl/crypto/rc2/rc2cfb64.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 */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc2.h> #include "rc2_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 RC2_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, RC2_KEY *schedule, unsigned char *ivec, int *num, int encrypt) { register unsigned long v0, v1, t; register int n = *num; register long l = length; unsigned long ti[2]; unsigned char *iv, c, cc; iv = (unsigned char *)ivec; if (encrypt) { while (l--) { if (n == 0) { c2l(iv, v0); ti[0] = v0; c2l(iv, v1); ti[1] = v1; RC2_encrypt((unsigned long *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2c(t, iv); t = ti[1]; l2c(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) { c2l(iv, v0); ti[0] = v0; c2l(iv, v1); ti[1] = v1; RC2_encrypt((unsigned long *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2c(t, iv); t = ti[1]; l2c(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/rc2/rc2_skey.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc2.h> #include "rc2_local.h" static const unsigned char key_table[256] = { 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad, }; #if defined(_MSC_VER) && defined(_ARM_) # pragma optimize("g",off) #endif /* * It has come to my attention that there are 2 versions of the RC2 key * schedule. One which is normal, and another which has a hook to use a * reduced key length. BSAFE uses the latter version. What I previously * shipped is the same as specifying 1024 for the 'bits' parameter. Bsafe * uses a version where the bits parameter is the same as len*8 */ void RC2_set_key(RC2_KEY *key, int len, const unsigned char *data, int bits) { int i, j; unsigned char *k; RC2_INT *ki; unsigned int c, d; k = (unsigned char *)&(key->data[0]); *k = 0; /* for if there is a zero length key */ if (len > 128) len = 128; if (bits <= 0) bits = 1024; if (bits > 1024) bits = 1024; for (i = 0; i < len; i++) k[i] = data[i]; /* expand table */ d = k[len - 1]; j = 0; for (i = len; i < 128; i++, j++) { d = key_table[(k[j] + d) & 0xff]; k[i] = d; } /* hmm.... key reduction to 'bits' bits */ j = (bits + 7) >> 3; i = 128 - j; c = (0xff >> (-bits & 0x07)); d = key_table[k[i] & c]; k[i] = d; while (i--) { d = key_table[k[i + j] ^ d]; k[i] = d; } /* copy from bytes into RC2_INT's */ ki = &(key->data[63]); for (i = 127; i >= 0; i -= 2) *(ki--) = ((k[i] << 8) | k[i - 1]) & 0xffff; } #if defined(_MSC_VER) # pragma optimize("",on) #endif
./openssl/crypto/rc2/rc2_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 */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc2.h> #include "rc2_local.h" #include <openssl/opensslv.h> /*- * RC2 as implemented frm a posting from * Newsgroups: sci.crypt * Subject: Specification for Ron Rivests Cipher No.2 * Message-ID: <4fk39f$f70@net.auckland.ac.nz> * Date: 11 Feb 1996 06:45:03 GMT */ void RC2_ecb_encrypt(const unsigned char *in, unsigned char *out, RC2_KEY *ks, int encrypt) { unsigned long l, d[2]; c2l(in, l); d[0] = l; c2l(in, l); d[1] = l; if (encrypt) RC2_encrypt(d, ks); else RC2_decrypt(d, ks); l = d[0]; l2c(l, out); l = d[1]; l2c(l, out); l = d[0] = d[1] = 0; }
./openssl/crypto/ct/ct_oct.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifdef OPENSSL_NO_CT # error "CT is disabled" #endif #include <limits.h> #include <string.h> #include <openssl/asn1.h> #include <openssl/buffer.h> #include <openssl/ct.h> #include <openssl/err.h> #include "ct_local.h" int o2i_SCT_signature(SCT *sct, const unsigned char **in, size_t len) { size_t siglen; size_t len_remaining = len; const unsigned char *p; if (sct->version != SCT_VERSION_V1) { ERR_raise(ERR_LIB_CT, CT_R_UNSUPPORTED_VERSION); return -1; } /* * digitally-signed struct header: (1 byte) Hash algorithm (1 byte) * Signature algorithm (2 bytes + ?) Signature * * This explicitly rejects empty signatures: they're invalid for * all supported algorithms. */ if (len <= 4) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID_SIGNATURE); return -1; } p = *in; /* Get hash and signature algorithm */ sct->hash_alg = *p++; sct->sig_alg = *p++; if (SCT_get_signature_nid(sct) == NID_undef) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID_SIGNATURE); return -1; } /* Retrieve signature and check it is consistent with the buffer length */ n2s(p, siglen); len_remaining -= (p - *in); if (siglen > len_remaining) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID_SIGNATURE); return -1; } if (SCT_set1_signature(sct, p, siglen) != 1) return -1; len_remaining -= siglen; *in = p + siglen; return len - len_remaining; } SCT *o2i_SCT(SCT **psct, const unsigned char **in, size_t len) { SCT *sct = NULL; const unsigned char *p; if (len == 0 || len > MAX_SCT_SIZE) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID); goto err; } if ((sct = SCT_new()) == NULL) goto err; p = *in; sct->version = *p; if (sct->version == SCT_VERSION_V1) { int sig_len; size_t len2; /*- * Fixed-length header: * struct { * Version sct_version; (1 byte) * log_id id; (32 bytes) * uint64 timestamp; (8 bytes) * CtExtensions extensions; (2 bytes + ?) * } */ if (len < 43) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID); goto err; } len -= 43; p++; sct->log_id = OPENSSL_memdup(p, CT_V1_HASHLEN); if (sct->log_id == NULL) goto err; sct->log_id_len = CT_V1_HASHLEN; p += CT_V1_HASHLEN; n2l8(p, sct->timestamp); n2s(p, len2); if (len < len2) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID); goto err; } if (len2 > 0) { sct->ext = OPENSSL_memdup(p, len2); if (sct->ext == NULL) goto err; } sct->ext_len = len2; p += len2; len -= len2; sig_len = o2i_SCT_signature(sct, &p, len); if (sig_len <= 0) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID); goto err; } len -= sig_len; *in = p + len; } else { /* If not V1 just cache encoding */ sct->sct = OPENSSL_memdup(p, len); if (sct->sct == NULL) goto err; sct->sct_len = len; *in = p + len; } if (psct != NULL) { SCT_free(*psct); *psct = sct; } return sct; err: SCT_free(sct); return NULL; } int i2o_SCT_signature(const SCT *sct, unsigned char **out) { size_t len; unsigned char *p = NULL, *pstart = NULL; if (!SCT_signature_is_complete(sct)) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID_SIGNATURE); goto err; } if (sct->version != SCT_VERSION_V1) { ERR_raise(ERR_LIB_CT, CT_R_UNSUPPORTED_VERSION); goto err; } /* * (1 byte) Hash algorithm * (1 byte) Signature algorithm * (2 bytes + ?) Signature */ len = 4 + sct->sig_len; if (out != NULL) { if (*out != NULL) { p = *out; *out += len; } else { pstart = p = OPENSSL_malloc(len); if (p == NULL) goto err; *out = p; } *p++ = sct->hash_alg; *p++ = sct->sig_alg; s2n(sct->sig_len, p); memcpy(p, sct->sig, sct->sig_len); } return len; err: OPENSSL_free(pstart); return -1; } int i2o_SCT(const SCT *sct, unsigned char **out) { size_t len; unsigned char *p = NULL, *pstart = NULL; if (!SCT_is_complete(sct)) { ERR_raise(ERR_LIB_CT, CT_R_SCT_NOT_SET); goto err; } /* * Fixed-length header: struct { (1 byte) Version sct_version; (32 bytes) * log_id id; (8 bytes) uint64 timestamp; (2 bytes + ?) CtExtensions * extensions; (1 byte) Hash algorithm (1 byte) Signature algorithm (2 * bytes + ?) Signature */ if (sct->version == SCT_VERSION_V1) len = 43 + sct->ext_len + 4 + sct->sig_len; else len = sct->sct_len; if (out == NULL) return len; if (*out != NULL) { p = *out; *out += len; } else { pstart = p = OPENSSL_malloc(len); if (p == NULL) goto err; *out = p; } if (sct->version == SCT_VERSION_V1) { *p++ = sct->version; memcpy(p, sct->log_id, CT_V1_HASHLEN); p += CT_V1_HASHLEN; l2n8(sct->timestamp, p); s2n(sct->ext_len, p); if (sct->ext_len > 0) { memcpy(p, sct->ext, sct->ext_len); p += sct->ext_len; } if (i2o_SCT_signature(sct, &p) <= 0) goto err; } else { memcpy(p, sct->sct, len); } return len; err: OPENSSL_free(pstart); return -1; } STACK_OF(SCT) *o2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, size_t len) { STACK_OF(SCT) *sk = NULL; size_t list_len, sct_len; if (len < 2 || len > MAX_SCT_LIST_SIZE) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LIST_INVALID); return NULL; } n2s(*pp, list_len); if (list_len != len - 2) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LIST_INVALID); return NULL; } if (a == NULL || *a == NULL) { sk = sk_SCT_new_null(); if (sk == NULL) return NULL; } else { SCT *sct; /* Use the given stack, but empty it first. */ sk = *a; while ((sct = sk_SCT_pop(sk)) != NULL) SCT_free(sct); } while (list_len > 0) { SCT *sct; if (list_len < 2) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LIST_INVALID); goto err; } n2s(*pp, sct_len); list_len -= 2; if (sct_len == 0 || sct_len > list_len) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LIST_INVALID); goto err; } list_len -= sct_len; if ((sct = o2i_SCT(NULL, pp, sct_len)) == NULL) goto err; if (!sk_SCT_push(sk, sct)) { SCT_free(sct); goto err; } } if (a != NULL && *a == NULL) *a = sk; return sk; err: if (a == NULL || *a == NULL) SCT_LIST_free(sk); return NULL; } int i2o_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **pp) { int len, sct_len, i, is_pp_new = 0; size_t len2; unsigned char *p = NULL, *p2; if (pp != NULL) { if (*pp == NULL) { if ((len = i2o_SCT_LIST(a, NULL)) == -1) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LIST_INVALID); return -1; } if ((*pp = OPENSSL_malloc(len)) == NULL) return -1; is_pp_new = 1; } p = *pp + 2; } len2 = 2; for (i = 0; i < sk_SCT_num(a); i++) { if (pp != NULL) { p2 = p; p += 2; if ((sct_len = i2o_SCT(sk_SCT_value(a, i), &p)) == -1) goto err; s2n(sct_len, p2); } else { if ((sct_len = i2o_SCT(sk_SCT_value(a, i), NULL)) == -1) goto err; } len2 += 2 + sct_len; } if (len2 > MAX_SCT_LIST_SIZE) goto err; if (pp != NULL) { p = *pp; s2n(len2 - 2, p); if (!is_pp_new) *pp += len2; } return len2; err: if (is_pp_new) { OPENSSL_free(*pp); *pp = NULL; } return -1; } STACK_OF(SCT) *d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, long len) { ASN1_OCTET_STRING *oct = NULL; STACK_OF(SCT) *sk = NULL; const unsigned char *p; p = *pp; if (d2i_ASN1_OCTET_STRING(&oct, &p, len) == NULL) return NULL; p = oct->data; if ((sk = o2i_SCT_LIST(a, &p, oct->length)) != NULL) *pp += len; ASN1_OCTET_STRING_free(oct); return sk; } int i2d_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **out) { ASN1_OCTET_STRING oct; int len; oct.data = NULL; if ((oct.length = i2o_SCT_LIST(a, &oct.data)) == -1) return -1; len = i2d_ASN1_OCTET_STRING(&oct, out); OPENSSL_free(oct.data); return len; }
./openssl/crypto/ct/ct_vfy.c
/* * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/ct.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #include "ct_local.h" typedef enum sct_signature_type_t { SIGNATURE_TYPE_NOT_SET = -1, SIGNATURE_TYPE_CERT_TIMESTAMP, SIGNATURE_TYPE_TREE_HASH } SCT_SIGNATURE_TYPE; /* * Update encoding for SCT signature verification/generation to supplied * EVP_MD_CTX. */ static int sct_ctx_update(EVP_MD_CTX *ctx, const SCT_CTX *sctx, const SCT *sct) { unsigned char tmpbuf[12]; unsigned char *p, *der; size_t derlen; /*+ * digitally-signed struct { * (1 byte) Version sct_version; * (1 byte) SignatureType signature_type = certificate_timestamp; * (8 bytes) uint64 timestamp; * (2 bytes) LogEntryType entry_type; * (? bytes) select(entry_type) { * case x509_entry: ASN.1Cert; * case precert_entry: PreCert; * } signed_entry; * (2 bytes + sct->ext_len) CtExtensions extensions; * } */ if (sct->entry_type == CT_LOG_ENTRY_TYPE_NOT_SET) return 0; if (sct->entry_type == CT_LOG_ENTRY_TYPE_PRECERT && sctx->ihash == NULL) return 0; p = tmpbuf; *p++ = sct->version; *p++ = SIGNATURE_TYPE_CERT_TIMESTAMP; l2n8(sct->timestamp, p); s2n(sct->entry_type, p); if (!EVP_DigestUpdate(ctx, tmpbuf, p - tmpbuf)) return 0; if (sct->entry_type == CT_LOG_ENTRY_TYPE_X509) { der = sctx->certder; derlen = sctx->certderlen; } else { if (!EVP_DigestUpdate(ctx, sctx->ihash, sctx->ihashlen)) return 0; der = sctx->preder; derlen = sctx->prederlen; } /* If no encoding available, fatal error */ if (der == NULL) return 0; /* Include length first */ p = tmpbuf; l2n3(derlen, p); if (!EVP_DigestUpdate(ctx, tmpbuf, 3)) return 0; if (!EVP_DigestUpdate(ctx, der, derlen)) return 0; /* Add any extensions */ p = tmpbuf; s2n(sct->ext_len, p); if (!EVP_DigestUpdate(ctx, tmpbuf, 2)) return 0; if (sct->ext_len && !EVP_DigestUpdate(ctx, sct->ext, sct->ext_len)) return 0; return 1; } int SCT_CTX_verify(const SCT_CTX *sctx, const SCT *sct) { EVP_MD_CTX *ctx = NULL; int ret = 0; if (!SCT_is_complete(sct) || sctx->pkey == NULL || sct->entry_type == CT_LOG_ENTRY_TYPE_NOT_SET || (sct->entry_type == CT_LOG_ENTRY_TYPE_PRECERT && sctx->ihash == NULL)) { ERR_raise(ERR_LIB_CT, CT_R_SCT_NOT_SET); return 0; } if (sct->version != SCT_VERSION_V1) { ERR_raise(ERR_LIB_CT, CT_R_SCT_UNSUPPORTED_VERSION); return 0; } if (sct->log_id_len != sctx->pkeyhashlen || memcmp(sct->log_id, sctx->pkeyhash, sctx->pkeyhashlen) != 0) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LOG_ID_MISMATCH); return 0; } if (sct->timestamp > sctx->epoch_time_in_ms) { ERR_raise(ERR_LIB_CT, CT_R_SCT_FUTURE_TIMESTAMP); return 0; } ctx = EVP_MD_CTX_new(); if (ctx == NULL) goto end; if (!EVP_DigestVerifyInit_ex(ctx, NULL, "SHA2-256", sctx->libctx, sctx->propq, sctx->pkey, NULL)) goto end; if (!sct_ctx_update(ctx, sctx, sct)) goto end; /* Verify signature */ ret = EVP_DigestVerifyFinal(ctx, sct->sig, sct->sig_len); /* If ret < 0 some other error: fall through without setting error */ if (ret == 0) ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID_SIGNATURE); end: EVP_MD_CTX_free(ctx); return ret; }
./openssl/crypto/ct/ct_x509v3.c
/* * Copyright 2016-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 */ #ifdef OPENSSL_NO_CT # error "CT is disabled" #endif #include "ct_local.h" static char *i2s_poison(const X509V3_EXT_METHOD *method, void *val) { return OPENSSL_strdup("NULL"); } static void *s2i_poison(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str) { return ASN1_NULL_new(); } static int i2r_SCT_LIST(X509V3_EXT_METHOD *method, STACK_OF(SCT) *sct_list, BIO *out, int indent) { SCT_LIST_print(sct_list, out, indent, "\n", NULL); return 1; } static int set_sct_list_source(STACK_OF(SCT) *s, sct_source_t source) { if (s != NULL) { int i; for (i = 0; i < sk_SCT_num(s); i++) { int res = SCT_set_source(sk_SCT_value(s, i), source); if (res != 1) { return 0; } } } return 1; } static STACK_OF(SCT) *x509_ext_d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, long len) { STACK_OF(SCT) *s = d2i_SCT_LIST(a, pp, len); if (set_sct_list_source(s, SCT_SOURCE_X509V3_EXTENSION) != 1) { SCT_LIST_free(s); *a = NULL; return NULL; } return s; } static STACK_OF(SCT) *ocsp_ext_d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, long len) { STACK_OF(SCT) *s = d2i_SCT_LIST(a, pp, len); if (set_sct_list_source(s, SCT_SOURCE_OCSP_STAPLED_RESPONSE) != 1) { SCT_LIST_free(s); *a = NULL; return NULL; } return s; } /* Handlers for X509v3/OCSP Certificate Transparency extensions */ const X509V3_EXT_METHOD ossl_v3_ct_scts[3] = { /* X509v3 extension in certificates that contains SCTs */ { NID_ct_precert_scts, 0, NULL, NULL, (X509V3_EXT_FREE)SCT_LIST_free, (X509V3_EXT_D2I)x509_ext_d2i_SCT_LIST, (X509V3_EXT_I2D)i2d_SCT_LIST, NULL, NULL, NULL, NULL, (X509V3_EXT_I2R)i2r_SCT_LIST, NULL, NULL }, /* X509v3 extension to mark a certificate as a pre-certificate */ { NID_ct_precert_poison, 0, ASN1_ITEM_ref(ASN1_NULL), NULL, NULL, NULL, NULL, i2s_poison, s2i_poison, NULL, NULL, NULL, NULL, NULL }, /* OCSP extension that contains SCTs */ { NID_ct_cert_scts, 0, NULL, 0, (X509V3_EXT_FREE)SCT_LIST_free, (X509V3_EXT_D2I)ocsp_ext_d2i_SCT_LIST, (X509V3_EXT_I2D)i2d_SCT_LIST, NULL, NULL, NULL, NULL, (X509V3_EXT_I2R)i2r_SCT_LIST, NULL, NULL }, };
./openssl/crypto/ct/ct_policy.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifdef OPENSSL_NO_CT # error "CT is disabled" #endif #include <openssl/ct.h> #include <openssl/err.h> #include "internal/time.h" #include "ct_local.h" /* * Number of seconds in the future that an SCT timestamp can be, by default, * without being considered invalid. This is added to time() when setting a * default value for CT_POLICY_EVAL_CTX.epoch_time_in_ms. * It can be overridden by calling CT_POLICY_EVAL_CTX_set_time(). */ static const time_t SCT_CLOCK_DRIFT_TOLERANCE = 300; CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq) { CT_POLICY_EVAL_CTX *ctx = OPENSSL_zalloc(sizeof(CT_POLICY_EVAL_CTX)); OSSL_TIME now; if (ctx == NULL) return NULL; ctx->libctx = libctx; if (propq != NULL) { ctx->propq = OPENSSL_strdup(propq); if (ctx->propq == NULL) { OPENSSL_free(ctx); return NULL; } } now = ossl_time_add(ossl_time_now(), ossl_seconds2time(SCT_CLOCK_DRIFT_TOLERANCE)); ctx->epoch_time_in_ms = ossl_time2ms(now); return ctx; } CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new(void) { return CT_POLICY_EVAL_CTX_new_ex(NULL, NULL); } void CT_POLICY_EVAL_CTX_free(CT_POLICY_EVAL_CTX *ctx) { if (ctx == NULL) return; X509_free(ctx->cert); X509_free(ctx->issuer); OPENSSL_free(ctx->propq); OPENSSL_free(ctx); } int CT_POLICY_EVAL_CTX_set1_cert(CT_POLICY_EVAL_CTX *ctx, X509 *cert) { if (!X509_up_ref(cert)) return 0; ctx->cert = cert; return 1; } int CT_POLICY_EVAL_CTX_set1_issuer(CT_POLICY_EVAL_CTX *ctx, X509 *issuer) { if (!X509_up_ref(issuer)) return 0; ctx->issuer = issuer; return 1; } void CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(CT_POLICY_EVAL_CTX *ctx, CTLOG_STORE *log_store) { ctx->log_store = log_store; } void CT_POLICY_EVAL_CTX_set_time(CT_POLICY_EVAL_CTX *ctx, uint64_t time_in_ms) { ctx->epoch_time_in_ms = time_in_ms; } X509* CT_POLICY_EVAL_CTX_get0_cert(const CT_POLICY_EVAL_CTX *ctx) { return ctx->cert; } X509* CT_POLICY_EVAL_CTX_get0_issuer(const CT_POLICY_EVAL_CTX *ctx) { return ctx->issuer; } const CTLOG_STORE *CT_POLICY_EVAL_CTX_get0_log_store(const CT_POLICY_EVAL_CTX *ctx) { return ctx->log_store; } uint64_t CT_POLICY_EVAL_CTX_get_time(const CT_POLICY_EVAL_CTX *ctx) { return ctx->epoch_time_in_ms; }
./openssl/crypto/ct/ct_sct_ctx.c
/* * Copyright 2016-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 */ #ifdef OPENSSL_NO_CT # error "CT is disabled" #endif #include <stddef.h> #include <string.h> #include <openssl/err.h> #include <openssl/obj_mac.h> #include <openssl/x509.h> #include "ct_local.h" SCT_CTX *SCT_CTX_new(OSSL_LIB_CTX *libctx, const char *propq) { SCT_CTX *sctx = OPENSSL_zalloc(sizeof(*sctx)); if (sctx == NULL) return NULL; sctx->libctx = libctx; if (propq != NULL) { sctx->propq = OPENSSL_strdup(propq); if (sctx->propq == NULL) { OPENSSL_free(sctx); return NULL; } } return sctx; } void SCT_CTX_free(SCT_CTX *sctx) { if (sctx == NULL) return; EVP_PKEY_free(sctx->pkey); OPENSSL_free(sctx->pkeyhash); OPENSSL_free(sctx->ihash); OPENSSL_free(sctx->certder); OPENSSL_free(sctx->preder); OPENSSL_free(sctx->propq); OPENSSL_free(sctx); } /* * Finds the index of the first extension with the given NID in cert. * If there is more than one extension with that NID, *is_duplicated is set to * 1, otherwise 0 (unless it is NULL). */ static int ct_x509_get_ext(X509 *cert, int nid, int *is_duplicated) { int ret = X509_get_ext_by_NID(cert, nid, -1); if (is_duplicated != NULL) *is_duplicated = ret >= 0 && X509_get_ext_by_NID(cert, nid, ret) >= 0; return ret; } /* * Modifies a certificate by deleting extensions and copying the issuer and * AKID from the presigner certificate, if necessary. * Returns 1 on success, 0 otherwise. */ __owur static int ct_x509_cert_fixup(X509 *cert, X509 *presigner) { int preidx, certidx; int pre_akid_ext_is_dup, cert_akid_ext_is_dup; if (presigner == NULL) return 1; preidx = ct_x509_get_ext(presigner, NID_authority_key_identifier, &pre_akid_ext_is_dup); certidx = ct_x509_get_ext(cert, NID_authority_key_identifier, &cert_akid_ext_is_dup); /* An error occurred whilst searching for the extension */ if (preidx < -1 || certidx < -1) return 0; /* Invalid certificate if they contain duplicate extensions */ if (pre_akid_ext_is_dup || cert_akid_ext_is_dup) return 0; /* AKID must be present in both certificate or absent in both */ if (preidx >= 0 && certidx == -1) return 0; if (preidx == -1 && certidx >= 0) return 0; /* Copy issuer name */ if (!X509_set_issuer_name(cert, X509_get_issuer_name(presigner))) return 0; if (preidx != -1) { /* Retrieve and copy AKID encoding */ X509_EXTENSION *preext = X509_get_ext(presigner, preidx); X509_EXTENSION *certext = X509_get_ext(cert, certidx); ASN1_OCTET_STRING *preextdata; /* Should never happen */ if (preext == NULL || certext == NULL) return 0; preextdata = X509_EXTENSION_get_data(preext); if (preextdata == NULL || !X509_EXTENSION_set_data(certext, preextdata)) return 0; } return 1; } int SCT_CTX_set1_cert(SCT_CTX *sctx, X509 *cert, X509 *presigner) { unsigned char *certder = NULL, *preder = NULL; X509 *pretmp = NULL; int certderlen = 0, prederlen = 0; int idx = -1; int poison_ext_is_dup, sct_ext_is_dup; int poison_idx = ct_x509_get_ext(cert, NID_ct_precert_poison, &poison_ext_is_dup); /* Duplicate poison extensions are present - error */ if (poison_ext_is_dup) goto err; /* If *cert doesn't have a poison extension, it isn't a precert */ if (poison_idx == -1) { /* cert isn't a precert, so we shouldn't have a presigner */ if (presigner != NULL) goto err; certderlen = i2d_X509(cert, &certder); if (certderlen < 0) goto err; } /* See if cert has a precert SCTs extension */ idx = ct_x509_get_ext(cert, NID_ct_precert_scts, &sct_ext_is_dup); /* Duplicate SCT extensions are present - error */ if (sct_ext_is_dup) goto err; if (idx >= 0 && poison_idx >= 0) { /* * cert can't both contain SCTs (i.e. have an SCT extension) and be a * precert (i.e. have a poison extension). */ goto err; } if (idx == -1) { idx = poison_idx; } /* * If either a poison or SCT extension is present, remove it before encoding * cert. This, along with ct_x509_cert_fixup(), gets a TBSCertificate (see * RFC5280) from cert, which is what the CT log signed when it produced the * SCT. */ if (idx >= 0) { /* Take a copy of certificate so we don't modify passed version */ pretmp = X509_dup(cert); if (pretmp == NULL) goto err; X509_EXTENSION_free(X509_delete_ext(pretmp, idx)); if (!ct_x509_cert_fixup(pretmp, presigner)) goto err; prederlen = i2d_re_X509_tbs(pretmp, &preder); if (prederlen <= 0) goto err; } X509_free(pretmp); OPENSSL_free(sctx->certder); sctx->certder = certder; sctx->certderlen = certderlen; OPENSSL_free(sctx->preder); sctx->preder = preder; sctx->prederlen = prederlen; return 1; err: OPENSSL_free(certder); OPENSSL_free(preder); X509_free(pretmp); return 0; } __owur static int ct_public_key_hash(SCT_CTX *sctx, X509_PUBKEY *pkey, unsigned char **hash, size_t *hash_len) { int ret = 0; unsigned char *md = NULL, *der = NULL; int der_len; unsigned int md_len; EVP_MD *sha256 = EVP_MD_fetch(sctx->libctx, "SHA2-256", sctx->propq); if (sha256 == NULL) goto err; /* Reuse buffer if possible */ if (*hash != NULL && *hash_len >= SHA256_DIGEST_LENGTH) { md = *hash; } else { md = OPENSSL_malloc(SHA256_DIGEST_LENGTH); if (md == NULL) goto err; } /* Calculate key hash */ der_len = i2d_X509_PUBKEY(pkey, &der); if (der_len <= 0) goto err; if (!EVP_Digest(der, der_len, md, &md_len, sha256, NULL)) goto err; if (md != *hash) { OPENSSL_free(*hash); *hash = md; *hash_len = SHA256_DIGEST_LENGTH; } md = NULL; ret = 1; err: EVP_MD_free(sha256); OPENSSL_free(md); OPENSSL_free(der); return ret; } int SCT_CTX_set1_issuer(SCT_CTX *sctx, const X509 *issuer) { return SCT_CTX_set1_issuer_pubkey(sctx, X509_get_X509_PUBKEY(issuer)); } int SCT_CTX_set1_issuer_pubkey(SCT_CTX *sctx, X509_PUBKEY *pubkey) { return ct_public_key_hash(sctx, pubkey, &sctx->ihash, &sctx->ihashlen); } int SCT_CTX_set1_pubkey(SCT_CTX *sctx, X509_PUBKEY *pubkey) { EVP_PKEY *pkey = X509_PUBKEY_get(pubkey); if (pkey == NULL) return 0; if (!ct_public_key_hash(sctx, pubkey, &sctx->pkeyhash, &sctx->pkeyhashlen)) { EVP_PKEY_free(pkey); return 0; } EVP_PKEY_free(sctx->pkey); sctx->pkey = pkey; return 1; } void SCT_CTX_set_time(SCT_CTX *sctx, uint64_t time_in_ms) { sctx->epoch_time_in_ms = time_in_ms; }
./openssl/crypto/ct/ct_log.c
/* * Copyright 2016-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 <string.h> #include <openssl/conf.h> #include <openssl/ct.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/safestack.h> #include "internal/cryptlib.h" /* * Information about a CT log server. */ struct ctlog_st { OSSL_LIB_CTX *libctx; char *propq; char *name; uint8_t log_id[CT_V1_HASHLEN]; EVP_PKEY *public_key; }; /* * A store for multiple CTLOG instances. * It takes ownership of any CTLOG instances added to it. */ struct ctlog_store_st { OSSL_LIB_CTX *libctx; char *propq; STACK_OF(CTLOG) *logs; }; /* The context when loading a CT log list from a CONF file. */ typedef struct ctlog_store_load_ctx_st { CTLOG_STORE *log_store; CONF *conf; size_t invalid_log_entries; } CTLOG_STORE_LOAD_CTX; /* * Creates an empty context for loading a CT log store. * It should be populated before use. */ static CTLOG_STORE_LOAD_CTX *ctlog_store_load_ctx_new(void); /* * Deletes a CT log store load context. * Does not delete any of the fields. */ static void ctlog_store_load_ctx_free(CTLOG_STORE_LOAD_CTX* ctx); static CTLOG_STORE_LOAD_CTX *ctlog_store_load_ctx_new(void) { CTLOG_STORE_LOAD_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); return ctx; } static void ctlog_store_load_ctx_free(CTLOG_STORE_LOAD_CTX* ctx) { OPENSSL_free(ctx); } /* Converts a log's public key into a SHA256 log ID */ static int ct_v1_log_id_from_pkey(CTLOG *log, EVP_PKEY *pkey) { int ret = 0; unsigned char *pkey_der = NULL; int pkey_der_len = i2d_PUBKEY(pkey, &pkey_der); unsigned int len; EVP_MD *sha256 = NULL; if (pkey_der_len <= 0) { ERR_raise(ERR_LIB_CT, CT_R_LOG_KEY_INVALID); goto err; } sha256 = EVP_MD_fetch(log->libctx, "SHA2-256", log->propq); if (sha256 == NULL) { ERR_raise(ERR_LIB_CT, ERR_R_EVP_LIB); goto err; } ret = EVP_Digest(pkey_der, pkey_der_len, log->log_id, &len, sha256, NULL); err: EVP_MD_free(sha256); OPENSSL_free(pkey_der); return ret; } CTLOG_STORE *CTLOG_STORE_new_ex(OSSL_LIB_CTX *libctx, const char *propq) { CTLOG_STORE *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->libctx = libctx; if (propq != NULL) { ret->propq = OPENSSL_strdup(propq); if (ret->propq == NULL) goto err; } ret->logs = sk_CTLOG_new_null(); if (ret->logs == NULL) { ERR_raise(ERR_LIB_CT, ERR_R_CRYPTO_LIB); goto err; } return ret; err: CTLOG_STORE_free(ret); return NULL; } CTLOG_STORE *CTLOG_STORE_new(void) { return CTLOG_STORE_new_ex(NULL, NULL); } void CTLOG_STORE_free(CTLOG_STORE *store) { if (store != NULL) { OPENSSL_free(store->propq); sk_CTLOG_pop_free(store->logs, CTLOG_free); OPENSSL_free(store); } } static int ctlog_new_from_conf(CTLOG_STORE *store, CTLOG **ct_log, const CONF *conf, const char *section) { const char *description = NCONF_get_string(conf, section, "description"); char *pkey_base64; if (description == NULL) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_MISSING_DESCRIPTION); return 0; } pkey_base64 = NCONF_get_string(conf, section, "key"); if (pkey_base64 == NULL) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_MISSING_KEY); return 0; } return CTLOG_new_from_base64_ex(ct_log, pkey_base64, description, store->libctx, store->propq); } int CTLOG_STORE_load_default_file(CTLOG_STORE *store) { const char *fpath = ossl_safe_getenv(CTLOG_FILE_EVP); if (fpath == NULL) fpath = CTLOG_FILE; return CTLOG_STORE_load_file(store, fpath); } /* * Called by CONF_parse_list, which stops if this returns <= 0, * Otherwise, one bad log entry would stop loading of any of * the following log entries. * It may stop parsing and returns -1 on any internal (malloc) error. */ static int ctlog_store_load_log(const char *log_name, int log_name_len, void *arg) { CTLOG_STORE_LOAD_CTX *load_ctx = arg; CTLOG *ct_log = NULL; /* log_name may not be null-terminated, so fix that before using it */ char *tmp; int ret = 0; /* log_name will be NULL for empty list entries */ if (log_name == NULL) return 1; tmp = OPENSSL_strndup(log_name, log_name_len); if (tmp == NULL) return -1; ret = ctlog_new_from_conf(load_ctx->log_store, &ct_log, load_ctx->conf, tmp); OPENSSL_free(tmp); if (ret < 0) { /* Propagate any internal error */ return ret; } if (ret == 0) { /* If we can't load this log, record that fact and skip it */ ++load_ctx->invalid_log_entries; return 1; } if (!sk_CTLOG_push(load_ctx->log_store->logs, ct_log)) { CTLOG_free(ct_log); ERR_raise(ERR_LIB_CT, ERR_R_CRYPTO_LIB); return -1; } return 1; } int CTLOG_STORE_load_file(CTLOG_STORE *store, const char *file) { int ret = 0; char *enabled_logs; CTLOG_STORE_LOAD_CTX* load_ctx = ctlog_store_load_ctx_new(); if (load_ctx == NULL) return 0; load_ctx->log_store = store; load_ctx->conf = NCONF_new(NULL); if (load_ctx->conf == NULL) goto end; if (NCONF_load(load_ctx->conf, file, NULL) <= 0) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID); goto end; } enabled_logs = NCONF_get_string(load_ctx->conf, NULL, "enabled_logs"); if (enabled_logs == NULL) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID); goto end; } if (!CONF_parse_list(enabled_logs, ',', 1, ctlog_store_load_log, load_ctx) || load_ctx->invalid_log_entries > 0) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID); goto end; } ret = 1; end: NCONF_free(load_ctx->conf); ctlog_store_load_ctx_free(load_ctx); return ret; } /* * Initialize a new CTLOG object. * Takes ownership of the public key. * Copies the name. */ CTLOG *CTLOG_new_ex(EVP_PKEY *public_key, const char *name, OSSL_LIB_CTX *libctx, const char *propq) { CTLOG *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->libctx = libctx; if (propq != NULL) { ret->propq = OPENSSL_strdup(propq); if (ret->propq == NULL) goto err; } ret->name = OPENSSL_strdup(name); if (ret->name == NULL) goto err; if (ct_v1_log_id_from_pkey(ret, public_key) != 1) goto err; ret->public_key = public_key; return ret; err: CTLOG_free(ret); return NULL; } CTLOG *CTLOG_new(EVP_PKEY *public_key, const char *name) { return CTLOG_new_ex(public_key, name, NULL, NULL); } /* Frees CT log and associated structures */ void CTLOG_free(CTLOG *log) { if (log != NULL) { OPENSSL_free(log->name); EVP_PKEY_free(log->public_key); OPENSSL_free(log->propq); OPENSSL_free(log); } } const char *CTLOG_get0_name(const CTLOG *log) { return log->name; } void CTLOG_get0_log_id(const CTLOG *log, const uint8_t **log_id, size_t *log_id_len) { *log_id = log->log_id; *log_id_len = CT_V1_HASHLEN; } EVP_PKEY *CTLOG_get0_public_key(const CTLOG *log) { return log->public_key; } /* * Given a log ID, finds the matching log. * Returns NULL if no match found. */ const CTLOG *CTLOG_STORE_get0_log_by_id(const CTLOG_STORE *store, const uint8_t *log_id, size_t log_id_len) { int i; for (i = 0; i < sk_CTLOG_num(store->logs); ++i) { const CTLOG *log = sk_CTLOG_value(store->logs, i); if (memcmp(log->log_id, log_id, log_id_len) == 0) return log; } return NULL; }
./openssl/crypto/ct/ct_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/cterr.h> #include "crypto/cterr.h" #ifndef OPENSSL_NO_CT # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA CT_str_reasons[] = { {ERR_PACK(ERR_LIB_CT, 0, CT_R_BASE64_DECODE_ERROR), "base64 decode error"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_INVALID_LOG_ID_LENGTH), "invalid log id length"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_INVALID), "log conf invalid"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_INVALID_KEY), "log conf invalid key"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_MISSING_DESCRIPTION), "log conf missing description"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_MISSING_KEY), "log conf missing key"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_KEY_INVALID), "log key invalid"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_FUTURE_TIMESTAMP), "sct future timestamp"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_INVALID), "sct invalid"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_INVALID_SIGNATURE), "sct invalid signature"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_LIST_INVALID), "sct list invalid"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_LOG_ID_MISMATCH), "sct log id mismatch"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_NOT_SET), "sct not set"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_UNSUPPORTED_VERSION), "sct unsupported version"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_UNRECOGNIZED_SIGNATURE_NID), "unrecognized signature nid"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_UNSUPPORTED_ENTRY_TYPE), "unsupported entry type"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_UNSUPPORTED_VERSION), "unsupported version"}, {0, NULL} }; # endif int ossl_err_load_CT_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(CT_str_reasons[0].error) == NULL) ERR_load_strings_const(CT_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
./openssl/crypto/ct/ct_local.h
/* * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stddef.h> #include <openssl/ct.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/safestack.h> /* * From RFC6962: opaque SerializedSCT<1..2^16-1>; struct { SerializedSCT * sct_list <1..2^16-1>; } SignedCertificateTimestampList; */ # define MAX_SCT_SIZE 65535 # define MAX_SCT_LIST_SIZE MAX_SCT_SIZE /* * Macros to read and write integers in network-byte order. */ #define n2s(c,s) ((s=(((unsigned int)((c)[0]))<< 8)| \ (((unsigned int)((c)[1])) )),c+=2) #define s2n(s,c) ((c[0]=(unsigned char)(((s)>> 8)&0xff), \ c[1]=(unsigned char)(((s) )&0xff)),c+=2) #define l2n3(l,c) ((c[0]=(unsigned char)(((l)>>16)&0xff), \ c[1]=(unsigned char)(((l)>> 8)&0xff), \ c[2]=(unsigned char)(((l) )&0xff)),c+=3) #define n2l8(c,l) (l =((uint64_t)(*((c)++)))<<56, \ l|=((uint64_t)(*((c)++)))<<48, \ l|=((uint64_t)(*((c)++)))<<40, \ l|=((uint64_t)(*((c)++)))<<32, \ l|=((uint64_t)(*((c)++)))<<24, \ l|=((uint64_t)(*((c)++)))<<16, \ l|=((uint64_t)(*((c)++)))<< 8, \ l|=((uint64_t)(*((c)++)))) #define l2n8(l,c) (*((c)++)=(unsigned char)(((l)>>56)&0xff), \ *((c)++)=(unsigned char)(((l)>>48)&0xff), \ *((c)++)=(unsigned char)(((l)>>40)&0xff), \ *((c)++)=(unsigned char)(((l)>>32)&0xff), \ *((c)++)=(unsigned char)(((l)>>24)&0xff), \ *((c)++)=(unsigned char)(((l)>>16)&0xff), \ *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ *((c)++)=(unsigned char)(((l) )&0xff)) /* Signed Certificate Timestamp */ struct sct_st { sct_version_t version; /* If version is not SCT_VERSION_V1, this contains the encoded SCT */ unsigned char *sct; size_t sct_len; /* If version is SCT_VERSION_V1, fields below contain components of the SCT */ unsigned char *log_id; size_t log_id_len; /* * Note, we cannot distinguish between an unset timestamp, and one * that is set to 0. However since CT didn't exist in 1970, no real * SCT should ever be set as such. */ uint64_t timestamp; unsigned char *ext; size_t ext_len; unsigned char hash_alg; unsigned char sig_alg; unsigned char *sig; size_t sig_len; /* Log entry type */ ct_log_entry_type_t entry_type; /* Where this SCT was found, e.g. certificate, OCSP response, etc. */ sct_source_t source; /* The result of the last attempt to validate this SCT. */ sct_validation_status_t validation_status; }; /* Miscellaneous data that is useful when verifying an SCT */ struct sct_ctx_st { /* Public key */ EVP_PKEY *pkey; /* Hash of public key */ unsigned char *pkeyhash; size_t pkeyhashlen; /* For pre-certificate: issuer public key hash */ unsigned char *ihash; size_t ihashlen; /* certificate encoding */ unsigned char *certder; size_t certderlen; /* pre-certificate encoding */ unsigned char *preder; size_t prederlen; /* milliseconds since epoch (to check that the SCT isn't from the future) */ uint64_t epoch_time_in_ms; OSSL_LIB_CTX *libctx; char *propq; }; /* Context when evaluating whether a Certificate Transparency policy is met */ struct ct_policy_eval_ctx_st { X509 *cert; X509 *issuer; CTLOG_STORE *log_store; /* milliseconds since epoch (to check that SCTs aren't from the future) */ uint64_t epoch_time_in_ms; OSSL_LIB_CTX *libctx; char *propq; }; /* * Creates a new context for verifying an SCT. */ SCT_CTX *SCT_CTX_new(OSSL_LIB_CTX *ctx, const char *propq); /* * Deletes an SCT verification context. */ void SCT_CTX_free(SCT_CTX *sctx); /* * Sets the certificate that the SCT was created for. * If *cert does not have a poison extension, presigner must be NULL. * If *cert does not have a poison extension, it may have a single SCT * (NID_ct_precert_scts) extension. * If either *cert or *presigner have an AKID (NID_authority_key_identifier) * extension, both must have one. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_cert(SCT_CTX *sctx, X509 *cert, X509 *presigner); /* * Sets the issuer of the certificate that the SCT was created for. * This is just a convenience method to save extracting the public key and * calling SCT_CTX_set1_issuer_pubkey(). * Issuer must not be NULL. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_issuer(SCT_CTX *sctx, const X509 *issuer); /* * Sets the public key of the issuer of the certificate that the SCT was created * for. * The public key must not be NULL. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_issuer_pubkey(SCT_CTX *sctx, X509_PUBKEY *pubkey); /* * Sets the public key of the CT log that the SCT is from. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_pubkey(SCT_CTX *sctx, X509_PUBKEY *pubkey); /* * Sets the time to evaluate the SCT against, in milliseconds since the Unix * epoch. If the SCT's timestamp is after this time, it will be interpreted as * having been issued in the future. RFC6962 states that "TLS clients MUST * reject SCTs whose timestamp is in the future", so an SCT will not validate * in this case. */ void SCT_CTX_set_time(SCT_CTX *sctx, uint64_t time_in_ms); /* * Verifies an SCT with the given context. * Returns 1 if the SCT verifies successfully; any other value indicates * failure. See EVP_DigestVerifyFinal() for the meaning of those values. */ __owur int SCT_CTX_verify(const SCT_CTX *sctx, const SCT *sct); /* * Does this SCT have the minimum fields populated to be usable? * Returns 1 if so, 0 otherwise. */ __owur int SCT_is_complete(const SCT *sct); /* * Does this SCT have the signature-related fields populated? * Returns 1 if so, 0 otherwise. * This checks that the signature and hash algorithms are set to supported * values and that the signature field is set. */ __owur int SCT_signature_is_complete(const SCT *sct); /* * Serialize (to TLS format) an |sct| signature and write it to |out|. * If |out| is null, no signature will be output but the length will be returned. * If |out| points to a null pointer, a string will be allocated to hold the * TLS-format signature. It is the responsibility of the caller to free it. * If |out| points to an allocated string, the signature will be written to it. * The length of the signature in TLS format will be returned. */ __owur int i2o_SCT_signature(const SCT *sct, unsigned char **out); /* * Parses an SCT signature in TLS format and populates the |sct| with it. * |in| should be a pointer to a string containing the TLS-format signature. * |in| will be advanced to the end of the signature if parsing succeeds. * |len| should be the length of the signature in |in|. * Returns the number of bytes parsed, or a negative integer if an error occurs. * If an error occurs, the SCT's signature NID may be updated whilst the * signature field itself remains unset. */ __owur int o2i_SCT_signature(SCT *sct, const unsigned char **in, size_t len); /* * Handlers for Certificate Transparency X509v3/OCSP extensions */ extern const X509V3_EXT_METHOD ossl_v3_ct_scts[3];
./openssl/crypto/ct/ct_b64.c
/* * Copyright 2016-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 <limits.h> #include <string.h> #include <openssl/ct.h> #include <openssl/err.h> #include <openssl/evp.h> #include "ct_local.h" /* * Decodes the base64 string |in| into |out|. * A new string will be malloc'd and assigned to |out|. This will be owned by * the caller. Do not provide a pre-allocated string in |out|. */ static int ct_base64_decode(const char *in, unsigned char **out) { size_t inlen = strlen(in); int outlen, i; unsigned char *outbuf = NULL; if (inlen == 0) { *out = NULL; return 0; } outlen = (inlen / 4) * 3; outbuf = OPENSSL_malloc(outlen); if (outbuf == NULL) goto err; outlen = EVP_DecodeBlock(outbuf, (unsigned char *)in, inlen); if (outlen < 0) { ERR_raise(ERR_LIB_CT, CT_R_BASE64_DECODE_ERROR); goto err; } /* Subtract padding bytes from |outlen|. Any more than 2 is malformed. */ i = 0; while (in[--inlen] == '=') { --outlen; if (++i > 2) goto err; } *out = outbuf; return outlen; err: OPENSSL_free(outbuf); return -1; } SCT *SCT_new_from_base64(unsigned char version, const char *logid_base64, ct_log_entry_type_t entry_type, uint64_t timestamp, const char *extensions_base64, const char *signature_base64) { SCT *sct = SCT_new(); unsigned char *dec = NULL; const unsigned char* p = NULL; int declen; if (sct == NULL) { ERR_raise(ERR_LIB_CT, ERR_R_CT_LIB); return NULL; } /* * RFC6962 section 4.1 says we "MUST NOT expect this to be 0", but we * can only construct SCT versions that have been defined. */ if (!SCT_set_version(sct, version)) { ERR_raise(ERR_LIB_CT, CT_R_SCT_UNSUPPORTED_VERSION); goto err; } declen = ct_base64_decode(logid_base64, &dec); if (declen < 0) { ERR_raise(ERR_LIB_CT, X509_R_BASE64_DECODE_ERROR); goto err; } if (!SCT_set0_log_id(sct, dec, declen)) goto err; dec = NULL; declen = ct_base64_decode(extensions_base64, &dec); if (declen < 0) { ERR_raise(ERR_LIB_CT, X509_R_BASE64_DECODE_ERROR); goto err; } SCT_set0_extensions(sct, dec, declen); dec = NULL; declen = ct_base64_decode(signature_base64, &dec); if (declen < 0) { ERR_raise(ERR_LIB_CT, X509_R_BASE64_DECODE_ERROR); goto err; } p = dec; if (o2i_SCT_signature(sct, &p, declen) <= 0) goto err; OPENSSL_free(dec); dec = NULL; SCT_set_timestamp(sct, timestamp); if (!SCT_set_log_entry_type(sct, entry_type)) goto err; return sct; err: OPENSSL_free(dec); SCT_free(sct); return NULL; } /* * Allocate, build and returns a new |ct_log| from input |pkey_base64| * It returns 1 on success, * 0 on decoding failure, or invalid parameter if any * -1 on internal (malloc) failure */ int CTLOG_new_from_base64_ex(CTLOG **ct_log, const char *pkey_base64, const char *name, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char *pkey_der = NULL; int pkey_der_len; const unsigned char *p; EVP_PKEY *pkey = NULL; if (ct_log == NULL) { ERR_raise(ERR_LIB_CT, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } pkey_der_len = ct_base64_decode(pkey_base64, &pkey_der); if (pkey_der_len < 0) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID_KEY); return 0; } p = pkey_der; pkey = d2i_PUBKEY_ex(NULL, &p, pkey_der_len, libctx, propq); OPENSSL_free(pkey_der); if (pkey == NULL) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID_KEY); return 0; } *ct_log = CTLOG_new_ex(pkey, name, libctx, propq); if (*ct_log == NULL) { EVP_PKEY_free(pkey); return 0; } return 1; } int CTLOG_new_from_base64(CTLOG **ct_log, const char *pkey_base64, const char *name) { return CTLOG_new_from_base64_ex(ct_log, pkey_base64, name, NULL, NULL); }
./openssl/crypto/ct/ct_sct.c
/* * Copyright 2016-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 */ #ifdef OPENSSL_NO_CT # error "CT disabled" #endif #include <openssl/ct.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/tls1.h> #include <openssl/x509.h> #include "ct_local.h" SCT *SCT_new(void) { SCT *sct = OPENSSL_zalloc(sizeof(*sct)); if (sct == NULL) return NULL; sct->entry_type = CT_LOG_ENTRY_TYPE_NOT_SET; sct->version = SCT_VERSION_NOT_SET; return sct; } void SCT_free(SCT *sct) { if (sct == NULL) return; OPENSSL_free(sct->log_id); OPENSSL_free(sct->ext); OPENSSL_free(sct->sig); OPENSSL_free(sct->sct); OPENSSL_free(sct); } void SCT_LIST_free(STACK_OF(SCT) *a) { sk_SCT_pop_free(a, SCT_free); } int SCT_set_version(SCT *sct, sct_version_t version) { if (version != SCT_VERSION_V1) { ERR_raise(ERR_LIB_CT, CT_R_UNSUPPORTED_VERSION); return 0; } sct->version = version; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; return 1; } int SCT_set_log_entry_type(SCT *sct, ct_log_entry_type_t entry_type) { sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; switch (entry_type) { case CT_LOG_ENTRY_TYPE_X509: case CT_LOG_ENTRY_TYPE_PRECERT: sct->entry_type = entry_type; return 1; case CT_LOG_ENTRY_TYPE_NOT_SET: break; } ERR_raise(ERR_LIB_CT, CT_R_UNSUPPORTED_ENTRY_TYPE); return 0; } int SCT_set0_log_id(SCT *sct, unsigned char *log_id, size_t log_id_len) { if (sct->version == SCT_VERSION_V1 && log_id_len != CT_V1_HASHLEN) { ERR_raise(ERR_LIB_CT, CT_R_INVALID_LOG_ID_LENGTH); return 0; } OPENSSL_free(sct->log_id); sct->log_id = log_id; sct->log_id_len = log_id_len; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; return 1; } int SCT_set1_log_id(SCT *sct, const unsigned char *log_id, size_t log_id_len) { if (sct->version == SCT_VERSION_V1 && log_id_len != CT_V1_HASHLEN) { ERR_raise(ERR_LIB_CT, CT_R_INVALID_LOG_ID_LENGTH); return 0; } OPENSSL_free(sct->log_id); sct->log_id = NULL; sct->log_id_len = 0; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; if (log_id != NULL && log_id_len > 0) { sct->log_id = OPENSSL_memdup(log_id, log_id_len); if (sct->log_id == NULL) return 0; sct->log_id_len = log_id_len; } return 1; } void SCT_set_timestamp(SCT *sct, uint64_t timestamp) { sct->timestamp = timestamp; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; } int SCT_set_signature_nid(SCT *sct, int nid) { switch (nid) { case NID_sha256WithRSAEncryption: sct->hash_alg = TLSEXT_hash_sha256; sct->sig_alg = TLSEXT_signature_rsa; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; return 1; case NID_ecdsa_with_SHA256: sct->hash_alg = TLSEXT_hash_sha256; sct->sig_alg = TLSEXT_signature_ecdsa; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; return 1; default: ERR_raise(ERR_LIB_CT, CT_R_UNRECOGNIZED_SIGNATURE_NID); return 0; } } void SCT_set0_extensions(SCT *sct, unsigned char *ext, size_t ext_len) { OPENSSL_free(sct->ext); sct->ext = ext; sct->ext_len = ext_len; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; } int SCT_set1_extensions(SCT *sct, const unsigned char *ext, size_t ext_len) { OPENSSL_free(sct->ext); sct->ext = NULL; sct->ext_len = 0; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; if (ext != NULL && ext_len > 0) { sct->ext = OPENSSL_memdup(ext, ext_len); if (sct->ext == NULL) return 0; sct->ext_len = ext_len; } return 1; } void SCT_set0_signature(SCT *sct, unsigned char *sig, size_t sig_len) { OPENSSL_free(sct->sig); sct->sig = sig; sct->sig_len = sig_len; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; } int SCT_set1_signature(SCT *sct, const unsigned char *sig, size_t sig_len) { OPENSSL_free(sct->sig); sct->sig = NULL; sct->sig_len = 0; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; if (sig != NULL && sig_len > 0) { sct->sig = OPENSSL_memdup(sig, sig_len); if (sct->sig == NULL) return 0; sct->sig_len = sig_len; } return 1; } sct_version_t SCT_get_version(const SCT *sct) { return sct->version; } ct_log_entry_type_t SCT_get_log_entry_type(const SCT *sct) { return sct->entry_type; } size_t SCT_get0_log_id(const SCT *sct, unsigned char **log_id) { *log_id = sct->log_id; return sct->log_id_len; } uint64_t SCT_get_timestamp(const SCT *sct) { return sct->timestamp; } int SCT_get_signature_nid(const SCT *sct) { if (sct->version == SCT_VERSION_V1) { if (sct->hash_alg == TLSEXT_hash_sha256) { switch (sct->sig_alg) { case TLSEXT_signature_ecdsa: return NID_ecdsa_with_SHA256; case TLSEXT_signature_rsa: return NID_sha256WithRSAEncryption; default: return NID_undef; } } } return NID_undef; } size_t SCT_get0_extensions(const SCT *sct, unsigned char **ext) { *ext = sct->ext; return sct->ext_len; } size_t SCT_get0_signature(const SCT *sct, unsigned char **sig) { *sig = sct->sig; return sct->sig_len; } int SCT_is_complete(const SCT *sct) { switch (sct->version) { case SCT_VERSION_NOT_SET: return 0; case SCT_VERSION_V1: return sct->log_id != NULL && SCT_signature_is_complete(sct); default: return sct->sct != NULL; /* Just need cached encoding */ } } int SCT_signature_is_complete(const SCT *sct) { return SCT_get_signature_nid(sct) != NID_undef && sct->sig != NULL && sct->sig_len > 0; } sct_source_t SCT_get_source(const SCT *sct) { return sct->source; } int SCT_set_source(SCT *sct, sct_source_t source) { sct->source = source; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; switch (source) { case SCT_SOURCE_TLS_EXTENSION: case SCT_SOURCE_OCSP_STAPLED_RESPONSE: return SCT_set_log_entry_type(sct, CT_LOG_ENTRY_TYPE_X509); case SCT_SOURCE_X509V3_EXTENSION: return SCT_set_log_entry_type(sct, CT_LOG_ENTRY_TYPE_PRECERT); case SCT_SOURCE_UNKNOWN: break; } /* if we aren't sure, leave the log entry type alone */ return 1; } sct_validation_status_t SCT_get_validation_status(const SCT *sct) { return sct->validation_status; } int SCT_validate(SCT *sct, const CT_POLICY_EVAL_CTX *ctx) { int is_sct_valid = -1; SCT_CTX *sctx = NULL; X509_PUBKEY *pub = NULL, *log_pkey = NULL; const CTLOG *log; /* * With an unrecognized SCT version we don't know what such an SCT means, * let alone validate one. So we return validation failure (0). */ if (sct->version != SCT_VERSION_V1) { sct->validation_status = SCT_VALIDATION_STATUS_UNKNOWN_VERSION; return 0; } log = CTLOG_STORE_get0_log_by_id(ctx->log_store, sct->log_id, sct->log_id_len); /* Similarly, an SCT from an unknown log also cannot be validated. */ if (log == NULL) { sct->validation_status = SCT_VALIDATION_STATUS_UNKNOWN_LOG; return 0; } sctx = SCT_CTX_new(ctx->libctx, ctx->propq); if (sctx == NULL) goto err; if (X509_PUBKEY_set(&log_pkey, CTLOG_get0_public_key(log)) != 1) goto err; if (SCT_CTX_set1_pubkey(sctx, log_pkey) != 1) goto err; if (SCT_get_log_entry_type(sct) == CT_LOG_ENTRY_TYPE_PRECERT) { EVP_PKEY *issuer_pkey; if (ctx->issuer == NULL) { sct->validation_status = SCT_VALIDATION_STATUS_UNVERIFIED; goto end; } issuer_pkey = X509_get0_pubkey(ctx->issuer); if (X509_PUBKEY_set(&pub, issuer_pkey) != 1) goto err; if (SCT_CTX_set1_issuer_pubkey(sctx, pub) != 1) goto err; } SCT_CTX_set_time(sctx, ctx->epoch_time_in_ms); /* * XXX: Potential for optimization. This repeats some idempotent heavy * lifting on the certificate for each candidate SCT, and appears to not * use any information in the SCT itself, only the certificate is * processed. So it may make more sense to do this just once, perhaps * associated with the shared (by all SCTs) policy eval ctx. * * XXX: Failure here is global (SCT independent) and represents either an * issue with the certificate (e.g. duplicate extensions) or an out of * memory condition. When the certificate is incompatible with CT, we just * mark the SCTs invalid, rather than report a failure to determine the * validation status. That way, callbacks that want to do "soft" SCT * processing will not abort handshakes with false positive internal * errors. Since the function does not distinguish between certificate * issues (peer's fault) and internal problems (out fault) the safe thing * to do is to report a validation failure and let the callback or * application decide what to do. */ if (SCT_CTX_set1_cert(sctx, ctx->cert, NULL) != 1) sct->validation_status = SCT_VALIDATION_STATUS_UNVERIFIED; else sct->validation_status = SCT_CTX_verify(sctx, sct) == 1 ? SCT_VALIDATION_STATUS_VALID : SCT_VALIDATION_STATUS_INVALID; end: is_sct_valid = sct->validation_status == SCT_VALIDATION_STATUS_VALID; err: X509_PUBKEY_free(pub); X509_PUBKEY_free(log_pkey); SCT_CTX_free(sctx); return is_sct_valid; } int SCT_LIST_validate(const STACK_OF(SCT) *scts, CT_POLICY_EVAL_CTX *ctx) { int are_scts_valid = 1; int sct_count = scts != NULL ? sk_SCT_num(scts) : 0; int i; for (i = 0; i < sct_count; ++i) { int is_sct_valid = -1; SCT *sct = sk_SCT_value(scts, i); if (sct == NULL) continue; is_sct_valid = SCT_validate(sct, ctx); if (is_sct_valid < 0) return is_sct_valid; are_scts_valid &= is_sct_valid; } return are_scts_valid; }
./openssl/crypto/ct/ct_prn.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifdef OPENSSL_NO_CT # error "CT is disabled" #endif #include <openssl/asn1.h> #include <openssl/bio.h> #include "ct_local.h" static void SCT_signature_algorithms_print(const SCT *sct, BIO *out) { int nid = SCT_get_signature_nid(sct); if (nid == NID_undef) BIO_printf(out, "%02X%02X", sct->hash_alg, sct->sig_alg); else BIO_printf(out, "%s", OBJ_nid2ln(nid)); } static void timestamp_print(uint64_t timestamp, BIO *out) { ASN1_GENERALIZEDTIME *gen = ASN1_GENERALIZEDTIME_new(); char genstr[20]; if (gen == NULL) return; ASN1_GENERALIZEDTIME_adj(gen, (time_t)0, (int)(timestamp / 86400000), (timestamp % 86400000) / 1000); /* * Note GeneralizedTime from ASN1_GENERALIZETIME_adj is always 15 * characters long with a final Z. Update it with fractional seconds. */ BIO_snprintf(genstr, sizeof(genstr), "%.14s.%03dZ", ASN1_STRING_get0_data(gen), (unsigned int)(timestamp % 1000)); if (ASN1_GENERALIZEDTIME_set_string(gen, genstr)) ASN1_GENERALIZEDTIME_print(out, gen); ASN1_GENERALIZEDTIME_free(gen); } const char *SCT_validation_status_string(const SCT *sct) { switch (SCT_get_validation_status(sct)) { case SCT_VALIDATION_STATUS_NOT_SET: return "not set"; case SCT_VALIDATION_STATUS_UNKNOWN_VERSION: return "unknown version"; case SCT_VALIDATION_STATUS_UNKNOWN_LOG: return "unknown log"; case SCT_VALIDATION_STATUS_UNVERIFIED: return "unverified"; case SCT_VALIDATION_STATUS_INVALID: return "invalid"; case SCT_VALIDATION_STATUS_VALID: return "valid"; } return "unknown status"; } void SCT_print(const SCT *sct, BIO *out, int indent, const CTLOG_STORE *log_store) { const CTLOG *log = NULL; if (log_store != NULL) { log = CTLOG_STORE_get0_log_by_id(log_store, sct->log_id, sct->log_id_len); } BIO_printf(out, "%*sSigned Certificate Timestamp:", indent, ""); BIO_printf(out, "\n%*sVersion : ", indent + 4, ""); if (sct->version != SCT_VERSION_V1) { BIO_printf(out, "unknown\n%*s", indent + 16, ""); BIO_hex_string(out, indent + 16, 16, sct->sct, sct->sct_len); return; } BIO_printf(out, "v1 (0x0)"); if (log != NULL) { BIO_printf(out, "\n%*sLog : %s", indent + 4, "", CTLOG_get0_name(log)); } BIO_printf(out, "\n%*sLog ID : ", indent + 4, ""); BIO_hex_string(out, indent + 16, 16, sct->log_id, sct->log_id_len); BIO_printf(out, "\n%*sTimestamp : ", indent + 4, ""); timestamp_print(sct->timestamp, out); BIO_printf(out, "\n%*sExtensions: ", indent + 4, ""); if (sct->ext_len == 0) BIO_printf(out, "none"); else BIO_hex_string(out, indent + 16, 16, sct->ext, sct->ext_len); BIO_printf(out, "\n%*sSignature : ", indent + 4, ""); SCT_signature_algorithms_print(sct, out); BIO_printf(out, "\n%*s ", indent + 4, ""); BIO_hex_string(out, indent + 16, 16, sct->sig, sct->sig_len); } void SCT_LIST_print(const STACK_OF(SCT) *sct_list, BIO *out, int indent, const char *separator, const CTLOG_STORE *log_store) { int sct_count = sk_SCT_num(sct_list); int i; for (i = 0; i < sct_count; ++i) { SCT *sct = sk_SCT_value(sct_list, i); SCT_print(sct, out, indent, log_store); if (i < sk_SCT_num(sct_list) - 1) BIO_printf(out, "%s", separator); } }
./openssl/crypto/aria/aria.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Copyright (C) 2017 National Security Research Institute. All Rights Reserved. * * Information for ARIA * http://210.104.33.10/ARIA/index-e.html (English) * http://seed.kisa.or.kr/ (Korean) * * Public domain version is distributed above. */ #include <openssl/e_os2.h> #include "crypto/aria.h" #include <assert.h> #include <string.h> #ifndef OPENSSL_SMALL_FOOTPRINT /* Begin macro */ /* rotation */ #define rotl32(v, r) (((uint32_t)(v) << (r)) | ((uint32_t)(v) >> (32 - r))) #define rotr32(v, r) (((uint32_t)(v) >> (r)) | ((uint32_t)(v) << (32 - r))) #define bswap32(v) \ (((v) << 24) ^ ((v) >> 24) ^ \ (((v) & 0x0000ff00) << 8) ^ (((v) & 0x00ff0000) >> 8)) #define GET_U8_BE(X, Y) ((uint8_t)((X) >> ((3 - Y) * 8))) #define GET_U32_BE(X, Y) ( \ ((uint32_t)((const uint8_t *)(X))[Y * 4 ] << 24) ^ \ ((uint32_t)((const uint8_t *)(X))[Y * 4 + 1] << 16) ^ \ ((uint32_t)((const uint8_t *)(X))[Y * 4 + 2] << 8) ^ \ ((uint32_t)((const uint8_t *)(X))[Y * 4 + 3] ) ) #define PUT_U32_BE(DEST, IDX, VAL) \ do { \ ((uint8_t *)(DEST))[IDX * 4 ] = GET_U8_BE(VAL, 0); \ ((uint8_t *)(DEST))[IDX * 4 + 1] = GET_U8_BE(VAL, 1); \ ((uint8_t *)(DEST))[IDX * 4 + 2] = GET_U8_BE(VAL, 2); \ ((uint8_t *)(DEST))[IDX * 4 + 3] = GET_U8_BE(VAL, 3); \ } while(0) #define MAKE_U32(V0, V1, V2, V3) ( \ ((uint32_t)((uint8_t)(V0)) << 24) | \ ((uint32_t)((uint8_t)(V1)) << 16) | \ ((uint32_t)((uint8_t)(V2)) << 8) | \ ((uint32_t)((uint8_t)(V3)) ) ) /* End Macro*/ /* Key Constant * 128bit : 0, 1, 2 * 192bit : 1, 2, 3(0) * 256bit : 2, 3(0), 4(1) */ static const uint32_t Key_RC[5][4] = { { 0x517cc1b7, 0x27220a94, 0xfe13abe8, 0xfa9a6ee0 }, { 0x6db14acc, 0x9e21c820, 0xff28b1d5, 0xef5de2b0 }, { 0xdb92371d, 0x2126e970, 0x03249775, 0x04e8c90e }, { 0x517cc1b7, 0x27220a94, 0xfe13abe8, 0xfa9a6ee0 }, { 0x6db14acc, 0x9e21c820, 0xff28b1d5, 0xef5de2b0 } }; /* 32bit expanded s-box */ static const uint32_t S1[256] = { 0x00636363, 0x007c7c7c, 0x00777777, 0x007b7b7b, 0x00f2f2f2, 0x006b6b6b, 0x006f6f6f, 0x00c5c5c5, 0x00303030, 0x00010101, 0x00676767, 0x002b2b2b, 0x00fefefe, 0x00d7d7d7, 0x00ababab, 0x00767676, 0x00cacaca, 0x00828282, 0x00c9c9c9, 0x007d7d7d, 0x00fafafa, 0x00595959, 0x00474747, 0x00f0f0f0, 0x00adadad, 0x00d4d4d4, 0x00a2a2a2, 0x00afafaf, 0x009c9c9c, 0x00a4a4a4, 0x00727272, 0x00c0c0c0, 0x00b7b7b7, 0x00fdfdfd, 0x00939393, 0x00262626, 0x00363636, 0x003f3f3f, 0x00f7f7f7, 0x00cccccc, 0x00343434, 0x00a5a5a5, 0x00e5e5e5, 0x00f1f1f1, 0x00717171, 0x00d8d8d8, 0x00313131, 0x00151515, 0x00040404, 0x00c7c7c7, 0x00232323, 0x00c3c3c3, 0x00181818, 0x00969696, 0x00050505, 0x009a9a9a, 0x00070707, 0x00121212, 0x00808080, 0x00e2e2e2, 0x00ebebeb, 0x00272727, 0x00b2b2b2, 0x00757575, 0x00090909, 0x00838383, 0x002c2c2c, 0x001a1a1a, 0x001b1b1b, 0x006e6e6e, 0x005a5a5a, 0x00a0a0a0, 0x00525252, 0x003b3b3b, 0x00d6d6d6, 0x00b3b3b3, 0x00292929, 0x00e3e3e3, 0x002f2f2f, 0x00848484, 0x00535353, 0x00d1d1d1, 0x00000000, 0x00ededed, 0x00202020, 0x00fcfcfc, 0x00b1b1b1, 0x005b5b5b, 0x006a6a6a, 0x00cbcbcb, 0x00bebebe, 0x00393939, 0x004a4a4a, 0x004c4c4c, 0x00585858, 0x00cfcfcf, 0x00d0d0d0, 0x00efefef, 0x00aaaaaa, 0x00fbfbfb, 0x00434343, 0x004d4d4d, 0x00333333, 0x00858585, 0x00454545, 0x00f9f9f9, 0x00020202, 0x007f7f7f, 0x00505050, 0x003c3c3c, 0x009f9f9f, 0x00a8a8a8, 0x00515151, 0x00a3a3a3, 0x00404040, 0x008f8f8f, 0x00929292, 0x009d9d9d, 0x00383838, 0x00f5f5f5, 0x00bcbcbc, 0x00b6b6b6, 0x00dadada, 0x00212121, 0x00101010, 0x00ffffff, 0x00f3f3f3, 0x00d2d2d2, 0x00cdcdcd, 0x000c0c0c, 0x00131313, 0x00ececec, 0x005f5f5f, 0x00979797, 0x00444444, 0x00171717, 0x00c4c4c4, 0x00a7a7a7, 0x007e7e7e, 0x003d3d3d, 0x00646464, 0x005d5d5d, 0x00191919, 0x00737373, 0x00606060, 0x00818181, 0x004f4f4f, 0x00dcdcdc, 0x00222222, 0x002a2a2a, 0x00909090, 0x00888888, 0x00464646, 0x00eeeeee, 0x00b8b8b8, 0x00141414, 0x00dedede, 0x005e5e5e, 0x000b0b0b, 0x00dbdbdb, 0x00e0e0e0, 0x00323232, 0x003a3a3a, 0x000a0a0a, 0x00494949, 0x00060606, 0x00242424, 0x005c5c5c, 0x00c2c2c2, 0x00d3d3d3, 0x00acacac, 0x00626262, 0x00919191, 0x00959595, 0x00e4e4e4, 0x00797979, 0x00e7e7e7, 0x00c8c8c8, 0x00373737, 0x006d6d6d, 0x008d8d8d, 0x00d5d5d5, 0x004e4e4e, 0x00a9a9a9, 0x006c6c6c, 0x00565656, 0x00f4f4f4, 0x00eaeaea, 0x00656565, 0x007a7a7a, 0x00aeaeae, 0x00080808, 0x00bababa, 0x00787878, 0x00252525, 0x002e2e2e, 0x001c1c1c, 0x00a6a6a6, 0x00b4b4b4, 0x00c6c6c6, 0x00e8e8e8, 0x00dddddd, 0x00747474, 0x001f1f1f, 0x004b4b4b, 0x00bdbdbd, 0x008b8b8b, 0x008a8a8a, 0x00707070, 0x003e3e3e, 0x00b5b5b5, 0x00666666, 0x00484848, 0x00030303, 0x00f6f6f6, 0x000e0e0e, 0x00616161, 0x00353535, 0x00575757, 0x00b9b9b9, 0x00868686, 0x00c1c1c1, 0x001d1d1d, 0x009e9e9e, 0x00e1e1e1, 0x00f8f8f8, 0x00989898, 0x00111111, 0x00696969, 0x00d9d9d9, 0x008e8e8e, 0x00949494, 0x009b9b9b, 0x001e1e1e, 0x00878787, 0x00e9e9e9, 0x00cecece, 0x00555555, 0x00282828, 0x00dfdfdf, 0x008c8c8c, 0x00a1a1a1, 0x00898989, 0x000d0d0d, 0x00bfbfbf, 0x00e6e6e6, 0x00424242, 0x00686868, 0x00414141, 0x00999999, 0x002d2d2d, 0x000f0f0f, 0x00b0b0b0, 0x00545454, 0x00bbbbbb, 0x00161616 }; static const uint32_t S2[256] = { 0xe200e2e2, 0x4e004e4e, 0x54005454, 0xfc00fcfc, 0x94009494, 0xc200c2c2, 0x4a004a4a, 0xcc00cccc, 0x62006262, 0x0d000d0d, 0x6a006a6a, 0x46004646, 0x3c003c3c, 0x4d004d4d, 0x8b008b8b, 0xd100d1d1, 0x5e005e5e, 0xfa00fafa, 0x64006464, 0xcb00cbcb, 0xb400b4b4, 0x97009797, 0xbe00bebe, 0x2b002b2b, 0xbc00bcbc, 0x77007777, 0x2e002e2e, 0x03000303, 0xd300d3d3, 0x19001919, 0x59005959, 0xc100c1c1, 0x1d001d1d, 0x06000606, 0x41004141, 0x6b006b6b, 0x55005555, 0xf000f0f0, 0x99009999, 0x69006969, 0xea00eaea, 0x9c009c9c, 0x18001818, 0xae00aeae, 0x63006363, 0xdf00dfdf, 0xe700e7e7, 0xbb00bbbb, 0x00000000, 0x73007373, 0x66006666, 0xfb00fbfb, 0x96009696, 0x4c004c4c, 0x85008585, 0xe400e4e4, 0x3a003a3a, 0x09000909, 0x45004545, 0xaa00aaaa, 0x0f000f0f, 0xee00eeee, 0x10001010, 0xeb00ebeb, 0x2d002d2d, 0x7f007f7f, 0xf400f4f4, 0x29002929, 0xac00acac, 0xcf00cfcf, 0xad00adad, 0x91009191, 0x8d008d8d, 0x78007878, 0xc800c8c8, 0x95009595, 0xf900f9f9, 0x2f002f2f, 0xce00cece, 0xcd00cdcd, 0x08000808, 0x7a007a7a, 0x88008888, 0x38003838, 0x5c005c5c, 0x83008383, 0x2a002a2a, 0x28002828, 0x47004747, 0xdb00dbdb, 0xb800b8b8, 0xc700c7c7, 0x93009393, 0xa400a4a4, 0x12001212, 0x53005353, 0xff00ffff, 0x87008787, 0x0e000e0e, 0x31003131, 0x36003636, 0x21002121, 0x58005858, 0x48004848, 0x01000101, 0x8e008e8e, 0x37003737, 0x74007474, 0x32003232, 0xca00caca, 0xe900e9e9, 0xb100b1b1, 0xb700b7b7, 0xab00abab, 0x0c000c0c, 0xd700d7d7, 0xc400c4c4, 0x56005656, 0x42004242, 0x26002626, 0x07000707, 0x98009898, 0x60006060, 0xd900d9d9, 0xb600b6b6, 0xb900b9b9, 0x11001111, 0x40004040, 0xec00ecec, 0x20002020, 0x8c008c8c, 0xbd00bdbd, 0xa000a0a0, 0xc900c9c9, 0x84008484, 0x04000404, 0x49004949, 0x23002323, 0xf100f1f1, 0x4f004f4f, 0x50005050, 0x1f001f1f, 0x13001313, 0xdc00dcdc, 0xd800d8d8, 0xc000c0c0, 0x9e009e9e, 0x57005757, 0xe300e3e3, 0xc300c3c3, 0x7b007b7b, 0x65006565, 0x3b003b3b, 0x02000202, 0x8f008f8f, 0x3e003e3e, 0xe800e8e8, 0x25002525, 0x92009292, 0xe500e5e5, 0x15001515, 0xdd00dddd, 0xfd00fdfd, 0x17001717, 0xa900a9a9, 0xbf00bfbf, 0xd400d4d4, 0x9a009a9a, 0x7e007e7e, 0xc500c5c5, 0x39003939, 0x67006767, 0xfe00fefe, 0x76007676, 0x9d009d9d, 0x43004343, 0xa700a7a7, 0xe100e1e1, 0xd000d0d0, 0xf500f5f5, 0x68006868, 0xf200f2f2, 0x1b001b1b, 0x34003434, 0x70007070, 0x05000505, 0xa300a3a3, 0x8a008a8a, 0xd500d5d5, 0x79007979, 0x86008686, 0xa800a8a8, 0x30003030, 0xc600c6c6, 0x51005151, 0x4b004b4b, 0x1e001e1e, 0xa600a6a6, 0x27002727, 0xf600f6f6, 0x35003535, 0xd200d2d2, 0x6e006e6e, 0x24002424, 0x16001616, 0x82008282, 0x5f005f5f, 0xda00dada, 0xe600e6e6, 0x75007575, 0xa200a2a2, 0xef00efef, 0x2c002c2c, 0xb200b2b2, 0x1c001c1c, 0x9f009f9f, 0x5d005d5d, 0x6f006f6f, 0x80008080, 0x0a000a0a, 0x72007272, 0x44004444, 0x9b009b9b, 0x6c006c6c, 0x90009090, 0x0b000b0b, 0x5b005b5b, 0x33003333, 0x7d007d7d, 0x5a005a5a, 0x52005252, 0xf300f3f3, 0x61006161, 0xa100a1a1, 0xf700f7f7, 0xb000b0b0, 0xd600d6d6, 0x3f003f3f, 0x7c007c7c, 0x6d006d6d, 0xed00eded, 0x14001414, 0xe000e0e0, 0xa500a5a5, 0x3d003d3d, 0x22002222, 0xb300b3b3, 0xf800f8f8, 0x89008989, 0xde00dede, 0x71007171, 0x1a001a1a, 0xaf00afaf, 0xba00baba, 0xb500b5b5, 0x81008181 }; static const uint32_t X1[256] = { 0x52520052, 0x09090009, 0x6a6a006a, 0xd5d500d5, 0x30300030, 0x36360036, 0xa5a500a5, 0x38380038, 0xbfbf00bf, 0x40400040, 0xa3a300a3, 0x9e9e009e, 0x81810081, 0xf3f300f3, 0xd7d700d7, 0xfbfb00fb, 0x7c7c007c, 0xe3e300e3, 0x39390039, 0x82820082, 0x9b9b009b, 0x2f2f002f, 0xffff00ff, 0x87870087, 0x34340034, 0x8e8e008e, 0x43430043, 0x44440044, 0xc4c400c4, 0xdede00de, 0xe9e900e9, 0xcbcb00cb, 0x54540054, 0x7b7b007b, 0x94940094, 0x32320032, 0xa6a600a6, 0xc2c200c2, 0x23230023, 0x3d3d003d, 0xeeee00ee, 0x4c4c004c, 0x95950095, 0x0b0b000b, 0x42420042, 0xfafa00fa, 0xc3c300c3, 0x4e4e004e, 0x08080008, 0x2e2e002e, 0xa1a100a1, 0x66660066, 0x28280028, 0xd9d900d9, 0x24240024, 0xb2b200b2, 0x76760076, 0x5b5b005b, 0xa2a200a2, 0x49490049, 0x6d6d006d, 0x8b8b008b, 0xd1d100d1, 0x25250025, 0x72720072, 0xf8f800f8, 0xf6f600f6, 0x64640064, 0x86860086, 0x68680068, 0x98980098, 0x16160016, 0xd4d400d4, 0xa4a400a4, 0x5c5c005c, 0xcccc00cc, 0x5d5d005d, 0x65650065, 0xb6b600b6, 0x92920092, 0x6c6c006c, 0x70700070, 0x48480048, 0x50500050, 0xfdfd00fd, 0xeded00ed, 0xb9b900b9, 0xdada00da, 0x5e5e005e, 0x15150015, 0x46460046, 0x57570057, 0xa7a700a7, 0x8d8d008d, 0x9d9d009d, 0x84840084, 0x90900090, 0xd8d800d8, 0xabab00ab, 0x00000000, 0x8c8c008c, 0xbcbc00bc, 0xd3d300d3, 0x0a0a000a, 0xf7f700f7, 0xe4e400e4, 0x58580058, 0x05050005, 0xb8b800b8, 0xb3b300b3, 0x45450045, 0x06060006, 0xd0d000d0, 0x2c2c002c, 0x1e1e001e, 0x8f8f008f, 0xcaca00ca, 0x3f3f003f, 0x0f0f000f, 0x02020002, 0xc1c100c1, 0xafaf00af, 0xbdbd00bd, 0x03030003, 0x01010001, 0x13130013, 0x8a8a008a, 0x6b6b006b, 0x3a3a003a, 0x91910091, 0x11110011, 0x41410041, 0x4f4f004f, 0x67670067, 0xdcdc00dc, 0xeaea00ea, 0x97970097, 0xf2f200f2, 0xcfcf00cf, 0xcece00ce, 0xf0f000f0, 0xb4b400b4, 0xe6e600e6, 0x73730073, 0x96960096, 0xacac00ac, 0x74740074, 0x22220022, 0xe7e700e7, 0xadad00ad, 0x35350035, 0x85850085, 0xe2e200e2, 0xf9f900f9, 0x37370037, 0xe8e800e8, 0x1c1c001c, 0x75750075, 0xdfdf00df, 0x6e6e006e, 0x47470047, 0xf1f100f1, 0x1a1a001a, 0x71710071, 0x1d1d001d, 0x29290029, 0xc5c500c5, 0x89890089, 0x6f6f006f, 0xb7b700b7, 0x62620062, 0x0e0e000e, 0xaaaa00aa, 0x18180018, 0xbebe00be, 0x1b1b001b, 0xfcfc00fc, 0x56560056, 0x3e3e003e, 0x4b4b004b, 0xc6c600c6, 0xd2d200d2, 0x79790079, 0x20200020, 0x9a9a009a, 0xdbdb00db, 0xc0c000c0, 0xfefe00fe, 0x78780078, 0xcdcd00cd, 0x5a5a005a, 0xf4f400f4, 0x1f1f001f, 0xdddd00dd, 0xa8a800a8, 0x33330033, 0x88880088, 0x07070007, 0xc7c700c7, 0x31310031, 0xb1b100b1, 0x12120012, 0x10100010, 0x59590059, 0x27270027, 0x80800080, 0xecec00ec, 0x5f5f005f, 0x60600060, 0x51510051, 0x7f7f007f, 0xa9a900a9, 0x19190019, 0xb5b500b5, 0x4a4a004a, 0x0d0d000d, 0x2d2d002d, 0xe5e500e5, 0x7a7a007a, 0x9f9f009f, 0x93930093, 0xc9c900c9, 0x9c9c009c, 0xefef00ef, 0xa0a000a0, 0xe0e000e0, 0x3b3b003b, 0x4d4d004d, 0xaeae00ae, 0x2a2a002a, 0xf5f500f5, 0xb0b000b0, 0xc8c800c8, 0xebeb00eb, 0xbbbb00bb, 0x3c3c003c, 0x83830083, 0x53530053, 0x99990099, 0x61610061, 0x17170017, 0x2b2b002b, 0x04040004, 0x7e7e007e, 0xbaba00ba, 0x77770077, 0xd6d600d6, 0x26260026, 0xe1e100e1, 0x69690069, 0x14140014, 0x63630063, 0x55550055, 0x21210021, 0x0c0c000c, 0x7d7d007d }; static const uint32_t X2[256] = { 0x30303000, 0x68686800, 0x99999900, 0x1b1b1b00, 0x87878700, 0xb9b9b900, 0x21212100, 0x78787800, 0x50505000, 0x39393900, 0xdbdbdb00, 0xe1e1e100, 0x72727200, 0x09090900, 0x62626200, 0x3c3c3c00, 0x3e3e3e00, 0x7e7e7e00, 0x5e5e5e00, 0x8e8e8e00, 0xf1f1f100, 0xa0a0a000, 0xcccccc00, 0xa3a3a300, 0x2a2a2a00, 0x1d1d1d00, 0xfbfbfb00, 0xb6b6b600, 0xd6d6d600, 0x20202000, 0xc4c4c400, 0x8d8d8d00, 0x81818100, 0x65656500, 0xf5f5f500, 0x89898900, 0xcbcbcb00, 0x9d9d9d00, 0x77777700, 0xc6c6c600, 0x57575700, 0x43434300, 0x56565600, 0x17171700, 0xd4d4d400, 0x40404000, 0x1a1a1a00, 0x4d4d4d00, 0xc0c0c000, 0x63636300, 0x6c6c6c00, 0xe3e3e300, 0xb7b7b700, 0xc8c8c800, 0x64646400, 0x6a6a6a00, 0x53535300, 0xaaaaaa00, 0x38383800, 0x98989800, 0x0c0c0c00, 0xf4f4f400, 0x9b9b9b00, 0xededed00, 0x7f7f7f00, 0x22222200, 0x76767600, 0xafafaf00, 0xdddddd00, 0x3a3a3a00, 0x0b0b0b00, 0x58585800, 0x67676700, 0x88888800, 0x06060600, 0xc3c3c300, 0x35353500, 0x0d0d0d00, 0x01010100, 0x8b8b8b00, 0x8c8c8c00, 0xc2c2c200, 0xe6e6e600, 0x5f5f5f00, 0x02020200, 0x24242400, 0x75757500, 0x93939300, 0x66666600, 0x1e1e1e00, 0xe5e5e500, 0xe2e2e200, 0x54545400, 0xd8d8d800, 0x10101000, 0xcecece00, 0x7a7a7a00, 0xe8e8e800, 0x08080800, 0x2c2c2c00, 0x12121200, 0x97979700, 0x32323200, 0xababab00, 0xb4b4b400, 0x27272700, 0x0a0a0a00, 0x23232300, 0xdfdfdf00, 0xefefef00, 0xcacaca00, 0xd9d9d900, 0xb8b8b800, 0xfafafa00, 0xdcdcdc00, 0x31313100, 0x6b6b6b00, 0xd1d1d100, 0xadadad00, 0x19191900, 0x49494900, 0xbdbdbd00, 0x51515100, 0x96969600, 0xeeeeee00, 0xe4e4e400, 0xa8a8a800, 0x41414100, 0xdadada00, 0xffffff00, 0xcdcdcd00, 0x55555500, 0x86868600, 0x36363600, 0xbebebe00, 0x61616100, 0x52525200, 0xf8f8f800, 0xbbbbbb00, 0x0e0e0e00, 0x82828200, 0x48484800, 0x69696900, 0x9a9a9a00, 0xe0e0e000, 0x47474700, 0x9e9e9e00, 0x5c5c5c00, 0x04040400, 0x4b4b4b00, 0x34343400, 0x15151500, 0x79797900, 0x26262600, 0xa7a7a700, 0xdedede00, 0x29292900, 0xaeaeae00, 0x92929200, 0xd7d7d700, 0x84848400, 0xe9e9e900, 0xd2d2d200, 0xbababa00, 0x5d5d5d00, 0xf3f3f300, 0xc5c5c500, 0xb0b0b000, 0xbfbfbf00, 0xa4a4a400, 0x3b3b3b00, 0x71717100, 0x44444400, 0x46464600, 0x2b2b2b00, 0xfcfcfc00, 0xebebeb00, 0x6f6f6f00, 0xd5d5d500, 0xf6f6f600, 0x14141400, 0xfefefe00, 0x7c7c7c00, 0x70707000, 0x5a5a5a00, 0x7d7d7d00, 0xfdfdfd00, 0x2f2f2f00, 0x18181800, 0x83838300, 0x16161600, 0xa5a5a500, 0x91919100, 0x1f1f1f00, 0x05050500, 0x95959500, 0x74747400, 0xa9a9a900, 0xc1c1c100, 0x5b5b5b00, 0x4a4a4a00, 0x85858500, 0x6d6d6d00, 0x13131300, 0x07070700, 0x4f4f4f00, 0x4e4e4e00, 0x45454500, 0xb2b2b200, 0x0f0f0f00, 0xc9c9c900, 0x1c1c1c00, 0xa6a6a600, 0xbcbcbc00, 0xececec00, 0x73737300, 0x90909000, 0x7b7b7b00, 0xcfcfcf00, 0x59595900, 0x8f8f8f00, 0xa1a1a100, 0xf9f9f900, 0x2d2d2d00, 0xf2f2f200, 0xb1b1b100, 0x00000000, 0x94949400, 0x37373700, 0x9f9f9f00, 0xd0d0d000, 0x2e2e2e00, 0x9c9c9c00, 0x6e6e6e00, 0x28282800, 0x3f3f3f00, 0x80808000, 0xf0f0f000, 0x3d3d3d00, 0xd3d3d300, 0x25252500, 0x8a8a8a00, 0xb5b5b500, 0xe7e7e700, 0x42424200, 0xb3b3b300, 0xc7c7c700, 0xeaeaea00, 0xf7f7f700, 0x4c4c4c00, 0x11111100, 0x33333300, 0x03030300, 0xa2a2a200, 0xacacac00, 0x60606000 }; /* Key XOR Layer */ #define ARIA_ADD_ROUND_KEY(RK, T0, T1, T2, T3) \ do { \ (T0) ^= (RK)->u[0]; \ (T1) ^= (RK)->u[1]; \ (T2) ^= (RK)->u[2]; \ (T3) ^= (RK)->u[3]; \ } while(0) /* S-Box Layer 1 + M */ #define ARIA_SBOX_LAYER1_WITH_PRE_DIFF(T0, T1, T2, T3) \ do { \ (T0) = \ S1[GET_U8_BE(T0, 0)] ^ \ S2[GET_U8_BE(T0, 1)] ^ \ X1[GET_U8_BE(T0, 2)] ^ \ X2[GET_U8_BE(T0, 3)]; \ (T1) = \ S1[GET_U8_BE(T1, 0)] ^ \ S2[GET_U8_BE(T1, 1)] ^ \ X1[GET_U8_BE(T1, 2)] ^ \ X2[GET_U8_BE(T1, 3)]; \ (T2) = \ S1[GET_U8_BE(T2, 0)] ^ \ S2[GET_U8_BE(T2, 1)] ^ \ X1[GET_U8_BE(T2, 2)] ^ \ X2[GET_U8_BE(T2, 3)]; \ (T3) = \ S1[GET_U8_BE(T3, 0)] ^ \ S2[GET_U8_BE(T3, 1)] ^ \ X1[GET_U8_BE(T3, 2)] ^ \ X2[GET_U8_BE(T3, 3)]; \ } while(0) /* S-Box Layer 2 + M */ #define ARIA_SBOX_LAYER2_WITH_PRE_DIFF(T0, T1, T2, T3) \ do { \ (T0) = \ X1[GET_U8_BE(T0, 0)] ^ \ X2[GET_U8_BE(T0, 1)] ^ \ S1[GET_U8_BE(T0, 2)] ^ \ S2[GET_U8_BE(T0, 3)]; \ (T1) = \ X1[GET_U8_BE(T1, 0)] ^ \ X2[GET_U8_BE(T1, 1)] ^ \ S1[GET_U8_BE(T1, 2)] ^ \ S2[GET_U8_BE(T1, 3)]; \ (T2) = \ X1[GET_U8_BE(T2, 0)] ^ \ X2[GET_U8_BE(T2, 1)] ^ \ S1[GET_U8_BE(T2, 2)] ^ \ S2[GET_U8_BE(T2, 3)]; \ (T3) = \ X1[GET_U8_BE(T3, 0)] ^ \ X2[GET_U8_BE(T3, 1)] ^ \ S1[GET_U8_BE(T3, 2)] ^ \ S2[GET_U8_BE(T3, 3)]; \ } while(0) /* Word-level diffusion */ #define ARIA_DIFF_WORD(T0,T1,T2,T3) \ do { \ (T1) ^= (T2); \ (T2) ^= (T3); \ (T0) ^= (T1); \ \ (T3) ^= (T1); \ (T2) ^= (T0); \ (T1) ^= (T2); \ } while(0) /* Byte-level diffusion */ #define ARIA_DIFF_BYTE(T0, T1, T2, T3) \ do { \ (T1) = (((T1) << 8) & 0xff00ff00) ^ (((T1) >> 8) & 0x00ff00ff); \ (T2) = rotr32(T2, 16); \ (T3) = bswap32(T3); \ } while(0) /* Odd round Substitution & Diffusion */ #define ARIA_SUBST_DIFF_ODD(T0, T1, T2, T3) \ do { \ ARIA_SBOX_LAYER1_WITH_PRE_DIFF(T0, T1, T2, T3); \ ARIA_DIFF_WORD(T0, T1, T2, T3); \ ARIA_DIFF_BYTE(T0, T1, T2, T3); \ ARIA_DIFF_WORD(T0, T1, T2, T3); \ } while(0) /* Even round Substitution & Diffusion */ #define ARIA_SUBST_DIFF_EVEN(T0, T1, T2, T3) \ do { \ ARIA_SBOX_LAYER2_WITH_PRE_DIFF(T0, T1, T2, T3); \ ARIA_DIFF_WORD(T0, T1, T2, T3); \ ARIA_DIFF_BYTE(T2, T3, T0, T1); \ ARIA_DIFF_WORD(T0, T1, T2, T3); \ } while(0) /* Q, R Macro expanded ARIA GSRK */ #define _ARIA_GSRK(RK, X, Y, Q, R) \ do { \ (RK)->u[0] = \ ((X)[0]) ^ \ (((Y)[((Q) ) % 4]) >> (R)) ^ \ (((Y)[((Q) + 3) % 4]) << (32 - (R))); \ (RK)->u[1] = \ ((X)[1]) ^ \ (((Y)[((Q) + 1) % 4]) >> (R)) ^ \ (((Y)[((Q) ) % 4]) << (32 - (R))); \ (RK)->u[2] = \ ((X)[2]) ^ \ (((Y)[((Q) + 2) % 4]) >> (R)) ^ \ (((Y)[((Q) + 1) % 4]) << (32 - (R))); \ (RK)->u[3] = \ ((X)[3]) ^ \ (((Y)[((Q) + 3) % 4]) >> (R)) ^ \ (((Y)[((Q) + 2) % 4]) << (32 - (R))); \ } while(0) #define ARIA_GSRK(RK, X, Y, N) _ARIA_GSRK(RK, X, Y, 4 - ((N) / 32), (N) % 32) #define ARIA_DEC_DIFF_BYTE(X, Y, TMP, TMP2) \ do { \ (TMP) = (X); \ (TMP2) = rotr32((TMP), 8); \ (Y) = (TMP2) ^ rotr32((TMP) ^ (TMP2), 16); \ } while(0) void ossl_aria_encrypt(const unsigned char *in, unsigned char *out, const ARIA_KEY *key) { register uint32_t reg0, reg1, reg2, reg3; int Nr; const ARIA_u128 *rk; if (in == NULL || out == NULL || key == NULL) { return; } rk = key->rd_key; Nr = key->rounds; if (Nr != 12 && Nr != 14 && Nr != 16) { return; } reg0 = GET_U32_BE(in, 0); reg1 = GET_U32_BE(in, 1); reg2 = GET_U32_BE(in, 2); reg3 = GET_U32_BE(in, 3); ARIA_ADD_ROUND_KEY(rk, reg0, reg1, reg2, reg3); rk++; ARIA_SUBST_DIFF_ODD(reg0, reg1, reg2, reg3); ARIA_ADD_ROUND_KEY(rk, reg0, reg1, reg2, reg3); rk++; while ((Nr -= 2) > 0) { ARIA_SUBST_DIFF_EVEN(reg0, reg1, reg2, reg3); ARIA_ADD_ROUND_KEY(rk, reg0, reg1, reg2, reg3); rk++; ARIA_SUBST_DIFF_ODD(reg0, reg1, reg2, reg3); ARIA_ADD_ROUND_KEY(rk, reg0, reg1, reg2, reg3); rk++; } reg0 = rk->u[0] ^ MAKE_U32( (uint8_t)(X1[GET_U8_BE(reg0, 0)] ), (uint8_t)(X2[GET_U8_BE(reg0, 1)] >> 8), (uint8_t)(S1[GET_U8_BE(reg0, 2)] ), (uint8_t)(S2[GET_U8_BE(reg0, 3)] )); reg1 = rk->u[1] ^ MAKE_U32( (uint8_t)(X1[GET_U8_BE(reg1, 0)] ), (uint8_t)(X2[GET_U8_BE(reg1, 1)] >> 8), (uint8_t)(S1[GET_U8_BE(reg1, 2)] ), (uint8_t)(S2[GET_U8_BE(reg1, 3)] )); reg2 = rk->u[2] ^ MAKE_U32( (uint8_t)(X1[GET_U8_BE(reg2, 0)] ), (uint8_t)(X2[GET_U8_BE(reg2, 1)] >> 8), (uint8_t)(S1[GET_U8_BE(reg2, 2)] ), (uint8_t)(S2[GET_U8_BE(reg2, 3)] )); reg3 = rk->u[3] ^ MAKE_U32( (uint8_t)(X1[GET_U8_BE(reg3, 0)] ), (uint8_t)(X2[GET_U8_BE(reg3, 1)] >> 8), (uint8_t)(S1[GET_U8_BE(reg3, 2)] ), (uint8_t)(S2[GET_U8_BE(reg3, 3)] )); PUT_U32_BE(out, 0, reg0); PUT_U32_BE(out, 1, reg1); PUT_U32_BE(out, 2, reg2); PUT_U32_BE(out, 3, reg3); } int ossl_aria_set_encrypt_key(const unsigned char *userKey, const int bits, ARIA_KEY *key) { register uint32_t reg0, reg1, reg2, reg3; uint32_t w0[4], w1[4], w2[4], w3[4]; const uint32_t *ck; ARIA_u128 *rk; int Nr = (bits + 256) / 32; if (userKey == NULL || key == NULL) { return -1; } if (bits != 128 && bits != 192 && bits != 256) { return -2; } rk = key->rd_key; key->rounds = Nr; ck = &Key_RC[(bits - 128) / 64][0]; w0[0] = GET_U32_BE(userKey, 0); w0[1] = GET_U32_BE(userKey, 1); w0[2] = GET_U32_BE(userKey, 2); w0[3] = GET_U32_BE(userKey, 3); reg0 = w0[0] ^ ck[0]; reg1 = w0[1] ^ ck[1]; reg2 = w0[2] ^ ck[2]; reg3 = w0[3] ^ ck[3]; ARIA_SUBST_DIFF_ODD(reg0, reg1, reg2, reg3); if (bits > 128) { w1[0] = GET_U32_BE(userKey, 4); w1[1] = GET_U32_BE(userKey, 5); if (bits > 192) { w1[2] = GET_U32_BE(userKey, 6); w1[3] = GET_U32_BE(userKey, 7); } else { w1[2] = w1[3] = 0; } } else { w1[0] = w1[1] = w1[2] = w1[3] = 0; } w1[0] ^= reg0; w1[1] ^= reg1; w1[2] ^= reg2; w1[3] ^= reg3; reg0 = w1[0]; reg1 = w1[1]; reg2 = w1[2]; reg3 = w1[3]; reg0 ^= ck[4]; reg1 ^= ck[5]; reg2 ^= ck[6]; reg3 ^= ck[7]; ARIA_SUBST_DIFF_EVEN(reg0, reg1, reg2, reg3); reg0 ^= w0[0]; reg1 ^= w0[1]; reg2 ^= w0[2]; reg3 ^= w0[3]; w2[0] = reg0; w2[1] = reg1; w2[2] = reg2; w2[3] = reg3; reg0 ^= ck[8]; reg1 ^= ck[9]; reg2 ^= ck[10]; reg3 ^= ck[11]; ARIA_SUBST_DIFF_ODD(reg0, reg1, reg2, reg3); w3[0] = reg0 ^ w1[0]; w3[1] = reg1 ^ w1[1]; w3[2] = reg2 ^ w1[2]; w3[3] = reg3 ^ w1[3]; ARIA_GSRK(rk, w0, w1, 19); rk++; ARIA_GSRK(rk, w1, w2, 19); rk++; ARIA_GSRK(rk, w2, w3, 19); rk++; ARIA_GSRK(rk, w3, w0, 19); rk++; ARIA_GSRK(rk, w0, w1, 31); rk++; ARIA_GSRK(rk, w1, w2, 31); rk++; ARIA_GSRK(rk, w2, w3, 31); rk++; ARIA_GSRK(rk, w3, w0, 31); rk++; ARIA_GSRK(rk, w0, w1, 67); rk++; ARIA_GSRK(rk, w1, w2, 67); rk++; ARIA_GSRK(rk, w2, w3, 67); rk++; ARIA_GSRK(rk, w3, w0, 67); rk++; ARIA_GSRK(rk, w0, w1, 97); if (bits > 128) { rk++; ARIA_GSRK(rk, w1, w2, 97); rk++; ARIA_GSRK(rk, w2, w3, 97); } if (bits > 192) { rk++; ARIA_GSRK(rk, w3, w0, 97); rk++; ARIA_GSRK(rk, w0, w1, 109); } return 0; } int ossl_aria_set_decrypt_key(const unsigned char *userKey, const int bits, ARIA_KEY *key) { ARIA_u128 *rk_head; ARIA_u128 *rk_tail; register uint32_t w1, w2; register uint32_t reg0, reg1, reg2, reg3; uint32_t s0, s1, s2, s3; const int r = ossl_aria_set_encrypt_key(userKey, bits, key); if (r != 0) { return r; } rk_head = key->rd_key; rk_tail = rk_head + key->rounds; reg0 = rk_head->u[0]; reg1 = rk_head->u[1]; reg2 = rk_head->u[2]; reg3 = rk_head->u[3]; memcpy(rk_head, rk_tail, ARIA_BLOCK_SIZE); rk_tail->u[0] = reg0; rk_tail->u[1] = reg1; rk_tail->u[2] = reg2; rk_tail->u[3] = reg3; rk_head++; rk_tail--; for (; rk_head < rk_tail; rk_head++, rk_tail--) { ARIA_DEC_DIFF_BYTE(rk_head->u[0], reg0, w1, w2); ARIA_DEC_DIFF_BYTE(rk_head->u[1], reg1, w1, w2); ARIA_DEC_DIFF_BYTE(rk_head->u[2], reg2, w1, w2); ARIA_DEC_DIFF_BYTE(rk_head->u[3], reg3, w1, w2); ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); ARIA_DIFF_BYTE(reg0, reg1, reg2, reg3); ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); s0 = reg0; s1 = reg1; s2 = reg2; s3 = reg3; ARIA_DEC_DIFF_BYTE(rk_tail->u[0], reg0, w1, w2); ARIA_DEC_DIFF_BYTE(rk_tail->u[1], reg1, w1, w2); ARIA_DEC_DIFF_BYTE(rk_tail->u[2], reg2, w1, w2); ARIA_DEC_DIFF_BYTE(rk_tail->u[3], reg3, w1, w2); ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); ARIA_DIFF_BYTE(reg0, reg1, reg2, reg3); ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); rk_head->u[0] = reg0; rk_head->u[1] = reg1; rk_head->u[2] = reg2; rk_head->u[3] = reg3; rk_tail->u[0] = s0; rk_tail->u[1] = s1; rk_tail->u[2] = s2; rk_tail->u[3] = s3; } ARIA_DEC_DIFF_BYTE(rk_head->u[0], reg0, w1, w2); ARIA_DEC_DIFF_BYTE(rk_head->u[1], reg1, w1, w2); ARIA_DEC_DIFF_BYTE(rk_head->u[2], reg2, w1, w2); ARIA_DEC_DIFF_BYTE(rk_head->u[3], reg3, w1, w2); ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); ARIA_DIFF_BYTE(reg0, reg1, reg2, reg3); ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); rk_tail->u[0] = reg0; rk_tail->u[1] = reg1; rk_tail->u[2] = reg2; rk_tail->u[3] = reg3; return 0; } #else static const unsigned char sb1[256] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; static const unsigned char sb2[256] = { 0xe2, 0x4e, 0x54, 0xfc, 0x94, 0xc2, 0x4a, 0xcc, 0x62, 0x0d, 0x6a, 0x46, 0x3c, 0x4d, 0x8b, 0xd1, 0x5e, 0xfa, 0x64, 0xcb, 0xb4, 0x97, 0xbe, 0x2b, 0xbc, 0x77, 0x2e, 0x03, 0xd3, 0x19, 0x59, 0xc1, 0x1d, 0x06, 0x41, 0x6b, 0x55, 0xf0, 0x99, 0x69, 0xea, 0x9c, 0x18, 0xae, 0x63, 0xdf, 0xe7, 0xbb, 0x00, 0x73, 0x66, 0xfb, 0x96, 0x4c, 0x85, 0xe4, 0x3a, 0x09, 0x45, 0xaa, 0x0f, 0xee, 0x10, 0xeb, 0x2d, 0x7f, 0xf4, 0x29, 0xac, 0xcf, 0xad, 0x91, 0x8d, 0x78, 0xc8, 0x95, 0xf9, 0x2f, 0xce, 0xcd, 0x08, 0x7a, 0x88, 0x38, 0x5c, 0x83, 0x2a, 0x28, 0x47, 0xdb, 0xb8, 0xc7, 0x93, 0xa4, 0x12, 0x53, 0xff, 0x87, 0x0e, 0x31, 0x36, 0x21, 0x58, 0x48, 0x01, 0x8e, 0x37, 0x74, 0x32, 0xca, 0xe9, 0xb1, 0xb7, 0xab, 0x0c, 0xd7, 0xc4, 0x56, 0x42, 0x26, 0x07, 0x98, 0x60, 0xd9, 0xb6, 0xb9, 0x11, 0x40, 0xec, 0x20, 0x8c, 0xbd, 0xa0, 0xc9, 0x84, 0x04, 0x49, 0x23, 0xf1, 0x4f, 0x50, 0x1f, 0x13, 0xdc, 0xd8, 0xc0, 0x9e, 0x57, 0xe3, 0xc3, 0x7b, 0x65, 0x3b, 0x02, 0x8f, 0x3e, 0xe8, 0x25, 0x92, 0xe5, 0x15, 0xdd, 0xfd, 0x17, 0xa9, 0xbf, 0xd4, 0x9a, 0x7e, 0xc5, 0x39, 0x67, 0xfe, 0x76, 0x9d, 0x43, 0xa7, 0xe1, 0xd0, 0xf5, 0x68, 0xf2, 0x1b, 0x34, 0x70, 0x05, 0xa3, 0x8a, 0xd5, 0x79, 0x86, 0xa8, 0x30, 0xc6, 0x51, 0x4b, 0x1e, 0xa6, 0x27, 0xf6, 0x35, 0xd2, 0x6e, 0x24, 0x16, 0x82, 0x5f, 0xda, 0xe6, 0x75, 0xa2, 0xef, 0x2c, 0xb2, 0x1c, 0x9f, 0x5d, 0x6f, 0x80, 0x0a, 0x72, 0x44, 0x9b, 0x6c, 0x90, 0x0b, 0x5b, 0x33, 0x7d, 0x5a, 0x52, 0xf3, 0x61, 0xa1, 0xf7, 0xb0, 0xd6, 0x3f, 0x7c, 0x6d, 0xed, 0x14, 0xe0, 0xa5, 0x3d, 0x22, 0xb3, 0xf8, 0x89, 0xde, 0x71, 0x1a, 0xaf, 0xba, 0xb5, 0x81 }; static const unsigned char sb3[256] = { 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }; static const unsigned char sb4[256] = { 0x30, 0x68, 0x99, 0x1b, 0x87, 0xb9, 0x21, 0x78, 0x50, 0x39, 0xdb, 0xe1, 0x72, 0x09, 0x62, 0x3c, 0x3e, 0x7e, 0x5e, 0x8e, 0xf1, 0xa0, 0xcc, 0xa3, 0x2a, 0x1d, 0xfb, 0xb6, 0xd6, 0x20, 0xc4, 0x8d, 0x81, 0x65, 0xf5, 0x89, 0xcb, 0x9d, 0x77, 0xc6, 0x57, 0x43, 0x56, 0x17, 0xd4, 0x40, 0x1a, 0x4d, 0xc0, 0x63, 0x6c, 0xe3, 0xb7, 0xc8, 0x64, 0x6a, 0x53, 0xaa, 0x38, 0x98, 0x0c, 0xf4, 0x9b, 0xed, 0x7f, 0x22, 0x76, 0xaf, 0xdd, 0x3a, 0x0b, 0x58, 0x67, 0x88, 0x06, 0xc3, 0x35, 0x0d, 0x01, 0x8b, 0x8c, 0xc2, 0xe6, 0x5f, 0x02, 0x24, 0x75, 0x93, 0x66, 0x1e, 0xe5, 0xe2, 0x54, 0xd8, 0x10, 0xce, 0x7a, 0xe8, 0x08, 0x2c, 0x12, 0x97, 0x32, 0xab, 0xb4, 0x27, 0x0a, 0x23, 0xdf, 0xef, 0xca, 0xd9, 0xb8, 0xfa, 0xdc, 0x31, 0x6b, 0xd1, 0xad, 0x19, 0x49, 0xbd, 0x51, 0x96, 0xee, 0xe4, 0xa8, 0x41, 0xda, 0xff, 0xcd, 0x55, 0x86, 0x36, 0xbe, 0x61, 0x52, 0xf8, 0xbb, 0x0e, 0x82, 0x48, 0x69, 0x9a, 0xe0, 0x47, 0x9e, 0x5c, 0x04, 0x4b, 0x34, 0x15, 0x79, 0x26, 0xa7, 0xde, 0x29, 0xae, 0x92, 0xd7, 0x84, 0xe9, 0xd2, 0xba, 0x5d, 0xf3, 0xc5, 0xb0, 0xbf, 0xa4, 0x3b, 0x71, 0x44, 0x46, 0x2b, 0xfc, 0xeb, 0x6f, 0xd5, 0xf6, 0x14, 0xfe, 0x7c, 0x70, 0x5a, 0x7d, 0xfd, 0x2f, 0x18, 0x83, 0x16, 0xa5, 0x91, 0x1f, 0x05, 0x95, 0x74, 0xa9, 0xc1, 0x5b, 0x4a, 0x85, 0x6d, 0x13, 0x07, 0x4f, 0x4e, 0x45, 0xb2, 0x0f, 0xc9, 0x1c, 0xa6, 0xbc, 0xec, 0x73, 0x90, 0x7b, 0xcf, 0x59, 0x8f, 0xa1, 0xf9, 0x2d, 0xf2, 0xb1, 0x00, 0x94, 0x37, 0x9f, 0xd0, 0x2e, 0x9c, 0x6e, 0x28, 0x3f, 0x80, 0xf0, 0x3d, 0xd3, 0x25, 0x8a, 0xb5, 0xe7, 0x42, 0xb3, 0xc7, 0xea, 0xf7, 0x4c, 0x11, 0x33, 0x03, 0xa2, 0xac, 0x60 }; static const ARIA_u128 c1 = {{ 0x51, 0x7c, 0xc1, 0xb7, 0x27, 0x22, 0x0a, 0x94, 0xfe, 0x13, 0xab, 0xe8, 0xfa, 0x9a, 0x6e, 0xe0 }}; static const ARIA_u128 c2 = {{ 0x6d, 0xb1, 0x4a, 0xcc, 0x9e, 0x21, 0xc8, 0x20, 0xff, 0x28, 0xb1, 0xd5, 0xef, 0x5d, 0xe2, 0xb0 }}; static const ARIA_u128 c3 = {{ 0xdb, 0x92, 0x37, 0x1d, 0x21, 0x26, 0xe9, 0x70, 0x03, 0x24, 0x97, 0x75, 0x04, 0xe8, 0xc9, 0x0e }}; /* * Exclusive or two 128 bit values into the result. * It is safe for the result to be the same as the either input. */ static void xor128(ARIA_c128 o, const ARIA_c128 x, const ARIA_u128 *y) { int i; for (i = 0; i < ARIA_BLOCK_SIZE; i++) o[i] = x[i] ^ y->c[i]; } /* * Generalised circular rotate right and exclusive or function. * It is safe for the output to overlap either input. */ static ossl_inline void rotnr(unsigned int n, ARIA_u128 *o, const ARIA_u128 *xor, const ARIA_u128 *z) { const unsigned int bytes = n / 8, bits = n % 8; unsigned int i; ARIA_u128 t; for (i = 0; i < ARIA_BLOCK_SIZE; i++) t.c[(i + bytes) % ARIA_BLOCK_SIZE] = z->c[i]; for (i = 0; i < ARIA_BLOCK_SIZE; i++) o->c[i] = ((t.c[i] >> bits) | (t.c[i ? i - 1 : ARIA_BLOCK_SIZE - 1] << (8 - bits))) ^ xor->c[i]; } /* * Circular rotate 19 bits right and xor. * It is safe for the output to overlap either input. */ static void rot19r(ARIA_u128 *o, const ARIA_u128 *xor, const ARIA_u128 *z) { rotnr(19, o, xor, z); } /* * Circular rotate 31 bits right and xor. * It is safe for the output to overlap either input. */ static void rot31r(ARIA_u128 *o, const ARIA_u128 *xor, const ARIA_u128 *z) { rotnr(31, o, xor, z); } /* * Circular rotate 61 bits left and xor. * It is safe for the output to overlap either input. */ static void rot61l(ARIA_u128 *o, const ARIA_u128 *xor, const ARIA_u128 *z) { rotnr(8 * ARIA_BLOCK_SIZE - 61, o, xor, z); } /* * Circular rotate 31 bits left and xor. * It is safe for the output to overlap either input. */ static void rot31l(ARIA_u128 *o, const ARIA_u128 *xor, const ARIA_u128 *z) { rotnr(8 * ARIA_BLOCK_SIZE - 31, o, xor, z); } /* * Circular rotate 19 bits left and xor. * It is safe for the output to overlap either input. */ static void rot19l(ARIA_u128 *o, const ARIA_u128 *xor, const ARIA_u128 *z) { rotnr(8 * ARIA_BLOCK_SIZE - 19, o, xor, z); } /* * First substitution and xor layer, used for odd steps. * It is safe for the input and output to be the same. */ static void sl1(ARIA_u128 *o, const ARIA_u128 *x, const ARIA_u128 *y) { unsigned int i; for (i = 0; i < ARIA_BLOCK_SIZE; i += 4) { o->c[i ] = sb1[x->c[i ] ^ y->c[i ]]; o->c[i + 1] = sb2[x->c[i + 1] ^ y->c[i + 1]]; o->c[i + 2] = sb3[x->c[i + 2] ^ y->c[i + 2]]; o->c[i + 3] = sb4[x->c[i + 3] ^ y->c[i + 3]]; } } /* * Second substitution and xor layer, used for even steps. * It is safe for the input and output to be the same. */ static void sl2(ARIA_c128 o, const ARIA_u128 *x, const ARIA_u128 *y) { unsigned int i; for (i = 0; i < ARIA_BLOCK_SIZE; i += 4) { o[i ] = sb3[x->c[i ] ^ y->c[i ]]; o[i + 1] = sb4[x->c[i + 1] ^ y->c[i + 1]]; o[i + 2] = sb1[x->c[i + 2] ^ y->c[i + 2]]; o[i + 3] = sb2[x->c[i + 3] ^ y->c[i + 3]]; } } /* * Diffusion layer step * It is NOT safe for the input and output to overlap. */ static void a(ARIA_u128 *y, const ARIA_u128 *x) { y->c[ 0] = x->c[ 3] ^ x->c[ 4] ^ x->c[ 6] ^ x->c[ 8] ^ x->c[ 9] ^ x->c[13] ^ x->c[14]; y->c[ 1] = x->c[ 2] ^ x->c[ 5] ^ x->c[ 7] ^ x->c[ 8] ^ x->c[ 9] ^ x->c[12] ^ x->c[15]; y->c[ 2] = x->c[ 1] ^ x->c[ 4] ^ x->c[ 6] ^ x->c[10] ^ x->c[11] ^ x->c[12] ^ x->c[15]; y->c[ 3] = x->c[ 0] ^ x->c[ 5] ^ x->c[ 7] ^ x->c[10] ^ x->c[11] ^ x->c[13] ^ x->c[14]; y->c[ 4] = x->c[ 0] ^ x->c[ 2] ^ x->c[ 5] ^ x->c[ 8] ^ x->c[11] ^ x->c[14] ^ x->c[15]; y->c[ 5] = x->c[ 1] ^ x->c[ 3] ^ x->c[ 4] ^ x->c[ 9] ^ x->c[10] ^ x->c[14] ^ x->c[15]; y->c[ 6] = x->c[ 0] ^ x->c[ 2] ^ x->c[ 7] ^ x->c[ 9] ^ x->c[10] ^ x->c[12] ^ x->c[13]; y->c[ 7] = x->c[ 1] ^ x->c[ 3] ^ x->c[ 6] ^ x->c[ 8] ^ x->c[11] ^ x->c[12] ^ x->c[13]; y->c[ 8] = x->c[ 0] ^ x->c[ 1] ^ x->c[ 4] ^ x->c[ 7] ^ x->c[10] ^ x->c[13] ^ x->c[15]; y->c[ 9] = x->c[ 0] ^ x->c[ 1] ^ x->c[ 5] ^ x->c[ 6] ^ x->c[11] ^ x->c[12] ^ x->c[14]; y->c[10] = x->c[ 2] ^ x->c[ 3] ^ x->c[ 5] ^ x->c[ 6] ^ x->c[ 8] ^ x->c[13] ^ x->c[15]; y->c[11] = x->c[ 2] ^ x->c[ 3] ^ x->c[ 4] ^ x->c[ 7] ^ x->c[ 9] ^ x->c[12] ^ x->c[14]; y->c[12] = x->c[ 1] ^ x->c[ 2] ^ x->c[ 6] ^ x->c[ 7] ^ x->c[ 9] ^ x->c[11] ^ x->c[12]; y->c[13] = x->c[ 0] ^ x->c[ 3] ^ x->c[ 6] ^ x->c[ 7] ^ x->c[ 8] ^ x->c[10] ^ x->c[13]; y->c[14] = x->c[ 0] ^ x->c[ 3] ^ x->c[ 4] ^ x->c[ 5] ^ x->c[ 9] ^ x->c[11] ^ x->c[14]; y->c[15] = x->c[ 1] ^ x->c[ 2] ^ x->c[ 4] ^ x->c[ 5] ^ x->c[ 8] ^ x->c[10] ^ x->c[15]; } /* * Odd round function * Apply the first substitution layer and then a diffusion step. * It is safe for the input and output to overlap. */ static ossl_inline void FO(ARIA_u128 *o, const ARIA_u128 *d, const ARIA_u128 *rk) { ARIA_u128 y; sl1(&y, d, rk); a(o, &y); } /* * Even round function * Apply the second substitution layer and then a diffusion step. * It is safe for the input and output to overlap. */ static ossl_inline void FE(ARIA_u128 *o, const ARIA_u128 *d, const ARIA_u128 *rk) { ARIA_u128 y; sl2(y.c, d, rk); a(o, &y); } /* * Encrypt or decrypt a single block * in and out can overlap */ static void do_encrypt(unsigned char *o, const unsigned char *pin, unsigned int rounds, const ARIA_u128 *keys) { ARIA_u128 p; unsigned int i; memcpy(&p, pin, sizeof(p)); for (i = 0; i < rounds - 2; i += 2) { FO(&p, &p, &keys[i]); FE(&p, &p, &keys[i + 1]); } FO(&p, &p, &keys[rounds - 2]); sl2(o, &p, &keys[rounds - 1]); xor128(o, o, &keys[rounds]); } /* * Encrypt a single block * in and out can overlap */ void ossl_aria_encrypt(const unsigned char *in, unsigned char *out, const ARIA_KEY *key) { assert(in != NULL && out != NULL && key != NULL); do_encrypt(out, in, key->rounds, key->rd_key); } /* * Expand the cipher key into the encryption key schedule. * We short circuit execution of the last two * or four rotations based on the key size. */ int ossl_aria_set_encrypt_key(const unsigned char *userKey, const int bits, ARIA_KEY *key) { const ARIA_u128 *ck1, *ck2, *ck3; ARIA_u128 kr, w0, w1, w2, w3; if (!userKey || !key) return -1; memcpy(w0.c, userKey, sizeof(w0)); switch (bits) { default: return -2; case 128: key->rounds = 12; ck1 = &c1; ck2 = &c2; ck3 = &c3; memset(kr.c, 0, sizeof(kr)); break; case 192: key->rounds = 14; ck1 = &c2; ck2 = &c3; ck3 = &c1; memcpy(kr.c, userKey + ARIA_BLOCK_SIZE, sizeof(kr) / 2); memset(kr.c + ARIA_BLOCK_SIZE / 2, 0, sizeof(kr) / 2); break; case 256: key->rounds = 16; ck1 = &c3; ck2 = &c1; ck3 = &c2; memcpy(kr.c, userKey + ARIA_BLOCK_SIZE, sizeof(kr)); break; } FO(&w3, &w0, ck1); xor128(w1.c, w3.c, &kr); FE(&w3, &w1, ck2); xor128(w2.c, w3.c, &w0); FO(&kr, &w2, ck3); xor128(w3.c, kr.c, &w1); rot19r(&key->rd_key[ 0], &w0, &w1); rot19r(&key->rd_key[ 1], &w1, &w2); rot19r(&key->rd_key[ 2], &w2, &w3); rot19r(&key->rd_key[ 3], &w3, &w0); rot31r(&key->rd_key[ 4], &w0, &w1); rot31r(&key->rd_key[ 5], &w1, &w2); rot31r(&key->rd_key[ 6], &w2, &w3); rot31r(&key->rd_key[ 7], &w3, &w0); rot61l(&key->rd_key[ 8], &w0, &w1); rot61l(&key->rd_key[ 9], &w1, &w2); rot61l(&key->rd_key[10], &w2, &w3); rot61l(&key->rd_key[11], &w3, &w0); rot31l(&key->rd_key[12], &w0, &w1); if (key->rounds > 12) { rot31l(&key->rd_key[13], &w1, &w2); rot31l(&key->rd_key[14], &w2, &w3); if (key->rounds > 14) { rot31l(&key->rd_key[15], &w3, &w0); rot19l(&key->rd_key[16], &w0, &w1); } } return 0; } /* * Expand the cipher key into the decryption key schedule. */ int ossl_aria_set_decrypt_key(const unsigned char *userKey, const int bits, ARIA_KEY *key) { ARIA_KEY ek; const int r = ossl_aria_set_encrypt_key(userKey, bits, &ek); unsigned int i, rounds = ek.rounds; if (r == 0) { key->rounds = rounds; memcpy(&key->rd_key[0], &ek.rd_key[rounds], sizeof(key->rd_key[0])); for (i = 1; i < rounds; i++) a(&key->rd_key[i], &ek.rd_key[rounds - i]); memcpy(&key->rd_key[rounds], &ek.rd_key[0], sizeof(key->rd_key[rounds])); } return r; } #endif
./openssl/crypto/cast/c_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 */ /* * CAST low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/cast.h> #include "cast_local.h" #include <openssl/opensslv.h> void CAST_ecb_encrypt(const unsigned char *in, unsigned char *out, const CAST_KEY *ks, int enc) { CAST_LONG l, d[2]; n2l(in, l); d[0] = l; n2l(in, l); d[1] = l; if (enc) CAST_encrypt(d, ks); else CAST_decrypt(d, ks); l = d[0]; l2n(l, out); l = d[1]; l2n(l, out); l = d[0] = d[1] = 0; }
./openssl/crypto/cast/c_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 */ /* * CAST low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/cast.h> #include "cast_local.h" #include "cast_s.h" #define CAST_exp(l,A,a,n) \ A[n/4]=l; \ a[n+3]=(l )&0xff; \ a[n+2]=(l>> 8)&0xff; \ a[n+1]=(l>>16)&0xff; \ a[n+0]=(l>>24)&0xff; #define S4 CAST_S_table4 #define S5 CAST_S_table5 #define S6 CAST_S_table6 #define S7 CAST_S_table7 void CAST_set_key(CAST_KEY *key, int len, const unsigned char *data) { CAST_LONG x[16]; CAST_LONG z[16]; CAST_LONG k[32]; CAST_LONG X[4], Z[4]; CAST_LONG l, *K; int i; for (i = 0; i < 16; i++) x[i] = 0; if (len > 16) len = 16; for (i = 0; i < len; i++) x[i] = data[i]; if (len <= 10) key->short_key = 1; else key->short_key = 0; K = &k[0]; X[0] = ((x[0] << 24) | (x[1] << 16) | (x[2] << 8) | x[3]) & 0xffffffffL; X[1] = ((x[4] << 24) | (x[5] << 16) | (x[6] << 8) | x[7]) & 0xffffffffL; X[2] = ((x[8] << 24) | (x[9] << 16) | (x[10] << 8) | x[11]) & 0xffffffffL; X[3] = ((x[12] << 24) | (x[13] << 16) | (x[14] << 8) | x[15]) & 0xffffffffL; for (;;) { l = X[0] ^ S4[x[13]] ^ S5[x[15]] ^ S6[x[12]] ^ S7[x[14]] ^ S6[x[8]]; CAST_exp(l, Z, z, 0); l = X[2] ^ S4[z[0]] ^ S5[z[2]] ^ S6[z[1]] ^ S7[z[3]] ^ S7[x[10]]; CAST_exp(l, Z, z, 4); l = X[3] ^ S4[z[7]] ^ S5[z[6]] ^ S6[z[5]] ^ S7[z[4]] ^ S4[x[9]]; CAST_exp(l, Z, z, 8); l = X[1] ^ S4[z[10]] ^ S5[z[9]] ^ S6[z[11]] ^ S7[z[8]] ^ S5[x[11]]; CAST_exp(l, Z, z, 12); K[0] = S4[z[8]] ^ S5[z[9]] ^ S6[z[7]] ^ S7[z[6]] ^ S4[z[2]]; K[1] = S4[z[10]] ^ S5[z[11]] ^ S6[z[5]] ^ S7[z[4]] ^ S5[z[6]]; K[2] = S4[z[12]] ^ S5[z[13]] ^ S6[z[3]] ^ S7[z[2]] ^ S6[z[9]]; K[3] = S4[z[14]] ^ S5[z[15]] ^ S6[z[1]] ^ S7[z[0]] ^ S7[z[12]]; l = Z[2] ^ S4[z[5]] ^ S5[z[7]] ^ S6[z[4]] ^ S7[z[6]] ^ S6[z[0]]; CAST_exp(l, X, x, 0); l = Z[0] ^ S4[x[0]] ^ S5[x[2]] ^ S6[x[1]] ^ S7[x[3]] ^ S7[z[2]]; CAST_exp(l, X, x, 4); l = Z[1] ^ S4[x[7]] ^ S5[x[6]] ^ S6[x[5]] ^ S7[x[4]] ^ S4[z[1]]; CAST_exp(l, X, x, 8); l = Z[3] ^ S4[x[10]] ^ S5[x[9]] ^ S6[x[11]] ^ S7[x[8]] ^ S5[z[3]]; CAST_exp(l, X, x, 12); K[4] = S4[x[3]] ^ S5[x[2]] ^ S6[x[12]] ^ S7[x[13]] ^ S4[x[8]]; K[5] = S4[x[1]] ^ S5[x[0]] ^ S6[x[14]] ^ S7[x[15]] ^ S5[x[13]]; K[6] = S4[x[7]] ^ S5[x[6]] ^ S6[x[8]] ^ S7[x[9]] ^ S6[x[3]]; K[7] = S4[x[5]] ^ S5[x[4]] ^ S6[x[10]] ^ S7[x[11]] ^ S7[x[7]]; l = X[0] ^ S4[x[13]] ^ S5[x[15]] ^ S6[x[12]] ^ S7[x[14]] ^ S6[x[8]]; CAST_exp(l, Z, z, 0); l = X[2] ^ S4[z[0]] ^ S5[z[2]] ^ S6[z[1]] ^ S7[z[3]] ^ S7[x[10]]; CAST_exp(l, Z, z, 4); l = X[3] ^ S4[z[7]] ^ S5[z[6]] ^ S6[z[5]] ^ S7[z[4]] ^ S4[x[9]]; CAST_exp(l, Z, z, 8); l = X[1] ^ S4[z[10]] ^ S5[z[9]] ^ S6[z[11]] ^ S7[z[8]] ^ S5[x[11]]; CAST_exp(l, Z, z, 12); K[8] = S4[z[3]] ^ S5[z[2]] ^ S6[z[12]] ^ S7[z[13]] ^ S4[z[9]]; K[9] = S4[z[1]] ^ S5[z[0]] ^ S6[z[14]] ^ S7[z[15]] ^ S5[z[12]]; K[10] = S4[z[7]] ^ S5[z[6]] ^ S6[z[8]] ^ S7[z[9]] ^ S6[z[2]]; K[11] = S4[z[5]] ^ S5[z[4]] ^ S6[z[10]] ^ S7[z[11]] ^ S7[z[6]]; l = Z[2] ^ S4[z[5]] ^ S5[z[7]] ^ S6[z[4]] ^ S7[z[6]] ^ S6[z[0]]; CAST_exp(l, X, x, 0); l = Z[0] ^ S4[x[0]] ^ S5[x[2]] ^ S6[x[1]] ^ S7[x[3]] ^ S7[z[2]]; CAST_exp(l, X, x, 4); l = Z[1] ^ S4[x[7]] ^ S5[x[6]] ^ S6[x[5]] ^ S7[x[4]] ^ S4[z[1]]; CAST_exp(l, X, x, 8); l = Z[3] ^ S4[x[10]] ^ S5[x[9]] ^ S6[x[11]] ^ S7[x[8]] ^ S5[z[3]]; CAST_exp(l, X, x, 12); K[12] = S4[x[8]] ^ S5[x[9]] ^ S6[x[7]] ^ S7[x[6]] ^ S4[x[3]]; K[13] = S4[x[10]] ^ S5[x[11]] ^ S6[x[5]] ^ S7[x[4]] ^ S5[x[7]]; K[14] = S4[x[12]] ^ S5[x[13]] ^ S6[x[3]] ^ S7[x[2]] ^ S6[x[8]]; K[15] = S4[x[14]] ^ S5[x[15]] ^ S6[x[1]] ^ S7[x[0]] ^ S7[x[13]]; if (K != k) break; K += 16; } for (i = 0; i < 16; i++) { key->data[i * 2] = k[i]; key->data[i * 2 + 1] = ((k[i + 16]) + 16) & 0x1f; } }
./openssl/crypto/cast/c_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 */ /* * CAST low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/cast.h> #include "cast_local.h" void CAST_encrypt(CAST_LONG *data, const CAST_KEY *key) { CAST_LONG l, r, t; const CAST_LONG *k; k = &(key->data[0]); l = data[0]; r = data[1]; E_CAST(0, k, l, r, +, ^, -); E_CAST(1, k, r, l, ^, -, +); E_CAST(2, k, l, r, -, +, ^); E_CAST(3, k, r, l, +, ^, -); E_CAST(4, k, l, r, ^, -, +); E_CAST(5, k, r, l, -, +, ^); E_CAST(6, k, l, r, +, ^, -); E_CAST(7, k, r, l, ^, -, +); E_CAST(8, k, l, r, -, +, ^); E_CAST(9, k, r, l, +, ^, -); E_CAST(10, k, l, r, ^, -, +); E_CAST(11, k, r, l, -, +, ^); if (!key->short_key) { E_CAST(12, k, l, r, +, ^, -); E_CAST(13, k, r, l, ^, -, +); E_CAST(14, k, l, r, -, +, ^); E_CAST(15, k, r, l, +, ^, -); } data[1] = l & 0xffffffffL; data[0] = r & 0xffffffffL; } void CAST_decrypt(CAST_LONG *data, const CAST_KEY *key) { CAST_LONG l, r, t; const CAST_LONG *k; k = &(key->data[0]); l = data[0]; r = data[1]; if (!key->short_key) { E_CAST(15, k, l, r, +, ^, -); E_CAST(14, k, r, l, -, +, ^); E_CAST(13, k, l, r, ^, -, +); E_CAST(12, k, r, l, +, ^, -); } E_CAST(11, k, l, r, -, +, ^); E_CAST(10, k, r, l, ^, -, +); E_CAST(9, k, l, r, +, ^, -); E_CAST(8, k, r, l, -, +, ^); E_CAST(7, k, l, r, ^, -, +); E_CAST(6, k, r, l, +, ^, -); E_CAST(5, k, l, r, -, +, ^); E_CAST(4, k, r, l, ^, -, +); E_CAST(3, k, l, r, +, ^, -); E_CAST(2, k, r, l, -, +, ^); E_CAST(1, k, l, r, ^, -, +); E_CAST(0, k, r, l, +, ^, -); data[1] = l & 0xffffffffL; data[0] = r & 0xffffffffL; } void CAST_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, const CAST_KEY *ks, unsigned char *iv, int enc) { register CAST_LONG tin0, tin1; register CAST_LONG tout0, tout1, xor0, xor1; register long l = length; CAST_LONG tin[2]; if (enc) { n2l(iv, tout0); n2l(iv, tout1); iv -= 8; for (l -= 8; l >= 0; l -= 8) { n2l(in, tin0); n2l(in, tin1); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; CAST_encrypt(tin, ks); 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; CAST_encrypt(tin, ks); tout0 = tin[0]; tout1 = tin[1]; l2n(tout0, out); l2n(tout1, out); } l2n(tout0, iv); l2n(tout1, iv); } else { n2l(iv, xor0); n2l(iv, xor1); iv -= 8; for (l -= 8; l >= 0; l -= 8) { n2l(in, tin0); n2l(in, tin1); tin[0] = tin0; tin[1] = tin1; CAST_decrypt(tin, ks); 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; CAST_decrypt(tin, ks); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2nn(tout0, tout1, out, l + 8); xor0 = tin0; xor1 = tin1; } l2n(xor0, iv); l2n(xor1, iv); } tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; tin[0] = tin[1] = 0; }
./openssl/crypto/cast/c_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 */ /* * CAST low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/cast.h> #include "cast_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 CAST_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, const CAST_KEY *schedule, unsigned char *ivec, int *num) { register CAST_LONG v0, v1, t; register int n = *num; register long l = length; unsigned char d[8]; register char *dp; CAST_LONG ti[2]; unsigned char *iv; int save = 0; iv = 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) { CAST_encrypt((CAST_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 = ivec; l2n(v0, iv); l2n(v1, iv); } t = v0 = v1 = ti[0] = ti[1] = 0; *num = n; }
./openssl/crypto/cast/cast_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 */ #ifdef OPENSSL_SYS_WIN32 # include <stdlib.h> #endif /* 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)) #if defined(OPENSSL_SYS_WIN32) && defined(_MSC_VER) # define ROTL(a,n) (_lrotl(a,n)) #else # define ROTL(a,n) ((((a)<<(n))&0xffffffffL)|((a)>>((32-(n))&31))) #endif #define C_M 0x3fc #define C_0 22L #define C_1 14L #define C_2 6L #define C_3 2L /* left shift */ /* The rotate has an extra 16 added to it to help the x86 asm */ #if defined(CAST_PTR) # define E_CAST(n,key,L,R,OP1,OP2,OP3) \ { \ int i; \ t=(key[n*2] OP1 R)&0xffffffffL; \ i=key[n*2+1]; \ t=ROTL(t,i); \ L^= (((((*(CAST_LONG *)((unsigned char *) \ CAST_S_table0+((t>>C_2)&C_M)) OP2 \ *(CAST_LONG *)((unsigned char *) \ CAST_S_table1+((t<<C_3)&C_M)))&0xffffffffL) OP3 \ *(CAST_LONG *)((unsigned char *) \ CAST_S_table2+((t>>C_0)&C_M)))&0xffffffffL) OP1 \ *(CAST_LONG *)((unsigned char *) \ CAST_S_table3+((t>>C_1)&C_M)))&0xffffffffL; \ } #elif defined(CAST_PTR2) # define E_CAST(n,key,L,R,OP1,OP2,OP3) \ { \ int i; \ CAST_LONG u,v,w; \ w=(key[n*2] OP1 R)&0xffffffffL; \ i=key[n*2+1]; \ w=ROTL(w,i); \ u=w>>C_2; \ v=w<<C_3; \ u&=C_M; \ v&=C_M; \ t= *(CAST_LONG *)((unsigned char *)CAST_S_table0+u); \ u=w>>C_0; \ t=(t OP2 *(CAST_LONG *)((unsigned char *)CAST_S_table1+v))&0xffffffffL;\ v=w>>C_1; \ u&=C_M; \ v&=C_M; \ t=(t OP3 *(CAST_LONG *)((unsigned char *)CAST_S_table2+u)&0xffffffffL);\ t=(t OP1 *(CAST_LONG *)((unsigned char *)CAST_S_table3+v)&0xffffffffL);\ L^=(t&0xffffffff); \ } #else # define E_CAST(n,key,L,R,OP1,OP2,OP3) \ { \ CAST_LONG a,b,c,d; \ t=(key[n*2] OP1 R)&0xffffffff; \ t=ROTL(t,(key[n*2+1])); \ a=CAST_S_table0[(t>> 8)&0xff]; \ b=CAST_S_table1[(t )&0xff]; \ c=CAST_S_table2[(t>>24)&0xff]; \ d=CAST_S_table3[(t>>16)&0xff]; \ L^=(((((a OP2 b)&0xffffffffL) OP3 c)&0xffffffffL) OP1 d)&0xffffffffL; \ } #endif extern const CAST_LONG CAST_S_table0[256]; extern const CAST_LONG CAST_S_table1[256]; extern const CAST_LONG CAST_S_table2[256]; extern const CAST_LONG CAST_S_table3[256]; extern const CAST_LONG CAST_S_table4[256]; extern const CAST_LONG CAST_S_table5[256]; extern const CAST_LONG CAST_S_table6[256]; extern const CAST_LONG CAST_S_table7[256];
./openssl/crypto/cast/cast_s.h
/* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ const CAST_LONG CAST_S_table0[256] = { 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf, }; const CAST_LONG CAST_S_table1[256] = { 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1, }; const CAST_LONG CAST_S_table2[256] = { 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783, }; const CAST_LONG CAST_S_table3[256] = { 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2, }; const CAST_LONG CAST_S_table4[256] = { 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4, }; const CAST_LONG CAST_S_table5[256] = { 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f, }; const CAST_LONG CAST_S_table6[256] = { 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3, }; const CAST_LONG CAST_S_table7[256] = { 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e, };
./openssl/crypto/cast/c_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 */ /* * CAST low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/cast.h> #include "cast_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 CAST_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, const CAST_KEY *schedule, unsigned char *ivec, int *num, int enc) { register CAST_LONG v0, v1, t; register int n = *num; register long l = length; CAST_LONG ti[2]; unsigned char *iv, c, cc; iv = ivec; if (enc) { while (l--) { if (n == 0) { n2l(iv, v0); ti[0] = v0; n2l(iv, v1); ti[1] = v1; CAST_encrypt((CAST_LONG *)ti, schedule); iv = ivec; t = ti[0]; l2n(t, iv); t = ti[1]; l2n(t, iv); iv = 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; CAST_encrypt((CAST_LONG *)ti, schedule); iv = ivec; t = ti[0]; l2n(t, iv); t = ti[1]; l2n(t, iv); iv = 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/sm2/sm2_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 "crypto/sm2err.h" #ifndef OPENSSL_NO_SM2 # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA SM2_str_reasons[] = { {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_ASN1_ERROR), "asn1 error"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_BAD_SIGNATURE), "bad signature"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_BUFFER_TOO_SMALL), "buffer too small"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_DIST_ID_TOO_LARGE), "dist id too large"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_ID_NOT_SET), "id not set"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_ID_TOO_LARGE), "id too large"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_CURVE), "invalid curve"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_DIGEST), "invalid digest"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_DIGEST_TYPE), "invalid digest type"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_ENCODING), "invalid encoding"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_FIELD), "invalid field"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_PRIVATE_KEY), "invalid private key"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_NO_PARAMETERS_SET), "no parameters set"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_USER_ID_TOO_LARGE), "user id too large"}, {0, NULL} }; # endif int ossl_err_load_SM2_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(SM2_str_reasons[0].error) == NULL) ERR_load_strings_const(SM2_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
./openssl/crypto/sm2/sm2_sign.c
/* * Copyright 2017-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * Ported from Ribose contributions from Botan. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/deprecated.h" #include "crypto/sm2.h" #include "crypto/sm2err.h" #include "crypto/ec.h" /* ossl_ec_group_do_inverse_ord() */ #include "internal/numbers.h" #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/bn.h> #include <string.h> int ossl_sm2_compute_z_digest(uint8_t *out, const EVP_MD *digest, const uint8_t *id, const size_t id_len, const EC_KEY *key) { int rc = 0; const EC_GROUP *group = EC_KEY_get0_group(key); BN_CTX *ctx = NULL; EVP_MD_CTX *hash = NULL; BIGNUM *p = NULL; BIGNUM *a = NULL; BIGNUM *b = NULL; BIGNUM *xG = NULL; BIGNUM *yG = NULL; BIGNUM *xA = NULL; BIGNUM *yA = NULL; int p_bytes = 0; uint8_t *buf = NULL; uint16_t entl = 0; uint8_t e_byte = 0; hash = EVP_MD_CTX_new(); if (hash == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } ctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(key)); if (ctx == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } p = BN_CTX_get(ctx); a = BN_CTX_get(ctx); b = BN_CTX_get(ctx); xG = BN_CTX_get(ctx); yG = BN_CTX_get(ctx); xA = BN_CTX_get(ctx); yA = BN_CTX_get(ctx); if (yA == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } if (!EVP_DigestInit(hash, digest)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } /* Z = h(ENTL || ID || a || b || xG || yG || xA || yA) */ if (id_len >= (UINT16_MAX / 8)) { /* too large */ ERR_raise(ERR_LIB_SM2, SM2_R_ID_TOO_LARGE); goto done; } entl = (uint16_t)(8 * id_len); e_byte = entl >> 8; if (!EVP_DigestUpdate(hash, &e_byte, 1)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } e_byte = entl & 0xFF; if (!EVP_DigestUpdate(hash, &e_byte, 1)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } if (id_len > 0 && !EVP_DigestUpdate(hash, id, id_len)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } if (!EC_GROUP_get_curve(group, p, a, b, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } p_bytes = BN_num_bytes(p); buf = OPENSSL_zalloc(p_bytes); if (buf == NULL) goto done; if (BN_bn2binpad(a, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || BN_bn2binpad(b, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || !EC_POINT_get_affine_coordinates(group, EC_GROUP_get0_generator(group), xG, yG, ctx) || BN_bn2binpad(xG, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || BN_bn2binpad(yG, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || !EC_POINT_get_affine_coordinates(group, EC_KEY_get0_public_key(key), xA, yA, ctx) || BN_bn2binpad(xA, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || BN_bn2binpad(yA, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || !EVP_DigestFinal(hash, out, NULL)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } rc = 1; done: OPENSSL_free(buf); BN_CTX_free(ctx); EVP_MD_CTX_free(hash); return rc; } static BIGNUM *sm2_compute_msg_hash(const EVP_MD *digest, const EC_KEY *key, const uint8_t *id, const size_t id_len, const uint8_t *msg, size_t msg_len) { EVP_MD_CTX *hash = EVP_MD_CTX_new(); const int md_size = EVP_MD_get_size(digest); uint8_t *z = NULL; BIGNUM *e = NULL; EVP_MD *fetched_digest = NULL; OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key); const char *propq = ossl_ec_key_get0_propq(key); if (md_size < 0) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_DIGEST); goto done; } if (hash == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } z = OPENSSL_zalloc(md_size); if (z == NULL) goto done; fetched_digest = EVP_MD_fetch(libctx, EVP_MD_get0_name(digest), propq); if (fetched_digest == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } if (!ossl_sm2_compute_z_digest(z, fetched_digest, id, id_len, key)) { /* SM2err already called */ goto done; } if (!EVP_DigestInit(hash, fetched_digest) || !EVP_DigestUpdate(hash, z, md_size) || !EVP_DigestUpdate(hash, msg, msg_len) /* reuse z buffer to hold H(Z || M) */ || !EVP_DigestFinal(hash, z, NULL)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } e = BN_bin2bn(z, md_size, NULL); if (e == NULL) ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); done: EVP_MD_free(fetched_digest); OPENSSL_free(z); EVP_MD_CTX_free(hash); return e; } static ECDSA_SIG *sm2_sig_gen(const EC_KEY *key, const BIGNUM *e) { const BIGNUM *dA = EC_KEY_get0_private_key(key); const EC_GROUP *group = EC_KEY_get0_group(key); const BIGNUM *order = EC_GROUP_get0_order(group); ECDSA_SIG *sig = NULL; EC_POINT *kG = NULL; BN_CTX *ctx = NULL; BIGNUM *k = NULL; BIGNUM *rk = NULL; BIGNUM *r = NULL; BIGNUM *s = NULL; BIGNUM *x1 = NULL; BIGNUM *tmp = NULL; OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key); kG = EC_POINT_new(group); if (kG == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } ctx = BN_CTX_new_ex(libctx); if (ctx == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } BN_CTX_start(ctx); k = BN_CTX_get(ctx); rk = BN_CTX_get(ctx); x1 = BN_CTX_get(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } /* * These values are returned and so should not be allocated out of the * context */ r = BN_new(); s = BN_new(); if (r == NULL || s == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } /* * A3: Generate a random number k in [1,n-1] using random number generators; * A4: Compute (x1,y1)=[k]G, and convert the type of data x1 to be integer * as specified in clause 4.2.8 of GM/T 0003.1-2012; * A5: Compute r=(e+x1) mod n. If r=0 or r+k=n, then go to A3; * A6: Compute s=(1/(1+dA)*(k-r*dA)) mod n. If s=0, then go to A3; * A7: Convert the type of data (r,s) to be bit strings according to the details * in clause 4.2.2 of GM/T 0003.1-2012. Then the signature of message M is (r,s). */ for (;;) { if (!BN_priv_rand_range_ex(k, order, 0, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } if (!EC_POINT_mul(group, kG, k, NULL, NULL, ctx) || !EC_POINT_get_affine_coordinates(group, kG, x1, NULL, ctx) || !BN_mod_add(r, e, x1, order, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } /* try again if r == 0 or r+k == n */ if (BN_is_zero(r)) continue; if (!BN_add(rk, r, k)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } if (BN_cmp(rk, order) == 0) continue; if (!BN_add(s, dA, BN_value_one()) || !ossl_ec_group_do_inverse_ord(group, s, s, ctx) || !BN_mod_mul(tmp, dA, r, order, ctx) || !BN_sub(tmp, k, tmp) || !BN_mod_mul(s, s, tmp, order, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } /* try again if s == 0 */ if (BN_is_zero(s)) continue; sig = ECDSA_SIG_new(); if (sig == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_ECDSA_LIB); goto done; } /* takes ownership of r and s */ ECDSA_SIG_set0(sig, r, s); break; } done: if (sig == NULL) { BN_free(r); BN_free(s); } BN_CTX_free(ctx); EC_POINT_free(kG); return sig; } static int sm2_sig_verify(const EC_KEY *key, const ECDSA_SIG *sig, const BIGNUM *e) { int ret = 0; const EC_GROUP *group = EC_KEY_get0_group(key); const BIGNUM *order = EC_GROUP_get0_order(group); BN_CTX *ctx = NULL; EC_POINT *pt = NULL; BIGNUM *t = NULL; BIGNUM *x1 = NULL; const BIGNUM *r = NULL; const BIGNUM *s = NULL; OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key); ctx = BN_CTX_new_ex(libctx); pt = EC_POINT_new(group); if (ctx == NULL || pt == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } BN_CTX_start(ctx); t = BN_CTX_get(ctx); x1 = BN_CTX_get(ctx); if (x1 == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } /* * B1: verify whether r' in [1,n-1], verification failed if not * B2: verify whether s' in [1,n-1], verification failed if not * B3: set M'~=ZA || M' * B4: calculate e'=Hv(M'~) * B5: calculate t = (r' + s') modn, verification failed if t=0 * B6: calculate the point (x1', y1')=[s']G + [t]PA * B7: calculate R=(e'+x1') modn, verification pass if yes, otherwise failed */ ECDSA_SIG_get0(sig, &r, &s); if (BN_cmp(r, BN_value_one()) < 0 || BN_cmp(s, BN_value_one()) < 0 || BN_cmp(order, r) <= 0 || BN_cmp(order, s) <= 0) { ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE); goto done; } if (!BN_mod_add(t, r, s, order, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } if (BN_is_zero(t)) { ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE); goto done; } if (!EC_POINT_mul(group, pt, s, EC_KEY_get0_public_key(key), t, ctx) || !EC_POINT_get_affine_coordinates(group, pt, x1, NULL, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } if (!BN_mod_add(t, e, x1, order, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } if (BN_cmp(r, t) == 0) ret = 1; done: BN_CTX_end(ctx); EC_POINT_free(pt); BN_CTX_free(ctx); return ret; } ECDSA_SIG *ossl_sm2_do_sign(const EC_KEY *key, const EVP_MD *digest, const uint8_t *id, const size_t id_len, const uint8_t *msg, size_t msg_len) { BIGNUM *e = NULL; ECDSA_SIG *sig = NULL; e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len); if (e == NULL) { /* SM2err already called */ goto done; } sig = sm2_sig_gen(key, e); done: BN_free(e); return sig; } int ossl_sm2_do_verify(const EC_KEY *key, const EVP_MD *digest, const ECDSA_SIG *sig, const uint8_t *id, const size_t id_len, const uint8_t *msg, size_t msg_len) { BIGNUM *e = NULL; int ret = 0; e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len); if (e == NULL) { /* SM2err already called */ goto done; } ret = sm2_sig_verify(key, sig, e); done: BN_free(e); return ret; } int ossl_sm2_internal_sign(const unsigned char *dgst, int dgstlen, unsigned char *sig, unsigned int *siglen, EC_KEY *eckey) { BIGNUM *e = NULL; ECDSA_SIG *s = NULL; int sigleni; int ret = -1; e = BN_bin2bn(dgst, dgstlen, NULL); if (e == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } s = sm2_sig_gen(eckey, e); if (s == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } sigleni = i2d_ECDSA_SIG(s, sig != NULL ? &sig : NULL); if (sigleni < 0) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } *siglen = (unsigned int)sigleni; ret = 1; done: ECDSA_SIG_free(s); BN_free(e); return ret; } int ossl_sm2_internal_verify(const unsigned char *dgst, int dgstlen, const unsigned char *sig, int sig_len, EC_KEY *eckey) { ECDSA_SIG *s = NULL; BIGNUM *e = NULL; const unsigned char *p = sig; unsigned char *der = NULL; int derlen = -1; int ret = -1; s = ECDSA_SIG_new(); if (s == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_ECDSA_LIB); goto done; } if (d2i_ECDSA_SIG(&s, &p, sig_len) == NULL) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING); goto done; } /* Ensure signature uses DER and doesn't have trailing garbage */ derlen = i2d_ECDSA_SIG(s, &der); if (derlen != sig_len || memcmp(sig, der, derlen) != 0) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING); goto done; } e = BN_bin2bn(dgst, dgstlen, NULL); if (e == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } ret = sm2_sig_verify(eckey, s, e); done: OPENSSL_free(der); BN_free(e); ECDSA_SIG_free(s); return ret; }
./openssl/crypto/sm2/sm2_key.c
/* * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/deprecated.h" /* to be able to use EC_KEY and EC_GROUP */ #include <openssl/err.h> #include "crypto/sm2err.h" #include "crypto/sm2.h" #include <openssl/ec.h> /* EC_KEY and EC_GROUP functions */ /* * SM2 key generation is implemented within ec_generate_key() in * crypto/ec/ec_key.c */ int ossl_sm2_key_private_check(const EC_KEY *eckey) { int ret = 0; BIGNUM *max = NULL; const EC_GROUP *group = NULL; const BIGNUM *priv_key = NULL, *order = NULL; if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL || (priv_key = EC_KEY_get0_private_key(eckey)) == NULL || (order = EC_GROUP_get0_order(group)) == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* range of SM2 private key is [1, n-1) */ max = BN_dup(order); if (max == NULL || !BN_sub_word(max, 1)) goto end; if (BN_cmp(priv_key, BN_value_one()) < 0 || BN_cmp(priv_key, max) >= 0) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_PRIVATE_KEY); goto end; } ret = 1; end: BN_free(max); return ret; }
./openssl/crypto/sm2/sm2_crypt.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * Ported from Ribose contributions from Botan. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "crypto/sm2.h" #include "crypto/sm2err.h" #include "crypto/ec.h" /* ossl_ecdh_kdf_X9_63() */ #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/bn.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <string.h> typedef struct SM2_Ciphertext_st SM2_Ciphertext; DECLARE_ASN1_FUNCTIONS(SM2_Ciphertext) struct SM2_Ciphertext_st { BIGNUM *C1x; BIGNUM *C1y; ASN1_OCTET_STRING *C3; ASN1_OCTET_STRING *C2; }; ASN1_SEQUENCE(SM2_Ciphertext) = { ASN1_SIMPLE(SM2_Ciphertext, C1x, BIGNUM), ASN1_SIMPLE(SM2_Ciphertext, C1y, BIGNUM), ASN1_SIMPLE(SM2_Ciphertext, C3, ASN1_OCTET_STRING), ASN1_SIMPLE(SM2_Ciphertext, C2, ASN1_OCTET_STRING), } ASN1_SEQUENCE_END(SM2_Ciphertext) IMPLEMENT_ASN1_FUNCTIONS(SM2_Ciphertext) static size_t ec_field_size(const EC_GROUP *group) { /* Is there some simpler way to do this? */ BIGNUM *p = BN_new(); BIGNUM *a = BN_new(); BIGNUM *b = BN_new(); size_t field_size = 0; if (p == NULL || a == NULL || b == NULL) goto done; if (!EC_GROUP_get_curve(group, p, a, b, NULL)) goto done; field_size = (BN_num_bits(p) + 7) / 8; done: BN_free(p); BN_free(a); BN_free(b); return field_size; } int ossl_sm2_plaintext_size(const unsigned char *ct, size_t ct_size, size_t *pt_size) { struct SM2_Ciphertext_st *sm2_ctext = NULL; sm2_ctext = d2i_SM2_Ciphertext(NULL, &ct, ct_size); if (sm2_ctext == NULL) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING); return 0; } *pt_size = sm2_ctext->C2->length; SM2_Ciphertext_free(sm2_ctext); return 1; } int ossl_sm2_ciphertext_size(const EC_KEY *key, const EVP_MD *digest, size_t msg_len, size_t *ct_size) { const size_t field_size = ec_field_size(EC_KEY_get0_group(key)); const int md_size = EVP_MD_get_size(digest); size_t sz; if (field_size == 0 || md_size < 0) return 0; /* Integer and string are simple type; set constructed = 0, means primitive and definite length encoding. */ sz = 2 * ASN1_object_size(0, field_size + 1, V_ASN1_INTEGER) + ASN1_object_size(0, md_size, V_ASN1_OCTET_STRING) + ASN1_object_size(0, msg_len, V_ASN1_OCTET_STRING); /* Sequence is structured type; set constructed = 1, means constructed and definite length encoding. */ *ct_size = ASN1_object_size(1, sz, V_ASN1_SEQUENCE); return 1; } int ossl_sm2_encrypt(const EC_KEY *key, const EVP_MD *digest, const uint8_t *msg, size_t msg_len, uint8_t *ciphertext_buf, size_t *ciphertext_len) { int rc = 0, ciphertext_leni; size_t i; BN_CTX *ctx = NULL; BIGNUM *k = NULL; BIGNUM *x1 = NULL; BIGNUM *y1 = NULL; BIGNUM *x2 = NULL; BIGNUM *y2 = NULL; EVP_MD_CTX *hash = EVP_MD_CTX_new(); struct SM2_Ciphertext_st ctext_struct; const EC_GROUP *group = EC_KEY_get0_group(key); const BIGNUM *order = EC_GROUP_get0_order(group); const EC_POINT *P = EC_KEY_get0_public_key(key); EC_POINT *kG = NULL; EC_POINT *kP = NULL; uint8_t *msg_mask = NULL; uint8_t *x2y2 = NULL; uint8_t *C3 = NULL; size_t field_size; const int C3_size = EVP_MD_get_size(digest); EVP_MD *fetched_digest = NULL; OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key); const char *propq = ossl_ec_key_get0_propq(key); /* NULL these before any "goto done" */ ctext_struct.C2 = NULL; ctext_struct.C3 = NULL; if (hash == NULL || C3_size <= 0) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } field_size = ec_field_size(group); if (field_size == 0) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } kG = EC_POINT_new(group); kP = EC_POINT_new(group); if (kG == NULL || kP == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } ctx = BN_CTX_new_ex(libctx); if (ctx == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } BN_CTX_start(ctx); k = BN_CTX_get(ctx); x1 = BN_CTX_get(ctx); x2 = BN_CTX_get(ctx); y1 = BN_CTX_get(ctx); y2 = BN_CTX_get(ctx); if (y2 == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } x2y2 = OPENSSL_zalloc(2 * field_size); C3 = OPENSSL_zalloc(C3_size); if (x2y2 == NULL || C3 == NULL) goto done; memset(ciphertext_buf, 0, *ciphertext_len); if (!BN_priv_rand_range_ex(k, order, 0, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } if (!EC_POINT_mul(group, kG, k, NULL, NULL, ctx) || !EC_POINT_get_affine_coordinates(group, kG, x1, y1, ctx) || !EC_POINT_mul(group, kP, NULL, P, k, ctx) || !EC_POINT_get_affine_coordinates(group, kP, x2, y2, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } if (BN_bn2binpad(x2, x2y2, field_size) < 0 || BN_bn2binpad(y2, x2y2 + field_size, field_size) < 0) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } msg_mask = OPENSSL_zalloc(msg_len); if (msg_mask == NULL) goto done; /* X9.63 with no salt happens to match the KDF used in SM2 */ if (!ossl_ecdh_kdf_X9_63(msg_mask, msg_len, x2y2, 2 * field_size, NULL, 0, digest, libctx, propq)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } for (i = 0; i != msg_len; ++i) msg_mask[i] ^= msg[i]; fetched_digest = EVP_MD_fetch(libctx, EVP_MD_get0_name(digest), propq); if (fetched_digest == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } if (EVP_DigestInit(hash, fetched_digest) == 0 || EVP_DigestUpdate(hash, x2y2, field_size) == 0 || EVP_DigestUpdate(hash, msg, msg_len) == 0 || EVP_DigestUpdate(hash, x2y2 + field_size, field_size) == 0 || EVP_DigestFinal(hash, C3, NULL) == 0) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } ctext_struct.C1x = x1; ctext_struct.C1y = y1; ctext_struct.C3 = ASN1_OCTET_STRING_new(); ctext_struct.C2 = ASN1_OCTET_STRING_new(); if (ctext_struct.C3 == NULL || ctext_struct.C2 == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_ASN1_LIB); goto done; } if (!ASN1_OCTET_STRING_set(ctext_struct.C3, C3, C3_size) || !ASN1_OCTET_STRING_set(ctext_struct.C2, msg_mask, msg_len)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } ciphertext_leni = i2d_SM2_Ciphertext(&ctext_struct, &ciphertext_buf); /* Ensure cast to size_t is safe */ if (ciphertext_leni < 0) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } *ciphertext_len = (size_t)ciphertext_leni; rc = 1; done: EVP_MD_free(fetched_digest); ASN1_OCTET_STRING_free(ctext_struct.C2); ASN1_OCTET_STRING_free(ctext_struct.C3); OPENSSL_free(msg_mask); OPENSSL_free(x2y2); OPENSSL_free(C3); EVP_MD_CTX_free(hash); BN_CTX_free(ctx); EC_POINT_free(kG); EC_POINT_free(kP); return rc; } int ossl_sm2_decrypt(const EC_KEY *key, const EVP_MD *digest, const uint8_t *ciphertext, size_t ciphertext_len, uint8_t *ptext_buf, size_t *ptext_len) { int rc = 0; int i; BN_CTX *ctx = NULL; const EC_GROUP *group = EC_KEY_get0_group(key); EC_POINT *C1 = NULL; struct SM2_Ciphertext_st *sm2_ctext = NULL; BIGNUM *x2 = NULL; BIGNUM *y2 = NULL; uint8_t *x2y2 = NULL; uint8_t *computed_C3 = NULL; const size_t field_size = ec_field_size(group); const int hash_size = EVP_MD_get_size(digest); uint8_t *msg_mask = NULL; const uint8_t *C2 = NULL; const uint8_t *C3 = NULL; int msg_len = 0; EVP_MD_CTX *hash = NULL; OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key); const char *propq = ossl_ec_key_get0_propq(key); if (field_size == 0 || hash_size <= 0) goto done; memset(ptext_buf, 0xFF, *ptext_len); sm2_ctext = d2i_SM2_Ciphertext(NULL, &ciphertext, ciphertext_len); if (sm2_ctext == NULL) { ERR_raise(ERR_LIB_SM2, SM2_R_ASN1_ERROR); goto done; } if (sm2_ctext->C3->length != hash_size) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING); goto done; } C2 = sm2_ctext->C2->data; C3 = sm2_ctext->C3->data; msg_len = sm2_ctext->C2->length; if (*ptext_len < (size_t)msg_len) { ERR_raise(ERR_LIB_SM2, SM2_R_BUFFER_TOO_SMALL); goto done; } ctx = BN_CTX_new_ex(libctx); if (ctx == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } BN_CTX_start(ctx); x2 = BN_CTX_get(ctx); y2 = BN_CTX_get(ctx); if (y2 == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } msg_mask = OPENSSL_zalloc(msg_len); x2y2 = OPENSSL_zalloc(2 * field_size); computed_C3 = OPENSSL_zalloc(hash_size); if (msg_mask == NULL || x2y2 == NULL || computed_C3 == NULL) goto done; C1 = EC_POINT_new(group); if (C1 == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } if (!EC_POINT_set_affine_coordinates(group, C1, sm2_ctext->C1x, sm2_ctext->C1y, ctx) || !EC_POINT_mul(group, C1, NULL, C1, EC_KEY_get0_private_key(key), ctx) || !EC_POINT_get_affine_coordinates(group, C1, x2, y2, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } if (BN_bn2binpad(x2, x2y2, field_size) < 0 || BN_bn2binpad(y2, x2y2 + field_size, field_size) < 0 || !ossl_ecdh_kdf_X9_63(msg_mask, msg_len, x2y2, 2 * field_size, NULL, 0, digest, libctx, propq)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } for (i = 0; i != msg_len; ++i) ptext_buf[i] = C2[i] ^ msg_mask[i]; hash = EVP_MD_CTX_new(); if (hash == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } if (!EVP_DigestInit(hash, digest) || !EVP_DigestUpdate(hash, x2y2, field_size) || !EVP_DigestUpdate(hash, ptext_buf, msg_len) || !EVP_DigestUpdate(hash, x2y2 + field_size, field_size) || !EVP_DigestFinal(hash, computed_C3, NULL)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } if (CRYPTO_memcmp(computed_C3, C3, hash_size) != 0) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_DIGEST); goto done; } rc = 1; *ptext_len = msg_len; done: if (rc == 0) memset(ptext_buf, 0, *ptext_len); OPENSSL_free(msg_mask); OPENSSL_free(x2y2); OPENSSL_free(computed_C3); EC_POINT_free(C1); BN_CTX_free(ctx); SM2_Ciphertext_free(sm2_ctext); EVP_MD_CTX_free(hash); return rc; }
./openssl/crypto/ess/ess_lib.c
/* * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/ess.h> #include "internal/sizes.h" #include "crypto/ess.h" #include "crypto/x509.h" static ESS_CERT_ID *ESS_CERT_ID_new_init(const X509 *cert, int set_issuer_serial); static ESS_CERT_ID_V2 *ESS_CERT_ID_V2_new_init(const EVP_MD *hash_alg, const X509 *cert, int set_issuer_serial); ESS_SIGNING_CERT *OSSL_ESS_signing_cert_new_init(const X509 *signcert, const STACK_OF(X509) *certs, int set_issuer_serial) { ESS_CERT_ID *cid = NULL; ESS_SIGNING_CERT *sc; int i; if ((sc = ESS_SIGNING_CERT_new()) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ESS_LIB); goto err; } if (sc->cert_ids == NULL && (sc->cert_ids = sk_ESS_CERT_ID_new_null()) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_CRYPTO_LIB); goto err; } if ((cid = ESS_CERT_ID_new_init(signcert, set_issuer_serial)) == NULL || !sk_ESS_CERT_ID_push(sc->cert_ids, cid)) { ERR_raise(ERR_LIB_ESS, ERR_R_ESS_LIB); goto err; } for (i = 0; i < sk_X509_num(certs); ++i) { X509 *cert = sk_X509_value(certs, i); if ((cid = ESS_CERT_ID_new_init(cert, 1)) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ESS_LIB); goto err; } if (!sk_ESS_CERT_ID_push(sc->cert_ids, cid)) { ERR_raise(ERR_LIB_ESS, ERR_R_CRYPTO_LIB); goto err; } } return sc; err: ESS_SIGNING_CERT_free(sc); ESS_CERT_ID_free(cid); return NULL; } static ESS_CERT_ID *ESS_CERT_ID_new_init(const X509 *cert, int set_issuer_serial) { ESS_CERT_ID *cid = NULL; GENERAL_NAME *name = NULL; unsigned char cert_sha1[SHA_DIGEST_LENGTH]; if ((cid = ESS_CERT_ID_new()) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ESS_LIB); goto err; } if (!X509_digest(cert, EVP_sha1(), cert_sha1, NULL)) { ERR_raise(ERR_LIB_ESS, ERR_R_X509_LIB); goto err; } if (!ASN1_OCTET_STRING_set(cid->hash, cert_sha1, SHA_DIGEST_LENGTH)) { ERR_raise(ERR_LIB_ESS, ERR_R_ASN1_LIB); goto err; } /* Setting the issuer/serial if requested. */ if (!set_issuer_serial) return cid; if (cid->issuer_serial == NULL && (cid->issuer_serial = ESS_ISSUER_SERIAL_new()) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ESS_LIB); goto err; } if ((name = GENERAL_NAME_new()) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ASN1_LIB); goto err; } name->type = GEN_DIRNAME; if ((name->d.dirn = X509_NAME_dup(X509_get_issuer_name(cert))) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_X509_LIB); goto err; } if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name)) { ERR_raise(ERR_LIB_ESS, ERR_R_CRYPTO_LIB); goto err; } name = NULL; /* Ownership is lost. */ ASN1_INTEGER_free(cid->issuer_serial->serial); if ((cid->issuer_serial->serial = ASN1_INTEGER_dup(X509_get0_serialNumber(cert))) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ASN1_LIB); goto err; } return cid; err: GENERAL_NAME_free(name); ESS_CERT_ID_free(cid); return NULL; } ESS_SIGNING_CERT_V2 *OSSL_ESS_signing_cert_v2_new_init(const EVP_MD *hash_alg, const X509 *signcert, const STACK_OF(X509) *certs, int set_issuer_serial) { ESS_CERT_ID_V2 *cid = NULL; ESS_SIGNING_CERT_V2 *sc; int i; if ((sc = ESS_SIGNING_CERT_V2_new()) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ESS_LIB); goto err; } cid = ESS_CERT_ID_V2_new_init(hash_alg, signcert, set_issuer_serial); if (cid == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ESS_LIB); goto err; } if (!sk_ESS_CERT_ID_V2_push(sc->cert_ids, cid)) { ERR_raise(ERR_LIB_ESS, ERR_R_CRYPTO_LIB); goto err; } cid = NULL; for (i = 0; i < sk_X509_num(certs); ++i) { X509 *cert = sk_X509_value(certs, i); if ((cid = ESS_CERT_ID_V2_new_init(hash_alg, cert, 1)) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ESS_LIB); goto err; } if (!sk_ESS_CERT_ID_V2_push(sc->cert_ids, cid)) { ERR_raise(ERR_LIB_ESS, ERR_R_CRYPTO_LIB); goto err; } cid = NULL; } return sc; err: ESS_SIGNING_CERT_V2_free(sc); ESS_CERT_ID_V2_free(cid); return NULL; } static ESS_CERT_ID_V2 *ESS_CERT_ID_V2_new_init(const EVP_MD *hash_alg, const X509 *cert, int set_issuer_serial) { ESS_CERT_ID_V2 *cid; GENERAL_NAME *name = NULL; unsigned char hash[EVP_MAX_MD_SIZE]; unsigned int hash_len = sizeof(hash); X509_ALGOR *alg = NULL; memset(hash, 0, sizeof(hash)); if ((cid = ESS_CERT_ID_V2_new()) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ESS_LIB); goto err; } if (!EVP_MD_is_a(hash_alg, SN_sha256)) { alg = X509_ALGOR_new(); if (alg == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ASN1_LIB); goto err; } X509_ALGOR_set_md(alg, hash_alg); if (alg->algorithm == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ASN1_LIB); goto err; } cid->hash_alg = alg; alg = NULL; } else { cid->hash_alg = NULL; } if (!X509_digest(cert, hash_alg, hash, &hash_len)) { ERR_raise(ERR_LIB_ESS, ERR_R_X509_LIB); goto err; } if (!ASN1_OCTET_STRING_set(cid->hash, hash, hash_len)) { ERR_raise(ERR_LIB_ESS, ERR_R_ASN1_LIB); goto err; } if (!set_issuer_serial) return cid; if ((cid->issuer_serial = ESS_ISSUER_SERIAL_new()) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ESS_LIB); goto err; } if ((name = GENERAL_NAME_new()) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ASN1_LIB); goto err; } name->type = GEN_DIRNAME; if ((name->d.dirn = X509_NAME_dup(X509_get_issuer_name(cert))) == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ASN1_LIB); goto err; } if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name)) { ERR_raise(ERR_LIB_ESS, ERR_R_CRYPTO_LIB); goto err; } name = NULL; /* Ownership is lost. */ ASN1_INTEGER_free(cid->issuer_serial->serial); cid->issuer_serial->serial = ASN1_INTEGER_dup(X509_get0_serialNumber(cert)); if (cid->issuer_serial->serial == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_ASN1_LIB); goto err; } return cid; err: X509_ALGOR_free(alg); GENERAL_NAME_free(name); ESS_CERT_ID_V2_free(cid); return NULL; } static int ess_issuer_serial_cmp(const ESS_ISSUER_SERIAL *is, const X509 *cert) { GENERAL_NAME *issuer; if (is == NULL || cert == NULL || sk_GENERAL_NAME_num(is->issuer) != 1) return -1; issuer = sk_GENERAL_NAME_value(is->issuer, 0); if (issuer->type != GEN_DIRNAME || X509_NAME_cmp(issuer->d.dirn, X509_get_issuer_name(cert)) != 0) return -1; return ASN1_INTEGER_cmp(is->serial, X509_get0_serialNumber(cert)); } /* * Find the cert in |certs| referenced by |cid| if not NULL, else by |cid_v2|. * The cert must be the first one in |certs| if and only if |index| is 0. * Return 0 on not found, -1 on error, else 1 + the position in |certs|. */ static int find(const ESS_CERT_ID *cid, const ESS_CERT_ID_V2 *cid_v2, int index, const STACK_OF(X509) *certs) { const X509 *cert; EVP_MD *md = NULL; char name[OSSL_MAX_NAME_SIZE]; unsigned char cert_digest[EVP_MAX_MD_SIZE]; unsigned int len, cid_hash_len; const ESS_ISSUER_SERIAL *is; int i; int ret = -1; if (cid == NULL && cid_v2 == NULL) { ERR_raise(ERR_LIB_ESS, ERR_R_PASSED_INVALID_ARGUMENT); return -1; } if (cid != NULL) strcpy(name, "SHA1"); else if (cid_v2->hash_alg == NULL) strcpy(name, "SHA256"); else OBJ_obj2txt(name, sizeof(name), cid_v2->hash_alg->algorithm, 0); (void)ERR_set_mark(); md = EVP_MD_fetch(NULL, name, NULL); if (md == NULL) md = (EVP_MD *)EVP_get_digestbyname(name); if (md == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_ESS, ESS_R_ESS_DIGEST_ALG_UNKNOWN); goto end; } (void)ERR_pop_to_mark(); for (i = 0; i < sk_X509_num(certs); ++i) { cert = sk_X509_value(certs, i); cid_hash_len = cid != NULL ? cid->hash->length : cid_v2->hash->length; if (!X509_digest(cert, md, cert_digest, &len) || cid_hash_len != len) { ERR_raise(ERR_LIB_ESS, ESS_R_ESS_CERT_DIGEST_ERROR); goto end; } if (memcmp(cid != NULL ? cid->hash->data : cid_v2->hash->data, cert_digest, len) == 0) { is = cid != NULL ? cid->issuer_serial : cid_v2->issuer_serial; /* Well, it's not really required to match the serial numbers. */ if (is == NULL || ess_issuer_serial_cmp(is, cert) == 0) { if ((i == 0) == (index == 0)) { ret = i + 1; goto end; } ERR_raise(ERR_LIB_ESS, ESS_R_ESS_CERT_ID_WRONG_ORDER); goto end; } } } ret = 0; ERR_raise(ERR_LIB_ESS, ESS_R_ESS_CERT_ID_NOT_FOUND); end: EVP_MD_free(md); return ret; } int OSSL_ESS_check_signing_certs(const ESS_SIGNING_CERT *ss, const ESS_SIGNING_CERT_V2 *ssv2, const STACK_OF(X509) *chain, int require_signing_cert) { int n_v1 = ss == NULL ? -1 : sk_ESS_CERT_ID_num(ss->cert_ids); int n_v2 = ssv2 == NULL ? -1 : sk_ESS_CERT_ID_V2_num(ssv2->cert_ids); int i, ret; if (require_signing_cert && ss == NULL && ssv2 == NULL) { ERR_raise(ERR_LIB_CMS, ESS_R_MISSING_SIGNING_CERTIFICATE_ATTRIBUTE); return -1; } if (n_v1 == 0 || n_v2 == 0) { ERR_raise(ERR_LIB_ESS, ESS_R_EMPTY_ESS_CERT_ID_LIST); return -1; } /* If both ss and ssv2 exist, as required evaluate them independently. */ for (i = 0; i < n_v1; i++) { ret = find(sk_ESS_CERT_ID_value(ss->cert_ids, i), NULL, i, chain); if (ret <= 0) return ret; } for (i = 0; i < n_v2; i++) { ret = find(NULL, sk_ESS_CERT_ID_V2_value(ssv2->cert_ids, i), i, chain); if (ret <= 0) return ret; } return 1; }
./openssl/crypto/ess/ess_asn1.c
/* * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/asn1t.h> #include <openssl/cms.h> #include <openssl/ess.h> #include <openssl/x509v3.h> #include "crypto/ess.h" /* ASN1 stuff for ESS Structure */ ASN1_SEQUENCE(ESS_ISSUER_SERIAL) = { ASN1_SEQUENCE_OF(ESS_ISSUER_SERIAL, issuer, GENERAL_NAME), ASN1_SIMPLE(ESS_ISSUER_SERIAL, serial, ASN1_INTEGER) } static_ASN1_SEQUENCE_END(ESS_ISSUER_SERIAL) IMPLEMENT_ASN1_FUNCTIONS(ESS_ISSUER_SERIAL) IMPLEMENT_ASN1_DUP_FUNCTION(ESS_ISSUER_SERIAL) ASN1_SEQUENCE(ESS_CERT_ID) = { ASN1_SIMPLE(ESS_CERT_ID, hash, ASN1_OCTET_STRING), ASN1_OPT(ESS_CERT_ID, issuer_serial, ESS_ISSUER_SERIAL) } static_ASN1_SEQUENCE_END(ESS_CERT_ID) IMPLEMENT_ASN1_FUNCTIONS(ESS_CERT_ID) IMPLEMENT_ASN1_DUP_FUNCTION(ESS_CERT_ID) ASN1_SEQUENCE(ESS_SIGNING_CERT) = { ASN1_SEQUENCE_OF(ESS_SIGNING_CERT, cert_ids, ESS_CERT_ID), ASN1_SEQUENCE_OF_OPT(ESS_SIGNING_CERT, policy_info, POLICYINFO) } ASN1_SEQUENCE_END(ESS_SIGNING_CERT) IMPLEMENT_ASN1_FUNCTIONS(ESS_SIGNING_CERT) IMPLEMENT_ASN1_DUP_FUNCTION(ESS_SIGNING_CERT) ASN1_SEQUENCE(ESS_CERT_ID_V2) = { ASN1_OPT(ESS_CERT_ID_V2, hash_alg, X509_ALGOR), ASN1_SIMPLE(ESS_CERT_ID_V2, hash, ASN1_OCTET_STRING), ASN1_OPT(ESS_CERT_ID_V2, issuer_serial, ESS_ISSUER_SERIAL) } static_ASN1_SEQUENCE_END(ESS_CERT_ID_V2) IMPLEMENT_ASN1_FUNCTIONS(ESS_CERT_ID_V2) IMPLEMENT_ASN1_DUP_FUNCTION(ESS_CERT_ID_V2) ASN1_SEQUENCE(ESS_SIGNING_CERT_V2) = { ASN1_SEQUENCE_OF(ESS_SIGNING_CERT_V2, cert_ids, ESS_CERT_ID_V2), ASN1_SEQUENCE_OF_OPT(ESS_SIGNING_CERT_V2, policy_info, POLICYINFO) } ASN1_SEQUENCE_END(ESS_SIGNING_CERT_V2) IMPLEMENT_ASN1_FUNCTIONS(ESS_SIGNING_CERT_V2) IMPLEMENT_ASN1_DUP_FUNCTION(ESS_SIGNING_CERT_V2)
./openssl/crypto/ess/ess_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/esserr.h> #include "crypto/esserr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA ESS_str_reasons[] = { {ERR_PACK(ERR_LIB_ESS, 0, ESS_R_EMPTY_ESS_CERT_ID_LIST), "empty ess cert id list"}, {ERR_PACK(ERR_LIB_ESS, 0, ESS_R_ESS_CERT_DIGEST_ERROR), "ess cert digest error"}, {ERR_PACK(ERR_LIB_ESS, 0, ESS_R_ESS_CERT_ID_NOT_FOUND), "ess cert id not found"}, {ERR_PACK(ERR_LIB_ESS, 0, ESS_R_ESS_CERT_ID_WRONG_ORDER), "ess cert id wrong order"}, {ERR_PACK(ERR_LIB_ESS, 0, ESS_R_ESS_DIGEST_ALG_UNKNOWN), "ess digest alg unknown"}, {ERR_PACK(ERR_LIB_ESS, 0, ESS_R_ESS_SIGNING_CERTIFICATE_ERROR), "ess signing certificate error"}, {ERR_PACK(ERR_LIB_ESS, 0, ESS_R_ESS_SIGNING_CERT_ADD_ERROR), "ess signing cert add error"}, {ERR_PACK(ERR_LIB_ESS, 0, ESS_R_ESS_SIGNING_CERT_V2_ADD_ERROR), "ess signing cert v2 add error"}, {ERR_PACK(ERR_LIB_ESS, 0, ESS_R_MISSING_SIGNING_CERTIFICATE_ATTRIBUTE), "missing signing certificate attribute"}, {0, NULL} }; #endif int ossl_err_load_ESS_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(ESS_str_reasons[0].error) == NULL) ERR_load_strings_const(ESS_str_reasons); #endif return 1; }
./openssl/crypto/srp/srp_vfy.c
/* * Copyright 2004-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2004, EdelKey Project. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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 Christophe Renou and Peter Sylvester, * for the EdelKey project. */ /* All the SRP APIs in this file are deprecated */ #define OPENSSL_SUPPRESS_DEPRECATED #ifndef OPENSSL_NO_SRP # include "internal/cryptlib.h" # include "crypto/evp.h" # include <openssl/sha.h> # include <openssl/srp.h> # include <openssl/evp.h> # include <openssl/buffer.h> # include <openssl/rand.h> # include <openssl/txt_db.h> # include <openssl/err.h> # define SRP_RANDOM_SALT_LEN 20 # define MAX_LEN 2500 /* * Note that SRP uses its own variant of base 64 encoding. A different base64 * alphabet is used and no padding '=' characters are added. Instead we pad to * the front with 0 bytes and subsequently strip off leading encoded padding. * This variant is used for compatibility with other SRP implementations - * notably libsrp, but also others. It is also required for backwards * compatibility in order to load verifier files from other OpenSSL versions. */ /* * Convert a base64 string into raw byte array representation. * Returns the length of the decoded data, or -1 on error. */ static int t_fromb64(unsigned char *a, size_t alen, const char *src) { EVP_ENCODE_CTX *ctx; int outl = 0, outl2 = 0; size_t size, padsize; const unsigned char *pad = (const unsigned char *)"00"; while (*src == ' ' || *src == '\t' || *src == '\n') ++src; size = strlen(src); padsize = 4 - (size & 3); padsize &= 3; /* Four bytes in src become three bytes output. */ if (size > INT_MAX || ((size + padsize) / 4) * 3 > alen) return -1; ctx = EVP_ENCODE_CTX_new(); if (ctx == NULL) return -1; /* * This should never occur because 1 byte of data always requires 2 bytes of * encoding, i.e. * 0 bytes unencoded = 0 bytes encoded * 1 byte unencoded = 2 bytes encoded * 2 bytes unencoded = 3 bytes encoded * 3 bytes unencoded = 4 bytes encoded * 4 bytes unencoded = 6 bytes encoded * etc */ if (padsize == 3) { outl = -1; goto err; } /* Valid padsize values are now 0, 1 or 2 */ EVP_DecodeInit(ctx); evp_encode_ctx_set_flags(ctx, EVP_ENCODE_CTX_USE_SRP_ALPHABET); /* Add any encoded padding that is required */ if (padsize != 0 && EVP_DecodeUpdate(ctx, a, &outl, pad, padsize) < 0) { outl = -1; goto err; } if (EVP_DecodeUpdate(ctx, a, &outl2, (const unsigned char *)src, size) < 0) { outl = -1; goto err; } outl += outl2; EVP_DecodeFinal(ctx, a + outl, &outl2); outl += outl2; /* Strip off the leading padding */ if (padsize != 0) { if ((int)padsize >= outl) { outl = -1; goto err; } /* * If we added 1 byte of padding prior to encoding then we have 2 bytes * of "real" data which gets spread across 4 encoded bytes like this: * (6 bits pad)(2 bits pad | 4 bits data)(6 bits data)(6 bits data) * So 1 byte of pre-encoding padding results in 1 full byte of encoded * padding. * If we added 2 bytes of padding prior to encoding this gets encoded * as: * (6 bits pad)(6 bits pad)(4 bits pad | 2 bits data)(6 bits data) * So 2 bytes of pre-encoding padding results in 2 full bytes of encoded * padding, i.e. we have to strip the same number of bytes of padding * from the encoded data as we added to the pre-encoded data. */ memmove(a, a + padsize, outl - padsize); outl -= padsize; } err: EVP_ENCODE_CTX_free(ctx); return outl; } /* * Convert a raw byte string into a null-terminated base64 ASCII string. * Returns 1 on success or 0 on error. */ static int t_tob64(char *dst, const unsigned char *src, int size) { EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new(); int outl = 0, outl2 = 0; unsigned char pad[2] = {0, 0}; size_t leadz = 0; if (ctx == NULL) return 0; EVP_EncodeInit(ctx); evp_encode_ctx_set_flags(ctx, EVP_ENCODE_CTX_NO_NEWLINES | EVP_ENCODE_CTX_USE_SRP_ALPHABET); /* * We pad at the front with zero bytes until the length is a multiple of 3 * so that EVP_EncodeUpdate/EVP_EncodeFinal does not add any of its own "=" * padding */ leadz = 3 - (size % 3); if (leadz != 3 && !EVP_EncodeUpdate(ctx, (unsigned char *)dst, &outl, pad, leadz)) { EVP_ENCODE_CTX_free(ctx); return 0; } if (!EVP_EncodeUpdate(ctx, (unsigned char *)dst + outl, &outl2, src, size)) { EVP_ENCODE_CTX_free(ctx); return 0; } outl += outl2; EVP_EncodeFinal(ctx, (unsigned char *)dst + outl, &outl2); outl += outl2; /* Strip the encoded padding at the front */ if (leadz != 3) { memmove(dst, dst + leadz, outl - leadz); dst[outl - leadz] = '\0'; } EVP_ENCODE_CTX_free(ctx); return 1; } void SRP_user_pwd_free(SRP_user_pwd *user_pwd) { if (user_pwd == NULL) return; BN_free(user_pwd->s); BN_clear_free(user_pwd->v); OPENSSL_free(user_pwd->id); OPENSSL_free(user_pwd->info); OPENSSL_free(user_pwd); } SRP_user_pwd *SRP_user_pwd_new(void) { SRP_user_pwd *ret; if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) return NULL; ret->N = NULL; ret->g = NULL; ret->s = NULL; ret->v = NULL; ret->id = NULL; ret->info = NULL; return ret; } void SRP_user_pwd_set_gN(SRP_user_pwd *vinfo, const BIGNUM *g, const BIGNUM *N) { vinfo->N = N; vinfo->g = g; } int SRP_user_pwd_set1_ids(SRP_user_pwd *vinfo, const char *id, const char *info) { OPENSSL_free(vinfo->id); OPENSSL_free(vinfo->info); if (id != NULL && NULL == (vinfo->id = OPENSSL_strdup(id))) return 0; return (info == NULL || NULL != (vinfo->info = OPENSSL_strdup(info))); } static int SRP_user_pwd_set_sv(SRP_user_pwd *vinfo, const char *s, const char *v) { unsigned char tmp[MAX_LEN]; int len; vinfo->v = NULL; vinfo->s = NULL; len = t_fromb64(tmp, sizeof(tmp), v); if (len < 0) return 0; if (NULL == (vinfo->v = BN_bin2bn(tmp, len, NULL))) return 0; len = t_fromb64(tmp, sizeof(tmp), s); if (len < 0) goto err; vinfo->s = BN_bin2bn(tmp, len, NULL); if (vinfo->s == NULL) goto err; return 1; err: BN_free(vinfo->v); vinfo->v = NULL; return 0; } int SRP_user_pwd_set0_sv(SRP_user_pwd *vinfo, BIGNUM *s, BIGNUM *v) { BN_free(vinfo->s); BN_clear_free(vinfo->v); vinfo->v = v; vinfo->s = s; return (vinfo->s != NULL && vinfo->v != NULL); } static SRP_user_pwd *srp_user_pwd_dup(SRP_user_pwd *src) { SRP_user_pwd *ret; if (src == NULL) return NULL; if ((ret = SRP_user_pwd_new()) == NULL) return NULL; SRP_user_pwd_set_gN(ret, src->g, src->N); if (!SRP_user_pwd_set1_ids(ret, src->id, src->info) || !SRP_user_pwd_set0_sv(ret, BN_dup(src->s), BN_dup(src->v))) { SRP_user_pwd_free(ret); return NULL; } return ret; } SRP_VBASE *SRP_VBASE_new(char *seed_key) { SRP_VBASE *vb = OPENSSL_malloc(sizeof(*vb)); if (vb == NULL) return NULL; if ((vb->users_pwd = sk_SRP_user_pwd_new_null()) == NULL || (vb->gN_cache = sk_SRP_gN_cache_new_null()) == NULL) { sk_SRP_user_pwd_free(vb->users_pwd); OPENSSL_free(vb); return NULL; } vb->default_g = NULL; vb->default_N = NULL; vb->seed_key = NULL; if ((seed_key != NULL) && (vb->seed_key = OPENSSL_strdup(seed_key)) == NULL) { sk_SRP_user_pwd_free(vb->users_pwd); sk_SRP_gN_cache_free(vb->gN_cache); OPENSSL_free(vb); return NULL; } return vb; } void SRP_VBASE_free(SRP_VBASE *vb) { if (!vb) return; sk_SRP_user_pwd_pop_free(vb->users_pwd, SRP_user_pwd_free); sk_SRP_gN_cache_free(vb->gN_cache); OPENSSL_free(vb->seed_key); OPENSSL_free(vb); } static SRP_gN_cache *SRP_gN_new_init(const char *ch) { unsigned char tmp[MAX_LEN]; int len; SRP_gN_cache *newgN = OPENSSL_malloc(sizeof(*newgN)); if (newgN == NULL) return NULL; len = t_fromb64(tmp, sizeof(tmp), ch); if (len < 0) goto err; if ((newgN->b64_bn = OPENSSL_strdup(ch)) == NULL) goto err; if ((newgN->bn = BN_bin2bn(tmp, len, NULL))) return newgN; OPENSSL_free(newgN->b64_bn); err: OPENSSL_free(newgN); return NULL; } static void SRP_gN_free(SRP_gN_cache *gN_cache) { if (gN_cache == NULL) return; OPENSSL_free(gN_cache->b64_bn); BN_free(gN_cache->bn); OPENSSL_free(gN_cache); } static SRP_gN *SRP_get_gN_by_id(const char *id, STACK_OF(SRP_gN) *gN_tab) { int i; SRP_gN *gN; if (gN_tab != NULL) { for (i = 0; i < sk_SRP_gN_num(gN_tab); i++) { gN = sk_SRP_gN_value(gN_tab, i); if (gN && (id == NULL || strcmp(gN->id, id) == 0)) return gN; } } return SRP_get_default_gN(id); } static BIGNUM *SRP_gN_place_bn(STACK_OF(SRP_gN_cache) *gN_cache, char *ch) { int i; if (gN_cache == NULL) return NULL; /* search if we have already one... */ for (i = 0; i < sk_SRP_gN_cache_num(gN_cache); i++) { SRP_gN_cache *cache = sk_SRP_gN_cache_value(gN_cache, i); if (strcmp(cache->b64_bn, ch) == 0) return cache->bn; } { /* it is the first time that we find it */ SRP_gN_cache *newgN = SRP_gN_new_init(ch); if (newgN) { if (sk_SRP_gN_cache_insert(gN_cache, newgN, 0) > 0) return newgN->bn; SRP_gN_free(newgN); } } return NULL; } /* * This function parses the verifier file generated by the srp app. * The format for each entry is: * V base64(verifier) base64(salt) username gNid userinfo(optional) * or * I base64(N) base64(g) * Note that base64 is the SRP variant of base64 encoding described * in t_fromb64(). */ int SRP_VBASE_init(SRP_VBASE *vb, char *verifier_file) { int error_code = SRP_ERR_MEMORY; STACK_OF(SRP_gN) *SRP_gN_tab = sk_SRP_gN_new_null(); char *last_index = NULL; int i; char **pp; SRP_gN *gN = NULL; SRP_user_pwd *user_pwd = NULL; TXT_DB *tmpdb = NULL; BIO *in = BIO_new(BIO_s_file()); if (SRP_gN_tab == NULL) goto err; error_code = SRP_ERR_OPEN_FILE; if (in == NULL || BIO_read_filename(in, verifier_file) <= 0) goto err; error_code = SRP_ERR_VBASE_INCOMPLETE_FILE; if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL) goto err; error_code = SRP_ERR_MEMORY; if (vb->seed_key) { last_index = SRP_get_default_gN(NULL)->id; } for (i = 0; i < sk_OPENSSL_PSTRING_num(tmpdb->data); i++) { pp = sk_OPENSSL_PSTRING_value(tmpdb->data, i); if (pp[DB_srptype][0] == DB_SRP_INDEX) { /* * we add this couple in the internal Stack */ if ((gN = OPENSSL_malloc(sizeof(*gN))) == NULL) goto err; if ((gN->id = OPENSSL_strdup(pp[DB_srpid])) == NULL || (gN->N = SRP_gN_place_bn(vb->gN_cache, pp[DB_srpverifier])) == NULL || (gN->g = SRP_gN_place_bn(vb->gN_cache, pp[DB_srpsalt])) == NULL || sk_SRP_gN_insert(SRP_gN_tab, gN, 0) == 0) goto err; gN = NULL; if (vb->seed_key != NULL) { last_index = pp[DB_srpid]; } } else if (pp[DB_srptype][0] == DB_SRP_VALID) { /* it is a user .... */ const SRP_gN *lgN; if ((lgN = SRP_get_gN_by_id(pp[DB_srpgN], SRP_gN_tab)) != NULL) { error_code = SRP_ERR_MEMORY; if ((user_pwd = SRP_user_pwd_new()) == NULL) goto err; SRP_user_pwd_set_gN(user_pwd, lgN->g, lgN->N); if (!SRP_user_pwd_set1_ids (user_pwd, pp[DB_srpid], pp[DB_srpinfo])) goto err; error_code = SRP_ERR_VBASE_BN_LIB; if (!SRP_user_pwd_set_sv (user_pwd, pp[DB_srpsalt], pp[DB_srpverifier])) goto err; if (sk_SRP_user_pwd_insert(vb->users_pwd, user_pwd, 0) == 0) goto err; user_pwd = NULL; /* abandon responsibility */ } } } if (last_index != NULL) { /* this means that we want to simulate a default user */ if (((gN = SRP_get_gN_by_id(last_index, SRP_gN_tab)) == NULL)) { error_code = SRP_ERR_VBASE_BN_LIB; goto err; } vb->default_g = gN->g; vb->default_N = gN->N; gN = NULL; } error_code = SRP_NO_ERROR; err: /* * there may be still some leaks to fix, if this fails, the application * terminates most likely */ if (gN != NULL) { OPENSSL_free(gN->id); OPENSSL_free(gN); } SRP_user_pwd_free(user_pwd); TXT_DB_free(tmpdb); BIO_free_all(in); sk_SRP_gN_free(SRP_gN_tab); return error_code; } static SRP_user_pwd *find_user(SRP_VBASE *vb, char *username) { int i; SRP_user_pwd *user; if (vb == NULL) return NULL; for (i = 0; i < sk_SRP_user_pwd_num(vb->users_pwd); i++) { user = sk_SRP_user_pwd_value(vb->users_pwd, i); if (strcmp(user->id, username) == 0) return user; } return NULL; } int SRP_VBASE_add0_user(SRP_VBASE *vb, SRP_user_pwd *user_pwd) { if (sk_SRP_user_pwd_push(vb->users_pwd, user_pwd) <= 0) return 0; return 1; } # ifndef OPENSSL_NO_DEPRECATED_1_1_0 /* * DEPRECATED: use SRP_VBASE_get1_by_user instead. * This method ignores the configured seed and fails for an unknown user. * Ownership of the returned pointer is not released to the caller. * In other words, caller must not free the result. */ SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username) { return find_user(vb, username); } # endif /* * Ownership of the returned pointer is released to the caller. * In other words, caller must free the result once done. */ SRP_user_pwd *SRP_VBASE_get1_by_user(SRP_VBASE *vb, char *username) { SRP_user_pwd *user; unsigned char digv[SHA_DIGEST_LENGTH]; unsigned char digs[SHA_DIGEST_LENGTH]; EVP_MD_CTX *ctxt = NULL; EVP_MD *md = NULL; if (vb == NULL) return NULL; if ((user = find_user(vb, username)) != NULL) return srp_user_pwd_dup(user); if ((vb->seed_key == NULL) || (vb->default_g == NULL) || (vb->default_N == NULL)) return NULL; /* if the user is unknown we set parameters as well if we have a seed_key */ if ((user = SRP_user_pwd_new()) == NULL) return NULL; SRP_user_pwd_set_gN(user, vb->default_g, vb->default_N); if (!SRP_user_pwd_set1_ids(user, username, NULL)) goto err; if (RAND_priv_bytes(digv, SHA_DIGEST_LENGTH) <= 0) goto err; md = EVP_MD_fetch(NULL, SN_sha1, NULL); if (md == NULL) goto err; ctxt = EVP_MD_CTX_new(); if (ctxt == NULL || !EVP_DigestInit_ex(ctxt, md, NULL) || !EVP_DigestUpdate(ctxt, vb->seed_key, strlen(vb->seed_key)) || !EVP_DigestUpdate(ctxt, username, strlen(username)) || !EVP_DigestFinal_ex(ctxt, digs, NULL)) goto err; EVP_MD_CTX_free(ctxt); ctxt = NULL; EVP_MD_free(md); md = NULL; if (SRP_user_pwd_set0_sv(user, BN_bin2bn(digs, SHA_DIGEST_LENGTH, NULL), BN_bin2bn(digv, SHA_DIGEST_LENGTH, NULL))) return user; err: EVP_MD_free(md); EVP_MD_CTX_free(ctxt); SRP_user_pwd_free(user); return NULL; } /* * create a verifier (*salt,*verifier,g and N are in base64) */ char *SRP_create_verifier_ex(const char *user, const char *pass, char **salt, char **verifier, const char *N, const char *g, OSSL_LIB_CTX *libctx, const char *propq) { int len; char *result = NULL, *vf = NULL; const BIGNUM *N_bn = NULL, *g_bn = NULL; BIGNUM *N_bn_alloc = NULL, *g_bn_alloc = NULL, *s = NULL, *v = NULL; unsigned char tmp[MAX_LEN]; unsigned char tmp2[MAX_LEN]; char *defgNid = NULL; int vfsize = 0; if ((user == NULL) || (pass == NULL) || (salt == NULL) || (verifier == NULL)) goto err; if (N) { if ((len = t_fromb64(tmp, sizeof(tmp), N)) <= 0) goto err; N_bn_alloc = BN_bin2bn(tmp, len, NULL); if (N_bn_alloc == NULL) goto err; N_bn = N_bn_alloc; if ((len = t_fromb64(tmp, sizeof(tmp), g)) <= 0) goto err; g_bn_alloc = BN_bin2bn(tmp, len, NULL); if (g_bn_alloc == NULL) goto err; g_bn = g_bn_alloc; defgNid = "*"; } else { SRP_gN *gN = SRP_get_default_gN(g); if (gN == NULL) goto err; N_bn = gN->N; g_bn = gN->g; defgNid = gN->id; } if (*salt == NULL) { if (RAND_bytes_ex(libctx, tmp2, SRP_RANDOM_SALT_LEN, 0) <= 0) goto err; s = BN_bin2bn(tmp2, SRP_RANDOM_SALT_LEN, NULL); } else { if ((len = t_fromb64(tmp2, sizeof(tmp2), *salt)) <= 0) goto err; s = BN_bin2bn(tmp2, len, NULL); } if (s == NULL) goto err; if (!SRP_create_verifier_BN_ex(user, pass, &s, &v, N_bn, g_bn, libctx, propq)) goto err; if (BN_bn2bin(v, tmp) < 0) goto err; vfsize = BN_num_bytes(v) * 2; if (((vf = OPENSSL_malloc(vfsize)) == NULL)) goto err; if (!t_tob64(vf, tmp, BN_num_bytes(v))) goto err; if (*salt == NULL) { char *tmp_salt; if ((tmp_salt = OPENSSL_malloc(SRP_RANDOM_SALT_LEN * 2)) == NULL) { goto err; } if (!t_tob64(tmp_salt, tmp2, SRP_RANDOM_SALT_LEN)) { OPENSSL_free(tmp_salt); goto err; } *salt = tmp_salt; } *verifier = vf; vf = NULL; result = defgNid; err: BN_free(N_bn_alloc); BN_free(g_bn_alloc); OPENSSL_clear_free(vf, vfsize); BN_clear_free(s); BN_clear_free(v); return result; } char *SRP_create_verifier(const char *user, const char *pass, char **salt, char **verifier, const char *N, const char *g) { return SRP_create_verifier_ex(user, pass, salt, verifier, N, g, NULL, NULL); } /* * create a verifier (*salt,*verifier,g and N are BIGNUMs). If *salt != NULL * then the provided salt will be used. On successful exit *verifier will point * to a newly allocated BIGNUM containing the verifier and (if a salt was not * provided) *salt will be populated with a newly allocated BIGNUM containing a * random salt. * The caller is responsible for freeing the allocated *salt and *verifier * BIGNUMS. */ int SRP_create_verifier_BN_ex(const char *user, const char *pass, BIGNUM **salt, BIGNUM **verifier, const BIGNUM *N, const BIGNUM *g, OSSL_LIB_CTX *libctx, const char *propq) { int result = 0; BIGNUM *x = NULL; BN_CTX *bn_ctx = BN_CTX_new_ex(libctx); unsigned char tmp2[MAX_LEN]; BIGNUM *salttmp = NULL, *verif; if ((user == NULL) || (pass == NULL) || (salt == NULL) || (verifier == NULL) || (N == NULL) || (g == NULL) || (bn_ctx == NULL)) goto err; if (*salt == NULL) { if (RAND_bytes_ex(libctx, tmp2, SRP_RANDOM_SALT_LEN, 0) <= 0) goto err; salttmp = BN_bin2bn(tmp2, SRP_RANDOM_SALT_LEN, NULL); if (salttmp == NULL) goto err; } else { salttmp = *salt; } x = SRP_Calc_x_ex(salttmp, user, pass, libctx, propq); if (x == NULL) goto err; verif = BN_new(); if (verif == NULL) goto err; if (!BN_mod_exp(verif, g, x, N, bn_ctx)) { BN_clear_free(verif); goto err; } result = 1; *salt = salttmp; *verifier = verif; err: if (salt != NULL && *salt != salttmp) BN_clear_free(salttmp); BN_clear_free(x); BN_CTX_free(bn_ctx); return result; } int SRP_create_verifier_BN(const char *user, const char *pass, BIGNUM **salt, BIGNUM **verifier, const BIGNUM *N, const BIGNUM *g) { return SRP_create_verifier_BN_ex(user, pass, salt, verifier, N, g, NULL, NULL); } #endif
./openssl/crypto/srp/srp_lib.c
/* * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2004, EdelKey Project. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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 Christophe Renou and Peter Sylvester, * for the EdelKey project. */ /* All the SRP APIs in this file are deprecated */ #define OPENSSL_SUPPRESS_DEPRECATED #ifndef OPENSSL_NO_SRP # include "internal/cryptlib.h" # include <openssl/sha.h> # include <openssl/srp.h> # include <openssl/evp.h> # include "crypto/bn_srp.h" /* calculate = SHA1(PAD(x) || PAD(y)) */ static BIGNUM *srp_Calc_xy(const BIGNUM *x, const BIGNUM *y, const BIGNUM *N, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char digest[SHA_DIGEST_LENGTH]; unsigned char *tmp = NULL; int numN = BN_num_bytes(N); BIGNUM *res = NULL; EVP_MD *sha1 = EVP_MD_fetch(libctx, "SHA1", propq); if (sha1 == NULL) return NULL; if (x != N && BN_ucmp(x, N) >= 0) goto err; if (y != N && BN_ucmp(y, N) >= 0) goto err; if ((tmp = OPENSSL_malloc(numN * 2)) == NULL) goto err; if (BN_bn2binpad(x, tmp, numN) < 0 || BN_bn2binpad(y, tmp + numN, numN) < 0 || !EVP_Digest(tmp, numN * 2, digest, NULL, sha1, NULL)) goto err; res = BN_bin2bn(digest, sizeof(digest), NULL); err: EVP_MD_free(sha1); OPENSSL_free(tmp); return res; } static BIGNUM *srp_Calc_k(const BIGNUM *N, const BIGNUM *g, OSSL_LIB_CTX *libctx, const char *propq) { /* k = SHA1(N | PAD(g)) -- tls-srp RFC 5054 */ return srp_Calc_xy(N, g, N, libctx, propq); } BIGNUM *SRP_Calc_u_ex(const BIGNUM *A, const BIGNUM *B, const BIGNUM *N, OSSL_LIB_CTX *libctx, const char *propq) { /* u = SHA1(PAD(A) || PAD(B) ) -- tls-srp RFC 5054 */ return srp_Calc_xy(A, B, N, libctx, propq); } BIGNUM *SRP_Calc_u(const BIGNUM *A, const BIGNUM *B, const BIGNUM *N) { /* u = SHA1(PAD(A) || PAD(B) ) -- tls-srp RFC 5054 */ return srp_Calc_xy(A, B, N, NULL, NULL); } BIGNUM *SRP_Calc_server_key(const BIGNUM *A, const BIGNUM *v, const BIGNUM *u, const BIGNUM *b, const BIGNUM *N) { BIGNUM *tmp = NULL, *S = NULL; BN_CTX *bn_ctx; if (u == NULL || A == NULL || v == NULL || b == NULL || N == NULL) return NULL; if ((bn_ctx = BN_CTX_new()) == NULL || (tmp = BN_new()) == NULL) goto err; /* S = (A*v**u) ** b */ if (!BN_mod_exp(tmp, v, u, N, bn_ctx)) goto err; if (!BN_mod_mul(tmp, A, tmp, N, bn_ctx)) goto err; S = BN_new(); if (S != NULL && !BN_mod_exp(S, tmp, b, N, bn_ctx)) { BN_free(S); S = NULL; } err: BN_CTX_free(bn_ctx); BN_clear_free(tmp); return S; } BIGNUM *SRP_Calc_B_ex(const BIGNUM *b, const BIGNUM *N, const BIGNUM *g, const BIGNUM *v, OSSL_LIB_CTX *libctx, const char *propq) { BIGNUM *kv = NULL, *gb = NULL; BIGNUM *B = NULL, *k = NULL; BN_CTX *bn_ctx; if (b == NULL || N == NULL || g == NULL || v == NULL || (bn_ctx = BN_CTX_new_ex(libctx)) == NULL) return NULL; if ((kv = BN_new()) == NULL || (gb = BN_new()) == NULL || (B = BN_new()) == NULL) goto err; /* B = g**b + k*v */ if (!BN_mod_exp(gb, g, b, N, bn_ctx) || (k = srp_Calc_k(N, g, libctx, propq)) == NULL || !BN_mod_mul(kv, v, k, N, bn_ctx) || !BN_mod_add(B, gb, kv, N, bn_ctx)) { BN_free(B); B = NULL; } err: BN_CTX_free(bn_ctx); BN_clear_free(kv); BN_clear_free(gb); BN_free(k); return B; } BIGNUM *SRP_Calc_B(const BIGNUM *b, const BIGNUM *N, const BIGNUM *g, const BIGNUM *v) { return SRP_Calc_B_ex(b, N, g, v, NULL, NULL); } BIGNUM *SRP_Calc_x_ex(const BIGNUM *s, const char *user, const char *pass, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char dig[SHA_DIGEST_LENGTH]; EVP_MD_CTX *ctxt; unsigned char *cs = NULL; BIGNUM *res = NULL; EVP_MD *sha1 = NULL; if ((s == NULL) || (user == NULL) || (pass == NULL)) return NULL; ctxt = EVP_MD_CTX_new(); if (ctxt == NULL) return NULL; if ((cs = OPENSSL_malloc(BN_num_bytes(s))) == NULL) goto err; sha1 = EVP_MD_fetch(libctx, "SHA1", propq); if (sha1 == NULL) goto err; if (!EVP_DigestInit_ex(ctxt, sha1, NULL) || !EVP_DigestUpdate(ctxt, user, strlen(user)) || !EVP_DigestUpdate(ctxt, ":", 1) || !EVP_DigestUpdate(ctxt, pass, strlen(pass)) || !EVP_DigestFinal_ex(ctxt, dig, NULL) || !EVP_DigestInit_ex(ctxt, sha1, NULL)) goto err; if (BN_bn2bin(s, cs) < 0) goto err; if (!EVP_DigestUpdate(ctxt, cs, BN_num_bytes(s))) goto err; if (!EVP_DigestUpdate(ctxt, dig, sizeof(dig)) || !EVP_DigestFinal_ex(ctxt, dig, NULL)) goto err; res = BN_bin2bn(dig, sizeof(dig), NULL); err: EVP_MD_free(sha1); OPENSSL_free(cs); EVP_MD_CTX_free(ctxt); return res; } BIGNUM *SRP_Calc_x(const BIGNUM *s, const char *user, const char *pass) { return SRP_Calc_x_ex(s, user, pass, NULL, NULL); } BIGNUM *SRP_Calc_A(const BIGNUM *a, const BIGNUM *N, const BIGNUM *g) { BN_CTX *bn_ctx; BIGNUM *A = NULL; if (a == NULL || N == NULL || g == NULL || (bn_ctx = BN_CTX_new()) == NULL) return NULL; if ((A = BN_new()) != NULL && !BN_mod_exp(A, g, a, N, bn_ctx)) { BN_free(A); A = NULL; } BN_CTX_free(bn_ctx); return A; } BIGNUM *SRP_Calc_client_key_ex(const BIGNUM *N, const BIGNUM *B, const BIGNUM *g, const BIGNUM *x, const BIGNUM *a, const BIGNUM *u, OSSL_LIB_CTX *libctx, const char *propq) { BIGNUM *tmp = NULL, *tmp2 = NULL, *tmp3 = NULL, *k = NULL, *K = NULL; BIGNUM *xtmp = NULL; BN_CTX *bn_ctx; if (u == NULL || B == NULL || N == NULL || g == NULL || x == NULL || a == NULL || (bn_ctx = BN_CTX_new_ex(libctx)) == NULL) return NULL; if ((tmp = BN_new()) == NULL || (tmp2 = BN_new()) == NULL || (tmp3 = BN_new()) == NULL || (xtmp = BN_new()) == NULL) goto err; BN_with_flags(xtmp, x, BN_FLG_CONSTTIME); BN_set_flags(tmp, BN_FLG_CONSTTIME); if (!BN_mod_exp(tmp, g, xtmp, N, bn_ctx)) goto err; if ((k = srp_Calc_k(N, g, libctx, propq)) == NULL) goto err; if (!BN_mod_mul(tmp2, tmp, k, N, bn_ctx)) goto err; if (!BN_mod_sub(tmp, B, tmp2, N, bn_ctx)) goto err; if (!BN_mul(tmp3, u, xtmp, bn_ctx)) goto err; if (!BN_add(tmp2, a, tmp3)) goto err; K = BN_new(); if (K != NULL && !BN_mod_exp(K, tmp, tmp2, N, bn_ctx)) { BN_free(K); K = NULL; } err: BN_CTX_free(bn_ctx); BN_free(xtmp); BN_clear_free(tmp); BN_clear_free(tmp2); BN_clear_free(tmp3); BN_free(k); return K; } BIGNUM *SRP_Calc_client_key(const BIGNUM *N, const BIGNUM *B, const BIGNUM *g, const BIGNUM *x, const BIGNUM *a, const BIGNUM *u) { return SRP_Calc_client_key_ex(N, B, g, x, a, u, NULL, NULL); } int SRP_Verify_B_mod_N(const BIGNUM *B, const BIGNUM *N) { BIGNUM *r; BN_CTX *bn_ctx; int ret = 0; if (B == NULL || N == NULL || (bn_ctx = BN_CTX_new()) == NULL) return 0; if ((r = BN_new()) == NULL) goto err; /* Checks if B % N == 0 */ if (!BN_nnmod(r, B, N, bn_ctx)) goto err; ret = !BN_is_zero(r); err: BN_CTX_free(bn_ctx); BN_free(r); return ret; } int SRP_Verify_A_mod_N(const BIGNUM *A, const BIGNUM *N) { /* Checks if A % N == 0 */ return SRP_Verify_B_mod_N(A, N); } static SRP_gN knowngN[] = { {"8192", &ossl_bn_generator_19, &ossl_bn_group_8192}, {"6144", &ossl_bn_generator_5, &ossl_bn_group_6144}, {"4096", &ossl_bn_generator_5, &ossl_bn_group_4096}, {"3072", &ossl_bn_generator_5, &ossl_bn_group_3072}, {"2048", &ossl_bn_generator_2, &ossl_bn_group_2048}, {"1536", &ossl_bn_generator_2, &ossl_bn_group_1536}, {"1024", &ossl_bn_generator_2, &ossl_bn_group_1024}, }; # define KNOWN_GN_NUMBER sizeof(knowngN) / sizeof(SRP_gN) /* * Check if G and N are known parameters. The values have been generated * from the IETF RFC 5054 */ char *SRP_check_known_gN_param(const BIGNUM *g, const BIGNUM *N) { size_t i; if ((g == NULL) || (N == NULL)) return NULL; for (i = 0; i < KNOWN_GN_NUMBER; i++) { if (BN_cmp(knowngN[i].g, g) == 0 && BN_cmp(knowngN[i].N, N) == 0) return knowngN[i].id; } return NULL; } SRP_gN *SRP_get_default_gN(const char *id) { size_t i; if (id == NULL) return knowngN; for (i = 0; i < KNOWN_GN_NUMBER; i++) { if (strcmp(knowngN[i].id, id) == 0) return knowngN + i; } return NULL; } #endif
./openssl/crypto/encode_decode/encoder_local.h
/* * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core_dispatch.h> #include <openssl/types.h> #include <openssl/safestack.h> #include <openssl/encoder.h> #include <openssl/decoder.h> #include "internal/cryptlib.h" #include "internal/passphrase.h" #include "internal/property.h" #include "internal/refcount.h" struct ossl_endecode_base_st { OSSL_PROVIDER *prov; int id; char *name; const OSSL_ALGORITHM *algodef; OSSL_PROPERTY_LIST *parsed_propdef; CRYPTO_REF_COUNT refcnt; }; struct ossl_encoder_st { struct ossl_endecode_base_st base; OSSL_FUNC_encoder_newctx_fn *newctx; OSSL_FUNC_encoder_freectx_fn *freectx; OSSL_FUNC_encoder_get_params_fn *get_params; OSSL_FUNC_encoder_gettable_params_fn *gettable_params; OSSL_FUNC_encoder_set_ctx_params_fn *set_ctx_params; OSSL_FUNC_encoder_settable_ctx_params_fn *settable_ctx_params; OSSL_FUNC_encoder_does_selection_fn *does_selection; OSSL_FUNC_encoder_encode_fn *encode; OSSL_FUNC_encoder_import_object_fn *import_object; OSSL_FUNC_encoder_free_object_fn *free_object; }; struct ossl_decoder_st { struct ossl_endecode_base_st base; OSSL_FUNC_decoder_newctx_fn *newctx; OSSL_FUNC_decoder_freectx_fn *freectx; OSSL_FUNC_decoder_get_params_fn *get_params; OSSL_FUNC_decoder_gettable_params_fn *gettable_params; OSSL_FUNC_decoder_set_ctx_params_fn *set_ctx_params; OSSL_FUNC_decoder_settable_ctx_params_fn *settable_ctx_params; OSSL_FUNC_decoder_does_selection_fn *does_selection; OSSL_FUNC_decoder_decode_fn *decode; OSSL_FUNC_decoder_export_object_fn *export_object; }; struct ossl_encoder_instance_st { OSSL_ENCODER *encoder; /* Never NULL */ void *encoderctx; /* Never NULL */ const char *output_type; /* Never NULL */ const char *output_structure; /* May be NULL */ }; DEFINE_STACK_OF(OSSL_ENCODER_INSTANCE) void ossl_encoder_instance_free(OSSL_ENCODER_INSTANCE *encoder_inst); struct ossl_encoder_ctx_st { /* * Select what parts of an object will be encoded. This selection is * bit encoded, and the bits correspond to selection bits available with * the provider side operation. For example, when encoding an EVP_PKEY, * the OSSL_KEYMGMT_SELECT_ macros are used for this. */ int selection; /* * The desired output type. The encoder implementation must have a * gettable "output-type" parameter that this will match against. */ const char *output_type; /* * The desired output structure, if that's relevant for the type of * object being encoded. It may be used for selection of the starting * encoder implementations in a chain. */ const char *output_structure; /* * Decoders that are components of any current decoding path. */ STACK_OF(OSSL_ENCODER_INSTANCE) *encoder_insts; /* * The constructor and destructor of an object to pass to the first * encoder in a chain. */ OSSL_ENCODER_CONSTRUCT *construct; OSSL_ENCODER_CLEANUP *cleanup; void *construct_data; /* For any function that needs a passphrase reader */ struct ossl_passphrase_data_st pwdata; }; struct ossl_decoder_instance_st { OSSL_DECODER *decoder; /* Never NULL */ void *decoderctx; /* Never NULL */ const char *input_type; /* Never NULL */ const char *input_structure; /* May be NULL */ int input_type_id; unsigned int flag_input_structure_was_set : 1; }; DEFINE_STACK_OF(OSSL_DECODER_INSTANCE) struct ossl_decoder_ctx_st { /* * The caller may know the input type of the data they pass. If not, * this will remain NULL and the decoding functionality will start * with trying to decode with any desencoder in |decoder_insts|, * regardless of their respective input type. */ const char *start_input_type; /* * The desired input structure, if that's relevant for the type of * object being encoded. It may be used for selection of the ending * decoder implementations in a chain, i.e. those chosen using the * expected output data type. */ const char *input_structure; /* * Select what parts of an object are expected. This may affect what * decoder implementations are selected, because there are structures * that look different depending on this selection; for example, EVP_PKEY * objects often have different encoding structures for private keys, * public keys and key parameters. * This selection is bit encoded, and the bits correspond to selection * bits available with the provider side operation. For example, when * encoding an EVP_PKEY, the OSSL_KEYMGMT_SELECT_ macros are used for * this. */ int selection; /* * Decoders that are components of any current decoding path. */ STACK_OF(OSSL_DECODER_INSTANCE) *decoder_insts; /* * The constructors of a decoding, and its caller argument. */ OSSL_DECODER_CONSTRUCT *construct; OSSL_DECODER_CLEANUP *cleanup; void *construct_data; /* For any function that needs a passphrase reader */ struct ossl_passphrase_data_st pwdata; }; const OSSL_PROPERTY_LIST * ossl_decoder_parsed_properties(const OSSL_DECODER *decoder); const OSSL_PROPERTY_LIST * ossl_encoder_parsed_properties(const OSSL_ENCODER *encoder); int ossl_decoder_fast_is_a(OSSL_DECODER *decoder, const char *name, int *id_cache);
./openssl/crypto/encode_decode/encoder_meth.c
/* * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core.h> #include <openssl/core_dispatch.h> #include <openssl/encoder.h> #include <openssl/ui.h> #include "internal/core.h" #include "internal/namemap.h" #include "internal/property.h" #include "internal/provider.h" #include "crypto/encoder.h" #include "encoder_local.h" #include "crypto/context.h" /* * Encoder can have multiple names, separated with colons in a name string */ #define NAME_SEPARATOR ':' /* Simple method structure constructor and destructor */ static OSSL_ENCODER *ossl_encoder_new(void) { OSSL_ENCODER *encoder = NULL; if ((encoder = OPENSSL_zalloc(sizeof(*encoder))) == NULL) return NULL; if (!CRYPTO_NEW_REF(&encoder->base.refcnt, 1)) { OSSL_ENCODER_free(encoder); return NULL; } return encoder; } int OSSL_ENCODER_up_ref(OSSL_ENCODER *encoder) { int ref = 0; CRYPTO_UP_REF(&encoder->base.refcnt, &ref); return 1; } void OSSL_ENCODER_free(OSSL_ENCODER *encoder) { int ref = 0; if (encoder == NULL) return; CRYPTO_DOWN_REF(&encoder->base.refcnt, &ref); if (ref > 0) return; OPENSSL_free(encoder->base.name); ossl_property_free(encoder->base.parsed_propdef); ossl_provider_free(encoder->base.prov); CRYPTO_FREE_REF(&encoder->base.refcnt); OPENSSL_free(encoder); } /* Data to be passed through ossl_method_construct() */ struct encoder_data_st { OSSL_LIB_CTX *libctx; int id; /* For get_encoder_from_store() */ const char *names; /* For get_encoder_from_store() */ const char *propquery; /* For get_encoder_from_store() */ OSSL_METHOD_STORE *tmp_store; /* For get_tmp_encoder_store() */ unsigned int flag_construct_error_occurred : 1; }; /* * Generic routines to fetch / create ENCODER methods with * ossl_method_construct() */ /* Temporary encoder method store, constructor and destructor */ static void *get_tmp_encoder_store(void *data) { struct encoder_data_st *methdata = data; if (methdata->tmp_store == NULL) methdata->tmp_store = ossl_method_store_new(methdata->libctx); return methdata->tmp_store; } static void dealloc_tmp_encoder_store(void *store) { if (store != NULL) ossl_method_store_free(store); } /* Get the permanent encoder store */ static OSSL_METHOD_STORE *get_encoder_store(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_ENCODER_STORE_INDEX); } static int reserve_encoder_store(void *store, void *data) { struct encoder_data_st *methdata = data; if (store == NULL && (store = get_encoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_lock_store(store); } static int unreserve_encoder_store(void *store, void *data) { struct encoder_data_st *methdata = data; if (store == NULL && (store = get_encoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_unlock_store(store); } /* Get encoder methods from a store, or put one in */ static void *get_encoder_from_store(void *store, const OSSL_PROVIDER **prov, void *data) { struct encoder_data_st *methdata = data; void *method = NULL; int id; /* * get_encoder_from_store() is only called to try and get the method * that OSSL_ENCODER_fetch() is asking for, and the name or name id are * passed via methdata. */ if ((id = methdata->id) == 0 && methdata->names != NULL) { OSSL_NAMEMAP *namemap = ossl_namemap_stored(methdata->libctx); const char *names = methdata->names; const char *q = strchr(names, NAME_SEPARATOR); size_t l = (q == NULL ? strlen(names) : (size_t)(q - names)); if (namemap == 0) return NULL; id = ossl_namemap_name2num_n(namemap, methdata->names, l); } if (id == 0) return NULL; if (store == NULL && (store = get_encoder_store(methdata->libctx)) == NULL) return NULL; if (!ossl_method_store_fetch(store, id, methdata->propquery, prov, &method)) return NULL; return method; } static int put_encoder_in_store(void *store, void *method, const OSSL_PROVIDER *prov, const char *names, const char *propdef, void *data) { struct encoder_data_st *methdata = data; OSSL_NAMEMAP *namemap; int id; size_t l = 0; /* * put_encoder_in_store() is only called with an OSSL_ENCODER method that * was successfully created by construct_encoder() below, which means that * all the names should already be stored in the namemap with the same * numeric identity, so just use the first to get that identity. */ if (names != NULL) { const char *q = strchr(names, NAME_SEPARATOR); l = (q == NULL ? strlen(names) : (size_t)(q - names)); } if ((namemap = ossl_namemap_stored(methdata->libctx)) == NULL || (id = ossl_namemap_name2num_n(namemap, names, l)) == 0) return 0; if (store == NULL && (store = get_encoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_store_add(store, prov, id, propdef, method, (int (*)(void *))OSSL_ENCODER_up_ref, (void (*)(void *))OSSL_ENCODER_free); } /* Create and populate a encoder method */ static void *encoder_from_algorithm(int id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { OSSL_ENCODER *encoder = NULL; const OSSL_DISPATCH *fns = algodef->implementation; OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); if ((encoder = ossl_encoder_new()) == NULL) return NULL; encoder->base.id = id; if ((encoder->base.name = ossl_algorithm_get1_first_name(algodef)) == NULL) { OSSL_ENCODER_free(encoder); return NULL; } encoder->base.algodef = algodef; if ((encoder->base.parsed_propdef = ossl_parse_property(libctx, algodef->property_definition)) == NULL) { OSSL_ENCODER_free(encoder); return NULL; } for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_ENCODER_NEWCTX: if (encoder->newctx == NULL) encoder->newctx = OSSL_FUNC_encoder_newctx(fns); break; case OSSL_FUNC_ENCODER_FREECTX: if (encoder->freectx == NULL) encoder->freectx = OSSL_FUNC_encoder_freectx(fns); break; case OSSL_FUNC_ENCODER_GET_PARAMS: if (encoder->get_params == NULL) encoder->get_params = OSSL_FUNC_encoder_get_params(fns); break; case OSSL_FUNC_ENCODER_GETTABLE_PARAMS: if (encoder->gettable_params == NULL) encoder->gettable_params = OSSL_FUNC_encoder_gettable_params(fns); break; case OSSL_FUNC_ENCODER_SET_CTX_PARAMS: if (encoder->set_ctx_params == NULL) encoder->set_ctx_params = OSSL_FUNC_encoder_set_ctx_params(fns); break; case OSSL_FUNC_ENCODER_SETTABLE_CTX_PARAMS: if (encoder->settable_ctx_params == NULL) encoder->settable_ctx_params = OSSL_FUNC_encoder_settable_ctx_params(fns); break; case OSSL_FUNC_ENCODER_DOES_SELECTION: if (encoder->does_selection == NULL) encoder->does_selection = OSSL_FUNC_encoder_does_selection(fns); break; case OSSL_FUNC_ENCODER_ENCODE: if (encoder->encode == NULL) encoder->encode = OSSL_FUNC_encoder_encode(fns); break; case OSSL_FUNC_ENCODER_IMPORT_OBJECT: if (encoder->import_object == NULL) encoder->import_object = OSSL_FUNC_encoder_import_object(fns); break; case OSSL_FUNC_ENCODER_FREE_OBJECT: if (encoder->free_object == NULL) encoder->free_object = OSSL_FUNC_encoder_free_object(fns); break; } } /* * Try to check that the method is sensible. * If you have a constructor, you must have a destructor and vice versa. * You must have the encoding driver functions. */ if (!((encoder->newctx == NULL && encoder->freectx == NULL) || (encoder->newctx != NULL && encoder->freectx != NULL) || (encoder->import_object != NULL && encoder->free_object != NULL) || (encoder->import_object == NULL && encoder->free_object == NULL)) || encoder->encode == NULL) { OSSL_ENCODER_free(encoder); ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_INVALID_PROVIDER_FUNCTIONS); return NULL; } if (prov != NULL && !ossl_provider_up_ref(prov)) { OSSL_ENCODER_free(encoder); return NULL; } encoder->base.prov = prov; return encoder; } /* * The core fetching functionality passes the names of the implementation. * This function is responsible to getting an identity number for them, * then call encoder_from_algorithm() with that identity number. */ static void *construct_encoder(const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov, void *data) { /* * This function is only called if get_encoder_from_store() returned * NULL, so it's safe to say that of all the spots to create a new * namemap entry, this is it. Should the name already exist there, we * know that ossl_namemap_add() will return its corresponding number. */ struct encoder_data_st *methdata = data; OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); const char *names = algodef->algorithm_names; int id = ossl_namemap_add_names(namemap, 0, names, NAME_SEPARATOR); void *method = NULL; if (id != 0) method = encoder_from_algorithm(id, algodef, prov); /* * Flag to indicate that there was actual construction errors. This * helps inner_evp_generic_fetch() determine what error it should * record on inaccessible algorithms. */ if (method == NULL) methdata->flag_construct_error_occurred = 1; return method; } /* Intermediary function to avoid ugly casts, used below */ static void destruct_encoder(void *method, void *data) { OSSL_ENCODER_free(method); } static int up_ref_encoder(void *method) { return OSSL_ENCODER_up_ref(method); } static void free_encoder(void *method) { OSSL_ENCODER_free(method); } /* Fetching support. Can fetch by numeric identity or by name */ static OSSL_ENCODER * inner_ossl_encoder_fetch(struct encoder_data_st *methdata, const char *name, const char *properties) { OSSL_METHOD_STORE *store = get_encoder_store(methdata->libctx); OSSL_NAMEMAP *namemap = ossl_namemap_stored(methdata->libctx); const char *const propq = properties != NULL ? properties : ""; void *method = NULL; int unsupported, id; if (store == NULL || namemap == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } id = name != NULL ? ossl_namemap_name2num(namemap, name) : 0; /* * If we haven't found the name yet, chances are that the algorithm to * be fetched is unsupported. */ unsupported = id == 0; if (id == 0 || !ossl_method_store_cache_get(store, NULL, id, propq, &method)) { OSSL_METHOD_CONSTRUCT_METHOD mcm = { get_tmp_encoder_store, reserve_encoder_store, unreserve_encoder_store, get_encoder_from_store, put_encoder_in_store, construct_encoder, destruct_encoder }; OSSL_PROVIDER *prov = NULL; methdata->id = id; methdata->names = name; methdata->propquery = propq; methdata->flag_construct_error_occurred = 0; if ((method = ossl_method_construct(methdata->libctx, OSSL_OP_ENCODER, &prov, 0 /* !force_cache */, &mcm, methdata)) != NULL) { /* * If construction did create a method for us, we know that * there is a correct name_id and meth_id, since those have * already been calculated in get_encoder_from_store() and * put_encoder_in_store() above. */ if (id == 0) id = ossl_namemap_name2num(namemap, name); ossl_method_store_cache_set(store, prov, id, propq, method, up_ref_encoder, free_encoder); } /* * If we never were in the constructor, the algorithm to be fetched * is unsupported. */ unsupported = !methdata->flag_construct_error_occurred; } if ((id != 0 || name != NULL) && method == NULL) { int code = unsupported ? ERR_R_UNSUPPORTED : ERR_R_FETCH_FAILED; if (name == NULL) name = ossl_namemap_num2name(namemap, id, 0); ERR_raise_data(ERR_LIB_OSSL_ENCODER, code, "%s, Name (%s : %d), Properties (%s)", ossl_lib_ctx_get_descriptor(methdata->libctx), name == NULL ? "<null>" : name, id, properties == NULL ? "<null>" : properties); } return method; } OSSL_ENCODER *OSSL_ENCODER_fetch(OSSL_LIB_CTX *libctx, const char *name, const char *properties) { struct encoder_data_st methdata; void *method; methdata.libctx = libctx; methdata.tmp_store = NULL; method = inner_ossl_encoder_fetch(&methdata, name, properties); dealloc_tmp_encoder_store(methdata.tmp_store); return method; } int ossl_encoder_store_cache_flush(OSSL_LIB_CTX *libctx) { OSSL_METHOD_STORE *store = get_encoder_store(libctx); if (store != NULL) return ossl_method_store_cache_flush_all(store); return 1; } int ossl_encoder_store_remove_all_provided(const OSSL_PROVIDER *prov) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_METHOD_STORE *store = get_encoder_store(libctx); if (store != NULL) return ossl_method_store_remove_all_provided(store, prov); return 1; } /* * Library of basic method functions */ const OSSL_PROVIDER *OSSL_ENCODER_get0_provider(const OSSL_ENCODER *encoder) { if (!ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return encoder->base.prov; } const char *OSSL_ENCODER_get0_properties(const OSSL_ENCODER *encoder) { if (!ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return encoder->base.algodef->property_definition; } const OSSL_PROPERTY_LIST * ossl_encoder_parsed_properties(const OSSL_ENCODER *encoder) { if (!ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return encoder->base.parsed_propdef; } int ossl_encoder_get_number(const OSSL_ENCODER *encoder) { if (!ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return encoder->base.id; } const char *OSSL_ENCODER_get0_name(const OSSL_ENCODER *encoder) { return encoder->base.name; } const char *OSSL_ENCODER_get0_description(const OSSL_ENCODER *encoder) { return encoder->base.algodef->algorithm_description; } int OSSL_ENCODER_is_a(const OSSL_ENCODER *encoder, const char *name) { if (encoder->base.prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(encoder->base.prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_name2num(namemap, name) == encoder->base.id; } return 0; } struct do_one_data_st { void (*user_fn)(OSSL_ENCODER *encoder, void *arg); void *user_arg; }; static void do_one(ossl_unused int id, void *method, void *arg) { struct do_one_data_st *data = arg; data->user_fn(method, data->user_arg); } void OSSL_ENCODER_do_all_provided(OSSL_LIB_CTX *libctx, void (*user_fn)(OSSL_ENCODER *encoder, void *arg), void *user_arg) { struct encoder_data_st methdata; struct do_one_data_st data; methdata.libctx = libctx; methdata.tmp_store = NULL; (void)inner_ossl_encoder_fetch(&methdata, NULL, NULL /* properties */); data.user_fn = user_fn; data.user_arg = user_arg; if (methdata.tmp_store != NULL) ossl_method_store_do_all(methdata.tmp_store, &do_one, &data); ossl_method_store_do_all(get_encoder_store(libctx), &do_one, &data); dealloc_tmp_encoder_store(methdata.tmp_store); } int OSSL_ENCODER_names_do_all(const OSSL_ENCODER *encoder, void (*fn)(const char *name, void *data), void *data) { if (encoder == NULL) return 0; if (encoder->base.prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(encoder->base.prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_doall_names(namemap, encoder->base.id, fn, data); } return 1; } const OSSL_PARAM * OSSL_ENCODER_gettable_params(OSSL_ENCODER *encoder) { if (encoder != NULL && encoder->gettable_params != NULL) { void *provctx = ossl_provider_ctx(OSSL_ENCODER_get0_provider(encoder)); return encoder->gettable_params(provctx); } return NULL; } int OSSL_ENCODER_get_params(OSSL_ENCODER *encoder, OSSL_PARAM params[]) { if (encoder != NULL && encoder->get_params != NULL) return encoder->get_params(params); return 0; } const OSSL_PARAM *OSSL_ENCODER_settable_ctx_params(OSSL_ENCODER *encoder) { if (encoder != NULL && encoder->settable_ctx_params != NULL) { void *provctx = ossl_provider_ctx(OSSL_ENCODER_get0_provider(encoder)); return encoder->settable_ctx_params(provctx); } return NULL; } /* * Encoder context support */ OSSL_ENCODER_CTX *OSSL_ENCODER_CTX_new(void) { OSSL_ENCODER_CTX *ctx; ctx = OPENSSL_zalloc(sizeof(*ctx)); return ctx; } int OSSL_ENCODER_CTX_set_params(OSSL_ENCODER_CTX *ctx, const OSSL_PARAM params[]) { int ok = 1; size_t i; size_t l; if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ctx->encoder_insts == NULL) return 1; l = OSSL_ENCODER_CTX_get_num_encoders(ctx); for (i = 0; i < l; i++) { OSSL_ENCODER_INSTANCE *encoder_inst = sk_OSSL_ENCODER_INSTANCE_value(ctx->encoder_insts, i); OSSL_ENCODER *encoder = OSSL_ENCODER_INSTANCE_get_encoder(encoder_inst); void *encoderctx = OSSL_ENCODER_INSTANCE_get_encoder_ctx(encoder_inst); if (encoderctx == NULL || encoder->set_ctx_params == NULL) continue; if (!encoder->set_ctx_params(encoderctx, params)) ok = 0; } return ok; } void OSSL_ENCODER_CTX_free(OSSL_ENCODER_CTX *ctx) { if (ctx != NULL) { sk_OSSL_ENCODER_INSTANCE_pop_free(ctx->encoder_insts, ossl_encoder_instance_free); OPENSSL_free(ctx->construct_data); ossl_pw_clear_passphrase_data(&ctx->pwdata); OPENSSL_free(ctx); } }
./openssl/crypto/encode_decode/decoder_meth.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 <openssl/core.h> #include <openssl/core_dispatch.h> #include <openssl/decoder.h> #include <openssl/ui.h> #include "internal/core.h" #include "internal/namemap.h" #include "internal/property.h" #include "internal/provider.h" #include "crypto/decoder.h" #include "encoder_local.h" #include "crypto/context.h" /* * Decoder can have multiple names, separated with colons in a name string */ #define NAME_SEPARATOR ':' /* Simple method structure constructor and destructor */ static OSSL_DECODER *ossl_decoder_new(void) { OSSL_DECODER *decoder = NULL; if ((decoder = OPENSSL_zalloc(sizeof(*decoder))) == NULL) return NULL; if (!CRYPTO_NEW_REF(&decoder->base.refcnt, 1)) { OSSL_DECODER_free(decoder); return NULL; } return decoder; } int OSSL_DECODER_up_ref(OSSL_DECODER *decoder) { int ref = 0; CRYPTO_UP_REF(&decoder->base.refcnt, &ref); return 1; } void OSSL_DECODER_free(OSSL_DECODER *decoder) { int ref = 0; if (decoder == NULL) return; CRYPTO_DOWN_REF(&decoder->base.refcnt, &ref); if (ref > 0) return; OPENSSL_free(decoder->base.name); ossl_property_free(decoder->base.parsed_propdef); ossl_provider_free(decoder->base.prov); CRYPTO_FREE_REF(&decoder->base.refcnt); OPENSSL_free(decoder); } /* Data to be passed through ossl_method_construct() */ struct decoder_data_st { OSSL_LIB_CTX *libctx; int id; /* For get_decoder_from_store() */ const char *names; /* For get_decoder_from_store() */ const char *propquery; /* For get_decoder_from_store() */ OSSL_METHOD_STORE *tmp_store; /* For get_tmp_decoder_store() */ unsigned int flag_construct_error_occurred : 1; }; /* * Generic routines to fetch / create DECODER methods with * ossl_method_construct() */ /* Temporary decoder method store, constructor and destructor */ static void *get_tmp_decoder_store(void *data) { struct decoder_data_st *methdata = data; if (methdata->tmp_store == NULL) methdata->tmp_store = ossl_method_store_new(methdata->libctx); return methdata->tmp_store; } static void dealloc_tmp_decoder_store(void *store) { if (store != NULL) ossl_method_store_free(store); } /* Get the permanent decoder store */ static OSSL_METHOD_STORE *get_decoder_store(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DECODER_STORE_INDEX); } static int reserve_decoder_store(void *store, void *data) { struct decoder_data_st *methdata = data; if (store == NULL && (store = get_decoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_lock_store(store); } static int unreserve_decoder_store(void *store, void *data) { struct decoder_data_st *methdata = data; if (store == NULL && (store = get_decoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_unlock_store(store); } /* Get decoder methods from a store, or put one in */ static void *get_decoder_from_store(void *store, const OSSL_PROVIDER **prov, void *data) { struct decoder_data_st *methdata = data; void *method = NULL; int id; /* * get_decoder_from_store() is only called to try and get the method * that OSSL_DECODER_fetch() is asking for, and the name or name id are * passed via methdata. */ if ((id = methdata->id) == 0 && methdata->names != NULL) { OSSL_NAMEMAP *namemap = ossl_namemap_stored(methdata->libctx); const char *names = methdata->names; const char *q = strchr(names, NAME_SEPARATOR); size_t l = (q == NULL ? strlen(names) : (size_t)(q - names)); if (namemap == 0) return NULL; id = ossl_namemap_name2num_n(namemap, names, l); } if (id == 0) return NULL; if (store == NULL && (store = get_decoder_store(methdata->libctx)) == NULL) return NULL; if (!ossl_method_store_fetch(store, id, methdata->propquery, prov, &method)) return NULL; return method; } static int put_decoder_in_store(void *store, void *method, const OSSL_PROVIDER *prov, const char *names, const char *propdef, void *data) { struct decoder_data_st *methdata = data; OSSL_NAMEMAP *namemap; int id; size_t l = 0; /* * put_decoder_in_store() is only called with an OSSL_DECODER method that * was successfully created by construct_decoder() below, which means that * all the names should already be stored in the namemap with the same * numeric identity, so just use the first to get that identity. */ if (names != NULL) { const char *q = strchr(names, NAME_SEPARATOR); l = (q == NULL ? strlen(names) : (size_t)(q - names)); } if ((namemap = ossl_namemap_stored(methdata->libctx)) == NULL || (id = ossl_namemap_name2num_n(namemap, names, l)) == 0) return 0; if (store == NULL && (store = get_decoder_store(methdata->libctx)) == NULL) return 0; return ossl_method_store_add(store, prov, id, propdef, method, (int (*)(void *))OSSL_DECODER_up_ref, (void (*)(void *))OSSL_DECODER_free); } /* Create and populate a decoder method */ void *ossl_decoder_from_algorithm(int id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { OSSL_DECODER *decoder = NULL; const OSSL_DISPATCH *fns = algodef->implementation; OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); if ((decoder = ossl_decoder_new()) == NULL) return NULL; decoder->base.id = id; if ((decoder->base.name = ossl_algorithm_get1_first_name(algodef)) == NULL) { OSSL_DECODER_free(decoder); return NULL; } decoder->base.algodef = algodef; if ((decoder->base.parsed_propdef = ossl_parse_property(libctx, algodef->property_definition)) == NULL) { OSSL_DECODER_free(decoder); return NULL; } for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_DECODER_NEWCTX: if (decoder->newctx == NULL) decoder->newctx = OSSL_FUNC_decoder_newctx(fns); break; case OSSL_FUNC_DECODER_FREECTX: if (decoder->freectx == NULL) decoder->freectx = OSSL_FUNC_decoder_freectx(fns); break; case OSSL_FUNC_DECODER_GET_PARAMS: if (decoder->get_params == NULL) decoder->get_params = OSSL_FUNC_decoder_get_params(fns); break; case OSSL_FUNC_DECODER_GETTABLE_PARAMS: if (decoder->gettable_params == NULL) decoder->gettable_params = OSSL_FUNC_decoder_gettable_params(fns); break; case OSSL_FUNC_DECODER_SET_CTX_PARAMS: if (decoder->set_ctx_params == NULL) decoder->set_ctx_params = OSSL_FUNC_decoder_set_ctx_params(fns); break; case OSSL_FUNC_DECODER_SETTABLE_CTX_PARAMS: if (decoder->settable_ctx_params == NULL) decoder->settable_ctx_params = OSSL_FUNC_decoder_settable_ctx_params(fns); break; case OSSL_FUNC_DECODER_DOES_SELECTION: if (decoder->does_selection == NULL) decoder->does_selection = OSSL_FUNC_decoder_does_selection(fns); break; case OSSL_FUNC_DECODER_DECODE: if (decoder->decode == NULL) decoder->decode = OSSL_FUNC_decoder_decode(fns); break; case OSSL_FUNC_DECODER_EXPORT_OBJECT: if (decoder->export_object == NULL) decoder->export_object = OSSL_FUNC_decoder_export_object(fns); break; } } /* * Try to check that the method is sensible. * If you have a constructor, you must have a destructor and vice versa. * You must have at least one of the encoding driver functions. */ if (!((decoder->newctx == NULL && decoder->freectx == NULL) || (decoder->newctx != NULL && decoder->freectx != NULL)) || decoder->decode == NULL) { OSSL_DECODER_free(decoder); ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROVIDER_FUNCTIONS); return NULL; } if (prov != NULL && !ossl_provider_up_ref(prov)) { OSSL_DECODER_free(decoder); return NULL; } decoder->base.prov = prov; return decoder; } /* * The core fetching functionality passes the names of the implementation. * This function is responsible to getting an identity number for them, * then call ossl_decoder_from_algorithm() with that identity number. */ static void *construct_decoder(const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov, void *data) { /* * This function is only called if get_decoder_from_store() returned * NULL, so it's safe to say that of all the spots to create a new * namemap entry, this is it. Should the name already exist there, we * know that ossl_namemap_add() will return its corresponding number. */ struct decoder_data_st *methdata = data; OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); const char *names = algodef->algorithm_names; int id = ossl_namemap_add_names(namemap, 0, names, NAME_SEPARATOR); void *method = NULL; if (id != 0) method = ossl_decoder_from_algorithm(id, algodef, prov); /* * Flag to indicate that there was actual construction errors. This * helps inner_evp_generic_fetch() determine what error it should * record on inaccessible algorithms. */ if (method == NULL) methdata->flag_construct_error_occurred = 1; return method; } /* Intermediary function to avoid ugly casts, used below */ static void destruct_decoder(void *method, void *data) { OSSL_DECODER_free(method); } static int up_ref_decoder(void *method) { return OSSL_DECODER_up_ref(method); } static void free_decoder(void *method) { OSSL_DECODER_free(method); } /* Fetching support. Can fetch by numeric identity or by name */ static OSSL_DECODER * inner_ossl_decoder_fetch(struct decoder_data_st *methdata, const char *name, const char *properties) { OSSL_METHOD_STORE *store = get_decoder_store(methdata->libctx); OSSL_NAMEMAP *namemap = ossl_namemap_stored(methdata->libctx); const char *const propq = properties != NULL ? properties : ""; void *method = NULL; int unsupported, id; if (store == NULL || namemap == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } id = name != NULL ? ossl_namemap_name2num(namemap, name) : 0; /* * If we haven't found the name yet, chances are that the algorithm to * be fetched is unsupported. */ unsupported = id == 0; if (id == 0 || !ossl_method_store_cache_get(store, NULL, id, propq, &method)) { OSSL_METHOD_CONSTRUCT_METHOD mcm = { get_tmp_decoder_store, reserve_decoder_store, unreserve_decoder_store, get_decoder_from_store, put_decoder_in_store, construct_decoder, destruct_decoder }; OSSL_PROVIDER *prov = NULL; methdata->id = id; methdata->names = name; methdata->propquery = propq; methdata->flag_construct_error_occurred = 0; if ((method = ossl_method_construct(methdata->libctx, OSSL_OP_DECODER, &prov, 0 /* !force_cache */, &mcm, methdata)) != NULL) { /* * If construction did create a method for us, we know that * there is a correct name_id and meth_id, since those have * already been calculated in get_decoder_from_store() and * put_decoder_in_store() above. */ if (id == 0 && name != NULL) id = ossl_namemap_name2num(namemap, name); if (id != 0) ossl_method_store_cache_set(store, prov, id, propq, method, up_ref_decoder, free_decoder); } /* * If we never were in the constructor, the algorithm to be fetched * is unsupported. */ unsupported = !methdata->flag_construct_error_occurred; } if ((id != 0 || name != NULL) && method == NULL) { int code = unsupported ? ERR_R_UNSUPPORTED : ERR_R_FETCH_FAILED; if (name == NULL) name = ossl_namemap_num2name(namemap, id, 0); ERR_raise_data(ERR_LIB_OSSL_DECODER, code, "%s, Name (%s : %d), Properties (%s)", ossl_lib_ctx_get_descriptor(methdata->libctx), name == NULL ? "<null>" : name, id, properties == NULL ? "<null>" : properties); } return method; } OSSL_DECODER *OSSL_DECODER_fetch(OSSL_LIB_CTX *libctx, const char *name, const char *properties) { struct decoder_data_st methdata; void *method; methdata.libctx = libctx; methdata.tmp_store = NULL; method = inner_ossl_decoder_fetch(&methdata, name, properties); dealloc_tmp_decoder_store(methdata.tmp_store); return method; } int ossl_decoder_store_cache_flush(OSSL_LIB_CTX *libctx) { OSSL_METHOD_STORE *store = get_decoder_store(libctx); if (store != NULL) return ossl_method_store_cache_flush_all(store); return 1; } int ossl_decoder_store_remove_all_provided(const OSSL_PROVIDER *prov) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_METHOD_STORE *store = get_decoder_store(libctx); if (store != NULL) return ossl_method_store_remove_all_provided(store, prov); return 1; } /* * Library of basic method functions */ const OSSL_PROVIDER *OSSL_DECODER_get0_provider(const OSSL_DECODER *decoder) { if (!ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return decoder->base.prov; } const char *OSSL_DECODER_get0_properties(const OSSL_DECODER *decoder) { if (!ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return decoder->base.algodef->property_definition; } const OSSL_PROPERTY_LIST * ossl_decoder_parsed_properties(const OSSL_DECODER *decoder) { if (!ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return decoder->base.parsed_propdef; } int ossl_decoder_get_number(const OSSL_DECODER *decoder) { if (!ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } return decoder->base.id; } const char *OSSL_DECODER_get0_name(const OSSL_DECODER *decoder) { return decoder->base.name; } const char *OSSL_DECODER_get0_description(const OSSL_DECODER *decoder) { return decoder->base.algodef->algorithm_description; } int OSSL_DECODER_is_a(const OSSL_DECODER *decoder, const char *name) { if (decoder->base.prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(decoder->base.prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_name2num(namemap, name) == decoder->base.id; } return 0; } static int resolve_name(OSSL_DECODER *decoder, const char *name) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(decoder->base.prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_name2num(namemap, name); } int ossl_decoder_fast_is_a(OSSL_DECODER *decoder, const char *name, int *id_cache) { int id = *id_cache; if (id <= 0) *id_cache = id = resolve_name(decoder, name); return id > 0 && ossl_decoder_get_number(decoder) == id; } struct do_one_data_st { void (*user_fn)(OSSL_DECODER *decoder, void *arg); void *user_arg; }; static void do_one(ossl_unused int id, void *method, void *arg) { struct do_one_data_st *data = arg; data->user_fn(method, data->user_arg); } void OSSL_DECODER_do_all_provided(OSSL_LIB_CTX *libctx, void (*user_fn)(OSSL_DECODER *decoder, void *arg), void *user_arg) { struct decoder_data_st methdata; struct do_one_data_st data; methdata.libctx = libctx; methdata.tmp_store = NULL; (void)inner_ossl_decoder_fetch(&methdata, NULL, NULL /* properties */); data.user_fn = user_fn; data.user_arg = user_arg; if (methdata.tmp_store != NULL) ossl_method_store_do_all(methdata.tmp_store, &do_one, &data); ossl_method_store_do_all(get_decoder_store(libctx), &do_one, &data); dealloc_tmp_decoder_store(methdata.tmp_store); } int OSSL_DECODER_names_do_all(const OSSL_DECODER *decoder, void (*fn)(const char *name, void *data), void *data) { if (decoder == NULL) return 0; if (decoder->base.prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(decoder->base.prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_doall_names(namemap, decoder->base.id, fn, data); } return 1; } const OSSL_PARAM * OSSL_DECODER_gettable_params(OSSL_DECODER *decoder) { if (decoder != NULL && decoder->gettable_params != NULL) { void *provctx = ossl_provider_ctx(OSSL_DECODER_get0_provider(decoder)); return decoder->gettable_params(provctx); } return NULL; } int OSSL_DECODER_get_params(OSSL_DECODER *decoder, OSSL_PARAM params[]) { if (decoder != NULL && decoder->get_params != NULL) return decoder->get_params(params); return 0; } const OSSL_PARAM * OSSL_DECODER_settable_ctx_params(OSSL_DECODER *decoder) { if (decoder != NULL && decoder->settable_ctx_params != NULL) { void *provctx = ossl_provider_ctx(OSSL_DECODER_get0_provider(decoder)); return decoder->settable_ctx_params(provctx); } return NULL; } /* * Decoder context support */ /* * |encoder| value NULL is valid, and signifies that there is no decoder. * This is useful to provide fallback mechanisms. * Functions that want to verify if there is a decoder can do so with * OSSL_DECODER_CTX_get_decoder() */ OSSL_DECODER_CTX *OSSL_DECODER_CTX_new(void) { OSSL_DECODER_CTX *ctx; ctx = OPENSSL_zalloc(sizeof(*ctx)); return ctx; } int OSSL_DECODER_CTX_set_params(OSSL_DECODER_CTX *ctx, const OSSL_PARAM params[]) { int ok = 1; size_t i; size_t l; if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ctx->decoder_insts == NULL) return 1; l = OSSL_DECODER_CTX_get_num_decoders(ctx); for (i = 0; i < l; i++) { OSSL_DECODER_INSTANCE *decoder_inst = sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i); OSSL_DECODER *decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst); OSSL_DECODER *decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst); if (decoderctx == NULL || decoder->set_ctx_params == NULL) continue; if (!decoder->set_ctx_params(decoderctx, params)) ok = 0; } return ok; } void OSSL_DECODER_CTX_free(OSSL_DECODER_CTX *ctx) { if (ctx != NULL) { if (ctx->cleanup != NULL) ctx->cleanup(ctx->construct_data); sk_OSSL_DECODER_INSTANCE_pop_free(ctx->decoder_insts, ossl_decoder_instance_free); ossl_pw_clear_passphrase_data(&ctx->pwdata); OPENSSL_free(ctx); } }
./openssl/crypto/encode_decode/decoder_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/decodererr.h> #include "crypto/decodererr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA OSSL_DECODER_str_reasons[] = { {ERR_PACK(ERR_LIB_OSSL_DECODER, 0, OSSL_DECODER_R_COULD_NOT_DECODE_OBJECT), "could not decode object"}, {ERR_PACK(ERR_LIB_OSSL_DECODER, 0, OSSL_DECODER_R_DECODER_NOT_FOUND), "decoder not found"}, {ERR_PACK(ERR_LIB_OSSL_DECODER, 0, OSSL_DECODER_R_MISSING_GET_PARAMS), "missing get params"}, {0, NULL} }; #endif int ossl_err_load_OSSL_DECODER_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(OSSL_DECODER_str_reasons[0].error) == NULL) ERR_load_strings_const(OSSL_DECODER_str_reasons); #endif return 1; }
./openssl/crypto/encode_decode/encoder_pkey.c
/* * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/ui.h> #include <openssl/params.h> #include <openssl/encoder.h> #include <openssl/core_names.h> #include <openssl/provider.h> #include <openssl/safestack.h> #include <openssl/trace.h> #include "internal/provider.h" #include "internal/property.h" #include "internal/namemap.h" #include "crypto/evp.h" #include "encoder_local.h" DEFINE_STACK_OF(OSSL_ENCODER) int OSSL_ENCODER_CTX_set_cipher(OSSL_ENCODER_CTX *ctx, const char *cipher_name, const char *propquery) { OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ENCODER_PARAM_CIPHER, (void *)cipher_name, 0); params[1] = OSSL_PARAM_construct_utf8_string(OSSL_ENCODER_PARAM_PROPERTIES, (void *)propquery, 0); return OSSL_ENCODER_CTX_set_params(ctx, params); } int OSSL_ENCODER_CTX_set_passphrase(OSSL_ENCODER_CTX *ctx, const unsigned char *kstr, size_t klen) { return ossl_pw_set_passphrase(&ctx->pwdata, kstr, klen); } int OSSL_ENCODER_CTX_set_passphrase_ui(OSSL_ENCODER_CTX *ctx, const UI_METHOD *ui_method, void *ui_data) { return ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data); } int OSSL_ENCODER_CTX_set_pem_password_cb(OSSL_ENCODER_CTX *ctx, pem_password_cb *cb, void *cbarg) { return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg); } int OSSL_ENCODER_CTX_set_passphrase_cb(OSSL_ENCODER_CTX *ctx, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { return ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, cb, cbarg); } /* * Support for OSSL_ENCODER_CTX_new_for_type: * finding a suitable encoder */ struct collected_encoder_st { STACK_OF(OPENSSL_CSTRING) *names; int *id_names; const char *output_structure; const char *output_type; const OSSL_PROVIDER *keymgmt_prov; OSSL_ENCODER_CTX *ctx; unsigned int flag_find_same_provider:1; int error_occurred; }; static void collect_encoder(OSSL_ENCODER *encoder, void *arg) { struct collected_encoder_st *data = arg; const OSSL_PROVIDER *prov; if (data->error_occurred) return; data->error_occurred = 1; /* Assume the worst */ prov = OSSL_ENCODER_get0_provider(encoder); /* * collect_encoder() is called in two passes, one where the encoders * from the same provider as the keymgmt are looked up, and one where * the other encoders are looked up. |data->flag_find_same_provider| * tells us which pass we're in. */ if ((data->keymgmt_prov == prov) == data->flag_find_same_provider) { void *provctx = OSSL_PROVIDER_get0_provider_ctx(prov); int i, end_i = sk_OPENSSL_CSTRING_num(data->names); int match; for (i = 0; i < end_i; i++) { if (data->flag_find_same_provider) match = (data->id_names[i] == encoder->base.id); else match = OSSL_ENCODER_is_a(encoder, sk_OPENSSL_CSTRING_value(data->names, i)); if (!match || (encoder->does_selection != NULL && !encoder->does_selection(provctx, data->ctx->selection)) || (data->keymgmt_prov != prov && encoder->import_object == NULL)) continue; /* Only add each encoder implementation once */ if (OSSL_ENCODER_CTX_add_encoder(data->ctx, encoder)) break; } } data->error_occurred = 0; /* All is good now */ } struct collected_names_st { STACK_OF(OPENSSL_CSTRING) *names; unsigned int error_occurred:1; }; static void collect_name(const char *name, void *arg) { struct collected_names_st *data = arg; if (data->error_occurred) return; data->error_occurred = 1; /* Assume the worst */ if (sk_OPENSSL_CSTRING_push(data->names, name) <= 0) return; data->error_occurred = 0; /* All is good now */ } /* * Support for OSSL_ENCODER_to_bio: * writing callback for the OSSL_PARAM (the implementation doesn't have * intimate knowledge of the provider side object) */ struct construct_data_st { const EVP_PKEY *pk; int selection; OSSL_ENCODER_INSTANCE *encoder_inst; const void *obj; void *constructed_obj; }; static int encoder_import_cb(const OSSL_PARAM params[], void *arg) { struct construct_data_st *construct_data = arg; OSSL_ENCODER_INSTANCE *encoder_inst = construct_data->encoder_inst; OSSL_ENCODER *encoder = OSSL_ENCODER_INSTANCE_get_encoder(encoder_inst); void *encoderctx = OSSL_ENCODER_INSTANCE_get_encoder_ctx(encoder_inst); construct_data->constructed_obj = encoder->import_object(encoderctx, construct_data->selection, params); return (construct_data->constructed_obj != NULL); } static const void * encoder_construct_pkey(OSSL_ENCODER_INSTANCE *encoder_inst, void *arg) { struct construct_data_st *data = arg; if (data->obj == NULL) { OSSL_ENCODER *encoder = OSSL_ENCODER_INSTANCE_get_encoder(encoder_inst); const EVP_PKEY *pk = data->pk; const OSSL_PROVIDER *k_prov = EVP_KEYMGMT_get0_provider(pk->keymgmt); const OSSL_PROVIDER *e_prov = OSSL_ENCODER_get0_provider(encoder); if (k_prov != e_prov) { data->encoder_inst = encoder_inst; if (!evp_keymgmt_export(pk->keymgmt, pk->keydata, data->selection, &encoder_import_cb, data)) return NULL; data->obj = data->constructed_obj; } else { data->obj = pk->keydata; } } return data->obj; } static void encoder_destruct_pkey(void *arg) { struct construct_data_st *data = arg; if (data->encoder_inst != NULL) { OSSL_ENCODER *encoder = OSSL_ENCODER_INSTANCE_get_encoder(data->encoder_inst); encoder->free_object(data->constructed_obj); } data->constructed_obj = NULL; } /* * OSSL_ENCODER_CTX_new_for_pkey() returns a ctx with no encoder if * it couldn't find a suitable encoder. This allows a caller to detect if * a suitable encoder was found, with OSSL_ENCODER_CTX_get_num_encoder(), * and to use fallback methods if the result is NULL. */ static int ossl_encoder_ctx_setup_for_pkey(OSSL_ENCODER_CTX *ctx, const EVP_PKEY *pkey, int selection, const char *propquery) { struct construct_data_st *data = NULL; const OSSL_PROVIDER *prov = NULL; OSSL_LIB_CTX *libctx = NULL; int ok = 0, i, end; OSSL_NAMEMAP *namemap; if (!ossl_assert(ctx != NULL) || !ossl_assert(pkey != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (evp_pkey_is_provided(pkey)) { prov = EVP_KEYMGMT_get0_provider(pkey->keymgmt); libctx = ossl_provider_libctx(prov); } if (pkey->keymgmt != NULL) { struct collected_encoder_st encoder_data; struct collected_names_st keymgmt_data; if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL) goto err; /* * Select the first encoder implementations in two steps. * First, collect the keymgmt names, then the encoders that match. */ keymgmt_data.names = sk_OPENSSL_CSTRING_new_null(); if (keymgmt_data.names == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_CRYPTO_LIB); goto err; } keymgmt_data.error_occurred = 0; EVP_KEYMGMT_names_do_all(pkey->keymgmt, collect_name, &keymgmt_data); if (keymgmt_data.error_occurred) { sk_OPENSSL_CSTRING_free(keymgmt_data.names); goto err; } encoder_data.names = keymgmt_data.names; encoder_data.output_type = ctx->output_type; encoder_data.output_structure = ctx->output_structure; encoder_data.error_occurred = 0; encoder_data.keymgmt_prov = prov; encoder_data.ctx = ctx; encoder_data.id_names = NULL; /* * collect_encoder() is called many times, and for every call it converts all encoder_data.names * into namemap ids if it calls OSSL_ENCODER_is_a(). We cache the ids here instead, * and can use them for encoders with the same provider as the keymgmt. */ namemap = ossl_namemap_stored(libctx); end = sk_OPENSSL_CSTRING_num(encoder_data.names); if (end > 0) { encoder_data.id_names = OPENSSL_malloc(end * sizeof(int)); if (encoder_data.id_names == NULL) { sk_OPENSSL_CSTRING_free(keymgmt_data.names); goto err; } for (i = 0; i < end; ++i) { const char *name = sk_OPENSSL_CSTRING_value(keymgmt_data.names, i); encoder_data.id_names[i] = ossl_namemap_name2num(namemap, name); } } /* * Place the encoders with the a different provider as the keymgmt * last (the chain is processed in reverse order) */ encoder_data.flag_find_same_provider = 0; OSSL_ENCODER_do_all_provided(libctx, collect_encoder, &encoder_data); /* * Place the encoders with the same provider as the keymgmt first * (the chain is processed in reverse order) */ encoder_data.flag_find_same_provider = 1; OSSL_ENCODER_do_all_provided(libctx, collect_encoder, &encoder_data); OPENSSL_free(encoder_data.id_names); sk_OPENSSL_CSTRING_free(keymgmt_data.names); if (encoder_data.error_occurred) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_CRYPTO_LIB); goto err; } } if (data != NULL && OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0) { if (!OSSL_ENCODER_CTX_set_construct(ctx, encoder_construct_pkey) || !OSSL_ENCODER_CTX_set_construct_data(ctx, data) || !OSSL_ENCODER_CTX_set_cleanup(ctx, encoder_destruct_pkey)) goto err; data->pk = pkey; data->selection = selection; data = NULL; /* Avoid it being freed */ } ok = 1; err: if (data != NULL) { OSSL_ENCODER_CTX_set_construct_data(ctx, NULL); OPENSSL_free(data); } return ok; } OSSL_ENCODER_CTX *OSSL_ENCODER_CTX_new_for_pkey(const EVP_PKEY *pkey, int selection, const char *output_type, const char *output_struct, const char *propquery) { OSSL_ENCODER_CTX *ctx = NULL; OSSL_LIB_CTX *libctx = NULL; if (pkey == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!evp_pkey_is_assigned(pkey)) { ERR_raise_data(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_INVALID_ARGUMENT, "The passed EVP_PKEY must be assigned a key"); return NULL; } if ((ctx = OSSL_ENCODER_CTX_new()) == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_OSSL_ENCODER_LIB); return NULL; } if (evp_pkey_is_provided(pkey)) { const OSSL_PROVIDER *prov = EVP_KEYMGMT_get0_provider(pkey->keymgmt); libctx = ossl_provider_libctx(prov); } OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "(ctx %p) Looking for %s encoders with selection %d\n", (void *)ctx, EVP_PKEY_get0_type_name(pkey), selection); BIO_printf(trc_out, " output type: %s, output structure: %s\n", output_type, output_struct); } OSSL_TRACE_END(ENCODER); if (OSSL_ENCODER_CTX_set_output_type(ctx, output_type) && (output_struct == NULL || OSSL_ENCODER_CTX_set_output_structure(ctx, output_struct)) && OSSL_ENCODER_CTX_set_selection(ctx, selection) && ossl_encoder_ctx_setup_for_pkey(ctx, pkey, selection, propquery) && OSSL_ENCODER_CTX_add_extra(ctx, libctx, propquery)) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; int save_parameters = pkey->save_parameters; params[0] = OSSL_PARAM_construct_int(OSSL_ENCODER_PARAM_SAVE_PARAMETERS, &save_parameters); /* ignoring error as this is only auxiliary parameter */ (void)OSSL_ENCODER_CTX_set_params(ctx, params); OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "(ctx %p) Got %d encoders\n", (void *)ctx, OSSL_ENCODER_CTX_get_num_encoders(ctx)); } OSSL_TRACE_END(ENCODER); return ctx; } OSSL_ENCODER_CTX_free(ctx); return NULL; }
./openssl/crypto/encode_decode/decoder_lib.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 <openssl/core_names.h> #include <openssl/bio.h> #include <openssl/params.h> #include <openssl/provider.h> #include <openssl/evperr.h> #include <openssl/ecerr.h> #include <openssl/pkcs12err.h> #include <openssl/x509err.h> #include <openssl/trace.h> #include "internal/bio.h" #include "internal/provider.h" #include "internal/namemap.h" #include "crypto/decoder.h" #include "encoder_local.h" #include "internal/e_os.h" struct decoder_process_data_st { OSSL_DECODER_CTX *ctx; /* Current BIO */ BIO *bio; /* Index of the current decoder instance to be processed */ size_t current_decoder_inst_index; /* For tracing, count recursion level */ size_t recursion; /*- * Flags */ unsigned int flag_next_level_called : 1; unsigned int flag_construct_called : 1; unsigned int flag_input_structure_checked : 1; }; static int decoder_process(const OSSL_PARAM params[], void *arg); int OSSL_DECODER_from_bio(OSSL_DECODER_CTX *ctx, BIO *in) { struct decoder_process_data_st data; int ok = 0; BIO *new_bio = NULL; unsigned long lasterr; if (in == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (OSSL_DECODER_CTX_get_num_decoders(ctx) == 0) { ERR_raise_data(ERR_LIB_OSSL_DECODER, OSSL_DECODER_R_DECODER_NOT_FOUND, "No decoders were found. For standard decoders you need " "at least one of the default or base providers " "available. Did you forget to load them?"); return 0; } lasterr = ERR_peek_last_error(); if (BIO_tell(in) < 0) { new_bio = BIO_new(BIO_f_readbuffer()); if (new_bio == NULL) return 0; in = BIO_push(new_bio, in); } memset(&data, 0, sizeof(data)); data.ctx = ctx; data.bio = in; /* Enable passphrase caching */ (void)ossl_pw_enable_passphrase_caching(&ctx->pwdata); ok = decoder_process(NULL, &data); if (!data.flag_construct_called) { const char *spaces = ctx->start_input_type != NULL && ctx->input_structure != NULL ? " " : ""; const char *input_type_label = ctx->start_input_type != NULL ? "Input type: " : ""; const char *input_structure_label = ctx->input_structure != NULL ? "Input structure: " : ""; const char *comma = ctx->start_input_type != NULL && ctx->input_structure != NULL ? ", " : ""; const char *input_type = ctx->start_input_type != NULL ? ctx->start_input_type : ""; const char *input_structure = ctx->input_structure != NULL ? ctx->input_structure : ""; if (ERR_peek_last_error() == lasterr || ERR_peek_error() == 0) /* Prevent spurious decoding error but add at least something */ ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_UNSUPPORTED, "No supported data to decode. %s%s%s%s%s%s", spaces, input_type_label, input_type, comma, input_structure_label, input_structure); ok = 0; } /* Clear any internally cached passphrase */ (void)ossl_pw_clear_passphrase_cache(&ctx->pwdata); if (new_bio != NULL) { BIO_pop(new_bio); BIO_free(new_bio); } return ok; } #ifndef OPENSSL_NO_STDIO static BIO *bio_from_file(FILE *fp) { BIO *b; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_BIO_LIB); return NULL; } BIO_set_fp(b, fp, BIO_NOCLOSE); return b; } int OSSL_DECODER_from_fp(OSSL_DECODER_CTX *ctx, FILE *fp) { BIO *b = bio_from_file(fp); int ret = 0; if (b != NULL) ret = OSSL_DECODER_from_bio(ctx, b); BIO_free(b); return ret; } #endif int OSSL_DECODER_from_data(OSSL_DECODER_CTX *ctx, const unsigned char **pdata, size_t *pdata_len) { BIO *membio; int ret = 0; if (pdata == NULL || *pdata == NULL || pdata_len == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } membio = BIO_new_mem_buf(*pdata, (int)*pdata_len); if (OSSL_DECODER_from_bio(ctx, membio)) { *pdata_len = (size_t)BIO_get_mem_data(membio, pdata); ret = 1; } BIO_free(membio); return ret; } int OSSL_DECODER_CTX_set_selection(OSSL_DECODER_CTX *ctx, int selection) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* * 0 is a valid selection, and means that the caller leaves * it to code to discover what the selection is. */ ctx->selection = selection; return 1; } int OSSL_DECODER_CTX_set_input_type(OSSL_DECODER_CTX *ctx, const char *input_type) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* * NULL is a valid starting input type, and means that the caller leaves * it to code to discover what the starting input type is. */ ctx->start_input_type = input_type; return 1; } int OSSL_DECODER_CTX_set_input_structure(OSSL_DECODER_CTX *ctx, const char *input_structure) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* * NULL is a valid starting input structure, and means that the caller * leaves it to code to discover what the starting input structure is. */ ctx->input_structure = input_structure; return 1; } OSSL_DECODER_INSTANCE *ossl_decoder_instance_new(OSSL_DECODER *decoder, void *decoderctx) { OSSL_DECODER_INSTANCE *decoder_inst = NULL; const OSSL_PROVIDER *prov; OSSL_LIB_CTX *libctx; const OSSL_PROPERTY_LIST *props; const OSSL_PROPERTY_DEFINITION *prop; if (!ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((decoder_inst = OPENSSL_zalloc(sizeof(*decoder_inst))) == NULL) return 0; prov = OSSL_DECODER_get0_provider(decoder); libctx = ossl_provider_libctx(prov); props = ossl_decoder_parsed_properties(decoder); if (props == NULL) { ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION, "there are no property definitions with decoder %s", OSSL_DECODER_get0_name(decoder)); goto err; } /* The "input" property is mandatory */ prop = ossl_property_find_property(props, libctx, "input"); decoder_inst->input_type = ossl_property_get_string_value(libctx, prop); decoder_inst->input_type_id = 0; if (decoder_inst->input_type == NULL) { ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION, "the mandatory 'input' property is missing " "for decoder %s (properties: %s)", OSSL_DECODER_get0_name(decoder), OSSL_DECODER_get0_properties(decoder)); goto err; } /* The "structure" property is optional */ prop = ossl_property_find_property(props, libctx, "structure"); if (prop != NULL) { decoder_inst->input_structure = ossl_property_get_string_value(libctx, prop); } if (!OSSL_DECODER_up_ref(decoder)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_INTERNAL_ERROR); goto err; } decoder_inst->decoder = decoder; decoder_inst->decoderctx = decoderctx; return decoder_inst; err: ossl_decoder_instance_free(decoder_inst); return NULL; } void ossl_decoder_instance_free(OSSL_DECODER_INSTANCE *decoder_inst) { if (decoder_inst != NULL) { if (decoder_inst->decoder != NULL) decoder_inst->decoder->freectx(decoder_inst->decoderctx); decoder_inst->decoderctx = NULL; OSSL_DECODER_free(decoder_inst->decoder); decoder_inst->decoder = NULL; OPENSSL_free(decoder_inst); } } OSSL_DECODER_INSTANCE *ossl_decoder_instance_dup(const OSSL_DECODER_INSTANCE *src) { OSSL_DECODER_INSTANCE *dest; const OSSL_PROVIDER *prov; void *provctx; if ((dest = OPENSSL_zalloc(sizeof(*dest))) == NULL) return NULL; *dest = *src; if (!OSSL_DECODER_up_ref(dest->decoder)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_INTERNAL_ERROR); goto err; } prov = OSSL_DECODER_get0_provider(dest->decoder); provctx = OSSL_PROVIDER_get0_provider_ctx(prov); dest->decoderctx = dest->decoder->newctx(provctx); if (dest->decoderctx == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_INTERNAL_ERROR); OSSL_DECODER_free(dest->decoder); goto err; } return dest; err: OPENSSL_free(dest); return NULL; } int ossl_decoder_ctx_add_decoder_inst(OSSL_DECODER_CTX *ctx, OSSL_DECODER_INSTANCE *di) { int ok; if (ctx->decoder_insts == NULL && (ctx->decoder_insts = sk_OSSL_DECODER_INSTANCE_new_null()) == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB); return 0; } ok = (sk_OSSL_DECODER_INSTANCE_push(ctx->decoder_insts, di) > 0); if (ok) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Added decoder instance %p for decoder %p\n" " %s with %s\n", (void *)ctx, (void *)di, (void *)di->decoder, OSSL_DECODER_get0_name(di->decoder), OSSL_DECODER_get0_properties(di->decoder)); } OSSL_TRACE_END(DECODER); } return ok; } int OSSL_DECODER_CTX_add_decoder(OSSL_DECODER_CTX *ctx, OSSL_DECODER *decoder) { OSSL_DECODER_INSTANCE *decoder_inst = NULL; const OSSL_PROVIDER *prov = NULL; void *decoderctx = NULL; void *provctx = NULL; if (!ossl_assert(ctx != NULL) || !ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } prov = OSSL_DECODER_get0_provider(decoder); provctx = OSSL_PROVIDER_get0_provider_ctx(prov); if ((decoderctx = decoder->newctx(provctx)) == NULL || (decoder_inst = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) goto err; /* Avoid double free of decoderctx on further errors */ decoderctx = NULL; if (!ossl_decoder_ctx_add_decoder_inst(ctx, decoder_inst)) goto err; return 1; err: ossl_decoder_instance_free(decoder_inst); if (decoderctx != NULL) decoder->freectx(decoderctx); return 0; } struct collect_extra_decoder_data_st { OSSL_DECODER_CTX *ctx; const char *output_type; int output_type_id; /* * 0 to check that the decoder's input type is the same as the decoder name * 1 to check that the decoder's input type differs from the decoder name */ enum { IS_SAME = 0, IS_DIFFERENT = 1 } type_check; size_t w_prev_start, w_prev_end; /* "previous" decoders */ size_t w_new_start, w_new_end; /* "new" decoders */ }; DEFINE_STACK_OF(OSSL_DECODER) static void collect_all_decoders(OSSL_DECODER *decoder, void *arg) { STACK_OF(OSSL_DECODER) *skdecoders = arg; if (OSSL_DECODER_up_ref(decoder) && !sk_OSSL_DECODER_push(skdecoders, decoder)) OSSL_DECODER_free(decoder); } static void collect_extra_decoder(OSSL_DECODER *decoder, void *arg) { struct collect_extra_decoder_data_st *data = arg; size_t j; const OSSL_PROVIDER *prov = OSSL_DECODER_get0_provider(decoder); void *provctx = OSSL_PROVIDER_get0_provider_ctx(prov); if (ossl_decoder_fast_is_a(decoder, data->output_type, &data->output_type_id)) { void *decoderctx = NULL; OSSL_DECODER_INSTANCE *di = NULL; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) [%d] Checking out decoder %p:\n" " %s with %s\n", (void *)data->ctx, data->type_check, (void *)decoder, OSSL_DECODER_get0_name(decoder), OSSL_DECODER_get0_properties(decoder)); } OSSL_TRACE_END(DECODER); /* * Check that we don't already have this decoder in our stack, * starting with the previous windows but also looking at what * we have added in the current window. */ for (j = data->w_prev_start; j < data->w_new_end; j++) { OSSL_DECODER_INSTANCE *check_inst = sk_OSSL_DECODER_INSTANCE_value(data->ctx->decoder_insts, j); if (decoder->base.algodef == check_inst->decoder->base.algodef) { /* We found it, so don't do anything more */ OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, " REJECTED: already exists in the chain\n"); } OSSL_TRACE_END(DECODER); return; } } if ((decoderctx = decoder->newctx(provctx)) == NULL) return; if ((di = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) { decoder->freectx(decoderctx); return; } switch (data->type_check) { case IS_SAME: /* If it differs, this is not a decoder to add for now. */ if (!ossl_decoder_fast_is_a(decoder, OSSL_DECODER_INSTANCE_get_input_type(di), &di->input_type_id)) { ossl_decoder_instance_free(di); OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, " REJECTED: input type doesn't match output type\n"); } OSSL_TRACE_END(DECODER); return; } break; case IS_DIFFERENT: /* If it's the same, this is not a decoder to add for now. */ if (ossl_decoder_fast_is_a(decoder, OSSL_DECODER_INSTANCE_get_input_type(di), &di->input_type_id)) { ossl_decoder_instance_free(di); OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, " REJECTED: input type matches output type\n"); } OSSL_TRACE_END(DECODER); return; } break; } /* * Apart from keeping w_new_end up to date, We don't care about * errors here. If it doesn't collect, then it doesn't... */ if (!ossl_decoder_ctx_add_decoder_inst(data->ctx, di)) { ossl_decoder_instance_free(di); return; } data->w_new_end++; } } int OSSL_DECODER_CTX_add_extra(OSSL_DECODER_CTX *ctx, OSSL_LIB_CTX *libctx, const char *propq) { /* * This function goes through existing decoder methods in * |ctx->decoder_insts|, and tries to fetch new decoders that produce * what the existing ones want as input, and push those newly fetched * decoders on top of the same stack. * Then it does the same again, but looping over the newly fetched * decoders, until there are no more decoders to be fetched, or * when we have done this 10 times. * * we do this with sliding windows on the stack by keeping track of indexes * and of the end. * * +----------------+ * | DER to RSA | <--- w_prev_start * +----------------+ * | DER to DSA | * +----------------+ * | DER to DH | * +----------------+ * | PEM to DER | <--- w_prev_end, w_new_start * +----------------+ * <--- w_new_end */ struct collect_extra_decoder_data_st data; size_t depth = 0; /* Counts the number of iterations */ size_t count; /* Calculates how many were added in each iteration */ size_t numdecoders; STACK_OF(OSSL_DECODER) *skdecoders; if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* * If there is no stack of OSSL_DECODER_INSTANCE, we have nothing * more to add. That's fine. */ if (ctx->decoder_insts == NULL) return 1; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Looking for extra decoders\n", (void *)ctx); } OSSL_TRACE_END(DECODER); skdecoders = sk_OSSL_DECODER_new_null(); if (skdecoders == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB); return 0; } OSSL_DECODER_do_all_provided(libctx, collect_all_decoders, skdecoders); numdecoders = sk_OSSL_DECODER_num(skdecoders); memset(&data, 0, sizeof(data)); data.ctx = ctx; data.w_prev_start = 0; data.w_prev_end = sk_OSSL_DECODER_INSTANCE_num(ctx->decoder_insts); do { size_t i, j; data.w_new_start = data.w_new_end = data.w_prev_end; /* * Two iterations: * 0. All decoders that have the same name as their input type. * This allows for decoders that unwrap some data in a specific * encoding, and pass the result on with the same encoding. * 1. All decoders that a different name than their input type. */ for (data.type_check = IS_SAME; data.type_check <= IS_DIFFERENT; data.type_check++) { for (i = data.w_prev_start; i < data.w_prev_end; i++) { OSSL_DECODER_INSTANCE *decoder_inst = sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i); data.output_type = OSSL_DECODER_INSTANCE_get_input_type(decoder_inst); data.output_type_id = 0; for (j = 0; j < numdecoders; j++) collect_extra_decoder(sk_OSSL_DECODER_value(skdecoders, j), &data); } } /* How many were added in this iteration */ count = data.w_new_end - data.w_new_start; /* Slide the "previous decoder" windows */ data.w_prev_start = data.w_new_start; data.w_prev_end = data.w_new_end; depth++; } while (count != 0 && depth <= 10); sk_OSSL_DECODER_pop_free(skdecoders, OSSL_DECODER_free); return 1; } int OSSL_DECODER_CTX_get_num_decoders(OSSL_DECODER_CTX *ctx) { if (ctx == NULL || ctx->decoder_insts == NULL) return 0; return sk_OSSL_DECODER_INSTANCE_num(ctx->decoder_insts); } int OSSL_DECODER_CTX_set_construct(OSSL_DECODER_CTX *ctx, OSSL_DECODER_CONSTRUCT *construct) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->construct = construct; return 1; } int OSSL_DECODER_CTX_set_construct_data(OSSL_DECODER_CTX *ctx, void *construct_data) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->construct_data = construct_data; return 1; } int OSSL_DECODER_CTX_set_cleanup(OSSL_DECODER_CTX *ctx, OSSL_DECODER_CLEANUP *cleanup) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->cleanup = cleanup; return 1; } OSSL_DECODER_CONSTRUCT * OSSL_DECODER_CTX_get_construct(OSSL_DECODER_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->construct; } void *OSSL_DECODER_CTX_get_construct_data(OSSL_DECODER_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->construct_data; } OSSL_DECODER_CLEANUP * OSSL_DECODER_CTX_get_cleanup(OSSL_DECODER_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->cleanup; } int OSSL_DECODER_export(OSSL_DECODER_INSTANCE *decoder_inst, void *reference, size_t reference_sz, OSSL_CALLBACK *export_cb, void *export_cbarg) { OSSL_DECODER *decoder = NULL; void *decoderctx = NULL; if (!(ossl_assert(decoder_inst != NULL) && ossl_assert(reference != NULL) && ossl_assert(export_cb != NULL) && ossl_assert(export_cbarg != NULL))) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst); decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst); return decoder->export_object(decoderctx, reference, reference_sz, export_cb, export_cbarg); } OSSL_DECODER * OSSL_DECODER_INSTANCE_get_decoder(OSSL_DECODER_INSTANCE *decoder_inst) { if (decoder_inst == NULL) return NULL; return decoder_inst->decoder; } void * OSSL_DECODER_INSTANCE_get_decoder_ctx(OSSL_DECODER_INSTANCE *decoder_inst) { if (decoder_inst == NULL) return NULL; return decoder_inst->decoderctx; } const char * OSSL_DECODER_INSTANCE_get_input_type(OSSL_DECODER_INSTANCE *decoder_inst) { if (decoder_inst == NULL) return NULL; return decoder_inst->input_type; } const char * OSSL_DECODER_INSTANCE_get_input_structure(OSSL_DECODER_INSTANCE *decoder_inst, int *was_set) { if (decoder_inst == NULL) return NULL; *was_set = decoder_inst->flag_input_structure_was_set; return decoder_inst->input_structure; } static int decoder_process(const OSSL_PARAM params[], void *arg) { struct decoder_process_data_st *data = arg; OSSL_DECODER_CTX *ctx = data->ctx; OSSL_DECODER_INSTANCE *decoder_inst = NULL; OSSL_DECODER *decoder = NULL; OSSL_CORE_BIO *cbio = NULL; BIO *bio = data->bio; long loc; size_t i; int ok = 0; /* For recursions */ struct decoder_process_data_st new_data; const char *data_type = NULL; const char *data_structure = NULL; /* * This is an indicator up the call stack that something was indeed * decoded, leading to a recursive call of this function. */ data->flag_next_level_called = 1; memset(&new_data, 0, sizeof(new_data)); new_data.ctx = data->ctx; new_data.recursion = data->recursion + 1; #define LEVEL_STR ">>>>>>>>>>>>>>>>" #define LEVEL (new_data.recursion < sizeof(LEVEL_STR) \ ? &LEVEL_STR[sizeof(LEVEL_STR) - new_data.recursion - 1] \ : LEVEL_STR "...") if (params == NULL) { /* First iteration, where we prepare for what is to come */ OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) starting to walk the decoder chain\n", (void *)new_data.ctx); } OSSL_TRACE_END(DECODER); data->current_decoder_inst_index = OSSL_DECODER_CTX_get_num_decoders(ctx); bio = data->bio; } else { const OSSL_PARAM *p; const char *trace_data_structure; decoder_inst = sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, data->current_decoder_inst_index); decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst); data->flag_construct_called = 0; if (ctx->construct != NULL) { int rv; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s Running constructor\n", (void *)new_data.ctx, LEVEL); } OSSL_TRACE_END(DECODER); rv = ctx->construct(decoder_inst, params, ctx->construct_data); OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s Running constructor => %d\n", (void *)new_data.ctx, LEVEL, rv); } OSSL_TRACE_END(DECODER); ok = (rv > 0); if (ok) { data->flag_construct_called = 1; goto end; } } /* The constructor didn't return success */ /* * so we try to use the object we got and feed it to any next * decoder that will take it. Object references are not * allowed for this. * If this data isn't present, decoding has failed. */ p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA); if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING) goto end; new_data.bio = BIO_new_mem_buf(p->data, (int)p->data_size); if (new_data.bio == NULL) goto end; bio = new_data.bio; /* Get the data type if there is one */ p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE); if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &data_type)) goto end; /* Get the data structure if there is one */ p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_STRUCTURE); if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &data_structure)) goto end; /* * If the data structure is "type-specific" and the data type is * given, we drop the data structure. The reasoning is that the * data type is already enough to find the applicable next decoder, * so an additional "type-specific" data structure is extraneous. * * Furthermore, if the OSSL_DECODER caller asked for a type specific * structure under another name, such as "DH", we get a mismatch * if the data structure we just received is "type-specific". * There's only so much you can do without infusing this code with * too special knowledge. */ trace_data_structure = data_structure; if (data_type != NULL && data_structure != NULL && OPENSSL_strcasecmp(data_structure, "type-specific") == 0) data_structure = NULL; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s incoming from previous decoder (%p):\n" " data type: %s, data structure: %s%s\n", (void *)new_data.ctx, LEVEL, (void *)decoder, data_type, trace_data_structure, (trace_data_structure == data_structure ? "" : " (dropped)")); } OSSL_TRACE_END(DECODER); } /* * If we have no more decoders to look through at this point, * we failed */ if (data->current_decoder_inst_index == 0) goto end; if ((loc = BIO_tell(bio)) < 0) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_BIO_LIB); goto end; } if ((cbio = ossl_core_bio_new_from_bio(bio)) == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_BIO_LIB); goto end; } for (i = data->current_decoder_inst_index; i-- > 0;) { OSSL_DECODER_INSTANCE *new_decoder_inst = sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i); OSSL_DECODER *new_decoder = OSSL_DECODER_INSTANCE_get_decoder(new_decoder_inst); void *new_decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(new_decoder_inst); const char *new_input_type = OSSL_DECODER_INSTANCE_get_input_type(new_decoder_inst); int n_i_s_was_set = 0; /* We don't care here */ const char *new_input_structure = OSSL_DECODER_INSTANCE_get_input_structure(new_decoder_inst, &n_i_s_was_set); OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] Considering decoder instance %p (decoder %p):\n" " %s with %s\n", (void *)new_data.ctx, LEVEL, (unsigned int)i, (void *)new_decoder_inst, (void *)new_decoder, OSSL_DECODER_get0_name(new_decoder), OSSL_DECODER_get0_properties(new_decoder)); } OSSL_TRACE_END(DECODER); /* * If |decoder| is NULL, it means we've just started, and the caller * may have specified what it expects the initial input to be. If * that's the case, we do this extra check. */ if (decoder == NULL && ctx->start_input_type != NULL && OPENSSL_strcasecmp(ctx->start_input_type, new_input_type) != 0) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] the start input type '%s' doesn't match the input type of the considered decoder, skipping...\n", (void *)new_data.ctx, LEVEL, (unsigned int)i, ctx->start_input_type); } OSSL_TRACE_END(DECODER); continue; } /* * If we have a previous decoder, we check that the input type * of the next to be used matches the type of this previous one. * |new_input_type| holds the value of the "input-type" parameter * for the decoder we're currently considering. */ if (decoder != NULL && !ossl_decoder_fast_is_a(decoder, new_input_type, &new_decoder_inst->input_type_id)) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] the input type doesn't match the name of the previous decoder (%p), skipping...\n", (void *)new_data.ctx, LEVEL, (unsigned int)i, (void *)decoder); } OSSL_TRACE_END(DECODER); continue; } /* * If the previous decoder gave us a data type, we check to see * if that matches the decoder we're currently considering. */ if (data_type != NULL && !OSSL_DECODER_is_a(new_decoder, data_type)) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] the previous decoder's data type doesn't match the name of the considered decoder, skipping...\n", (void *)new_data.ctx, LEVEL, (unsigned int)i); } OSSL_TRACE_END(DECODER); continue; } /* * If the previous decoder gave us a data structure name, we check * to see that it matches the input data structure of the decoder * we're currently considering. */ if (data_structure != NULL && (new_input_structure == NULL || OPENSSL_strcasecmp(data_structure, new_input_structure) != 0)) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] the previous decoder's data structure doesn't match the input structure of the considered decoder, skipping...\n", (void *)new_data.ctx, LEVEL, (unsigned int)i); } OSSL_TRACE_END(DECODER); continue; } /* * If the decoder we're currently considering specifies a structure, * and this check hasn't already been done earlier in this chain of * decoder_process() calls, check that it matches the user provided * input structure, if one is given. */ if (!data->flag_input_structure_checked && ctx->input_structure != NULL && new_input_structure != NULL) { data->flag_input_structure_checked = 1; if (OPENSSL_strcasecmp(new_input_structure, ctx->input_structure) != 0) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] the previous decoder's data structure doesn't match the input structure given by the user, skipping...\n", (void *)new_data.ctx, LEVEL, (unsigned int)i); } OSSL_TRACE_END(DECODER); continue; } } /* * Checking the return value of BIO_reset() or BIO_seek() is unsafe. * Furthermore, BIO_reset() is unsafe to use if the source BIO happens * to be a BIO_s_mem(), because the earlier BIO_tell() gives us zero * no matter where we are in the underlying buffer we're reading from. * * So, we simply do a BIO_seek(), and use BIO_tell() that we're back * at the same position. This is a best effort attempt, but BIO_seek() * and BIO_tell() should come as a pair... */ (void)BIO_seek(bio, loc); if (BIO_tell(bio) != loc) goto end; /* Recurse */ OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] Running decoder instance %p\n", (void *)new_data.ctx, LEVEL, (unsigned int)i, (void *)new_decoder_inst); } OSSL_TRACE_END(DECODER); /* * We only care about errors reported from decoder implementations * if it returns false (i.e. there was a fatal error). */ ERR_set_mark(); new_data.current_decoder_inst_index = i; new_data.flag_input_structure_checked = data->flag_input_structure_checked; ok = new_decoder->decode(new_decoderctx, cbio, new_data.ctx->selection, decoder_process, &new_data, ossl_pw_passphrase_callback_dec, &new_data.ctx->pwdata); OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] Running decoder instance %p => %d" " (recursed further: %s, construct called: %s)\n", (void *)new_data.ctx, LEVEL, (unsigned int)i, (void *)new_decoder_inst, ok, new_data.flag_next_level_called ? "yes" : "no", new_data.flag_construct_called ? "yes" : "no"); } OSSL_TRACE_END(DECODER); data->flag_construct_called = new_data.flag_construct_called; /* Break on error or if we tried to construct an object already */ if (!ok || data->flag_construct_called) { ERR_clear_last_mark(); break; } ERR_pop_to_mark(); /* * Break if the decoder implementation that we called recursed, since * that indicates that it successfully decoded something. */ if (new_data.flag_next_level_called) break; } end: ossl_core_bio_free(cbio); BIO_free(new_data.bio); return ok; }
./openssl/crypto/encode_decode/encoder_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/encodererr.h> #include "crypto/encodererr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA OSSL_ENCODER_str_reasons[] = { {ERR_PACK(ERR_LIB_OSSL_ENCODER, 0, OSSL_ENCODER_R_ENCODER_NOT_FOUND), "encoder not found"}, {ERR_PACK(ERR_LIB_OSSL_ENCODER, 0, OSSL_ENCODER_R_INCORRECT_PROPERTY_QUERY), "incorrect property query"}, {ERR_PACK(ERR_LIB_OSSL_ENCODER, 0, OSSL_ENCODER_R_MISSING_GET_PARAMS), "missing get params"}, {0, NULL} }; #endif int ossl_err_load_OSSL_ENCODER_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(OSSL_ENCODER_str_reasons[0].error) == NULL) ERR_load_strings_const(OSSL_ENCODER_str_reasons); #endif return 1; }
./openssl/crypto/encode_decode/decoder_pkey.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 <openssl/core_names.h> #include <openssl/core_object.h> #include <openssl/provider.h> #include <openssl/evp.h> #include <openssl/ui.h> #include <openssl/decoder.h> #include <openssl/safestack.h> #include <openssl/trace.h> #include "crypto/evp.h" #include "crypto/decoder.h" #include "crypto/evp/evp_local.h" #include "crypto/lhash.h" #include "encoder_local.h" #include "internal/namemap.h" #include "internal/sizes.h" int OSSL_DECODER_CTX_set_passphrase(OSSL_DECODER_CTX *ctx, const unsigned char *kstr, size_t klen) { return ossl_pw_set_passphrase(&ctx->pwdata, kstr, klen); } int OSSL_DECODER_CTX_set_passphrase_ui(OSSL_DECODER_CTX *ctx, const UI_METHOD *ui_method, void *ui_data) { return ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data); } int OSSL_DECODER_CTX_set_pem_password_cb(OSSL_DECODER_CTX *ctx, pem_password_cb *cb, void *cbarg) { return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg); } int OSSL_DECODER_CTX_set_passphrase_cb(OSSL_DECODER_CTX *ctx, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { return ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, cb, cbarg); } /* * Support for OSSL_DECODER_CTX_new_for_pkey: * The construct data, and collecting keymgmt information for it */ DEFINE_STACK_OF(EVP_KEYMGMT) struct decoder_pkey_data_st { OSSL_LIB_CTX *libctx; char *propq; int selection; STACK_OF(EVP_KEYMGMT) *keymgmts; char *object_type; /* recorded object data type, may be NULL */ void **object; /* Where the result should end up */ }; static int decoder_construct_pkey(OSSL_DECODER_INSTANCE *decoder_inst, const OSSL_PARAM *params, void *construct_data) { struct decoder_pkey_data_st *data = construct_data; OSSL_DECODER *decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst); void *decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst); const OSSL_PROVIDER *decoder_prov = OSSL_DECODER_get0_provider(decoder); EVP_KEYMGMT *keymgmt = NULL; const OSSL_PROVIDER *keymgmt_prov = NULL; int i, end; /* * |object_ref| points to a provider reference to an object, its exact * contents entirely opaque to us, but may be passed to any provider * function that expects this (such as OSSL_FUNC_keymgmt_load(). * * This pointer is considered volatile, i.e. whatever it points at * is assumed to be freed as soon as this function returns. */ void *object_ref = NULL; size_t object_ref_sz = 0; const OSSL_PARAM *p; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE); if (p != NULL) { char *object_type = NULL; if (!OSSL_PARAM_get_utf8_string(p, &object_type, 0)) return 0; OPENSSL_free(data->object_type); data->object_type = object_type; } /* * For stuff that should end up in an EVP_PKEY, we only accept an object * reference for the moment. This enforces that the key data itself * remains with the provider. */ p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_REFERENCE); if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING) return 0; object_ref = p->data; object_ref_sz = p->data_size; /* * First, we try to find a keymgmt that comes from the same provider as * the decoder that passed the params. */ end = sk_EVP_KEYMGMT_num(data->keymgmts); for (i = 0; i < end; i++) { keymgmt = sk_EVP_KEYMGMT_value(data->keymgmts, i); keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt); if (keymgmt_prov == decoder_prov && evp_keymgmt_has_load(keymgmt) && EVP_KEYMGMT_is_a(keymgmt, data->object_type)) break; } if (i < end) { /* To allow it to be freed further down */ if (!EVP_KEYMGMT_up_ref(keymgmt)) return 0; } else if ((keymgmt = EVP_KEYMGMT_fetch(data->libctx, data->object_type, data->propq)) != NULL) { keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt); } if (keymgmt != NULL) { EVP_PKEY *pkey = NULL; void *keydata = NULL; /* * If the EVP_KEYMGMT and the OSSL_DECODER are from the * same provider, we assume that the KEYMGMT has a key loading * function that can handle the provider reference we hold. * * Otherwise, we export from the decoder and import the * result in the keymgmt. */ if (keymgmt_prov == decoder_prov) { keydata = evp_keymgmt_load(keymgmt, object_ref, object_ref_sz); } else { struct evp_keymgmt_util_try_import_data_st import_data; import_data.keymgmt = keymgmt; import_data.keydata = NULL; if (data->selection == 0) /* import/export functions do not tolerate 0 selection */ import_data.selection = OSSL_KEYMGMT_SELECT_ALL; else import_data.selection = data->selection; /* * No need to check for errors here, the value of * |import_data.keydata| is as much an indicator. */ (void)decoder->export_object(decoderctx, object_ref, object_ref_sz, &evp_keymgmt_util_try_import, &import_data); keydata = import_data.keydata; import_data.keydata = NULL; } if (keydata != NULL && (pkey = evp_keymgmt_util_make_pkey(keymgmt, keydata)) == NULL) evp_keymgmt_freedata(keymgmt, keydata); *data->object = pkey; /* * evp_keymgmt_util_make_pkey() increments the reference count when * assigning the EVP_PKEY, so we can free the keymgmt here. */ EVP_KEYMGMT_free(keymgmt); } /* * We successfully looked through, |*ctx->object| determines if we * actually found something. */ return (*data->object != NULL); } static void decoder_clean_pkey_construct_arg(void *construct_data) { struct decoder_pkey_data_st *data = construct_data; if (data != NULL) { sk_EVP_KEYMGMT_pop_free(data->keymgmts, EVP_KEYMGMT_free); OPENSSL_free(data->propq); OPENSSL_free(data->object_type); OPENSSL_free(data); } } struct collect_data_st { OSSL_LIB_CTX *libctx; OSSL_DECODER_CTX *ctx; const char *keytype; /* the keytype requested, if any */ int keytype_id; /* if keytype_resolved is set, keymgmt name_id; else 0 */ int sm2_id; /* if keytype_resolved is set and EC, SM2 name_id; else 0 */ int total; /* number of matching results */ char error_occurred; char keytype_resolved; STACK_OF(EVP_KEYMGMT) *keymgmts; }; static void collect_decoder_keymgmt(EVP_KEYMGMT *keymgmt, OSSL_DECODER *decoder, void *provctx, struct collect_data_st *data) { void *decoderctx = NULL; OSSL_DECODER_INSTANCE *di = NULL; /* * We already checked the EVP_KEYMGMT is applicable in check_keymgmt so we * don't check it again here. */ if (keymgmt->name_id != decoder->base.id) /* Mismatch is not an error, continue. */ return; if ((decoderctx = decoder->newctx(provctx)) == NULL) { data->error_occurred = 1; return; } if ((di = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) { decoder->freectx(decoderctx); data->error_occurred = 1; return; } OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Checking out decoder %p:\n" " %s with %s\n", (void *)data->ctx, (void *)decoder, OSSL_DECODER_get0_name(decoder), OSSL_DECODER_get0_properties(decoder)); } OSSL_TRACE_END(DECODER); if (!ossl_decoder_ctx_add_decoder_inst(data->ctx, di)) { ossl_decoder_instance_free(di); data->error_occurred = 1; return; } ++data->total; } static void collect_decoder(OSSL_DECODER *decoder, void *arg) { struct collect_data_st *data = arg; STACK_OF(EVP_KEYMGMT) *keymgmts = data->keymgmts; int i, end_i; EVP_KEYMGMT *keymgmt; const OSSL_PROVIDER *prov; void *provctx; if (data->error_occurred) return; prov = OSSL_DECODER_get0_provider(decoder); provctx = OSSL_PROVIDER_get0_provider_ctx(prov); /* * Either the caller didn't give us a selection, or if they did, the decoder * must tell us if it supports that selection to be accepted. If the decoder * doesn't have |does_selection|, it's seen as taking anything. */ if (decoder->does_selection != NULL && !decoder->does_selection(provctx, data->ctx->selection)) return; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Checking out decoder %p:\n" " %s with %s\n", (void *)data->ctx, (void *)decoder, OSSL_DECODER_get0_name(decoder), OSSL_DECODER_get0_properties(decoder)); } OSSL_TRACE_END(DECODER); end_i = sk_EVP_KEYMGMT_num(keymgmts); for (i = 0; i < end_i; ++i) { keymgmt = sk_EVP_KEYMGMT_value(keymgmts, i); collect_decoder_keymgmt(keymgmt, decoder, provctx, data); if (data->error_occurred) return; } } /* * Is this EVP_KEYMGMT applicable given the key type given in the call to * ossl_decoder_ctx_setup_for_pkey (if any)? */ static int check_keymgmt(EVP_KEYMGMT *keymgmt, struct collect_data_st *data) { /* If no keytype was specified, everything matches. */ if (data->keytype == NULL) return 1; if (!data->keytype_resolved) { /* We haven't cached the IDs from the keytype string yet. */ OSSL_NAMEMAP *namemap = ossl_namemap_stored(data->libctx); data->keytype_id = ossl_namemap_name2num(namemap, data->keytype); /* * If keytype is a value ambiguously used for both EC and SM2, * collect the ID for SM2 as well. */ if (data->keytype_id != 0 && (strcmp(data->keytype, "id-ecPublicKey") == 0 || strcmp(data->keytype, "1.2.840.10045.2.1") == 0)) data->sm2_id = ossl_namemap_name2num(namemap, "SM2"); /* * If keytype_id is zero the name was not found, but we still * set keytype_resolved to avoid trying all this again. */ data->keytype_resolved = 1; } /* Specified keytype could not be resolved, so nothing matches. */ if (data->keytype_id == 0) return 0; /* Does not match the keytype specified, so skip. */ if (keymgmt->name_id != data->keytype_id && keymgmt->name_id != data->sm2_id) return 0; return 1; } static void collect_keymgmt(EVP_KEYMGMT *keymgmt, void *arg) { struct collect_data_st *data = arg; if (!check_keymgmt(keymgmt, data)) return; /* * We have to ref EVP_KEYMGMT here because in the success case, * data->keymgmts is referenced by the constructor we register in the * OSSL_DECODER_CTX. The registered cleanup function * (decoder_clean_pkey_construct_arg) unrefs every element of the stack and * frees it. */ if (!EVP_KEYMGMT_up_ref(keymgmt)) return; if (sk_EVP_KEYMGMT_push(data->keymgmts, keymgmt) <= 0) { EVP_KEYMGMT_free(keymgmt); data->error_occurred = 1; } } /* * This function does the actual binding of decoders to the OSSL_DECODER_CTX. It * searches for decoders matching 'keytype', which is a string like "RSA", "DH", * etc. If 'keytype' is NULL, decoders for all keytypes are bound. */ static int ossl_decoder_ctx_setup_for_pkey(OSSL_DECODER_CTX *ctx, const char *keytype, OSSL_LIB_CTX *libctx, const char *propquery) { int ok = 0; struct decoder_pkey_data_st *process_data = NULL; struct collect_data_st collect_data = { NULL }; STACK_OF(EVP_KEYMGMT) *keymgmts = NULL; OSSL_TRACE_BEGIN(DECODER) { const char *input_type = ctx->start_input_type; const char *input_structure = ctx->input_structure; BIO_printf(trc_out, "(ctx %p) Looking for decoders producing %s%s%s%s%s%s\n", (void *)ctx, keytype != NULL ? keytype : "", keytype != NULL ? " keys" : "keys of any type", input_type != NULL ? " from " : "", input_type != NULL ? input_type : "", input_structure != NULL ? " with " : "", input_structure != NULL ? input_structure : ""); } OSSL_TRACE_END(DECODER); /* Allocate data. */ if ((process_data = OPENSSL_zalloc(sizeof(*process_data))) == NULL) goto err; if ((propquery != NULL && (process_data->propq = OPENSSL_strdup(propquery)) == NULL)) goto err; /* Allocate our list of EVP_KEYMGMTs. */ keymgmts = sk_EVP_KEYMGMT_new_null(); if (keymgmts == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB); goto err; } process_data->object = NULL; process_data->libctx = libctx; process_data->selection = ctx->selection; process_data->keymgmts = keymgmts; /* * Enumerate all keymgmts into a stack. * * We could nest EVP_KEYMGMT_do_all_provided inside * OSSL_DECODER_do_all_provided or vice versa but these functions become * bottlenecks if called repeatedly, which is why we collect the * EVP_KEYMGMTs into a stack here and call both functions only once. * * We resolve the keytype string to a name ID so we don't have to resolve it * multiple times, avoiding repeated calls to EVP_KEYMGMT_is_a, which is a * performance bottleneck. However, we do this lazily on the first call to * collect_keymgmt made by EVP_KEYMGMT_do_all_provided, rather than do it * upfront, as this ensures that the names for all loaded providers have * been registered by the time we try to resolve the keytype string. */ collect_data.ctx = ctx; collect_data.libctx = libctx; collect_data.keymgmts = keymgmts; collect_data.keytype = keytype; EVP_KEYMGMT_do_all_provided(libctx, collect_keymgmt, &collect_data); if (collect_data.error_occurred) goto err; /* Enumerate all matching decoders. */ OSSL_DECODER_do_all_provided(libctx, collect_decoder, &collect_data); if (collect_data.error_occurred) goto err; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Got %d decoders producing keys\n", (void *)ctx, collect_data.total); } OSSL_TRACE_END(DECODER); /* * Finish initializing the decoder context. If one or more decoders matched * above then the number of decoders attached to the OSSL_DECODER_CTX will * be nonzero. Else nothing was found and we do nothing. */ if (OSSL_DECODER_CTX_get_num_decoders(ctx) != 0) { if (!OSSL_DECODER_CTX_set_construct(ctx, decoder_construct_pkey) || !OSSL_DECODER_CTX_set_construct_data(ctx, process_data) || !OSSL_DECODER_CTX_set_cleanup(ctx, decoder_clean_pkey_construct_arg)) goto err; process_data = NULL; /* Avoid it being freed */ } ok = 1; err: decoder_clean_pkey_construct_arg(process_data); return ok; } /* Only const here because deep_copy requires it */ static EVP_KEYMGMT *keymgmt_dup(const EVP_KEYMGMT *keymgmt) { if (!EVP_KEYMGMT_up_ref((EVP_KEYMGMT *)keymgmt)) return NULL; return (EVP_KEYMGMT *)keymgmt; } /* * Duplicates a template OSSL_DECODER_CTX that has been setup for an EVP_PKEY * operation and sets up the duplicate for a new operation. * It does not duplicate the pwdata on the assumption that this does not form * part of the template. That is set up later. */ static OSSL_DECODER_CTX * ossl_decoder_ctx_for_pkey_dup(OSSL_DECODER_CTX *src, EVP_PKEY **pkey, const char *input_type, const char *input_structure) { OSSL_DECODER_CTX *dest; struct decoder_pkey_data_st *process_data_src, *process_data_dest = NULL; if (src == NULL) return NULL; if ((dest = OSSL_DECODER_CTX_new()) == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB); return NULL; } if (!OSSL_DECODER_CTX_set_input_type(dest, input_type) || !OSSL_DECODER_CTX_set_input_structure(dest, input_structure)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB); goto err; } dest->selection = src->selection; if (src->decoder_insts != NULL) { dest->decoder_insts = sk_OSSL_DECODER_INSTANCE_deep_copy(src->decoder_insts, ossl_decoder_instance_dup, ossl_decoder_instance_free); if (dest->decoder_insts == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB); goto err; } } if (!OSSL_DECODER_CTX_set_construct(dest, OSSL_DECODER_CTX_get_construct(src))) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB); goto err; } process_data_src = OSSL_DECODER_CTX_get_construct_data(src); if (process_data_src != NULL) { process_data_dest = OPENSSL_zalloc(sizeof(*process_data_dest)); if (process_data_dest == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB); goto err; } if (process_data_src->propq != NULL) { process_data_dest->propq = OPENSSL_strdup(process_data_src->propq); if (process_data_dest->propq == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB); goto err; } } if (process_data_src->keymgmts != NULL) { process_data_dest->keymgmts = sk_EVP_KEYMGMT_deep_copy(process_data_src->keymgmts, keymgmt_dup, EVP_KEYMGMT_free); if (process_data_dest->keymgmts == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_EVP_LIB); goto err; } } process_data_dest->object = (void **)pkey; process_data_dest->libctx = process_data_src->libctx; process_data_dest->selection = process_data_src->selection; if (!OSSL_DECODER_CTX_set_construct_data(dest, process_data_dest)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB); goto err; } process_data_dest = NULL; } if (!OSSL_DECODER_CTX_set_cleanup(dest, OSSL_DECODER_CTX_get_cleanup(src))) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB); goto err; } return dest; err: if (process_data_dest != NULL) { OPENSSL_free(process_data_dest->propq); sk_EVP_KEYMGMT_pop_free(process_data_dest->keymgmts, EVP_KEYMGMT_free); OPENSSL_free(process_data_dest); } OSSL_DECODER_CTX_free(dest); return NULL; } typedef struct { char *input_type; char *input_structure; char *keytype; int selection; char *propquery; OSSL_DECODER_CTX *template; } DECODER_CACHE_ENTRY; DEFINE_LHASH_OF_EX(DECODER_CACHE_ENTRY); typedef struct { CRYPTO_RWLOCK *lock; LHASH_OF(DECODER_CACHE_ENTRY) *hashtable; } DECODER_CACHE; static void decoder_cache_entry_free(DECODER_CACHE_ENTRY *entry) { if (entry == NULL) return; OPENSSL_free(entry->input_type); OPENSSL_free(entry->input_structure); OPENSSL_free(entry->keytype); OPENSSL_free(entry->propquery); OSSL_DECODER_CTX_free(entry->template); OPENSSL_free(entry); } static unsigned long decoder_cache_entry_hash(const DECODER_CACHE_ENTRY *cache) { unsigned long hash = 17; hash = (hash * 23) + (cache->propquery == NULL ? 0 : ossl_lh_strcasehash(cache->propquery)); hash = (hash * 23) + (cache->input_structure == NULL ? 0 : ossl_lh_strcasehash(cache->input_structure)); hash = (hash * 23) + (cache->input_type == NULL ? 0 : ossl_lh_strcasehash(cache->input_type)); hash = (hash * 23) + (cache->keytype == NULL ? 0 : ossl_lh_strcasehash(cache->keytype)); hash ^= cache->selection; return hash; } static ossl_inline int nullstrcmp(const char *a, const char *b, int casecmp) { if (a == NULL || b == NULL) { if (a == NULL) { if (b == NULL) return 0; else return 1; } else { return -1; } } else { if (casecmp) return OPENSSL_strcasecmp(a, b); else return strcmp(a, b); } } static int decoder_cache_entry_cmp(const DECODER_CACHE_ENTRY *a, const DECODER_CACHE_ENTRY *b) { int cmp; if (a->selection != b->selection) return (a->selection < b->selection) ? -1 : 1; cmp = nullstrcmp(a->keytype, b->keytype, 1); if (cmp != 0) return cmp; cmp = nullstrcmp(a->input_type, b->input_type, 1); if (cmp != 0) return cmp; cmp = nullstrcmp(a->input_structure, b->input_structure, 1); if (cmp != 0) return cmp; cmp = nullstrcmp(a->propquery, b->propquery, 0); return cmp; } void *ossl_decoder_cache_new(OSSL_LIB_CTX *ctx) { DECODER_CACHE *cache = OPENSSL_malloc(sizeof(*cache)); if (cache == NULL) return NULL; cache->lock = CRYPTO_THREAD_lock_new(); if (cache->lock == NULL) { OPENSSL_free(cache); return NULL; } cache->hashtable = lh_DECODER_CACHE_ENTRY_new(decoder_cache_entry_hash, decoder_cache_entry_cmp); if (cache->hashtable == NULL) { CRYPTO_THREAD_lock_free(cache->lock); OPENSSL_free(cache); return NULL; } return cache; } void ossl_decoder_cache_free(void *vcache) { DECODER_CACHE *cache = (DECODER_CACHE *)vcache; lh_DECODER_CACHE_ENTRY_doall(cache->hashtable, decoder_cache_entry_free); lh_DECODER_CACHE_ENTRY_free(cache->hashtable); CRYPTO_THREAD_lock_free(cache->lock); OPENSSL_free(cache); } /* * Called whenever a provider gets activated/deactivated. In that case the * decoders that are available might change so we flush our cache. */ int ossl_decoder_cache_flush(OSSL_LIB_CTX *libctx) { DECODER_CACHE *cache = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DECODER_CACHE_INDEX); if (cache == NULL) return 0; if (!CRYPTO_THREAD_write_lock(cache->lock)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB); return 0; } lh_DECODER_CACHE_ENTRY_doall(cache->hashtable, decoder_cache_entry_free); lh_DECODER_CACHE_ENTRY_flush(cache->hashtable); CRYPTO_THREAD_unlock(cache->lock); return 1; } OSSL_DECODER_CTX * OSSL_DECODER_CTX_new_for_pkey(EVP_PKEY **pkey, const char *input_type, const char *input_structure, const char *keytype, int selection, OSSL_LIB_CTX *libctx, const char *propquery) { OSSL_DECODER_CTX *ctx = NULL; OSSL_PARAM decoder_params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; DECODER_CACHE *cache = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DECODER_CACHE_INDEX); DECODER_CACHE_ENTRY cacheent, *res, *newcache = NULL; if (cache == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB); return NULL; } if (propquery != NULL) decoder_params[0] = OSSL_PARAM_construct_utf8_string(OSSL_DECODER_PARAM_PROPERTIES, (char *)propquery, 0); /* It is safe to cast away the const here */ cacheent.input_type = (char *)input_type; cacheent.input_structure = (char *)input_structure; cacheent.keytype = (char *)keytype; cacheent.selection = selection; cacheent.propquery = (char *)propquery; if (!CRYPTO_THREAD_read_lock(cache->lock)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB); return NULL; } /* First see if we have a template OSSL_DECODER_CTX */ res = lh_DECODER_CACHE_ENTRY_retrieve(cache->hashtable, &cacheent); if (res == NULL) { /* * There is no template so we will have to construct one. This will be * time consuming so release the lock and we will later upgrade it to a * write lock. */ CRYPTO_THREAD_unlock(cache->lock); if ((ctx = OSSL_DECODER_CTX_new()) == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB); return NULL; } OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Looking for %s decoders with selection %d\n", (void *)ctx, keytype, selection); BIO_printf(trc_out, " input type: %s, input structure: %s\n", input_type, input_structure); } OSSL_TRACE_END(DECODER); if (OSSL_DECODER_CTX_set_input_type(ctx, input_type) && OSSL_DECODER_CTX_set_input_structure(ctx, input_structure) && OSSL_DECODER_CTX_set_selection(ctx, selection) && ossl_decoder_ctx_setup_for_pkey(ctx, keytype, libctx, propquery) && OSSL_DECODER_CTX_add_extra(ctx, libctx, propquery) && (propquery == NULL || OSSL_DECODER_CTX_set_params(ctx, decoder_params))) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Got %d decoders\n", (void *)ctx, OSSL_DECODER_CTX_get_num_decoders(ctx)); } OSSL_TRACE_END(DECODER); } else { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB); OSSL_DECODER_CTX_free(ctx); return NULL; } newcache = OPENSSL_zalloc(sizeof(*newcache)); if (newcache == NULL) { OSSL_DECODER_CTX_free(ctx); return NULL; } if (input_type != NULL) { newcache->input_type = OPENSSL_strdup(input_type); if (newcache->input_type == NULL) goto err; } if (input_structure != NULL) { newcache->input_structure = OPENSSL_strdup(input_structure); if (newcache->input_structure == NULL) goto err; } if (keytype != NULL) { newcache->keytype = OPENSSL_strdup(keytype); if (newcache->keytype == NULL) goto err; } if (propquery != NULL) { newcache->propquery = OPENSSL_strdup(propquery); if (newcache->propquery == NULL) goto err; } newcache->selection = selection; newcache->template = ctx; if (!CRYPTO_THREAD_write_lock(cache->lock)) { ctx = NULL; ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB); goto err; } res = lh_DECODER_CACHE_ENTRY_retrieve(cache->hashtable, &cacheent); if (res == NULL) { (void)lh_DECODER_CACHE_ENTRY_insert(cache->hashtable, newcache); if (lh_DECODER_CACHE_ENTRY_error(cache->hashtable)) { ctx = NULL; ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB); goto err; } } else { /* * We raced with another thread to construct this and lost. Free * what we just created and use the entry from the hashtable instead */ decoder_cache_entry_free(newcache); ctx = res->template; } } else { ctx = res->template; } ctx = ossl_decoder_ctx_for_pkey_dup(ctx, pkey, input_type, input_structure); CRYPTO_THREAD_unlock(cache->lock); return ctx; err: decoder_cache_entry_free(newcache); OSSL_DECODER_CTX_free(ctx); return NULL; }
./openssl/crypto/encode_decode/encoder_lib.c
/* * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core_names.h> #include <openssl/bio.h> #include <openssl/encoder.h> #include <openssl/buffer.h> #include <openssl/params.h> #include <openssl/provider.h> #include <openssl/trace.h> #include "internal/bio.h" #include "internal/provider.h" #include "encoder_local.h" struct encoder_process_data_st { OSSL_ENCODER_CTX *ctx; /* Current BIO */ BIO *bio; /* Index of the current encoder instance to be processed */ int current_encoder_inst_index; /* Processing data passed down through recursion */ int level; /* Recursion level */ OSSL_ENCODER_INSTANCE *next_encoder_inst; int count_output_structure; /* Processing data passed up through recursion */ OSSL_ENCODER_INSTANCE *prev_encoder_inst; unsigned char *running_output; size_t running_output_length; /* Data type = the name of the first succeeding encoder implementation */ const char *data_type; }; static int encoder_process(struct encoder_process_data_st *data); int OSSL_ENCODER_to_bio(OSSL_ENCODER_CTX *ctx, BIO *out) { struct encoder_process_data_st data; memset(&data, 0, sizeof(data)); data.ctx = ctx; data.bio = out; data.current_encoder_inst_index = OSSL_ENCODER_CTX_get_num_encoders(ctx); if (data.current_encoder_inst_index == 0) { ERR_raise_data(ERR_LIB_OSSL_ENCODER, OSSL_ENCODER_R_ENCODER_NOT_FOUND, "No encoders were found. For standard encoders you need " "at least one of the default or base providers " "available. Did you forget to load them?"); return 0; } return encoder_process(&data) > 0; } #ifndef OPENSSL_NO_STDIO static BIO *bio_from_file(FILE *fp) { BIO *b; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_BUF_LIB); return NULL; } BIO_set_fp(b, fp, BIO_NOCLOSE); return b; } int OSSL_ENCODER_to_fp(OSSL_ENCODER_CTX *ctx, FILE *fp) { BIO *b = bio_from_file(fp); int ret = 0; if (b != NULL) ret = OSSL_ENCODER_to_bio(ctx, b); BIO_free(b); return ret; } #endif int OSSL_ENCODER_to_data(OSSL_ENCODER_CTX *ctx, unsigned char **pdata, size_t *pdata_len) { BIO *out; BUF_MEM *buf = NULL; int ret = 0; if (pdata_len == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } out = BIO_new(BIO_s_mem()); if (out != NULL && OSSL_ENCODER_to_bio(ctx, out) && BIO_get_mem_ptr(out, &buf) > 0) { ret = 1; /* Hope for the best. A too small buffer will clear this */ if (pdata != NULL && *pdata != NULL) { if (*pdata_len < buf->length) /* * It's tempting to do |*pdata_len = (size_t)buf->length| * However, it's believed to be confusing more than helpful, * so we don't. */ ret = 0; else *pdata_len -= buf->length; } else { /* The buffer with the right size is already allocated for us */ *pdata_len = (size_t)buf->length; } if (ret) { if (pdata != NULL) { if (*pdata != NULL) { memcpy(*pdata, buf->data, buf->length); *pdata += buf->length; } else { /* In this case, we steal the data from BIO_s_mem() */ *pdata = (unsigned char *)buf->data; buf->data = NULL; } } } } BIO_free(out); return ret; } int OSSL_ENCODER_CTX_set_selection(OSSL_ENCODER_CTX *ctx, int selection) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (!ossl_assert(selection != 0)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } ctx->selection = selection; return 1; } int OSSL_ENCODER_CTX_set_output_type(OSSL_ENCODER_CTX *ctx, const char *output_type) { if (!ossl_assert(ctx != NULL) || !ossl_assert(output_type != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->output_type = output_type; return 1; } int OSSL_ENCODER_CTX_set_output_structure(OSSL_ENCODER_CTX *ctx, const char *output_structure) { if (!ossl_assert(ctx != NULL) || !ossl_assert(output_structure != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->output_structure = output_structure; return 1; } static OSSL_ENCODER_INSTANCE *ossl_encoder_instance_new(OSSL_ENCODER *encoder, void *encoderctx) { OSSL_ENCODER_INSTANCE *encoder_inst = NULL; const OSSL_PROVIDER *prov; OSSL_LIB_CTX *libctx; const OSSL_PROPERTY_LIST *props; const OSSL_PROPERTY_DEFINITION *prop; if (!ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((encoder_inst = OPENSSL_zalloc(sizeof(*encoder_inst))) == NULL) return 0; if (!OSSL_ENCODER_up_ref(encoder)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_INTERNAL_ERROR); goto err; } prov = OSSL_ENCODER_get0_provider(encoder); libctx = ossl_provider_libctx(prov); props = ossl_encoder_parsed_properties(encoder); if (props == NULL) { ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION, "there are no property definitions with encoder %s", OSSL_ENCODER_get0_name(encoder)); goto err; } /* The "output" property is mandatory */ prop = ossl_property_find_property(props, libctx, "output"); encoder_inst->output_type = ossl_property_get_string_value(libctx, prop); if (encoder_inst->output_type == NULL) { ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION, "the mandatory 'output' property is missing " "for encoder %s (properties: %s)", OSSL_ENCODER_get0_name(encoder), OSSL_ENCODER_get0_properties(encoder)); goto err; } /* The "structure" property is optional */ prop = ossl_property_find_property(props, libctx, "structure"); if (prop != NULL) encoder_inst->output_structure = ossl_property_get_string_value(libctx, prop); encoder_inst->encoder = encoder; encoder_inst->encoderctx = encoderctx; return encoder_inst; err: ossl_encoder_instance_free(encoder_inst); return NULL; } void ossl_encoder_instance_free(OSSL_ENCODER_INSTANCE *encoder_inst) { if (encoder_inst != NULL) { if (encoder_inst->encoder != NULL) encoder_inst->encoder->freectx(encoder_inst->encoderctx); encoder_inst->encoderctx = NULL; OSSL_ENCODER_free(encoder_inst->encoder); encoder_inst->encoder = NULL; OPENSSL_free(encoder_inst); } } static int ossl_encoder_ctx_add_encoder_inst(OSSL_ENCODER_CTX *ctx, OSSL_ENCODER_INSTANCE *ei) { int ok; if (ctx->encoder_insts == NULL && (ctx->encoder_insts = sk_OSSL_ENCODER_INSTANCE_new_null()) == NULL) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_CRYPTO_LIB); return 0; } ok = (sk_OSSL_ENCODER_INSTANCE_push(ctx->encoder_insts, ei) > 0); if (ok) { OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "(ctx %p) Added encoder instance %p (encoder %p):\n" " %s with %s\n", (void *)ctx, (void *)ei, (void *)ei->encoder, OSSL_ENCODER_get0_name(ei->encoder), OSSL_ENCODER_get0_properties(ei->encoder)); } OSSL_TRACE_END(ENCODER); } return ok; } int OSSL_ENCODER_CTX_add_encoder(OSSL_ENCODER_CTX *ctx, OSSL_ENCODER *encoder) { OSSL_ENCODER_INSTANCE *encoder_inst = NULL; const OSSL_PROVIDER *prov = NULL; void *encoderctx = NULL; void *provctx = NULL; if (!ossl_assert(ctx != NULL) || !ossl_assert(encoder != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } prov = OSSL_ENCODER_get0_provider(encoder); provctx = OSSL_PROVIDER_get0_provider_ctx(prov); if ((encoderctx = encoder->newctx(provctx)) == NULL || (encoder_inst = ossl_encoder_instance_new(encoder, encoderctx)) == NULL) goto err; /* Avoid double free of encoderctx on further errors */ encoderctx = NULL; if (!ossl_encoder_ctx_add_encoder_inst(ctx, encoder_inst)) goto err; return 1; err: ossl_encoder_instance_free(encoder_inst); if (encoderctx != NULL) encoder->freectx(encoderctx); return 0; } int OSSL_ENCODER_CTX_add_extra(OSSL_ENCODER_CTX *ctx, OSSL_LIB_CTX *libctx, const char *propq) { return 1; } int OSSL_ENCODER_CTX_get_num_encoders(OSSL_ENCODER_CTX *ctx) { if (ctx == NULL || ctx->encoder_insts == NULL) return 0; return sk_OSSL_ENCODER_INSTANCE_num(ctx->encoder_insts); } int OSSL_ENCODER_CTX_set_construct(OSSL_ENCODER_CTX *ctx, OSSL_ENCODER_CONSTRUCT *construct) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->construct = construct; return 1; } int OSSL_ENCODER_CTX_set_construct_data(OSSL_ENCODER_CTX *ctx, void *construct_data) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->construct_data = construct_data; return 1; } int OSSL_ENCODER_CTX_set_cleanup(OSSL_ENCODER_CTX *ctx, OSSL_ENCODER_CLEANUP *cleanup) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->cleanup = cleanup; return 1; } OSSL_ENCODER * OSSL_ENCODER_INSTANCE_get_encoder(OSSL_ENCODER_INSTANCE *encoder_inst) { if (encoder_inst == NULL) return NULL; return encoder_inst->encoder; } void * OSSL_ENCODER_INSTANCE_get_encoder_ctx(OSSL_ENCODER_INSTANCE *encoder_inst) { if (encoder_inst == NULL) return NULL; return encoder_inst->encoderctx; } const char * OSSL_ENCODER_INSTANCE_get_output_type(OSSL_ENCODER_INSTANCE *encoder_inst) { if (encoder_inst == NULL) return NULL; return encoder_inst->output_type; } const char * OSSL_ENCODER_INSTANCE_get_output_structure(OSSL_ENCODER_INSTANCE *encoder_inst) { if (encoder_inst == NULL) return NULL; return encoder_inst->output_structure; } static int encoder_process(struct encoder_process_data_st *data) { OSSL_ENCODER_INSTANCE *current_encoder_inst = NULL; OSSL_ENCODER *current_encoder = NULL; OSSL_ENCODER_CTX *current_encoder_ctx = NULL; BIO *allocated_out = NULL; const void *original_data = NULL; OSSL_PARAM abstract[10]; const OSSL_PARAM *current_abstract = NULL; int i; int ok = -1; /* -1 signifies that the lookup loop gave nothing */ int top = 0; if (data->next_encoder_inst == NULL) { /* First iteration, where we prepare for what is to come */ data->count_output_structure = data->ctx->output_structure == NULL ? -1 : 0; top = 1; } for (i = data->current_encoder_inst_index; i-- > 0;) { OSSL_ENCODER *next_encoder = NULL; const char *current_output_type; const char *current_output_structure; struct encoder_process_data_st new_data; if (!top) next_encoder = OSSL_ENCODER_INSTANCE_get_encoder(data->next_encoder_inst); current_encoder_inst = sk_OSSL_ENCODER_INSTANCE_value(data->ctx->encoder_insts, i); current_encoder = OSSL_ENCODER_INSTANCE_get_encoder(current_encoder_inst); current_encoder_ctx = OSSL_ENCODER_INSTANCE_get_encoder_ctx(current_encoder_inst); current_output_type = OSSL_ENCODER_INSTANCE_get_output_type(current_encoder_inst); current_output_structure = OSSL_ENCODER_INSTANCE_get_output_structure(current_encoder_inst); memset(&new_data, 0, sizeof(new_data)); new_data.ctx = data->ctx; new_data.current_encoder_inst_index = i; new_data.next_encoder_inst = current_encoder_inst; new_data.count_output_structure = data->count_output_structure; new_data.level = data->level + 1; OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] (ctx %p) Considering encoder instance %p (encoder %p)\n", data->level, (void *)data->ctx, (void *)current_encoder_inst, (void *)current_encoder); } OSSL_TRACE_END(ENCODER); /* * If this is the top call, we check if the output type of the current * encoder matches the desired output type. * If this isn't the top call, i.e. this is deeper in the recursion, * we instead check if the output type of the current encoder matches * the name of the next encoder (the one found by the parent call). */ if (top) { if (data->ctx->output_type != NULL && OPENSSL_strcasecmp(current_output_type, data->ctx->output_type) != 0) { OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] Skipping because current encoder output type (%s) != desired output type (%s)\n", data->level, current_output_type, data->ctx->output_type); } OSSL_TRACE_END(ENCODER); continue; } } else { if (!OSSL_ENCODER_is_a(next_encoder, current_output_type)) { OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] Skipping because current encoder output type (%s) != name of encoder %p\n", data->level, current_output_type, (void *)next_encoder); } OSSL_TRACE_END(ENCODER); continue; } } /* * If the caller and the current encoder specify an output structure, * Check if they match. If they do, count the match, otherwise skip * the current encoder. */ if (data->ctx->output_structure != NULL && current_output_structure != NULL) { if (OPENSSL_strcasecmp(data->ctx->output_structure, current_output_structure) != 0) { OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] Skipping because current encoder output structure (%s) != ctx output structure (%s)\n", data->level, current_output_structure, data->ctx->output_structure); } OSSL_TRACE_END(ENCODER); continue; } data->count_output_structure++; } /* * Recurse to process the encoder implementations before the current * one. */ ok = encoder_process(&new_data); data->prev_encoder_inst = new_data.prev_encoder_inst; data->running_output = new_data.running_output; data->running_output_length = new_data.running_output_length; /* * ok == -1 means that the recursion call above gave no further * encoders, and that the one we're currently at should * be tried. * ok == 0 means that something failed in the recursion call * above, making the result unsuitable for a chain. * In this case, we simply continue to try finding a * suitable encoder at this recursion level. * ok == 1 means that the recursion call was successful, and we * try to use the result at this recursion level. */ if (ok != 0) break; OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] Skipping because recursion level %d failed\n", data->level, new_data.level); } OSSL_TRACE_END(ENCODER); } /* * If |i < 0|, we didn't find any useful encoder in this recursion, so * we do the rest of the process only if |i >= 0|. */ if (i < 0) { ok = -1; OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] (ctx %p) No suitable encoder found\n", data->level, (void *)data->ctx); } OSSL_TRACE_END(ENCODER); } else { /* Preparations */ switch (ok) { case 0: break; case -1: /* * We have reached the beginning of the encoder instance sequence, * so we prepare the object to be encoded. */ /* * |data->count_output_structure| is one of these values: * * -1 There is no desired output structure * 0 There is a desired output structure, and it wasn't * matched by any of the encoder instances that were * considered * >0 There is a desired output structure, and at least one * of the encoder instances matched it */ if (data->count_output_structure == 0) return 0; original_data = data->ctx->construct(current_encoder_inst, data->ctx->construct_data); /* Also set the data type, using the encoder implementation name */ data->data_type = OSSL_ENCODER_get0_name(current_encoder); /* Assume that the constructor recorded an error */ if (original_data != NULL) ok = 1; else ok = 0; break; case 1: if (!ossl_assert(data->running_output != NULL)) { ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_INTERNAL_ERROR); ok = 0; break; } { /* * Create an object abstraction from the latest output, which * was stolen from the previous round. */ OSSL_PARAM *abstract_p = abstract; const char *prev_output_structure = OSSL_ENCODER_INSTANCE_get_output_structure(data->prev_encoder_inst); *abstract_p++ = OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE, (char *)data->data_type, 0); if (prev_output_structure != NULL) *abstract_p++ = OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_STRUCTURE, (char *)prev_output_structure, 0); *abstract_p++ = OSSL_PARAM_construct_octet_string(OSSL_OBJECT_PARAM_DATA, data->running_output, data->running_output_length); *abstract_p = OSSL_PARAM_construct_end(); current_abstract = abstract; } break; } /* Calling the encoder implementation */ if (ok) { OSSL_CORE_BIO *cbio = NULL; BIO *current_out = NULL; /* * If we're at the last encoder instance to use, we're setting up * final output. Otherwise, set up an intermediary memory output. */ if (top) current_out = data->bio; else if ((current_out = allocated_out = BIO_new(BIO_s_mem())) == NULL) ok = 0; /* Assume BIO_new() recorded an error */ if (ok) ok = (cbio = ossl_core_bio_new_from_bio(current_out)) != NULL; if (ok) { ok = current_encoder->encode(current_encoder_ctx, cbio, original_data, current_abstract, data->ctx->selection, ossl_pw_passphrase_callback_enc, &data->ctx->pwdata); OSSL_TRACE_BEGIN(ENCODER) { BIO_printf(trc_out, "[%d] (ctx %p) Running encoder instance %p => %d\n", data->level, (void *)data->ctx, (void *)current_encoder_inst, ok); } OSSL_TRACE_END(ENCODER); } ossl_core_bio_free(cbio); data->prev_encoder_inst = current_encoder_inst; } } /* Cleanup and collecting the result */ OPENSSL_free(data->running_output); data->running_output = NULL; /* * Steal the output from the BIO_s_mem, if we did allocate one. * That'll be the data for an object abstraction in the next round. */ if (allocated_out != NULL) { BUF_MEM *buf; BIO_get_mem_ptr(allocated_out, &buf); data->running_output = (unsigned char *)buf->data; data->running_output_length = buf->length; memset(buf, 0, sizeof(*buf)); } BIO_free(allocated_out); if (original_data != NULL) data->ctx->cleanup(data->ctx->construct_data); return ok; }
./openssl/crypto/rc4/rc4_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 */ /* * RC4 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc4.h> #include "rc4_local.h" #include <openssl/opensslv.h> const char *RC4_options(void) { if (sizeof(RC4_INT) == 1) return "rc4(char)"; else return "rc4(int)"; } /*- * RC4 as implemented from a posting from * Newsgroups: sci.crypt * Subject: RC4 Algorithm revealed. * Message-ID: <sternCvKL4B.Hyy@netcom.com> * Date: Wed, 14 Sep 1994 06:35:31 GMT */ void RC4_set_key(RC4_KEY *key, int len, const unsigned char *data) { register RC4_INT tmp; register int id1, id2; register RC4_INT *d; unsigned int i; d = &(key->data[0]); key->x = 0; key->y = 0; id1 = id2 = 0; #define SK_LOOP(d,n) { \ tmp=d[(n)]; \ id2 = (data[id1] + tmp + id2) & 0xff; \ if (++id1 == len) id1=0; \ d[(n)]=d[id2]; \ d[id2]=tmp; } for (i = 0; i < 256; i++) d[i] = i; for (i = 0; i < 256; i += 4) { SK_LOOP(d, i + 0); SK_LOOP(d, i + 1); SK_LOOP(d, i + 2); SK_LOOP(d, i + 3); } }
./openssl/crypto/rc4/rc4_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 */ /* * RC4 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc4.h> #include "rc4_local.h" /*- * RC4 as implemented from a posting from * Newsgroups: sci.crypt * Subject: RC4 Algorithm revealed. * Message-ID: <sternCvKL4B.Hyy@netcom.com> * Date: Wed, 14 Sep 1994 06:35:31 GMT */ void RC4(RC4_KEY *key, size_t len, const unsigned char *indata, unsigned char *outdata) { register RC4_INT *d; register RC4_INT x, y, tx, ty; size_t i; x = key->x; y = key->y; d = key->data; #define LOOP(in,out) \ x=((x+1)&0xff); \ tx=d[x]; \ y=(tx+y)&0xff; \ d[x]=ty=d[y]; \ d[y]=tx; \ (out) = d[(tx+ty)&0xff]^ (in); i = len >> 3; if (i) { for (;;) { LOOP(indata[0], outdata[0]); LOOP(indata[1], outdata[1]); LOOP(indata[2], outdata[2]); LOOP(indata[3], outdata[3]); LOOP(indata[4], outdata[4]); LOOP(indata[5], outdata[5]); LOOP(indata[6], outdata[6]); LOOP(indata[7], outdata[7]); indata += 8; outdata += 8; if (--i == 0) break; } } i = len & 0x07; if (i) { for (;;) { LOOP(indata[0], outdata[0]); if (--i == 0) break; LOOP(indata[1], outdata[1]); if (--i == 0) break; LOOP(indata[2], outdata[2]); if (--i == 0) break; LOOP(indata[3], outdata[3]); if (--i == 0) break; LOOP(indata[4], outdata[4]); if (--i == 0) break; LOOP(indata[5], outdata[5]); if (--i == 0) break; LOOP(indata[6], outdata[6]); if (--i == 0) break; } } key->x = x; key->y = y; }
./openssl/crypto/rc4/rc4_local.h
/* * Copyright 1998-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_RC4_LOCAL_H # define OSSL_CRYPTO_RC4_LOCAL_H # include <openssl/opensslconf.h> # include "internal/cryptlib.h" #endif
./openssl/crypto/x509/by_store.c
/* * Copyright 2018-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/store.h> #include "internal/cryptlib.h" #include "crypto/x509.h" #include "x509_local.h" /* Generic object loader, given expected type and criterion */ static int cache_objects(X509_LOOKUP *lctx, const char *uri, const OSSL_STORE_SEARCH *criterion, int depth, OSSL_LIB_CTX *libctx, const char *propq) { int ok = 0; OSSL_STORE_CTX *ctx = NULL; X509_STORE *xstore = X509_LOOKUP_get_store(lctx); if ((ctx = OSSL_STORE_open_ex(uri, libctx, propq, NULL, NULL, NULL, NULL, NULL)) == NULL) return 0; /* * We try to set the criterion, but don't care if it was valid or not. * For an OSSL_STORE, it merely serves as an optimization, the expectation * being that if the criterion couldn't be used, we will get *everything* * from the container that the URI represents rather than the subset that * the criterion indicates, so the biggest harm is that we cache more * objects certs and CRLs than we may expect, but that's ok. * * Specifically for OpenSSL's own file: scheme, the only workable * criterion is the BY_NAME one, which it can only apply on directories, * but it's possible that the URI is a single file rather than a directory, * and in that case, the BY_NAME criterion is pointless. * * We could very simply not apply any criterion at all here, and just let * the code that selects certs and CRLs from the cached objects do its job, * but it's a nice optimization when it can be applied (such as on an * actual directory with a thousand CA certs). */ if (criterion != NULL) OSSL_STORE_find(ctx, criterion); for (;;) { OSSL_STORE_INFO *info = OSSL_STORE_load(ctx); int infotype; /* NULL means error or "end of file". Either way, we break. */ if (info == NULL) break; infotype = OSSL_STORE_INFO_get_type(info); ok = 0; if (infotype == OSSL_STORE_INFO_NAME) { /* * This is an entry in the "directory" represented by the current * uri. if |depth| allows, dive into it. */ if (depth > 0) ok = cache_objects(lctx, OSSL_STORE_INFO_get0_NAME(info), criterion, depth - 1, libctx, propq); } else { /* * We know that X509_STORE_add_{cert|crl} increments the object's * refcount, so we can safely use OSSL_STORE_INFO_get0_{cert,crl} * to get them. */ switch (infotype) { case OSSL_STORE_INFO_CERT: ok = X509_STORE_add_cert(xstore, OSSL_STORE_INFO_get0_CERT(info)); break; case OSSL_STORE_INFO_CRL: ok = X509_STORE_add_crl(xstore, OSSL_STORE_INFO_get0_CRL(info)); break; } } OSSL_STORE_INFO_free(info); if (!ok) break; } OSSL_STORE_close(ctx); return ok; } /* Because OPENSSL_free is a macro and for C type match */ static void free_uri(OPENSSL_STRING data) { OPENSSL_free(data); } static void by_store_free(X509_LOOKUP *ctx) { STACK_OF(OPENSSL_STRING) *uris = X509_LOOKUP_get_method_data(ctx); sk_OPENSSL_STRING_pop_free(uris, free_uri); } static int by_store_ctrl_ex(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, char **retp, OSSL_LIB_CTX *libctx, const char *propq) { switch (cmd) { case X509_L_ADD_STORE: /* If no URI is given, use the default cert dir as default URI */ if (argp == NULL) argp = ossl_safe_getenv(X509_get_default_cert_dir_env()); if (argp == NULL) argp = X509_get_default_cert_dir(); { STACK_OF(OPENSSL_STRING) *uris = X509_LOOKUP_get_method_data(ctx); char *data = OPENSSL_strdup(argp); if (data == NULL) { return 0; } if (uris == NULL) { uris = sk_OPENSSL_STRING_new_null(); X509_LOOKUP_set_method_data(ctx, uris); } return sk_OPENSSL_STRING_push(uris, data) > 0; } case X509_L_LOAD_STORE: /* This is a shortcut for quick loading of specific containers */ return cache_objects(ctx, argp, NULL, 0, libctx, propq); } return 0; } static int by_store_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, char **retp) { return by_store_ctrl_ex(ctx, cmd, argp, argl, retp, NULL, NULL); } static int by_store(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const OSSL_STORE_SEARCH *criterion, X509_OBJECT *ret, OSSL_LIB_CTX *libctx, const char *propq) { STACK_OF(OPENSSL_STRING) *uris = X509_LOOKUP_get_method_data(ctx); int i; int ok = 0; for (i = 0; i < sk_OPENSSL_STRING_num(uris); i++) { ok = cache_objects(ctx, sk_OPENSSL_STRING_value(uris, i), criterion, 1 /* depth */, libctx, propq); if (ok) break; } return ok; } static int by_store_subject_ex(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret, OSSL_LIB_CTX *libctx, const char *propq) { OSSL_STORE_SEARCH *criterion = OSSL_STORE_SEARCH_by_name((X509_NAME *)name); /* won't modify it */ int ok = by_store(ctx, type, criterion, ret, libctx, propq); STACK_OF(X509_OBJECT) *store_objects = X509_STORE_get0_objects(X509_LOOKUP_get_store(ctx)); X509_OBJECT *tmp = NULL; OSSL_STORE_SEARCH_free(criterion); if (ok) tmp = X509_OBJECT_retrieve_by_subject(store_objects, type, name); ok = 0; if (tmp != NULL) { /* * This could also be done like this: * * if (tmp != NULL) { * *ret = *tmp; * ok = 1; * } * * However, we want to exercise the documented API to the max, so * we do it the hard way. * * To be noted is that X509_OBJECT_set1_* increment the refcount, * but so does X509_STORE_CTX_get_by_subject upon return of this * function, so we must ensure the refcount is decremented * before we return, or we will get a refcount leak. We cannot do * this with X509_OBJECT_free(), though, as that will free a bit * too much. */ switch (type) { case X509_LU_X509: ok = X509_OBJECT_set1_X509(ret, tmp->data.x509); if (ok) X509_free(tmp->data.x509); break; case X509_LU_CRL: ok = X509_OBJECT_set1_X509_CRL(ret, tmp->data.crl); if (ok) X509_CRL_free(tmp->data.crl); break; case X509_LU_NONE: break; } } return ok; } static int by_store_subject(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret) { return by_store_subject_ex(ctx, type, name, ret, NULL, NULL); } /* * We lack the implementations for get_by_issuer_serial, get_by_fingerprint * and get_by_alias. There's simply not enough support in the X509_LOOKUP * or X509_STORE APIs. */ static X509_LOOKUP_METHOD x509_store_lookup = { "Load certs from STORE URIs", NULL, /* new_item */ by_store_free, /* free */ NULL, /* init */ NULL, /* shutdown */ by_store_ctrl, /* ctrl */ by_store_subject, /* get_by_subject */ NULL, /* get_by_issuer_serial */ NULL, /* get_by_fingerprint */ NULL, /* get_by_alias */ by_store_subject_ex, by_store_ctrl_ex }; X509_LOOKUP_METHOD *X509_LOOKUP_store(void) { return &x509_store_lookup; }
./openssl/crypto/x509/by_dir.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 */ #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/e_os.h" #include "internal/cryptlib.h" #include <stdio.h> #include <time.h> #include <errno.h> #include <sys/types.h> #ifndef OPENSSL_NO_POSIX_IO # include <sys/stat.h> #endif #include <openssl/x509.h> #include "crypto/x509.h" #include "x509_local.h" struct lookup_dir_hashes_st { unsigned long hash; int suffix; }; struct lookup_dir_entry_st { char *dir; int dir_type; STACK_OF(BY_DIR_HASH) *hashes; }; typedef struct lookup_dir_st { BUF_MEM *buffer; STACK_OF(BY_DIR_ENTRY) *dirs; CRYPTO_RWLOCK *lock; } BY_DIR; static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, char **retp); static int new_dir(X509_LOOKUP *lu); static void free_dir(X509_LOOKUP *lu); static int add_cert_dir(BY_DIR *ctx, const char *dir, int type); static int get_cert_by_subject(X509_LOOKUP *xl, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret); static int get_cert_by_subject_ex(X509_LOOKUP *xl, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret, OSSL_LIB_CTX *libctx, const char *propq); static X509_LOOKUP_METHOD x509_dir_lookup = { "Load certs from files in a directory", new_dir, /* new_item */ free_dir, /* free */ NULL, /* init */ NULL, /* shutdown */ dir_ctrl, /* ctrl */ get_cert_by_subject, /* get_by_subject */ NULL, /* get_by_issuer_serial */ NULL, /* get_by_fingerprint */ NULL, /* get_by_alias */ get_cert_by_subject_ex, /* get_by_subject_ex */ NULL, /* ctrl_ex */ }; X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void) { return &x509_dir_lookup; } static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, char **retp) { int ret = 0; BY_DIR *ld = (BY_DIR *)ctx->method_data; switch (cmd) { case X509_L_ADD_DIR: if (argl == X509_FILETYPE_DEFAULT) { const char *dir = ossl_safe_getenv(X509_get_default_cert_dir_env()); if (dir) ret = add_cert_dir(ld, dir, X509_FILETYPE_PEM); else ret = add_cert_dir(ld, X509_get_default_cert_dir(), X509_FILETYPE_PEM); if (!ret) { ERR_raise(ERR_LIB_X509, X509_R_LOADING_CERT_DIR); } } else ret = add_cert_dir(ld, argp, (int)argl); break; } return ret; } static int new_dir(X509_LOOKUP *lu) { BY_DIR *a = OPENSSL_malloc(sizeof(*a)); if (a == NULL) return 0; if ((a->buffer = BUF_MEM_new()) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_BN_LIB); goto err; } a->dirs = NULL; a->lock = CRYPTO_THREAD_lock_new(); if (a->lock == NULL) { BUF_MEM_free(a->buffer); ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } lu->method_data = a; return 1; err: OPENSSL_free(a); return 0; } static void by_dir_hash_free(BY_DIR_HASH *hash) { OPENSSL_free(hash); } static int by_dir_hash_cmp(const BY_DIR_HASH *const *a, const BY_DIR_HASH *const *b) { if ((*a)->hash > (*b)->hash) return 1; if ((*a)->hash < (*b)->hash) return -1; return 0; } static void by_dir_entry_free(BY_DIR_ENTRY *ent) { OPENSSL_free(ent->dir); sk_BY_DIR_HASH_pop_free(ent->hashes, by_dir_hash_free); OPENSSL_free(ent); } static void free_dir(X509_LOOKUP *lu) { BY_DIR *a = (BY_DIR *)lu->method_data; sk_BY_DIR_ENTRY_pop_free(a->dirs, by_dir_entry_free); BUF_MEM_free(a->buffer); CRYPTO_THREAD_lock_free(a->lock); OPENSSL_free(a); } static int add_cert_dir(BY_DIR *ctx, const char *dir, int type) { int j; size_t len; const char *s, *ss, *p; if (dir == NULL || *dir == '\0') { ERR_raise(ERR_LIB_X509, X509_R_INVALID_DIRECTORY); return 0; } s = dir; p = s; do { if ((*p == LIST_SEPARATOR_CHAR) || (*p == '\0')) { BY_DIR_ENTRY *ent; ss = s; s = p + 1; len = p - ss; if (len == 0) continue; for (j = 0; j < sk_BY_DIR_ENTRY_num(ctx->dirs); j++) { ent = sk_BY_DIR_ENTRY_value(ctx->dirs, j); if (strlen(ent->dir) == len && strncmp(ent->dir, ss, len) == 0) break; } if (j < sk_BY_DIR_ENTRY_num(ctx->dirs)) continue; if (ctx->dirs == NULL) { ctx->dirs = sk_BY_DIR_ENTRY_new_null(); if (!ctx->dirs) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); return 0; } } ent = OPENSSL_malloc(sizeof(*ent)); if (ent == NULL) return 0; ent->dir_type = type; ent->hashes = sk_BY_DIR_HASH_new(by_dir_hash_cmp); ent->dir = OPENSSL_strndup(ss, len); if (ent->dir == NULL || ent->hashes == NULL) { by_dir_entry_free(ent); return 0; } if (!sk_BY_DIR_ENTRY_push(ctx->dirs, ent)) { by_dir_entry_free(ent); ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); return 0; } } } while (*p++ != '\0'); return 1; } static int get_cert_by_subject_ex(X509_LOOKUP *xl, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret, OSSL_LIB_CTX *libctx, const char *propq) { BY_DIR *ctx; union { X509 st_x509; X509_CRL crl; } data; int ok = 0; int i, j, k; unsigned long h; BUF_MEM *b = NULL; X509_OBJECT stmp, *tmp; const char *postfix = ""; if (name == NULL) return 0; stmp.type = type; if (type == X509_LU_X509) { data.st_x509.cert_info.subject = (X509_NAME *)name; /* won't modify it */ stmp.data.x509 = &data.st_x509; } else if (type == X509_LU_CRL) { data.crl.crl.issuer = (X509_NAME *)name; /* won't modify it */ stmp.data.crl = &data.crl; postfix = "r"; } else { ERR_raise(ERR_LIB_X509, X509_R_WRONG_LOOKUP_TYPE); goto finish; } if ((b = BUF_MEM_new()) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB); goto finish; } ctx = (BY_DIR *)xl->method_data; h = X509_NAME_hash_ex(name, libctx, propq, &i); if (i == 0) goto finish; for (i = 0; i < sk_BY_DIR_ENTRY_num(ctx->dirs); i++) { BY_DIR_ENTRY *ent; int idx; BY_DIR_HASH htmp, *hent; ent = sk_BY_DIR_ENTRY_value(ctx->dirs, i); j = strlen(ent->dir) + 1 + 8 + 6 + 1 + 1; if (!BUF_MEM_grow(b, j)) { ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB); goto finish; } if (type == X509_LU_CRL && ent->hashes) { htmp.hash = h; if (!CRYPTO_THREAD_read_lock(ctx->lock)) goto finish; idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp); if (idx >= 0) { hent = sk_BY_DIR_HASH_value(ent->hashes, idx); k = hent->suffix; } else { hent = NULL; k = 0; } CRYPTO_THREAD_unlock(ctx->lock); } else { k = 0; hent = NULL; } for (;;) { char c = '/'; #ifdef OPENSSL_SYS_VMS c = ent->dir[strlen(ent->dir) - 1]; if (c != ':' && c != '>' && c != ']') { /* * If no separator is present, we assume the directory * specifier is a logical name, and add a colon. We really * should use better VMS routines for merging things like * this, but this will do for now... -- Richard Levitte */ c = ':'; } else { c = '\0'; } if (c == '\0') { /* * This is special. When c == '\0', no directory separator * should be added. */ BIO_snprintf(b->data, b->max, "%s%08lx.%s%d", ent->dir, h, postfix, k); } else #endif { BIO_snprintf(b->data, b->max, "%s%c%08lx.%s%d", ent->dir, c, h, postfix, k); } #ifndef OPENSSL_NO_POSIX_IO # ifdef _WIN32 # define stat _stat # endif { struct stat st; if (stat(b->data, &st) < 0) break; } #endif /* found one. */ if (type == X509_LU_X509) { if ((X509_load_cert_file_ex(xl, b->data, ent->dir_type, libctx, propq)) == 0) break; } else if (type == X509_LU_CRL) { if ((X509_load_crl_file(xl, b->data, ent->dir_type)) == 0) break; } /* else case will caught higher up */ k++; } /* * we have added it to the cache so now pull it out again * * Note: quadratic time find here since the objects won't generally be * sorted and sorting the would result in O(n^2 log n) complexity. */ if (k > 0) { if (!X509_STORE_lock(xl->store_ctx)) goto finish; j = sk_X509_OBJECT_find(xl->store_ctx->objs, &stmp); tmp = sk_X509_OBJECT_value(xl->store_ctx->objs, j); X509_STORE_unlock(xl->store_ctx); } else { tmp = NULL; } /* * If a CRL, update the last file suffix added for this. * We don't need to add an entry if k is 0 as this is the initial value. * This avoids the need for a write lock and sort operation in the * simple case where no CRL is present for a hash. */ if (type == X509_LU_CRL && k > 0) { if (!CRYPTO_THREAD_write_lock(ctx->lock)) goto finish; /* * Look for entry again in case another thread added an entry * first. */ if (hent == NULL) { htmp.hash = h; idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp); hent = sk_BY_DIR_HASH_value(ent->hashes, idx); } if (hent == NULL) { hent = OPENSSL_malloc(sizeof(*hent)); if (hent == NULL) { CRYPTO_THREAD_unlock(ctx->lock); ok = 0; goto finish; } hent->hash = h; hent->suffix = k; if (!sk_BY_DIR_HASH_push(ent->hashes, hent)) { CRYPTO_THREAD_unlock(ctx->lock); OPENSSL_free(hent); ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); ok = 0; goto finish; } /* * Ensure stack is sorted so that subsequent sk_BY_DIR_HASH_find * will not mutate the stack and therefore require a write lock. */ sk_BY_DIR_HASH_sort(ent->hashes); } else if (hent->suffix < k) { hent->suffix = k; } CRYPTO_THREAD_unlock(ctx->lock); } if (tmp != NULL) { ok = 1; ret->type = tmp->type; memcpy(&ret->data, &tmp->data, sizeof(ret->data)); /* * Clear any errors that might have been raised processing empty * or malformed files. */ ERR_clear_error(); goto finish; } } finish: /* If we changed anything, resort the objects for faster lookup */ if (!sk_X509_OBJECT_is_sorted(xl->store_ctx->objs)) { if (X509_STORE_lock(xl->store_ctx)) { sk_X509_OBJECT_sort(xl->store_ctx->objs); X509_STORE_unlock(xl->store_ctx); } } BUF_MEM_free(b); return ok; } static int get_cert_by_subject(X509_LOOKUP *xl, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret) { return get_cert_by_subject_ex(xl, type, name, ret, NULL, NULL); }
./openssl/crypto/x509/x_x509a.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/evp.h> #include <openssl/asn1t.h> #include <openssl/x509.h> #include "crypto/x509.h" /* * X509_CERT_AUX routines. These are used to encode additional user * modifiable data about a certificate. This data is appended to the X509 * encoding when the *_X509_AUX routines are used. This means that the * "traditional" X509 routines will simply ignore the extra data. */ static X509_CERT_AUX *aux_get(X509 *x); ASN1_SEQUENCE(X509_CERT_AUX) = { ASN1_SEQUENCE_OF_OPT(X509_CERT_AUX, trust, ASN1_OBJECT), ASN1_IMP_SEQUENCE_OF_OPT(X509_CERT_AUX, reject, ASN1_OBJECT, 0), ASN1_OPT(X509_CERT_AUX, alias, ASN1_UTF8STRING), ASN1_OPT(X509_CERT_AUX, keyid, ASN1_OCTET_STRING), ASN1_IMP_SEQUENCE_OF_OPT(X509_CERT_AUX, other, X509_ALGOR, 1) } ASN1_SEQUENCE_END(X509_CERT_AUX) IMPLEMENT_ASN1_FUNCTIONS(X509_CERT_AUX) int X509_trusted(const X509 *x) { return x->aux ? 1 : 0; } static X509_CERT_AUX *aux_get(X509 *x) { if (x == NULL) return NULL; if (x->aux == NULL && (x->aux = X509_CERT_AUX_new()) == NULL) return NULL; return x->aux; } int X509_alias_set1(X509 *x, const unsigned char *name, int len) { X509_CERT_AUX *aux; if (!name) { if (!x || !x->aux || !x->aux->alias) return 1; ASN1_UTF8STRING_free(x->aux->alias); x->aux->alias = NULL; return 1; } if ((aux = aux_get(x)) == NULL) return 0; if (aux->alias == NULL && (aux->alias = ASN1_UTF8STRING_new()) == NULL) return 0; return ASN1_STRING_set(aux->alias, name, len); } int X509_keyid_set1(X509 *x, const unsigned char *id, int len) { X509_CERT_AUX *aux; if (!id) { if (!x || !x->aux || !x->aux->keyid) return 1; ASN1_OCTET_STRING_free(x->aux->keyid); x->aux->keyid = NULL; return 1; } if ((aux = aux_get(x)) == NULL) return 0; if (aux->keyid == NULL && (aux->keyid = ASN1_OCTET_STRING_new()) == NULL) return 0; return ASN1_STRING_set(aux->keyid, id, len); } unsigned char *X509_alias_get0(X509 *x, int *len) { if (!x->aux || !x->aux->alias) return NULL; if (len) *len = x->aux->alias->length; return x->aux->alias->data; } unsigned char *X509_keyid_get0(X509 *x, int *len) { if (!x->aux || !x->aux->keyid) return NULL; if (len) *len = x->aux->keyid->length; return x->aux->keyid->data; } int X509_add1_trust_object(X509 *x, const ASN1_OBJECT *obj) { X509_CERT_AUX *aux; ASN1_OBJECT *objtmp = NULL; if (obj) { objtmp = OBJ_dup(obj); if (!objtmp) return 0; } if ((aux = aux_get(x)) == NULL) goto err; if (aux->trust == NULL && (aux->trust = sk_ASN1_OBJECT_new_null()) == NULL) goto err; if (!objtmp || sk_ASN1_OBJECT_push(aux->trust, objtmp)) return 1; err: ASN1_OBJECT_free(objtmp); return 0; } int X509_add1_reject_object(X509 *x, const ASN1_OBJECT *obj) { X509_CERT_AUX *aux; ASN1_OBJECT *objtmp; int res = 0; if ((objtmp = OBJ_dup(obj)) == NULL) return 0; if ((aux = aux_get(x)) == NULL) goto err; if (aux->reject == NULL && (aux->reject = sk_ASN1_OBJECT_new_null()) == NULL) goto err; if (sk_ASN1_OBJECT_push(aux->reject, objtmp) > 0) res = 1; err: if (!res) ASN1_OBJECT_free(objtmp); return res; } void X509_trust_clear(X509 *x) { if (x->aux) { sk_ASN1_OBJECT_pop_free(x->aux->trust, ASN1_OBJECT_free); x->aux->trust = NULL; } } void X509_reject_clear(X509 *x) { if (x->aux) { sk_ASN1_OBJECT_pop_free(x->aux->reject, ASN1_OBJECT_free); x->aux->reject = NULL; } } STACK_OF(ASN1_OBJECT) *X509_get0_trust_objects(X509 *x) { if (x->aux != NULL) return x->aux->trust; return NULL; } STACK_OF(ASN1_OBJECT) *X509_get0_reject_objects(X509 *x) { if (x->aux != NULL) return x->aux->reject; return NULL; }
./openssl/crypto/x509/v3_bcons.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/asn1.h> #include <openssl/asn1t.h> #include <openssl/conf.h> #include <openssl/x509v3.h> #include "ext_dat.h" #include "x509_local.h" static STACK_OF(CONF_VALUE) *i2v_BASIC_CONSTRAINTS(X509V3_EXT_METHOD *method, BASIC_CONSTRAINTS *bcons, STACK_OF(CONF_VALUE) *extlist); static BASIC_CONSTRAINTS *v2i_BASIC_CONSTRAINTS(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *values); const X509V3_EXT_METHOD ossl_v3_bcons = { NID_basic_constraints, 0, ASN1_ITEM_ref(BASIC_CONSTRAINTS), 0, 0, 0, 0, 0, 0, (X509V3_EXT_I2V) i2v_BASIC_CONSTRAINTS, (X509V3_EXT_V2I)v2i_BASIC_CONSTRAINTS, NULL, NULL, NULL }; ASN1_SEQUENCE(BASIC_CONSTRAINTS) = { ASN1_OPT(BASIC_CONSTRAINTS, ca, ASN1_FBOOLEAN), ASN1_OPT(BASIC_CONSTRAINTS, pathlen, ASN1_INTEGER) } ASN1_SEQUENCE_END(BASIC_CONSTRAINTS) IMPLEMENT_ASN1_FUNCTIONS(BASIC_CONSTRAINTS) static STACK_OF(CONF_VALUE) *i2v_BASIC_CONSTRAINTS(X509V3_EXT_METHOD *method, BASIC_CONSTRAINTS *bcons, STACK_OF(CONF_VALUE) *extlist) { X509V3_add_value_bool("CA", bcons->ca, &extlist); X509V3_add_value_int("pathlen", bcons->pathlen, &extlist); return extlist; } static BASIC_CONSTRAINTS *v2i_BASIC_CONSTRAINTS(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *values) { BASIC_CONSTRAINTS *bcons = NULL; CONF_VALUE *val; int i; if ((bcons = BASIC_CONSTRAINTS_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); return NULL; } for (i = 0; i < sk_CONF_VALUE_num(values); i++) { val = sk_CONF_VALUE_value(values, i); if (strcmp(val->name, "CA") == 0) { if (!X509V3_get_value_bool(val, &bcons->ca)) goto err; } else if (strcmp(val->name, "pathlen") == 0) { if (!X509V3_get_value_int(val, &bcons->pathlen)) goto err; } else { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NAME); X509V3_conf_add_error_name_value(val); goto err; } } return bcons; err: BASIC_CONSTRAINTS_free(bcons); return NULL; }
./openssl/crypto/x509/v3_san.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 "crypto/x509.h" #include <openssl/conf.h> #include <openssl/x509v3.h> #include <openssl/bio.h> #include "ext_dat.h" static GENERAL_NAMES *v2i_subject_alt(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval); static GENERAL_NAMES *v2i_issuer_alt(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval); static int copy_email(X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p); static int copy_issuer(X509V3_CTX *ctx, GENERAL_NAMES *gens); static int do_othername(GENERAL_NAME *gen, const char *value, X509V3_CTX *ctx); static int do_dirname(GENERAL_NAME *gen, const char *value, X509V3_CTX *ctx); const X509V3_EXT_METHOD ossl_v3_alt[3] = { {NID_subject_alt_name, 0, ASN1_ITEM_ref(GENERAL_NAMES), 0, 0, 0, 0, 0, 0, (X509V3_EXT_I2V) i2v_GENERAL_NAMES, (X509V3_EXT_V2I)v2i_subject_alt, NULL, NULL, NULL}, {NID_issuer_alt_name, 0, ASN1_ITEM_ref(GENERAL_NAMES), 0, 0, 0, 0, 0, 0, (X509V3_EXT_I2V) i2v_GENERAL_NAMES, (X509V3_EXT_V2I)v2i_issuer_alt, NULL, NULL, NULL}, {NID_certificate_issuer, 0, ASN1_ITEM_ref(GENERAL_NAMES), 0, 0, 0, 0, 0, 0, (X509V3_EXT_I2V) i2v_GENERAL_NAMES, NULL, NULL, NULL, NULL}, }; STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES(X509V3_EXT_METHOD *method, GENERAL_NAMES *gens, STACK_OF(CONF_VALUE) *ret) { int i; GENERAL_NAME *gen; STACK_OF(CONF_VALUE) *tmpret = NULL, *origret = ret; for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) { gen = sk_GENERAL_NAME_value(gens, i); /* * i2v_GENERAL_NAME allocates ret if it is NULL. If something goes * wrong we need to free the stack - but only if it was empty when we * originally entered this function. */ tmpret = i2v_GENERAL_NAME(method, gen, ret); if (tmpret == NULL) { if (origret == NULL) sk_CONF_VALUE_pop_free(ret, X509V3_conf_free); return NULL; } ret = tmpret; } if (ret == NULL) return sk_CONF_VALUE_new_null(); return ret; } STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method, GENERAL_NAME *gen, STACK_OF(CONF_VALUE) *ret) { char othername[300]; char oline[256], *tmp; switch (gen->type) { case GEN_OTHERNAME: switch (OBJ_obj2nid(gen->d.otherName->type_id)) { case NID_id_on_SmtpUTF8Mailbox: if (gen->d.otherName->value->type != V_ASN1_UTF8STRING || !x509v3_add_len_value_uchar("othername: SmtpUTF8Mailbox:", gen->d.otherName->value->value.utf8string->data, gen->d.otherName->value->value.utf8string->length, &ret)) return NULL; break; case NID_XmppAddr: if (gen->d.otherName->value->type != V_ASN1_UTF8STRING || !x509v3_add_len_value_uchar("othername: XmppAddr:", gen->d.otherName->value->value.utf8string->data, gen->d.otherName->value->value.utf8string->length, &ret)) return NULL; break; case NID_SRVName: if (gen->d.otherName->value->type != V_ASN1_IA5STRING || !x509v3_add_len_value_uchar("othername: SRVName:", gen->d.otherName->value->value.ia5string->data, gen->d.otherName->value->value.ia5string->length, &ret)) return NULL; break; case NID_ms_upn: if (gen->d.otherName->value->type != V_ASN1_UTF8STRING || !x509v3_add_len_value_uchar("othername: UPN:", gen->d.otherName->value->value.utf8string->data, gen->d.otherName->value->value.utf8string->length, &ret)) return NULL; break; case NID_NAIRealm: if (gen->d.otherName->value->type != V_ASN1_UTF8STRING || !x509v3_add_len_value_uchar("othername: NAIRealm:", gen->d.otherName->value->value.utf8string->data, gen->d.otherName->value->value.utf8string->length, &ret)) return NULL; break; default: if (OBJ_obj2txt(oline, sizeof(oline), gen->d.otherName->type_id, 0) > 0) BIO_snprintf(othername, sizeof(othername), "othername: %s:", oline); else OPENSSL_strlcpy(othername, "othername:", sizeof(othername)); /* check if the value is something printable */ if (gen->d.otherName->value->type == V_ASN1_IA5STRING) { if (x509v3_add_len_value_uchar(othername, gen->d.otherName->value->value.ia5string->data, gen->d.otherName->value->value.ia5string->length, &ret)) return ret; } if (gen->d.otherName->value->type == V_ASN1_UTF8STRING) { if (x509v3_add_len_value_uchar(othername, gen->d.otherName->value->value.utf8string->data, gen->d.otherName->value->value.utf8string->length, &ret)) return ret; } if (!X509V3_add_value(othername, "<unsupported>", &ret)) return NULL; break; } break; case GEN_X400: if (!X509V3_add_value("X400Name", "<unsupported>", &ret)) return NULL; break; case GEN_EDIPARTY: if (!X509V3_add_value("EdiPartyName", "<unsupported>", &ret)) return NULL; break; case GEN_EMAIL: if (!x509v3_add_len_value_uchar("email", gen->d.ia5->data, gen->d.ia5->length, &ret)) return NULL; break; case GEN_DNS: if (!x509v3_add_len_value_uchar("DNS", gen->d.ia5->data, gen->d.ia5->length, &ret)) return NULL; break; case GEN_URI: if (!x509v3_add_len_value_uchar("URI", gen->d.ia5->data, gen->d.ia5->length, &ret)) return NULL; break; case GEN_DIRNAME: if (X509_NAME_oneline(gen->d.dirn, oline, sizeof(oline)) == NULL || !X509V3_add_value("DirName", oline, &ret)) return NULL; break; case GEN_IPADD: tmp = ossl_ipaddr_to_asc(gen->d.ip->data, gen->d.ip->length); if (tmp == NULL || !X509V3_add_value("IP Address", tmp, &ret)) ret = NULL; OPENSSL_free(tmp); break; case GEN_RID: i2t_ASN1_OBJECT(oline, 256, gen->d.rid); if (!X509V3_add_value("Registered ID", oline, &ret)) return NULL; break; } return ret; } int GENERAL_NAME_print(BIO *out, GENERAL_NAME *gen) { char *tmp; int nid; switch (gen->type) { case GEN_OTHERNAME: nid = OBJ_obj2nid(gen->d.otherName->type_id); /* Validate the types are as we expect before we use them */ if ((nid == NID_SRVName && gen->d.otherName->value->type != V_ASN1_IA5STRING) || (nid != NID_SRVName && gen->d.otherName->value->type != V_ASN1_UTF8STRING)) { BIO_printf(out, "othername:<unsupported>"); break; } switch (nid) { case NID_id_on_SmtpUTF8Mailbox: BIO_printf(out, "othername:SmtpUTF8Mailbox:%.*s", gen->d.otherName->value->value.utf8string->length, gen->d.otherName->value->value.utf8string->data); break; case NID_XmppAddr: BIO_printf(out, "othername:XmppAddr:%.*s", gen->d.otherName->value->value.utf8string->length, gen->d.otherName->value->value.utf8string->data); break; case NID_SRVName: BIO_printf(out, "othername:SRVName:%.*s", gen->d.otherName->value->value.ia5string->length, gen->d.otherName->value->value.ia5string->data); break; case NID_ms_upn: BIO_printf(out, "othername:UPN:%.*s", gen->d.otherName->value->value.utf8string->length, gen->d.otherName->value->value.utf8string->data); break; case NID_NAIRealm: BIO_printf(out, "othername:NAIRealm:%.*s", gen->d.otherName->value->value.utf8string->length, gen->d.otherName->value->value.utf8string->data); break; default: BIO_printf(out, "othername:<unsupported>"); break; } break; case GEN_X400: BIO_printf(out, "X400Name:<unsupported>"); break; case GEN_EDIPARTY: /* Maybe fix this: it is supported now */ BIO_printf(out, "EdiPartyName:<unsupported>"); break; case GEN_EMAIL: BIO_printf(out, "email:"); ASN1_STRING_print(out, gen->d.ia5); break; case GEN_DNS: BIO_printf(out, "DNS:"); ASN1_STRING_print(out, gen->d.ia5); break; case GEN_URI: BIO_printf(out, "URI:"); ASN1_STRING_print(out, gen->d.ia5); break; case GEN_DIRNAME: BIO_printf(out, "DirName:"); X509_NAME_print_ex(out, gen->d.dirn, 0, XN_FLAG_ONELINE); break; case GEN_IPADD: tmp = ossl_ipaddr_to_asc(gen->d.ip->data, gen->d.ip->length); if (tmp == NULL) return 0; BIO_printf(out, "IP Address:%s", tmp); OPENSSL_free(tmp); break; case GEN_RID: BIO_printf(out, "Registered ID:"); i2a_ASN1_OBJECT(out, gen->d.rid); break; } return 1; } static GENERAL_NAMES *v2i_issuer_alt(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { const int num = sk_CONF_VALUE_num(nval); GENERAL_NAMES *gens = sk_GENERAL_NAME_new_reserve(NULL, num); int i; if (gens == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); sk_GENERAL_NAME_free(gens); return NULL; } for (i = 0; i < num; i++) { CONF_VALUE *cnf = sk_CONF_VALUE_value(nval, i); if (!ossl_v3_name_cmp(cnf->name, "issuer") && cnf->value && strcmp(cnf->value, "copy") == 0) { if (!copy_issuer(ctx, gens)) goto err; } else { GENERAL_NAME *gen = v2i_GENERAL_NAME(method, ctx, cnf); if (gen == NULL) goto err; sk_GENERAL_NAME_push(gens, gen); /* no failure as it was reserved */ } } return gens; err: sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); return NULL; } /* Append subject altname of issuer to issuer alt name of subject */ static int copy_issuer(X509V3_CTX *ctx, GENERAL_NAMES *gens) { GENERAL_NAMES *ialt; GENERAL_NAME *gen; X509_EXTENSION *ext; int i, num; if (ctx != NULL && (ctx->flags & X509V3_CTX_TEST) != 0) return 1; if (!ctx || !ctx->issuer_cert) { ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_ISSUER_DETAILS); goto err; } i = X509_get_ext_by_NID(ctx->issuer_cert, NID_subject_alt_name, -1); if (i < 0) return 1; if ((ext = X509_get_ext(ctx->issuer_cert, i)) == NULL || (ialt = X509V3_EXT_d2i(ext)) == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_ISSUER_DECODE_ERROR); goto err; } num = sk_GENERAL_NAME_num(ialt); if (!sk_GENERAL_NAME_reserve(gens, num)) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto err; } for (i = 0; i < num; i++) { gen = sk_GENERAL_NAME_value(ialt, i); sk_GENERAL_NAME_push(gens, gen); /* no failure as it was reserved */ } sk_GENERAL_NAME_free(ialt); return 1; err: return 0; } static GENERAL_NAMES *v2i_subject_alt(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { GENERAL_NAMES *gens; CONF_VALUE *cnf; const int num = sk_CONF_VALUE_num(nval); int i; gens = sk_GENERAL_NAME_new_reserve(NULL, num); if (gens == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); sk_GENERAL_NAME_free(gens); return NULL; } for (i = 0; i < num; i++) { cnf = sk_CONF_VALUE_value(nval, i); if (ossl_v3_name_cmp(cnf->name, "email") == 0 && cnf->value && strcmp(cnf->value, "copy") == 0) { if (!copy_email(ctx, gens, 0)) goto err; } else if (ossl_v3_name_cmp(cnf->name, "email") == 0 && cnf->value && strcmp(cnf->value, "move") == 0) { if (!copy_email(ctx, gens, 1)) goto err; } else { GENERAL_NAME *gen; if ((gen = v2i_GENERAL_NAME(method, ctx, cnf)) == NULL) goto err; sk_GENERAL_NAME_push(gens, gen); /* no failure as it was reserved */ } } return gens; err: sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); return NULL; } /* * Copy any email addresses in a certificate or request to GENERAL_NAMES */ static int copy_email(X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p) { X509_NAME *nm; ASN1_IA5STRING *email = NULL; X509_NAME_ENTRY *ne; GENERAL_NAME *gen = NULL; int i = -1; if (ctx != NULL && (ctx->flags & X509V3_CTX_TEST) != 0) return 1; if (ctx == NULL || (ctx->subject_cert == NULL && ctx->subject_req == NULL)) { ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_SUBJECT_DETAILS); return 0; } /* Find the subject name */ nm = ctx->subject_cert != NULL ? X509_get_subject_name(ctx->subject_cert) : X509_REQ_get_subject_name(ctx->subject_req); /* Now add any email address(es) to STACK */ while ((i = X509_NAME_get_index_by_NID(nm, NID_pkcs9_emailAddress, i)) >= 0) { ne = X509_NAME_get_entry(nm, i); email = ASN1_STRING_dup(X509_NAME_ENTRY_get_data(ne)); if (move_p) { X509_NAME_delete_entry(nm, i); X509_NAME_ENTRY_free(ne); i--; } if (email == NULL || (gen = GENERAL_NAME_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } gen->d.ia5 = email; email = NULL; gen->type = GEN_EMAIL; if (!sk_GENERAL_NAME_push(gens, gen)) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto err; } gen = NULL; } return 1; err: GENERAL_NAME_free(gen); ASN1_IA5STRING_free(email); return 0; } GENERAL_NAMES *v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { GENERAL_NAME *gen; GENERAL_NAMES *gens; CONF_VALUE *cnf; const int num = sk_CONF_VALUE_num(nval); int i; gens = sk_GENERAL_NAME_new_reserve(NULL, num); if (gens == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); sk_GENERAL_NAME_free(gens); return NULL; } for (i = 0; i < num; i++) { cnf = sk_CONF_VALUE_value(nval, i); if ((gen = v2i_GENERAL_NAME(method, ctx, cnf)) == NULL) goto err; sk_GENERAL_NAME_push(gens, gen); /* no failure as it was reserved */ } return gens; err: sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); return NULL; } GENERAL_NAME *v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, CONF_VALUE *cnf) { return v2i_GENERAL_NAME_ex(NULL, method, ctx, cnf, 0); } GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out, const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, int gen_type, const char *value, int is_nc) { char is_string = 0; GENERAL_NAME *gen = NULL; if (!value) { ERR_raise(ERR_LIB_X509V3, X509V3_R_MISSING_VALUE); return NULL; } if (out) gen = out; else { gen = GENERAL_NAME_new(); if (gen == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); return NULL; } } switch (gen_type) { case GEN_URI: case GEN_EMAIL: case GEN_DNS: is_string = 1; break; case GEN_RID: { ASN1_OBJECT *obj; if ((obj = OBJ_txt2obj(value, 0)) == NULL) { ERR_raise_data(ERR_LIB_X509V3, X509V3_R_BAD_OBJECT, "value=%s", value); goto err; } gen->d.rid = obj; } break; case GEN_IPADD: if (is_nc) gen->d.ip = a2i_IPADDRESS_NC(value); else gen->d.ip = a2i_IPADDRESS(value); if (gen->d.ip == NULL) { ERR_raise_data(ERR_LIB_X509V3, X509V3_R_BAD_IP_ADDRESS, "value=%s", value); goto err; } break; case GEN_DIRNAME: if (!do_dirname(gen, value, ctx)) { ERR_raise(ERR_LIB_X509V3, X509V3_R_DIRNAME_ERROR); goto err; } break; case GEN_OTHERNAME: if (!do_othername(gen, value, ctx)) { ERR_raise(ERR_LIB_X509V3, X509V3_R_OTHERNAME_ERROR); goto err; } break; default: ERR_raise(ERR_LIB_X509V3, X509V3_R_UNSUPPORTED_TYPE); goto err; } if (is_string) { if ((gen->d.ia5 = ASN1_IA5STRING_new()) == NULL || !ASN1_STRING_set(gen->d.ia5, (unsigned char *)value, strlen(value))) { ASN1_IA5STRING_free(gen->d.ia5); gen->d.ia5 = NULL; ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } } gen->type = gen_type; return gen; err: if (!out) GENERAL_NAME_free(gen); return NULL; } GENERAL_NAME *v2i_GENERAL_NAME_ex(GENERAL_NAME *out, const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, CONF_VALUE *cnf, int is_nc) { int type; char *name, *value; name = cnf->name; value = cnf->value; if (!value) { ERR_raise(ERR_LIB_X509V3, X509V3_R_MISSING_VALUE); return NULL; } if (!ossl_v3_name_cmp(name, "email")) type = GEN_EMAIL; else if (!ossl_v3_name_cmp(name, "URI")) type = GEN_URI; else if (!ossl_v3_name_cmp(name, "DNS")) type = GEN_DNS; else if (!ossl_v3_name_cmp(name, "RID")) type = GEN_RID; else if (!ossl_v3_name_cmp(name, "IP")) type = GEN_IPADD; else if (!ossl_v3_name_cmp(name, "dirName")) type = GEN_DIRNAME; else if (!ossl_v3_name_cmp(name, "otherName")) type = GEN_OTHERNAME; else { ERR_raise_data(ERR_LIB_X509V3, X509V3_R_UNSUPPORTED_OPTION, "name=%s", name); return NULL; } return a2i_GENERAL_NAME(out, method, ctx, type, value, is_nc); } static int do_othername(GENERAL_NAME *gen, const char *value, X509V3_CTX *ctx) { char *objtmp = NULL, *p; int objlen; if ((p = strchr(value, ';')) == NULL) return 0; if ((gen->d.otherName = OTHERNAME_new()) == NULL) return 0; /* * Free this up because we will overwrite it. no need to free type_id * because it is static */ ASN1_TYPE_free(gen->d.otherName->value); if ((gen->d.otherName->value = ASN1_generate_v3(p + 1, ctx)) == NULL) goto err; objlen = p - value; objtmp = OPENSSL_strndup(value, objlen); if (objtmp == NULL) goto err; gen->d.otherName->type_id = OBJ_txt2obj(objtmp, 0); OPENSSL_free(objtmp); if (!gen->d.otherName->type_id) goto err; return 1; err: OTHERNAME_free(gen->d.otherName); gen->d.otherName = NULL; return 0; } static int do_dirname(GENERAL_NAME *gen, const char *value, X509V3_CTX *ctx) { int ret = 0; STACK_OF(CONF_VALUE) *sk = NULL; X509_NAME *nm; if ((nm = X509_NAME_new()) == NULL) goto err; sk = X509V3_get_section(ctx, value); if (!sk) { ERR_raise_data(ERR_LIB_X509V3, X509V3_R_SECTION_NOT_FOUND, "section=%s", value); goto err; } /* FIXME: should allow other character types... */ ret = X509V3_NAME_from_section(nm, sk, MBSTRING_ASC); if (!ret) goto err; gen->d.dirn = nm; err: if (ret == 0) X509_NAME_free(nm); X509V3_section_free(ctx, sk); return ret; }
./openssl/crypto/x509/x509name.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 <openssl/safestack.h> #include <openssl/asn1.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/x509.h> #include "crypto/x509.h" int X509_NAME_get_text_by_NID(const X509_NAME *name, int nid, char *buf, int len) { ASN1_OBJECT *obj; obj = OBJ_nid2obj(nid); if (obj == NULL) return -1; return X509_NAME_get_text_by_OBJ(name, obj, buf, len); } int X509_NAME_get_text_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj, char *buf, int len) { int i; const ASN1_STRING *data; i = X509_NAME_get_index_by_OBJ(name, obj, -1); if (i < 0) return -1; data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i)); if (buf == NULL) return data->length; if (len <= 0) return 0; i = (data->length > (len - 1)) ? (len - 1) : data->length; memcpy(buf, data->data, i); buf[i] = '\0'; return i; } int X509_NAME_entry_count(const X509_NAME *name) { int ret; if (name == NULL) return 0; ret = sk_X509_NAME_ENTRY_num(name->entries); return ret > 0 ? ret : 0; } int X509_NAME_get_index_by_NID(const X509_NAME *name, int nid, int lastpos) { ASN1_OBJECT *obj; obj = OBJ_nid2obj(nid); if (obj == NULL) return -2; return X509_NAME_get_index_by_OBJ(name, obj, lastpos); } /* NOTE: you should be passing -1, not 0 as lastpos */ int X509_NAME_get_index_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj, int lastpos) { int n; X509_NAME_ENTRY *ne; STACK_OF(X509_NAME_ENTRY) *sk; if (name == NULL) return -1; if (lastpos < 0) lastpos = -1; sk = name->entries; n = sk_X509_NAME_ENTRY_num(sk); for (lastpos++; lastpos < n; lastpos++) { ne = sk_X509_NAME_ENTRY_value(sk, lastpos); if (OBJ_cmp(ne->object, obj) == 0) return lastpos; } return -1; } X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc) { if (name == NULL || sk_X509_NAME_ENTRY_num(name->entries) <= loc || loc < 0) return NULL; return sk_X509_NAME_ENTRY_value(name->entries, loc); } X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc) { X509_NAME_ENTRY *ret; int i, n, set_prev, set_next; STACK_OF(X509_NAME_ENTRY) *sk; if (name == NULL || sk_X509_NAME_ENTRY_num(name->entries) <= loc || loc < 0) return NULL; sk = name->entries; ret = sk_X509_NAME_ENTRY_delete(sk, loc); n = sk_X509_NAME_ENTRY_num(sk); name->modified = 1; if (loc == n) return ret; /* else we need to fixup the set field */ if (loc != 0) set_prev = (sk_X509_NAME_ENTRY_value(sk, loc - 1))->set; else set_prev = ret->set - 1; set_next = sk_X509_NAME_ENTRY_value(sk, loc)->set; /*- * set_prev is the previous set * set is the current set * set_next is the following * prev 1 1 1 1 1 1 1 1 * set 1 1 2 2 * next 1 1 2 2 2 2 3 2 * so basically only if prev and next differ by 2, then * re-number down by 1 */ if (set_prev + 1 < set_next) for (i = loc; i < n; i++) sk_X509_NAME_ENTRY_value(sk, i)->set--; return ret; } int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type, const unsigned char *bytes, int len, int loc, int set) { X509_NAME_ENTRY *ne; int ret; ne = X509_NAME_ENTRY_create_by_OBJ(NULL, obj, type, bytes, len); if (!ne) return 0; ret = X509_NAME_add_entry(name, ne, loc, set); X509_NAME_ENTRY_free(ne); return ret; } int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type, const unsigned char *bytes, int len, int loc, int set) { X509_NAME_ENTRY *ne; int ret; ne = X509_NAME_ENTRY_create_by_NID(NULL, nid, type, bytes, len); if (!ne) return 0; ret = X509_NAME_add_entry(name, ne, loc, set); X509_NAME_ENTRY_free(ne); return ret; } int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type, const unsigned char *bytes, int len, int loc, int set) { X509_NAME_ENTRY *ne; int ret; ne = X509_NAME_ENTRY_create_by_txt(NULL, field, type, bytes, len); if (!ne) return 0; ret = X509_NAME_add_entry(name, ne, loc, set); X509_NAME_ENTRY_free(ne); return ret; } /* * if set is -1, append to previous set, 0 'a new one', and 1, prepend to the * guy we are about to stomp on. */ int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne, int loc, int set) { X509_NAME_ENTRY *new_name = NULL; int n, i, inc; STACK_OF(X509_NAME_ENTRY) *sk; if (name == NULL) return 0; sk = name->entries; n = sk_X509_NAME_ENTRY_num(sk); if (loc > n) loc = n; else if (loc < 0) loc = n; inc = (set == 0); name->modified = 1; if (set == -1) { if (loc == 0) { set = 0; inc = 1; } else { set = sk_X509_NAME_ENTRY_value(sk, loc - 1)->set; } } else { /* if (set >= 0) */ if (loc >= n) { if (loc != 0) set = sk_X509_NAME_ENTRY_value(sk, loc - 1)->set + 1; else set = 0; } else set = sk_X509_NAME_ENTRY_value(sk, loc)->set; } if ((new_name = X509_NAME_ENTRY_dup(ne)) == NULL) goto err; new_name->set = set; if (!sk_X509_NAME_ENTRY_insert(sk, new_name, loc)) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } if (inc) { n = sk_X509_NAME_ENTRY_num(sk); for (i = loc + 1; i < n; i++) sk_X509_NAME_ENTRY_value(sk, i)->set += 1; } return 1; err: X509_NAME_ENTRY_free(new_name); return 0; } X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne, const char *field, int type, const unsigned char *bytes, int len) { ASN1_OBJECT *obj; X509_NAME_ENTRY *nentry; obj = OBJ_txt2obj(field, 0); if (obj == NULL) { ERR_raise_data(ERR_LIB_X509, X509_R_INVALID_FIELD_NAME, "name=%s", field); return NULL; } nentry = X509_NAME_ENTRY_create_by_OBJ(ne, obj, type, bytes, len); ASN1_OBJECT_free(obj); return nentry; } X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid, int type, const unsigned char *bytes, int len) { ASN1_OBJECT *obj; X509_NAME_ENTRY *nentry; obj = OBJ_nid2obj(nid); if (obj == NULL) { ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_NID); return NULL; } nentry = X509_NAME_ENTRY_create_by_OBJ(ne, obj, type, bytes, len); ASN1_OBJECT_free(obj); return nentry; } X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne, const ASN1_OBJECT *obj, int type, const unsigned char *bytes, int len) { X509_NAME_ENTRY *ret; if ((ne == NULL) || (*ne == NULL)) { if ((ret = X509_NAME_ENTRY_new()) == NULL) return NULL; } else ret = *ne; if (!X509_NAME_ENTRY_set_object(ret, obj)) goto err; if (!X509_NAME_ENTRY_set_data(ret, type, bytes, len)) goto err; if ((ne != NULL) && (*ne == NULL)) *ne = ret; return ret; err: if ((ne == NULL) || (ret != *ne)) X509_NAME_ENTRY_free(ret); return NULL; } int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj) { if ((ne == NULL) || (obj == NULL)) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return 0; } ASN1_OBJECT_free(ne->object); ne->object = OBJ_dup(obj); return ((ne->object == NULL) ? 0 : 1); } int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type, const unsigned char *bytes, int len) { int i; if ((ne == NULL) || ((bytes == NULL) && (len != 0))) return 0; if ((type > 0) && (type & MBSTRING_FLAG)) return ASN1_STRING_set_by_NID(&ne->value, bytes, len, type, OBJ_obj2nid(ne->object)) ? 1 : 0; if (len < 0) len = strlen((const char *)bytes); i = ASN1_STRING_set(ne->value, bytes, len); if (!i) return 0; if (type != V_ASN1_UNDEF) { if (type == V_ASN1_APP_CHOOSE) ne->value->type = ASN1_PRINTABLE_type(bytes, len); else ne->value->type = type; } return 1; } ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne) { if (ne == NULL) return NULL; return ne->object; } ASN1_STRING *X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne) { if (ne == NULL) return NULL; return ne->value; } int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne) { return ne->set; }
./openssl/crypto/x509/x509_lu.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include "internal/refcount.h" #include <openssl/x509.h> #include "crypto/x509.h" #include <openssl/x509v3.h> #include "x509_local.h" X509_LOOKUP *X509_LOOKUP_new(X509_LOOKUP_METHOD *method) { X509_LOOKUP *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->method = method; if (method->new_item != NULL && method->new_item(ret) == 0) { OPENSSL_free(ret); return NULL; } return ret; } void X509_LOOKUP_free(X509_LOOKUP *ctx) { if (ctx == NULL) return; if ((ctx->method != NULL) && (ctx->method->free != NULL)) (*ctx->method->free) (ctx); OPENSSL_free(ctx); } int X509_STORE_lock(X509_STORE *xs) { return CRYPTO_THREAD_write_lock(xs->lock); } static int x509_store_read_lock(X509_STORE *xs) { return CRYPTO_THREAD_read_lock(xs->lock); } int X509_STORE_unlock(X509_STORE *xs) { return CRYPTO_THREAD_unlock(xs->lock); } int X509_LOOKUP_init(X509_LOOKUP *ctx) { if (ctx->method == NULL) return 0; if (ctx->method->init != NULL) return ctx->method->init(ctx); else return 1; } int X509_LOOKUP_shutdown(X509_LOOKUP *ctx) { if (ctx->method == NULL) return 0; if (ctx->method->shutdown != NULL) return ctx->method->shutdown(ctx); else return 1; } int X509_LOOKUP_ctrl_ex(X509_LOOKUP *ctx, int cmd, const char *argc, long argl, char **ret, OSSL_LIB_CTX *libctx, const char *propq) { if (ctx->method == NULL) return -1; if (ctx->method->ctrl_ex != NULL) return ctx->method->ctrl_ex(ctx, cmd, argc, argl, ret, libctx, propq); if (ctx->method->ctrl != NULL) return ctx->method->ctrl(ctx, cmd, argc, argl, ret); return 1; } int X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, long argl, char **ret) { return X509_LOOKUP_ctrl_ex(ctx, cmd, argc, argl, ret, NULL, NULL); } int X509_LOOKUP_by_subject_ex(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret, OSSL_LIB_CTX *libctx, const char *propq) { if (ctx->skip || ctx->method == NULL || (ctx->method->get_by_subject == NULL && ctx->method->get_by_subject_ex == NULL)) return 0; if (ctx->method->get_by_subject_ex != NULL) return ctx->method->get_by_subject_ex(ctx, type, name, ret, libctx, propq); else return ctx->method->get_by_subject(ctx, type, name, ret); } int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret) { return X509_LOOKUP_by_subject_ex(ctx, type, name, ret, NULL, NULL); } int X509_LOOKUP_by_issuer_serial(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, const ASN1_INTEGER *serial, X509_OBJECT *ret) { if ((ctx->method == NULL) || (ctx->method->get_by_issuer_serial == NULL)) return 0; return ctx->method->get_by_issuer_serial(ctx, type, name, serial, ret); } int X509_LOOKUP_by_fingerprint(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const unsigned char *bytes, int len, X509_OBJECT *ret) { if ((ctx->method == NULL) || (ctx->method->get_by_fingerprint == NULL)) return 0; return ctx->method->get_by_fingerprint(ctx, type, bytes, len, ret); } int X509_LOOKUP_by_alias(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const char *str, int len, X509_OBJECT *ret) { if ((ctx->method == NULL) || (ctx->method->get_by_alias == NULL)) return 0; return ctx->method->get_by_alias(ctx, type, str, len, ret); } int X509_LOOKUP_set_method_data(X509_LOOKUP *ctx, void *data) { ctx->method_data = data; return 1; } void *X509_LOOKUP_get_method_data(const X509_LOOKUP *ctx) { return ctx->method_data; } X509_STORE *X509_LOOKUP_get_store(const X509_LOOKUP *ctx) { return ctx->store_ctx; } static int x509_object_cmp(const X509_OBJECT *const *a, const X509_OBJECT *const *b) { int ret; ret = ((*a)->type - (*b)->type); if (ret) return ret; switch ((*a)->type) { case X509_LU_X509: ret = X509_subject_name_cmp((*a)->data.x509, (*b)->data.x509); break; case X509_LU_CRL: ret = X509_CRL_cmp((*a)->data.crl, (*b)->data.crl); break; case X509_LU_NONE: /* abort(); */ return 0; } return ret; } X509_STORE *X509_STORE_new(void) { X509_STORE *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; if ((ret->objs = sk_X509_OBJECT_new(x509_object_cmp)) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } ret->cache = 1; if ((ret->get_cert_methods = sk_X509_LOOKUP_new_null()) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } if ((ret->param = X509_VERIFY_PARAM_new()) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto err; } if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE, ret, &ret->ex_data)) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } if (!CRYPTO_NEW_REF(&ret->references, 1)) goto err; return ret; err: X509_VERIFY_PARAM_free(ret->param); sk_X509_OBJECT_free(ret->objs); sk_X509_LOOKUP_free(ret->get_cert_methods); CRYPTO_THREAD_lock_free(ret->lock); OPENSSL_free(ret); return NULL; } void X509_STORE_free(X509_STORE *xs) { int i; STACK_OF(X509_LOOKUP) *sk; X509_LOOKUP *lu; if (xs == NULL) return; CRYPTO_DOWN_REF(&xs->references, &i); REF_PRINT_COUNT("X509_STORE", xs); if (i > 0) return; REF_ASSERT_ISNT(i < 0); sk = xs->get_cert_methods; for (i = 0; i < sk_X509_LOOKUP_num(sk); i++) { lu = sk_X509_LOOKUP_value(sk, i); X509_LOOKUP_shutdown(lu); X509_LOOKUP_free(lu); } sk_X509_LOOKUP_free(sk); sk_X509_OBJECT_pop_free(xs->objs, X509_OBJECT_free); CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE, xs, &xs->ex_data); X509_VERIFY_PARAM_free(xs->param); CRYPTO_THREAD_lock_free(xs->lock); CRYPTO_FREE_REF(&xs->references); OPENSSL_free(xs); } int X509_STORE_up_ref(X509_STORE *xs) { int i; if (CRYPTO_UP_REF(&xs->references, &i) <= 0) return 0; REF_PRINT_COUNT("X509_STORE", xs); REF_ASSERT_ISNT(i < 2); return i > 1 ? 1 : 0; } X509_LOOKUP *X509_STORE_add_lookup(X509_STORE *xs, X509_LOOKUP_METHOD *m) { int i; STACK_OF(X509_LOOKUP) *sk; X509_LOOKUP *lu; sk = xs->get_cert_methods; for (i = 0; i < sk_X509_LOOKUP_num(sk); i++) { lu = sk_X509_LOOKUP_value(sk, i); if (m == lu->method) { return lu; } } /* a new one */ lu = X509_LOOKUP_new(m); if (lu == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); return NULL; } lu->store_ctx = xs; if (sk_X509_LOOKUP_push(xs->get_cert_methods, lu)) return lu; /* sk_X509_LOOKUP_push() failed */ ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); X509_LOOKUP_free(lu); return NULL; } /* Also fill the cache (ctx->store->objs) with all matching certificates. */ X509_OBJECT *X509_STORE_CTX_get_obj_by_subject(X509_STORE_CTX *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name) { X509_OBJECT *ret = X509_OBJECT_new(); if (ret == NULL) return NULL; if (!X509_STORE_CTX_get_by_subject(ctx, type, name, ret)) { X509_OBJECT_free(ret); return NULL; } return ret; } /* * May be called with |ret| == NULL just for the side effect of * caching all certs matching the given subject DN in |ctx->store->objs|. * Returns 1 if successful, * 0 if not found or X509_LOOKUP_by_subject_ex() returns an error, * -1 on failure */ static int ossl_x509_store_ctx_get_by_subject(const X509_STORE_CTX *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret) { X509_STORE *store = ctx->store; X509_LOOKUP *lu; X509_OBJECT stmp, *tmp; int i, j; if (store == NULL) return 0; stmp.type = X509_LU_NONE; stmp.data.ptr = NULL; if (!x509_store_read_lock(store)) return 0; /* Should already be sorted...but just in case */ if (!sk_X509_OBJECT_is_sorted(store->objs)) { X509_STORE_unlock(store); /* Take a write lock instead of a read lock */ if (!X509_STORE_lock(store)) return 0; /* * Another thread might have sorted it in the meantime. But if so, * sk_X509_OBJECT_sort() exits early. */ sk_X509_OBJECT_sort(store->objs); } tmp = X509_OBJECT_retrieve_by_subject(store->objs, type, name); X509_STORE_unlock(store); if (tmp == NULL || type == X509_LU_CRL) { for (i = 0; i < sk_X509_LOOKUP_num(store->get_cert_methods); i++) { lu = sk_X509_LOOKUP_value(store->get_cert_methods, i); if (lu->skip) continue; if (lu->method == NULL) return -1; j = X509_LOOKUP_by_subject_ex(lu, type, name, &stmp, ctx->libctx, ctx->propq); if (j != 0) { /* non-zero value is considered success here */ tmp = &stmp; break; } } if (tmp == NULL) return 0; } if (!X509_OBJECT_up_ref_count(tmp)) return -1; ret->type = tmp->type; ret->data.ptr = tmp->data.ptr; return 1; } /* Also fill the cache |ctx->store->objs| with all matching certificates. */ int X509_STORE_CTX_get_by_subject(const X509_STORE_CTX *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret) { return ossl_x509_store_ctx_get_by_subject(ctx, type, name, ret) > 0; } static int x509_store_add(X509_STORE *store, void *x, int crl) { X509_OBJECT *obj; int ret = 0, added = 0; if (x == NULL) return 0; obj = X509_OBJECT_new(); if (obj == NULL) return 0; if (crl) { obj->type = X509_LU_CRL; obj->data.crl = (X509_CRL *)x; } else { obj->type = X509_LU_X509; obj->data.x509 = (X509 *)x; } if (!X509_OBJECT_up_ref_count(obj)) { obj->type = X509_LU_NONE; X509_OBJECT_free(obj); return 0; } if (!X509_STORE_lock(store)) { obj->type = X509_LU_NONE; X509_OBJECT_free(obj); return 0; } if (X509_OBJECT_retrieve_match(store->objs, obj)) { ret = 1; } else { added = sk_X509_OBJECT_push(store->objs, obj); ret = added != 0; } X509_STORE_unlock(store); if (added == 0) /* obj not pushed */ X509_OBJECT_free(obj); return ret; } int X509_STORE_add_cert(X509_STORE *xs, X509 *x) { if (!x509_store_add(xs, x, 0)) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); return 0; } return 1; } int X509_STORE_add_crl(X509_STORE *xs, X509_CRL *x) { if (!x509_store_add(xs, x, 1)) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); return 0; } return 1; } int X509_OBJECT_up_ref_count(X509_OBJECT *a) { switch (a->type) { case X509_LU_NONE: break; case X509_LU_X509: return X509_up_ref(a->data.x509); case X509_LU_CRL: return X509_CRL_up_ref(a->data.crl); } return 1; } X509 *X509_OBJECT_get0_X509(const X509_OBJECT *a) { if (a == NULL || a->type != X509_LU_X509) return NULL; return a->data.x509; } X509_CRL *X509_OBJECT_get0_X509_CRL(const X509_OBJECT *a) { if (a == NULL || a->type != X509_LU_CRL) return NULL; return a->data.crl; } X509_LOOKUP_TYPE X509_OBJECT_get_type(const X509_OBJECT *a) { return a->type; } X509_OBJECT *X509_OBJECT_new(void) { X509_OBJECT *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->type = X509_LU_NONE; return ret; } static void x509_object_free_internal(X509_OBJECT *a) { if (a == NULL) return; switch (a->type) { case X509_LU_NONE: break; case X509_LU_X509: X509_free(a->data.x509); break; case X509_LU_CRL: X509_CRL_free(a->data.crl); break; } } int X509_OBJECT_set1_X509(X509_OBJECT *a, X509 *obj) { if (a == NULL || !X509_up_ref(obj)) return 0; x509_object_free_internal(a); a->type = X509_LU_X509; a->data.x509 = obj; return 1; } int X509_OBJECT_set1_X509_CRL(X509_OBJECT *a, X509_CRL *obj) { if (a == NULL || !X509_CRL_up_ref(obj)) return 0; x509_object_free_internal(a); a->type = X509_LU_CRL; a->data.crl = obj; return 1; } void X509_OBJECT_free(X509_OBJECT *a) { x509_object_free_internal(a); OPENSSL_free(a); } /* Returns -1 if not found, but also on error */ static int x509_object_idx_cnt(STACK_OF(X509_OBJECT) *h, X509_LOOKUP_TYPE type, const X509_NAME *name, int *pnmatch) { X509_OBJECT stmp; X509 x509_s; X509_CRL crl_s; stmp.type = type; switch (type) { case X509_LU_X509: stmp.data.x509 = &x509_s; x509_s.cert_info.subject = (X509_NAME *)name; /* won't modify it */ break; case X509_LU_CRL: stmp.data.crl = &crl_s; crl_s.crl.issuer = (X509_NAME *)name; /* won't modify it */ break; case X509_LU_NONE: default: /* abort(); */ return -1; } /* Assumes h is locked for read if applicable */ return sk_X509_OBJECT_find_all(h, &stmp, pnmatch); } /* Assumes h is locked for read if applicable */ int X509_OBJECT_idx_by_subject(STACK_OF(X509_OBJECT) *h, X509_LOOKUP_TYPE type, const X509_NAME *name) { return x509_object_idx_cnt(h, type, name, NULL); } /* Assumes h is locked for read if applicable */ X509_OBJECT *X509_OBJECT_retrieve_by_subject(STACK_OF(X509_OBJECT) *h, X509_LOOKUP_TYPE type, const X509_NAME *name) { int idx = X509_OBJECT_idx_by_subject(h, type, name); if (idx == -1) return NULL; return sk_X509_OBJECT_value(h, idx); } STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(const X509_STORE *xs) { return xs->objs; } static X509_OBJECT *x509_object_dup(const X509_OBJECT *obj) { X509_OBJECT *ret = X509_OBJECT_new(); if (ret == NULL) return NULL; ret->type = obj->type; ret->data = obj->data; X509_OBJECT_up_ref_count(ret); return ret; } STACK_OF(X509_OBJECT) *X509_STORE_get1_objects(X509_STORE *store) { STACK_OF(X509_OBJECT) *objs; if (store == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!x509_store_read_lock(store)) return NULL; objs = sk_X509_OBJECT_deep_copy(store->objs, x509_object_dup, X509_OBJECT_free); X509_STORE_unlock(store); return objs; } STACK_OF(X509) *X509_STORE_get1_all_certs(X509_STORE *store) { STACK_OF(X509) *sk; STACK_OF(X509_OBJECT) *objs; int i; if (store == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((sk = sk_X509_new_null()) == NULL) return NULL; if (!X509_STORE_lock(store)) goto out_free; sk_X509_OBJECT_sort(store->objs); objs = X509_STORE_get0_objects(store); for (i = 0; i < sk_X509_OBJECT_num(objs); i++) { X509 *cert = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i)); if (cert != NULL && !X509_add_cert(sk, cert, X509_ADD_FLAG_UP_REF)) goto err; } X509_STORE_unlock(store); return sk; err: X509_STORE_unlock(store); out_free: OSSL_STACK_OF_X509_free(sk); return NULL; } /* Returns NULL on internal/fatal error, empty stack if not found */ STACK_OF(X509) *X509_STORE_CTX_get1_certs(X509_STORE_CTX *ctx, const X509_NAME *nm) { int i, idx, cnt; STACK_OF(X509) *sk = NULL; X509 *x; X509_OBJECT *obj; X509_STORE *store = ctx->store; if (store == NULL) return sk_X509_new_null(); if (!X509_STORE_lock(store)) return NULL; sk_X509_OBJECT_sort(store->objs); idx = x509_object_idx_cnt(store->objs, X509_LU_X509, nm, &cnt); if (idx < 0) { /* * Nothing found in cache: do lookup to possibly add new objects to * cache */ X509_OBJECT *xobj = X509_OBJECT_new(); X509_STORE_unlock(store); if (xobj == NULL) return NULL; i = ossl_x509_store_ctx_get_by_subject(ctx, X509_LU_X509, nm, xobj); if (i <= 0) { X509_OBJECT_free(xobj); return i < 0 ? NULL : sk_X509_new_null(); } X509_OBJECT_free(xobj); if (!X509_STORE_lock(store)) return NULL; sk_X509_OBJECT_sort(store->objs); idx = x509_object_idx_cnt(store->objs, X509_LU_X509, nm, &cnt); if (idx < 0) { sk = sk_X509_new_null(); goto end; } } sk = sk_X509_new_null(); if (sk == NULL) goto end; for (i = 0; i < cnt; i++, idx++) { obj = sk_X509_OBJECT_value(store->objs, idx); x = obj->data.x509; if (!X509_add_cert(sk, x, X509_ADD_FLAG_UP_REF)) { X509_STORE_unlock(store); OSSL_STACK_OF_X509_free(sk); return NULL; } } end: X509_STORE_unlock(store); return sk; } /* Returns NULL on internal/fatal error, empty stack if not found */ STACK_OF(X509_CRL) *X509_STORE_CTX_get1_crls(const X509_STORE_CTX *ctx, const X509_NAME *nm) { int i = 1, idx, cnt; STACK_OF(X509_CRL) *sk = sk_X509_CRL_new_null(); X509_CRL *x; X509_OBJECT *obj, *xobj = X509_OBJECT_new(); X509_STORE *store = ctx->store; /* Always do lookup to possibly add new CRLs to cache */ if (sk == NULL || xobj == NULL || (i = ossl_x509_store_ctx_get_by_subject(ctx, X509_LU_CRL, nm, xobj)) < 0) { X509_OBJECT_free(xobj); sk_X509_CRL_free(sk); return NULL; } X509_OBJECT_free(xobj); if (i == 0) return sk; if (!X509_STORE_lock(store)) { sk_X509_CRL_free(sk); return NULL; } sk_X509_OBJECT_sort(store->objs); idx = x509_object_idx_cnt(store->objs, X509_LU_CRL, nm, &cnt); if (idx < 0) { X509_STORE_unlock(store); return sk; } for (i = 0; i < cnt; i++, idx++) { obj = sk_X509_OBJECT_value(store->objs, idx); x = obj->data.crl; if (!X509_CRL_up_ref(x)) { X509_STORE_unlock(store); sk_X509_CRL_pop_free(sk, X509_CRL_free); return NULL; } if (!sk_X509_CRL_push(sk, x)) { X509_STORE_unlock(store); X509_CRL_free(x); sk_X509_CRL_pop_free(sk, X509_CRL_free); return NULL; } } X509_STORE_unlock(store); return sk; } X509_OBJECT *X509_OBJECT_retrieve_match(STACK_OF(X509_OBJECT) *h, X509_OBJECT *x) { int idx, i, num; X509_OBJECT *obj; idx = sk_X509_OBJECT_find(h, x); if (idx < 0) return NULL; if ((x->type != X509_LU_X509) && (x->type != X509_LU_CRL)) return sk_X509_OBJECT_value(h, idx); for (i = idx, num = sk_X509_OBJECT_num(h); i < num; i++) { obj = sk_X509_OBJECT_value(h, i); if (x509_object_cmp((const X509_OBJECT **)&obj, (const X509_OBJECT **)&x)) return NULL; if (x->type == X509_LU_X509) { if (!X509_cmp(obj->data.x509, x->data.x509)) return obj; } else if (x->type == X509_LU_CRL) { if (X509_CRL_match(obj->data.crl, x->data.crl) == 0) return obj; } else { return obj; } } return NULL; } /*- * Try to get issuer cert from |ctx->store| matching the subject name of |x|. * Prefer the first non-expired one, else take the most recently expired one. * * Return values are: * 1 lookup successful. * 0 certificate not found. * -1 some other error. */ int X509_STORE_CTX_get1_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *x) { const X509_NAME *xn; X509_OBJECT *obj = X509_OBJECT_new(), *pobj = NULL; X509_STORE *store = ctx->store; int i, ok, idx, ret, nmatch = 0; if (obj == NULL) return -1; *issuer = NULL; xn = X509_get_issuer_name(x); ok = ossl_x509_store_ctx_get_by_subject(ctx, X509_LU_X509, xn, obj); if (ok != 1) { X509_OBJECT_free(obj); return ok; } /* If certificate matches and is currently valid all OK */ if (ctx->check_issued(ctx, x, obj->data.x509)) { if (ossl_x509_check_cert_time(ctx, obj->data.x509, -1)) { *issuer = obj->data.x509; /* |*issuer| has taken over the cert reference from |obj| */ obj->type = X509_LU_NONE; X509_OBJECT_free(obj); return 1; } } X509_OBJECT_free(obj); /* * Due to limitations of the API this can only retrieve a single cert. * However it will fill the cache with all matching certificates, * so we can examine the cache for all matches. */ if (store == NULL) return 0; /* Find index of first currently valid cert accepted by 'check_issued' */ ret = 0; if (!X509_STORE_lock(store)) return 0; sk_X509_OBJECT_sort(store->objs); idx = x509_object_idx_cnt(store->objs, X509_LU_X509, xn, &nmatch); if (idx != -1) { /* should be true as we've had at least one match */ /* Look through all matching certs for suitable issuer */ for (i = idx; i < idx + nmatch; i++) { pobj = sk_X509_OBJECT_value(store->objs, i); /* See if we've run past the matches */ if (pobj->type != X509_LU_X509) break; if (ctx->check_issued(ctx, x, pobj->data.x509)) { ret = 1; /* If times check fine, exit with match, else keep looking. */ if (ossl_x509_check_cert_time(ctx, pobj->data.x509, -1)) { *issuer = pobj->data.x509; break; } /* * Leave the so far most recently expired match in *issuer * so we return nearest match if no certificate time is OK. */ if (*issuer == NULL || ASN1_TIME_compare(X509_get0_notAfter(pobj->data.x509), X509_get0_notAfter(*issuer)) > 0) *issuer = pobj->data.x509; } } } if (*issuer != NULL && !X509_up_ref(*issuer)) { *issuer = NULL; ret = -1; } X509_STORE_unlock(store); return ret; } int X509_STORE_set_flags(X509_STORE *xs, unsigned long flags) { return X509_VERIFY_PARAM_set_flags(xs->param, flags); } int X509_STORE_set_depth(X509_STORE *xs, int depth) { X509_VERIFY_PARAM_set_depth(xs->param, depth); return 1; } int X509_STORE_set_purpose(X509_STORE *xs, int purpose) { return X509_VERIFY_PARAM_set_purpose(xs->param, purpose); } int X509_STORE_set_trust(X509_STORE *xs, int trust) { return X509_VERIFY_PARAM_set_trust(xs->param, trust); } int X509_STORE_set1_param(X509_STORE *xs, const X509_VERIFY_PARAM *param) { return X509_VERIFY_PARAM_set1(xs->param, param); } X509_VERIFY_PARAM *X509_STORE_get0_param(const X509_STORE *xs) { return xs->param; } void X509_STORE_set_verify(X509_STORE *xs, X509_STORE_CTX_verify_fn verify) { xs->verify = verify; } X509_STORE_CTX_verify_fn X509_STORE_get_verify(const X509_STORE *xs) { return xs->verify; } void X509_STORE_set_verify_cb(X509_STORE *xs, X509_STORE_CTX_verify_cb verify_cb) { xs->verify_cb = verify_cb; } X509_STORE_CTX_verify_cb X509_STORE_get_verify_cb(const X509_STORE *xs) { return xs->verify_cb; } void X509_STORE_set_get_issuer(X509_STORE *xs, X509_STORE_CTX_get_issuer_fn get_issuer) { xs->get_issuer = get_issuer; } X509_STORE_CTX_get_issuer_fn X509_STORE_get_get_issuer(const X509_STORE *xs) { return xs->get_issuer; } void X509_STORE_set_check_issued(X509_STORE *xs, X509_STORE_CTX_check_issued_fn check_issued) { xs->check_issued = check_issued; } X509_STORE_CTX_check_issued_fn X509_STORE_get_check_issued(const X509_STORE *xs) { return xs->check_issued; } void X509_STORE_set_check_revocation(X509_STORE *xs, X509_STORE_CTX_check_revocation_fn cb) { xs->check_revocation = cb; } X509_STORE_CTX_check_revocation_fn X509_STORE_get_check_revocation(const X509_STORE *xs) { return xs->check_revocation; } void X509_STORE_set_get_crl(X509_STORE *xs, X509_STORE_CTX_get_crl_fn get_crl) { xs->get_crl = get_crl; } X509_STORE_CTX_get_crl_fn X509_STORE_get_get_crl(const X509_STORE *xs) { return xs->get_crl; } void X509_STORE_set_check_crl(X509_STORE *xs, X509_STORE_CTX_check_crl_fn check_crl) { xs->check_crl = check_crl; } X509_STORE_CTX_check_crl_fn X509_STORE_get_check_crl(const X509_STORE *xs) { return xs->check_crl; } void X509_STORE_set_cert_crl(X509_STORE *xs, X509_STORE_CTX_cert_crl_fn cert_crl) { xs->cert_crl = cert_crl; } X509_STORE_CTX_cert_crl_fn X509_STORE_get_cert_crl(const X509_STORE *xs) { return xs->cert_crl; } void X509_STORE_set_check_policy(X509_STORE *xs, X509_STORE_CTX_check_policy_fn check_policy) { xs->check_policy = check_policy; } X509_STORE_CTX_check_policy_fn X509_STORE_get_check_policy(const X509_STORE *xs) { return xs->check_policy; } void X509_STORE_set_lookup_certs(X509_STORE *xs, X509_STORE_CTX_lookup_certs_fn lookup_certs) { xs->lookup_certs = lookup_certs; } X509_STORE_CTX_lookup_certs_fn X509_STORE_get_lookup_certs(const X509_STORE *xs) { return xs->lookup_certs; } void X509_STORE_set_lookup_crls(X509_STORE *xs, X509_STORE_CTX_lookup_crls_fn lookup_crls) { xs->lookup_crls = lookup_crls; } X509_STORE_CTX_lookup_crls_fn X509_STORE_get_lookup_crls(const X509_STORE *xs) { return xs->lookup_crls; } void X509_STORE_set_cleanup(X509_STORE *xs, X509_STORE_CTX_cleanup_fn cleanup) { xs->cleanup = cleanup; } X509_STORE_CTX_cleanup_fn X509_STORE_get_cleanup(const X509_STORE *xs) { return xs->cleanup; } int X509_STORE_set_ex_data(X509_STORE *xs, int idx, void *data) { return CRYPTO_set_ex_data(&xs->ex_data, idx, data); } void *X509_STORE_get_ex_data(const X509_STORE *xs, int idx) { return CRYPTO_get_ex_data(&xs->ex_data, idx); } X509_STORE *X509_STORE_CTX_get0_store(const X509_STORE_CTX *ctx) { return ctx->store; }
./openssl/crypto/x509/t_crl.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/buffer.h> #include <openssl/bn.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #ifndef OPENSSL_NO_STDIO int X509_CRL_print_fp(FILE *fp, X509_CRL *x) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = X509_CRL_print(b, x); BIO_free(b); return ret; } #endif int X509_CRL_print(BIO *out, X509_CRL *x) { return X509_CRL_print_ex(out, x, XN_FLAG_COMPAT); } int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag) { STACK_OF(X509_REVOKED) *rev; X509_REVOKED *r; const X509_ALGOR *sig_alg; const ASN1_BIT_STRING *sig; long l; int i; BIO_printf(out, "Certificate Revocation List (CRL):\n"); l = X509_CRL_get_version(x); if (l >= X509_CRL_VERSION_1 && l <= X509_CRL_VERSION_2) BIO_printf(out, "%8sVersion %ld (0x%lx)\n", "", l + 1, (unsigned long)l); else BIO_printf(out, "%8sVersion unknown (%ld)\n", "", l); X509_CRL_get0_signature(x, &sig, &sig_alg); BIO_puts(out, " "); X509_signature_print(out, sig_alg, NULL); BIO_printf(out, "%8sIssuer: ", ""); X509_NAME_print_ex(out, X509_CRL_get_issuer(x), 0, nmflag); BIO_puts(out, "\n"); BIO_printf(out, "%8sLast Update: ", ""); ASN1_TIME_print(out, X509_CRL_get0_lastUpdate(x)); BIO_printf(out, "\n%8sNext Update: ", ""); if (X509_CRL_get0_nextUpdate(x)) ASN1_TIME_print(out, X509_CRL_get0_nextUpdate(x)); else BIO_printf(out, "NONE"); BIO_printf(out, "\n"); X509V3_extensions_print(out, "CRL extensions", X509_CRL_get0_extensions(x), 0, 8); rev = X509_CRL_get_REVOKED(x); if (sk_X509_REVOKED_num(rev) > 0) BIO_printf(out, "Revoked Certificates:\n"); else BIO_printf(out, "No Revoked Certificates.\n"); for (i = 0; i < sk_X509_REVOKED_num(rev); i++) { r = sk_X509_REVOKED_value(rev, i); BIO_printf(out, " Serial Number: "); i2a_ASN1_INTEGER(out, X509_REVOKED_get0_serialNumber(r)); BIO_printf(out, "\n Revocation Date: "); ASN1_TIME_print(out, X509_REVOKED_get0_revocationDate(r)); BIO_printf(out, "\n"); X509V3_extensions_print(out, "CRL entry extensions", X509_REVOKED_get0_extensions(r), 0, 8); } X509_signature_print(out, sig_alg, sig); return 1; }
./openssl/crypto/x509/x509_d2.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 <openssl/crypto.h> #include <openssl/x509.h> int X509_STORE_set_default_paths_ex(X509_STORE *ctx, OSSL_LIB_CTX *libctx, const char *propq) { X509_LOOKUP *lookup; lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_file()); if (lookup == NULL) return 0; X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT, libctx, propq); lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_hash_dir()); if (lookup == NULL) return 0; X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT); lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_store()); if (lookup == NULL) return 0; X509_LOOKUP_add_store_ex(lookup, NULL, libctx, propq); /* clear any errors */ ERR_clear_error(); return 1; } int X509_STORE_set_default_paths(X509_STORE *ctx) { return X509_STORE_set_default_paths_ex(ctx, NULL, NULL); } int X509_STORE_load_file_ex(X509_STORE *ctx, const char *file, OSSL_LIB_CTX *libctx, const char *propq) { X509_LOOKUP *lookup; if (file == NULL || (lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_file())) == NULL || X509_LOOKUP_load_file_ex(lookup, file, X509_FILETYPE_PEM, libctx, propq) <= 0) return 0; return 1; } int X509_STORE_load_file(X509_STORE *ctx, const char *file) { return X509_STORE_load_file_ex(ctx, file, NULL, NULL); } int X509_STORE_load_path(X509_STORE *ctx, const char *path) { X509_LOOKUP *lookup; if (path == NULL || (lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_hash_dir())) == NULL || X509_LOOKUP_add_dir(lookup, path, X509_FILETYPE_PEM) <= 0) return 0; return 1; } int X509_STORE_load_store_ex(X509_STORE *ctx, const char *uri, OSSL_LIB_CTX *libctx, const char *propq) { X509_LOOKUP *lookup; if (uri == NULL || (lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_store())) == NULL || X509_LOOKUP_add_store_ex(lookup, uri, libctx, propq) == 0) return 0; return 1; } int X509_STORE_load_store(X509_STORE *ctx, const char *uri) { return X509_STORE_load_store_ex(ctx, uri, NULL, NULL); } int X509_STORE_load_locations_ex(X509_STORE *ctx, const char *file, const char *path, OSSL_LIB_CTX *libctx, const char *propq) { if (file == NULL && path == NULL) return 0; if (file != NULL && !X509_STORE_load_file_ex(ctx, file, libctx, propq)) return 0; if (path != NULL && !X509_STORE_load_path(ctx, path)) return 0; return 1; } int X509_STORE_load_locations(X509_STORE *ctx, const char *file, const char *path) { return X509_STORE_load_locations_ex(ctx, file, path, NULL, NULL); }
./openssl/crypto/x509/v3_tlsf.c
/* * Copyright 2015-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 "internal/cryptlib.h" #include <stdio.h> #include <openssl/asn1t.h> #include <openssl/conf.h> #include <openssl/x509v3.h> #include "ext_dat.h" #include "x509_local.h" static STACK_OF(CONF_VALUE) *i2v_TLS_FEATURE(const X509V3_EXT_METHOD *method, TLS_FEATURE *tls_feature, STACK_OF(CONF_VALUE) *ext_list); static TLS_FEATURE *v2i_TLS_FEATURE(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval); ASN1_ITEM_TEMPLATE(TLS_FEATURE) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, TLS_FEATURE, ASN1_INTEGER) static_ASN1_ITEM_TEMPLATE_END(TLS_FEATURE) IMPLEMENT_ASN1_ALLOC_FUNCTIONS(TLS_FEATURE) const X509V3_EXT_METHOD ossl_v3_tls_feature = { NID_tlsfeature, 0, ASN1_ITEM_ref(TLS_FEATURE), 0, 0, 0, 0, 0, 0, (X509V3_EXT_I2V)i2v_TLS_FEATURE, (X509V3_EXT_V2I)v2i_TLS_FEATURE, 0, 0, NULL }; typedef struct { long num; const char *name; } TLS_FEATURE_NAME; static TLS_FEATURE_NAME tls_feature_tbl[] = { { 5, "status_request" }, { 17, "status_request_v2" } }; /* * i2v_TLS_FEATURE converts the TLS_FEATURE structure tls_feature into the * STACK_OF(CONF_VALUE) structure ext_list. STACK_OF(CONF_VALUE) is the format * used by the CONF library to represent a multi-valued extension. ext_list is * returned. */ static STACK_OF(CONF_VALUE) *i2v_TLS_FEATURE(const X509V3_EXT_METHOD *method, TLS_FEATURE *tls_feature, STACK_OF(CONF_VALUE) *ext_list) { int i; size_t j; ASN1_INTEGER *ai; long tlsextid; for (i = 0; i < sk_ASN1_INTEGER_num(tls_feature); i++) { ai = sk_ASN1_INTEGER_value(tls_feature, i); tlsextid = ASN1_INTEGER_get(ai); for (j = 0; j < OSSL_NELEM(tls_feature_tbl); j++) if (tlsextid == tls_feature_tbl[j].num) break; if (j < OSSL_NELEM(tls_feature_tbl)) X509V3_add_value(NULL, tls_feature_tbl[j].name, &ext_list); else X509V3_add_value_int(NULL, ai, &ext_list); } return ext_list; } /* * v2i_TLS_FEATURE converts the multi-valued extension nval into a TLS_FEATURE * structure, which is returned if the conversion is successful. In case of * error, NULL is returned. */ static TLS_FEATURE *v2i_TLS_FEATURE(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { TLS_FEATURE *tlsf; char *extval, *endptr; ASN1_INTEGER *ai = NULL; CONF_VALUE *val; int i; size_t j; long tlsextid; if ((tlsf = sk_ASN1_INTEGER_new_null()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); return NULL; } for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { val = sk_CONF_VALUE_value(nval, i); if (val->value) extval = val->value; else extval = val->name; for (j = 0; j < OSSL_NELEM(tls_feature_tbl); j++) if (OPENSSL_strcasecmp(extval, tls_feature_tbl[j].name) == 0) break; if (j < OSSL_NELEM(tls_feature_tbl)) tlsextid = tls_feature_tbl[j].num; else { tlsextid = strtol(extval, &endptr, 10); if (((*endptr) != '\0') || (extval == endptr) || (tlsextid < 0) || (tlsextid > 65535)) { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SYNTAX); X509V3_conf_add_error_name_value(val); goto err; } } if ((ai = ASN1_INTEGER_new()) == NULL || !ASN1_INTEGER_set(ai, tlsextid) || sk_ASN1_INTEGER_push(tlsf, ai) <= 0) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } /* So it doesn't get purged if an error occurs next time around */ ai = NULL; } return tlsf; err: sk_ASN1_INTEGER_pop_free(tlsf, ASN1_INTEGER_free); ASN1_INTEGER_free(ai); return NULL; }
./openssl/crypto/x509/v3_bitst.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/conf.h> #include <openssl/x509v3.h> #include "ext_dat.h" static BIT_STRING_BITNAME ns_cert_type_table[] = { {0, "SSL Client", "client"}, {1, "SSL Server", "server"}, {2, "S/MIME", "email"}, {3, "Object Signing", "objsign"}, {4, "Unused", "reserved"}, {5, "SSL CA", "sslCA"}, {6, "S/MIME CA", "emailCA"}, {7, "Object Signing CA", "objCA"}, {-1, NULL, NULL} }; static BIT_STRING_BITNAME key_usage_type_table[] = { {0, "Digital Signature", "digitalSignature"}, {1, "Non Repudiation", "nonRepudiation"}, {2, "Key Encipherment", "keyEncipherment"}, {3, "Data Encipherment", "dataEncipherment"}, {4, "Key Agreement", "keyAgreement"}, {5, "Certificate Sign", "keyCertSign"}, {6, "CRL Sign", "cRLSign"}, {7, "Encipher Only", "encipherOnly"}, {8, "Decipher Only", "decipherOnly"}, {-1, NULL, NULL} }; const X509V3_EXT_METHOD ossl_v3_nscert = EXT_BITSTRING(NID_netscape_cert_type, ns_cert_type_table); const X509V3_EXT_METHOD ossl_v3_key_usage = EXT_BITSTRING(NID_key_usage, key_usage_type_table); STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING(X509V3_EXT_METHOD *method, ASN1_BIT_STRING *bits, STACK_OF(CONF_VALUE) *ret) { BIT_STRING_BITNAME *bnam; for (bnam = method->usr_data; bnam->lname; bnam++) { if (ASN1_BIT_STRING_get_bit(bits, bnam->bitnum)) X509V3_add_value(bnam->lname, NULL, &ret); } return ret; } ASN1_BIT_STRING *v2i_ASN1_BIT_STRING(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { CONF_VALUE *val; ASN1_BIT_STRING *bs; int i; BIT_STRING_BITNAME *bnam; if ((bs = ASN1_BIT_STRING_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); return NULL; } for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { val = sk_CONF_VALUE_value(nval, i); for (bnam = method->usr_data; bnam->lname; bnam++) { if (strcmp(bnam->sname, val->name) == 0 || strcmp(bnam->lname, val->name) == 0) { if (!ASN1_BIT_STRING_set_bit(bs, bnam->bitnum, 1)) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); ASN1_BIT_STRING_free(bs); return NULL; } break; } } if (!bnam->lname) { ERR_raise_data(ERR_LIB_X509V3, X509V3_R_UNKNOWN_BIT_STRING_ARGUMENT, "%s", val->name); ASN1_BIT_STRING_free(bs); return NULL; } } return bs; }
./openssl/crypto/x509/v3_no_rev_avail.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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/x509v3.h> #include "ext_dat.h" static int i2r_NO_REV_AVAIL(X509V3_EXT_METHOD *method, void *su, BIO *out, int indent) { return 1; } static void *r2i_NO_REV_AVAIL(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *value) { return ASN1_NULL_new(); } static char *i2s_NO_REV_AVAIL(const X509V3_EXT_METHOD *method, void *val) { return OPENSSL_strdup("NULL"); } static void *s2i_NO_REV_AVAIL(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str) { return ASN1_NULL_new(); } /* * The noRevAvail X.509v3 extension is defined in ITU Recommendation X.509 * (2019), Section 17.2.2.7. See: https://www.itu.int/rec/T-REC-X.509-201910-I/en. */ const X509V3_EXT_METHOD ossl_v3_no_rev_avail = { NID_no_rev_avail, 0, ASN1_ITEM_ref(ASN1_NULL), 0, 0, 0, 0, (X509V3_EXT_I2S)i2s_NO_REV_AVAIL, (X509V3_EXT_S2I)s2i_NO_REV_AVAIL, 0, 0, (X509V3_EXT_I2R)i2r_NO_REV_AVAIL, (X509V3_EXT_R2I)r2i_NO_REV_AVAIL, NULL };
./openssl/crypto/x509/pcy_node.c
/* * Copyright 2004-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/asn1.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include "pcy_local.h" static int node_cmp(const X509_POLICY_NODE *const *a, const X509_POLICY_NODE *const *b) { return OBJ_cmp((*a)->data->valid_policy, (*b)->data->valid_policy); } STACK_OF(X509_POLICY_NODE) *ossl_policy_node_cmp_new(void) { return sk_X509_POLICY_NODE_new(node_cmp); } X509_POLICY_NODE *ossl_policy_tree_find_sk(STACK_OF(X509_POLICY_NODE) *nodes, const ASN1_OBJECT *id) { X509_POLICY_DATA n; X509_POLICY_NODE l; int idx; n.valid_policy = (ASN1_OBJECT *)id; l.data = &n; idx = sk_X509_POLICY_NODE_find(nodes, &l); return sk_X509_POLICY_NODE_value(nodes, idx); } X509_POLICY_NODE *ossl_policy_level_find_node(const X509_POLICY_LEVEL *level, const X509_POLICY_NODE *parent, const ASN1_OBJECT *id) { X509_POLICY_NODE *node; int i; for (i = 0; i < sk_X509_POLICY_NODE_num(level->nodes); i++) { node = sk_X509_POLICY_NODE_value(level->nodes, i); if (node->parent == parent) { if (!OBJ_cmp(node->data->valid_policy, id)) return node; } } return NULL; } X509_POLICY_NODE *ossl_policy_level_add_node(X509_POLICY_LEVEL *level, X509_POLICY_DATA *data, X509_POLICY_NODE *parent, X509_POLICY_TREE *tree, int extra_data) { X509_POLICY_NODE *node; /* Verify that the tree isn't too large. This mitigates CVE-2023-0464 */ if (tree->node_maximum > 0 && tree->node_count >= tree->node_maximum) return NULL; node = OPENSSL_zalloc(sizeof(*node)); if (node == NULL) return NULL; node->data = data; node->parent = parent; if (level != NULL) { if (OBJ_obj2nid(data->valid_policy) == NID_any_policy) { if (level->anyPolicy) goto node_error; level->anyPolicy = node; } else { if (level->nodes == NULL) level->nodes = ossl_policy_node_cmp_new(); if (level->nodes == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_X509_LIB); goto node_error; } if (!sk_X509_POLICY_NODE_push(level->nodes, node)) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto node_error; } } } if (extra_data) { if (tree->extra_data == NULL) tree->extra_data = sk_X509_POLICY_DATA_new_null(); if (tree->extra_data == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto extra_data_error; } if (!sk_X509_POLICY_DATA_push(tree->extra_data, data)) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto extra_data_error; } } tree->node_count++; if (parent) parent->nchild++; return node; extra_data_error: if (level != NULL) { if (level->anyPolicy == node) level->anyPolicy = NULL; else (void) sk_X509_POLICY_NODE_pop(level->nodes); } node_error: ossl_policy_node_free(node); return NULL; } void ossl_policy_node_free(X509_POLICY_NODE *node) { OPENSSL_free(node); } /* * See if a policy node matches a policy OID. If mapping enabled look through * expected policy set otherwise just valid policy. */ int ossl_policy_node_match(const X509_POLICY_LEVEL *lvl, const X509_POLICY_NODE *node, const ASN1_OBJECT *oid) { int i; ASN1_OBJECT *policy_oid; const X509_POLICY_DATA *x = node->data; if ((lvl->flags & X509_V_FLAG_INHIBIT_MAP) || !(x->flags & POLICY_DATA_FLAG_MAP_MASK)) { if (!OBJ_cmp(x->valid_policy, oid)) return 1; return 0; } for (i = 0; i < sk_ASN1_OBJECT_num(x->expected_policy_set); i++) { policy_oid = sk_ASN1_OBJECT_value(x->expected_policy_set, i); if (!OBJ_cmp(policy_oid, oid)) return 1; } return 0; }
./openssl/crypto/x509/v3_single_use.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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/x509v3.h> #include "ext_dat.h" static int i2r_SINGLE_USE(X509V3_EXT_METHOD *method, void *su, BIO *out, int indent) { return 1; } static void *r2i_SINGLE_USE(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *value) { return ASN1_NULL_new(); } static char *i2s_SINGLE_USE(const X509V3_EXT_METHOD *method, void *val) { return OPENSSL_strdup("NULL"); } static void *s2i_SINGLE_USE(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str) { return ASN1_NULL_new(); } /* * The singleUse X.509v3 extension is defined in ITU Recommendation X.509 * (2019), Section 17.1.2.5. See: https://www.itu.int/rec/T-REC-X.509-201910-I/en. */ const X509V3_EXT_METHOD ossl_v3_single_use = { NID_single_use, 0, ASN1_ITEM_ref(ASN1_NULL), 0, 0, 0, 0, (X509V3_EXT_I2S)i2s_SINGLE_USE, (X509V3_EXT_S2I)s2i_SINGLE_USE, 0, 0, (X509V3_EXT_I2R)i2r_SINGLE_USE, (X509V3_EXT_R2I)r2i_SINGLE_USE, NULL };
./openssl/crypto/x509/v3_ncons.c
/* * Copyright 2003-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/numbers.h" #include "internal/safe_math.h" #include <stdio.h> #include "crypto/asn1.h" #include <openssl/asn1t.h> #include <openssl/conf.h> #include <openssl/x509v3.h> #include <openssl/bn.h> #include "crypto/x509.h" #include "crypto/punycode.h" #include "ext_dat.h" OSSL_SAFE_MATH_SIGNED(int, int) static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval); static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a, BIO *bp, int ind); static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method, STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp, int ind, const char *name); static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip); static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc); static int nc_match_single(int effective_type, GENERAL_NAME *sub, GENERAL_NAME *gen); static int nc_dn(const X509_NAME *sub, const X509_NAME *nm); static int nc_dns(ASN1_IA5STRING *sub, ASN1_IA5STRING *dns); static int nc_email(ASN1_IA5STRING *sub, ASN1_IA5STRING *eml); static int nc_email_eai(ASN1_TYPE *emltype, ASN1_IA5STRING *base); static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base); static int nc_ip(ASN1_OCTET_STRING *ip, ASN1_OCTET_STRING *base); const X509V3_EXT_METHOD ossl_v3_name_constraints = { NID_name_constraints, 0, ASN1_ITEM_ref(NAME_CONSTRAINTS), 0, 0, 0, 0, 0, 0, 0, v2i_NAME_CONSTRAINTS, i2r_NAME_CONSTRAINTS, 0, NULL }; ASN1_SEQUENCE(GENERAL_SUBTREE) = { ASN1_SIMPLE(GENERAL_SUBTREE, base, GENERAL_NAME), ASN1_IMP_OPT(GENERAL_SUBTREE, minimum, ASN1_INTEGER, 0), ASN1_IMP_OPT(GENERAL_SUBTREE, maximum, ASN1_INTEGER, 1) } ASN1_SEQUENCE_END(GENERAL_SUBTREE) ASN1_SEQUENCE(NAME_CONSTRAINTS) = { ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, permittedSubtrees, GENERAL_SUBTREE, 0), ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, excludedSubtrees, GENERAL_SUBTREE, 1), } ASN1_SEQUENCE_END(NAME_CONSTRAINTS) IMPLEMENT_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE) IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS) #define IA5_OFFSET_LEN(ia5base, offset) \ ((ia5base)->length - ((unsigned char *)(offset) - (ia5base)->data)) /* Like memchr but for ASN1_IA5STRING. Additionally you can specify the * starting point to search from */ # define ia5memchr(str, start, c) memchr(start, c, IA5_OFFSET_LEN(str, start)) /* Like memrrchr but for ASN1_IA5STRING */ static char *ia5memrchr(ASN1_IA5STRING *str, int c) { int i; for (i = str->length; i > 0 && str->data[i - 1] != c; i--); if (i == 0) return NULL; return (char *)&str->data[i - 1]; } /* * We cannot use strncasecmp here because that applies locale specific rules. It * also doesn't work with ASN1_STRINGs that may have embedded NUL characters. * For example in Turkish 'I' is not the uppercase character for 'i'. We need to * do a simple ASCII case comparison ignoring the locale (that is why we use * numeric constants below). */ static int ia5ncasecmp(const char *s1, const char *s2, size_t n) { for (; n > 0; n--, s1++, s2++) { if (*s1 != *s2) { unsigned char c1 = (unsigned char)*s1, c2 = (unsigned char)*s2; /* Convert to lower case */ if (c1 >= 0x41 /* A */ && c1 <= 0x5A /* Z */) c1 += 0x20; if (c2 >= 0x41 /* A */ && c2 <= 0x5A /* Z */) c2 += 0x20; if (c1 == c2) continue; if (c1 < c2) return -1; /* c1 > c2 */ return 1; } } return 0; } static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { int i; CONF_VALUE tval, *val; STACK_OF(GENERAL_SUBTREE) **ptree = NULL; NAME_CONSTRAINTS *ncons = NULL; GENERAL_SUBTREE *sub = NULL; ncons = NAME_CONSTRAINTS_new(); if (ncons == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { val = sk_CONF_VALUE_value(nval, i); if (HAS_PREFIX(val->name, "permitted") && val->name[9]) { ptree = &ncons->permittedSubtrees; tval.name = val->name + 10; } else if (HAS_PREFIX(val->name, "excluded") && val->name[8]) { ptree = &ncons->excludedSubtrees; tval.name = val->name + 9; } else { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SYNTAX); goto err; } tval.value = val->value; sub = GENERAL_SUBTREE_new(); if (sub == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } if (!v2i_GENERAL_NAME_ex(sub->base, method, ctx, &tval, 1)) { ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB); goto err; } if (*ptree == NULL) *ptree = sk_GENERAL_SUBTREE_new_null(); if (*ptree == NULL || !sk_GENERAL_SUBTREE_push(*ptree, sub)) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto err; } sub = NULL; } return ncons; err: NAME_CONSTRAINTS_free(ncons); GENERAL_SUBTREE_free(sub); return NULL; } static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a, BIO *bp, int ind) { NAME_CONSTRAINTS *ncons = a; do_i2r_name_constraints(method, ncons->permittedSubtrees, bp, ind, "Permitted"); if (ncons->permittedSubtrees && ncons->excludedSubtrees) BIO_puts(bp, "\n"); do_i2r_name_constraints(method, ncons->excludedSubtrees, bp, ind, "Excluded"); return 1; } static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method, STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp, int ind, const char *name) { GENERAL_SUBTREE *tree; int i; if (sk_GENERAL_SUBTREE_num(trees) > 0) BIO_printf(bp, "%*s%s:\n", ind, "", name); for (i = 0; i < sk_GENERAL_SUBTREE_num(trees); i++) { if (i > 0) BIO_puts(bp, "\n"); tree = sk_GENERAL_SUBTREE_value(trees, i); BIO_printf(bp, "%*s", ind + 2, ""); if (tree->base->type == GEN_IPADD) print_nc_ipadd(bp, tree->base->d.ip); else GENERAL_NAME_print(bp, tree->base); } return 1; } static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip) { /* ip->length should be 8 or 32 and len1 == len2 == 4 or len1 == len2 == 16 */ int len1 = ip->length >= 16 ? 16 : ip->length >= 4 ? 4 : ip->length; int len2 = ip->length - len1; char *ip1 = ossl_ipaddr_to_asc(ip->data, len1); char *ip2 = ossl_ipaddr_to_asc(ip->data + len1, len2); int ret = ip1 != NULL && ip2 != NULL && BIO_printf(bp, "IP:%s/%s", ip1, ip2) > 0; OPENSSL_free(ip1); OPENSSL_free(ip2); return ret; } #define NAME_CHECK_MAX (1 << 20) static int add_lengths(int *out, int a, int b) { int err = 0; /* sk_FOO_num(NULL) returns -1 but is effectively 0 when iterating. */ if (a < 0) a = 0; if (b < 0) b = 0; *out = safe_add_int(a, b, &err); return !err; } /*- * Check a certificate conforms to a specified set of constraints. * Return values: * X509_V_OK: All constraints obeyed. * X509_V_ERR_PERMITTED_VIOLATION: Permitted subtree violation. * X509_V_ERR_EXCLUDED_VIOLATION: Excluded subtree violation. * X509_V_ERR_SUBTREE_MINMAX: Min or max values present and matching type. * X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: Unsupported constraint type. * X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: bad unsupported constraint syntax. * X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: bad or unsupported syntax of name */ int NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc) { int r, i, name_count, constraint_count; X509_NAME *nm; nm = X509_get_subject_name(x); /* * Guard against certificates with an excessive number of names or * constraints causing a computationally expensive name constraints check. */ if (!add_lengths(&name_count, X509_NAME_entry_count(nm), sk_GENERAL_NAME_num(x->altname)) || !add_lengths(&constraint_count, sk_GENERAL_SUBTREE_num(nc->permittedSubtrees), sk_GENERAL_SUBTREE_num(nc->excludedSubtrees)) || (name_count > 0 && constraint_count > NAME_CHECK_MAX / name_count)) return X509_V_ERR_UNSPECIFIED; if (X509_NAME_entry_count(nm) > 0) { GENERAL_NAME gntmp; gntmp.type = GEN_DIRNAME; gntmp.d.directoryName = nm; r = nc_match(&gntmp, nc); if (r != X509_V_OK) return r; gntmp.type = GEN_EMAIL; /* Process any email address attributes in subject name */ for (i = -1;;) { const X509_NAME_ENTRY *ne; i = X509_NAME_get_index_by_NID(nm, NID_pkcs9_emailAddress, i); if (i == -1) break; ne = X509_NAME_get_entry(nm, i); gntmp.d.rfc822Name = X509_NAME_ENTRY_get_data(ne); if (gntmp.d.rfc822Name->type != V_ASN1_IA5STRING) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; r = nc_match(&gntmp, nc); if (r != X509_V_OK) return r; } } for (i = 0; i < sk_GENERAL_NAME_num(x->altname); i++) { GENERAL_NAME *gen = sk_GENERAL_NAME_value(x->altname, i); r = nc_match(gen, nc); if (r != X509_V_OK) return r; } return X509_V_OK; } static int cn2dnsid(ASN1_STRING *cn, unsigned char **dnsid, size_t *idlen) { int utf8_length; unsigned char *utf8_value; int i; int isdnsname = 0; /* Don't leave outputs uninitialized */ *dnsid = NULL; *idlen = 0; /*- * Per RFC 6125, DNS-IDs representing internationalized domain names appear * in certificates in A-label encoded form: * * https://tools.ietf.org/html/rfc6125#section-6.4.2 * * The same applies to CNs which are intended to represent DNS names. * However, while in the SAN DNS-IDs are IA5Strings, as CNs they may be * needlessly encoded in 16-bit Unicode. We perform a conversion to UTF-8 * to ensure that we get an ASCII representation of any CNs that are * representable as ASCII, but just not encoded as ASCII. The UTF-8 form * may contain some non-ASCII octets, and that's fine, such CNs are not * valid legacy DNS names. * * Note, 'int' is the return type of ASN1_STRING_to_UTF8() so that's what * we must use for 'utf8_length'. */ if ((utf8_length = ASN1_STRING_to_UTF8(&utf8_value, cn)) < 0) return X509_V_ERR_OUT_OF_MEM; /* * Some certificates have had names that include a *trailing* NUL byte. * Remove these harmless NUL characters. They would otherwise yield false * alarms with the following embedded NUL check. */ while (utf8_length > 0 && utf8_value[utf8_length - 1] == '\0') --utf8_length; /* Reject *embedded* NULs */ if (memchr(utf8_value, 0, utf8_length) != NULL) { OPENSSL_free(utf8_value); return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; } /* * XXX: Deviation from strict DNS name syntax, also check names with '_' * Check DNS name syntax, any '-' or '.' must be internal, * and on either side of each '.' we can't have a '-' or '.'. * * If the name has just one label, we don't consider it a DNS name. This * means that "CN=sometld" cannot be precluded by DNS name constraints, but * that is not a problem. */ for (i = 0; i < utf8_length; ++i) { unsigned char c = utf8_value[i]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') continue; /* Dot and hyphen cannot be first or last. */ if (i > 0 && i < utf8_length - 1) { if (c == '-') continue; /* * Next to a dot the preceding and following characters must not be * another dot or a hyphen. Otherwise, record that the name is * plausible, since it has two or more labels. */ if (c == '.' && utf8_value[i + 1] != '.' && utf8_value[i - 1] != '-' && utf8_value[i + 1] != '-') { isdnsname = 1; continue; } } isdnsname = 0; break; } if (isdnsname) { *dnsid = utf8_value; *idlen = (size_t)utf8_length; return X509_V_OK; } OPENSSL_free(utf8_value); return X509_V_OK; } /* * Check CN against DNS-ID name constraints. */ int NAME_CONSTRAINTS_check_CN(X509 *x, NAME_CONSTRAINTS *nc) { int r, i; const X509_NAME *nm = X509_get_subject_name(x); ASN1_STRING stmp; GENERAL_NAME gntmp; stmp.flags = 0; stmp.type = V_ASN1_IA5STRING; gntmp.type = GEN_DNS; gntmp.d.dNSName = &stmp; /* Process any commonName attributes in subject name */ for (i = -1;;) { X509_NAME_ENTRY *ne; ASN1_STRING *cn; unsigned char *idval; size_t idlen; i = X509_NAME_get_index_by_NID(nm, NID_commonName, i); if (i == -1) break; ne = X509_NAME_get_entry(nm, i); cn = X509_NAME_ENTRY_get_data(ne); /* Only process attributes that look like hostnames */ if ((r = cn2dnsid(cn, &idval, &idlen)) != X509_V_OK) return r; if (idlen == 0) continue; stmp.length = idlen; stmp.data = idval; r = nc_match(&gntmp, nc); OPENSSL_free(idval); if (r != X509_V_OK) return r; } return X509_V_OK; } /* * Return nonzero if the GeneralSubtree has valid 'minimum' field * (must be absent or 0) and valid 'maximum' field (must be absent). */ static int nc_minmax_valid(GENERAL_SUBTREE *sub) { BIGNUM *bn = NULL; int ok = 1; if (sub->maximum) ok = 0; if (sub->minimum) { bn = ASN1_INTEGER_to_BN(sub->minimum, NULL); if (bn == NULL || !BN_is_zero(bn)) ok = 0; BN_free(bn); } return ok; } static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc) { GENERAL_SUBTREE *sub; int i, r, match = 0; int effective_type = gen->type; /* * We need to compare not gen->type field but an "effective" type because * the otherName field may contain EAI email address treated specially * according to RFC 8398, section 6 */ if (effective_type == GEN_OTHERNAME && (OBJ_obj2nid(gen->d.otherName->type_id) == NID_id_on_SmtpUTF8Mailbox)) { effective_type = GEN_EMAIL; } /* * Permitted subtrees: if any subtrees exist of matching the type at * least one subtree must match. */ for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) { sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i); if (effective_type != sub->base->type || (effective_type == GEN_OTHERNAME && OBJ_cmp(gen->d.otherName->type_id, sub->base->d.otherName->type_id) != 0)) continue; if (!nc_minmax_valid(sub)) return X509_V_ERR_SUBTREE_MINMAX; /* If we already have a match don't bother trying any more */ if (match == 2) continue; if (match == 0) match = 1; r = nc_match_single(effective_type, gen, sub->base); if (r == X509_V_OK) match = 2; else if (r != X509_V_ERR_PERMITTED_VIOLATION) return r; } if (match == 1) return X509_V_ERR_PERMITTED_VIOLATION; /* Excluded subtrees: must not match any of these */ for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) { sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i); if (effective_type != sub->base->type || (effective_type == GEN_OTHERNAME && OBJ_cmp(gen->d.otherName->type_id, sub->base->d.otherName->type_id) != 0)) continue; if (!nc_minmax_valid(sub)) return X509_V_ERR_SUBTREE_MINMAX; r = nc_match_single(effective_type, gen, sub->base); if (r == X509_V_OK) return X509_V_ERR_EXCLUDED_VIOLATION; else if (r != X509_V_ERR_PERMITTED_VIOLATION) return r; } return X509_V_OK; } static int nc_match_single(int effective_type, GENERAL_NAME *gen, GENERAL_NAME *base) { switch (gen->type) { case GEN_OTHERNAME: switch (effective_type) { case GEN_EMAIL: /* * We are here only when we have SmtpUTF8 name, * so we match the value of othername with base->d.rfc822Name */ return nc_email_eai(gen->d.otherName->value, base->d.rfc822Name); default: return X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE; } case GEN_DIRNAME: return nc_dn(gen->d.directoryName, base->d.directoryName); case GEN_DNS: return nc_dns(gen->d.dNSName, base->d.dNSName); case GEN_EMAIL: return nc_email(gen->d.rfc822Name, base->d.rfc822Name); case GEN_URI: return nc_uri(gen->d.uniformResourceIdentifier, base->d.uniformResourceIdentifier); case GEN_IPADD: return nc_ip(gen->d.iPAddress, base->d.iPAddress); default: return X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE; } } /* * directoryName name constraint matching. The canonical encoding of * X509_NAME makes this comparison easy. It is matched if the subtree is a * subset of the name. */ static int nc_dn(const X509_NAME *nm, const X509_NAME *base) { /* Ensure canonical encodings are up to date. */ if (nm->modified && i2d_X509_NAME(nm, NULL) < 0) return X509_V_ERR_OUT_OF_MEM; if (base->modified && i2d_X509_NAME(base, NULL) < 0) return X509_V_ERR_OUT_OF_MEM; if (base->canon_enclen > nm->canon_enclen) return X509_V_ERR_PERMITTED_VIOLATION; if (memcmp(base->canon_enc, nm->canon_enc, base->canon_enclen)) return X509_V_ERR_PERMITTED_VIOLATION; return X509_V_OK; } static int nc_dns(ASN1_IA5STRING *dns, ASN1_IA5STRING *base) { char *baseptr = (char *)base->data; char *dnsptr = (char *)dns->data; /* Empty matches everything */ if (base->length == 0) return X509_V_OK; if (dns->length < base->length) return X509_V_ERR_PERMITTED_VIOLATION; /* * Otherwise can add zero or more components on the left so compare RHS * and if dns is longer and expect '.' as preceding character. */ if (dns->length > base->length) { dnsptr += dns->length - base->length; if (*baseptr != '.' && dnsptr[-1] != '.') return X509_V_ERR_PERMITTED_VIOLATION; } if (ia5ncasecmp(baseptr, dnsptr, base->length)) return X509_V_ERR_PERMITTED_VIOLATION; return X509_V_OK; } /* * This function implements comparison between ASCII/U-label in emltype * and A-label in base according to RFC 8398, section 6. * Convert base to U-label and ASCII-parts of domain names, for base * Octet-to-octet comparison of `emltype` and `base` hostname parts * (ASCII-parts should be compared in case-insensitive manner) */ static int nc_email_eai(ASN1_TYPE *emltype, ASN1_IA5STRING *base) { ASN1_UTF8STRING *eml; char *baseptr = NULL; const char *emlptr; const char *emlat; char ulabel[256]; size_t size = sizeof(ulabel); int ret = X509_V_OK; size_t emlhostlen; /* We do not accept embedded NUL characters */ if (base->length > 0 && memchr(base->data, 0, base->length) != NULL) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; /* 'base' may not be NUL terminated. Create a copy that is */ baseptr = OPENSSL_strndup((char *)base->data, base->length); if (baseptr == NULL) return X509_V_ERR_OUT_OF_MEM; if (emltype->type != V_ASN1_UTF8STRING) { ret = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; goto end; } eml = emltype->value.utf8string; emlptr = (char *)eml->data; emlat = ia5memrchr(eml, '@'); if (emlat == NULL) { ret = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; goto end; } /* Special case: initial '.' is RHS match */ if (*baseptr == '.') { ulabel[0] = '.'; if (ossl_a2ulabel(baseptr, ulabel + 1, size - 1) <= 0) { ret = X509_V_ERR_UNSPECIFIED; goto end; } if ((size_t)eml->length > strlen(ulabel)) { emlptr += eml->length - strlen(ulabel); /* X509_V_OK */ if (ia5ncasecmp(ulabel, emlptr, strlen(ulabel)) == 0) goto end; } ret = X509_V_ERR_PERMITTED_VIOLATION; goto end; } if (ossl_a2ulabel(baseptr, ulabel, size) <= 0) { ret = X509_V_ERR_UNSPECIFIED; goto end; } /* Just have hostname left to match: case insensitive */ emlptr = emlat + 1; emlhostlen = IA5_OFFSET_LEN(eml, emlptr); if (emlhostlen != strlen(ulabel) || ia5ncasecmp(ulabel, emlptr, emlhostlen) != 0) { ret = X509_V_ERR_PERMITTED_VIOLATION; goto end; } end: OPENSSL_free(baseptr); return ret; } static int nc_email(ASN1_IA5STRING *eml, ASN1_IA5STRING *base) { const char *baseptr = (char *)base->data; const char *emlptr = (char *)eml->data; const char *baseat = ia5memrchr(base, '@'); const char *emlat = ia5memrchr(eml, '@'); size_t basehostlen, emlhostlen; if (!emlat) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; /* Special case: initial '.' is RHS match */ if (!baseat && base->length > 0 && (*baseptr == '.')) { if (eml->length > base->length) { emlptr += eml->length - base->length; if (ia5ncasecmp(baseptr, emlptr, base->length) == 0) return X509_V_OK; } return X509_V_ERR_PERMITTED_VIOLATION; } /* If we have anything before '@' match local part */ if (baseat) { if (baseat != baseptr) { if ((baseat - baseptr) != (emlat - emlptr)) return X509_V_ERR_PERMITTED_VIOLATION; if (memchr(baseptr, 0, baseat - baseptr) || memchr(emlptr, 0, emlat - emlptr)) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; /* Case sensitive match of local part */ if (strncmp(baseptr, emlptr, emlat - emlptr)) return X509_V_ERR_PERMITTED_VIOLATION; } /* Position base after '@' */ baseptr = baseat + 1; } emlptr = emlat + 1; basehostlen = IA5_OFFSET_LEN(base, baseptr); emlhostlen = IA5_OFFSET_LEN(eml, emlptr); /* Just have hostname left to match: case insensitive */ if (basehostlen != emlhostlen || ia5ncasecmp(baseptr, emlptr, emlhostlen)) return X509_V_ERR_PERMITTED_VIOLATION; return X509_V_OK; } static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base) { const char *baseptr = (char *)base->data; const char *hostptr = (char *)uri->data; const char *p = ia5memchr(uri, (char *)uri->data, ':'); int hostlen; /* Check for foo:// and skip past it */ if (p == NULL || IA5_OFFSET_LEN(uri, p) < 3 || p[1] != '/' || p[2] != '/') return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; hostptr = p + 3; /* Determine length of hostname part of URI */ /* Look for a port indicator as end of hostname first */ p = ia5memchr(uri, hostptr, ':'); /* Otherwise look for trailing slash */ if (p == NULL) p = ia5memchr(uri, hostptr, '/'); if (p == NULL) hostlen = IA5_OFFSET_LEN(uri, hostptr); else hostlen = p - hostptr; if (hostlen == 0) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; /* Special case: initial '.' is RHS match */ if (base->length > 0 && *baseptr == '.') { if (hostlen > base->length) { p = hostptr + hostlen - base->length; if (ia5ncasecmp(p, baseptr, base->length) == 0) return X509_V_OK; } return X509_V_ERR_PERMITTED_VIOLATION; } if ((base->length != (int)hostlen) || ia5ncasecmp(hostptr, baseptr, hostlen)) return X509_V_ERR_PERMITTED_VIOLATION; return X509_V_OK; } static int nc_ip(ASN1_OCTET_STRING *ip, ASN1_OCTET_STRING *base) { int hostlen, baselen, i; unsigned char *hostptr, *baseptr, *maskptr; hostptr = ip->data; hostlen = ip->length; baseptr = base->data; baselen = base->length; /* Invalid if not IPv4 or IPv6 */ if (!((hostlen == 4) || (hostlen == 16))) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; if (!((baselen == 8) || (baselen == 32))) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; /* Do not match IPv4 with IPv6 */ if (hostlen * 2 != baselen) return X509_V_ERR_PERMITTED_VIOLATION; maskptr = base->data + hostlen; /* Considering possible not aligned base ipAddress */ /* Not checking for wrong mask definition: i.e.: 255.0.255.0 */ for (i = 0; i < hostlen; i++) if ((hostptr[i] & maskptr[i]) != (baseptr[i] & maskptr[i])) return X509_V_ERR_PERMITTED_VIOLATION; return X509_V_OK; }
./openssl/crypto/x509/x509type.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> int X509_certificate_type(const X509 *x, const EVP_PKEY *pkey) { const EVP_PKEY *pk; int ret = 0, i; if (x == NULL) return 0; if (pkey == NULL) pk = X509_get0_pubkey(x); else pk = pkey; if (pk == NULL) return 0; switch (EVP_PKEY_get_id(pk)) { case EVP_PKEY_RSA: ret = EVP_PK_RSA | EVP_PKT_SIGN; /* if (!sign only extension) */ ret |= EVP_PKT_ENC; break; case EVP_PKEY_RSA_PSS: ret = EVP_PK_RSA | EVP_PKT_SIGN; break; case EVP_PKEY_DSA: ret = EVP_PK_DSA | EVP_PKT_SIGN; break; case EVP_PKEY_EC: ret = EVP_PK_EC | EVP_PKT_SIGN | EVP_PKT_EXCH; break; case EVP_PKEY_ED448: case EVP_PKEY_ED25519: ret = EVP_PKT_SIGN; break; case EVP_PKEY_DH: ret = EVP_PK_DH | EVP_PKT_EXCH; break; case NID_id_GostR3410_2001: case NID_id_GostR3410_2012_256: case NID_id_GostR3410_2012_512: ret = EVP_PKT_EXCH | EVP_PKT_SIGN; break; default: break; } i = X509_get_signature_nid(x); if (i && OBJ_find_sigid_algs(i, NULL, &i)) { switch (i) { case NID_rsaEncryption: case NID_rsa: ret |= EVP_PKS_RSA; break; case NID_dsa: case NID_dsa_2: ret |= EVP_PKS_DSA; break; case NID_X9_62_id_ecPublicKey: ret |= EVP_PKS_EC; break; default: break; } } return ret; }
./openssl/crypto/x509/t_req.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/buffer.h> #include <openssl/bn.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/rsa.h> #include <openssl/dsa.h> #ifndef OPENSSL_NO_STDIO int X509_REQ_print_fp(FILE *fp, X509_REQ *x) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = X509_REQ_print(b, x); BIO_free(b); return ret; } #endif int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflags, unsigned long cflag) { long l; int i; EVP_PKEY *pkey; STACK_OF(X509_EXTENSION) *exts; char mlch = ' '; int nmindent = 0, printok = 0; if ((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) { mlch = '\n'; nmindent = 12; } if (nmflags == XN_FLAG_COMPAT) printok = 1; if (!(cflag & X509_FLAG_NO_HEADER)) { if (BIO_write(bp, "Certificate Request:\n", 21) <= 0) goto err; if (BIO_write(bp, " Data:\n", 10) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_VERSION)) { l = X509_REQ_get_version(x); if (l == X509_REQ_VERSION_1) { if (BIO_printf(bp, "%8sVersion: %ld (0x%lx)\n", "", l + 1, (unsigned long)l) <= 0) goto err; } else { if (BIO_printf(bp, "%8sVersion: Unknown (%ld)\n", "", l) <= 0) goto err; } } if (!(cflag & X509_FLAG_NO_SUBJECT)) { if (BIO_printf(bp, " Subject:%c", mlch) <= 0) goto err; if (X509_NAME_print_ex(bp, X509_REQ_get_subject_name(x), nmindent, nmflags) < printok) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_PUBKEY)) { X509_PUBKEY *xpkey; ASN1_OBJECT *koid; if (BIO_write(bp, " Subject Public Key Info:\n", 33) <= 0) goto err; if (BIO_printf(bp, "%12sPublic Key Algorithm: ", "") <= 0) goto err; xpkey = X509_REQ_get_X509_PUBKEY(x); X509_PUBKEY_get0_param(&koid, NULL, NULL, NULL, xpkey); if (i2a_ASN1_OBJECT(bp, koid) <= 0) goto err; if (BIO_puts(bp, "\n") <= 0) goto err; pkey = X509_REQ_get0_pubkey(x); if (pkey == NULL) { if (BIO_printf(bp, "%12sUnable to load Public Key\n", "") <= 0) goto err; ERR_print_errors(bp); } else { if (EVP_PKEY_print_public(bp, pkey, 16, NULL) <= 0) goto err; } } if (!(cflag & X509_FLAG_NO_ATTRIBUTES)) { /* may not be */ if (BIO_printf(bp, "%8sAttributes:\n", "") <= 0) goto err; if (X509_REQ_get_attr_count(x) == 0) { if (BIO_printf(bp, "%12s(none)\n", "") <= 0) goto err; } else { for (i = 0; i < X509_REQ_get_attr_count(x); i++) { ASN1_TYPE *at; X509_ATTRIBUTE *a; ASN1_BIT_STRING *bs = NULL; ASN1_OBJECT *aobj; int j, type = 0, count = 1, ii = 0; a = X509_REQ_get_attr(x, i); aobj = X509_ATTRIBUTE_get0_object(a); if (X509_REQ_extension_nid(OBJ_obj2nid(aobj))) continue; if (BIO_printf(bp, "%12s", "") <= 0) goto err; if ((j = i2a_ASN1_OBJECT(bp, aobj)) > 0) { ii = 0; count = X509_ATTRIBUTE_count(a); if (count == 0) { ERR_raise(ERR_LIB_X509, X509_R_INVALID_ATTRIBUTES); return 0; } get_next: at = X509_ATTRIBUTE_get0_type(a, ii); type = at->type; bs = at->value.asn1_string; } for (j = 25 - j; j > 0; j--) if (BIO_write(bp, " ", 1) != 1) goto err; if (BIO_puts(bp, ":") <= 0) goto err; switch (type) { case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_NUMERICSTRING: case V_ASN1_UTF8STRING: case V_ASN1_IA5STRING: if (BIO_write(bp, (char *)bs->data, bs->length) != bs->length) goto err; if (BIO_puts(bp, "\n") <= 0) goto err; break; default: if (BIO_puts(bp, "unable to print attribute\n") <= 0) goto err; break; } if (++ii < count) goto get_next; } } } if (!(cflag & X509_FLAG_NO_EXTENSIONS)) { exts = X509_REQ_get_extensions(x); if (exts) { if (BIO_printf(bp, "%12sRequested Extensions:\n", "") <= 0) goto err; for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) { ASN1_OBJECT *obj; X509_EXTENSION *ex; int critical; ex = sk_X509_EXTENSION_value(exts, i); if (BIO_printf(bp, "%16s", "") <= 0) goto err; obj = X509_EXTENSION_get_object(ex); if (i2a_ASN1_OBJECT(bp, obj) <= 0) goto err; critical = X509_EXTENSION_get_critical(ex); if (BIO_printf(bp, ": %s\n", critical ? "critical" : "") <= 0) goto err; if (!X509V3_EXT_print(bp, ex, cflag, 20)) { if (BIO_printf(bp, "%20s", "") <= 0 || ASN1_STRING_print(bp, X509_EXTENSION_get_data(ex)) <= 0) goto err; } if (BIO_write(bp, "\n", 1) <= 0) goto err; } sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); } } if (!(cflag & X509_FLAG_NO_SIGDUMP)) { const X509_ALGOR *sig_alg; const ASN1_BIT_STRING *sig; X509_REQ_get0_signature(x, &sig, &sig_alg); if (!X509_signature_print(bp, sig_alg, sig)) goto err; } return 1; err: ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB); return 0; } int X509_REQ_print(BIO *bp, X509_REQ *x) { return X509_REQ_print_ex(bp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT); }
./openssl/crypto/x509/x509_vfy.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/deprecated.h" #include <stdio.h> #include <time.h> #include <errno.h> #include <limits.h> #include "crypto/ctype.h" #include "internal/cryptlib.h" #include <openssl/crypto.h> #include <openssl/buffer.h> #include <openssl/evp.h> #include <openssl/asn1.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/objects.h> #include <openssl/core_names.h> #include "internal/dane.h" #include "crypto/x509.h" #include "x509_local.h" /* CRL score values */ #define CRL_SCORE_NOCRITICAL 0x100 /* No unhandled critical extensions */ #define CRL_SCORE_SCOPE 0x080 /* certificate is within CRL scope */ #define CRL_SCORE_TIME 0x040 /* CRL times valid */ #define CRL_SCORE_ISSUER_NAME 0x020 /* Issuer name matches certificate */ #define CRL_SCORE_VALID /* If this score or above CRL is probably valid */ \ (CRL_SCORE_NOCRITICAL | CRL_SCORE_TIME | CRL_SCORE_SCOPE) #define CRL_SCORE_ISSUER_CERT 0x018 /* CRL issuer is certificate issuer */ #define CRL_SCORE_SAME_PATH 0x008 /* CRL issuer is on certificate path */ #define CRL_SCORE_AKID 0x004 /* CRL issuer matches CRL AKID */ #define CRL_SCORE_TIME_DELTA 0x002 /* Have a delta CRL with valid times */ static int x509_verify_x509(X509_STORE_CTX *ctx); static int x509_verify_rpk(X509_STORE_CTX *ctx); static int build_chain(X509_STORE_CTX *ctx); static int verify_chain(X509_STORE_CTX *ctx); static int verify_rpk(X509_STORE_CTX *ctx); static int dane_verify(X509_STORE_CTX *ctx); static int dane_verify_rpk(X509_STORE_CTX *ctx); static int null_callback(int ok, X509_STORE_CTX *e); static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer); static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x); static int check_extensions(X509_STORE_CTX *ctx); static int check_name_constraints(X509_STORE_CTX *ctx); static int check_id(X509_STORE_CTX *ctx); static int check_trust(X509_STORE_CTX *ctx, int num_untrusted); static int check_revocation(X509_STORE_CTX *ctx); static int check_cert(X509_STORE_CTX *ctx); static int check_policy(X509_STORE_CTX *ctx); static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x); static int check_dane_issuer(X509_STORE_CTX *ctx, int depth); static int check_cert_key_level(X509_STORE_CTX *ctx, X509 *cert); static int check_key_level(X509_STORE_CTX *ctx, EVP_PKEY *pkey); static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert); static int check_curve(X509 *cert); static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer, unsigned int *preasons, X509_CRL *crl, X509 *x); static int get_crl_delta(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x); static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pcrl_score, X509_CRL *base, STACK_OF(X509_CRL) *crls); static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer, int *pcrl_score); static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score, unsigned int *preasons); static int check_crl_path(X509_STORE_CTX *ctx, X509 *x); static int check_crl_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *cert_path, STACK_OF(X509) *crl_path); static int internal_verify(X509_STORE_CTX *ctx); static int null_callback(int ok, X509_STORE_CTX *e) { return ok; } /*- * Return 1 if given cert is considered self-signed, 0 if not, or -1 on error. * This actually verifies self-signedness only if requested. * It calls ossl_x509v3_cache_extensions() * to match issuer and subject names (i.e., the cert being self-issued) and any * present authority key identifier to match the subject key identifier, etc. */ int X509_self_signed(X509 *cert, int verify_signature) { EVP_PKEY *pkey; if ((pkey = X509_get0_pubkey(cert)) == NULL) { /* handles cert == NULL */ ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY); return -1; } if (!ossl_x509v3_cache_extensions(cert)) return -1; if ((cert->ex_flags & EXFLAG_SS) == 0) return 0; if (!verify_signature) return 1; return X509_verify(cert, pkey); } /* * Given a certificate, try and find an exact match in the store. * Returns 1 on success, 0 on not found, -1 on internal error. */ static int lookup_cert_match(X509 **result, X509_STORE_CTX *ctx, X509 *x) { STACK_OF(X509) *certs; X509 *xtmp = NULL; int i, ret; *result = NULL; /* Lookup all certs with matching subject name */ ERR_set_mark(); certs = ctx->lookup_certs(ctx, X509_get_subject_name(x)); ERR_pop_to_mark(); if (certs == NULL) return -1; /* Look for exact match */ for (i = 0; i < sk_X509_num(certs); i++) { xtmp = sk_X509_value(certs, i); if (X509_cmp(xtmp, x) == 0) break; xtmp = NULL; } ret = xtmp != NULL; if (ret) { if (!X509_up_ref(xtmp)) ret = -1; else *result = xtmp; } OSSL_STACK_OF_X509_free(certs); return ret; } /*- * Inform the verify callback of an error. * The error code is set to |err| if |err| is not X509_V_OK, else * |ctx->error| is left unchanged (under the assumption it is set elsewhere). * The error depth is |depth| if >= 0, else it defaults to |ctx->error_depth|. * The error cert is |x| if not NULL, else the cert in |ctx->chain| at |depth|. * * Returns 0 to abort verification with an error, non-zero to continue. */ static int verify_cb_cert(X509_STORE_CTX *ctx, X509 *x, int depth, int err) { if (depth < 0) depth = ctx->error_depth; else ctx->error_depth = depth; ctx->current_cert = x != NULL ? x : sk_X509_value(ctx->chain, depth); if (err != X509_V_OK) ctx->error = err; return ctx->verify_cb(0, ctx); } #define CB_FAIL_IF(cond, ctx, cert, depth, err) \ if ((cond) && verify_cb_cert(ctx, cert, depth, err) == 0) \ return 0 /*- * Inform the verify callback of an error, CRL-specific variant. Here, the * error depth and certificate are already set, we just specify the error * number. * * Returns 0 to abort verification with an error, non-zero to continue. */ static int verify_cb_crl(X509_STORE_CTX *ctx, int err) { ctx->error = err; return ctx->verify_cb(0, ctx); } /* Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int check_auth_level(X509_STORE_CTX *ctx) { int i; int num = sk_X509_num(ctx->chain); if (ctx->param->auth_level <= 0) return 1; for (i = 0; i < num; ++i) { X509 *cert = sk_X509_value(ctx->chain, i); /* * We've already checked the security of the leaf key, so here we only * check the security of issuer keys. */ CB_FAIL_IF(i > 0 && !check_cert_key_level(ctx, cert), ctx, cert, i, X509_V_ERR_CA_KEY_TOO_SMALL); /* * We also check the signature algorithm security of all certificates * except those of the trust anchor at index num-1. */ CB_FAIL_IF(i < num - 1 && !check_sig_level(ctx, cert), ctx, cert, i, X509_V_ERR_CA_MD_TOO_WEAK); } return 1; } /*- * Returns -1 on internal error. * Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int verify_rpk(X509_STORE_CTX *ctx) { /* Not much to verify on a RPK */ if (ctx->verify != NULL) return ctx->verify(ctx); return !!ctx->verify_cb(ctx->error == X509_V_OK, ctx); } /*- * Returns -1 on internal error. * Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int verify_chain(X509_STORE_CTX *ctx) { int err; int ok; if ((ok = build_chain(ctx)) <= 0 || (ok = check_extensions(ctx)) <= 0 || (ok = check_auth_level(ctx)) <= 0 || (ok = check_id(ctx)) <= 0 || (ok = X509_get_pubkey_parameters(NULL, ctx->chain) ? 1 : -1) <= 0 || (ok = ctx->check_revocation(ctx)) <= 0) return ok; err = X509_chain_check_suiteb(&ctx->error_depth, NULL, ctx->chain, ctx->param->flags); CB_FAIL_IF(err != X509_V_OK, ctx, NULL, ctx->error_depth, err); /* Verify chain signatures and expiration times */ ok = ctx->verify != NULL ? ctx->verify(ctx) : internal_verify(ctx); if (ok <= 0) return ok; if ((ok = check_name_constraints(ctx)) <= 0) return ok; #ifndef OPENSSL_NO_RFC3779 /* RFC 3779 path validation, now that CRL check has been done */ if ((ok = X509v3_asid_validate_path(ctx)) <= 0) return ok; if ((ok = X509v3_addr_validate_path(ctx)) <= 0) return ok; #endif /* If we get this far evaluate policies */ if ((ctx->param->flags & X509_V_FLAG_POLICY_CHECK) != 0) ok = ctx->check_policy(ctx); return ok; } int X509_STORE_CTX_verify(X509_STORE_CTX *ctx) { if (ctx == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return -1; } if (ctx->rpk != NULL) return x509_verify_rpk(ctx); if (ctx->cert == NULL && sk_X509_num(ctx->untrusted) >= 1) ctx->cert = sk_X509_value(ctx->untrusted, 0); return x509_verify_x509(ctx); } int X509_verify_cert(X509_STORE_CTX *ctx) { if (ctx == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return -1; } return (ctx->rpk != NULL) ? x509_verify_rpk(ctx) : x509_verify_x509(ctx); } /*- * Returns -1 on internal error. * Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int x509_verify_rpk(X509_STORE_CTX *ctx) { int ret; /* If the peer's public key is too weak, we can stop early. */ if (!check_key_level(ctx, ctx->rpk) && verify_cb_cert(ctx, NULL, 0, X509_V_ERR_EE_KEY_TOO_SMALL) == 0) return 0; /* Barring any data to verify the RPK, simply report it as untrusted */ ctx->error = X509_V_ERR_RPK_UNTRUSTED; ret = DANETLS_ENABLED(ctx->dane) ? dane_verify_rpk(ctx) : verify_rpk(ctx); /* * Safety-net. If we are returning an error, we must also set ctx->error, * so that the chain is not considered verified should the error be ignored * (e.g. TLS with SSL_VERIFY_NONE). */ if (ret <= 0 && ctx->error == X509_V_OK) ctx->error = X509_V_ERR_UNSPECIFIED; return ret; } /*- * Returns -1 on internal error. * Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int x509_verify_x509(X509_STORE_CTX *ctx) { int ret; if (ctx->cert == NULL) { ERR_raise(ERR_LIB_X509, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY); ctx->error = X509_V_ERR_INVALID_CALL; return -1; } if (ctx->chain != NULL) { /* * This X509_STORE_CTX has already been used to verify a cert. We * cannot do another one. */ ERR_raise(ERR_LIB_X509, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); ctx->error = X509_V_ERR_INVALID_CALL; return -1; } if (!ossl_x509_add_cert_new(&ctx->chain, ctx->cert, X509_ADD_FLAG_UP_REF)) { ctx->error = X509_V_ERR_OUT_OF_MEM; return -1; } ctx->num_untrusted = 1; /* If the peer's public key is too weak, we can stop early. */ CB_FAIL_IF(!check_cert_key_level(ctx, ctx->cert), ctx, ctx->cert, 0, X509_V_ERR_EE_KEY_TOO_SMALL); ret = DANETLS_ENABLED(ctx->dane) ? dane_verify(ctx) : verify_chain(ctx); /* * Safety-net. If we are returning an error, we must also set ctx->error, * so that the chain is not considered verified should the error be ignored * (e.g. TLS with SSL_VERIFY_NONE). */ if (ret <= 0 && ctx->error == X509_V_OK) ctx->error = X509_V_ERR_UNSPECIFIED; return ret; } static int sk_X509_contains(STACK_OF(X509) *sk, X509 *cert) { int i, n = sk_X509_num(sk); for (i = 0; i < n; i++) if (X509_cmp(sk_X509_value(sk, i), cert) == 0) return 1; return 0; } /* * Find in given STACK_OF(X509) |sk| an issuer cert (if any) of given cert |x|. * The issuer must not yet be in |ctx->chain|, yet allowing the exception that * |x| is self-issued and |ctx->chain| has just one element. * Prefer the first non-expired one, else take the most recently expired one. */ static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x) { int i; X509 *issuer, *rv = NULL; for (i = 0; i < sk_X509_num(sk); i++) { issuer = sk_X509_value(sk, i); if (ctx->check_issued(ctx, x, issuer) && (((x->ex_flags & EXFLAG_SI) != 0 && sk_X509_num(ctx->chain) == 1) || !sk_X509_contains(ctx->chain, issuer))) { if (ossl_x509_check_cert_time(ctx, issuer, -1)) return issuer; if (rv == NULL || ASN1_TIME_compare(X509_get0_notAfter(issuer), X509_get0_notAfter(rv)) > 0) rv = issuer; } } return rv; } /* Check that the given certificate |x| is issued by the certificate |issuer| */ static int check_issued(ossl_unused X509_STORE_CTX *ctx, X509 *x, X509 *issuer) { int err = ossl_x509_likely_issued(issuer, x); if (err == X509_V_OK) return 1; /* * SUBJECT_ISSUER_MISMATCH just means 'x' is clearly not issued by 'issuer'. * Every other error code likely indicates a real error. */ return 0; } /*- * Alternative get_issuer method: look up from a STACK_OF(X509) in other_ctx. * Returns -1 on internal error. */ static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x) { *issuer = find_issuer(ctx, ctx->other_ctx, x); if (*issuer == NULL) return 0; return X509_up_ref(*issuer) ? 1 : -1; } /*- * Alternative lookup method: look from a STACK stored in other_ctx. * Returns NULL on internal/fatal error, empty stack if not found. */ static STACK_OF(X509) *lookup_certs_sk(X509_STORE_CTX *ctx, const X509_NAME *nm) { STACK_OF(X509) *sk = sk_X509_new_null(); X509 *x; int i; if (sk == NULL) return NULL; for (i = 0; i < sk_X509_num(ctx->other_ctx); i++) { x = sk_X509_value(ctx->other_ctx, i); if (X509_NAME_cmp(nm, X509_get_subject_name(x)) == 0) { if (!X509_add_cert(sk, x, X509_ADD_FLAG_UP_REF)) { OSSL_STACK_OF_X509_free(sk); ctx->error = X509_V_ERR_OUT_OF_MEM; return NULL; } } } return sk; } /* * Check EE or CA certificate purpose. For trusted certificates explicit local * auxiliary trust can be used to override EKU-restrictions. * Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int check_purpose(X509_STORE_CTX *ctx, X509 *x, int purpose, int depth, int must_be_ca) { int tr_ok = X509_TRUST_UNTRUSTED; /* * For trusted certificates we want to see whether any auxiliary trust * settings trump the purpose constraints. * * This is complicated by the fact that the trust ordinals in * ctx->param->trust are entirely independent of the purpose ordinals in * ctx->param->purpose! * * What connects them is their mutual initialization via calls from * X509_STORE_CTX_set_default() into X509_VERIFY_PARAM_lookup() which sets * related values of both param->trust and param->purpose. It is however * typically possible to infer associated trust values from a purpose value * via the X509_PURPOSE API. * * Therefore, we can only check for trust overrides when the purpose we're * checking is the same as ctx->param->purpose and ctx->param->trust is * also set. */ if (depth >= ctx->num_untrusted && purpose == ctx->param->purpose) tr_ok = X509_check_trust(x, ctx->param->trust, X509_TRUST_NO_SS_COMPAT); switch (tr_ok) { case X509_TRUST_TRUSTED: return 1; case X509_TRUST_REJECTED: break; default: /* can only be X509_TRUST_UNTRUSTED */ switch (X509_check_purpose(x, purpose, must_be_ca > 0)) { case 1: return 1; case 0: break; default: if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) == 0) return 1; } break; } return verify_cb_cert(ctx, x, depth, X509_V_ERR_INVALID_PURPOSE); } /*- * Check extensions of a cert chain for consistency with the supplied purpose. * Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int check_extensions(X509_STORE_CTX *ctx) { int i, must_be_ca, plen = 0; X509 *x; int ret, proxy_path_length = 0; int purpose, allow_proxy_certs, num = sk_X509_num(ctx->chain); /*- * must_be_ca can have 1 of 3 values: * -1: we accept both CA and non-CA certificates, to allow direct * use of self-signed certificates (which are marked as CA). * 0: we only accept non-CA certificates. This is currently not * used, but the possibility is present for future extensions. * 1: we only accept CA certificates. This is currently used for * all certificates in the chain except the leaf certificate. */ must_be_ca = -1; /* CRL path validation */ if (ctx->parent != NULL) { allow_proxy_certs = 0; purpose = X509_PURPOSE_CRL_SIGN; } else { allow_proxy_certs = (ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS) != 0; purpose = ctx->param->purpose; } for (i = 0; i < num; i++) { x = sk_X509_value(ctx->chain, i); CB_FAIL_IF((ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) == 0 && (x->ex_flags & EXFLAG_CRITICAL) != 0, ctx, x, i, X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION); CB_FAIL_IF(!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY) != 0, ctx, x, i, X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED); ret = X509_check_ca(x); switch (must_be_ca) { case -1: CB_FAIL_IF((ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0 && ret != 1 && ret != 0, ctx, x, i, X509_V_ERR_INVALID_CA); break; case 0: CB_FAIL_IF(ret != 0, ctx, x, i, X509_V_ERR_INVALID_NON_CA); break; default: /* X509_V_FLAG_X509_STRICT is implicit for intermediate CAs */ CB_FAIL_IF(ret == 0 || ((i + 1 < num || (ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0) && ret != 1), ctx, x, i, X509_V_ERR_INVALID_CA); break; } if (num > 1) { /* Check for presence of explicit elliptic curve parameters */ ret = check_curve(x); CB_FAIL_IF(ret < 0, ctx, x, i, X509_V_ERR_UNSPECIFIED); CB_FAIL_IF(ret == 0, ctx, x, i, X509_V_ERR_EC_KEY_EXPLICIT_PARAMS); } /* * Do the following set of checks only if strict checking is requested * and not for self-issued (including self-signed) EE (non-CA) certs * because RFC 5280 does not apply to them according RFC 6818 section 2. */ if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0 && num > 1) { /* * this should imply * !(i == 0 && (x->ex_flags & EXFLAG_CA) == 0 * && (x->ex_flags & EXFLAG_SI) != 0) */ /* Check Basic Constraints according to RFC 5280 section 4.2.1.9 */ if (x->ex_pathlen != -1) { CB_FAIL_IF((x->ex_flags & EXFLAG_CA) == 0, ctx, x, i, X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA); CB_FAIL_IF((x->ex_kusage & KU_KEY_CERT_SIGN) == 0, ctx, x, i, X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN); } CB_FAIL_IF((x->ex_flags & EXFLAG_CA) != 0 && (x->ex_flags & EXFLAG_BCONS) != 0 && (x->ex_flags & EXFLAG_BCONS_CRITICAL) == 0, ctx, x, i, X509_V_ERR_CA_BCONS_NOT_CRITICAL); /* Check Key Usage according to RFC 5280 section 4.2.1.3 */ if ((x->ex_flags & EXFLAG_CA) != 0) { CB_FAIL_IF((x->ex_flags & EXFLAG_KUSAGE) == 0, ctx, x, i, X509_V_ERR_CA_CERT_MISSING_KEY_USAGE); } else { CB_FAIL_IF((x->ex_kusage & KU_KEY_CERT_SIGN) != 0, ctx, x, i, X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA); } /* Check issuer is non-empty acc. to RFC 5280 section 4.1.2.4 */ CB_FAIL_IF(X509_NAME_entry_count(X509_get_issuer_name(x)) == 0, ctx, x, i, X509_V_ERR_ISSUER_NAME_EMPTY); /* Check subject is non-empty acc. to RFC 5280 section 4.1.2.6 */ CB_FAIL_IF(((x->ex_flags & EXFLAG_CA) != 0 || (x->ex_kusage & KU_CRL_SIGN) != 0 || x->altname == NULL) && X509_NAME_entry_count(X509_get_subject_name(x)) == 0, ctx, x, i, X509_V_ERR_SUBJECT_NAME_EMPTY); CB_FAIL_IF(X509_NAME_entry_count(X509_get_subject_name(x)) == 0 && x->altname != NULL && (x->ex_flags & EXFLAG_SAN_CRITICAL) == 0, ctx, x, i, X509_V_ERR_EMPTY_SUBJECT_SAN_NOT_CRITICAL); /* Check SAN is non-empty according to RFC 5280 section 4.2.1.6 */ CB_FAIL_IF(x->altname != NULL && sk_GENERAL_NAME_num(x->altname) <= 0, ctx, x, i, X509_V_ERR_EMPTY_SUBJECT_ALT_NAME); /* Check sig alg consistency acc. to RFC 5280 section 4.1.1.2 */ CB_FAIL_IF(X509_ALGOR_cmp(&x->sig_alg, &x->cert_info.signature) != 0, ctx, x, i, X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY); CB_FAIL_IF(x->akid != NULL && (x->ex_flags & EXFLAG_AKID_CRITICAL) != 0, ctx, x, i, X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL); CB_FAIL_IF(x->skid != NULL && (x->ex_flags & EXFLAG_SKID_CRITICAL) != 0, ctx, x, i, X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL); if (X509_get_version(x) >= X509_VERSION_3) { /* Check AKID presence acc. to RFC 5280 section 4.2.1.1 */ CB_FAIL_IF(i + 1 < num /* * this means not last cert in chain, * taken as "generated by conforming CAs" */ && (x->akid == NULL || x->akid->keyid == NULL), ctx, x, i, X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER); /* Check SKID presence acc. to RFC 5280 section 4.2.1.2 */ CB_FAIL_IF((x->ex_flags & EXFLAG_CA) != 0 && x->skid == NULL, ctx, x, i, X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER); } else { CB_FAIL_IF(sk_X509_EXTENSION_num(X509_get0_extensions(x)) > 0, ctx, x, i, X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3); } } /* check_purpose() makes the callback as needed */ if (purpose > 0 && !check_purpose(ctx, x, purpose, i, must_be_ca)) return 0; /* Check path length */ CB_FAIL_IF(i > 1 && x->ex_pathlen != -1 && plen > x->ex_pathlen + proxy_path_length, ctx, x, i, X509_V_ERR_PATH_LENGTH_EXCEEDED); /* Increment path length if not a self-issued intermediate CA */ if (i > 0 && (x->ex_flags & EXFLAG_SI) == 0) plen++; /* * If this certificate is a proxy certificate, the next certificate * must be another proxy certificate or a EE certificate. If not, * the next certificate must be a CA certificate. */ if (x->ex_flags & EXFLAG_PROXY) { /* * RFC3820, 4.1.3 (b)(1) stipulates that if pCPathLengthConstraint * is less than max_path_length, the former should be copied to * the latter, and 4.1.4 (a) stipulates that max_path_length * should be verified to be larger than zero and decrement it. * * Because we're checking the certs in the reverse order, we start * with verifying that proxy_path_length isn't larger than pcPLC, * and copy the latter to the former if it is, and finally, * increment proxy_path_length. */ if (x->ex_pcpathlen != -1) { CB_FAIL_IF(proxy_path_length > x->ex_pcpathlen, ctx, x, i, X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED); proxy_path_length = x->ex_pcpathlen; } proxy_path_length++; must_be_ca = 0; } else { must_be_ca = 1; } } return 1; } static int has_san_id(X509 *x, int gtype) { int i; int ret = 0; GENERAL_NAMES *gs = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL); if (gs == NULL) return 0; for (i = 0; i < sk_GENERAL_NAME_num(gs); i++) { GENERAL_NAME *g = sk_GENERAL_NAME_value(gs, i); if (g->type == gtype) { ret = 1; break; } } GENERAL_NAMES_free(gs); return ret; } /*- * Returns -1 on internal error. * Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int check_name_constraints(X509_STORE_CTX *ctx) { int i; /* Check name constraints for all certificates */ for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) { X509 *x = sk_X509_value(ctx->chain, i); int j; /* Ignore self-issued certs unless last in chain */ if (i != 0 && (x->ex_flags & EXFLAG_SI) != 0) continue; /* * Proxy certificates policy has an extra constraint, where the * certificate subject MUST be the issuer with a single CN entry * added. * (RFC 3820: 3.4, 4.1.3 (a)(4)) */ if ((x->ex_flags & EXFLAG_PROXY) != 0) { X509_NAME *tmpsubject = X509_get_subject_name(x); X509_NAME *tmpissuer = X509_get_issuer_name(x); X509_NAME_ENTRY *tmpentry = NULL; int last_nid = 0; int err = X509_V_OK; int last_loc = X509_NAME_entry_count(tmpsubject) - 1; /* Check that there are at least two RDNs */ if (last_loc < 1) { err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION; goto proxy_name_done; } /* * Check that there is exactly one more RDN in subject as * there is in issuer. */ if (X509_NAME_entry_count(tmpsubject) != X509_NAME_entry_count(tmpissuer) + 1) { err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION; goto proxy_name_done; } /* * Check that the last subject component isn't part of a * multi-valued RDN */ if (X509_NAME_ENTRY_set(X509_NAME_get_entry(tmpsubject, last_loc)) == X509_NAME_ENTRY_set(X509_NAME_get_entry(tmpsubject, last_loc - 1))) { err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION; goto proxy_name_done; } /* * Check that the last subject RDN is a commonName, and that * all the previous RDNs match the issuer exactly */ tmpsubject = X509_NAME_dup(tmpsubject); if (tmpsubject == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB); ctx->error = X509_V_ERR_OUT_OF_MEM; return -1; } tmpentry = X509_NAME_delete_entry(tmpsubject, last_loc); last_nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(tmpentry)); if (last_nid != NID_commonName || X509_NAME_cmp(tmpsubject, tmpissuer) != 0) { err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION; } X509_NAME_ENTRY_free(tmpentry); X509_NAME_free(tmpsubject); proxy_name_done: CB_FAIL_IF(err != X509_V_OK, ctx, x, i, err); } /* * Check against constraints for all certificates higher in chain * including trust anchor. Trust anchor not strictly speaking needed * but if it includes constraints it is to be assumed it expects them * to be obeyed. */ for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) { NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc; if (nc) { int rv = NAME_CONSTRAINTS_check(x, nc); int ret = 1; /* If EE certificate check commonName too */ if (rv == X509_V_OK && i == 0 && (ctx->param->hostflags & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT) == 0 && ((ctx->param->hostflags & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT) != 0 || (ret = has_san_id(x, GEN_DNS)) == 0)) rv = NAME_CONSTRAINTS_check_CN(x, nc); if (ret < 0) return ret; switch (rv) { case X509_V_OK: break; case X509_V_ERR_OUT_OF_MEM: return -1; default: CB_FAIL_IF(1, ctx, x, i, rv); break; } } } } return 1; } static int check_id_error(X509_STORE_CTX *ctx, int errcode) { return verify_cb_cert(ctx, ctx->cert, 0, errcode); } static int check_hosts(X509 *x, X509_VERIFY_PARAM *vpm) { int i; int n = sk_OPENSSL_STRING_num(vpm->hosts); char *name; if (vpm->peername != NULL) { OPENSSL_free(vpm->peername); vpm->peername = NULL; } for (i = 0; i < n; ++i) { name = sk_OPENSSL_STRING_value(vpm->hosts, i); if (X509_check_host(x, name, 0, vpm->hostflags, &vpm->peername) > 0) return 1; } return n == 0; } static int check_id(X509_STORE_CTX *ctx) { X509_VERIFY_PARAM *vpm = ctx->param; X509 *x = ctx->cert; if (vpm->hosts != NULL && check_hosts(x, vpm) <= 0) { if (!check_id_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH)) return 0; } if (vpm->email != NULL && X509_check_email(x, vpm->email, vpm->emaillen, 0) <= 0) { if (!check_id_error(ctx, X509_V_ERR_EMAIL_MISMATCH)) return 0; } if (vpm->ip != NULL && X509_check_ip(x, vpm->ip, vpm->iplen, 0) <= 0) { if (!check_id_error(ctx, X509_V_ERR_IP_ADDRESS_MISMATCH)) return 0; } return 1; } /* Returns -1 on internal error */ static int check_trust(X509_STORE_CTX *ctx, int num_untrusted) { int i, res; X509 *x = NULL; X509 *mx; SSL_DANE *dane = ctx->dane; int num = sk_X509_num(ctx->chain); int trust; /* * Check for a DANE issuer at depth 1 or greater, if it is a DANE-TA(2) * match, we're done, otherwise we'll merely record the match depth. */ if (DANETLS_HAS_TA(dane) && num_untrusted > 0 && num_untrusted < num) { trust = check_dane_issuer(ctx, num_untrusted); if (trust != X509_TRUST_UNTRUSTED) return trust; } /* * Check trusted certificates in chain at depth num_untrusted and up. * Note, that depths 0..num_untrusted-1 may also contain trusted * certificates, but the caller is expected to have already checked those, * and wants to incrementally check just any added since. */ for (i = num_untrusted; i < num; i++) { x = sk_X509_value(ctx->chain, i); trust = X509_check_trust(x, ctx->param->trust, 0); /* If explicitly trusted (so not neutral nor rejected) return trusted */ if (trust == X509_TRUST_TRUSTED) goto trusted; if (trust == X509_TRUST_REJECTED) goto rejected; } /* * If we are looking at a trusted certificate, and accept partial chains, * the chain is PKIX trusted. */ if (num_untrusted < num) { if ((ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) != 0) goto trusted; return X509_TRUST_UNTRUSTED; } if (num_untrusted == num && (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) != 0) { /* * Last-resort call with no new trusted certificates, check the leaf * for a direct trust store match. */ i = 0; x = sk_X509_value(ctx->chain, i); res = lookup_cert_match(&mx, ctx, x); if (res < 0) return res; if (res == 0) return X509_TRUST_UNTRUSTED; /* * Check explicit auxiliary trust/reject settings. If none are set, * we'll accept X509_TRUST_UNTRUSTED when not self-signed. */ trust = X509_check_trust(mx, ctx->param->trust, 0); if (trust == X509_TRUST_REJECTED) { X509_free(mx); goto rejected; } /* Replace leaf with trusted match */ (void)sk_X509_set(ctx->chain, 0, mx); X509_free(x); ctx->num_untrusted = 0; goto trusted; } /* * If no trusted certs in chain at all return untrusted and allow * standard (no issuer cert) etc errors to be indicated. */ return X509_TRUST_UNTRUSTED; rejected: return verify_cb_cert(ctx, x, i, X509_V_ERR_CERT_REJECTED) == 0 ? X509_TRUST_REJECTED : X509_TRUST_UNTRUSTED; trusted: if (!DANETLS_ENABLED(dane)) return X509_TRUST_TRUSTED; if (dane->pdpth < 0) dane->pdpth = num_untrusted; /* With DANE, PKIX alone is not trusted until we have both */ if (dane->mdpth >= 0) return X509_TRUST_TRUSTED; return X509_TRUST_UNTRUSTED; } /* Sadly, returns 0 also on internal error. */ static int check_revocation(X509_STORE_CTX *ctx) { int i = 0, last = 0, ok = 0; if ((ctx->param->flags & X509_V_FLAG_CRL_CHECK) == 0) return 1; if ((ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL) != 0) { last = sk_X509_num(ctx->chain) - 1; } else { /* If checking CRL paths this isn't the EE certificate */ if (ctx->parent != NULL) return 1; last = 0; } for (i = 0; i <= last; i++) { ctx->error_depth = i; ok = check_cert(ctx); if (!ok) return ok; } return 1; } /* Sadly, returns 0 also on internal error. */ static int check_cert(X509_STORE_CTX *ctx) { X509_CRL *crl = NULL, *dcrl = NULL; int ok = 0; int cnum = ctx->error_depth; X509 *x = sk_X509_value(ctx->chain, cnum); ctx->current_cert = x; ctx->current_issuer = NULL; ctx->current_crl_score = 0; ctx->current_reasons = 0; if ((x->ex_flags & EXFLAG_PROXY) != 0) return 1; while (ctx->current_reasons != CRLDP_ALL_REASONS) { unsigned int last_reasons = ctx->current_reasons; /* Try to retrieve relevant CRL */ if (ctx->get_crl != NULL) ok = ctx->get_crl(ctx, &crl, x); else ok = get_crl_delta(ctx, &crl, &dcrl, x); /* If error looking up CRL, nothing we can do except notify callback */ if (!ok) { ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL); goto done; } ctx->current_crl = crl; ok = ctx->check_crl(ctx, crl); if (!ok) goto done; if (dcrl != NULL) { ok = ctx->check_crl(ctx, dcrl); if (!ok) goto done; ok = ctx->cert_crl(ctx, dcrl, x); if (!ok) goto done; } else { ok = 1; } /* Don't look in full CRL if delta reason is removefromCRL */ if (ok != 2) { ok = ctx->cert_crl(ctx, crl, x); if (!ok) goto done; } X509_CRL_free(crl); X509_CRL_free(dcrl); crl = NULL; dcrl = NULL; /* * If reasons not updated we won't get anywhere by another iteration, * so exit loop. */ if (last_reasons == ctx->current_reasons) { ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL); goto done; } } done: X509_CRL_free(crl); X509_CRL_free(dcrl); ctx->current_crl = NULL; return ok; } /* Check CRL times against values in X509_STORE_CTX */ static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify) { time_t *ptime; int i; if ((ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME) != 0) ptime = &ctx->param->check_time; else if ((ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME) != 0) return 1; else ptime = NULL; if (notify) ctx->current_crl = crl; i = X509_cmp_time(X509_CRL_get0_lastUpdate(crl), ptime); if (i == 0) { if (!notify) return 0; if (!verify_cb_crl(ctx, X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD)) return 0; } if (i > 0) { if (!notify) return 0; if (!verify_cb_crl(ctx, X509_V_ERR_CRL_NOT_YET_VALID)) return 0; } if (X509_CRL_get0_nextUpdate(crl)) { i = X509_cmp_time(X509_CRL_get0_nextUpdate(crl), ptime); if (i == 0) { if (!notify) return 0; if (!verify_cb_crl(ctx, X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD)) return 0; } /* Ignore expiration of base CRL is delta is valid */ if (i < 0 && (ctx->current_crl_score & CRL_SCORE_TIME_DELTA) == 0) { if (!notify || !verify_cb_crl(ctx, X509_V_ERR_CRL_HAS_EXPIRED)) return 0; } } if (notify) ctx->current_crl = NULL; return 1; } static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 **pissuer, int *pscore, unsigned int *preasons, STACK_OF(X509_CRL) *crls) { int i, crl_score, best_score = *pscore; unsigned int reasons, best_reasons = 0; X509 *x = ctx->current_cert; X509_CRL *crl, *best_crl = NULL; X509 *crl_issuer = NULL, *best_crl_issuer = NULL; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); reasons = *preasons; crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x); if (crl_score < best_score || crl_score == 0) continue; /* If current CRL is equivalent use it if it is newer */ if (crl_score == best_score && best_crl != NULL) { int day, sec; if (ASN1_TIME_diff(&day, &sec, X509_CRL_get0_lastUpdate(best_crl), X509_CRL_get0_lastUpdate(crl)) == 0) continue; /* * ASN1_TIME_diff never returns inconsistent signs for |day| * and |sec|. */ if (day <= 0 && sec <= 0) continue; } best_crl = crl; best_crl_issuer = crl_issuer; best_score = crl_score; best_reasons = reasons; } if (best_crl != NULL) { X509_CRL_free(*pcrl); *pcrl = best_crl; *pissuer = best_crl_issuer; *pscore = best_score; *preasons = best_reasons; X509_CRL_up_ref(best_crl); X509_CRL_free(*pdcrl); *pdcrl = NULL; get_delta_sk(ctx, pdcrl, pscore, best_crl, crls); } if (best_score >= CRL_SCORE_VALID) return 1; return 0; } /* * Compare two CRL extensions for delta checking purposes. They should be * both present or both absent. If both present all fields must be identical. */ static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid) { ASN1_OCTET_STRING *exta = NULL, *extb = NULL; int i = X509_CRL_get_ext_by_NID(a, nid, -1); if (i >= 0) { /* Can't have multiple occurrences */ if (X509_CRL_get_ext_by_NID(a, nid, i) != -1) return 0; exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i)); } i = X509_CRL_get_ext_by_NID(b, nid, -1); if (i >= 0) { if (X509_CRL_get_ext_by_NID(b, nid, i) != -1) return 0; extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i)); } if (exta == NULL && extb == NULL) return 1; if (exta == NULL || extb == NULL) return 0; return ASN1_OCTET_STRING_cmp(exta, extb) == 0; } /* See if a base and delta are compatible */ static int check_delta_base(X509_CRL *delta, X509_CRL *base) { /* Delta CRL must be a delta */ if (delta->base_crl_number == NULL) return 0; /* Base must have a CRL number */ if (base->crl_number == NULL) return 0; /* Issuer names must match */ if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(delta)) != 0) return 0; /* AKID and IDP must match */ if (!crl_extension_match(delta, base, NID_authority_key_identifier)) return 0; if (!crl_extension_match(delta, base, NID_issuing_distribution_point)) return 0; /* Delta CRL base number must not exceed Full CRL number. */ if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0) return 0; /* Delta CRL number must exceed full CRL number */ return ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0; } /* * For a given base CRL find a delta... maybe extend to delta scoring or * retrieve a chain of deltas... */ static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore, X509_CRL *base, STACK_OF(X509_CRL) *crls) { X509_CRL *delta; int i; if ((ctx->param->flags & X509_V_FLAG_USE_DELTAS) == 0) return; if (((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST) == 0) return; for (i = 0; i < sk_X509_CRL_num(crls); i++) { delta = sk_X509_CRL_value(crls, i); if (check_delta_base(delta, base)) { if (check_crl_time(ctx, delta, 0)) *pscore |= CRL_SCORE_TIME_DELTA; X509_CRL_up_ref(delta); *dcrl = delta; return; } } *dcrl = NULL; } /* * For a given CRL return how suitable it is for the supplied certificate * 'x'. The return value is a mask of several criteria. If the issuer is not * the certificate issuer this is returned in *pissuer. The reasons mask is * also used to determine if the CRL is suitable: if no new reasons the CRL * is rejected, otherwise reasons is updated. */ static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer, unsigned int *preasons, X509_CRL *crl, X509 *x) { int crl_score = 0; unsigned int tmp_reasons = *preasons, crl_reasons; /* First see if we can reject CRL straight away */ /* Invalid IDP cannot be processed */ if ((crl->idp_flags & IDP_INVALID) != 0) return 0; /* Reason codes or indirect CRLs need extended CRL support */ if ((ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT) == 0) { if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS)) return 0; } else if ((crl->idp_flags & IDP_REASONS) != 0) { /* If no new reasons reject */ if ((crl->idp_reasons & ~tmp_reasons) == 0) return 0; } /* Don't process deltas at this stage */ else if (crl->base_crl_number != NULL) return 0; /* If issuer name doesn't match certificate need indirect CRL */ if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl)) != 0) { if ((crl->idp_flags & IDP_INDIRECT) == 0) return 0; } else { crl_score |= CRL_SCORE_ISSUER_NAME; } if ((crl->flags & EXFLAG_CRITICAL) == 0) crl_score |= CRL_SCORE_NOCRITICAL; /* Check expiration */ if (check_crl_time(ctx, crl, 0)) crl_score |= CRL_SCORE_TIME; /* Check authority key ID and locate certificate issuer */ crl_akid_check(ctx, crl, pissuer, &crl_score); /* If we can't locate certificate issuer at this point forget it */ if ((crl_score & CRL_SCORE_AKID) == 0) return 0; /* Check cert for matching CRL distribution points */ if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) { /* If no new reasons reject */ if ((crl_reasons & ~tmp_reasons) == 0) return 0; tmp_reasons |= crl_reasons; crl_score |= CRL_SCORE_SCOPE; } *preasons = tmp_reasons; return crl_score; } static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer, int *pcrl_score) { X509 *crl_issuer = NULL; const X509_NAME *cnm = X509_CRL_get_issuer(crl); int cidx = ctx->error_depth; int i; if (cidx != sk_X509_num(ctx->chain) - 1) cidx++; crl_issuer = sk_X509_value(ctx->chain, cidx); if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) { if (*pcrl_score & CRL_SCORE_ISSUER_NAME) { *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT; *pissuer = crl_issuer; return; } } for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) { crl_issuer = sk_X509_value(ctx->chain, cidx); if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm)) continue; if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) { *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH; *pissuer = crl_issuer; return; } } /* Anything else needs extended CRL support */ if ((ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT) == 0) return; /* * Otherwise the CRL issuer is not on the path. Look for it in the set of * untrusted certificates. */ for (i = 0; i < sk_X509_num(ctx->untrusted); i++) { crl_issuer = sk_X509_value(ctx->untrusted, i); if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm) != 0) continue; if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) { *pissuer = crl_issuer; *pcrl_score |= CRL_SCORE_AKID; return; } } } /* * Check the path of a CRL issuer certificate. This creates a new * X509_STORE_CTX and populates it with most of the parameters from the * parent. This could be optimised somewhat since a lot of path checking will * be duplicated by the parent, but this will rarely be used in practice. */ static int check_crl_path(X509_STORE_CTX *ctx, X509 *x) { X509_STORE_CTX crl_ctx = {0}; int ret; /* Don't allow recursive CRL path validation */ if (ctx->parent != NULL) return 0; if (!X509_STORE_CTX_init(&crl_ctx, ctx->store, x, ctx->untrusted)) return -1; crl_ctx.crls = ctx->crls; /* Copy verify params across */ X509_STORE_CTX_set0_param(&crl_ctx, ctx->param); crl_ctx.parent = ctx; crl_ctx.verify_cb = ctx->verify_cb; /* Verify CRL issuer */ ret = X509_verify_cert(&crl_ctx); if (ret <= 0) goto err; /* Check chain is acceptable */ ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain); err: X509_STORE_CTX_cleanup(&crl_ctx); return ret; } /* * RFC3280 says nothing about the relationship between CRL path and * certificate path, which could lead to situations where a certificate could * be revoked or validated by a CA not authorized to do so. RFC5280 is more * strict and states that the two paths must end in the same trust anchor, * though some discussions remain... until this is resolved we use the * RFC5280 version */ static int check_crl_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *cert_path, STACK_OF(X509) *crl_path) { X509 *cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1); X509 *crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1); return X509_cmp(cert_ta, crl_ta) == 0; } /*- * Check for match between two dist point names: three separate cases. * 1. Both are relative names and compare X509_NAME types. * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES. * 3. Both are full names and compare two GENERAL_NAMES. * 4. One is NULL: automatic match. */ static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b) { X509_NAME *nm = NULL; GENERAL_NAMES *gens = NULL; GENERAL_NAME *gena, *genb; int i, j; if (a == NULL || b == NULL) return 1; if (a->type == 1) { if (a->dpname == NULL) return 0; /* Case 1: two X509_NAME */ if (b->type == 1) { if (b->dpname == NULL) return 0; return X509_NAME_cmp(a->dpname, b->dpname) == 0; } /* Case 2: set name and GENERAL_NAMES appropriately */ nm = a->dpname; gens = b->name.fullname; } else if (b->type == 1) { if (b->dpname == NULL) return 0; /* Case 2: set name and GENERAL_NAMES appropriately */ gens = a->name.fullname; nm = b->dpname; } /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */ if (nm != NULL) { for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) { gena = sk_GENERAL_NAME_value(gens, i); if (gena->type != GEN_DIRNAME) continue; if (X509_NAME_cmp(nm, gena->d.directoryName) == 0) return 1; } return 0; } /* Else case 3: two GENERAL_NAMES */ for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) { gena = sk_GENERAL_NAME_value(a->name.fullname, i); for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) { genb = sk_GENERAL_NAME_value(b->name.fullname, j); if (GENERAL_NAME_cmp(gena, genb) == 0) return 1; } } return 0; } static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score) { int i; const X509_NAME *nm = X509_CRL_get_issuer(crl); /* If no CRLissuer return is successful iff don't need a match */ if (dp->CRLissuer == NULL) return (crl_score & CRL_SCORE_ISSUER_NAME) != 0; for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) { GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i); if (gen->type != GEN_DIRNAME) continue; if (X509_NAME_cmp(gen->d.directoryName, nm) == 0) return 1; } return 0; } /* Check CRLDP and IDP */ static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score, unsigned int *preasons) { int i; if ((crl->idp_flags & IDP_ONLYATTR) != 0) return 0; if ((x->ex_flags & EXFLAG_CA) != 0) { if ((crl->idp_flags & IDP_ONLYUSER) != 0) return 0; } else { if ((crl->idp_flags & IDP_ONLYCA) != 0) return 0; } *preasons = crl->idp_reasons; for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) { DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i); if (crldp_check_crlissuer(dp, crl, crl_score)) { if (crl->idp == NULL || idp_check_dp(dp->distpoint, crl->idp->distpoint)) { *preasons &= dp->dp_reasons; return 1; } } } return (crl->idp == NULL || crl->idp->distpoint == NULL) && (crl_score & CRL_SCORE_ISSUER_NAME) != 0; } /* * Retrieve CRL corresponding to current certificate. If deltas enabled try * to find a delta CRL too */ static int get_crl_delta(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x) { int ok; X509 *issuer = NULL; int crl_score = 0; unsigned int reasons; X509_CRL *crl = NULL, *dcrl = NULL; STACK_OF(X509_CRL) *skcrl; const X509_NAME *nm = X509_get_issuer_name(x); reasons = ctx->current_reasons; ok = get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, ctx->crls); if (ok) goto done; /* Lookup CRLs from store */ skcrl = ctx->lookup_crls(ctx, nm); /* If no CRLs found and a near match from get_crl_sk use that */ if (skcrl == NULL && crl != NULL) goto done; get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl); sk_X509_CRL_pop_free(skcrl, X509_CRL_free); done: /* If we got any kind of CRL use it and return success */ if (crl != NULL) { ctx->current_issuer = issuer; ctx->current_crl_score = crl_score; ctx->current_reasons = reasons; *pcrl = crl; *pdcrl = dcrl; return 1; } return 0; } /* Check CRL validity */ static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl) { X509 *issuer = NULL; EVP_PKEY *ikey = NULL; int cnum = ctx->error_depth; int chnum = sk_X509_num(ctx->chain) - 1; /* If we have an alternative CRL issuer cert use that */ if (ctx->current_issuer != NULL) { issuer = ctx->current_issuer; /* * Else find CRL issuer: if not last certificate then issuer is next * certificate in chain. */ } else if (cnum < chnum) { issuer = sk_X509_value(ctx->chain, cnum + 1); } else { issuer = sk_X509_value(ctx->chain, chnum); /* If not self-issued, can't check signature */ if (!ctx->check_issued(ctx, issuer, issuer) && !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER)) return 0; } if (issuer == NULL) return 1; /* * Skip most tests for deltas because they have already been done */ if (crl->base_crl_number == NULL) { /* Check for cRLSign bit if keyUsage present */ if ((issuer->ex_flags & EXFLAG_KUSAGE) != 0 && (issuer->ex_kusage & KU_CRL_SIGN) == 0 && !verify_cb_crl(ctx, X509_V_ERR_KEYUSAGE_NO_CRL_SIGN)) return 0; if ((ctx->current_crl_score & CRL_SCORE_SCOPE) == 0 && !verify_cb_crl(ctx, X509_V_ERR_DIFFERENT_CRL_SCOPE)) return 0; if ((ctx->current_crl_score & CRL_SCORE_SAME_PATH) == 0 && check_crl_path(ctx, ctx->current_issuer) <= 0 && !verify_cb_crl(ctx, X509_V_ERR_CRL_PATH_VALIDATION_ERROR)) return 0; if ((crl->idp_flags & IDP_INVALID) != 0 && !verify_cb_crl(ctx, X509_V_ERR_INVALID_EXTENSION)) return 0; } if ((ctx->current_crl_score & CRL_SCORE_TIME) == 0 && !check_crl_time(ctx, crl, 1)) return 0; /* Attempt to get issuer certificate public key */ ikey = X509_get0_pubkey(issuer); if (ikey == NULL && !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)) return 0; if (ikey != NULL) { int rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags); if (rv != X509_V_OK && !verify_cb_crl(ctx, rv)) return 0; /* Verify CRL signature */ if (X509_CRL_verify(crl, ikey) <= 0 && !verify_cb_crl(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE)) return 0; } return 1; } /* Check certificate against CRL */ static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x) { X509_REVOKED *rev; /* * The rules changed for this... previously if a CRL contained unhandled * critical extensions it could still be used to indicate a certificate * was revoked. This has since been changed since critical extensions can * change the meaning of CRL entries. */ if ((ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) == 0 && (crl->flags & EXFLAG_CRITICAL) != 0 && !verify_cb_crl(ctx, X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION)) return 0; /* * Look for serial number of certificate in CRL. If found, make sure * reason is not removeFromCRL. */ if (X509_CRL_get0_by_cert(crl, &rev, x)) { if (rev->reason == CRL_REASON_REMOVE_FROM_CRL) return 2; if (!verify_cb_crl(ctx, X509_V_ERR_CERT_REVOKED)) return 0; } return 1; } /* Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int check_policy(X509_STORE_CTX *ctx) { int ret; if (ctx->parent) return 1; /* * With DANE, the trust anchor might be a bare public key, not a * certificate! In that case our chain does not have the trust anchor * certificate as a top-most element. This comports well with RFC5280 * chain verification, since there too, the trust anchor is not part of the * chain to be verified. In particular, X509_policy_check() does not look * at the TA cert, but assumes that it is present as the top-most chain * element. We therefore temporarily push a NULL cert onto the chain if it * was verified via a bare public key, and pop it off right after the * X509_policy_check() call. */ if (ctx->bare_ta_signed && !sk_X509_push(ctx->chain, NULL)) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto memerr; } ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain, ctx->param->policies, ctx->param->flags); if (ctx->bare_ta_signed) (void)sk_X509_pop(ctx->chain); if (ret == X509_PCY_TREE_INTERNAL) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto memerr; } /* Invalid or inconsistent extensions */ if (ret == X509_PCY_TREE_INVALID) { int i, cbcalled = 0; /* Locate certificates with bad extensions and notify callback. */ for (i = 0; i < sk_X509_num(ctx->chain); i++) { X509 *x = sk_X509_value(ctx->chain, i); if ((x->ex_flags & EXFLAG_INVALID_POLICY) != 0) cbcalled = 1; CB_FAIL_IF((x->ex_flags & EXFLAG_INVALID_POLICY) != 0, ctx, x, i, X509_V_ERR_INVALID_POLICY_EXTENSION); } if (!cbcalled) { /* Should not be able to get here */ ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR); return 0; } /* The callback ignored the error so we return success */ return 1; } if (ret == X509_PCY_TREE_FAILURE) { ctx->current_cert = NULL; ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY; return ctx->verify_cb(0, ctx); } if (ret != X509_PCY_TREE_VALID) { ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR); return 0; } if ((ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) != 0) { ctx->current_cert = NULL; /* * Verification errors need to be "sticky", a callback may have allowed * an SSL handshake to continue despite an error, and we must then * remain in an error state. Therefore, we MUST NOT clear earlier * verification errors by setting the error to X509_V_OK. */ if (!ctx->verify_cb(2, ctx)) return 0; } return 1; memerr: ctx->error = X509_V_ERR_OUT_OF_MEM; return -1; } /*- * Check certificate validity times. * If depth >= 0, invoke verification callbacks on error, otherwise just return * the validation status. * * Return 1 on success, 0 otherwise. * Sadly, returns 0 also on internal error in ctx->verify_cb(). */ int ossl_x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int depth) { time_t *ptime; int i; if ((ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME) != 0) ptime = &ctx->param->check_time; else if ((ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME) != 0) return 1; else ptime = NULL; i = X509_cmp_time(X509_get0_notBefore(x), ptime); if (i >= 0 && depth < 0) return 0; CB_FAIL_IF(i == 0, ctx, x, depth, X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD); CB_FAIL_IF(i > 0, ctx, x, depth, X509_V_ERR_CERT_NOT_YET_VALID); i = X509_cmp_time(X509_get0_notAfter(x), ptime); if (i <= 0 && depth < 0) return 0; CB_FAIL_IF(i == 0, ctx, x, depth, X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD); CB_FAIL_IF(i < 0, ctx, x, depth, X509_V_ERR_CERT_HAS_EXPIRED); return 1; } /* * Verify the issuer signatures and cert times of ctx->chain. * Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int internal_verify(X509_STORE_CTX *ctx) { int n; X509 *xi; X509 *xs; /* For RPK: just do the verify callback */ if (ctx->rpk != NULL) { if (!ctx->verify_cb(ctx->error == X509_V_OK, ctx)) return 0; return 1; } n = sk_X509_num(ctx->chain) - 1; xi = sk_X509_value(ctx->chain, n); xs = xi; ctx->error_depth = n; if (ctx->bare_ta_signed) { /* * With DANE-verified bare public key TA signatures, * on the top certificate we check only the timestamps. * We report the issuer as NULL because all we have is a bare key. */ xi = NULL; } else if (ossl_x509_likely_issued(xi, xi) != X509_V_OK /* exceptional case: last cert in the chain is not self-issued */ && ((ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) == 0)) { if (n > 0) { n--; ctx->error_depth = n; xs = sk_X509_value(ctx->chain, n); } else { CB_FAIL_IF(1, ctx, xi, 0, X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE); } /* * The below code will certainly not do a * self-signature check on xi because it is not self-issued. */ } /* * Do not clear error (by ctx->error = X509_V_OK), it must be "sticky", * only the user's callback is allowed to reset errors (at its own peril). */ while (n >= 0) { /*- * For each iteration of this loop: * n is the subject depth * xs is the subject cert, for which the signature is to be checked * xi is NULL for DANE-verified bare public key TA signatures * else the supposed issuer cert containing the public key to use * Initially xs == xi if the last cert in the chain is self-issued. */ /* * Do signature check for self-signed certificates only if explicitly * asked for because it does not add any security and just wastes time. */ if (xi != NULL && (xs != xi || ((ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE) != 0 && (xi->ex_flags & EXFLAG_SS) != 0))) { EVP_PKEY *pkey; /* * If the issuer's public key is not available or its key usage * does not support issuing the subject cert, report the issuer * cert and its depth (rather than n, the depth of the subject). */ int issuer_depth = n + (xs == xi ? 0 : 1); /* * According to https://tools.ietf.org/html/rfc5280#section-6.1.4 * step (n) we must check any given key usage extension in a CA cert * when preparing the verification of a certificate issued by it. * According to https://tools.ietf.org/html/rfc5280#section-4.2.1.3 * we must not verify a certificate signature if the key usage of * the CA certificate that issued the certificate prohibits signing. * In case the 'issuing' certificate is the last in the chain and is * not a CA certificate but a 'self-issued' end-entity cert (i.e., * xs == xi && !(xi->ex_flags & EXFLAG_CA)) RFC 5280 does not apply * (see https://tools.ietf.org/html/rfc6818#section-2) and thus * we are free to ignore any key usage restrictions on such certs. */ int ret = xs == xi && (xi->ex_flags & EXFLAG_CA) == 0 ? X509_V_OK : ossl_x509_signing_allowed(xi, xs); CB_FAIL_IF(ret != X509_V_OK, ctx, xi, issuer_depth, ret); if ((pkey = X509_get0_pubkey(xi)) == NULL) { CB_FAIL_IF(1, ctx, xi, issuer_depth, X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY); } else { CB_FAIL_IF(X509_verify(xs, pkey) <= 0, ctx, xs, n, X509_V_ERR_CERT_SIGNATURE_FAILURE); } } /* In addition to RFC 5280 requirements do also for trust anchor cert */ /* Calls verify callback as needed */ if (!ossl_x509_check_cert_time(ctx, xs, n)) return 0; /* * Signal success at this depth. However, the previous error (if any) * is retained. */ ctx->current_issuer = xi; ctx->current_cert = xs; ctx->error_depth = n; if (!ctx->verify_cb(1, ctx)) return 0; if (--n >= 0) { xi = xs; xs = sk_X509_value(ctx->chain, n); } } return 1; } int X509_cmp_current_time(const ASN1_TIME *ctm) { return X509_cmp_time(ctm, NULL); } /* returns 0 on error, otherwise 1 if ctm > cmp_time, else -1 */ int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time) { static const size_t utctime_length = sizeof("YYMMDDHHMMSSZ") - 1; static const size_t generalizedtime_length = sizeof("YYYYMMDDHHMMSSZ") - 1; ASN1_TIME *asn1_cmp_time = NULL; int i, day, sec, ret = 0; #ifdef CHARSET_EBCDIC const char upper_z = 0x5A; #else const char upper_z = 'Z'; #endif /*- * Note that ASN.1 allows much more slack in the time format than RFC5280. * In RFC5280, the representation is fixed: * UTCTime: YYMMDDHHMMSSZ * GeneralizedTime: YYYYMMDDHHMMSSZ * * We do NOT currently enforce the following RFC 5280 requirement: * "CAs conforming to this profile MUST always encode certificate * validity dates through the year 2049 as UTCTime; certificate validity * dates in 2050 or later MUST be encoded as GeneralizedTime." */ switch (ctm->type) { case V_ASN1_UTCTIME: if (ctm->length != (int)(utctime_length)) return 0; break; case V_ASN1_GENERALIZEDTIME: if (ctm->length != (int)(generalizedtime_length)) return 0; break; default: return 0; } /** * Verify the format: the ASN.1 functions we use below allow a more * flexible format than what's mandated by RFC 5280. * Digit and date ranges will be verified in the conversion methods. */ for (i = 0; i < ctm->length - 1; i++) { if (!ossl_ascii_isdigit(ctm->data[i])) return 0; } if (ctm->data[ctm->length - 1] != upper_z) return 0; /* * There is ASN1_UTCTIME_cmp_time_t but no * ASN1_GENERALIZEDTIME_cmp_time_t or ASN1_TIME_cmp_time_t, * so we go through ASN.1 */ asn1_cmp_time = X509_time_adj(NULL, 0, cmp_time); if (asn1_cmp_time == NULL) goto err; if (ASN1_TIME_diff(&day, &sec, ctm, asn1_cmp_time) == 0) goto err; /* * X509_cmp_time comparison is <=. * The return value 0 is reserved for errors. */ ret = (day >= 0 && sec >= 0) ? -1 : 1; err: ASN1_TIME_free(asn1_cmp_time); return ret; } /* * Return 0 if time should not be checked or reference time is in range, * or else 1 if it is past the end, or -1 if it is before the start */ int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm, const ASN1_TIME *start, const ASN1_TIME *end) { time_t ref_time; time_t *time = NULL; unsigned long flags = vpm == NULL ? 0 : X509_VERIFY_PARAM_get_flags(vpm); if ((flags & X509_V_FLAG_USE_CHECK_TIME) != 0) { ref_time = X509_VERIFY_PARAM_get_time(vpm); time = &ref_time; } else if ((flags & X509_V_FLAG_NO_CHECK_TIME) != 0) { return 0; /* this means ok */ } /* else reference time is the current time */ if (end != NULL && X509_cmp_time(end, time) < 0) return 1; if (start != NULL && X509_cmp_time(start, time) > 0) return -1; return 0; } ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj) { return X509_time_adj(s, adj, NULL); } ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm) { return X509_time_adj_ex(s, 0, offset_sec, in_tm); } ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s, int offset_day, long offset_sec, time_t *in_tm) { time_t t; if (in_tm) t = *in_tm; else time(&t); if (s != NULL && (s->flags & ASN1_STRING_FLAG_MSTRING) == 0) { if (s->type == V_ASN1_UTCTIME) return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec); if (s->type == V_ASN1_GENERALIZEDTIME) return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec); } return ASN1_TIME_adj(s, t, offset_day, offset_sec); } /* Copy any missing public key parameters up the chain towards pkey */ int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain) { EVP_PKEY *ktmp = NULL, *ktmp2; int i, j; if (pkey != NULL && !EVP_PKEY_missing_parameters(pkey)) return 1; for (i = 0; i < sk_X509_num(chain); i++) { ktmp = X509_get0_pubkey(sk_X509_value(chain, i)); if (ktmp == NULL) { ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY); return 0; } if (!EVP_PKEY_missing_parameters(ktmp)) break; ktmp = NULL; } if (ktmp == NULL) { ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN); return 0; } /* first, populate the other certs */ for (j = i - 1; j >= 0; j--) { ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j)); if (!EVP_PKEY_copy_parameters(ktmp2, ktmp)) return 0; } if (pkey != NULL) return EVP_PKEY_copy_parameters(pkey, ktmp); return 1; } /* * Make a delta CRL as the difference between two full CRLs. * Sadly, returns NULL also on internal error. */ X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer, EVP_PKEY *skey, const EVP_MD *md, unsigned int flags) { X509_CRL *crl = NULL; int i; STACK_OF(X509_REVOKED) *revs = NULL; /* CRLs can't be delta already */ if (base->base_crl_number != NULL || newer->base_crl_number != NULL) { ERR_raise(ERR_LIB_X509, X509_R_CRL_ALREADY_DELTA); return NULL; } /* Base and new CRL must have a CRL number */ if (base->crl_number == NULL || newer->crl_number == NULL) { ERR_raise(ERR_LIB_X509, X509_R_NO_CRL_NUMBER); return NULL; } /* Issuer names must match */ if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(newer)) != 0) { ERR_raise(ERR_LIB_X509, X509_R_ISSUER_MISMATCH); return NULL; } /* AKID and IDP must match */ if (!crl_extension_match(base, newer, NID_authority_key_identifier)) { ERR_raise(ERR_LIB_X509, X509_R_AKID_MISMATCH); return NULL; } if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) { ERR_raise(ERR_LIB_X509, X509_R_IDP_MISMATCH); return NULL; } /* Newer CRL number must exceed full CRL number */ if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) { ERR_raise(ERR_LIB_X509, X509_R_NEWER_CRL_NOT_NEWER); return NULL; } /* CRLs must verify */ if (skey != NULL && (X509_CRL_verify(base, skey) <= 0 || X509_CRL_verify(newer, skey) <= 0)) { ERR_raise(ERR_LIB_X509, X509_R_CRL_VERIFY_FAILURE); return NULL; } /* Create new CRL */ crl = X509_CRL_new_ex(base->libctx, base->propq); if (crl == NULL || !X509_CRL_set_version(crl, X509_CRL_VERSION_2)) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto err; } /* Set issuer name */ if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer))) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto err; } if (!X509_CRL_set1_lastUpdate(crl, X509_CRL_get0_lastUpdate(newer))) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto err; } if (!X509_CRL_set1_nextUpdate(crl, X509_CRL_get0_nextUpdate(newer))) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto err; } /* Set base CRL number: must be critical */ if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0)) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto err; } /* * Copy extensions across from newest CRL to delta: this will set CRL * number to correct value too. */ for (i = 0; i < X509_CRL_get_ext_count(newer); i++) { X509_EXTENSION *ext = X509_CRL_get_ext(newer, i); if (!X509_CRL_add_ext(crl, ext, -1)) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto err; } } /* Go through revoked entries, copying as needed */ revs = X509_CRL_get_REVOKED(newer); for (i = 0; i < sk_X509_REVOKED_num(revs); i++) { X509_REVOKED *rvn, *rvtmp; rvn = sk_X509_REVOKED_value(revs, i); /* * Add only if not also in base. * Need something cleverer here for some more complex CRLs covering * multiple CAs. */ if (!X509_CRL_get0_by_serial(base, &rvtmp, &rvn->serialNumber)) { rvtmp = X509_REVOKED_dup(rvn); if (rvtmp == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB); goto err; } if (!X509_CRL_add0_revoked(crl, rvtmp)) { X509_REVOKED_free(rvtmp); ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto err; } } } if (skey != NULL && md != NULL && !X509_CRL_sign(crl, skey, md)) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto err; } return crl; err: X509_CRL_free(crl); return NULL; } int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data) { return CRYPTO_set_ex_data(&ctx->ex_data, idx, data); } void *X509_STORE_CTX_get_ex_data(const X509_STORE_CTX *ctx, int idx) { return CRYPTO_get_ex_data(&ctx->ex_data, idx); } int X509_STORE_CTX_get_error(const X509_STORE_CTX *ctx) { return ctx->error; } void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err) { ctx->error = err; } int X509_STORE_CTX_get_error_depth(const X509_STORE_CTX *ctx) { return ctx->error_depth; } void X509_STORE_CTX_set_error_depth(X509_STORE_CTX *ctx, int depth) { ctx->error_depth = depth; } X509 *X509_STORE_CTX_get_current_cert(const X509_STORE_CTX *ctx) { return ctx->current_cert; } void X509_STORE_CTX_set_current_cert(X509_STORE_CTX *ctx, X509 *x) { ctx->current_cert = x; } STACK_OF(X509) *X509_STORE_CTX_get0_chain(const X509_STORE_CTX *ctx) { return ctx->chain; } STACK_OF(X509) *X509_STORE_CTX_get1_chain(const X509_STORE_CTX *ctx) { if (ctx->chain == NULL) return NULL; return X509_chain_up_ref(ctx->chain); } X509 *X509_STORE_CTX_get0_current_issuer(const X509_STORE_CTX *ctx) { return ctx->current_issuer; } X509_CRL *X509_STORE_CTX_get0_current_crl(const X509_STORE_CTX *ctx) { return ctx->current_crl; } X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(const X509_STORE_CTX *ctx) { return ctx->parent; } void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x) { ctx->cert = x; } void X509_STORE_CTX_set0_rpk(X509_STORE_CTX *ctx, EVP_PKEY *rpk) { ctx->rpk = rpk; } void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk) { ctx->crls = sk; } int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose) { /* * XXX: Why isn't this function always used to set the associated trust? * Should there even be a VPM->trust field at all? Or should the trust * always be inferred from the purpose by X509_STORE_CTX_init(). */ return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0); } int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust) { /* * XXX: See above, this function would only be needed when the default * trust for the purpose needs an override in a corner case. */ return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust); } /* * This function is used to set the X509_STORE_CTX purpose and trust values. * This is intended to be used when another structure has its own trust and * purpose values which (if set) will be inherited by the ctx. If they aren't * set then we will usually have a default purpose in mind which should then * be used to set the trust value. An example of this is SSL use: an SSL * structure will have its own purpose and trust settings which the * application can set: if they aren't set then we use the default of SSL * client/server. */ int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose, int purpose, int trust) { int idx; /* If purpose not set use default */ if (purpose == 0) purpose = def_purpose; /* * If purpose is set but we don't have a default then set the default to * the current purpose */ else if (def_purpose == 0) def_purpose = purpose; /* If we have a purpose then check it is valid */ if (purpose != 0) { X509_PURPOSE *ptmp; idx = X509_PURPOSE_get_by_id(purpose); if (idx == -1) { ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID); return 0; } ptmp = X509_PURPOSE_get0(idx); if (ptmp->trust == X509_TRUST_DEFAULT) { idx = X509_PURPOSE_get_by_id(def_purpose); if (idx == -1) { ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID); return 0; } ptmp = X509_PURPOSE_get0(idx); } /* If trust not set then get from purpose default */ if (trust == 0) trust = ptmp->trust; } if (trust != 0) { idx = X509_TRUST_get_by_id(trust); if (idx == -1) { ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_TRUST_ID); return 0; } } if (ctx->param->purpose == 0 && purpose != 0) ctx->param->purpose = purpose; if (ctx->param->trust == 0 && trust != 0) ctx->param->trust = trust; return 1; } X509_STORE_CTX *X509_STORE_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq) { X509_STORE_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) return NULL; ctx->libctx = libctx; if (propq != NULL) { ctx->propq = OPENSSL_strdup(propq); if (ctx->propq == NULL) { OPENSSL_free(ctx); return NULL; } } return ctx; } X509_STORE_CTX *X509_STORE_CTX_new(void) { return X509_STORE_CTX_new_ex(NULL, NULL); } void X509_STORE_CTX_free(X509_STORE_CTX *ctx) { if (ctx == NULL) return; X509_STORE_CTX_cleanup(ctx); /* libctx and propq survive X509_STORE_CTX_cleanup() */ OPENSSL_free(ctx->propq); OPENSSL_free(ctx); } int X509_STORE_CTX_init_rpk(X509_STORE_CTX *ctx, X509_STORE *store, EVP_PKEY *rpk) { if (!X509_STORE_CTX_init(ctx, store, NULL, NULL)) return 0; ctx->rpk = rpk; return 1; } int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509, STACK_OF(X509) *chain) { if (ctx == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return 0; } X509_STORE_CTX_cleanup(ctx); ctx->store = store; ctx->cert = x509; ctx->untrusted = chain; ctx->crls = NULL; ctx->num_untrusted = 0; ctx->other_ctx = NULL; ctx->valid = 0; ctx->chain = NULL; ctx->error = X509_V_OK; ctx->explicit_policy = 0; ctx->error_depth = 0; ctx->current_cert = NULL; ctx->current_issuer = NULL; ctx->current_crl = NULL; ctx->current_crl_score = 0; ctx->current_reasons = 0; ctx->tree = NULL; ctx->parent = NULL; ctx->dane = NULL; ctx->bare_ta_signed = 0; ctx->rpk = NULL; /* Zero ex_data to make sure we're cleanup-safe */ memset(&ctx->ex_data, 0, sizeof(ctx->ex_data)); /* store->cleanup is always 0 in OpenSSL, if set must be idempotent */ if (store != NULL) ctx->cleanup = store->cleanup; else ctx->cleanup = NULL; if (store != NULL && store->check_issued != NULL) ctx->check_issued = store->check_issued; else ctx->check_issued = check_issued; if (store != NULL && store->get_issuer != NULL) ctx->get_issuer = store->get_issuer; else ctx->get_issuer = X509_STORE_CTX_get1_issuer; if (store != NULL && store->verify_cb != NULL) ctx->verify_cb = store->verify_cb; else ctx->verify_cb = null_callback; if (store != NULL && store->verify != NULL) ctx->verify = store->verify; else ctx->verify = internal_verify; if (store != NULL && store->check_revocation != NULL) ctx->check_revocation = store->check_revocation; else ctx->check_revocation = check_revocation; if (store != NULL && store->get_crl != NULL) ctx->get_crl = store->get_crl; else ctx->get_crl = NULL; if (store != NULL && store->check_crl != NULL) ctx->check_crl = store->check_crl; else ctx->check_crl = check_crl; if (store != NULL && store->cert_crl != NULL) ctx->cert_crl = store->cert_crl; else ctx->cert_crl = cert_crl; if (store != NULL && store->check_policy != NULL) ctx->check_policy = store->check_policy; else ctx->check_policy = check_policy; if (store != NULL && store->lookup_certs != NULL) ctx->lookup_certs = store->lookup_certs; else ctx->lookup_certs = X509_STORE_CTX_get1_certs; if (store != NULL && store->lookup_crls != NULL) ctx->lookup_crls = store->lookup_crls; else ctx->lookup_crls = X509_STORE_CTX_get1_crls; ctx->param = X509_VERIFY_PARAM_new(); if (ctx->param == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB); goto err; } /* Inherit callbacks and flags from X509_STORE if not set use defaults. */ if (store == NULL) ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE; else if (X509_VERIFY_PARAM_inherit(ctx->param, store->param) == 0) goto err; if (!X509_STORE_CTX_set_default(ctx, "default")) goto err; /* * XXX: For now, continue to inherit trust from VPM, but infer from the * purpose if this still yields the default value. */ if (ctx->param->trust == X509_TRUST_DEFAULT) { int idx = X509_PURPOSE_get_by_id(ctx->param->purpose); X509_PURPOSE *xp = X509_PURPOSE_get0(idx); if (xp != NULL) ctx->param->trust = X509_PURPOSE_get_trust(xp); } if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &ctx->ex_data)) return 1; ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); err: /* * On error clean up allocated storage, if the store context was not * allocated with X509_STORE_CTX_new() this is our last chance to do so. */ X509_STORE_CTX_cleanup(ctx); return 0; } /* * Set alternative get_issuer method: just from a STACK of trusted certificates. * This avoids the complexity of X509_STORE where it is not needed. */ void X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk) { ctx->other_ctx = sk; ctx->get_issuer = get_issuer_sk; ctx->lookup_certs = lookup_certs_sk; } void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx) { /* * We need to be idempotent because, unfortunately, free() also calls * cleanup(), so the natural call sequence new(), init(), cleanup(), free() * calls cleanup() for the same object twice! Thus we must zero the * pointers below after they're freed! */ /* Seems to always be NULL in OpenSSL, do this at most once. */ if (ctx->cleanup != NULL) { ctx->cleanup(ctx); ctx->cleanup = NULL; } if (ctx->param != NULL) { if (ctx->parent == NULL) X509_VERIFY_PARAM_free(ctx->param); ctx->param = NULL; } X509_policy_tree_free(ctx->tree); ctx->tree = NULL; OSSL_STACK_OF_X509_free(ctx->chain); ctx->chain = NULL; CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data)); memset(&ctx->ex_data, 0, sizeof(ctx->ex_data)); } void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth) { X509_VERIFY_PARAM_set_depth(ctx->param, depth); } void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags) { X509_VERIFY_PARAM_set_flags(ctx->param, flags); } void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags, time_t t) { X509_VERIFY_PARAM_set_time(ctx->param, t); } void X509_STORE_CTX_set_current_reasons(X509_STORE_CTX *ctx, unsigned int current_reasons) { ctx->current_reasons = current_reasons; } X509 *X509_STORE_CTX_get0_cert(const X509_STORE_CTX *ctx) { return ctx->cert; } EVP_PKEY *X509_STORE_CTX_get0_rpk(const X509_STORE_CTX *ctx) { return ctx->rpk; } STACK_OF(X509) *X509_STORE_CTX_get0_untrusted(const X509_STORE_CTX *ctx) { return ctx->untrusted; } void X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk) { ctx->untrusted = sk; } void X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk) { OSSL_STACK_OF_X509_free(ctx->chain); ctx->chain = sk; } void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx, X509_STORE_CTX_verify_cb verify_cb) { ctx->verify_cb = verify_cb; } X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(const X509_STORE_CTX *ctx) { return ctx->verify_cb; } void X509_STORE_CTX_set_verify(X509_STORE_CTX *ctx, X509_STORE_CTX_verify_fn verify) { ctx->verify = verify; } X509_STORE_CTX_verify_fn X509_STORE_CTX_get_verify(const X509_STORE_CTX *ctx) { return ctx->verify; } X509_STORE_CTX_get_issuer_fn X509_STORE_CTX_get_get_issuer(const X509_STORE_CTX *ctx) { return ctx->get_issuer; } X509_STORE_CTX_check_issued_fn X509_STORE_CTX_get_check_issued(const X509_STORE_CTX *ctx) { return ctx->check_issued; } X509_STORE_CTX_check_revocation_fn X509_STORE_CTX_get_check_revocation(const X509_STORE_CTX *ctx) { return ctx->check_revocation; } X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(const X509_STORE_CTX *ctx) { return ctx->get_crl; } void X509_STORE_CTX_set_get_crl(X509_STORE_CTX *ctx, X509_STORE_CTX_get_crl_fn get_crl) { ctx->get_crl = get_crl; } X509_STORE_CTX_check_crl_fn X509_STORE_CTX_get_check_crl(const X509_STORE_CTX *ctx) { return ctx->check_crl; } X509_STORE_CTX_cert_crl_fn X509_STORE_CTX_get_cert_crl(const X509_STORE_CTX *ctx) { return ctx->cert_crl; } X509_STORE_CTX_check_policy_fn X509_STORE_CTX_get_check_policy(const X509_STORE_CTX *ctx) { return ctx->check_policy; } X509_STORE_CTX_lookup_certs_fn X509_STORE_CTX_get_lookup_certs(const X509_STORE_CTX *ctx) { return ctx->lookup_certs; } X509_STORE_CTX_lookup_crls_fn X509_STORE_CTX_get_lookup_crls(const X509_STORE_CTX *ctx) { return ctx->lookup_crls; } X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(const X509_STORE_CTX *ctx) { return ctx->cleanup; } X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(const X509_STORE_CTX *ctx) { return ctx->tree; } int X509_STORE_CTX_get_explicit_policy(const X509_STORE_CTX *ctx) { return ctx->explicit_policy; } int X509_STORE_CTX_get_num_untrusted(const X509_STORE_CTX *ctx) { return ctx->num_untrusted; } int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name) { const X509_VERIFY_PARAM *param; param = X509_VERIFY_PARAM_lookup(name); if (param == NULL) { ERR_raise_data(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID, "name=%s", name); return 0; } return X509_VERIFY_PARAM_inherit(ctx->param, param); } X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(const X509_STORE_CTX *ctx) { return ctx->param; } void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param) { X509_VERIFY_PARAM_free(ctx->param); ctx->param = param; } void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, SSL_DANE *dane) { ctx->dane = dane; } static unsigned char *dane_i2d(X509 *cert, uint8_t selector, unsigned int *i2dlen) { unsigned char *buf = NULL; int len; /* * Extract ASN.1 DER form of certificate or public key. */ switch (selector) { case DANETLS_SELECTOR_CERT: len = i2d_X509(cert, &buf); break; case DANETLS_SELECTOR_SPKI: len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf); break; default: ERR_raise(ERR_LIB_X509, X509_R_BAD_SELECTOR); return NULL; } if (len < 0 || buf == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB); return NULL; } *i2dlen = (unsigned int)len; return buf; } #define DANETLS_NONE 256 /* impossible uint8_t */ /* Returns -1 on internal error */ static int dane_match_cert(X509_STORE_CTX *ctx, X509 *cert, int depth) { SSL_DANE *dane = ctx->dane; unsigned usage = DANETLS_NONE; unsigned selector = DANETLS_NONE; unsigned ordinal = DANETLS_NONE; unsigned mtype = DANETLS_NONE; unsigned char *i2dbuf = NULL; unsigned int i2dlen = 0; unsigned char mdbuf[EVP_MAX_MD_SIZE]; unsigned char *cmpbuf = NULL; unsigned int cmplen = 0; int i; int recnum; int matched = 0; danetls_record *t = NULL; uint32_t mask; mask = (depth == 0) ? DANETLS_EE_MASK : DANETLS_TA_MASK; /* The trust store is not applicable with DANE-TA(2) */ if (depth >= ctx->num_untrusted) mask &= DANETLS_PKIX_MASK; /* * If we've previously matched a PKIX-?? record, no need to test any * further PKIX-?? records, it remains to just build the PKIX chain. * Had the match been a DANE-?? record, we'd be done already. */ if (dane->mdpth >= 0) mask &= ~DANETLS_PKIX_MASK; /*- * https://tools.ietf.org/html/rfc7671#section-5.1 * https://tools.ietf.org/html/rfc7671#section-5.2 * https://tools.ietf.org/html/rfc7671#section-5.3 * https://tools.ietf.org/html/rfc7671#section-5.4 * * We handle DANE-EE(3) records first as they require no chain building * and no expiration or hostname checks. We also process digests with * higher ordinals first and ignore lower priorities except Full(0) which * is always processed (last). If none match, we then process PKIX-EE(1). * * NOTE: This relies on DANE usages sorting before the corresponding PKIX * usages in SSL_dane_tlsa_add(), and also on descending sorting of digest * priorities. See twin comment in ssl/ssl_lib.c. * * We expect that most TLSA RRsets will have just a single usage, so we * don't go out of our way to cache multiple selector-specific i2d buffers * across usages, but if the selector happens to remain the same as switch * usages, that's OK. Thus, a set of "3 1 1", "3 0 1", "1 1 1", "1 0 1", * records would result in us generating each of the certificate and public * key DER forms twice, but more typically we'd just see multiple "3 1 1" * or multiple "3 0 1" records. * * As soon as we find a match at any given depth, we stop, because either * we've matched a DANE-?? record and the peer is authenticated, or, after * exhausting all DANE-?? records, we've matched a PKIX-?? record, which is * sufficient for DANE, and what remains to do is ordinary PKIX validation. */ recnum = (dane->umask & mask) != 0 ? sk_danetls_record_num(dane->trecs) : 0; for (i = 0; matched == 0 && i < recnum; ++i) { t = sk_danetls_record_value(dane->trecs, i); if ((DANETLS_USAGE_BIT(t->usage) & mask) == 0) continue; if (t->usage != usage) { usage = t->usage; /* Reset digest agility for each usage/selector pair */ mtype = DANETLS_NONE; ordinal = dane->dctx->mdord[t->mtype]; } if (t->selector != selector) { selector = t->selector; /* Update per-selector state */ OPENSSL_free(i2dbuf); i2dbuf = dane_i2d(cert, selector, &i2dlen); if (i2dbuf == NULL) return -1; /* Reset digest agility for each usage/selector pair */ mtype = DANETLS_NONE; ordinal = dane->dctx->mdord[t->mtype]; } else if (t->mtype != DANETLS_MATCHING_FULL) { /*- * Digest agility: * * <https://tools.ietf.org/html/rfc7671#section-9> * * For a fixed selector, after processing all records with the * highest mtype ordinal, ignore all mtypes with lower ordinals * other than "Full". */ if (dane->dctx->mdord[t->mtype] < ordinal) continue; } /* * Each time we hit a (new selector or) mtype, re-compute the relevant * digest, more complex caching is not worth the code space. */ if (t->mtype != mtype) { const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype]; cmpbuf = i2dbuf; cmplen = i2dlen; if (md != NULL) { cmpbuf = mdbuf; if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) { matched = -1; break; } } } /* * Squirrel away the certificate and depth if we have a match. Any * DANE match is dispositive, but with PKIX we still need to build a * full chain. */ if (cmplen == t->dlen && memcmp(cmpbuf, t->data, cmplen) == 0) { if (DANETLS_USAGE_BIT(usage) & DANETLS_DANE_MASK) matched = 1; if (matched || dane->mdpth < 0) { dane->mdpth = depth; dane->mtlsa = t; OPENSSL_free(dane->mcert); dane->mcert = cert; X509_up_ref(cert); } break; } } /* Clear the one-element DER cache */ OPENSSL_free(i2dbuf); return matched; } /* Returns -1 on internal error */ static int check_dane_issuer(X509_STORE_CTX *ctx, int depth) { SSL_DANE *dane = ctx->dane; int matched = 0; X509 *cert; if (!DANETLS_HAS_TA(dane) || depth == 0) return X509_TRUST_UNTRUSTED; /* * Record any DANE trust anchor matches, for the first depth to test, if * there's one at that depth. (This'll be false for length 1 chains looking * for an exact match for the leaf certificate). */ cert = sk_X509_value(ctx->chain, depth); if (cert != NULL && (matched = dane_match_cert(ctx, cert, depth)) < 0) return matched; if (matched > 0) { ctx->num_untrusted = depth - 1; return X509_TRUST_TRUSTED; } return X509_TRUST_UNTRUSTED; } static int check_dane_pkeys(X509_STORE_CTX *ctx) { SSL_DANE *dane = ctx->dane; danetls_record *t; int num = ctx->num_untrusted; X509 *cert = sk_X509_value(ctx->chain, num - 1); int recnum = sk_danetls_record_num(dane->trecs); int i; for (i = 0; i < recnum; ++i) { t = sk_danetls_record_value(dane->trecs, i); if (t->usage != DANETLS_USAGE_DANE_TA || t->selector != DANETLS_SELECTOR_SPKI || t->mtype != DANETLS_MATCHING_FULL || X509_verify(cert, t->spki) <= 0) continue; /* Clear any PKIX-?? matches that failed to extend to a full chain */ X509_free(dane->mcert); dane->mcert = NULL; /* Record match via a bare TA public key */ ctx->bare_ta_signed = 1; dane->mdpth = num - 1; dane->mtlsa = t; /* Prune any excess chain certificates */ num = sk_X509_num(ctx->chain); for (; num > ctx->num_untrusted; --num) X509_free(sk_X509_pop(ctx->chain)); return X509_TRUST_TRUSTED; } return X509_TRUST_UNTRUSTED; } /* * Only DANE-EE and SPKI are supported * Returns -1 on internal error */ static int dane_match_rpk(X509_STORE_CTX *ctx, EVP_PKEY *rpk) { SSL_DANE *dane = ctx->dane; danetls_record *t = NULL; int mtype = DANETLS_MATCHING_FULL; unsigned char *i2dbuf = NULL; unsigned int i2dlen = 0; unsigned char mdbuf[EVP_MAX_MD_SIZE]; unsigned char *cmpbuf; unsigned int cmplen = 0; int len; int recnum = sk_danetls_record_num(dane->trecs); int i; int matched = 0; /* Calculate ASN.1 DER of RPK */ if ((len = i2d_PUBKEY(rpk, &i2dbuf)) <= 0) return -1; cmplen = i2dlen = (unsigned int)len; cmpbuf = i2dbuf; for (i = 0; i < recnum; i++) { t = sk_danetls_record_value(dane->trecs, i); if (t->usage != DANETLS_USAGE_DANE_EE || t->selector != DANETLS_SELECTOR_SPKI) continue; /* Calculate hash - keep only one around */ if (t->mtype != mtype) { const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype]; cmpbuf = i2dbuf; cmplen = i2dlen; if (md != NULL) { cmpbuf = mdbuf; if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) { matched = -1; break; } } } if (cmplen == t->dlen && memcmp(cmpbuf, t->data, cmplen) == 0) { matched = 1; dane->mdpth = 0; dane->mtlsa = t; break; } } OPENSSL_free(i2dbuf); return matched; } static void dane_reset(SSL_DANE *dane) { /* Reset state to verify another chain, or clear after failure. */ X509_free(dane->mcert); dane->mcert = NULL; dane->mtlsa = NULL; dane->mdpth = -1; dane->pdpth = -1; } /* Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int check_leaf_suiteb(X509_STORE_CTX *ctx, X509 *cert) { int err = X509_chain_check_suiteb(NULL, cert, NULL, ctx->param->flags); CB_FAIL_IF(err != X509_V_OK, ctx, cert, 0, err); return 1; } /* Returns -1 on internal error */ static int dane_verify_rpk(X509_STORE_CTX *ctx) { SSL_DANE *dane = ctx->dane; int matched; dane_reset(dane); /* * Look for a DANE record for RPK * If error, return -1 * If found, call ctx->verify_cb(1, ctx) * If not found call ctx->verify_cb(0, ctx) */ matched = dane_match_rpk(ctx, ctx->rpk); ctx->error_depth = 0; if (matched < 0) { ctx->error = X509_V_ERR_UNSPECIFIED; return -1; } if (matched > 0) ctx->error = X509_V_OK; else ctx->error = X509_V_ERR_DANE_NO_MATCH; return verify_rpk(ctx); } /* Returns -1 on internal error */ static int dane_verify(X509_STORE_CTX *ctx) { X509 *cert = ctx->cert; SSL_DANE *dane = ctx->dane; int matched; int done; dane_reset(dane); /*- * When testing the leaf certificate, if we match a DANE-EE(3) record, * dane_match() returns 1 and we're done. If however we match a PKIX-EE(1) * record, the match depth and matching TLSA record are recorded, but the * return value is 0, because we still need to find a PKIX trust anchor. * Therefore, when DANE authentication is enabled (required), we're done * if: * + matched < 0, internal error. * + matched == 1, we matched a DANE-EE(3) record * + matched == 0, mdepth < 0 (no PKIX-EE match) and there are no * DANE-TA(2) or PKIX-TA(0) to test. */ matched = dane_match_cert(ctx, ctx->cert, 0); done = matched != 0 || (!DANETLS_HAS_TA(dane) && dane->mdpth < 0); if (done && !X509_get_pubkey_parameters(NULL, ctx->chain)) return -1; if (matched > 0) { /* Callback invoked as needed */ if (!check_leaf_suiteb(ctx, cert)) return 0; /* Callback invoked as needed */ if ((dane->flags & DANE_FLAG_NO_DANE_EE_NAMECHECKS) == 0 && !check_id(ctx)) return 0; /* Bypass internal_verify(), issue depth 0 success callback */ ctx->error_depth = 0; ctx->current_cert = cert; return ctx->verify_cb(1, ctx); } if (matched < 0) { ctx->error_depth = 0; ctx->current_cert = cert; ctx->error = X509_V_ERR_OUT_OF_MEM; return -1; } if (done) { /* Fail early, TA-based success is not possible */ if (!check_leaf_suiteb(ctx, cert)) return 0; return verify_cb_cert(ctx, cert, 0, X509_V_ERR_DANE_NO_MATCH); } /* * Chain verification for usages 0/1/2. TLSA record matching of depth > 0 * certificates happens in-line with building the rest of the chain. */ return verify_chain(ctx); } /* * Get trusted issuer, without duplicate suppression * Returns -1 on internal error. */ static int get1_trusted_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *cert) { STACK_OF(X509) *saved_chain = ctx->chain; int ok; ctx->chain = NULL; ok = ctx->get_issuer(issuer, ctx, cert); ctx->chain = saved_chain; return ok; } /*- * Returns -1 on internal error. * Sadly, returns 0 also on internal error in ctx->verify_cb(). */ static int build_chain(X509_STORE_CTX *ctx) { SSL_DANE *dane = ctx->dane; int num = sk_X509_num(ctx->chain); STACK_OF(X509) *sk_untrusted = NULL; unsigned int search; int may_trusted = 0; int may_alternate = 0; int trust = X509_TRUST_UNTRUSTED; int alt_untrusted = 0; int max_depth; int ok = 0; int i; /* Our chain starts with a single untrusted element. */ if (!ossl_assert(num == 1 && ctx->num_untrusted == num)) goto int_err; #define S_DOUNTRUSTED (1 << 0) /* Search untrusted chain */ #define S_DOTRUSTED (1 << 1) /* Search trusted store */ #define S_DOALTERNATE (1 << 2) /* Retry with pruned alternate chain */ /* * Set up search policy, untrusted if possible, trusted-first if enabled, * which is the default. * If we're doing DANE and not doing PKIX-TA/PKIX-EE, we never look in the * trust_store, otherwise we might look there first. If not trusted-first, * and alternate chains are not disabled, try building an alternate chain * if no luck with untrusted first. */ search = ctx->untrusted != NULL ? S_DOUNTRUSTED : 0; if (DANETLS_HAS_PKIX(dane) || !DANETLS_HAS_DANE(dane)) { if (search == 0 || (ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST) != 0) search |= S_DOTRUSTED; else if (!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) may_alternate = 1; may_trusted = 1; } /* Initialize empty untrusted stack. */ if ((sk_untrusted = sk_X509_new_null()) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto memerr; } /* * If we got any "Cert(0) Full(0)" trust anchors from DNS, *prepend* them * to our working copy of the untrusted certificate stack. */ if (DANETLS_ENABLED(dane) && dane->certs != NULL && !X509_add_certs(sk_untrusted, dane->certs, X509_ADD_FLAG_DEFAULT)) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto memerr; } /* * Shallow-copy the stack of untrusted certificates (with TLS, this is * typically the content of the peer's certificate message) so we can make * multiple passes over it, while free to remove elements as we go. */ if (!X509_add_certs(sk_untrusted, ctx->untrusted, X509_ADD_FLAG_DEFAULT)) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto memerr; } /* * Still absurdly large, but arithmetically safe, a lower hard upper bound * might be reasonable. */ if (ctx->param->depth > INT_MAX / 2) ctx->param->depth = INT_MAX / 2; /* * Try to extend the chain until we reach an ultimately trusted issuer. * Build chains up to one longer the limit, later fail if we hit the limit, * with an X509_V_ERR_CERT_CHAIN_TOO_LONG error code. */ max_depth = ctx->param->depth + 1; while (search != 0) { X509 *curr, *issuer = NULL; num = sk_X509_num(ctx->chain); ctx->error_depth = num - 1; /* * Look in the trust store if enabled for first lookup, or we've run * out of untrusted issuers and search here is not disabled. When we * reach the depth limit, we stop extending the chain, if by that point * we've not found a trust anchor, any trusted chain would be too long. * * The error reported to the application verify callback is at the * maximal valid depth with the current certificate equal to the last * not ultimately-trusted issuer. For example, with verify_depth = 0, * the callback will report errors at depth=1 when the immediate issuer * of the leaf certificate is not a trust anchor. No attempt will be * made to locate an issuer for that certificate, since such a chain * would be a-priori too long. */ if ((search & S_DOTRUSTED) != 0) { i = num; if ((search & S_DOALTERNATE) != 0) { /* * As high up the chain as we can, look for an alternative * trusted issuer of an untrusted certificate that currently * has an untrusted issuer. We use the alt_untrusted variable * to track how far up the chain we find the first match. It * is only if and when we find a match, that we prune the chain * and reset ctx->num_untrusted to the reduced count of * untrusted certificates. While we're searching for such a * match (which may never be found), it is neither safe nor * wise to preemptively modify either the chain or * ctx->num_untrusted. * * Note, like ctx->num_untrusted, alt_untrusted is a count of * untrusted certificates, not a "depth". */ i = alt_untrusted; } curr = sk_X509_value(ctx->chain, i - 1); /* Note: get1_trusted_issuer() must be used even if self-signed. */ ok = num > max_depth ? 0 : get1_trusted_issuer(&issuer, ctx, curr); if (ok < 0) { trust = -1; ctx->error = X509_V_ERR_STORE_LOOKUP; break; } if (ok > 0) { int self_signed = X509_self_signed(curr, 0); if (self_signed < 0) { X509_free(issuer); goto int_err; } /* * Alternative trusted issuer for a mid-chain untrusted cert? * Pop the untrusted cert's successors and retry. We might now * be able to complete a valid chain via the trust store. Note * that despite the current trust store match we might still * fail complete the chain to a suitable trust anchor, in which * case we may prune some more untrusted certificates and try * again. Thus the S_DOALTERNATE bit may yet be turned on * again with an even shorter untrusted chain! * * If in the process we threw away our matching PKIX-TA trust * anchor, reset DANE trust. We might find a suitable trusted * certificate among the ones from the trust store. */ if ((search & S_DOALTERNATE) != 0) { if (!ossl_assert(num > i && i > 0 && !self_signed)) { X509_free(issuer); goto int_err; } search &= ~S_DOALTERNATE; for (; num > i; --num) X509_free(sk_X509_pop(ctx->chain)); ctx->num_untrusted = num; if (DANETLS_ENABLED(dane) && dane->mdpth >= ctx->num_untrusted) { dane->mdpth = -1; X509_free(dane->mcert); dane->mcert = NULL; } if (DANETLS_ENABLED(dane) && dane->pdpth >= ctx->num_untrusted) dane->pdpth = -1; } if (!self_signed) { /* untrusted not self-signed certificate */ /* Grow the chain by trusted issuer */ if (!sk_X509_push(ctx->chain, issuer)) { X509_free(issuer); ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto memerr; } if ((self_signed = X509_self_signed(issuer, 0)) < 0) goto int_err; } else { /* * We have a self-signed untrusted cert that has the same * subject name (and perhaps keyid and/or serial number) as * a trust anchor. We must have an exact match to avoid * possible impersonation via key substitution etc. */ if (X509_cmp(curr, issuer) != 0) { /* Self-signed untrusted mimic. */ X509_free(issuer); ok = 0; } else { /* curr "==" issuer */ /* * Replace self-signed untrusted certificate * by its trusted matching issuer. */ X509_free(curr); ctx->num_untrusted = --num; (void)sk_X509_set(ctx->chain, num, issuer); } } /* * We've added a new trusted certificate to the chain, re-check * trust. If not done, and not self-signed look deeper. * Whether or not we're doing "trusted first", we no longer * look for untrusted certificates from the peer's chain. * * At this point ctx->num_trusted and num must reflect the * correct number of untrusted certificates, since the DANE * logic in check_trust() depends on distinguishing CAs from * "the wire" from CAs from the trust store. In particular, the * certificate at depth "num" should be the new trusted * certificate with ctx->num_untrusted <= num. */ if (ok) { if (!ossl_assert(ctx->num_untrusted <= num)) goto int_err; search &= ~S_DOUNTRUSTED; trust = check_trust(ctx, num); if (trust != X509_TRUST_UNTRUSTED) break; if (!self_signed) continue; } } /* * No dispositive decision, and either self-signed or no match, if * we were doing untrusted-first, and alt-chains are not disabled, * do that, by repeatedly losing one untrusted element at a time, * and trying to extend the shorted chain. */ if ((search & S_DOUNTRUSTED) == 0) { /* Continue search for a trusted issuer of a shorter chain? */ if ((search & S_DOALTERNATE) != 0 && --alt_untrusted > 0) continue; /* Still no luck and no fallbacks left? */ if (!may_alternate || (search & S_DOALTERNATE) != 0 || ctx->num_untrusted < 2) break; /* Search for a trusted issuer of a shorter chain */ search |= S_DOALTERNATE; alt_untrusted = ctx->num_untrusted - 1; } } /* * Try to extend chain with peer-provided untrusted certificate */ if ((search & S_DOUNTRUSTED) != 0) { num = sk_X509_num(ctx->chain); if (!ossl_assert(num == ctx->num_untrusted)) goto int_err; curr = sk_X509_value(ctx->chain, num - 1); issuer = (X509_self_signed(curr, 0) > 0 || num > max_depth) ? NULL : find_issuer(ctx, sk_untrusted, curr); if (issuer == NULL) { /* * Once we have reached a self-signed cert or num > max_depth * or can't find an issuer in the untrusted list we stop looking * there and start looking only in the trust store if enabled. */ search &= ~S_DOUNTRUSTED; if (may_trusted) search |= S_DOTRUSTED; continue; } /* Drop this issuer from future consideration */ (void)sk_X509_delete_ptr(sk_untrusted, issuer); /* Grow the chain by untrusted issuer */ if (!X509_add_cert(ctx->chain, issuer, X509_ADD_FLAG_UP_REF)) goto int_err; ++ctx->num_untrusted; /* Check for DANE-TA trust of the topmost untrusted certificate. */ trust = check_dane_issuer(ctx, ctx->num_untrusted - 1); if (trust == X509_TRUST_TRUSTED || trust == X509_TRUST_REJECTED) break; } } sk_X509_free(sk_untrusted); if (trust < 0) /* internal error */ return trust; /* * Last chance to make a trusted chain, either bare DANE-TA public-key * signers, or else direct leaf PKIX trust. */ num = sk_X509_num(ctx->chain); if (num <= max_depth) { if (trust == X509_TRUST_UNTRUSTED && DANETLS_HAS_DANE_TA(dane)) trust = check_dane_pkeys(ctx); if (trust == X509_TRUST_UNTRUSTED && num == ctx->num_untrusted) trust = check_trust(ctx, num); } switch (trust) { case X509_TRUST_TRUSTED: return 1; case X509_TRUST_REJECTED: /* Callback already issued */ return 0; case X509_TRUST_UNTRUSTED: default: switch (ctx->error) { case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: case X509_V_ERR_CERT_NOT_YET_VALID: case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: case X509_V_ERR_CERT_HAS_EXPIRED: return 0; /* Callback already done by ossl_x509_check_cert_time() */ default: /* A preliminary error has become final */ return verify_cb_cert(ctx, NULL, num - 1, ctx->error); case X509_V_OK: break; } CB_FAIL_IF(num > max_depth, ctx, NULL, num - 1, X509_V_ERR_CERT_CHAIN_TOO_LONG); CB_FAIL_IF(DANETLS_ENABLED(dane) && (!DANETLS_HAS_PKIX(dane) || dane->pdpth >= 0), ctx, NULL, num - 1, X509_V_ERR_DANE_NO_MATCH); if (X509_self_signed(sk_X509_value(ctx->chain, num - 1), 0) > 0) return verify_cb_cert(ctx, NULL, num - 1, num == 1 ? X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT : X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN); return verify_cb_cert(ctx, NULL, num - 1, ctx->num_untrusted < num ? X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT : X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY); } int_err: ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR); ctx->error = X509_V_ERR_UNSPECIFIED; sk_X509_free(sk_untrusted); return -1; memerr: ctx->error = X509_V_ERR_OUT_OF_MEM; sk_X509_free(sk_untrusted); return -1; } STACK_OF(X509) *X509_build_chain(X509 *target, STACK_OF(X509) *certs, X509_STORE *store, int with_self_signed, OSSL_LIB_CTX *libctx, const char *propq) { int finish_chain = store != NULL; X509_STORE_CTX *ctx; int flags = X509_ADD_FLAG_UP_REF; STACK_OF(X509) *result = NULL; if (target == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((ctx = X509_STORE_CTX_new_ex(libctx, propq)) == NULL) return NULL; if (!X509_STORE_CTX_init(ctx, store, target, finish_chain ? certs : NULL)) goto err; if (!finish_chain) X509_STORE_CTX_set0_trusted_stack(ctx, certs); if (!ossl_x509_add_cert_new(&ctx->chain, target, X509_ADD_FLAG_UP_REF)) { ctx->error = X509_V_ERR_OUT_OF_MEM; goto err; } ctx->num_untrusted = 1; if (!build_chain(ctx) && finish_chain) goto err; /* result list to store the up_ref'ed certificates */ if (sk_X509_num(ctx->chain) > 1 && !with_self_signed) flags |= X509_ADD_FLAG_NO_SS; if (!ossl_x509_add_certs_new(&result, ctx->chain, flags)) { sk_X509_free(result); result = NULL; } err: X509_STORE_CTX_free(ctx); return result; } /* * note that there's a corresponding minbits_table in ssl/ssl_cert.c * in ssl_get_security_level_bits that's used for selection of DH parameters */ static const int minbits_table[] = { 80, 112, 128, 192, 256 }; static const int NUM_AUTH_LEVELS = OSSL_NELEM(minbits_table); /*- * Check whether the given public key meets the security level of `ctx`. * Returns 1 on success, 0 otherwise. */ static int check_key_level(X509_STORE_CTX *ctx, EVP_PKEY *pkey) { int level = ctx->param->auth_level; /* * At security level zero, return without checking for a supported public * key type. Some engines support key types not understood outside the * engine, and we only need to understand the key when enforcing a security * floor. */ if (level <= 0) return 1; /* Unsupported or malformed keys are not secure */ if (pkey == NULL) return 0; if (level > NUM_AUTH_LEVELS) level = NUM_AUTH_LEVELS; return EVP_PKEY_get_security_bits(pkey) >= minbits_table[level - 1]; } /*- * Check whether the public key of `cert` meets the security level of `ctx`. * Returns 1 on success, 0 otherwise. */ static int check_cert_key_level(X509_STORE_CTX *ctx, X509 *cert) { return check_key_level(ctx, X509_get0_pubkey(cert)); } /*- * Check whether the public key of ``cert`` does not use explicit params * for an elliptic curve. * * Returns 1 on success, 0 if check fails, -1 for other errors. */ static int check_curve(X509 *cert) { EVP_PKEY *pkey = X509_get0_pubkey(cert); int ret, val; /* Unsupported or malformed key */ if (pkey == NULL) return -1; if (EVP_PKEY_get_id(pkey) != EVP_PKEY_EC) return 1; ret = EVP_PKEY_get_int_param(pkey, OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS, &val); return ret == 1 ? !val : -1; } /*- * Check whether the signature digest algorithm of ``cert`` meets the security * level of ``ctx``. Should not be checked for trust anchors (whether * self-signed or otherwise). * * Returns 1 on success, 0 otherwise. */ static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert) { int secbits = -1; int level = ctx->param->auth_level; if (level <= 0) return 1; if (level > NUM_AUTH_LEVELS) level = NUM_AUTH_LEVELS; if (!X509_get_signature_info(cert, NULL, NULL, &secbits, NULL)) return 0; return secbits >= minbits_table[level - 1]; }
./openssl/crypto/x509/v3_pcons.c
/* * Copyright 2003-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/asn1.h> #include <openssl/asn1t.h> #include <openssl/conf.h> #include <openssl/x509v3.h> #include "ext_dat.h" static STACK_OF(CONF_VALUE) *i2v_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *bcons, STACK_OF(CONF_VALUE) *extlist); static void *v2i_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *values); const X509V3_EXT_METHOD ossl_v3_policy_constraints = { NID_policy_constraints, 0, ASN1_ITEM_ref(POLICY_CONSTRAINTS), 0, 0, 0, 0, 0, 0, i2v_POLICY_CONSTRAINTS, v2i_POLICY_CONSTRAINTS, NULL, NULL, NULL }; ASN1_SEQUENCE(POLICY_CONSTRAINTS) = { ASN1_IMP_OPT(POLICY_CONSTRAINTS, requireExplicitPolicy, ASN1_INTEGER,0), ASN1_IMP_OPT(POLICY_CONSTRAINTS, inhibitPolicyMapping, ASN1_INTEGER,1) } ASN1_SEQUENCE_END(POLICY_CONSTRAINTS) IMPLEMENT_ASN1_ALLOC_FUNCTIONS(POLICY_CONSTRAINTS) static STACK_OF(CONF_VALUE) *i2v_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a, STACK_OF(CONF_VALUE) *extlist) { POLICY_CONSTRAINTS *pcons = a; X509V3_add_value_int("Require Explicit Policy", pcons->requireExplicitPolicy, &extlist); X509V3_add_value_int("Inhibit Policy Mapping", pcons->inhibitPolicyMapping, &extlist); return extlist; } static void *v2i_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *values) { POLICY_CONSTRAINTS *pcons = NULL; CONF_VALUE *val; int i; if ((pcons = POLICY_CONSTRAINTS_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); return NULL; } for (i = 0; i < sk_CONF_VALUE_num(values); i++) { val = sk_CONF_VALUE_value(values, i); if (strcmp(val->name, "requireExplicitPolicy") == 0) { if (!X509V3_get_value_int(val, &pcons->requireExplicitPolicy)) goto err; } else if (strcmp(val->name, "inhibitPolicyMapping") == 0) { if (!X509V3_get_value_int(val, &pcons->inhibitPolicyMapping)) goto err; } else { ERR_raise_data(ERR_LIB_X509V3, X509V3_R_INVALID_NAME, "%s", val->name); goto err; } } if (pcons->inhibitPolicyMapping == NULL && pcons->requireExplicitPolicy == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_ILLEGAL_EMPTY_EXTENSION); goto err; } return pcons; err: POLICY_CONSTRAINTS_free(pcons); return NULL; }
./openssl/crypto/x509/v3_pci.c
/* * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * This file is dual-licensed and is also available under the following * terms: * * Copyright (c) 2004 Kungliga Tekniska HΓΆgskolan * (Royal Institute of Technology, Stockholm, Sweden). * 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. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE 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 INSTITUTE 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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/x509v3.h> #include "ext_dat.h" static int i2r_pci(X509V3_EXT_METHOD *method, PROXY_CERT_INFO_EXTENSION *ext, BIO *out, int indent); static PROXY_CERT_INFO_EXTENSION *r2i_pci(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, char *str); const X509V3_EXT_METHOD ossl_v3_pci = { NID_proxyCertInfo, 0, ASN1_ITEM_ref(PROXY_CERT_INFO_EXTENSION), 0, 0, 0, 0, 0, 0, NULL, NULL, (X509V3_EXT_I2R)i2r_pci, (X509V3_EXT_R2I)r2i_pci, NULL, }; static int i2r_pci(X509V3_EXT_METHOD *method, PROXY_CERT_INFO_EXTENSION *pci, BIO *out, int indent) { BIO_printf(out, "%*sPath Length Constraint: ", indent, ""); if (pci->pcPathLengthConstraint) i2a_ASN1_INTEGER(out, pci->pcPathLengthConstraint); else BIO_printf(out, "infinite"); BIO_puts(out, "\n"); BIO_printf(out, "%*sPolicy Language: ", indent, ""); i2a_ASN1_OBJECT(out, pci->proxyPolicy->policyLanguage); if (pci->proxyPolicy->policy && pci->proxyPolicy->policy->data) BIO_printf(out, "\n%*sPolicy Text: %.*s", indent, "", pci->proxyPolicy->policy->length, pci->proxyPolicy->policy->data); return 1; } static int process_pci_value(CONF_VALUE *val, ASN1_OBJECT **language, ASN1_INTEGER **pathlen, ASN1_OCTET_STRING **policy) { int free_policy = 0; if (strcmp(val->name, "language") == 0) { if (*language) { ERR_raise(ERR_LIB_X509V3, X509V3_R_POLICY_LANGUAGE_ALREADY_DEFINED); X509V3_conf_err(val); return 0; } if ((*language = OBJ_txt2obj(val->value, 0)) == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER); X509V3_conf_err(val); return 0; } } else if (strcmp(val->name, "pathlen") == 0) { if (*pathlen) { ERR_raise(ERR_LIB_X509V3, X509V3_R_POLICY_PATH_LENGTH_ALREADY_DEFINED); X509V3_conf_err(val); return 0; } if (!X509V3_get_value_int(val, pathlen)) { ERR_raise(ERR_LIB_X509V3, X509V3_R_POLICY_PATH_LENGTH); X509V3_conf_err(val); return 0; } } else if (strcmp(val->name, "policy") == 0) { char *valp = val->value; unsigned char *tmp_data = NULL; long val_len; if (*policy == NULL) { *policy = ASN1_OCTET_STRING_new(); if (*policy == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); X509V3_conf_err(val); return 0; } free_policy = 1; } if (CHECK_AND_SKIP_PREFIX(valp, "hex:")) { unsigned char *tmp_data2 = OPENSSL_hexstr2buf(valp, &val_len); if (!tmp_data2) { X509V3_conf_err(val); goto err; } tmp_data = OPENSSL_realloc((*policy)->data, (*policy)->length + val_len + 1); if (tmp_data) { (*policy)->data = tmp_data; memcpy(&(*policy)->data[(*policy)->length], tmp_data2, val_len); (*policy)->length += val_len; (*policy)->data[(*policy)->length] = '\0'; } else { OPENSSL_free(tmp_data2); /* * realloc failure implies the original data space is b0rked * too! */ OPENSSL_free((*policy)->data); (*policy)->data = NULL; (*policy)->length = 0; X509V3_conf_err(val); goto err; } OPENSSL_free(tmp_data2); } else if (CHECK_AND_SKIP_PREFIX(valp, "file:")) { unsigned char buf[2048]; int n; BIO *b = BIO_new_file(valp, "r"); if (!b) { ERR_raise(ERR_LIB_X509V3, ERR_R_BIO_LIB); X509V3_conf_err(val); goto err; } while ((n = BIO_read(b, buf, sizeof(buf))) > 0 || (n == 0 && BIO_should_retry(b))) { if (!n) continue; tmp_data = OPENSSL_realloc((*policy)->data, (*policy)->length + n + 1); if (!tmp_data) { OPENSSL_free((*policy)->data); (*policy)->data = NULL; (*policy)->length = 0; X509V3_conf_err(val); BIO_free_all(b); goto err; } (*policy)->data = tmp_data; memcpy(&(*policy)->data[(*policy)->length], buf, n); (*policy)->length += n; (*policy)->data[(*policy)->length] = '\0'; } BIO_free_all(b); if (n < 0) { ERR_raise(ERR_LIB_X509V3, ERR_R_BIO_LIB); X509V3_conf_err(val); goto err; } } else if (CHECK_AND_SKIP_PREFIX(valp, "text:")) { val_len = strlen(valp); tmp_data = OPENSSL_realloc((*policy)->data, (*policy)->length + val_len + 1); if (tmp_data) { (*policy)->data = tmp_data; memcpy(&(*policy)->data[(*policy)->length], val->value + 5, val_len); (*policy)->length += val_len; (*policy)->data[(*policy)->length] = '\0'; } else { /* * realloc failure implies the original data space is b0rked * too! */ OPENSSL_free((*policy)->data); (*policy)->data = NULL; (*policy)->length = 0; X509V3_conf_err(val); goto err; } } else { ERR_raise(ERR_LIB_X509V3, X509V3_R_INCORRECT_POLICY_SYNTAX_TAG); X509V3_conf_err(val); goto err; } if (!tmp_data) { X509V3_conf_err(val); goto err; } } return 1; err: if (free_policy) { ASN1_OCTET_STRING_free(*policy); *policy = NULL; } return 0; } static PROXY_CERT_INFO_EXTENSION *r2i_pci(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, char *value) { PROXY_CERT_INFO_EXTENSION *pci = NULL; STACK_OF(CONF_VALUE) *vals; ASN1_OBJECT *language = NULL; ASN1_INTEGER *pathlen = NULL; ASN1_OCTET_STRING *policy = NULL; int i, j; vals = X509V3_parse_list(value); for (i = 0; i < sk_CONF_VALUE_num(vals); i++) { CONF_VALUE *cnf = sk_CONF_VALUE_value(vals, i); if (!cnf->name || (*cnf->name != '@' && !cnf->value)) { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_PROXY_POLICY_SETTING); X509V3_conf_err(cnf); goto err; } if (*cnf->name == '@') { STACK_OF(CONF_VALUE) *sect; int success_p = 1; sect = X509V3_get_section(ctx, cnf->name + 1); if (!sect) { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SECTION); X509V3_conf_err(cnf); goto err; } for (j = 0; success_p && j < sk_CONF_VALUE_num(sect); j++) { success_p = process_pci_value(sk_CONF_VALUE_value(sect, j), &language, &pathlen, &policy); } X509V3_section_free(ctx, sect); if (!success_p) goto err; } else { if (!process_pci_value(cnf, &language, &pathlen, &policy)) { X509V3_conf_err(cnf); goto err; } } } /* Language is mandatory */ if (!language) { ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_PROXY_CERT_POLICY_LANGUAGE_DEFINED); goto err; } i = OBJ_obj2nid(language); if ((i == NID_Independent || i == NID_id_ppl_inheritAll) && policy) { ERR_raise(ERR_LIB_X509V3, X509V3_R_POLICY_WHEN_PROXY_LANGUAGE_REQUIRES_NO_POLICY); goto err; } pci = PROXY_CERT_INFO_EXTENSION_new(); if (pci == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } pci->proxyPolicy->policyLanguage = language; language = NULL; pci->proxyPolicy->policy = policy; policy = NULL; pci->pcPathLengthConstraint = pathlen; pathlen = NULL; goto end; err: ASN1_OBJECT_free(language); ASN1_INTEGER_free(pathlen); pathlen = NULL; ASN1_OCTET_STRING_free(policy); policy = NULL; PROXY_CERT_INFO_EXTENSION_free(pci); pci = NULL; end: sk_CONF_VALUE_pop_free(vals, X509V3_conf_free); return pci; }
./openssl/crypto/x509/x509_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/x509err.h> #include "crypto/x509err.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA X509_str_reasons[] = { {ERR_PACK(ERR_LIB_X509, 0, X509_R_AKID_MISMATCH), "akid mismatch"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_BAD_SELECTOR), "bad selector"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_BAD_X509_FILETYPE), "bad x509 filetype"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_BASE64_DECODE_ERROR), "base64 decode error"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_CANT_CHECK_DH_KEY), "can't check dh key"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_CERTIFICATE_VERIFICATION_FAILED), "certificate verification failed"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_CERT_ALREADY_IN_HASH_TABLE), "cert already in hash table"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_CRL_ALREADY_DELTA), "crl already delta"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_CRL_VERIFY_FAILURE), "crl verify failure"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_DUPLICATE_ATTRIBUTE), "duplicate attribute"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_ERROR_GETTING_MD_BY_NID), "error getting md by nid"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_ERROR_USING_SIGINF_SET), "error using siginf set"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_IDP_MISMATCH), "idp mismatch"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_ATTRIBUTES), "invalid attributes"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_DIRECTORY), "invalid directory"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_DISTPOINT), "invalid distpoint"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_FIELD_NAME), "invalid field name"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_TRUST), "invalid trust"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_ISSUER_MISMATCH), "issuer mismatch"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_KEY_TYPE_MISMATCH), "key type mismatch"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_KEY_VALUES_MISMATCH), "key values mismatch"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_LOADING_CERT_DIR), "loading cert dir"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_LOADING_DEFAULTS), "loading defaults"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_METHOD_NOT_SUPPORTED), "method not supported"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_NAME_TOO_LONG), "name too long"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_NEWER_CRL_NOT_NEWER), "newer crl not newer"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CERTIFICATE_FOUND), "no certificate found"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CERTIFICATE_OR_CRL_FOUND), "no certificate or crl found"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY), "no cert set for us to verify"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CRL_FOUND), "no crl found"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CRL_NUMBER), "no crl number"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_PUBLIC_KEY_DECODE_ERROR), "public key decode error"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_PUBLIC_KEY_ENCODE_ERROR), "public key encode error"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_SHOULD_RETRY), "should retry"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN), "unable to find parameters in chain"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY), "unable to get certs public key"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_KEY_TYPE), "unknown key type"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_NID), "unknown nid"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_PURPOSE_ID), "unknown purpose id"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_SIGID_ALGS), "unknown sigid algs"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_TRUST_ID), "unknown trust id"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNSUPPORTED_ALGORITHM), "unsupported algorithm"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_WRONG_LOOKUP_TYPE), "wrong lookup type"}, {ERR_PACK(ERR_LIB_X509, 0, X509_R_WRONG_TYPE), "wrong type"}, {0, NULL} }; #endif int ossl_err_load_X509_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(X509_str_reasons[0].error) == NULL) ERR_load_strings_const(X509_str_reasons); #endif return 1; }
./openssl/crypto/x509/x509_set.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include "internal/refcount.h" #include <openssl/asn1.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include "crypto/asn1.h" #include "crypto/x509.h" #include "x509_local.h" int X509_set_version(X509 *x, long version) { if (x == NULL) return 0; if (version == X509_get_version(x)) return 1; /* avoid needless modification even re-allocation */ if (version == X509_VERSION_1) { ASN1_INTEGER_free(x->cert_info.version); x->cert_info.version = NULL; x->cert_info.enc.modified = 1; return 1; } if (x->cert_info.version == NULL) { if ((x->cert_info.version = ASN1_INTEGER_new()) == NULL) return 0; } if (!ASN1_INTEGER_set(x->cert_info.version, version)) return 0; x->cert_info.enc.modified = 1; return 1; } int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial) { ASN1_INTEGER *in; if (x == NULL) return 0; in = &x->cert_info.serialNumber; if (in != serial) return ASN1_STRING_copy(in, serial); x->cert_info.enc.modified = 1; return 1; } int X509_set_issuer_name(X509 *x, const X509_NAME *name) { if (x == NULL || !X509_NAME_set(&x->cert_info.issuer, name)) return 0; x->cert_info.enc.modified = 1; return 1; } int X509_set_subject_name(X509 *x, const X509_NAME *name) { if (x == NULL || !X509_NAME_set(&x->cert_info.subject, name)) return 0; x->cert_info.enc.modified = 1; return 1; } int ossl_x509_set1_time(int *modified, ASN1_TIME **ptm, const ASN1_TIME *tm) { ASN1_TIME *new; if (*ptm == tm) return 1; new = ASN1_STRING_dup(tm); if (tm != NULL && new == NULL) return 0; ASN1_TIME_free(*ptm); *ptm = new; if (modified != NULL) *modified = 1; return 1; } int X509_set1_notBefore(X509 *x, const ASN1_TIME *tm) { if (x == NULL || tm == NULL) return 0; return ossl_x509_set1_time(&x->cert_info.enc.modified, &x->cert_info.validity.notBefore, tm); } int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm) { if (x == NULL || tm == NULL) return 0; return ossl_x509_set1_time(&x->cert_info.enc.modified, &x->cert_info.validity.notAfter, tm); } int X509_set_pubkey(X509 *x, EVP_PKEY *pkey) { if (x == NULL) return 0; if (!X509_PUBKEY_set(&(x->cert_info.key), pkey)) return 0; x->cert_info.enc.modified = 1; return 1; } int X509_up_ref(X509 *x) { int i; if (CRYPTO_UP_REF(&x->references, &i) <= 0) return 0; REF_PRINT_COUNT("X509", x); REF_ASSERT_ISNT(i < 2); return i > 1; } long X509_get_version(const X509 *x) { return ASN1_INTEGER_get(x->cert_info.version); } const ASN1_TIME *X509_get0_notBefore(const X509 *x) { return x->cert_info.validity.notBefore; } const ASN1_TIME *X509_get0_notAfter(const X509 *x) { return x->cert_info.validity.notAfter; } ASN1_TIME *X509_getm_notBefore(const X509 *x) { return x->cert_info.validity.notBefore; } ASN1_TIME *X509_getm_notAfter(const X509 *x) { return x->cert_info.validity.notAfter; } int X509_get_signature_type(const X509 *x) { return EVP_PKEY_type(OBJ_obj2nid(x->sig_alg.algorithm)); } X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x) { return x->cert_info.key; } const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x) { return x->cert_info.extensions; } void X509_get0_uids(const X509 *x, const ASN1_BIT_STRING **piuid, const ASN1_BIT_STRING **psuid) { if (piuid != NULL) *piuid = x->cert_info.issuerUID; if (psuid != NULL) *psuid = x->cert_info.subjectUID; } const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x) { return &x->cert_info.signature; } int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid, int *secbits, uint32_t *flags) { if (mdnid != NULL) *mdnid = siginf->mdnid; if (pknid != NULL) *pknid = siginf->pknid; if (secbits != NULL) *secbits = siginf->secbits; if (flags != NULL) *flags = siginf->flags; return (siginf->flags & X509_SIG_INFO_VALID) != 0; } void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid, int secbits, uint32_t flags) { siginf->mdnid = mdnid; siginf->pknid = pknid; siginf->secbits = secbits; siginf->flags = flags; } int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits, uint32_t *flags) { X509_check_purpose(x, -1, -1); return X509_SIG_INFO_get(&x->siginf, mdnid, pknid, secbits, flags); } /* Modify *siginf according to alg and sig. Return 1 on success, else 0. */ static int x509_sig_info_init(X509_SIG_INFO *siginf, const X509_ALGOR *alg, const ASN1_STRING *sig, const EVP_PKEY *pubkey) { int pknid, mdnid; const EVP_MD *md; const EVP_PKEY_ASN1_METHOD *ameth; siginf->mdnid = NID_undef; siginf->pknid = NID_undef; siginf->secbits = -1; siginf->flags = 0; if (!OBJ_find_sigid_algs(OBJ_obj2nid(alg->algorithm), &mdnid, &pknid) || pknid == NID_undef) { ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_SIGID_ALGS); return 0; } siginf->mdnid = mdnid; siginf->pknid = pknid; switch (mdnid) { case NID_undef: /* If we have one, use a custom handler for this algorithm */ ameth = EVP_PKEY_asn1_find(NULL, pknid); if (ameth != NULL && ameth->siginf_set != NULL && ameth->siginf_set(siginf, alg, sig)) break; if (pubkey != NULL) { int secbits; secbits = EVP_PKEY_get_security_bits(pubkey); if (secbits != 0) { siginf->secbits = secbits; break; } } ERR_raise(ERR_LIB_X509, X509_R_ERROR_USING_SIGINF_SET); return 0; /* * SHA1 and MD5 are known to be broken. Reduce security bits so that * they're no longer accepted at security level 1. * The real values don't really matter as long as they're lower than 80, * which is our security level 1. */ case NID_sha1: /* * https://eprint.iacr.org/2020/014 puts a chosen-prefix attack * for SHA1 at2^63.4 */ siginf->secbits = 63; break; case NID_md5: /* * https://documents.epfl.ch/users/l/le/lenstra/public/papers/lat.pdf * puts a chosen-prefix attack for MD5 at 2^39. */ siginf->secbits = 39; break; case NID_id_GostR3411_94: /* * There is a collision attack on GOST R 34.11-94 at 2^105, see * https://link.springer.com/chapter/10.1007%2F978-3-540-85174-5_10 */ siginf->secbits = 105; break; default: /* Security bits: half number of bits in digest */ if ((md = EVP_get_digestbynid(mdnid)) == NULL) { ERR_raise(ERR_LIB_X509, X509_R_ERROR_GETTING_MD_BY_NID); return 0; } siginf->secbits = EVP_MD_get_size(md) * 4; break; } switch (mdnid) { case NID_sha1: case NID_sha256: case NID_sha384: case NID_sha512: siginf->flags |= X509_SIG_INFO_TLS; } siginf->flags |= X509_SIG_INFO_VALID; return 1; } /* Returns 1 on success, 0 on failure */ int ossl_x509_init_sig_info(X509 *x) { return x509_sig_info_init(&x->siginf, &x->sig_alg, &x->signature, X509_PUBKEY_get0(x->cert_info.key)); }
./openssl/crypto/x509/v3_no_ass.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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/x509v3.h> #include "ext_dat.h" static int i2r_NO_ASSERTION(X509V3_EXT_METHOD *method, void *su, BIO *out, int indent) { return 1; } static void *r2i_NO_ASSERTION(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *value) { return ASN1_NULL_new(); } static char *i2s_NO_ASSERTION(const X509V3_EXT_METHOD *method, void *val) { return OPENSSL_strdup("NULL"); } static void *s2i_NO_ASSERTION(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str) { return ASN1_NULL_new(); } /* * The noAssertion X.509v3 extension is defined in ITU Recommendation X.509 * (2019), Section 17.5.2.7. See: https://www.itu.int/rec/T-REC-X.509-201910-I/en. */ const X509V3_EXT_METHOD ossl_v3_no_assertion = { NID_no_assertion, 0, ASN1_ITEM_ref(ASN1_NULL), 0, 0, 0, 0, (X509V3_EXT_I2S)i2s_NO_ASSERTION, (X509V3_EXT_S2I)s2i_NO_ASSERTION, 0, 0, (X509V3_EXT_I2R)i2r_NO_ASSERTION, (X509V3_EXT_R2I)r2i_NO_ASSERTION, NULL };
./openssl/crypto/x509/x_attrib.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 <openssl/objects.h> #include <openssl/asn1t.h> #include <openssl/x509.h> #include "x509_local.h" /*- * X509_ATTRIBUTE: this has the following form: * * typedef struct x509_attributes_st * { * ASN1_OBJECT *object; * STACK_OF(ASN1_TYPE) *set; * } X509_ATTRIBUTE; * */ ASN1_SEQUENCE(X509_ATTRIBUTE) = { ASN1_SIMPLE(X509_ATTRIBUTE, object, ASN1_OBJECT), ASN1_SET_OF(X509_ATTRIBUTE, set, ASN1_ANY) } ASN1_SEQUENCE_END(X509_ATTRIBUTE) IMPLEMENT_ASN1_FUNCTIONS(X509_ATTRIBUTE) IMPLEMENT_ASN1_DUP_FUNCTION(X509_ATTRIBUTE) X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value) { X509_ATTRIBUTE *ret = NULL; ASN1_TYPE *val = NULL; ASN1_OBJECT *oid; if ((oid = OBJ_nid2obj(nid)) == NULL) return NULL; if ((ret = X509_ATTRIBUTE_new()) == NULL) return NULL; ret->object = oid; if ((val = ASN1_TYPE_new()) == NULL) goto err; if (!sk_ASN1_TYPE_push(ret->set, val)) goto err; ASN1_TYPE_set(val, atrtype, value); return ret; err: X509_ATTRIBUTE_free(ret); ASN1_TYPE_free(val); return NULL; }
./openssl/crypto/x509/x509_obj.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 <openssl/objects.h> #include <openssl/x509.h> #include <openssl/buffer.h> #include "crypto/x509.h" #include "crypto/ctype.h" /* * Limit to ensure we don't overflow: much greater than * anything encountered in practice. */ #define NAME_ONELINE_MAX (1024 * 1024) char *X509_NAME_oneline(const X509_NAME *a, char *buf, int len) { const X509_NAME_ENTRY *ne; int i; int n, lold, l, l1, l2, num, j, type; int prev_set = -1; const char *s; char *p; unsigned char *q; BUF_MEM *b = NULL; static const char hex[17] = "0123456789ABCDEF"; int gs_doit[4]; char tmp_buf[80]; #ifdef CHARSET_EBCDIC unsigned char ebcdic_buf[1024]; #endif if (buf == NULL) { if ((b = BUF_MEM_new()) == NULL) goto buferr; if (!BUF_MEM_grow(b, 200)) goto buferr; b->data[0] = '\0'; len = 200; } else if (len == 0) { return NULL; } if (a == NULL) { if (b) { buf = b->data; OPENSSL_free(b); } strncpy(buf, "NO X509_NAME", len); buf[len - 1] = '\0'; return buf; } len--; /* space for '\0' */ l = 0; for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) { ne = sk_X509_NAME_ENTRY_value(a->entries, i); n = OBJ_obj2nid(ne->object); if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) { i2t_ASN1_OBJECT(tmp_buf, sizeof(tmp_buf), ne->object); s = tmp_buf; } l1 = strlen(s); type = ne->value->type; num = ne->value->length; if (num > NAME_ONELINE_MAX) { ERR_raise(ERR_LIB_X509, X509_R_NAME_TOO_LONG); goto end; } q = ne->value->data; #ifdef CHARSET_EBCDIC if (type == V_ASN1_GENERALSTRING || type == V_ASN1_VISIBLESTRING || type == V_ASN1_PRINTABLESTRING || type == V_ASN1_TELETEXSTRING || type == V_ASN1_IA5STRING) { if (num > (int)sizeof(ebcdic_buf)) num = sizeof(ebcdic_buf); ascii2ebcdic(ebcdic_buf, q, num); q = ebcdic_buf; } #endif if ((type == V_ASN1_GENERALSTRING) && ((num % 4) == 0)) { gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 0; for (j = 0; j < num; j++) if (q[j] != 0) gs_doit[j & 3] = 1; if (gs_doit[0] | gs_doit[1] | gs_doit[2]) gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1; else { gs_doit[0] = gs_doit[1] = gs_doit[2] = 0; gs_doit[3] = 1; } } else gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1; for (l2 = j = 0; j < num; j++) { if (!gs_doit[j & 3]) continue; l2++; if (q[j] == '/' || q[j] == '+') l2++; /* char needs to be escaped */ else if ((ossl_toascii(q[j]) < ossl_toascii(' ')) || (ossl_toascii(q[j]) > ossl_toascii('~'))) l2 += 3; } lold = l; l += 1 + l1 + 1 + l2; if (l > NAME_ONELINE_MAX) { ERR_raise(ERR_LIB_X509, X509_R_NAME_TOO_LONG); goto end; } if (b != NULL) { if (!BUF_MEM_grow(b, l + 1)) goto buferr; p = &(b->data[lold]); } else if (l > len) { break; } else p = &(buf[lold]); *(p++) = prev_set == ne->set ? '+' : '/'; memcpy(p, s, (unsigned int)l1); p += l1; *(p++) = '='; #ifndef CHARSET_EBCDIC /* q was assigned above already. */ q = ne->value->data; #endif for (j = 0; j < num; j++) { if (!gs_doit[j & 3]) continue; #ifndef CHARSET_EBCDIC n = q[j]; if ((n < ' ') || (n > '~')) { *(p++) = '\\'; *(p++) = 'x'; *(p++) = hex[(n >> 4) & 0x0f]; *(p++) = hex[n & 0x0f]; } else { if (n == '/' || n == '+') *(p++) = '\\'; *(p++) = n; } #else n = os_toascii[q[j]]; if ((n < os_toascii[' ']) || (n > os_toascii['~'])) { *(p++) = '\\'; *(p++) = 'x'; *(p++) = hex[(n >> 4) & 0x0f]; *(p++) = hex[n & 0x0f]; } else { if (n == os_toascii['/'] || n == os_toascii['+']) *(p++) = '\\'; *(p++) = q[j]; } #endif } *p = '\0'; prev_set = ne->set; } if (b != NULL) { p = b->data; OPENSSL_free(b); } else p = buf; if (i == 0) *p = '\0'; return p; buferr: ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB); end: BUF_MEM_free(b); return NULL; }
./openssl/crypto/x509/x509_cmp.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/core_names.h> #include "crypto/x509.h" int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b) { int i; const X509_CINF *ai, *bi; if (b == NULL) return a != NULL; if (a == NULL) return -1; ai = &a->cert_info; bi = &b->cert_info; i = ASN1_INTEGER_cmp(&ai->serialNumber, &bi->serialNumber); if (i != 0) return i < 0 ? -1 : 1; return X509_NAME_cmp(ai->issuer, bi->issuer); } #ifndef OPENSSL_NO_MD5 unsigned long X509_issuer_and_serial_hash(X509 *a) { unsigned long ret = 0; EVP_MD_CTX *ctx = EVP_MD_CTX_new(); unsigned char md[16]; char *f = NULL; EVP_MD *digest = NULL; if (ctx == NULL) goto err; f = X509_NAME_oneline(a->cert_info.issuer, NULL, 0); if (f == NULL) goto err; digest = EVP_MD_fetch(a->libctx, SN_md5, a->propq); if (digest == NULL) goto err; if (!EVP_DigestInit_ex(ctx, digest, NULL)) goto err; if (!EVP_DigestUpdate(ctx, (unsigned char *)f, strlen(f))) goto err; if (!EVP_DigestUpdate (ctx, (unsigned char *)a->cert_info.serialNumber.data, (unsigned long)a->cert_info.serialNumber.length)) goto err; if (!EVP_DigestFinal_ex(ctx, &(md[0]), NULL)) goto err; ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) | ((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L) ) & 0xffffffffL; err: OPENSSL_free(f); EVP_MD_free(digest); EVP_MD_CTX_free(ctx); return ret; } #endif int X509_issuer_name_cmp(const X509 *a, const X509 *b) { return X509_NAME_cmp(a->cert_info.issuer, b->cert_info.issuer); } int X509_subject_name_cmp(const X509 *a, const X509 *b) { return X509_NAME_cmp(a->cert_info.subject, b->cert_info.subject); } int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b) { return X509_NAME_cmp(a->crl.issuer, b->crl.issuer); } int X509_CRL_match(const X509_CRL *a, const X509_CRL *b) { int rv; if ((a->flags & EXFLAG_NO_FINGERPRINT) == 0 && (b->flags & EXFLAG_NO_FINGERPRINT) == 0) rv = memcmp(a->sha1_hash, b->sha1_hash, SHA_DIGEST_LENGTH); else return -2; return rv < 0 ? -1 : rv > 0; } X509_NAME *X509_get_issuer_name(const X509 *a) { return a->cert_info.issuer; } unsigned long X509_issuer_name_hash(X509 *x) { return X509_NAME_hash_ex(x->cert_info.issuer, NULL, NULL, NULL); } #ifndef OPENSSL_NO_MD5 unsigned long X509_issuer_name_hash_old(X509 *x) { return X509_NAME_hash_old(x->cert_info.issuer); } #endif X509_NAME *X509_get_subject_name(const X509 *a) { return a->cert_info.subject; } ASN1_INTEGER *X509_get_serialNumber(X509 *a) { return &a->cert_info.serialNumber; } const ASN1_INTEGER *X509_get0_serialNumber(const X509 *a) { return &a->cert_info.serialNumber; } unsigned long X509_subject_name_hash(X509 *x) { return X509_NAME_hash_ex(x->cert_info.subject, NULL, NULL, NULL); } #ifndef OPENSSL_NO_MD5 unsigned long X509_subject_name_hash_old(X509 *x) { return X509_NAME_hash_old(x->cert_info.subject); } #endif /* * Compare two certificates: they must be identical for this to work. NB: * Although "cmp" operations are generally prototyped to take "const" * arguments (eg. for use in STACKs), the way X509 handling is - these * operations may involve ensuring the hashes are up-to-date and ensuring * certain cert information is cached. So this is the point where the * "depth-first" constification tree has to halt with an evil cast. */ int X509_cmp(const X509 *a, const X509 *b) { int rv = 0; if (a == b) /* for efficiency */ return 0; /* attempt to compute cert hash */ (void)X509_check_purpose((X509 *)a, -1, 0); (void)X509_check_purpose((X509 *)b, -1, 0); if ((a->ex_flags & EXFLAG_NO_FINGERPRINT) == 0 && (b->ex_flags & EXFLAG_NO_FINGERPRINT) == 0) rv = memcmp(a->sha1_hash, b->sha1_hash, SHA_DIGEST_LENGTH); if (rv != 0) return rv < 0 ? -1 : 1; /* Check for match against stored encoding too */ if (!a->cert_info.enc.modified && !b->cert_info.enc.modified) { if (a->cert_info.enc.len < b->cert_info.enc.len) return -1; if (a->cert_info.enc.len > b->cert_info.enc.len) return 1; rv = memcmp(a->cert_info.enc.enc, b->cert_info.enc.enc, a->cert_info.enc.len); } return rv < 0 ? -1 : rv > 0; } int ossl_x509_add_cert_new(STACK_OF(X509) **p_sk, X509 *cert, int flags) { if (*p_sk == NULL && (*p_sk = sk_X509_new_null()) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); return 0; } return X509_add_cert(*p_sk, cert, flags); } int X509_add_cert(STACK_OF(X509) *sk, X509 *cert, int flags) { if (sk == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((flags & X509_ADD_FLAG_NO_DUP) != 0) { /* * not using sk_X509_set_cmp_func() and sk_X509_find() * because this re-orders the certs on the stack */ int i; for (i = 0; i < sk_X509_num(sk); i++) { if (X509_cmp(sk_X509_value(sk, i), cert) == 0) return 1; } } if ((flags & X509_ADD_FLAG_NO_SS) != 0) { int ret = X509_self_signed(cert, 0); if (ret != 0) return ret > 0 ? 1 : 0; } if (!sk_X509_insert(sk, cert, (flags & X509_ADD_FLAG_PREPEND) != 0 ? 0 : -1)) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); return 0; } if ((flags & X509_ADD_FLAG_UP_REF) != 0) (void)X509_up_ref(cert); return 1; } int X509_add_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs, int flags) /* compiler would allow 'const' for the certs, yet they may get up-ref'ed */ { if (sk == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return 0; } return ossl_x509_add_certs_new(&sk, certs, flags); } int ossl_x509_add_certs_new(STACK_OF(X509) **p_sk, STACK_OF(X509) *certs, int flags) /* compiler would allow 'const' for the certs, yet they may get up-ref'ed */ { int n = sk_X509_num(certs /* may be NULL */); int i; for (i = 0; i < n; i++) { int j = (flags & X509_ADD_FLAG_PREPEND) == 0 ? i : n - 1 - i; /* if prepend, add certs in reverse order to keep original order */ if (!ossl_x509_add_cert_new(p_sk, sk_X509_value(certs, j), flags)) return 0; } return 1; } int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b) { int ret; if (b == NULL) return a != NULL; if (a == NULL) return -1; /* Ensure canonical encoding is present and up to date */ if (a->canon_enc == NULL || a->modified) { ret = i2d_X509_NAME((X509_NAME *)a, NULL); if (ret < 0) return -2; } if (b->canon_enc == NULL || b->modified) { ret = i2d_X509_NAME((X509_NAME *)b, NULL); if (ret < 0) return -2; } ret = a->canon_enclen - b->canon_enclen; if (ret == 0 && a->canon_enclen == 0) return 0; if (ret == 0) { if (a->canon_enc == NULL || b->canon_enc == NULL) return -2; ret = memcmp(a->canon_enc, b->canon_enc, a->canon_enclen); } return ret < 0 ? -1 : ret > 0; } unsigned long X509_NAME_hash_ex(const X509_NAME *x, OSSL_LIB_CTX *libctx, const char *propq, int *ok) { unsigned long ret = 0; unsigned char md[SHA_DIGEST_LENGTH]; EVP_MD *sha1 = EVP_MD_fetch(libctx, "SHA1", propq); int i2d_ret; /* Make sure X509_NAME structure contains valid cached encoding */ i2d_ret = i2d_X509_NAME(x, NULL); if (ok != NULL) *ok = 0; if (i2d_ret >= 0 && sha1 != NULL && EVP_Digest(x->canon_enc, x->canon_enclen, md, NULL, sha1, NULL)) { ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) | ((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L) ) & 0xffffffffL; if (ok != NULL) *ok = 1; } EVP_MD_free(sha1); return ret; } #ifndef OPENSSL_NO_MD5 /* * I now DER encode the name and hash it. Since I cache the DER encoding, * this is reasonably efficient. */ unsigned long X509_NAME_hash_old(const X509_NAME *x) { EVP_MD *md5 = EVP_MD_fetch(NULL, OSSL_DIGEST_NAME_MD5, "-fips"); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); unsigned long ret = 0; unsigned char md[16]; if (md5 == NULL || md_ctx == NULL) goto end; /* Make sure X509_NAME structure contains valid cached encoding */ if (i2d_X509_NAME(x, NULL) < 0) goto end; if (EVP_DigestInit_ex(md_ctx, md5, NULL) && EVP_DigestUpdate(md_ctx, x->bytes->data, x->bytes->length) && EVP_DigestFinal_ex(md_ctx, md, NULL)) ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) | ((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L) ) & 0xffffffffL; end: EVP_MD_CTX_free(md_ctx); EVP_MD_free(md5); return ret; } #endif /* Search a stack of X509 for a match */ X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, const X509_NAME *name, const ASN1_INTEGER *serial) { int i; X509 x, *x509 = NULL; if (!sk) return NULL; x.cert_info.serialNumber = *serial; x.cert_info.issuer = (X509_NAME *)name; /* won't modify it */ for (i = 0; i < sk_X509_num(sk); i++) { x509 = sk_X509_value(sk, i); if (X509_issuer_and_serial_cmp(x509, &x) == 0) return x509; } return NULL; } X509 *X509_find_by_subject(STACK_OF(X509) *sk, const X509_NAME *name) { X509 *x509; int i; for (i = 0; i < sk_X509_num(sk); i++) { x509 = sk_X509_value(sk, i); if (X509_NAME_cmp(X509_get_subject_name(x509), name) == 0) return x509; } return NULL; } EVP_PKEY *X509_get0_pubkey(const X509 *x) { if (x == NULL) return NULL; return X509_PUBKEY_get0(x->cert_info.key); } EVP_PKEY *X509_get_pubkey(X509 *x) { if (x == NULL) return NULL; return X509_PUBKEY_get(x->cert_info.key); } int X509_check_private_key(const X509 *cert, const EVP_PKEY *pkey) { const EVP_PKEY *xk = X509_get0_pubkey(cert); if (xk == NULL) { ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY); return 0; } return ossl_x509_check_private_key(xk, pkey); } int ossl_x509_check_private_key(const EVP_PKEY *x, const EVP_PKEY *pkey) { if (x == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return 0; } switch (EVP_PKEY_eq(x, pkey)) { case 1: return 1; case 0: ERR_raise(ERR_LIB_X509, X509_R_KEY_VALUES_MISMATCH); return 0; case -1: ERR_raise(ERR_LIB_X509, X509_R_KEY_TYPE_MISMATCH); return 0; case -2: ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_KEY_TYPE); /* fall thru */ default: return 0; } } /* * Check a suite B algorithm is permitted: pass in a public key and the NID * of its signature (or 0 if no signature). The pflags is a pointer to a * flags field which must contain the suite B verification flags. */ #ifndef OPENSSL_NO_EC static int check_suite_b(EVP_PKEY *pkey, int sign_nid, unsigned long *pflags) { char curve_name[80]; size_t curve_name_len; int curve_nid; if (pkey == NULL || !EVP_PKEY_is_a(pkey, "EC")) return X509_V_ERR_SUITE_B_INVALID_ALGORITHM; if (!EVP_PKEY_get_group_name(pkey, curve_name, sizeof(curve_name), &curve_name_len)) return X509_V_ERR_SUITE_B_INVALID_CURVE; curve_nid = OBJ_txt2nid(curve_name); /* Check curve is consistent with LOS */ if (curve_nid == NID_secp384r1) { /* P-384 */ /* * Check signature algorithm is consistent with curve. */ if (sign_nid != -1 && sign_nid != NID_ecdsa_with_SHA384) return X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM; if (!(*pflags & X509_V_FLAG_SUITEB_192_LOS)) return X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED; /* If we encounter P-384 we cannot use P-256 later */ *pflags &= ~X509_V_FLAG_SUITEB_128_LOS_ONLY; } else if (curve_nid == NID_X9_62_prime256v1) { /* P-256 */ if (sign_nid != -1 && sign_nid != NID_ecdsa_with_SHA256) return X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM; if (!(*pflags & X509_V_FLAG_SUITEB_128_LOS_ONLY)) return X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED; } else { return X509_V_ERR_SUITE_B_INVALID_CURVE; } return X509_V_OK; } int X509_chain_check_suiteb(int *perror_depth, X509 *x, STACK_OF(X509) *chain, unsigned long flags) { int rv, i, sign_nid; EVP_PKEY *pk; unsigned long tflags = flags; if (!(flags & X509_V_FLAG_SUITEB_128_LOS)) return X509_V_OK; /* If no EE certificate passed in must be first in chain */ if (x == NULL) { x = sk_X509_value(chain, 0); i = 1; } else { i = 0; } pk = X509_get0_pubkey(x); /* * With DANE-EE(3) success, or DANE-EE(3)/PKIX-EE(1) failure we don't build * a chain all, just report trust success or failure, but must also report * Suite-B errors if applicable. This is indicated via a NULL chain * pointer. All we need to do is check the leaf key algorithm. */ if (chain == NULL) return check_suite_b(pk, -1, &tflags); if (X509_get_version(x) != X509_VERSION_3) { rv = X509_V_ERR_SUITE_B_INVALID_VERSION; /* Correct error depth */ i = 0; goto end; } /* Check EE key only */ rv = check_suite_b(pk, -1, &tflags); if (rv != X509_V_OK) { /* Correct error depth */ i = 0; goto end; } for (; i < sk_X509_num(chain); i++) { sign_nid = X509_get_signature_nid(x); x = sk_X509_value(chain, i); if (X509_get_version(x) != X509_VERSION_3) { rv = X509_V_ERR_SUITE_B_INVALID_VERSION; goto end; } pk = X509_get0_pubkey(x); rv = check_suite_b(pk, sign_nid, &tflags); if (rv != X509_V_OK) goto end; } /* Final check: root CA signature */ rv = check_suite_b(pk, X509_get_signature_nid(x), &tflags); end: if (rv != X509_V_OK) { /* Invalid signature or LOS errors are for previous cert */ if ((rv == X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM || rv == X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED) && i) i--; /* * If we have LOS error and flags changed then we are signing P-384 * with P-256. Use more meaningful error. */ if (rv == X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED && flags != tflags) rv = X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256; if (perror_depth) *perror_depth = i; } return rv; } int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags) { int sign_nid; if (!(flags & X509_V_FLAG_SUITEB_128_LOS)) return X509_V_OK; sign_nid = OBJ_obj2nid(crl->crl.sig_alg.algorithm); return check_suite_b(pk, sign_nid, &flags); } #else int X509_chain_check_suiteb(int *perror_depth, X509 *x, STACK_OF(X509) *chain, unsigned long flags) { return 0; } int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags) { return 0; } #endif /* * Not strictly speaking an "up_ref" as a STACK doesn't have a reference * count but it has the same effect by duping the STACK and upping the ref of * each X509 structure. */ STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain) { STACK_OF(X509) *ret = sk_X509_dup(chain); int i; if (ret == NULL) return NULL; for (i = 0; i < sk_X509_num(ret); i++) { X509 *x = sk_X509_value(ret, i); if (!X509_up_ref(x)) goto err; } return ret; err: while (i-- > 0) X509_free(sk_X509_value(ret, i)); sk_X509_free(ret); return NULL; }
./openssl/crypto/x509/v3_crld.c
/* * Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/x509v3.h> #include "crypto/x509.h" #include "ext_dat.h" #include "x509_local.h" static void *v2i_crld(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval); static int i2r_crldp(const X509V3_EXT_METHOD *method, void *pcrldp, BIO *out, int indent); const X509V3_EXT_METHOD ossl_v3_crld = { NID_crl_distribution_points, 0, ASN1_ITEM_ref(CRL_DIST_POINTS), 0, 0, 0, 0, 0, 0, 0, v2i_crld, i2r_crldp, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_freshest_crl = { NID_freshest_crl, 0, ASN1_ITEM_ref(CRL_DIST_POINTS), 0, 0, 0, 0, 0, 0, 0, v2i_crld, i2r_crldp, 0, NULL }; static STACK_OF(GENERAL_NAME) *gnames_from_sectname(X509V3_CTX *ctx, char *sect) { STACK_OF(CONF_VALUE) *gnsect; STACK_OF(GENERAL_NAME) *gens; if (*sect == '@') gnsect = X509V3_get_section(ctx, sect + 1); else gnsect = X509V3_parse_list(sect); if (!gnsect) { ERR_raise(ERR_LIB_X509V3, X509V3_R_SECTION_NOT_FOUND); return NULL; } gens = v2i_GENERAL_NAMES(NULL, ctx, gnsect); if (*sect == '@') X509V3_section_free(ctx, gnsect); else sk_CONF_VALUE_pop_free(gnsect, X509V3_conf_free); return gens; } static int set_dist_point_name(DIST_POINT_NAME **pdp, X509V3_CTX *ctx, CONF_VALUE *cnf) { STACK_OF(GENERAL_NAME) *fnm = NULL; STACK_OF(X509_NAME_ENTRY) *rnm = NULL; if (cnf->value == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_MISSING_VALUE); goto err; } if (HAS_PREFIX(cnf->name, "fullname")) { fnm = gnames_from_sectname(ctx, cnf->value); if (!fnm) goto err; } else if (strcmp(cnf->name, "relativename") == 0) { int ret; STACK_OF(CONF_VALUE) *dnsect; X509_NAME *nm; nm = X509_NAME_new(); if (nm == NULL) return -1; dnsect = X509V3_get_section(ctx, cnf->value); if (!dnsect) { X509_NAME_free(nm); ERR_raise(ERR_LIB_X509V3, X509V3_R_SECTION_NOT_FOUND); return -1; } ret = X509V3_NAME_from_section(nm, dnsect, MBSTRING_ASC); X509V3_section_free(ctx, dnsect); rnm = nm->entries; nm->entries = NULL; X509_NAME_free(nm); if (!ret || sk_X509_NAME_ENTRY_num(rnm) <= 0) goto err; /* * Since its a name fragment can't have more than one RDNSequence */ if (sk_X509_NAME_ENTRY_value(rnm, sk_X509_NAME_ENTRY_num(rnm) - 1)->set) { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_MULTIPLE_RDNS); goto err; } } else return 0; if (*pdp) { ERR_raise(ERR_LIB_X509V3, X509V3_R_DISTPOINT_ALREADY_SET); goto err; } *pdp = DIST_POINT_NAME_new(); if (*pdp == NULL) goto err; if (fnm) { (*pdp)->type = 0; (*pdp)->name.fullname = fnm; } else { (*pdp)->type = 1; (*pdp)->name.relativename = rnm; } return 1; err: sk_GENERAL_NAME_pop_free(fnm, GENERAL_NAME_free); sk_X509_NAME_ENTRY_pop_free(rnm, X509_NAME_ENTRY_free); return -1; } static const BIT_STRING_BITNAME reason_flags[] = { {0, "Unused", "unused"}, {1, "Key Compromise", "keyCompromise"}, {2, "CA Compromise", "CACompromise"}, {3, "Affiliation Changed", "affiliationChanged"}, {4, "Superseded", "superseded"}, {5, "Cessation Of Operation", "cessationOfOperation"}, {6, "Certificate Hold", "certificateHold"}, {7, "Privilege Withdrawn", "privilegeWithdrawn"}, {8, "AA Compromise", "AACompromise"}, {-1, NULL, NULL} }; static int set_reasons(ASN1_BIT_STRING **preas, char *value) { STACK_OF(CONF_VALUE) *rsk = NULL; const BIT_STRING_BITNAME *pbn; const char *bnam; int i, ret = 0; rsk = X509V3_parse_list(value); if (rsk == NULL) return 0; if (*preas != NULL) goto err; for (i = 0; i < sk_CONF_VALUE_num(rsk); i++) { bnam = sk_CONF_VALUE_value(rsk, i)->name; if (*preas == NULL) { *preas = ASN1_BIT_STRING_new(); if (*preas == NULL) goto err; } for (pbn = reason_flags; pbn->lname; pbn++) { if (strcmp(pbn->sname, bnam) == 0) { if (!ASN1_BIT_STRING_set_bit(*preas, pbn->bitnum, 1)) goto err; break; } } if (pbn->lname == NULL) goto err; } ret = 1; err: sk_CONF_VALUE_pop_free(rsk, X509V3_conf_free); return ret; } static int print_reasons(BIO *out, const char *rname, ASN1_BIT_STRING *rflags, int indent) { int first = 1; const BIT_STRING_BITNAME *pbn; BIO_printf(out, "%*s%s:\n%*s", indent, "", rname, indent + 2, ""); for (pbn = reason_flags; pbn->lname; pbn++) { if (ASN1_BIT_STRING_get_bit(rflags, pbn->bitnum)) { if (first) first = 0; else BIO_puts(out, ", "); BIO_puts(out, pbn->lname); } } if (first) BIO_puts(out, "<EMPTY>\n"); else BIO_puts(out, "\n"); return 1; } static DIST_POINT *crldp_from_section(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { int i; CONF_VALUE *cnf; DIST_POINT *point = DIST_POINT_new(); if (point == NULL) goto err; for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { int ret; cnf = sk_CONF_VALUE_value(nval, i); ret = set_dist_point_name(&point->distpoint, ctx, cnf); if (ret > 0) continue; if (ret < 0) goto err; if (strcmp(cnf->name, "reasons") == 0) { if (!set_reasons(&point->reasons, cnf->value)) goto err; } else if (strcmp(cnf->name, "CRLissuer") == 0) { point->CRLissuer = gnames_from_sectname(ctx, cnf->value); if (point->CRLissuer == NULL) goto err; } } return point; err: DIST_POINT_free(point); return NULL; } static void *v2i_crld(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { STACK_OF(DIST_POINT) *crld; GENERAL_NAMES *gens = NULL; GENERAL_NAME *gen = NULL; CONF_VALUE *cnf; const int num = sk_CONF_VALUE_num(nval); int i; crld = sk_DIST_POINT_new_reserve(NULL, num); if (crld == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto err; } for (i = 0; i < num; i++) { DIST_POINT *point; cnf = sk_CONF_VALUE_value(nval, i); if (cnf->value == NULL) { STACK_OF(CONF_VALUE) *dpsect; dpsect = X509V3_get_section(ctx, cnf->name); if (!dpsect) goto err; point = crldp_from_section(ctx, dpsect); X509V3_section_free(ctx, dpsect); if (point == NULL) goto err; sk_DIST_POINT_push(crld, point); /* no failure as it was reserved */ } else { if ((gen = v2i_GENERAL_NAME(method, ctx, cnf)) == NULL) goto err; if ((gens = GENERAL_NAMES_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } if (!sk_GENERAL_NAME_push(gens, gen)) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto err; } gen = NULL; if ((point = DIST_POINT_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } sk_DIST_POINT_push(crld, point); /* no failure as it was reserved */ if ((point->distpoint = DIST_POINT_NAME_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } point->distpoint->name.fullname = gens; point->distpoint->type = 0; gens = NULL; } } return crld; err: GENERAL_NAME_free(gen); GENERAL_NAMES_free(gens); sk_DIST_POINT_pop_free(crld, DIST_POINT_free); return NULL; } static int dpn_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { DIST_POINT_NAME *dpn = (DIST_POINT_NAME *)*pval; switch (operation) { case ASN1_OP_NEW_POST: dpn->dpname = NULL; break; case ASN1_OP_FREE_POST: X509_NAME_free(dpn->dpname); break; } return 1; } ASN1_CHOICE_cb(DIST_POINT_NAME, dpn_cb) = { ASN1_IMP_SEQUENCE_OF(DIST_POINT_NAME, name.fullname, GENERAL_NAME, 0), ASN1_IMP_SET_OF(DIST_POINT_NAME, name.relativename, X509_NAME_ENTRY, 1) } ASN1_CHOICE_END_cb(DIST_POINT_NAME, DIST_POINT_NAME, type) IMPLEMENT_ASN1_FUNCTIONS(DIST_POINT_NAME) ASN1_SEQUENCE(DIST_POINT) = { ASN1_EXP_OPT(DIST_POINT, distpoint, DIST_POINT_NAME, 0), ASN1_IMP_OPT(DIST_POINT, reasons, ASN1_BIT_STRING, 1), ASN1_IMP_SEQUENCE_OF_OPT(DIST_POINT, CRLissuer, GENERAL_NAME, 2) } ASN1_SEQUENCE_END(DIST_POINT) IMPLEMENT_ASN1_FUNCTIONS(DIST_POINT) ASN1_ITEM_TEMPLATE(CRL_DIST_POINTS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, CRLDistributionPoints, DIST_POINT) ASN1_ITEM_TEMPLATE_END(CRL_DIST_POINTS) IMPLEMENT_ASN1_FUNCTIONS(CRL_DIST_POINTS) ASN1_SEQUENCE(ISSUING_DIST_POINT) = { ASN1_EXP_OPT(ISSUING_DIST_POINT, distpoint, DIST_POINT_NAME, 0), ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyuser, ASN1_FBOOLEAN, 1), ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyCA, ASN1_FBOOLEAN, 2), ASN1_IMP_OPT(ISSUING_DIST_POINT, onlysomereasons, ASN1_BIT_STRING, 3), ASN1_IMP_OPT(ISSUING_DIST_POINT, indirectCRL, ASN1_FBOOLEAN, 4), ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyattr, ASN1_FBOOLEAN, 5) } ASN1_SEQUENCE_END(ISSUING_DIST_POINT) IMPLEMENT_ASN1_FUNCTIONS(ISSUING_DIST_POINT) static int i2r_idp(const X509V3_EXT_METHOD *method, void *pidp, BIO *out, int indent); static void *v2i_idp(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval); const X509V3_EXT_METHOD ossl_v3_idp = { NID_issuing_distribution_point, X509V3_EXT_MULTILINE, ASN1_ITEM_ref(ISSUING_DIST_POINT), 0, 0, 0, 0, 0, 0, 0, v2i_idp, i2r_idp, 0, NULL }; static void *v2i_idp(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { ISSUING_DIST_POINT *idp = NULL; CONF_VALUE *cnf; char *name, *val; int i, ret; idp = ISSUING_DIST_POINT_new(); if (idp == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { cnf = sk_CONF_VALUE_value(nval, i); name = cnf->name; val = cnf->value; ret = set_dist_point_name(&idp->distpoint, ctx, cnf); if (ret > 0) continue; if (ret < 0) goto err; if (strcmp(name, "onlyuser") == 0) { if (!X509V3_get_value_bool(cnf, &idp->onlyuser)) goto err; } else if (strcmp(name, "onlyCA") == 0) { if (!X509V3_get_value_bool(cnf, &idp->onlyCA)) goto err; } else if (strcmp(name, "onlyAA") == 0) { if (!X509V3_get_value_bool(cnf, &idp->onlyattr)) goto err; } else if (strcmp(name, "indirectCRL") == 0) { if (!X509V3_get_value_bool(cnf, &idp->indirectCRL)) goto err; } else if (strcmp(name, "onlysomereasons") == 0) { if (!set_reasons(&idp->onlysomereasons, val)) goto err; } else { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NAME); X509V3_conf_add_error_name_value(cnf); goto err; } } return idp; err: ISSUING_DIST_POINT_free(idp); return NULL; } static int print_gens(BIO *out, STACK_OF(GENERAL_NAME) *gens, int indent) { int i; for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) { if (i > 0) BIO_puts(out, "\n"); BIO_printf(out, "%*s", indent + 2, ""); GENERAL_NAME_print(out, sk_GENERAL_NAME_value(gens, i)); } return 1; } static int print_distpoint(BIO *out, DIST_POINT_NAME *dpn, int indent) { if (dpn->type == 0) { BIO_printf(out, "%*sFull Name:\n", indent, ""); print_gens(out, dpn->name.fullname, indent); } else { X509_NAME ntmp; ntmp.entries = dpn->name.relativename; BIO_printf(out, "%*sRelative Name:\n%*s", indent, "", indent + 2, ""); X509_NAME_print_ex(out, &ntmp, 0, XN_FLAG_ONELINE); BIO_puts(out, "\n"); } return 1; } static int i2r_idp(const X509V3_EXT_METHOD *method, void *pidp, BIO *out, int indent) { ISSUING_DIST_POINT *idp = pidp; if (idp->distpoint) print_distpoint(out, idp->distpoint, indent); if (idp->onlyuser > 0) BIO_printf(out, "%*sOnly User Certificates\n", indent, ""); if (idp->onlyCA > 0) BIO_printf(out, "%*sOnly CA Certificates\n", indent, ""); if (idp->indirectCRL > 0) BIO_printf(out, "%*sIndirect CRL\n", indent, ""); if (idp->onlysomereasons) print_reasons(out, "Only Some Reasons", idp->onlysomereasons, indent); if (idp->onlyattr > 0) BIO_printf(out, "%*sOnly Attribute Certificates\n", indent, ""); if (!idp->distpoint && (idp->onlyuser <= 0) && (idp->onlyCA <= 0) && (idp->indirectCRL <= 0) && !idp->onlysomereasons && (idp->onlyattr <= 0)) BIO_printf(out, "%*s<EMPTY>\n", indent, ""); return 1; } static int i2r_crldp(const X509V3_EXT_METHOD *method, void *pcrldp, BIO *out, int indent) { STACK_OF(DIST_POINT) *crld = pcrldp; DIST_POINT *point; int i; for (i = 0; i < sk_DIST_POINT_num(crld); i++) { if (i > 0) BIO_puts(out, "\n"); point = sk_DIST_POINT_value(crld, i); if (point->distpoint) print_distpoint(out, point->distpoint, indent); if (point->reasons) print_reasons(out, "Reasons", point->reasons, indent); if (point->CRLissuer) { BIO_printf(out, "%*sCRL Issuer:\n", indent, ""); print_gens(out, point->CRLissuer, indent); } } return 1; } /* Append any nameRelativeToCRLIssuer in dpn to iname, set in dpn->dpname */ int DIST_POINT_set_dpname(DIST_POINT_NAME *dpn, const X509_NAME *iname) { int i; STACK_OF(X509_NAME_ENTRY) *frag; X509_NAME_ENTRY *ne; if (dpn == NULL || dpn->type != 1) return 1; frag = dpn->name.relativename; X509_NAME_free(dpn->dpname); /* just in case it was already set */ dpn->dpname = X509_NAME_dup(iname); if (dpn->dpname == NULL) return 0; for (i = 0; i < sk_X509_NAME_ENTRY_num(frag); i++) { ne = sk_X509_NAME_ENTRY_value(frag, i); if (!X509_NAME_add_entry(dpn->dpname, ne, -1, i ? 0 : 1)) goto err; } /* generate cached encoding of name */ if (i2d_X509_NAME(dpn->dpname, NULL) >= 0) return 1; err: X509_NAME_free(dpn->dpname); dpn->dpname = NULL; return 0; }
./openssl/crypto/x509/pcy_lib.c
/* * Copyright 2004-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include <openssl/x509.h> #include <openssl/x509v3.h> #include "pcy_local.h" /* accessor functions */ /* X509_POLICY_TREE stuff */ int X509_policy_tree_level_count(const X509_POLICY_TREE *tree) { if (!tree) return 0; return tree->nlevel; } X509_POLICY_LEVEL *X509_policy_tree_get0_level(const X509_POLICY_TREE *tree, int i) { if (!tree || (i < 0) || (i >= tree->nlevel)) return NULL; return tree->levels + i; } STACK_OF(X509_POLICY_NODE) *X509_policy_tree_get0_policies(const X509_POLICY_TREE *tree) { if (!tree) return NULL; return tree->auth_policies; } STACK_OF(X509_POLICY_NODE) *X509_policy_tree_get0_user_policies(const X509_POLICY_TREE *tree) { if (!tree) return NULL; if (tree->flags & POLICY_FLAG_ANY_POLICY) return tree->auth_policies; else return tree->user_policies; } /* X509_POLICY_LEVEL stuff */ int X509_policy_level_node_count(X509_POLICY_LEVEL *level) { int n; if (!level) return 0; if (level->anyPolicy) n = 1; else n = 0; if (level->nodes) n += sk_X509_POLICY_NODE_num(level->nodes); return n; } X509_POLICY_NODE *X509_policy_level_get0_node(const X509_POLICY_LEVEL *level, int i) { if (!level) return NULL; if (level->anyPolicy) { if (i == 0) return level->anyPolicy; i--; } return sk_X509_POLICY_NODE_value(level->nodes, i); } /* X509_POLICY_NODE stuff */ const ASN1_OBJECT *X509_policy_node_get0_policy(const X509_POLICY_NODE *node) { if (!node) return NULL; return node->data->valid_policy; } STACK_OF(POLICYQUALINFO) *X509_policy_node_get0_qualifiers(const X509_POLICY_NODE *node) { if (!node) return NULL; return node->data->qualifier_set; } const X509_POLICY_NODE *X509_policy_node_get0_parent(const X509_POLICY_NODE *node) { if (!node) return NULL; return node->parent; }
./openssl/crypto/x509/x509_trust.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/x509v3.h> #include "crypto/x509.h" static int tr_cmp(const X509_TRUST *const *a, const X509_TRUST *const *b); static void trtable_free(X509_TRUST *p); static int trust_1oidany(X509_TRUST *trust, X509 *x, int flags); static int trust_1oid(X509_TRUST *trust, X509 *x, int flags); static int trust_compat(X509_TRUST *trust, X509 *x, int flags); static int obj_trust(int id, X509 *x, int flags); static int (*default_trust) (int id, X509 *x, int flags) = obj_trust; /* * WARNING: the following table should be kept in order of trust and without * any gaps so we can just subtract the minimum trust value to get an index * into the table */ static X509_TRUST trstandard[] = { {X509_TRUST_COMPAT, 0, trust_compat, "compatible", 0, NULL}, {X509_TRUST_SSL_CLIENT, 0, trust_1oidany, "SSL Client", NID_client_auth, NULL}, {X509_TRUST_SSL_SERVER, 0, trust_1oidany, "SSL Server", NID_server_auth, NULL}, {X509_TRUST_EMAIL, 0, trust_1oidany, "S/MIME email", NID_email_protect, NULL}, {X509_TRUST_OBJECT_SIGN, 0, trust_1oidany, "Object Signer", NID_code_sign, NULL}, {X509_TRUST_OCSP_SIGN, 0, trust_1oid, "OCSP responder", NID_OCSP_sign, NULL}, {X509_TRUST_OCSP_REQUEST, 0, trust_1oid, "OCSP request", NID_ad_OCSP, NULL}, {X509_TRUST_TSA, 0, trust_1oidany, "TSA server", NID_time_stamp, NULL} }; #define X509_TRUST_COUNT OSSL_NELEM(trstandard) static STACK_OF(X509_TRUST) *trtable = NULL; static int tr_cmp(const X509_TRUST *const *a, const X509_TRUST *const *b) { return (*a)->trust - (*b)->trust; } int (*X509_TRUST_set_default(int (*trust) (int, X509 *, int))) (int, X509 *, int) { int (*oldtrust) (int, X509 *, int); oldtrust = default_trust; default_trust = trust; return oldtrust; } /* Returns X509_TRUST_TRUSTED, X509_TRUST_REJECTED, or X509_TRUST_UNTRUSTED */ int X509_check_trust(X509 *x, int id, int flags) { X509_TRUST *pt; int idx; /* We get this as a default value */ if (id == X509_TRUST_DEFAULT) return obj_trust(NID_anyExtendedKeyUsage, x, flags | X509_TRUST_DO_SS_COMPAT); idx = X509_TRUST_get_by_id(id); if (idx < 0) return default_trust(id, x, flags); pt = X509_TRUST_get0(idx); return pt->check_trust(pt, x, flags); } int X509_TRUST_get_count(void) { if (!trtable) return X509_TRUST_COUNT; return sk_X509_TRUST_num(trtable) + X509_TRUST_COUNT; } X509_TRUST *X509_TRUST_get0(int idx) { if (idx < 0) return NULL; if (idx < (int)X509_TRUST_COUNT) return trstandard + idx; return sk_X509_TRUST_value(trtable, idx - X509_TRUST_COUNT); } int X509_TRUST_get_by_id(int id) { X509_TRUST tmp; int idx; if ((id >= X509_TRUST_MIN) && (id <= X509_TRUST_MAX)) return id - X509_TRUST_MIN; if (trtable == NULL) return -1; tmp.trust = id; /* Ideally, this would be done under lock */ sk_X509_TRUST_sort(trtable); idx = sk_X509_TRUST_find(trtable, &tmp); if (idx < 0) return -1; return idx + X509_TRUST_COUNT; } int X509_TRUST_set(int *t, int trust) { if (X509_TRUST_get_by_id(trust) < 0) { ERR_raise(ERR_LIB_X509, X509_R_INVALID_TRUST); return 0; } *t = trust; return 1; } int X509_TRUST_add(int id, int flags, int (*ck) (X509_TRUST *, X509 *, int), const char *name, int arg1, void *arg2) { int idx; X509_TRUST *trtmp; /* * This is set according to what we change: application can't set it */ flags &= ~X509_TRUST_DYNAMIC; /* This will always be set for application modified trust entries */ flags |= X509_TRUST_DYNAMIC_NAME; /* Get existing entry if any */ idx = X509_TRUST_get_by_id(id); /* Need a new entry */ if (idx < 0) { if ((trtmp = OPENSSL_malloc(sizeof(*trtmp))) == NULL) return 0; trtmp->flags = X509_TRUST_DYNAMIC; } else trtmp = X509_TRUST_get0(idx); /* OPENSSL_free existing name if dynamic */ if (trtmp->flags & X509_TRUST_DYNAMIC_NAME) OPENSSL_free(trtmp->name); /* dup supplied name */ if ((trtmp->name = OPENSSL_strdup(name)) == NULL) goto err; /* Keep the dynamic flag of existing entry */ trtmp->flags &= X509_TRUST_DYNAMIC; /* Set all other flags */ trtmp->flags |= flags; trtmp->trust = id; trtmp->check_trust = ck; trtmp->arg1 = arg1; trtmp->arg2 = arg2; /* If its a new entry manage the dynamic table */ if (idx < 0) { if (trtable == NULL && (trtable = sk_X509_TRUST_new(tr_cmp)) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } if (!sk_X509_TRUST_push(trtable, trtmp)) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } } return 1; err: if (idx < 0) { OPENSSL_free(trtmp->name); OPENSSL_free(trtmp); } return 0; } static void trtable_free(X509_TRUST *p) { if (p == NULL) return; if (p->flags & X509_TRUST_DYNAMIC) { if (p->flags & X509_TRUST_DYNAMIC_NAME) OPENSSL_free(p->name); OPENSSL_free(p); } } void X509_TRUST_cleanup(void) { sk_X509_TRUST_pop_free(trtable, trtable_free); trtable = NULL; } int X509_TRUST_get_flags(const X509_TRUST *xp) { return xp->flags; } char *X509_TRUST_get0_name(const X509_TRUST *xp) { return xp->name; } int X509_TRUST_get_trust(const X509_TRUST *xp) { return xp->trust; } static int trust_1oidany(X509_TRUST *trust, X509 *x, int flags) { /* * Declare the chain verified if the desired trust OID is not rejected in * any auxiliary trust info for this certificate, and the OID is either * expressly trusted, or else either "anyEKU" is trusted, or the * certificate is self-signed and X509_TRUST_NO_SS_COMPAT is not set. */ flags |= X509_TRUST_DO_SS_COMPAT | X509_TRUST_OK_ANY_EKU; return obj_trust(trust->arg1, x, flags); } static int trust_1oid(X509_TRUST *trust, X509 *x, int flags) { /* * Declare the chain verified only if the desired trust OID is not * rejected and is expressly trusted. Neither "anyEKU" nor "compat" * trust in self-signed certificates apply. */ flags &= ~(X509_TRUST_DO_SS_COMPAT | X509_TRUST_OK_ANY_EKU); return obj_trust(trust->arg1, x, flags); } static int trust_compat(X509_TRUST *trust, X509 *x, int flags) { /* Call for side-effect of setting EXFLAG_SS for self-signed-certs */ if (X509_check_purpose(x, -1, 0) != 1) return X509_TRUST_UNTRUSTED; if ((flags & X509_TRUST_NO_SS_COMPAT) == 0 && (x->ex_flags & EXFLAG_SS)) return X509_TRUST_TRUSTED; else return X509_TRUST_UNTRUSTED; } static int obj_trust(int id, X509 *x, int flags) { X509_CERT_AUX *ax = x->aux; int i; if (ax != NULL && ax->reject != NULL) { for (i = 0; i < sk_ASN1_OBJECT_num(ax->reject); i++) { ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(ax->reject, i); int nid = OBJ_obj2nid(obj); if (nid == id || (nid == NID_anyExtendedKeyUsage && (flags & X509_TRUST_OK_ANY_EKU))) return X509_TRUST_REJECTED; } } if (ax != NULL && ax->trust != NULL) { for (i = 0; i < sk_ASN1_OBJECT_num(ax->trust); i++) { ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(ax->trust, i); int nid = OBJ_obj2nid(obj); if (nid == id || (nid == NID_anyExtendedKeyUsage && (flags & X509_TRUST_OK_ANY_EKU))) return X509_TRUST_TRUSTED; } /* * Reject when explicit trust EKU are set and none match. * * Returning untrusted is enough for full chains that end in * self-signed roots, because when explicit trust is specified it * suppresses the default blanket trust of self-signed objects. * * But for partial chains, this is not enough, because absent a similar * trust-self-signed policy, non matching EKUs are indistinguishable * from lack of EKU constraints. * * Therefore, failure to match any trusted purpose must trigger an * explicit reject. */ return X509_TRUST_REJECTED; } if ((flags & X509_TRUST_DO_SS_COMPAT) == 0) return X509_TRUST_UNTRUSTED; /* * Not rejected, and there is no list of accepted uses, try compat. */ return trust_compat(NULL, x, flags); }
./openssl/crypto/x509/v3_cpols.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/conf.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/x509v3.h> #include "x509_local.h" #include "pcy_local.h" #include "ext_dat.h" /* Certificate policies extension support: this one is a bit complex... */ static int i2r_certpol(X509V3_EXT_METHOD *method, STACK_OF(POLICYINFO) *pol, BIO *out, int indent); static STACK_OF(POLICYINFO) *r2i_certpol(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *value); static void print_qualifiers(BIO *out, STACK_OF(POLICYQUALINFO) *quals, int indent); static void print_notice(BIO *out, USERNOTICE *notice, int indent); static POLICYINFO *policy_section(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *polstrs, int ia5org); static POLICYQUALINFO *notice_section(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *unot, int ia5org); static int nref_nos(STACK_OF(ASN1_INTEGER) *nnums, STACK_OF(CONF_VALUE) *nos); static int displaytext_str2tag(const char *tagstr, unsigned int *tag_len); static int displaytext_get_tag_len(const char *tagstr); const X509V3_EXT_METHOD ossl_v3_cpols = { NID_certificate_policies, 0, ASN1_ITEM_ref(CERTIFICATEPOLICIES), 0, 0, 0, 0, 0, 0, 0, 0, (X509V3_EXT_I2R)i2r_certpol, (X509V3_EXT_R2I)r2i_certpol, NULL }; ASN1_ITEM_TEMPLATE(CERTIFICATEPOLICIES) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, CERTIFICATEPOLICIES, POLICYINFO) ASN1_ITEM_TEMPLATE_END(CERTIFICATEPOLICIES) IMPLEMENT_ASN1_FUNCTIONS(CERTIFICATEPOLICIES) ASN1_SEQUENCE(POLICYINFO) = { ASN1_SIMPLE(POLICYINFO, policyid, ASN1_OBJECT), ASN1_SEQUENCE_OF_OPT(POLICYINFO, qualifiers, POLICYQUALINFO) } ASN1_SEQUENCE_END(POLICYINFO) IMPLEMENT_ASN1_FUNCTIONS(POLICYINFO) ASN1_ADB_TEMPLATE(policydefault) = ASN1_SIMPLE(POLICYQUALINFO, d.other, ASN1_ANY); ASN1_ADB(POLICYQUALINFO) = { ADB_ENTRY(NID_id_qt_cps, ASN1_SIMPLE(POLICYQUALINFO, d.cpsuri, ASN1_IA5STRING)), ADB_ENTRY(NID_id_qt_unotice, ASN1_SIMPLE(POLICYQUALINFO, d.usernotice, USERNOTICE)) } ASN1_ADB_END(POLICYQUALINFO, 0, pqualid, 0, &policydefault_tt, NULL); ASN1_SEQUENCE(POLICYQUALINFO) = { ASN1_SIMPLE(POLICYQUALINFO, pqualid, ASN1_OBJECT), ASN1_ADB_OBJECT(POLICYQUALINFO) } ASN1_SEQUENCE_END(POLICYQUALINFO) IMPLEMENT_ASN1_FUNCTIONS(POLICYQUALINFO) ASN1_SEQUENCE(USERNOTICE) = { ASN1_OPT(USERNOTICE, noticeref, NOTICEREF), ASN1_OPT(USERNOTICE, exptext, DISPLAYTEXT) } ASN1_SEQUENCE_END(USERNOTICE) IMPLEMENT_ASN1_FUNCTIONS(USERNOTICE) ASN1_SEQUENCE(NOTICEREF) = { ASN1_SIMPLE(NOTICEREF, organization, DISPLAYTEXT), ASN1_SEQUENCE_OF(NOTICEREF, noticenos, ASN1_INTEGER) } ASN1_SEQUENCE_END(NOTICEREF) IMPLEMENT_ASN1_FUNCTIONS(NOTICEREF) static STACK_OF(POLICYINFO) *r2i_certpol(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *value) { STACK_OF(POLICYINFO) *pols; char *pstr; POLICYINFO *pol; ASN1_OBJECT *pobj; STACK_OF(CONF_VALUE) *vals = X509V3_parse_list(value); CONF_VALUE *cnf; const int num = sk_CONF_VALUE_num(vals); int i, ia5org; if (vals == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB); return NULL; } pols = sk_POLICYINFO_new_reserve(NULL, num); if (pols == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto err; } ia5org = 0; for (i = 0; i < num; i++) { cnf = sk_CONF_VALUE_value(vals, i); if (cnf->value != NULL || cnf->name == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_POLICY_IDENTIFIER); X509V3_conf_add_error_name_value(cnf); goto err; } pstr = cnf->name; if (strcmp(pstr, "ia5org") == 0) { ia5org = 1; continue; } else if (*pstr == '@') { STACK_OF(CONF_VALUE) *polsect; polsect = X509V3_get_section(ctx, pstr + 1); if (polsect == NULL) { ERR_raise_data(ERR_LIB_X509V3, X509V3_R_INVALID_SECTION, "%s", cnf->name); goto err; } pol = policy_section(ctx, polsect, ia5org); X509V3_section_free(ctx, polsect); if (pol == NULL) goto err; } else { if ((pobj = OBJ_txt2obj(cnf->name, 0)) == NULL) { ERR_raise_data(ERR_LIB_X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER, "%s", cnf->name); goto err; } pol = POLICYINFO_new(); if (pol == NULL) { ASN1_OBJECT_free(pobj); ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } pol->policyid = pobj; } if (!sk_POLICYINFO_push(pols, pol)) { POLICYINFO_free(pol); ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto err; } } sk_CONF_VALUE_pop_free(vals, X509V3_conf_free); return pols; err: sk_CONF_VALUE_pop_free(vals, X509V3_conf_free); sk_POLICYINFO_pop_free(pols, POLICYINFO_free); return NULL; } static POLICYINFO *policy_section(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *polstrs, int ia5org) { int i; CONF_VALUE *cnf; POLICYINFO *pol; POLICYQUALINFO *qual; if ((pol = POLICYINFO_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } for (i = 0; i < sk_CONF_VALUE_num(polstrs); i++) { cnf = sk_CONF_VALUE_value(polstrs, i); if (strcmp(cnf->name, "policyIdentifier") == 0) { ASN1_OBJECT *pobj; if ((pobj = OBJ_txt2obj(cnf->value, 0)) == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER); X509V3_conf_err(cnf); goto err; } pol->policyid = pobj; } else if (!ossl_v3_name_cmp(cnf->name, "CPS")) { if (pol->qualifiers == NULL) pol->qualifiers = sk_POLICYQUALINFO_new_null(); if ((qual = POLICYQUALINFO_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } if (!sk_POLICYQUALINFO_push(pol->qualifiers, qual)) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto err; } if ((qual->pqualid = OBJ_nid2obj(NID_id_qt_cps)) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_INTERNAL_ERROR); goto err; } if ((qual->d.cpsuri = ASN1_IA5STRING_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } if (!ASN1_STRING_set(qual->d.cpsuri, cnf->value, strlen(cnf->value))) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } } else if (!ossl_v3_name_cmp(cnf->name, "userNotice")) { STACK_OF(CONF_VALUE) *unot; if (*cnf->value != '@') { ERR_raise(ERR_LIB_X509V3, X509V3_R_EXPECTED_A_SECTION_NAME); X509V3_conf_err(cnf); goto err; } unot = X509V3_get_section(ctx, cnf->value + 1); if (!unot) { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SECTION); X509V3_conf_err(cnf); goto err; } qual = notice_section(ctx, unot, ia5org); X509V3_section_free(ctx, unot); if (!qual) goto err; if (pol->qualifiers == NULL) pol->qualifiers = sk_POLICYQUALINFO_new_null(); if (!sk_POLICYQUALINFO_push(pol->qualifiers, qual)) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto err; } } else { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_OPTION); X509V3_conf_err(cnf); goto err; } } if (pol->policyid == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_POLICY_IDENTIFIER); goto err; } return pol; err: POLICYINFO_free(pol); return NULL; } static int displaytext_get_tag_len(const char *tagstr) { char *colon = strchr(tagstr, ':'); return (colon == NULL) ? -1 : colon - tagstr; } static int displaytext_str2tag(const char *tagstr, unsigned int *tag_len) { int len; *tag_len = 0; len = displaytext_get_tag_len(tagstr); if (len == -1) return V_ASN1_VISIBLESTRING; *tag_len = len; if (len == sizeof("UTF8") - 1 && HAS_PREFIX(tagstr, "UTF8")) return V_ASN1_UTF8STRING; if (len == sizeof("UTF8String") - 1 && HAS_PREFIX(tagstr, "UTF8String")) return V_ASN1_UTF8STRING; if (len == sizeof("BMP") - 1 && HAS_PREFIX(tagstr, "BMP")) return V_ASN1_BMPSTRING; if (len == sizeof("BMPSTRING") - 1 && HAS_PREFIX(tagstr, "BMPSTRING")) return V_ASN1_BMPSTRING; if (len == sizeof("VISIBLE") - 1 && HAS_PREFIX(tagstr, "VISIBLE")) return V_ASN1_VISIBLESTRING; if (len == sizeof("VISIBLESTRING") - 1 && HAS_PREFIX(tagstr, "VISIBLESTRING")) return V_ASN1_VISIBLESTRING; *tag_len = 0; return V_ASN1_VISIBLESTRING; } static POLICYQUALINFO *notice_section(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *unot, int ia5org) { int i, ret, len, tag; unsigned int tag_len; CONF_VALUE *cnf; USERNOTICE *not; POLICYQUALINFO *qual; char *value = NULL; if ((qual = POLICYQUALINFO_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } if ((qual->pqualid = OBJ_nid2obj(NID_id_qt_unotice)) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_INTERNAL_ERROR); goto err; } if ((not = USERNOTICE_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } qual->d.usernotice = not; for (i = 0; i < sk_CONF_VALUE_num(unot); i++) { cnf = sk_CONF_VALUE_value(unot, i); value = cnf->value; if (strcmp(cnf->name, "explicitText") == 0) { tag = displaytext_str2tag(value, &tag_len); if ((not->exptext = ASN1_STRING_type_new(tag)) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } if (tag_len != 0) value += tag_len + 1; len = strlen(value); if (!ASN1_STRING_set(not->exptext, value, len)) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } } else if (strcmp(cnf->name, "organization") == 0) { NOTICEREF *nref; if (!not->noticeref) { if ((nref = NOTICEREF_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } not->noticeref = nref; } else nref = not->noticeref; if (ia5org) nref->organization->type = V_ASN1_IA5STRING; else nref->organization->type = V_ASN1_VISIBLESTRING; if (!ASN1_STRING_set(nref->organization, cnf->value, strlen(cnf->value))) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } } else if (strcmp(cnf->name, "noticeNumbers") == 0) { NOTICEREF *nref; STACK_OF(CONF_VALUE) *nos; if (!not->noticeref) { if ((nref = NOTICEREF_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } not->noticeref = nref; } else nref = not->noticeref; nos = X509V3_parse_list(cnf->value); if (!nos || !sk_CONF_VALUE_num(nos)) { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NUMBERS); X509V3_conf_add_error_name_value(cnf); sk_CONF_VALUE_pop_free(nos, X509V3_conf_free); goto err; } ret = nref_nos(nref->noticenos, nos); sk_CONF_VALUE_pop_free(nos, X509V3_conf_free); if (!ret) goto err; } else { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_OPTION); X509V3_conf_add_error_name_value(cnf); goto err; } } if (not->noticeref && (!not->noticeref->noticenos || !not->noticeref->organization)) { ERR_raise(ERR_LIB_X509V3, X509V3_R_NEED_ORGANIZATION_AND_NUMBERS); goto err; } return qual; err: POLICYQUALINFO_free(qual); return NULL; } static int nref_nos(STACK_OF(ASN1_INTEGER) *nnums, STACK_OF(CONF_VALUE) *nos) { CONF_VALUE *cnf; ASN1_INTEGER *aint; int i; for (i = 0; i < sk_CONF_VALUE_num(nos); i++) { cnf = sk_CONF_VALUE_value(nos, i); if ((aint = s2i_ASN1_INTEGER(NULL, cnf->name)) == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NUMBER); return 0; } if (!sk_ASN1_INTEGER_push(nnums, aint)) { ASN1_INTEGER_free(aint); ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); return 0; } } return 1; } static int i2r_certpol(X509V3_EXT_METHOD *method, STACK_OF(POLICYINFO) *pol, BIO *out, int indent) { int i; POLICYINFO *pinfo; /* First print out the policy OIDs */ for (i = 0; i < sk_POLICYINFO_num(pol); i++) { if (i > 0) BIO_puts(out, "\n"); pinfo = sk_POLICYINFO_value(pol, i); BIO_printf(out, "%*sPolicy: ", indent, ""); i2a_ASN1_OBJECT(out, pinfo->policyid); if (pinfo->qualifiers) { BIO_puts(out, "\n"); print_qualifiers(out, pinfo->qualifiers, indent + 2); } } return 1; } static void print_qualifiers(BIO *out, STACK_OF(POLICYQUALINFO) *quals, int indent) { POLICYQUALINFO *qualinfo; int i; for (i = 0; i < sk_POLICYQUALINFO_num(quals); i++) { if (i > 0) BIO_puts(out, "\n"); qualinfo = sk_POLICYQUALINFO_value(quals, i); switch (OBJ_obj2nid(qualinfo->pqualid)) { case NID_id_qt_cps: BIO_printf(out, "%*sCPS: %.*s", indent, "", qualinfo->d.cpsuri->length, qualinfo->d.cpsuri->data); break; case NID_id_qt_unotice: BIO_printf(out, "%*sUser Notice:\n", indent, ""); print_notice(out, qualinfo->d.usernotice, indent + 2); break; default: BIO_printf(out, "%*sUnknown Qualifier: ", indent + 2, ""); i2a_ASN1_OBJECT(out, qualinfo->pqualid); break; } } } static void print_notice(BIO *out, USERNOTICE *notice, int indent) { int i; if (notice->noticeref) { NOTICEREF *ref; ref = notice->noticeref; BIO_printf(out, "%*sOrganization: %.*s\n", indent, "", ref->organization->length, ref->organization->data); BIO_printf(out, "%*sNumber%s: ", indent, "", sk_ASN1_INTEGER_num(ref->noticenos) > 1 ? "s" : ""); for (i = 0; i < sk_ASN1_INTEGER_num(ref->noticenos); i++) { ASN1_INTEGER *num; char *tmp; num = sk_ASN1_INTEGER_value(ref->noticenos, i); if (i) BIO_puts(out, ", "); if (num == NULL) BIO_puts(out, "(null)"); else { tmp = i2s_ASN1_INTEGER(NULL, num); if (tmp == NULL) return; BIO_puts(out, tmp); OPENSSL_free(tmp); } } if (notice->exptext) BIO_puts(out, "\n"); } if (notice->exptext) BIO_printf(out, "%*sExplicit Text: %.*s", indent, "", notice->exptext->length, notice->exptext->data); } void X509_POLICY_NODE_print(BIO *out, X509_POLICY_NODE *node, int indent) { const X509_POLICY_DATA *dat = node->data; BIO_printf(out, "%*sPolicy: ", indent, ""); i2a_ASN1_OBJECT(out, dat->valid_policy); BIO_puts(out, "\n"); BIO_printf(out, "%*s%s\n", indent + 2, "", node_data_critical(dat) ? "Critical" : "Non Critical"); if (dat->qualifier_set) { print_qualifiers(out, dat->qualifier_set, indent + 2); BIO_puts(out, "\n"); } else BIO_printf(out, "%*sNo Qualifiers\n", indent + 2, ""); }
./openssl/crypto/x509/x509cset.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> #include "internal/cryptlib.h" #include "internal/refcount.h" #include <openssl/asn1.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/x509.h> #include "crypto/x509.h" int X509_CRL_set_version(X509_CRL *x, long version) { if (x == NULL) return 0; if (x->crl.version == NULL) { if ((x->crl.version = ASN1_INTEGER_new()) == NULL) return 0; } if (!ASN1_INTEGER_set(x->crl.version, version)) return 0; x->crl.enc.modified = 1; return 1; } int X509_CRL_set_issuer_name(X509_CRL *x, const X509_NAME *name) { if (x == NULL) return 0; if (!X509_NAME_set(&x->crl.issuer, name)) return 0; x->crl.enc.modified = 1; return 1; } int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm) { if (x == NULL || tm == NULL) return 0; return ossl_x509_set1_time(&x->crl.enc.modified, &x->crl.lastUpdate, tm); } int X509_CRL_set1_nextUpdate(X509_CRL *x, const ASN1_TIME *tm) { if (x == NULL) return 0; return ossl_x509_set1_time(&x->crl.enc.modified, &x->crl.nextUpdate, tm); } int X509_CRL_sort(X509_CRL *c) { int i; X509_REVOKED *r; /* * sort the data so it will be written in serial number order */ sk_X509_REVOKED_sort(c->crl.revoked); for (i = 0; i < sk_X509_REVOKED_num(c->crl.revoked); i++) { r = sk_X509_REVOKED_value(c->crl.revoked, i); r->sequence = i; } c->crl.enc.modified = 1; return 1; } int X509_CRL_up_ref(X509_CRL *crl) { int i; if (CRYPTO_UP_REF(&crl->references, &i) <= 0) return 0; REF_PRINT_COUNT("X509_CRL", crl); REF_ASSERT_ISNT(i < 2); return i > 1; } long X509_CRL_get_version(const X509_CRL *crl) { return ASN1_INTEGER_get(crl->crl.version); } const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl) { return crl->crl.lastUpdate; } const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl) { return crl->crl.nextUpdate; } #ifndef OPENSSL_NO_DEPRECATED_1_1_0 ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl) { return crl->crl.lastUpdate; } ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl) { return crl->crl.nextUpdate; } #endif X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl) { return crl->crl.issuer; } const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl) { return crl->crl.extensions; } STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl) { return crl->crl.revoked; } void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig, const X509_ALGOR **palg) { if (psig != NULL) *psig = &crl->signature; if (palg != NULL) *palg = &crl->sig_alg; } int X509_CRL_get_signature_nid(const X509_CRL *crl) { return OBJ_obj2nid(crl->sig_alg.algorithm); } const ASN1_TIME *X509_REVOKED_get0_revocationDate(const X509_REVOKED *x) { return x->revocationDate; } int X509_REVOKED_set_revocationDate(X509_REVOKED *x, ASN1_TIME *tm) { if (x == NULL || tm == NULL) return 0; return ossl_x509_set1_time(NULL, &x->revocationDate, tm); } const ASN1_INTEGER *X509_REVOKED_get0_serialNumber(const X509_REVOKED *x) { return &x->serialNumber; } int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial) { ASN1_INTEGER *in; if (x == NULL) return 0; in = &x->serialNumber; if (in != serial) return ASN1_STRING_copy(in, serial); return 1; } const STACK_OF(X509_EXTENSION) *X509_REVOKED_get0_extensions(const X509_REVOKED *r) { return r->extensions; } int i2d_re_X509_CRL_tbs(X509_CRL *crl, unsigned char **pp) { crl->crl.enc.modified = 1; return i2d_X509_CRL_INFO(&crl->crl, pp); }
./openssl/crypto/x509/v3_asid.c
/* * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Implementation of RFC 3779 section 3.2. */ #include <assert.h> #include <stdio.h> #include <string.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/x509v3.h> #include <openssl/x509.h> #include "crypto/x509.h" #include <openssl/bn.h> #include "ext_dat.h" #include "x509_local.h" #ifndef OPENSSL_NO_RFC3779 /* * OpenSSL ASN.1 template translation of RFC 3779 3.2.3. */ ASN1_SEQUENCE(ASRange) = { ASN1_SIMPLE(ASRange, min, ASN1_INTEGER), ASN1_SIMPLE(ASRange, max, ASN1_INTEGER) } ASN1_SEQUENCE_END(ASRange) ASN1_CHOICE(ASIdOrRange) = { ASN1_SIMPLE(ASIdOrRange, u.id, ASN1_INTEGER), ASN1_SIMPLE(ASIdOrRange, u.range, ASRange) } ASN1_CHOICE_END(ASIdOrRange) ASN1_CHOICE(ASIdentifierChoice) = { ASN1_SIMPLE(ASIdentifierChoice, u.inherit, ASN1_NULL), ASN1_SEQUENCE_OF(ASIdentifierChoice, u.asIdsOrRanges, ASIdOrRange) } ASN1_CHOICE_END(ASIdentifierChoice) ASN1_SEQUENCE(ASIdentifiers) = { ASN1_EXP_OPT(ASIdentifiers, asnum, ASIdentifierChoice, 0), ASN1_EXP_OPT(ASIdentifiers, rdi, ASIdentifierChoice, 1) } ASN1_SEQUENCE_END(ASIdentifiers) IMPLEMENT_ASN1_FUNCTIONS(ASRange) IMPLEMENT_ASN1_FUNCTIONS(ASIdOrRange) IMPLEMENT_ASN1_FUNCTIONS(ASIdentifierChoice) IMPLEMENT_ASN1_FUNCTIONS(ASIdentifiers) /* * i2r method for an ASIdentifierChoice. */ static int i2r_ASIdentifierChoice(BIO *out, ASIdentifierChoice *choice, int indent, const char *msg) { int i; char *s; if (choice == NULL) return 1; BIO_printf(out, "%*s%s:\n", indent, "", msg); switch (choice->type) { case ASIdentifierChoice_inherit: BIO_printf(out, "%*sinherit\n", indent + 2, ""); break; case ASIdentifierChoice_asIdsOrRanges: for (i = 0; i < sk_ASIdOrRange_num(choice->u.asIdsOrRanges); i++) { ASIdOrRange *aor = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); switch (aor->type) { case ASIdOrRange_id: if ((s = i2s_ASN1_INTEGER(NULL, aor->u.id)) == NULL) return 0; BIO_printf(out, "%*s%s\n", indent + 2, "", s); OPENSSL_free(s); break; case ASIdOrRange_range: if ((s = i2s_ASN1_INTEGER(NULL, aor->u.range->min)) == NULL) return 0; BIO_printf(out, "%*s%s-", indent + 2, "", s); OPENSSL_free(s); if ((s = i2s_ASN1_INTEGER(NULL, aor->u.range->max)) == NULL) return 0; BIO_printf(out, "%s\n", s); OPENSSL_free(s); break; default: return 0; } } break; default: return 0; } return 1; } /* * i2r method for an ASIdentifier extension. */ static int i2r_ASIdentifiers(const X509V3_EXT_METHOD *method, void *ext, BIO *out, int indent) { ASIdentifiers *asid = ext; return (i2r_ASIdentifierChoice(out, asid->asnum, indent, "Autonomous System Numbers") && i2r_ASIdentifierChoice(out, asid->rdi, indent, "Routing Domain Identifiers")); } /* * Sort comparison function for a sequence of ASIdOrRange elements. */ static int ASIdOrRange_cmp(const ASIdOrRange *const *a_, const ASIdOrRange *const *b_) { const ASIdOrRange *a = *a_, *b = *b_; assert((a->type == ASIdOrRange_id && a->u.id != NULL) || (a->type == ASIdOrRange_range && a->u.range != NULL && a->u.range->min != NULL && a->u.range->max != NULL)); assert((b->type == ASIdOrRange_id && b->u.id != NULL) || (b->type == ASIdOrRange_range && b->u.range != NULL && b->u.range->min != NULL && b->u.range->max != NULL)); if (a->type == ASIdOrRange_id && b->type == ASIdOrRange_id) return ASN1_INTEGER_cmp(a->u.id, b->u.id); if (a->type == ASIdOrRange_range && b->type == ASIdOrRange_range) { int r = ASN1_INTEGER_cmp(a->u.range->min, b->u.range->min); return r != 0 ? r : ASN1_INTEGER_cmp(a->u.range->max, b->u.range->max); } if (a->type == ASIdOrRange_id) return ASN1_INTEGER_cmp(a->u.id, b->u.range->min); else return ASN1_INTEGER_cmp(a->u.range->min, b->u.id); } /* * Add an inherit element. */ int X509v3_asid_add_inherit(ASIdentifiers *asid, int which) { ASIdentifierChoice **choice; if (asid == NULL) return 0; switch (which) { case V3_ASID_ASNUM: choice = &asid->asnum; break; case V3_ASID_RDI: choice = &asid->rdi; break; default: return 0; } if (*choice == NULL) { if ((*choice = ASIdentifierChoice_new()) == NULL) return 0; if (((*choice)->u.inherit = ASN1_NULL_new()) == NULL) { ASIdentifierChoice_free(*choice); *choice = NULL; return 0; } (*choice)->type = ASIdentifierChoice_inherit; } return (*choice)->type == ASIdentifierChoice_inherit; } /* * Add an ID or range to an ASIdentifierChoice. */ int X509v3_asid_add_id_or_range(ASIdentifiers *asid, int which, ASN1_INTEGER *min, ASN1_INTEGER *max) { ASIdentifierChoice **choice; ASIdOrRange *aor; if (asid == NULL) return 0; switch (which) { case V3_ASID_ASNUM: choice = &asid->asnum; break; case V3_ASID_RDI: choice = &asid->rdi; break; default: return 0; } if (*choice != NULL && (*choice)->type != ASIdentifierChoice_asIdsOrRanges) return 0; if (*choice == NULL) { if ((*choice = ASIdentifierChoice_new()) == NULL) return 0; (*choice)->u.asIdsOrRanges = sk_ASIdOrRange_new(ASIdOrRange_cmp); if ((*choice)->u.asIdsOrRanges == NULL) { ASIdentifierChoice_free(*choice); *choice = NULL; return 0; } (*choice)->type = ASIdentifierChoice_asIdsOrRanges; } if ((aor = ASIdOrRange_new()) == NULL) return 0; if (!sk_ASIdOrRange_reserve((*choice)->u.asIdsOrRanges, 1)) goto err; if (max == NULL) { aor->type = ASIdOrRange_id; aor->u.id = min; } else { aor->type = ASIdOrRange_range; if ((aor->u.range = ASRange_new()) == NULL) goto err; ASN1_INTEGER_free(aor->u.range->min); aor->u.range->min = min; ASN1_INTEGER_free(aor->u.range->max); aor->u.range->max = max; } /* Cannot fail due to the reservation above */ if (!ossl_assert(sk_ASIdOrRange_push((*choice)->u.asIdsOrRanges, aor))) goto err; return 1; err: ASIdOrRange_free(aor); return 0; } /* * Extract min and max values from an ASIdOrRange. */ static int extract_min_max(ASIdOrRange *aor, ASN1_INTEGER **min, ASN1_INTEGER **max) { if (!ossl_assert(aor != NULL)) return 0; switch (aor->type) { case ASIdOrRange_id: *min = aor->u.id; *max = aor->u.id; return 1; case ASIdOrRange_range: *min = aor->u.range->min; *max = aor->u.range->max; return 1; } return 0; } /* * Check whether an ASIdentifierChoice is in canonical form. */ static int ASIdentifierChoice_is_canonical(ASIdentifierChoice *choice) { ASN1_INTEGER *a_max_plus_one = NULL; ASN1_INTEGER *orig; BIGNUM *bn = NULL; int i, ret = 0; /* * Empty element or inheritance is canonical. */ if (choice == NULL || choice->type == ASIdentifierChoice_inherit) return 1; /* * If not a list, or if empty list, it's broken. */ if (choice->type != ASIdentifierChoice_asIdsOrRanges || sk_ASIdOrRange_num(choice->u.asIdsOrRanges) == 0) return 0; /* * It's a list, check it. */ for (i = 0; i < sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1; i++) { ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); ASIdOrRange *b = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i + 1); ASN1_INTEGER *a_min = NULL, *a_max = NULL, *b_min = NULL, *b_max = NULL; if (!extract_min_max(a, &a_min, &a_max) || !extract_min_max(b, &b_min, &b_max)) goto done; /* * Punt misordered list, overlapping start, or inverted range. */ if (ASN1_INTEGER_cmp(a_min, b_min) >= 0 || ASN1_INTEGER_cmp(a_min, a_max) > 0 || ASN1_INTEGER_cmp(b_min, b_max) > 0) goto done; /* * Calculate a_max + 1 to check for adjacency. */ if ((bn == NULL && (bn = BN_new()) == NULL) || ASN1_INTEGER_to_BN(a_max, bn) == NULL || !BN_add_word(bn, 1)) { ERR_raise(ERR_LIB_X509V3, ERR_R_BN_LIB); goto done; } if ((a_max_plus_one = BN_to_ASN1_INTEGER(bn, orig = a_max_plus_one)) == NULL) { a_max_plus_one = orig; ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto done; } /* * Punt if adjacent or overlapping. */ if (ASN1_INTEGER_cmp(a_max_plus_one, b_min) >= 0) goto done; } /* * Check for inverted range. */ i = sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1; { ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); ASN1_INTEGER *a_min, *a_max; if (a != NULL && a->type == ASIdOrRange_range) { if (!extract_min_max(a, &a_min, &a_max) || ASN1_INTEGER_cmp(a_min, a_max) > 0) goto done; } } ret = 1; done: ASN1_INTEGER_free(a_max_plus_one); BN_free(bn); return ret; } /* * Check whether an ASIdentifier extension is in canonical form. */ int X509v3_asid_is_canonical(ASIdentifiers *asid) { return (asid == NULL || (ASIdentifierChoice_is_canonical(asid->asnum) && ASIdentifierChoice_is_canonical(asid->rdi))); } /* * Whack an ASIdentifierChoice into canonical form. */ static int ASIdentifierChoice_canonize(ASIdentifierChoice *choice) { ASN1_INTEGER *a_max_plus_one = NULL; ASN1_INTEGER *orig; BIGNUM *bn = NULL; int i, ret = 0; /* * Nothing to do for empty element or inheritance. */ if (choice == NULL || choice->type == ASIdentifierChoice_inherit) return 1; /* * If not a list, or if empty list, it's broken. */ if (choice->type != ASIdentifierChoice_asIdsOrRanges || sk_ASIdOrRange_num(choice->u.asIdsOrRanges) == 0) { ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR); return 0; } /* * We have a non-empty list. Sort it. */ sk_ASIdOrRange_sort(choice->u.asIdsOrRanges); /* * Now check for errors and suboptimal encoding, rejecting the * former and fixing the latter. */ for (i = 0; i < sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1; i++) { ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); ASIdOrRange *b = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i + 1); ASN1_INTEGER *a_min = NULL, *a_max = NULL, *b_min = NULL, *b_max = NULL; if (!extract_min_max(a, &a_min, &a_max) || !extract_min_max(b, &b_min, &b_max)) goto done; /* * Make sure we're properly sorted (paranoia). */ if (!ossl_assert(ASN1_INTEGER_cmp(a_min, b_min) <= 0)) goto done; /* * Punt inverted ranges. */ if (ASN1_INTEGER_cmp(a_min, a_max) > 0 || ASN1_INTEGER_cmp(b_min, b_max) > 0) goto done; /* * Check for overlaps. */ if (ASN1_INTEGER_cmp(a_max, b_min) >= 0) { ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR); goto done; } /* * Calculate a_max + 1 to check for adjacency. */ if ((bn == NULL && (bn = BN_new()) == NULL) || ASN1_INTEGER_to_BN(a_max, bn) == NULL || !BN_add_word(bn, 1)) { ERR_raise(ERR_LIB_X509V3, ERR_R_BN_LIB); goto done; } if ((a_max_plus_one = BN_to_ASN1_INTEGER(bn, orig = a_max_plus_one)) == NULL) { a_max_plus_one = orig; ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto done; } /* * If a and b are adjacent, merge them. */ if (ASN1_INTEGER_cmp(a_max_plus_one, b_min) == 0) { ASRange *r; switch (a->type) { case ASIdOrRange_id: if ((r = OPENSSL_malloc(sizeof(*r))) == NULL) goto done; r->min = a_min; r->max = b_max; a->type = ASIdOrRange_range; a->u.range = r; break; case ASIdOrRange_range: ASN1_INTEGER_free(a->u.range->max); a->u.range->max = b_max; break; } switch (b->type) { case ASIdOrRange_id: b->u.id = NULL; break; case ASIdOrRange_range: b->u.range->max = NULL; break; } ASIdOrRange_free(b); (void)sk_ASIdOrRange_delete(choice->u.asIdsOrRanges, i + 1); i--; continue; } } /* * Check for final inverted range. */ i = sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1; { ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); ASN1_INTEGER *a_min, *a_max; if (a != NULL && a->type == ASIdOrRange_range) { if (!extract_min_max(a, &a_min, &a_max) || ASN1_INTEGER_cmp(a_min, a_max) > 0) goto done; } } /* Paranoia */ if (!ossl_assert(ASIdentifierChoice_is_canonical(choice))) goto done; ret = 1; done: ASN1_INTEGER_free(a_max_plus_one); BN_free(bn); return ret; } /* * Whack an ASIdentifier extension into canonical form. */ int X509v3_asid_canonize(ASIdentifiers *asid) { return (asid == NULL || (ASIdentifierChoice_canonize(asid->asnum) && ASIdentifierChoice_canonize(asid->rdi))); } /* * v2i method for an ASIdentifier extension. */ static void *v2i_ASIdentifiers(const struct v3_ext_method *method, struct v3_ext_ctx *ctx, STACK_OF(CONF_VALUE) *values) { ASN1_INTEGER *min = NULL, *max = NULL; ASIdentifiers *asid = NULL; int i; if ((asid = ASIdentifiers_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB); return NULL; } for (i = 0; i < sk_CONF_VALUE_num(values); i++) { CONF_VALUE *val = sk_CONF_VALUE_value(values, i); int i1 = 0, i2 = 0, i3 = 0, is_range = 0, which = 0; /* * Figure out whether this is an AS or an RDI. */ if (!ossl_v3_name_cmp(val->name, "AS")) { which = V3_ASID_ASNUM; } else if (!ossl_v3_name_cmp(val->name, "RDI")) { which = V3_ASID_RDI; } else { ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_NAME_ERROR); X509V3_conf_add_error_name_value(val); goto err; } if (val->value == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR); goto err; } /* * Handle inheritance. */ if (strcmp(val->value, "inherit") == 0) { if (X509v3_asid_add_inherit(asid, which)) continue; ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_INHERITANCE); X509V3_conf_add_error_name_value(val); goto err; } /* * Number, range, or mistake, pick it apart and figure out which. */ i1 = strspn(val->value, "0123456789"); if (val->value[i1] == '\0') { is_range = 0; } else { is_range = 1; i2 = i1 + strspn(val->value + i1, " \t"); if (val->value[i2] != '-') { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_ASNUMBER); X509V3_conf_add_error_name_value(val); goto err; } i2++; i2 = i2 + strspn(val->value + i2, " \t"); i3 = i2 + strspn(val->value + i2, "0123456789"); if (val->value[i3] != '\0') { ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_ASRANGE); X509V3_conf_add_error_name_value(val); goto err; } } /* * Syntax is ok, read and add it. */ if (!is_range) { if (!X509V3_get_value_int(val, &min)) { ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB); goto err; } } else { char *s = OPENSSL_strdup(val->value); if (s == NULL) goto err; s[i1] = '\0'; min = s2i_ASN1_INTEGER(NULL, s); max = s2i_ASN1_INTEGER(NULL, s + i2); OPENSSL_free(s); if (min == NULL || max == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB); goto err; } if (ASN1_INTEGER_cmp(min, max) > 0) { ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR); goto err; } } if (!X509v3_asid_add_id_or_range(asid, which, min, max)) { ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB); goto err; } min = max = NULL; } /* * Canonize the result, then we're done. */ if (!X509v3_asid_canonize(asid)) goto err; return asid; err: ASIdentifiers_free(asid); ASN1_INTEGER_free(min); ASN1_INTEGER_free(max); return NULL; } /* * OpenSSL dispatch. */ const X509V3_EXT_METHOD ossl_v3_asid = { NID_sbgp_autonomousSysNum, /* nid */ 0, /* flags */ ASN1_ITEM_ref(ASIdentifiers), /* template */ 0, 0, 0, 0, /* old functions, ignored */ 0, /* i2s */ 0, /* s2i */ 0, /* i2v */ v2i_ASIdentifiers, /* v2i */ i2r_ASIdentifiers, /* i2r */ 0, /* r2i */ NULL /* extension-specific data */ }; /* * Figure out whether extension uses inheritance. */ int X509v3_asid_inherits(ASIdentifiers *asid) { return (asid != NULL && ((asid->asnum != NULL && asid->asnum->type == ASIdentifierChoice_inherit) || (asid->rdi != NULL && asid->rdi->type == ASIdentifierChoice_inherit))); } /* * Figure out whether parent contains child. */ static int asid_contains(ASIdOrRanges *parent, ASIdOrRanges *child) { ASN1_INTEGER *p_min = NULL, *p_max = NULL, *c_min = NULL, *c_max = NULL; int p, c; if (child == NULL || parent == child) return 1; if (parent == NULL) return 0; p = 0; for (c = 0; c < sk_ASIdOrRange_num(child); c++) { if (!extract_min_max(sk_ASIdOrRange_value(child, c), &c_min, &c_max)) return 0; for (;; p++) { if (p >= sk_ASIdOrRange_num(parent)) return 0; if (!extract_min_max(sk_ASIdOrRange_value(parent, p), &p_min, &p_max)) return 0; if (ASN1_INTEGER_cmp(p_max, c_max) < 0) continue; if (ASN1_INTEGER_cmp(p_min, c_min) > 0) return 0; break; } } return 1; } /* * Test whether a is a subset of b. */ int X509v3_asid_subset(ASIdentifiers *a, ASIdentifiers *b) { int subset; if (a == NULL || a == b) return 1; if (b == NULL) return 0; if (X509v3_asid_inherits(a) || X509v3_asid_inherits(b)) return 0; subset = a->asnum == NULL || (b->asnum != NULL && asid_contains(b->asnum->u.asIdsOrRanges, a->asnum->u.asIdsOrRanges)); if (!subset) return 0; return a->rdi == NULL || (b->rdi != NULL && asid_contains(b->rdi->u.asIdsOrRanges, a->rdi->u.asIdsOrRanges)); } /* * Validation error handling via callback. */ #define validation_err(_err_) \ do { \ if (ctx != NULL) { \ ctx->error = _err_; \ ctx->error_depth = i; \ ctx->current_cert = x; \ ret = ctx->verify_cb(0, ctx); \ } else { \ ret = 0; \ } \ if (!ret) \ goto done; \ } while (0) /* * Core code for RFC 3779 3.3 path validation. */ static int asid_validate_path_internal(X509_STORE_CTX *ctx, STACK_OF(X509) *chain, ASIdentifiers *ext) { ASIdOrRanges *child_as = NULL, *child_rdi = NULL; int i, ret = 1, inherit_as = 0, inherit_rdi = 0; X509 *x; if (!ossl_assert(chain != NULL && sk_X509_num(chain) > 0) || !ossl_assert(ctx != NULL || ext != NULL) || !ossl_assert(ctx == NULL || ctx->verify_cb != NULL)) { if (ctx != NULL) ctx->error = X509_V_ERR_UNSPECIFIED; return 0; } /* * Figure out where to start. If we don't have an extension to * check, we're done. Otherwise, check canonical form and * set up for walking up the chain. */ if (ext != NULL) { i = -1; x = NULL; } else { i = 0; x = sk_X509_value(chain, i); if ((ext = x->rfc3779_asid) == NULL) goto done; } if (!X509v3_asid_is_canonical(ext)) validation_err(X509_V_ERR_INVALID_EXTENSION); if (ext->asnum != NULL) { switch (ext->asnum->type) { case ASIdentifierChoice_inherit: inherit_as = 1; break; case ASIdentifierChoice_asIdsOrRanges: child_as = ext->asnum->u.asIdsOrRanges; break; } } if (ext->rdi != NULL) { switch (ext->rdi->type) { case ASIdentifierChoice_inherit: inherit_rdi = 1; break; case ASIdentifierChoice_asIdsOrRanges: child_rdi = ext->rdi->u.asIdsOrRanges; break; } } /* * Now walk up the chain. Extensions must be in canonical form, no * cert may list resources that its parent doesn't list. */ for (i++; i < sk_X509_num(chain); i++) { x = sk_X509_value(chain, i); if (!ossl_assert(x != NULL)) { if (ctx != NULL) ctx->error = X509_V_ERR_UNSPECIFIED; return 0; } if (x->rfc3779_asid == NULL) { if (child_as != NULL || child_rdi != NULL) validation_err(X509_V_ERR_UNNESTED_RESOURCE); continue; } if (!X509v3_asid_is_canonical(x->rfc3779_asid)) validation_err(X509_V_ERR_INVALID_EXTENSION); if (x->rfc3779_asid->asnum == NULL && child_as != NULL) { validation_err(X509_V_ERR_UNNESTED_RESOURCE); child_as = NULL; inherit_as = 0; } if (x->rfc3779_asid->asnum != NULL && x->rfc3779_asid->asnum->type == ASIdentifierChoice_asIdsOrRanges) { if (inherit_as || asid_contains(x->rfc3779_asid->asnum->u.asIdsOrRanges, child_as)) { child_as = x->rfc3779_asid->asnum->u.asIdsOrRanges; inherit_as = 0; } else { validation_err(X509_V_ERR_UNNESTED_RESOURCE); } } if (x->rfc3779_asid->rdi == NULL && child_rdi != NULL) { validation_err(X509_V_ERR_UNNESTED_RESOURCE); child_rdi = NULL; inherit_rdi = 0; } if (x->rfc3779_asid->rdi != NULL && x->rfc3779_asid->rdi->type == ASIdentifierChoice_asIdsOrRanges) { if (inherit_rdi || asid_contains(x->rfc3779_asid->rdi->u.asIdsOrRanges, child_rdi)) { child_rdi = x->rfc3779_asid->rdi->u.asIdsOrRanges; inherit_rdi = 0; } else { validation_err(X509_V_ERR_UNNESTED_RESOURCE); } } } /* * Trust anchor can't inherit. */ if (!ossl_assert(x != NULL)) { if (ctx != NULL) ctx->error = X509_V_ERR_UNSPECIFIED; return 0; } if (x->rfc3779_asid != NULL) { if (x->rfc3779_asid->asnum != NULL && x->rfc3779_asid->asnum->type == ASIdentifierChoice_inherit) validation_err(X509_V_ERR_UNNESTED_RESOURCE); if (x->rfc3779_asid->rdi != NULL && x->rfc3779_asid->rdi->type == ASIdentifierChoice_inherit) validation_err(X509_V_ERR_UNNESTED_RESOURCE); } done: return ret; } #undef validation_err /* * RFC 3779 3.3 path validation -- called from X509_verify_cert(). */ int X509v3_asid_validate_path(X509_STORE_CTX *ctx) { if (ctx->chain == NULL || sk_X509_num(ctx->chain) == 0 || ctx->verify_cb == NULL) { ctx->error = X509_V_ERR_UNSPECIFIED; return 0; } return asid_validate_path_internal(ctx, ctx->chain, NULL); } /* * RFC 3779 3.3 path validation of an extension. * Test whether chain covers extension. */ int X509v3_asid_validate_resource_set(STACK_OF(X509) *chain, ASIdentifiers *ext, int allow_inheritance) { if (ext == NULL) return 1; if (chain == NULL || sk_X509_num(chain) == 0) return 0; if (!allow_inheritance && X509v3_asid_inherits(ext)) return 0; return asid_validate_path_internal(NULL, chain, ext); } #endif /* OPENSSL_NO_RFC3779 */
./openssl/crypto/x509/v3_enum.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/x509v3.h> #include "ext_dat.h" static ENUMERATED_NAMES crl_reasons[] = { {CRL_REASON_UNSPECIFIED, "Unspecified", "unspecified"}, {CRL_REASON_KEY_COMPROMISE, "Key Compromise", "keyCompromise"}, {CRL_REASON_CA_COMPROMISE, "CA Compromise", "CACompromise"}, {CRL_REASON_AFFILIATION_CHANGED, "Affiliation Changed", "affiliationChanged"}, {CRL_REASON_SUPERSEDED, "Superseded", "superseded"}, {CRL_REASON_CESSATION_OF_OPERATION, "Cessation Of Operation", "cessationOfOperation"}, {CRL_REASON_CERTIFICATE_HOLD, "Certificate Hold", "certificateHold"}, {CRL_REASON_REMOVE_FROM_CRL, "Remove From CRL", "removeFromCRL"}, {CRL_REASON_PRIVILEGE_WITHDRAWN, "Privilege Withdrawn", "privilegeWithdrawn"}, {CRL_REASON_AA_COMPROMISE, "AA Compromise", "AACompromise"}, {-1, NULL, NULL} }; const X509V3_EXT_METHOD ossl_v3_crl_reason = { NID_crl_reason, 0, ASN1_ITEM_ref(ASN1_ENUMERATED), 0, 0, 0, 0, (X509V3_EXT_I2S)i2s_ASN1_ENUMERATED_TABLE, 0, 0, 0, 0, 0, crl_reasons }; char *i2s_ASN1_ENUMERATED_TABLE(X509V3_EXT_METHOD *method, const ASN1_ENUMERATED *e) { ENUMERATED_NAMES *enam; long strval; strval = ASN1_ENUMERATED_get(e); for (enam = method->usr_data; enam->lname; enam++) { if (strval == enam->bitnum) return OPENSSL_strdup(enam->lname); } return i2s_ASN1_ENUMERATED(method, e); }
./openssl/crypto/x509/v3_lib.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 */ /* X509 v3 extension utilities */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/x509v3.h> #include "ext_dat.h" static STACK_OF(X509V3_EXT_METHOD) *ext_list = NULL; static int ext_cmp(const X509V3_EXT_METHOD *const *a, const X509V3_EXT_METHOD *const *b); static void ext_list_free(X509V3_EXT_METHOD *ext); int X509V3_EXT_add(X509V3_EXT_METHOD *ext) { if (ext_list == NULL && (ext_list = sk_X509V3_EXT_METHOD_new(ext_cmp)) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); return 0; } if (!sk_X509V3_EXT_METHOD_push(ext_list, ext)) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); return 0; } return 1; } static int ext_cmp(const X509V3_EXT_METHOD *const *a, const X509V3_EXT_METHOD *const *b) { return ((*a)->ext_nid - (*b)->ext_nid); } DECLARE_OBJ_BSEARCH_CMP_FN(const X509V3_EXT_METHOD *, const X509V3_EXT_METHOD *, ext); IMPLEMENT_OBJ_BSEARCH_CMP_FN(const X509V3_EXT_METHOD *, const X509V3_EXT_METHOD *, ext); #include "standard_exts.h" const X509V3_EXT_METHOD *X509V3_EXT_get_nid(int nid) { X509V3_EXT_METHOD tmp; const X509V3_EXT_METHOD *t = &tmp, *const *ret; int idx; if (nid < 0) return NULL; tmp.ext_nid = nid; ret = OBJ_bsearch_ext(&t, standard_exts, STANDARD_EXTENSION_COUNT); if (ret) return *ret; if (!ext_list) return NULL; /* Ideally, this would be done under a lock */ sk_X509V3_EXT_METHOD_sort(ext_list); idx = sk_X509V3_EXT_METHOD_find(ext_list, &tmp); /* A failure to locate the item is handled by the value method */ return sk_X509V3_EXT_METHOD_value(ext_list, idx); } const X509V3_EXT_METHOD *X509V3_EXT_get(X509_EXTENSION *ext) { int nid; if ((nid = OBJ_obj2nid(X509_EXTENSION_get_object(ext))) == NID_undef) return NULL; return X509V3_EXT_get_nid(nid); } int X509V3_EXT_add_list(X509V3_EXT_METHOD *extlist) { for (; extlist->ext_nid != -1; extlist++) if (!X509V3_EXT_add(extlist)) return 0; return 1; } int X509V3_EXT_add_alias(int nid_to, int nid_from) { const X509V3_EXT_METHOD *ext; X509V3_EXT_METHOD *tmpext; if ((ext = X509V3_EXT_get_nid(nid_from)) == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_NOT_FOUND); return 0; } if ((tmpext = OPENSSL_malloc(sizeof(*tmpext))) == NULL) return 0; *tmpext = *ext; tmpext->ext_nid = nid_to; tmpext->ext_flags |= X509V3_EXT_DYNAMIC; return X509V3_EXT_add(tmpext); } void X509V3_EXT_cleanup(void) { sk_X509V3_EXT_METHOD_pop_free(ext_list, ext_list_free); ext_list = NULL; } static void ext_list_free(X509V3_EXT_METHOD *ext) { if (ext->ext_flags & X509V3_EXT_DYNAMIC) OPENSSL_free(ext); } /* * Legacy function: we don't need to add standard extensions any more because * they are now kept in ext_dat.h. */ int X509V3_add_standard_extensions(void) { return 1; } /* Return an extension internal structure */ void *X509V3_EXT_d2i(X509_EXTENSION *ext) { const X509V3_EXT_METHOD *method; const unsigned char *p; ASN1_STRING *extvalue; int extlen; if ((method = X509V3_EXT_get(ext)) == NULL) return NULL; extvalue = X509_EXTENSION_get_data(ext); p = ASN1_STRING_get0_data(extvalue); extlen = ASN1_STRING_length(extvalue); if (method->it) return ASN1_item_d2i(NULL, &p, extlen, ASN1_ITEM_ptr(method->it)); return method->d2i(NULL, &p, extlen); } /*- * Get critical flag and decoded version of extension from a NID. * The "idx" variable returns the last found extension and can * be used to retrieve multiple extensions of the same NID. * However multiple extensions with the same NID is usually * due to a badly encoded certificate so if idx is NULL we * choke if multiple extensions exist. * The "crit" variable is set to the critical value. * The return value is the decoded extension or NULL on * error. The actual error can have several different causes, * the value of *crit reflects the cause: * >= 0, extension found but not decoded (reflects critical value). * -1 extension not found. * -2 extension occurs more than once. */ void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *x, int nid, int *crit, int *idx) { int lastpos, i; X509_EXTENSION *ex, *found_ex = NULL; if (!x) { if (idx) *idx = -1; if (crit) *crit = -1; return NULL; } if (idx) lastpos = *idx + 1; else lastpos = 0; if (lastpos < 0) lastpos = 0; for (i = lastpos; i < sk_X509_EXTENSION_num(x); i++) { ex = sk_X509_EXTENSION_value(x, i); if (OBJ_obj2nid(X509_EXTENSION_get_object(ex)) == nid) { if (idx) { *idx = i; found_ex = ex; break; } else if (found_ex) { /* Found more than one */ if (crit) *crit = -2; return NULL; } found_ex = ex; } } if (found_ex) { /* Found it */ if (crit) *crit = X509_EXTENSION_get_critical(found_ex); return X509V3_EXT_d2i(found_ex); } /* Extension not found */ if (idx) *idx = -1; if (crit) *crit = -1; return NULL; } /* * This function is a general extension append, replace and delete utility. * The precise operation is governed by the 'flags' value. The 'crit' and * 'value' arguments (if relevant) are the extensions internal structure. */ int X509V3_add1_i2d(STACK_OF(X509_EXTENSION) **x, int nid, void *value, int crit, unsigned long flags) { int errcode, extidx = -1; X509_EXTENSION *ext = NULL, *extmp; STACK_OF(X509_EXTENSION) *ret = NULL; unsigned long ext_op = flags & X509V3_ADD_OP_MASK; /* * If appending we don't care if it exists, otherwise look for existing * extension. */ if (ext_op != X509V3_ADD_APPEND) extidx = X509v3_get_ext_by_NID(*x, nid, -1); /* See if extension exists */ if (extidx >= 0) { /* If keep existing, nothing to do */ if (ext_op == X509V3_ADD_KEEP_EXISTING) return 1; /* If default then its an error */ if (ext_op == X509V3_ADD_DEFAULT) { errcode = X509V3_R_EXTENSION_EXISTS; goto err; } /* If delete, just delete it */ if (ext_op == X509V3_ADD_DELETE) { extmp = sk_X509_EXTENSION_delete(*x, extidx); if (extmp == NULL) return -1; X509_EXTENSION_free(extmp); return 1; } } else { /* * If replace existing or delete, error since extension must exist */ if ((ext_op == X509V3_ADD_REPLACE_EXISTING) || (ext_op == X509V3_ADD_DELETE)) { errcode = X509V3_R_EXTENSION_NOT_FOUND; goto err; } } /* * If we get this far then we have to create an extension: could have * some flags for alternative encoding schemes... */ ext = X509V3_EXT_i2d(nid, crit, value); if (!ext) { ERR_raise(ERR_LIB_X509V3, X509V3_R_ERROR_CREATING_EXTENSION); return 0; } /* If extension exists replace it.. */ if (extidx >= 0) { extmp = sk_X509_EXTENSION_value(*x, extidx); X509_EXTENSION_free(extmp); if (!sk_X509_EXTENSION_set(*x, extidx, ext)) return -1; return 1; } ret = *x; if (*x == NULL && (ret = sk_X509_EXTENSION_new_null()) == NULL) goto m_fail; if (!sk_X509_EXTENSION_push(ret, ext)) goto m_fail; *x = ret; return 1; m_fail: /* ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); */ if (ret != *x) sk_X509_EXTENSION_free(ret); X509_EXTENSION_free(ext); return -1; err: if (!(flags & X509V3_ADD_SILENT)) ERR_raise(ERR_LIB_X509V3, errcode); return 0; }
./openssl/crypto/x509/pcy_local.h
/* * Copyright 2004-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 */ typedef struct X509_POLICY_DATA_st X509_POLICY_DATA; DEFINE_STACK_OF(X509_POLICY_DATA) /* Internal structures */ /* * This structure and the field names correspond to the Policy 'node' of * RFC3280. NB this structure contains no pointers to parent or child data: * X509_POLICY_NODE contains that. This means that the main policy data can * be kept static and cached with the certificate. */ struct X509_POLICY_DATA_st { unsigned int flags; /* Policy OID and qualifiers for this data */ ASN1_OBJECT *valid_policy; STACK_OF(POLICYQUALINFO) *qualifier_set; STACK_OF(ASN1_OBJECT) *expected_policy_set; }; /* X509_POLICY_DATA flags values */ /* * This flag indicates the structure has been mapped using a policy mapping * extension. If policy mapping is not active its references get deleted. */ #define POLICY_DATA_FLAG_MAPPED 0x1 /* * This flag indicates the data doesn't correspond to a policy in Certificate * Policies: it has been mapped to any policy. */ #define POLICY_DATA_FLAG_MAPPED_ANY 0x2 /* AND with flags to see if any mapping has occurred */ #define POLICY_DATA_FLAG_MAP_MASK 0x3 /* qualifiers are shared and shouldn't be freed */ #define POLICY_DATA_FLAG_SHARED_QUALIFIERS 0x4 /* Parent node is an extra node and should be freed */ #define POLICY_DATA_FLAG_EXTRA_NODE 0x8 /* Corresponding CertificatePolicies is critical */ #define POLICY_DATA_FLAG_CRITICAL 0x10 /* This structure is cached with a certificate */ struct X509_POLICY_CACHE_st { /* anyPolicy data or NULL if no anyPolicy */ X509_POLICY_DATA *anyPolicy; /* other policy data */ STACK_OF(X509_POLICY_DATA) *data; /* If InhibitAnyPolicy present this is its value or -1 if absent. */ long any_skip; /* * If policyConstraints and requireExplicitPolicy present this is its * value or -1 if absent. */ long explicit_skip; /* * If policyConstraints and policyMapping present this is its value or -1 * if absent. */ long map_skip; }; /* * #define POLICY_CACHE_FLAG_CRITICAL POLICY_DATA_FLAG_CRITICAL */ /* This structure represents the relationship between nodes */ struct X509_POLICY_NODE_st { /* node data this refers to */ const X509_POLICY_DATA *data; /* Parent node */ X509_POLICY_NODE *parent; /* Number of child nodes */ int nchild; }; struct X509_POLICY_LEVEL_st { /* Cert for this level */ X509 *cert; /* nodes at this level */ STACK_OF(X509_POLICY_NODE) *nodes; /* anyPolicy node */ X509_POLICY_NODE *anyPolicy; /* Extra data */ /* * STACK_OF(X509_POLICY_DATA) *extra_data; */ unsigned int flags; }; struct X509_POLICY_TREE_st { /* The number of nodes in the tree */ size_t node_count; /* The maximum number of nodes in the tree */ size_t node_maximum; /* This is the tree 'level' data */ X509_POLICY_LEVEL *levels; int nlevel; /* * Extra policy data when additional nodes (not from the certificate) are * required. */ STACK_OF(X509_POLICY_DATA) *extra_data; /* This is the authority constrained policy set */ STACK_OF(X509_POLICY_NODE) *auth_policies; STACK_OF(X509_POLICY_NODE) *user_policies; unsigned int flags; }; /* Set if anyPolicy present in user policies */ #define POLICY_FLAG_ANY_POLICY 0x2 /* Useful macros */ #define node_data_critical(data) (data->flags & POLICY_DATA_FLAG_CRITICAL) #define node_critical(node) node_data_critical(node->data) /* Internal functions */ X509_POLICY_DATA *ossl_policy_data_new(POLICYINFO *policy, const ASN1_OBJECT *id, int crit); void ossl_policy_data_free(X509_POLICY_DATA *data); X509_POLICY_DATA *ossl_policy_cache_find_data(const X509_POLICY_CACHE *cache, const ASN1_OBJECT *id); int ossl_policy_cache_set_mapping(X509 *x, POLICY_MAPPINGS *maps); STACK_OF(X509_POLICY_NODE) *ossl_policy_node_cmp_new(void); void ossl_policy_cache_free(X509_POLICY_CACHE *cache); X509_POLICY_NODE *ossl_policy_level_find_node(const X509_POLICY_LEVEL *level, const X509_POLICY_NODE *parent, const ASN1_OBJECT *id); X509_POLICY_NODE *ossl_policy_tree_find_sk(STACK_OF(X509_POLICY_NODE) *sk, const ASN1_OBJECT *id); X509_POLICY_NODE *ossl_policy_level_add_node(X509_POLICY_LEVEL *level, X509_POLICY_DATA *data, X509_POLICY_NODE *parent, X509_POLICY_TREE *tree, int extra_data); void ossl_policy_node_free(X509_POLICY_NODE *node); int ossl_policy_node_match(const X509_POLICY_LEVEL *lvl, const X509_POLICY_NODE *node, const ASN1_OBJECT *oid); const X509_POLICY_CACHE *ossl_policy_cache_set(X509 *x);
./openssl/crypto/x509/x_exten.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 <stddef.h> #include <openssl/x509.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include "x509_local.h" ASN1_SEQUENCE(X509_EXTENSION) = { ASN1_SIMPLE(X509_EXTENSION, object, ASN1_OBJECT), ASN1_OPT(X509_EXTENSION, critical, ASN1_BOOLEAN), ASN1_EMBED(X509_EXTENSION, value, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(X509_EXTENSION) ASN1_ITEM_TEMPLATE(X509_EXTENSIONS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, Extension, X509_EXTENSION) ASN1_ITEM_TEMPLATE_END(X509_EXTENSIONS) IMPLEMENT_ASN1_FUNCTIONS(X509_EXTENSION) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS) IMPLEMENT_ASN1_DUP_FUNCTION(X509_EXTENSION)
./openssl/crypto/x509/v3_akid.c
/* * Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/x509v3.h> #include "crypto/x509.h" #include "ext_dat.h" static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(X509V3_EXT_METHOD *method, AUTHORITY_KEYID *akeyid, STACK_OF(CONF_VALUE) *extlist); static AUTHORITY_KEYID *v2i_AUTHORITY_KEYID(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *values); const X509V3_EXT_METHOD ossl_v3_akey_id = { NID_authority_key_identifier, X509V3_EXT_MULTILINE, ASN1_ITEM_ref(AUTHORITY_KEYID), 0, 0, 0, 0, 0, 0, (X509V3_EXT_I2V) i2v_AUTHORITY_KEYID, (X509V3_EXT_V2I)v2i_AUTHORITY_KEYID, 0, 0, NULL }; static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(X509V3_EXT_METHOD *method, AUTHORITY_KEYID *akeyid, STACK_OF(CONF_VALUE) *extlist) { char *tmp = NULL; STACK_OF(CONF_VALUE) *origextlist = extlist, *tmpextlist; if (akeyid->keyid) { tmp = i2s_ASN1_OCTET_STRING(NULL, akeyid->keyid); if (tmp == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); return NULL; } if (!X509V3_add_value((akeyid->issuer || akeyid->serial) ? "keyid" : NULL, tmp, &extlist)) { OPENSSL_free(tmp); ERR_raise(ERR_LIB_X509V3, ERR_R_X509_LIB); goto err; } OPENSSL_free(tmp); } if (akeyid->issuer) { tmpextlist = i2v_GENERAL_NAMES(NULL, akeyid->issuer, extlist); if (tmpextlist == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_X509_LIB); goto err; } extlist = tmpextlist; } if (akeyid->serial) { tmp = i2s_ASN1_OCTET_STRING(NULL, akeyid->serial); if (tmp == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } if (!X509V3_add_value("serial", tmp, &extlist)) { OPENSSL_free(tmp); goto err; } OPENSSL_free(tmp); } return extlist; err: if (origextlist == NULL) sk_CONF_VALUE_pop_free(extlist, X509V3_conf_free); return NULL; } /*- * Three explicit tags may be given, where 'keyid' and 'issuer' may be combined: * 'none': do not add any authority key identifier. * 'keyid': use the issuer's subject keyid; the option 'always' means its is * an error if the issuer certificate doesn't have a subject key id. * 'issuer': use the issuer's cert issuer and serial number. The default is * to only use this if 'keyid' is not present. With the option 'always' * this is always included. */ static AUTHORITY_KEYID *v2i_AUTHORITY_KEYID(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *values) { char keyid = 0, issuer = 0; int i, n = sk_CONF_VALUE_num(values); CONF_VALUE *cnf; ASN1_OCTET_STRING *ikeyid = NULL; X509_NAME *isname = NULL; GENERAL_NAMES *gens = NULL; GENERAL_NAME *gen = NULL; ASN1_INTEGER *serial = NULL; X509_EXTENSION *ext; X509 *issuer_cert; int same_issuer, ss; AUTHORITY_KEYID *akeyid = AUTHORITY_KEYID_new(); if (akeyid == NULL) goto err; if (n == 1 && strcmp(sk_CONF_VALUE_value(values, 0)->name, "none") == 0) { return akeyid; } for (i = 0; i < n; i++) { cnf = sk_CONF_VALUE_value(values, i); if (cnf->value != NULL && strcmp(cnf->value, "always") != 0) { ERR_raise_data(ERR_LIB_X509V3, X509V3_R_UNKNOWN_OPTION, "name=%s option=%s", cnf->name, cnf->value); goto err; } if (strcmp(cnf->name, "keyid") == 0 && keyid == 0) { keyid = 1; if (cnf->value != NULL) keyid = 2; } else if (strcmp(cnf->name, "issuer") == 0 && issuer == 0) { issuer = 1; if (cnf->value != NULL) issuer = 2; } else if (strcmp(cnf->name, "none") == 0 || strcmp(cnf->name, "keyid") == 0 || strcmp(cnf->name, "issuer") == 0) { ERR_raise_data(ERR_LIB_X509V3, X509V3_R_BAD_VALUE, "name=%s", cnf->name); goto err; } else { ERR_raise_data(ERR_LIB_X509V3, X509V3_R_UNKNOWN_VALUE, "name=%s", cnf->name); goto err; } } if (ctx != NULL && (ctx->flags & X509V3_CTX_TEST) != 0) return akeyid; if (ctx == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_NULL_PARAMETER); goto err; } if ((issuer_cert = ctx->issuer_cert) == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_ISSUER_CERTIFICATE); goto err; } same_issuer = ctx->subject_cert == ctx->issuer_cert; ERR_set_mark(); if (ctx->issuer_pkey != NULL) ss = X509_check_private_key(ctx->subject_cert, ctx->issuer_pkey); else ss = same_issuer; ERR_pop_to_mark(); /* unless forced with "always", AKID is suppressed for self-signed certs */ if (keyid == 2 || (keyid == 1 && !ss)) { /* * prefer any pre-existing subject key identifier of the issuer cert * except issuer cert is same as subject cert and is not self-signed */ i = X509_get_ext_by_NID(issuer_cert, NID_subject_key_identifier, -1); if (i >= 0 && (ext = X509_get_ext(issuer_cert, i)) != NULL && !(same_issuer && !ss)) { ikeyid = X509V3_EXT_d2i(ext); if (ASN1_STRING_length(ikeyid) == 0) /* indicating "none" */ { ASN1_OCTET_STRING_free(ikeyid); ikeyid = NULL; } } if (ikeyid == NULL && same_issuer && ctx->issuer_pkey != NULL) { /* generate fallback AKID, emulating s2i_skey_id(..., "hash") */ X509_PUBKEY *pubkey = NULL; if (X509_PUBKEY_set(&pubkey, ctx->issuer_pkey)) ikeyid = ossl_x509_pubkey_hash(pubkey); X509_PUBKEY_free(pubkey); } if (keyid == 2 && ikeyid == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_UNABLE_TO_GET_ISSUER_KEYID); goto err; } } if (issuer == 2 || (issuer == 1 && !ss && ikeyid == NULL)) { isname = X509_NAME_dup(X509_get_issuer_name(issuer_cert)); serial = ASN1_INTEGER_dup(X509_get0_serialNumber(issuer_cert)); if (isname == NULL || serial == NULL) { ERR_raise(ERR_LIB_X509V3, X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS); goto err; } } if (isname != NULL) { if ((gens = sk_GENERAL_NAME_new_null()) == NULL || (gen = GENERAL_NAME_new()) == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); goto err; } if (!sk_GENERAL_NAME_push(gens, gen)) { ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); goto err; } gen->type = GEN_DIRNAME; gen->d.dirn = isname; } akeyid->issuer = gens; gen = NULL; gens = NULL; akeyid->serial = serial; akeyid->keyid = ikeyid; return akeyid; err: sk_GENERAL_NAME_free(gens); GENERAL_NAME_free(gen); X509_NAME_free(isname); ASN1_INTEGER_free(serial); ASN1_OCTET_STRING_free(ikeyid); AUTHORITY_KEYID_free(akeyid); return NULL; }