file_path
stringlengths
19
75
code
stringlengths
279
1.37M
./openssl/crypto/cms/cms_ec.c
/* * Copyright 2006-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <assert.h> #include <limits.h> #include <openssl/cms.h> #include <openssl/err.h> #include <openssl/decoder.h> #include "internal/sizes.h" #include "crypto/asn1.h" #include "crypto/evp.h" #include "cms_local.h" static EVP_PKEY *pkey_type2param(int ptype, const void *pval, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *pctx = NULL; OSSL_DECODER_CTX *ctx = NULL; if (ptype == V_ASN1_SEQUENCE) { const ASN1_STRING *pstr = pval; const unsigned char *pm = pstr->data; size_t pmlen = (size_t)pstr->length; int selection = OSSL_KEYMGMT_SELECT_ALL_PARAMETERS; ctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", NULL, "EC", selection, libctx, propq); if (ctx == NULL) goto err; if (!OSSL_DECODER_from_data(ctx, &pm, &pmlen)) { ERR_raise(ERR_LIB_CMS, CMS_R_DECODE_ERROR); goto err; } OSSL_DECODER_CTX_free(ctx); return pkey; } else if (ptype == V_ASN1_OBJECT) { const ASN1_OBJECT *poid = pval; char groupname[OSSL_MAX_NAME_SIZE]; /* type == V_ASN1_OBJECT => the parameters are given by an asn1 OID */ pctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", propq); if (pctx == NULL || EVP_PKEY_paramgen_init(pctx) <= 0) goto err; if (OBJ_obj2txt(groupname, sizeof(groupname), poid, 0) <= 0 || EVP_PKEY_CTX_set_group_name(pctx, groupname) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_DECODE_ERROR); goto err; } if (EVP_PKEY_paramgen(pctx, &pkey) <= 0) goto err; EVP_PKEY_CTX_free(pctx); return pkey; } ERR_raise(ERR_LIB_CMS, CMS_R_DECODE_ERROR); return NULL; err: EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(pctx); OSSL_DECODER_CTX_free(ctx); return NULL; } static int ecdh_cms_set_peerkey(EVP_PKEY_CTX *pctx, X509_ALGOR *alg, ASN1_BIT_STRING *pubkey) { const ASN1_OBJECT *aoid; int atype; const void *aval; int rv = 0; EVP_PKEY *pkpeer = NULL; const unsigned char *p; int plen; X509_ALGOR_get0(&aoid, &atype, &aval, alg); if (OBJ_obj2nid(aoid) != NID_X9_62_id_ecPublicKey) goto err; /* If absent parameters get group from main key */ if (atype == V_ASN1_UNDEF || atype == V_ASN1_NULL) { EVP_PKEY *pk; pk = EVP_PKEY_CTX_get0_pkey(pctx); if (pk == NULL) goto err; pkpeer = EVP_PKEY_new(); if (pkpeer == NULL) goto err; if (!EVP_PKEY_copy_parameters(pkpeer, pk)) goto err; } else { pkpeer = pkey_type2param(atype, aval, EVP_PKEY_CTX_get0_libctx(pctx), EVP_PKEY_CTX_get0_propq(pctx)); if (pkpeer == NULL) goto err; } /* We have parameters now set public key */ plen = ASN1_STRING_length(pubkey); p = ASN1_STRING_get0_data(pubkey); if (p == NULL || plen == 0) goto err; if (!EVP_PKEY_set1_encoded_public_key(pkpeer, p, plen)) goto err; if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0) rv = 1; err: EVP_PKEY_free(pkpeer); return rv; } /* Set KDF parameters based on KDF NID */ static int ecdh_cms_set_kdf_param(EVP_PKEY_CTX *pctx, int eckdf_nid) { int kdf_nid, kdfmd_nid, cofactor; const EVP_MD *kdf_md; if (eckdf_nid == NID_undef) return 0; /* Lookup KDF type, cofactor mode and digest */ if (!OBJ_find_sigid_algs(eckdf_nid, &kdfmd_nid, &kdf_nid)) return 0; if (kdf_nid == NID_dh_std_kdf) cofactor = 0; else if (kdf_nid == NID_dh_cofactor_kdf) cofactor = 1; else return 0; if (EVP_PKEY_CTX_set_ecdh_cofactor_mode(pctx, cofactor) <= 0) return 0; if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, EVP_PKEY_ECDH_KDF_X9_63) <= 0) return 0; kdf_md = EVP_get_digestbynid(kdfmd_nid); if (!kdf_md) return 0; if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0) return 0; return 1; } static int ecdh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri) { int rv = 0; X509_ALGOR *alg, *kekalg = NULL; ASN1_OCTET_STRING *ukm; const unsigned char *p; unsigned char *der = NULL; int plen, keylen; EVP_CIPHER *kekcipher = NULL; EVP_CIPHER_CTX *kekctx; char name[OSSL_MAX_NAME_SIZE]; if (!CMS_RecipientInfo_kari_get0_alg(ri, &alg, &ukm)) return 0; if (!ecdh_cms_set_kdf_param(pctx, OBJ_obj2nid(alg->algorithm))) { ERR_raise(ERR_LIB_CMS, CMS_R_KDF_PARAMETER_ERROR); return 0; } if (alg->parameter->type != V_ASN1_SEQUENCE) return 0; p = alg->parameter->value.sequence->data; plen = alg->parameter->value.sequence->length; kekalg = d2i_X509_ALGOR(NULL, &p, plen); if (kekalg == NULL) goto err; kekctx = CMS_RecipientInfo_kari_get0_ctx(ri); if (kekctx == NULL) goto err; OBJ_obj2txt(name, sizeof(name), kekalg->algorithm, 0); kekcipher = EVP_CIPHER_fetch(pctx->libctx, name, pctx->propquery); if (kekcipher == NULL || EVP_CIPHER_get_mode(kekcipher) != EVP_CIPH_WRAP_MODE) goto err; if (!EVP_EncryptInit_ex(kekctx, kekcipher, NULL, NULL, NULL)) goto err; if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0) goto err; keylen = EVP_CIPHER_CTX_get_key_length(kekctx); if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0) goto err; plen = CMS_SharedInfo_encode(&der, kekalg, ukm, keylen); if (plen <= 0) goto err; if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, der, plen) <= 0) goto err; der = NULL; rv = 1; err: EVP_CIPHER_free(kekcipher); X509_ALGOR_free(kekalg); OPENSSL_free(der); return rv; } static int ecdh_cms_decrypt(CMS_RecipientInfo *ri) { EVP_PKEY_CTX *pctx; pctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (pctx == NULL) return 0; /* See if we need to set peer key */ if (!EVP_PKEY_CTX_get0_peerkey(pctx)) { X509_ALGOR *alg; ASN1_BIT_STRING *pubkey; if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &alg, &pubkey, NULL, NULL, NULL)) return 0; if (alg == NULL || pubkey == NULL) return 0; if (!ecdh_cms_set_peerkey(pctx, alg, pubkey)) { ERR_raise(ERR_LIB_CMS, CMS_R_PEER_KEY_ERROR); return 0; } } /* Set ECDH derivation parameters and initialise unwrap context */ if (!ecdh_cms_set_shared_info(pctx, ri)) { ERR_raise(ERR_LIB_CMS, CMS_R_SHARED_INFO_ERROR); return 0; } return 1; } static int ecdh_cms_encrypt(CMS_RecipientInfo *ri) { EVP_PKEY_CTX *pctx; EVP_PKEY *pkey; EVP_CIPHER_CTX *ctx; int keylen; X509_ALGOR *talg, *wrap_alg = NULL; const ASN1_OBJECT *aoid; ASN1_BIT_STRING *pubkey; ASN1_STRING *wrap_str; ASN1_OCTET_STRING *ukm; unsigned char *penc = NULL; int penclen; int rv = 0; int ecdh_nid, kdf_type, kdf_nid, wrap_nid; const EVP_MD *kdf_md; pctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (pctx == NULL) return 0; /* Get ephemeral key */ pkey = EVP_PKEY_CTX_get0_pkey(pctx); if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey, NULL, NULL, NULL)) goto err; X509_ALGOR_get0(&aoid, NULL, NULL, talg); /* Is everything uninitialised? */ if (aoid == OBJ_nid2obj(NID_undef)) { /* Set the key */ size_t enckeylen; enckeylen = EVP_PKEY_get1_encoded_public_key(pkey, &penc); if (enckeylen > INT_MAX || enckeylen == 0) goto err; ASN1_STRING_set0(pubkey, penc, (int)enckeylen); ossl_asn1_string_set_bits_left(pubkey, 0); penc = NULL; (void)X509_ALGOR_set0(talg, OBJ_nid2obj(NID_X9_62_id_ecPublicKey), V_ASN1_UNDEF, NULL); /* cannot fail */ } /* See if custom parameters set */ kdf_type = EVP_PKEY_CTX_get_ecdh_kdf_type(pctx); if (kdf_type <= 0) goto err; if (EVP_PKEY_CTX_get_ecdh_kdf_md(pctx, &kdf_md) <= 0) goto err; ecdh_nid = EVP_PKEY_CTX_get_ecdh_cofactor_mode(pctx); if (ecdh_nid < 0) goto err; else if (ecdh_nid == 0) ecdh_nid = NID_dh_std_kdf; else if (ecdh_nid == 1) ecdh_nid = NID_dh_cofactor_kdf; if (kdf_type == EVP_PKEY_ECDH_KDF_NONE) { kdf_type = EVP_PKEY_ECDH_KDF_X9_63; if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, kdf_type) <= 0) goto err; } else /* Unknown KDF */ goto err; if (kdf_md == NULL) { /* Fixme later for better MD */ kdf_md = EVP_sha1(); if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0) goto err; } if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm)) goto err; /* Lookup NID for KDF+cofactor+digest */ if (!OBJ_find_sigid_by_algs(&kdf_nid, EVP_MD_get_type(kdf_md), ecdh_nid)) goto err; /* Get wrap NID */ ctx = CMS_RecipientInfo_kari_get0_ctx(ri); wrap_nid = EVP_CIPHER_CTX_get_type(ctx); keylen = EVP_CIPHER_CTX_get_key_length(ctx); /* Package wrap algorithm in an AlgorithmIdentifier */ wrap_alg = X509_ALGOR_new(); if (wrap_alg == NULL) goto err; wrap_alg->algorithm = OBJ_nid2obj(wrap_nid); wrap_alg->parameter = ASN1_TYPE_new(); if (wrap_alg->parameter == NULL) goto err; if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0) goto err; if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) { ASN1_TYPE_free(wrap_alg->parameter); wrap_alg->parameter = NULL; } if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0) goto err; penclen = CMS_SharedInfo_encode(&penc, wrap_alg, ukm, keylen); if (penclen <= 0) goto err; if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, penc, penclen) <= 0) goto err; penc = NULL; /* * Now need to wrap encoding of wrap AlgorithmIdentifier into parameter * of another AlgorithmIdentifier. */ penclen = i2d_X509_ALGOR(wrap_alg, &penc); if (penclen <= 0) goto err; wrap_str = ASN1_STRING_new(); if (wrap_str == NULL) goto err; ASN1_STRING_set0(wrap_str, penc, penclen); penc = NULL; rv = X509_ALGOR_set0(talg, OBJ_nid2obj(kdf_nid), V_ASN1_SEQUENCE, wrap_str); if (!rv) ASN1_STRING_free(wrap_str); err: OPENSSL_free(penc); X509_ALGOR_free(wrap_alg); return rv; } int ossl_cms_ecdh_envelope(CMS_RecipientInfo *ri, int decrypt) { assert(decrypt == 0 || decrypt == 1); if (decrypt == 1) return ecdh_cms_decrypt(ri); if (decrypt == 0) return ecdh_cms_encrypt(ri); ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); return 0; }
./openssl/crypto/cms/cms_local.h
/* * Copyright 2008-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_CRYPTO_CMS_LOCAL_H # define OSSL_CRYPTO_CMS_LOCAL_H # include <openssl/x509.h> /* * Cryptographic message syntax (CMS) structures: taken from RFC3852 */ /* Forward references */ typedef struct CMS_IssuerAndSerialNumber_st CMS_IssuerAndSerialNumber; typedef struct CMS_EncapsulatedContentInfo_st CMS_EncapsulatedContentInfo; typedef struct CMS_SignerIdentifier_st CMS_SignerIdentifier; typedef struct CMS_OtherRevocationInfoFormat_st CMS_OtherRevocationInfoFormat; typedef struct CMS_OriginatorInfo_st CMS_OriginatorInfo; typedef struct CMS_EncryptedContentInfo_st CMS_EncryptedContentInfo; typedef struct CMS_DigestedData_st CMS_DigestedData; typedef struct CMS_EncryptedData_st CMS_EncryptedData; typedef struct CMS_AuthenticatedData_st CMS_AuthenticatedData; typedef struct CMS_AuthEnvelopedData_st CMS_AuthEnvelopedData; typedef struct CMS_CompressedData_st CMS_CompressedData; typedef struct CMS_OtherCertificateFormat_st CMS_OtherCertificateFormat; typedef struct CMS_KeyTransRecipientInfo_st CMS_KeyTransRecipientInfo; typedef struct CMS_OriginatorPublicKey_st CMS_OriginatorPublicKey; typedef struct CMS_OriginatorIdentifierOrKey_st CMS_OriginatorIdentifierOrKey; typedef struct CMS_KeyAgreeRecipientInfo_st CMS_KeyAgreeRecipientInfo; typedef struct CMS_RecipientKeyIdentifier_st CMS_RecipientKeyIdentifier; typedef struct CMS_KeyAgreeRecipientIdentifier_st CMS_KeyAgreeRecipientIdentifier; typedef struct CMS_KEKIdentifier_st CMS_KEKIdentifier; typedef struct CMS_KEKRecipientInfo_st CMS_KEKRecipientInfo; typedef struct CMS_PasswordRecipientInfo_st CMS_PasswordRecipientInfo; typedef struct CMS_OtherRecipientInfo_st CMS_OtherRecipientInfo; typedef struct CMS_ReceiptsFrom_st CMS_ReceiptsFrom; typedef struct CMS_CTX_st CMS_CTX; struct CMS_CTX_st { OSSL_LIB_CTX *libctx; char *propq; }; struct CMS_ContentInfo_st { ASN1_OBJECT *contentType; union { ASN1_OCTET_STRING *data; CMS_SignedData *signedData; CMS_EnvelopedData *envelopedData; CMS_DigestedData *digestedData; CMS_EncryptedData *encryptedData; CMS_AuthEnvelopedData *authEnvelopedData; CMS_AuthenticatedData *authenticatedData; CMS_CompressedData *compressedData; ASN1_TYPE *other; /* Other types ... */ void *otherData; } d; CMS_CTX ctx; }; DEFINE_STACK_OF(CMS_CertificateChoices) struct CMS_SignedData_st { int32_t version; STACK_OF(X509_ALGOR) *digestAlgorithms; CMS_EncapsulatedContentInfo *encapContentInfo; STACK_OF(CMS_CertificateChoices) *certificates; STACK_OF(CMS_RevocationInfoChoice) *crls; STACK_OF(CMS_SignerInfo) *signerInfos; }; struct CMS_EncapsulatedContentInfo_st { ASN1_OBJECT *eContentType; ASN1_OCTET_STRING *eContent; /* Set to 1 if incomplete structure only part set up */ int partial; }; struct CMS_SignerInfo_st { int32_t version; CMS_SignerIdentifier *sid; X509_ALGOR *digestAlgorithm; STACK_OF(X509_ATTRIBUTE) *signedAttrs; X509_ALGOR *signatureAlgorithm; ASN1_OCTET_STRING *signature; STACK_OF(X509_ATTRIBUTE) *unsignedAttrs; /* Signing certificate and key */ X509 *signer; EVP_PKEY *pkey; /* Digest and public key context for alternative parameters */ EVP_MD_CTX *mctx; EVP_PKEY_CTX *pctx; const CMS_CTX *cms_ctx; }; struct CMS_SignerIdentifier_st { int type; union { CMS_IssuerAndSerialNumber *issuerAndSerialNumber; ASN1_OCTET_STRING *subjectKeyIdentifier; } d; }; struct CMS_EnvelopedData_st { int32_t version; CMS_OriginatorInfo *originatorInfo; STACK_OF(CMS_RecipientInfo) *recipientInfos; CMS_EncryptedContentInfo *encryptedContentInfo; STACK_OF(X509_ATTRIBUTE) *unprotectedAttrs; }; struct CMS_OriginatorInfo_st { STACK_OF(CMS_CertificateChoices) *certificates; STACK_OF(CMS_RevocationInfoChoice) *crls; }; struct CMS_EncryptedContentInfo_st { ASN1_OBJECT *contentType; X509_ALGOR *contentEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedContent; /* Content encryption algorithm, key and tag */ const EVP_CIPHER *cipher; unsigned char *key; size_t keylen; unsigned char *tag; size_t taglen; /* Set to 1 if we are debugging decrypt and don't fake keys for MMA */ int debug; /* Set to 1 if we have no cert and need extra safety measures for MMA */ int havenocert; }; struct CMS_RecipientInfo_st { int type; union { CMS_KeyTransRecipientInfo *ktri; CMS_KeyAgreeRecipientInfo *kari; CMS_KEKRecipientInfo *kekri; CMS_PasswordRecipientInfo *pwri; CMS_OtherRecipientInfo *ori; } d; }; typedef CMS_SignerIdentifier CMS_RecipientIdentifier; struct CMS_KeyTransRecipientInfo_st { int32_t version; CMS_RecipientIdentifier *rid; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; /* Recipient Key and cert */ X509 *recip; EVP_PKEY *pkey; /* Public key context for this operation */ EVP_PKEY_CTX *pctx; const CMS_CTX *cms_ctx; }; struct CMS_KeyAgreeRecipientInfo_st { int32_t version; CMS_OriginatorIdentifierOrKey *originator; ASN1_OCTET_STRING *ukm; X509_ALGOR *keyEncryptionAlgorithm; STACK_OF(CMS_RecipientEncryptedKey) *recipientEncryptedKeys; /* Public key context associated with current operation */ EVP_PKEY_CTX *pctx; /* Cipher context for CEK wrapping */ EVP_CIPHER_CTX *ctx; const CMS_CTX *cms_ctx; }; struct CMS_OriginatorIdentifierOrKey_st { int type; union { CMS_IssuerAndSerialNumber *issuerAndSerialNumber; ASN1_OCTET_STRING *subjectKeyIdentifier; CMS_OriginatorPublicKey *originatorKey; } d; }; struct CMS_OriginatorPublicKey_st { X509_ALGOR *algorithm; ASN1_BIT_STRING *publicKey; }; struct CMS_RecipientEncryptedKey_st { CMS_KeyAgreeRecipientIdentifier *rid; ASN1_OCTET_STRING *encryptedKey; /* Public key associated with this recipient */ EVP_PKEY *pkey; }; struct CMS_KeyAgreeRecipientIdentifier_st { int type; union { CMS_IssuerAndSerialNumber *issuerAndSerialNumber; CMS_RecipientKeyIdentifier *rKeyId; } d; }; struct CMS_RecipientKeyIdentifier_st { ASN1_OCTET_STRING *subjectKeyIdentifier; ASN1_GENERALIZEDTIME *date; CMS_OtherKeyAttribute *other; }; struct CMS_KEKRecipientInfo_st { int32_t version; CMS_KEKIdentifier *kekid; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; /* Extra info: symmetric key to use */ unsigned char *key; size_t keylen; const CMS_CTX *cms_ctx; }; struct CMS_KEKIdentifier_st { ASN1_OCTET_STRING *keyIdentifier; ASN1_GENERALIZEDTIME *date; CMS_OtherKeyAttribute *other; }; struct CMS_PasswordRecipientInfo_st { int32_t version; X509_ALGOR *keyDerivationAlgorithm; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; /* Extra info: password to use */ unsigned char *pass; size_t passlen; const CMS_CTX *cms_ctx; }; struct CMS_OtherRecipientInfo_st { ASN1_OBJECT *oriType; ASN1_TYPE *oriValue; }; struct CMS_DigestedData_st { int32_t version; X509_ALGOR *digestAlgorithm; CMS_EncapsulatedContentInfo *encapContentInfo; ASN1_OCTET_STRING *digest; }; struct CMS_EncryptedData_st { int32_t version; CMS_EncryptedContentInfo *encryptedContentInfo; STACK_OF(X509_ATTRIBUTE) *unprotectedAttrs; }; struct CMS_AuthenticatedData_st { int32_t version; CMS_OriginatorInfo *originatorInfo; STACK_OF(CMS_RecipientInfo) *recipientInfos; X509_ALGOR *macAlgorithm; X509_ALGOR *digestAlgorithm; CMS_EncapsulatedContentInfo *encapContentInfo; STACK_OF(X509_ATTRIBUTE) *authAttrs; ASN1_OCTET_STRING *mac; STACK_OF(X509_ATTRIBUTE) *unauthAttrs; }; struct CMS_AuthEnvelopedData_st { int32_t version; CMS_OriginatorInfo *originatorInfo; STACK_OF(CMS_RecipientInfo) *recipientInfos; CMS_EncryptedContentInfo *authEncryptedContentInfo; STACK_OF(X509_ATTRIBUTE) *authAttrs; ASN1_OCTET_STRING *mac; STACK_OF(X509_ATTRIBUTE) *unauthAttrs; }; struct CMS_CompressedData_st { int32_t version; X509_ALGOR *compressionAlgorithm; STACK_OF(CMS_RecipientInfo) *recipientInfos; CMS_EncapsulatedContentInfo *encapContentInfo; }; struct CMS_RevocationInfoChoice_st { int type; union { X509_CRL *crl; CMS_OtherRevocationInfoFormat *other; } d; }; # define CMS_REVCHOICE_CRL 0 # define CMS_REVCHOICE_OTHER 1 struct CMS_OtherRevocationInfoFormat_st { ASN1_OBJECT *otherRevInfoFormat; ASN1_TYPE *otherRevInfo; }; struct CMS_CertificateChoices { int type; union { X509 *certificate; ASN1_STRING *extendedCertificate; /* Obsolete */ ASN1_STRING *v1AttrCert; /* Left encoded for now */ ASN1_STRING *v2AttrCert; /* Left encoded for now */ CMS_OtherCertificateFormat *other; } d; }; # define CMS_CERTCHOICE_CERT 0 # define CMS_CERTCHOICE_EXCERT 1 # define CMS_CERTCHOICE_V1ACERT 2 # define CMS_CERTCHOICE_V2ACERT 3 # define CMS_CERTCHOICE_OTHER 4 struct CMS_OtherCertificateFormat_st { ASN1_OBJECT *otherCertFormat; ASN1_TYPE *otherCert; }; /* * This is also defined in pkcs7.h but we duplicate it to allow the CMS code * to be independent of PKCS#7 */ struct CMS_IssuerAndSerialNumber_st { X509_NAME *issuer; ASN1_INTEGER *serialNumber; }; struct CMS_OtherKeyAttribute_st { ASN1_OBJECT *keyAttrId; ASN1_TYPE *keyAttr; }; /* ESS structures */ struct CMS_ReceiptRequest_st { ASN1_OCTET_STRING *signedContentIdentifier; CMS_ReceiptsFrom *receiptsFrom; STACK_OF(GENERAL_NAMES) *receiptsTo; }; struct CMS_ReceiptsFrom_st { int type; union { int32_t allOrFirstTier; STACK_OF(GENERAL_NAMES) *receiptList; } d; }; struct CMS_Receipt_st { int32_t version; ASN1_OBJECT *contentType; ASN1_OCTET_STRING *signedContentIdentifier; ASN1_OCTET_STRING *originatorSignatureValue; }; DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) DECLARE_ASN1_ITEM(CMS_SignerInfo) DECLARE_ASN1_ITEM(CMS_IssuerAndSerialNumber) DECLARE_ASN1_ITEM(CMS_Attributes_Sign) DECLARE_ASN1_ITEM(CMS_Attributes_Verify) DECLARE_ASN1_ITEM(CMS_RecipientInfo) DECLARE_ASN1_ITEM(CMS_PasswordRecipientInfo) DECLARE_ASN1_ALLOC_FUNCTIONS(CMS_IssuerAndSerialNumber) # define CMS_SIGNERINFO_ISSUER_SERIAL 0 # define CMS_SIGNERINFO_KEYIDENTIFIER 1 # define CMS_RECIPINFO_ISSUER_SERIAL 0 # define CMS_RECIPINFO_KEYIDENTIFIER 1 # define CMS_REK_ISSUER_SERIAL 0 # define CMS_REK_KEYIDENTIFIER 1 # define CMS_OIK_ISSUER_SERIAL 0 # define CMS_OIK_KEYIDENTIFIER 1 # define CMS_OIK_PUBKEY 2 BIO *ossl_cms_content_bio(CMS_ContentInfo *cms); const CMS_CTX *ossl_cms_get0_cmsctx(const CMS_ContentInfo *cms); OSSL_LIB_CTX *ossl_cms_ctx_get0_libctx(const CMS_CTX *ctx); const char *ossl_cms_ctx_get0_propq(const CMS_CTX *ctx); void ossl_cms_resolve_libctx(CMS_ContentInfo *ci); CMS_ContentInfo *ossl_cms_Data_create(OSSL_LIB_CTX *ctx, const char *propq); int ossl_cms_DataFinal(CMS_ContentInfo *cms, BIO *cmsbio, const unsigned char *precomp_md, unsigned int precomp_mdlen); CMS_ContentInfo *ossl_cms_DigestedData_create(const EVP_MD *md, OSSL_LIB_CTX *libctx, const char *propq); BIO *ossl_cms_DigestedData_init_bio(const CMS_ContentInfo *cms); int ossl_cms_DigestedData_do_final(const CMS_ContentInfo *cms, BIO *chain, int verify); BIO *ossl_cms_SignedData_init_bio(CMS_ContentInfo *cms); int ossl_cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain, const unsigned char *precomp_md, unsigned int precomp_mdlen); int ossl_cms_set1_SignerIdentifier(CMS_SignerIdentifier *sid, X509 *cert, int type, const CMS_CTX *ctx); int ossl_cms_SignerIdentifier_get0_signer_id(CMS_SignerIdentifier *sid, ASN1_OCTET_STRING **keyid, X509_NAME **issuer, ASN1_INTEGER **sno); int ossl_cms_SignerIdentifier_cert_cmp(CMS_SignerIdentifier *sid, X509 *cert); CMS_ContentInfo *ossl_cms_CompressedData_create(int comp_nid, OSSL_LIB_CTX *libctx, const char *propq); BIO *ossl_cms_CompressedData_init_bio(const CMS_ContentInfo *cms); BIO *ossl_cms_DigestAlgorithm_init_bio(X509_ALGOR *digestAlgorithm, const CMS_CTX *ctx); int ossl_cms_DigestAlgorithm_find_ctx(EVP_MD_CTX *mctx, BIO *chain, X509_ALGOR *mdalg); int ossl_cms_ias_cert_cmp(CMS_IssuerAndSerialNumber *ias, X509 *cert); int ossl_cms_keyid_cert_cmp(ASN1_OCTET_STRING *keyid, X509 *cert); int ossl_cms_set1_ias(CMS_IssuerAndSerialNumber **pias, X509 *cert); int ossl_cms_set1_keyid(ASN1_OCTET_STRING **pkeyid, X509 *cert); BIO *ossl_cms_EncryptedContent_init_bio(CMS_EncryptedContentInfo *ec, const CMS_CTX *ctx); BIO *ossl_cms_EncryptedData_init_bio(const CMS_ContentInfo *cms); int ossl_cms_EncryptedContent_init(CMS_EncryptedContentInfo *ec, const EVP_CIPHER *cipher, const unsigned char *key, size_t keylen, const CMS_CTX *ctx); int ossl_cms_Receipt_verify(CMS_ContentInfo *cms, CMS_ContentInfo *req_cms); int ossl_cms_msgSigDigest_add1(CMS_SignerInfo *dest, CMS_SignerInfo *src); ASN1_OCTET_STRING *ossl_cms_encode_Receipt(CMS_SignerInfo *si); BIO *ossl_cms_EnvelopedData_init_bio(CMS_ContentInfo *cms); int ossl_cms_EnvelopedData_final(CMS_ContentInfo *cms, BIO *chain); BIO *ossl_cms_AuthEnvelopedData_init_bio(CMS_ContentInfo *cms); int ossl_cms_AuthEnvelopedData_final(CMS_ContentInfo *cms, BIO *cmsbio); void ossl_cms_env_enc_content_free(const CMS_ContentInfo *cinf); CMS_EnvelopedData *ossl_cms_get0_enveloped(CMS_ContentInfo *cms); CMS_AuthEnvelopedData *ossl_cms_get0_auth_enveloped(CMS_ContentInfo *cms); CMS_EncryptedContentInfo *ossl_cms_get0_env_enc_content(const CMS_ContentInfo *cms); /* RecipientInfo routines */ int ossl_cms_env_asn1_ctrl(CMS_RecipientInfo *ri, int cmd); int ossl_cms_pkey_get_ri_type(EVP_PKEY *pk); int ossl_cms_pkey_is_ri_type_supported(EVP_PKEY *pk, int ri_type); void ossl_cms_RecipientInfos_set_cmsctx(CMS_ContentInfo *cms); /* KARI routines */ int ossl_cms_RecipientInfo_kari_init(CMS_RecipientInfo *ri, X509 *recip, EVP_PKEY *recipPubKey, X509 *originator, EVP_PKEY *originatorPrivKey, unsigned int flags, const CMS_CTX *ctx); int ossl_cms_RecipientInfo_kari_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri); /* PWRI routines */ int ossl_cms_RecipientInfo_pwri_crypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri, int en_de); /* SignerInfo routines */ int ossl_cms_si_check_attributes(const CMS_SignerInfo *si); void ossl_cms_SignerInfos_set_cmsctx(CMS_ContentInfo *cms); /* ESS routines */ int ossl_cms_check_signing_certs(const CMS_SignerInfo *si, const STACK_OF(X509) *chain); int ossl_cms_dh_envelope(CMS_RecipientInfo *ri, int decrypt); int ossl_cms_ecdh_envelope(CMS_RecipientInfo *ri, int decrypt); int ossl_cms_rsa_envelope(CMS_RecipientInfo *ri, int decrypt); int ossl_cms_rsa_sign(CMS_SignerInfo *si, int verify); DECLARE_ASN1_ITEM(CMS_CertificateChoices) DECLARE_ASN1_ITEM(CMS_DigestedData) DECLARE_ASN1_ITEM(CMS_EncryptedData) DECLARE_ASN1_ITEM(CMS_EnvelopedData) DECLARE_ASN1_ITEM(CMS_AuthEnvelopedData) DECLARE_ASN1_ITEM(CMS_KEKRecipientInfo) DECLARE_ASN1_ITEM(CMS_KeyAgreeRecipientInfo) DECLARE_ASN1_ITEM(CMS_KeyTransRecipientInfo) DECLARE_ASN1_ITEM(CMS_OriginatorPublicKey) DECLARE_ASN1_ITEM(CMS_OtherKeyAttribute) DECLARE_ASN1_ITEM(CMS_Receipt) DECLARE_ASN1_ITEM(CMS_ReceiptRequest) DECLARE_ASN1_ITEM(CMS_RecipientEncryptedKey) DECLARE_ASN1_ITEM(CMS_RecipientKeyIdentifier) DECLARE_ASN1_ITEM(CMS_RevocationInfoChoice) DECLARE_ASN1_ITEM(CMS_SignedData) DECLARE_ASN1_ITEM(CMS_CompressedData) #endif
./openssl/crypto/cms/cms_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/cmserr.h> #include "crypto/cmserr.h" #ifndef OPENSSL_NO_CMS # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA CMS_str_reasons[] = { {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ADD_SIGNER_ERROR), "add signer error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ATTRIBUTE_ERROR), "attribute error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_ALREADY_PRESENT), "certificate already present"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_HAS_NO_KEYID), "certificate has no keyid"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_VERIFY_ERROR), "certificate verify error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_AEAD_SET_TAG_ERROR), "cipher aead set tag error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_GET_TAG), "cipher get tag"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_INITIALISATION_ERROR), "cipher initialisation error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR), "cipher parameter initialisation error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CMS_DATAFINAL_ERROR), "cms datafinal error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CMS_LIB), "cms lib"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENTIDENTIFIER_MISMATCH), "contentidentifier mismatch"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_NOT_FOUND), "content not found"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_MISMATCH), "content type mismatch"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA), "content type not compressed data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA), "content type not enveloped data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA), "content type not signed data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_VERIFY_ERROR), "content verify error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CTRL_ERROR), "ctrl error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CTRL_FAILURE), "ctrl failure"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_DECODE_ERROR), "decode error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_DECRYPT_ERROR), "decrypt error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_GETTING_PUBLIC_KEY), "error getting public key"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE), "error reading messagedigest attribute"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_SETTING_KEY), "error setting key"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_SETTING_RECIPIENTINFO), "error setting recipientinfo"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ESS_SIGNING_CERTID_MISMATCH_ERROR), "ess signing certid mismatch error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_ENCRYPTED_KEY_LENGTH), "invalid encrypted key length"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER), "invalid key encryption parameter"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_KEY_LENGTH), "invalid key length"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_LABEL), "invalid label"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_OAEP_PARAMETERS), "invalid oaep parameters"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_KDF_PARAMETER_ERROR), "kdf parameter error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MD_BIO_INIT_ERROR), "md bio init error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH), "messagedigest attribute wrong length"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MESSAGEDIGEST_WRONG_LENGTH), "messagedigest wrong length"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_ERROR), "msgsigdigest error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE), "msgsigdigest verification failure"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_WRONG_LENGTH), "msgsigdigest wrong length"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NEED_ONE_SIGNER), "need one signer"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_A_SIGNED_RECEIPT), "not a signed receipt"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_ENCRYPTED_DATA), "not encrypted data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEK), "not kek"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEY_AGREEMENT), "not key agreement"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEY_TRANSPORT), "not key transport"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_PWRI), "not pwri"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE), "not supported for this key type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CIPHER), "no cipher"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CONTENT), "no content"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CONTENT_TYPE), "no content type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_DEFAULT_DIGEST), "no default digest"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_DIGEST_SET), "no digest set"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_KEY), "no key"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_KEY_OR_CERT), "no key or cert"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_DIGEST), "no matching digest"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_RECIPIENT), "no matching recipient"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_SIGNATURE), "no matching signature"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MSGSIGDIGEST), "no msgsigdigest"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PASSWORD), "no password"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PRIVATE_KEY), "no private key"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PUBLIC_KEY), "no public key"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_RECEIPT_REQUEST), "no receipt request"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_SIGNERS), "no signers"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_OPERATION_UNSUPPORTED), "operation unsupported"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_PEER_KEY_ERROR), "peer key error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), "private key does not match certificate"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_RECEIPT_DECODE_ERROR), "receipt decode error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_RECIPIENT_ERROR), "recipient error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SHARED_INFO_ERROR), "shared info error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SIGNER_CERTIFICATE_NOT_FOUND), "signer certificate not found"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SIGNFINAL_ERROR), "signfinal error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SMIME_TEXT_ERROR), "smime text error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_STORE_INIT_ERROR), "store init error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_COMPRESSED_DATA), "type not compressed data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_DATA), "type not data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_DIGESTED_DATA), "type not digested data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_ENCRYPTED_DATA), "type not encrypted data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_ENVELOPED_DATA), "type not enveloped data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNABLE_TO_FINALIZE_CONTEXT), "unable to finalize context"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_CIPHER), "unknown cipher"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_DIGEST_ALGORITHM), "unknown digest algorithm"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_ID), "unknown id"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM), "unsupported compression algorithm"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_CONTENT_ENCRYPTION_ALGORITHM), "unsupported content encryption algorithm"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_CONTENT_TYPE), "unsupported content type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_ENCRYPTION_TYPE), "unsupported encryption type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_KEK_ALGORITHM), "unsupported kek algorithm"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM), "unsupported key encryption algorithm"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_LABEL_SOURCE), "unsupported label source"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE), "unsupported recipientinfo type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_RECIPIENT_TYPE), "unsupported recipient type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_SIGNATURE_ALGORITHM), "unsupported signature algorithm"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_TYPE), "unsupported type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNWRAP_ERROR), "unwrap error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNWRAP_FAILURE), "unwrap failure"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_VERIFICATION_FAILURE), "verification failure"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_WRAP_ERROR), "wrap error"}, {0, NULL} }; # endif int ossl_err_load_CMS_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(CMS_str_reasons[0].error) == NULL) ERR_load_strings_const(CMS_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
./openssl/crypto/cms/cms_sd.c
/* * Copyright 2008-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 <openssl/asn1t.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/cms.h> #include <openssl/ess.h> #include "internal/sizes.h" #include "crypto/asn1.h" #include "crypto/evp.h" #include "crypto/ess.h" #include "crypto/x509.h" /* for ossl_x509_add_cert_new() */ #include "cms_local.h" /* CMS SignedData Utilities */ static CMS_SignedData *cms_get0_signed(CMS_ContentInfo *cms) { if (OBJ_obj2nid(cms->contentType) != NID_pkcs7_signed) { ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA); return NULL; } return cms->d.signedData; } static CMS_SignedData *cms_signed_data_init(CMS_ContentInfo *cms) { if (cms->d.other == NULL) { cms->d.signedData = M_ASN1_new_of(CMS_SignedData); if (!cms->d.signedData) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); return NULL; } cms->d.signedData->version = 1; cms->d.signedData->encapContentInfo->eContentType = OBJ_nid2obj(NID_pkcs7_data); cms->d.signedData->encapContentInfo->partial = 1; ASN1_OBJECT_free(cms->contentType); cms->contentType = OBJ_nid2obj(NID_pkcs7_signed); return cms->d.signedData; } return cms_get0_signed(cms); } /* Just initialise SignedData e.g. for certs only structure */ int CMS_SignedData_init(CMS_ContentInfo *cms) { if (cms_signed_data_init(cms)) return 1; else return 0; } /* Check structures and fixup version numbers (if necessary) */ static void cms_sd_set_version(CMS_SignedData *sd) { int i; CMS_CertificateChoices *cch; CMS_RevocationInfoChoice *rch; CMS_SignerInfo *si; for (i = 0; i < sk_CMS_CertificateChoices_num(sd->certificates); i++) { cch = sk_CMS_CertificateChoices_value(sd->certificates, i); if (cch->type == CMS_CERTCHOICE_OTHER) { if (sd->version < 5) sd->version = 5; } else if (cch->type == CMS_CERTCHOICE_V2ACERT) { if (sd->version < 4) sd->version = 4; } else if (cch->type == CMS_CERTCHOICE_V1ACERT) { if (sd->version < 3) sd->version = 3; } } for (i = 0; i < sk_CMS_RevocationInfoChoice_num(sd->crls); i++) { rch = sk_CMS_RevocationInfoChoice_value(sd->crls, i); if (rch->type == CMS_REVCHOICE_OTHER) { if (sd->version < 5) sd->version = 5; } } if ((OBJ_obj2nid(sd->encapContentInfo->eContentType) != NID_pkcs7_data) && (sd->version < 3)) sd->version = 3; for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) { si = sk_CMS_SignerInfo_value(sd->signerInfos, i); if (si->sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) { if (si->version < 3) si->version = 3; if (sd->version < 3) sd->version = 3; } else if (si->version < 1) { si->version = 1; } } if (sd->version < 1) sd->version = 1; } /* * RFC 5652 Section 11.1 Content Type * The content-type attribute within signed-data MUST * 1) be present if there are signed attributes * 2) match the content type in the signed-data, * 3) be a signed attribute. * 4) not have more than one copy of the attribute. * * Note that since the CMS_SignerInfo_sign() always adds the "signing time" * attribute, the content type attribute MUST be added also. * Assumptions: This assumes that the attribute does not already exist. */ static int cms_set_si_contentType_attr(CMS_ContentInfo *cms, CMS_SignerInfo *si) { ASN1_OBJECT *ctype = cms->d.signedData->encapContentInfo->eContentType; /* Add the contentType attribute */ return CMS_signed_add1_attr_by_NID(si, NID_pkcs9_contentType, V_ASN1_OBJECT, ctype, -1) > 0; } /* Copy an existing messageDigest value */ static int cms_copy_messageDigest(CMS_ContentInfo *cms, CMS_SignerInfo *si) { STACK_OF(CMS_SignerInfo) *sinfos; CMS_SignerInfo *sitmp; int i; sinfos = CMS_get0_SignerInfos(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { ASN1_OCTET_STRING *messageDigest; sitmp = sk_CMS_SignerInfo_value(sinfos, i); if (sitmp == si) continue; if (CMS_signed_get_attr_count(sitmp) < 0) continue; if (OBJ_cmp(si->digestAlgorithm->algorithm, sitmp->digestAlgorithm->algorithm)) continue; messageDigest = CMS_signed_get0_data_by_OBJ(sitmp, OBJ_nid2obj (NID_pkcs9_messageDigest), -3, V_ASN1_OCTET_STRING); if (!messageDigest) { ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE); return 0; } if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest, V_ASN1_OCTET_STRING, messageDigest, -1)) return 1; else return 0; } ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_DIGEST); return 0; } int ossl_cms_set1_SignerIdentifier(CMS_SignerIdentifier *sid, X509 *cert, int type, const CMS_CTX *ctx) { switch (type) { case CMS_SIGNERINFO_ISSUER_SERIAL: if (!ossl_cms_set1_ias(&sid->d.issuerAndSerialNumber, cert)) return 0; break; case CMS_SIGNERINFO_KEYIDENTIFIER: if (!ossl_cms_set1_keyid(&sid->d.subjectKeyIdentifier, cert)) return 0; break; default: ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_ID); return 0; } sid->type = type; return 1; } int ossl_cms_SignerIdentifier_get0_signer_id(CMS_SignerIdentifier *sid, ASN1_OCTET_STRING **keyid, X509_NAME **issuer, ASN1_INTEGER **sno) { if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL) { if (issuer) *issuer = sid->d.issuerAndSerialNumber->issuer; if (sno) *sno = sid->d.issuerAndSerialNumber->serialNumber; } else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) { if (keyid) *keyid = sid->d.subjectKeyIdentifier; } else { return 0; } return 1; } int ossl_cms_SignerIdentifier_cert_cmp(CMS_SignerIdentifier *sid, X509 *cert) { if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL) return ossl_cms_ias_cert_cmp(sid->d.issuerAndSerialNumber, cert); else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) return ossl_cms_keyid_cert_cmp(sid->d.subjectKeyIdentifier, cert); else return -1; } /* Method to map any, incl. provider-implemented PKEY types to OIDs */ /* (EC)DSA and all provider-delivered signatures implementation is the same */ static int cms_generic_sign(CMS_SignerInfo *si, int verify) { if (!ossl_assert(verify == 0 || verify == 1)) return -1; if (!verify) { EVP_PKEY *pkey = si->pkey; int snid, hnid, pknid = EVP_PKEY_get_id(pkey); X509_ALGOR *alg1, *alg2; CMS_SignerInfo_get0_algs(si, NULL, NULL, &alg1, &alg2); if (alg1 == NULL || alg1->algorithm == NULL) return -1; hnid = OBJ_obj2nid(alg1->algorithm); if (hnid == NID_undef) return -1; if (pknid <= 0) { /* check whether a provider registered a NID */ const char *typename = EVP_PKEY_get0_type_name(pkey); if (typename != NULL) pknid = OBJ_txt2nid(typename); } if (!OBJ_find_sigid_by_algs(&snid, hnid, pknid)) return -1; return X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, NULL); } return 1; } static int cms_sd_asn1_ctrl(CMS_SignerInfo *si, int cmd) { EVP_PKEY *pkey = si->pkey; int i; if (EVP_PKEY_is_a(pkey, "DSA") || EVP_PKEY_is_a(pkey, "EC")) return cms_generic_sign(si, cmd) > 0; else if (EVP_PKEY_is_a(pkey, "RSA") || EVP_PKEY_is_a(pkey, "RSA-PSS")) return ossl_cms_rsa_sign(si, cmd) > 0; /* Now give engines, providers, etc a chance to handle this */ if (pkey->ameth == NULL || pkey->ameth->pkey_ctrl == NULL) return cms_generic_sign(si, cmd) > 0; i = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_CMS_SIGN, cmd, si); if (i == -2) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); return 0; } if (i <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE); return 0; } return 1; } /* Add SigningCertificate signed attribute to the signer info. */ static int ossl_cms_add1_signing_cert(CMS_SignerInfo *si, const ESS_SIGNING_CERT *sc) { ASN1_STRING *seq = NULL; unsigned char *p, *pp = NULL; int ret, len = i2d_ESS_SIGNING_CERT(sc, NULL); if (len <= 0 || (pp = OPENSSL_malloc(len)) == NULL) return 0; p = pp; i2d_ESS_SIGNING_CERT(sc, &p); if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) { ASN1_STRING_free(seq); OPENSSL_free(pp); return 0; } OPENSSL_free(pp); ret = CMS_signed_add1_attr_by_NID(si, NID_id_smime_aa_signingCertificate, V_ASN1_SEQUENCE, seq, -1); ASN1_STRING_free(seq); return ret; } /* Add SigningCertificateV2 signed attribute to the signer info. */ static int ossl_cms_add1_signing_cert_v2(CMS_SignerInfo *si, const ESS_SIGNING_CERT_V2 *sc) { ASN1_STRING *seq = NULL; unsigned char *p, *pp = NULL; int ret, len = i2d_ESS_SIGNING_CERT_V2(sc, NULL); if (len <= 0 || (pp = OPENSSL_malloc(len)) == NULL) return 0; p = pp; i2d_ESS_SIGNING_CERT_V2(sc, &p); if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) { ASN1_STRING_free(seq); OPENSSL_free(pp); return 0; } OPENSSL_free(pp); ret = CMS_signed_add1_attr_by_NID(si, NID_id_smime_aa_signingCertificateV2, V_ASN1_SEQUENCE, seq, -1); ASN1_STRING_free(seq); return ret; } CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, X509 *signer, EVP_PKEY *pk, const EVP_MD *md, unsigned int flags) { CMS_SignedData *sd; CMS_SignerInfo *si = NULL; X509_ALGOR *alg; int i, type; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); if (!X509_check_private_key(signer, pk)) { ERR_raise(ERR_LIB_CMS, CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE); return NULL; } sd = cms_signed_data_init(cms); if (!sd) goto err; si = M_ASN1_new_of(CMS_SignerInfo); if (!si) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } /* Call for side-effect of computing hash and caching extensions */ X509_check_purpose(signer, -1, -1); X509_up_ref(signer); EVP_PKEY_up_ref(pk); si->cms_ctx = ctx; si->pkey = pk; si->signer = signer; si->mctx = EVP_MD_CTX_new(); si->pctx = NULL; if (si->mctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } if (flags & CMS_USE_KEYID) { si->version = 3; if (sd->version < 3) sd->version = 3; type = CMS_SIGNERINFO_KEYIDENTIFIER; } else { type = CMS_SIGNERINFO_ISSUER_SERIAL; si->version = 1; } if (!ossl_cms_set1_SignerIdentifier(si->sid, signer, type, ctx)) goto err; if (md == NULL) { int def_nid; if (EVP_PKEY_get_default_digest_nid(pk, &def_nid) <= 0) { ERR_raise_data(ERR_LIB_CMS, CMS_R_NO_DEFAULT_DIGEST, "pkey nid=%d", EVP_PKEY_get_id(pk)); goto err; } md = EVP_get_digestbynid(def_nid); if (md == NULL) { ERR_raise_data(ERR_LIB_CMS, CMS_R_NO_DEFAULT_DIGEST, "default md nid=%d", def_nid); goto err; } } X509_ALGOR_set_md(si->digestAlgorithm, md); /* See if digest is present in digestAlgorithms */ for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) { const ASN1_OBJECT *aoid; char name[OSSL_MAX_NAME_SIZE]; alg = sk_X509_ALGOR_value(sd->digestAlgorithms, i); X509_ALGOR_get0(&aoid, NULL, NULL, alg); OBJ_obj2txt(name, sizeof(name), aoid, 0); if (EVP_MD_is_a(md, name)) break; } if (i == sk_X509_ALGOR_num(sd->digestAlgorithms)) { if ((alg = X509_ALGOR_new()) == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } X509_ALGOR_set_md(alg, md); if (!sk_X509_ALGOR_push(sd->digestAlgorithms, alg)) { X509_ALGOR_free(alg); ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB); goto err; } } if (!(flags & CMS_KEY_PARAM) && !cms_sd_asn1_ctrl(si, 0)) { ERR_raise_data(ERR_LIB_CMS, CMS_R_UNSUPPORTED_SIGNATURE_ALGORITHM, "pkey nid=%d", EVP_PKEY_get_id(pk)); goto err; } if (!(flags & CMS_NOATTR)) { /* * Initialize signed attributes structure so other attributes * such as signing time etc are added later even if we add none here. */ if (!si->signedAttrs) { si->signedAttrs = sk_X509_ATTRIBUTE_new_null(); if (!si->signedAttrs) { ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB); goto err; } } if (!(flags & CMS_NOSMIMECAP)) { STACK_OF(X509_ALGOR) *smcap = NULL; i = CMS_add_standard_smimecap(&smcap); if (i) i = CMS_add_smimecap(si, smcap); sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free); if (!i) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } } if (flags & CMS_CADES) { ESS_SIGNING_CERT *sc = NULL; ESS_SIGNING_CERT_V2 *sc2 = NULL; int add_sc; if (md == NULL || EVP_MD_is_a(md, SN_sha1)) { if ((sc = OSSL_ESS_signing_cert_new_init(signer, NULL, 1)) == NULL) goto err; add_sc = ossl_cms_add1_signing_cert(si, sc); ESS_SIGNING_CERT_free(sc); } else { if ((sc2 = OSSL_ESS_signing_cert_v2_new_init(md, signer, NULL, 1)) == NULL) goto err; add_sc = ossl_cms_add1_signing_cert_v2(si, sc2); ESS_SIGNING_CERT_V2_free(sc2); } if (!add_sc) goto err; } if (flags & CMS_REUSE_DIGEST) { if (!cms_copy_messageDigest(cms, si)) goto err; if (!cms_set_si_contentType_attr(cms, si)) goto err; if (!(flags & (CMS_PARTIAL | CMS_KEY_PARAM)) && !CMS_SignerInfo_sign(si)) goto err; } } if (!(flags & CMS_NOCERTS)) { /* NB ignore -1 return for duplicate cert */ if (!CMS_add1_cert(cms, signer)) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } } if (flags & CMS_KEY_PARAM) { if (flags & CMS_NOATTR) { si->pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx), si->pkey, ossl_cms_ctx_get0_propq(ctx)); if (si->pctx == NULL) goto err; if (EVP_PKEY_sign_init(si->pctx) <= 0) goto err; if (EVP_PKEY_CTX_set_signature_md(si->pctx, md) <= 0) goto err; } else if (EVP_DigestSignInit_ex(si->mctx, &si->pctx, EVP_MD_get0_name(md), ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx), pk, NULL) <= 0) { goto err; } } if (sd->signerInfos == NULL) sd->signerInfos = sk_CMS_SignerInfo_new_null(); if (sd->signerInfos == NULL || !sk_CMS_SignerInfo_push(sd->signerInfos, si)) { ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB); goto err; } return si; err: M_ASN1_free_of(si, CMS_SignerInfo); return NULL; } void ossl_cms_SignerInfos_set_cmsctx(CMS_ContentInfo *cms) { int i; CMS_SignerInfo *si; STACK_OF(CMS_SignerInfo) *sinfos; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); ERR_set_mark(); sinfos = CMS_get0_SignerInfos(cms); ERR_pop_to_mark(); /* removes error in case sinfos == NULL */ for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (si != NULL) si->cms_ctx = ctx; } } static int cms_add1_signingTime(CMS_SignerInfo *si, ASN1_TIME *t) { ASN1_TIME *tt; int r = 0; if (t != NULL) tt = t; else tt = X509_gmtime_adj(NULL, 0); if (tt == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_X509_LIB); goto err; } if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_signingTime, tt->type, tt, -1) <= 0) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } r = 1; err: if (t == NULL) ASN1_TIME_free(tt); return r; } EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si) { return si->pctx; } EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si) { return si->mctx; } STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms) { CMS_SignedData *sd = cms_get0_signed(cms); return sd != NULL ? sd->signerInfos : NULL; } STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms) { STACK_OF(X509) *signers = NULL; STACK_OF(CMS_SignerInfo) *sinfos; CMS_SignerInfo *si; int i; sinfos = CMS_get0_SignerInfos(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (si->signer != NULL) { if (!ossl_x509_add_cert_new(&signers, si->signer, X509_ADD_FLAG_DEFAULT)) { sk_X509_free(signers); return NULL; } } } return signers; } void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer) { if (signer != NULL) { X509_up_ref(signer); EVP_PKEY_free(si->pkey); si->pkey = X509_get_pubkey(signer); } X509_free(si->signer); si->signer = signer; } int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, ASN1_OCTET_STRING **keyid, X509_NAME **issuer, ASN1_INTEGER **sno) { return ossl_cms_SignerIdentifier_get0_signer_id(si->sid, keyid, issuer, sno); } int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert) { return ossl_cms_SignerIdentifier_cert_cmp(si->sid, cert); } int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *scerts, unsigned int flags) { CMS_SignedData *sd; CMS_SignerInfo *si; CMS_CertificateChoices *cch; STACK_OF(CMS_CertificateChoices) *certs; X509 *x; int i, j; int ret = 0; sd = cms_get0_signed(cms); if (sd == NULL) return -1; certs = sd->certificates; for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) { si = sk_CMS_SignerInfo_value(sd->signerInfos, i); if (si->signer != NULL) continue; for (j = 0; j < sk_X509_num(scerts); j++) { x = sk_X509_value(scerts, j); if (CMS_SignerInfo_cert_cmp(si, x) == 0) { CMS_SignerInfo_set1_signer_cert(si, x); ret++; break; } } if (si->signer != NULL || (flags & CMS_NOINTERN)) continue; for (j = 0; j < sk_CMS_CertificateChoices_num(certs); j++) { cch = sk_CMS_CertificateChoices_value(certs, j); if (cch->type != CMS_CERTCHOICE_CERT) continue; x = cch->d.certificate; if (CMS_SignerInfo_cert_cmp(si, x) == 0) { CMS_SignerInfo_set1_signer_cert(si, x); ret++; break; } } } return ret; } void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, X509_ALGOR **pdig, X509_ALGOR **psig) { if (pk != NULL) *pk = si->pkey; if (signer != NULL) *signer = si->signer; if (pdig != NULL) *pdig = si->digestAlgorithm; if (psig != NULL) *psig = si->signatureAlgorithm; } ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si) { return si->signature; } static int cms_SignerInfo_content_sign(CMS_ContentInfo *cms, CMS_SignerInfo *si, BIO *chain, const unsigned char *md, unsigned int mdlen) { EVP_MD_CTX *mctx = EVP_MD_CTX_new(); int r = 0; EVP_PKEY_CTX *pctx = NULL; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); if (mctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); return 0; } if (si->pkey == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_PRIVATE_KEY); goto err; } if (!ossl_cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm)) goto err; /* Set SignerInfo algorithm details if we used custom parameter */ if (si->pctx && !cms_sd_asn1_ctrl(si, 0)) goto err; /* * If any signed attributes calculate and add messageDigest attribute */ if (CMS_signed_get_attr_count(si) >= 0) { unsigned char computed_md[EVP_MAX_MD_SIZE]; if (md == NULL) { if (!EVP_DigestFinal_ex(mctx, computed_md, &mdlen)) goto err; md = computed_md; } if (!CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest, V_ASN1_OCTET_STRING, md, mdlen)) goto err; /* Copy content type across */ if (!cms_set_si_contentType_attr(cms, si)) goto err; if (!CMS_SignerInfo_sign(si)) goto err; } else if (si->pctx) { unsigned char *sig; size_t siglen; unsigned char computed_md[EVP_MAX_MD_SIZE]; pctx = si->pctx; if (md == NULL) { if (!EVP_DigestFinal_ex(mctx, computed_md, &mdlen)) goto err; md = computed_md; } siglen = EVP_PKEY_get_size(si->pkey); if (siglen == 0 || (sig = OPENSSL_malloc(siglen)) == NULL) goto err; if (EVP_PKEY_sign(pctx, sig, &siglen, md, mdlen) <= 0) { OPENSSL_free(sig); goto err; } ASN1_STRING_set0(si->signature, sig, siglen); } else { unsigned char *sig; unsigned int siglen; if (md != NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_OPERATION_UNSUPPORTED); goto err; } siglen = EVP_PKEY_get_size(si->pkey); if (siglen == 0 || (sig = OPENSSL_malloc(siglen)) == NULL) goto err; if (!EVP_SignFinal_ex(mctx, sig, &siglen, si->pkey, ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx))) { ERR_raise(ERR_LIB_CMS, CMS_R_SIGNFINAL_ERROR); OPENSSL_free(sig); goto err; } ASN1_STRING_set0(si->signature, sig, siglen); } r = 1; err: EVP_MD_CTX_free(mctx); EVP_PKEY_CTX_free(pctx); return r; } int ossl_cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain, const unsigned char *precomp_md, unsigned int precomp_mdlen) { STACK_OF(CMS_SignerInfo) *sinfos; CMS_SignerInfo *si; int i; sinfos = CMS_get0_SignerInfos(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (!cms_SignerInfo_content_sign(cms, si, chain, precomp_md, precomp_mdlen)) return 0; } cms->d.signedData->encapContentInfo->partial = 0; return 1; } int CMS_SignerInfo_sign(CMS_SignerInfo *si) { EVP_MD_CTX *mctx = si->mctx; EVP_PKEY_CTX *pctx = NULL; unsigned char *abuf = NULL; int alen; size_t siglen; const CMS_CTX *ctx = si->cms_ctx; char md_name[OSSL_MAX_NAME_SIZE]; if (OBJ_obj2txt(md_name, sizeof(md_name), si->digestAlgorithm->algorithm, 0) <= 0) return 0; if (CMS_signed_get_attr_by_NID(si, NID_pkcs9_signingTime, -1) < 0) { if (!cms_add1_signingTime(si, NULL)) goto err; } if (!ossl_cms_si_check_attributes(si)) goto err; if (si->pctx) { pctx = si->pctx; } else { EVP_MD_CTX_reset(mctx); if (EVP_DigestSignInit_ex(mctx, &pctx, md_name, ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx), si->pkey, NULL) <= 0) goto err; si->pctx = pctx; } alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf, ASN1_ITEM_rptr(CMS_Attributes_Sign)); if (!abuf) goto err; if (EVP_DigestSignUpdate(mctx, abuf, alen) <= 0) goto err; if (EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) goto err; OPENSSL_free(abuf); abuf = OPENSSL_malloc(siglen); if (abuf == NULL) goto err; if (EVP_DigestSignFinal(mctx, abuf, &siglen) <= 0) goto err; EVP_MD_CTX_reset(mctx); ASN1_STRING_set0(si->signature, abuf, siglen); return 1; err: OPENSSL_free(abuf); EVP_MD_CTX_reset(mctx); return 0; } int CMS_SignerInfo_verify(CMS_SignerInfo *si) { EVP_MD_CTX *mctx = NULL; unsigned char *abuf = NULL; int alen, r = -1; char name[OSSL_MAX_NAME_SIZE]; const EVP_MD *md; EVP_MD *fetched_md = NULL; const CMS_CTX *ctx = si->cms_ctx; OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx); const char *propq = ossl_cms_ctx_get0_propq(ctx); if (si->pkey == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_PUBLIC_KEY); return -1; } if (!ossl_cms_si_check_attributes(si)) return -1; OBJ_obj2txt(name, sizeof(name), si->digestAlgorithm->algorithm, 0); (void)ERR_set_mark(); fetched_md = EVP_MD_fetch(libctx, name, propq); if (fetched_md != NULL) md = fetched_md; else md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm); if (md == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_DIGEST_ALGORITHM); return -1; } (void)ERR_pop_to_mark(); if (si->mctx == NULL && (si->mctx = EVP_MD_CTX_new()) == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } mctx = si->mctx; if (EVP_DigestVerifyInit_ex(mctx, &si->pctx, EVP_MD_get0_name(md), libctx, propq, si->pkey, NULL) <= 0) goto err; if (!cms_sd_asn1_ctrl(si, 1)) goto err; alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf, ASN1_ITEM_rptr(CMS_Attributes_Verify)); if (abuf == NULL || alen < 0) goto err; r = EVP_DigestVerifyUpdate(mctx, abuf, alen); OPENSSL_free(abuf); if (r <= 0) { r = -1; goto err; } r = EVP_DigestVerifyFinal(mctx, si->signature->data, si->signature->length); if (r <= 0) ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE); err: EVP_MD_free(fetched_md); EVP_MD_CTX_reset(mctx); return r; } /* Create a chain of digest BIOs from a CMS ContentInfo */ BIO *ossl_cms_SignedData_init_bio(CMS_ContentInfo *cms) { int i; CMS_SignedData *sd; BIO *chain = NULL; sd = cms_get0_signed(cms); if (sd == NULL) return NULL; if (cms->d.signedData->encapContentInfo->partial) cms_sd_set_version(sd); for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) { X509_ALGOR *digestAlgorithm; BIO *mdbio; digestAlgorithm = sk_X509_ALGOR_value(sd->digestAlgorithms, i); mdbio = ossl_cms_DigestAlgorithm_init_bio(digestAlgorithm, ossl_cms_get0_cmsctx(cms)); if (mdbio == NULL) goto err; if (chain != NULL) BIO_push(chain, mdbio); else chain = mdbio; } return chain; err: BIO_free_all(chain); return NULL; } int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain) { ASN1_OCTET_STRING *os = NULL; EVP_MD_CTX *mctx = EVP_MD_CTX_new(); EVP_PKEY_CTX *pkctx = NULL; int r = -1; unsigned char mval[EVP_MAX_MD_SIZE]; unsigned int mlen; if (mctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } /* If we have any signed attributes look for messageDigest value */ if (CMS_signed_get_attr_count(si) >= 0) { os = CMS_signed_get0_data_by_OBJ(si, OBJ_nid2obj(NID_pkcs9_messageDigest), -3, V_ASN1_OCTET_STRING); if (os == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE); goto err; } } if (!ossl_cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm)) goto err; if (EVP_DigestFinal_ex(mctx, mval, &mlen) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_UNABLE_TO_FINALIZE_CONTEXT); goto err; } /* If messageDigest found compare it */ if (os != NULL) { if (mlen != (unsigned int)os->length) { ERR_raise(ERR_LIB_CMS, CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH); goto err; } if (memcmp(mval, os->data, mlen)) { ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE); r = 0; } else { r = 1; } } else { const EVP_MD *md = EVP_MD_CTX_get0_md(mctx); const CMS_CTX *ctx = si->cms_ctx; pkctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx), si->pkey, ossl_cms_ctx_get0_propq(ctx)); if (pkctx == NULL) goto err; if (EVP_PKEY_verify_init(pkctx) <= 0) goto err; if (EVP_PKEY_CTX_set_signature_md(pkctx, md) <= 0) goto err; si->pctx = pkctx; if (!cms_sd_asn1_ctrl(si, 1)) goto err; r = EVP_PKEY_verify(pkctx, si->signature->data, si->signature->length, mval, mlen); if (r <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE); r = 0; } } err: EVP_PKEY_CTX_free(pkctx); EVP_MD_CTX_free(mctx); return r; } BIO *CMS_SignedData_verify(CMS_SignedData *sd, BIO *detached_data, STACK_OF(X509) *scerts, X509_STORE *store, STACK_OF(X509) *extra, STACK_OF(X509_CRL) *crls, unsigned int flags, OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *ci; BIO *bio = NULL; int i, res = 0; if (sd == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((ci = CMS_ContentInfo_new_ex(libctx, propq)) == NULL) return NULL; if ((bio = BIO_new(BIO_s_mem())) == NULL) goto end; ci->contentType = OBJ_nid2obj(NID_pkcs7_signed); ci->d.signedData = sd; for (i = 0; i < sk_X509_num(extra); i++) if (!CMS_add1_cert(ci, sk_X509_value(extra, i))) goto end; for (i = 0; i < sk_X509_CRL_num(crls); i++) if (!CMS_add1_crl(ci, sk_X509_CRL_value(crls, i))) goto end; res = CMS_verify(ci, scerts, store, detached_data, bio, flags); end: if (ci != NULL) ci->d.signedData = NULL; /* do not indirectly free |sd| */ CMS_ContentInfo_free(ci); if (!res) { BIO_free(bio); bio = NULL; } return bio; } int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs) { unsigned char *smder = NULL; int smderlen, r; smderlen = i2d_X509_ALGORS(algs, &smder); if (smderlen <= 0) return 0; r = CMS_signed_add1_attr_by_NID(si, NID_SMIMECapabilities, V_ASN1_SEQUENCE, smder, smderlen); OPENSSL_free(smder); return r; } int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, int algnid, int keysize) { X509_ALGOR *alg; ASN1_INTEGER *key = NULL; if (keysize > 0) { key = ASN1_INTEGER_new(); if (key == NULL || !ASN1_INTEGER_set(key, keysize)) { ASN1_INTEGER_free(key); return 0; } } alg = ossl_X509_ALGOR_from_nid(algnid, key != NULL ? V_ASN1_INTEGER : V_ASN1_UNDEF, key); if (alg == NULL) { ASN1_INTEGER_free(key); return 0; } if (*algs == NULL) *algs = sk_X509_ALGOR_new_null(); if (*algs == NULL || !sk_X509_ALGOR_push(*algs, alg)) { X509_ALGOR_free(alg); return 0; } return 1; } /* Check to see if a cipher exists and if so add S/MIME capabilities */ static int cms_add_cipher_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg) { if (EVP_get_cipherbynid(nid)) return CMS_add_simple_smimecap(sk, nid, arg); return 1; } static int cms_add_digest_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg) { if (EVP_get_digestbynid(nid)) return CMS_add_simple_smimecap(sk, nid, arg); return 1; } int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap) { if (!cms_add_cipher_smcap(smcap, NID_aes_256_cbc, -1) || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_256, -1) || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_512, -1) || !cms_add_digest_smcap(smcap, NID_id_GostR3411_94, -1) || !cms_add_cipher_smcap(smcap, NID_id_Gost28147_89, -1) || !cms_add_cipher_smcap(smcap, NID_aes_192_cbc, -1) || !cms_add_cipher_smcap(smcap, NID_aes_128_cbc, -1) || !cms_add_cipher_smcap(smcap, NID_des_ede3_cbc, -1) || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 128) || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 64) || !cms_add_cipher_smcap(smcap, NID_des_cbc, -1) || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 40)) return 0; return 1; }
./openssl/crypto/cms/cms_smime.c
/* * Copyright 2008-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 <openssl/asn1t.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/cms.h> #include "cms_local.h" #include "crypto/asn1.h" static BIO *cms_get_text_bio(BIO *out, unsigned int flags) { BIO *rbio; if (out == NULL) rbio = BIO_new(BIO_s_null()); else if (flags & CMS_TEXT) { rbio = BIO_new(BIO_s_mem()); BIO_set_mem_eof_return(rbio, 0); } else rbio = out; return rbio; } static int cms_copy_content(BIO *out, BIO *in, unsigned int flags) { unsigned char buf[4096]; int r = 0, i; BIO *tmpout; tmpout = cms_get_text_bio(out, flags); if (tmpout == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } /* Read all content through chain to process digest, decrypt etc */ for (;;) { i = BIO_read(in, buf, sizeof(buf)); if (i <= 0) { if (BIO_method_type(in) == BIO_TYPE_CIPHER) { if (BIO_get_cipher_status(in) <= 0) goto err; } if (i < 0) goto err; break; } if (tmpout != NULL && (BIO_write(tmpout, buf, i) != i)) goto err; } if (flags & CMS_TEXT) { if (!SMIME_text(tmpout, out)) { ERR_raise(ERR_LIB_CMS, CMS_R_SMIME_TEXT_ERROR); goto err; } } r = 1; err: if (tmpout != out) BIO_free(tmpout); return r; } static int check_content(CMS_ContentInfo *cms) { ASN1_OCTET_STRING **pos = CMS_get0_content(cms); if (pos == NULL || *pos == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_CONTENT); return 0; } return 1; } static void do_free_upto(BIO *f, BIO *upto) { if (upto != NULL) { BIO *tbio; do { tbio = BIO_pop(f); BIO_free(f); f = tbio; } while (f != NULL && f != upto); } else { BIO_free_all(f); } } int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags) { BIO *cont; int r; if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_data) { ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_DATA); return 0; } cont = CMS_dataInit(cms, NULL); if (cont == NULL) return 0; r = cms_copy_content(out, cont, flags); BIO_free_all(cont); return r; } CMS_ContentInfo *CMS_data_create_ex(BIO *in, unsigned int flags, OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *cms = ossl_cms_Data_create(libctx, propq); if (cms == NULL) return NULL; if ((flags & CMS_STREAM) || CMS_final(cms, in, NULL, flags)) return cms; CMS_ContentInfo_free(cms); return NULL; } CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags) { return CMS_data_create_ex(in, flags, NULL, NULL); } int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out, unsigned int flags) { BIO *cont; int r; if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_digest) { ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_DIGESTED_DATA); return 0; } if (dcont == NULL && !check_content(cms)) return 0; cont = CMS_dataInit(cms, dcont); if (cont == NULL) return 0; r = cms_copy_content(out, cont, flags); if (r) r = ossl_cms_DigestedData_do_final(cms, cont, 1); do_free_upto(cont, dcont); return r; } CMS_ContentInfo *CMS_digest_create_ex(BIO *in, const EVP_MD *md, unsigned int flags, OSSL_LIB_CTX *ctx, const char *propq) { CMS_ContentInfo *cms; /* * Because the EVP_MD is cached and can be a legacy algorithm, we * cannot fetch the algorithm if it isn't supplied. */ if (md == NULL) md = EVP_sha1(); cms = ossl_cms_DigestedData_create(md, ctx, propq); if (cms == NULL) return NULL; if (!(flags & CMS_DETACHED)) CMS_set_detached(cms, 0); if ((flags & CMS_STREAM) || CMS_final(cms, in, NULL, flags)) return cms; CMS_ContentInfo_free(cms); return NULL; } CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md, unsigned int flags) { return CMS_digest_create_ex(in, md, flags, NULL, NULL); } int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms, const unsigned char *key, size_t keylen, BIO *dcont, BIO *out, unsigned int flags) { BIO *cont; int r; if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_encrypted) { ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_ENCRYPTED_DATA); return 0; } if (dcont == NULL && !check_content(cms)) return 0; if (CMS_EncryptedData_set1_key(cms, NULL, key, keylen) <= 0) return 0; cont = CMS_dataInit(cms, dcont); if (cont == NULL) return 0; r = cms_copy_content(out, cont, flags); do_free_upto(cont, dcont); return r; } CMS_ContentInfo *CMS_EncryptedData_encrypt_ex(BIO *in, const EVP_CIPHER *cipher, const unsigned char *key, size_t keylen, unsigned int flags, OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *cms; if (cipher == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_CIPHER); return NULL; } cms = CMS_ContentInfo_new_ex(libctx, propq); if (cms == NULL) return NULL; if (!CMS_EncryptedData_set1_key(cms, cipher, key, keylen)) return NULL; if (!(flags & CMS_DETACHED)) CMS_set_detached(cms, 0); if ((flags & (CMS_STREAM | CMS_PARTIAL)) || CMS_final(cms, in, NULL, flags)) return cms; CMS_ContentInfo_free(cms); return NULL; } CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, const unsigned char *key, size_t keylen, unsigned int flags) { return CMS_EncryptedData_encrypt_ex(in, cipher, key, keylen, flags, NULL, NULL); } static int cms_signerinfo_verify_cert(CMS_SignerInfo *si, X509_STORE *store, STACK_OF(X509) *untrusted, STACK_OF(X509_CRL) *crls, STACK_OF(X509) **chain, const CMS_CTX *cms_ctx) { X509_STORE_CTX *ctx; X509 *signer; int i, j, r = 0; ctx = X509_STORE_CTX_new_ex(ossl_cms_ctx_get0_libctx(cms_ctx), ossl_cms_ctx_get0_propq(cms_ctx)); if (ctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_X509_LIB); goto err; } CMS_SignerInfo_get0_algs(si, NULL, &signer, NULL, NULL); if (!X509_STORE_CTX_init(ctx, store, signer, untrusted)) { ERR_raise(ERR_LIB_CMS, CMS_R_STORE_INIT_ERROR); goto err; } X509_STORE_CTX_set_default(ctx, "smime_sign"); if (crls != NULL) X509_STORE_CTX_set0_crls(ctx, crls); i = X509_verify_cert(ctx); if (i <= 0) { j = X509_STORE_CTX_get_error(ctx); ERR_raise_data(ERR_LIB_CMS, CMS_R_CERTIFICATE_VERIFY_ERROR, "Verify error: %s", X509_verify_cert_error_string(j)); goto err; } r = 1; /* also send back the trust chain when required */ if (chain != NULL) *chain = X509_STORE_CTX_get1_chain(ctx); err: X509_STORE_CTX_free(ctx); return r; } /* This strongly overlaps with PKCS7_verify() */ int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags) { CMS_SignerInfo *si; STACK_OF(CMS_SignerInfo) *sinfos; STACK_OF(X509) *cms_certs = NULL; STACK_OF(X509_CRL) *crls = NULL; STACK_OF(X509) **si_chains = NULL; X509 *signer; int i, scount = 0, ret = 0; BIO *cmsbio = NULL, *tmpin = NULL, *tmpout = NULL; int cadesVerify = (flags & CMS_CADES) != 0; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); if (dcont == NULL && !check_content(cms)) return 0; if (dcont != NULL && !(flags & CMS_BINARY)) { const ASN1_OBJECT *coid = CMS_get0_eContentType(cms); if (OBJ_obj2nid(coid) == NID_id_ct_asciiTextWithCRLF) flags |= CMS_ASCIICRLF; } /* Attempt to find all signer certificates */ sinfos = CMS_get0_SignerInfos(cms); if (sk_CMS_SignerInfo_num(sinfos) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_SIGNERS); goto err; } for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); CMS_SignerInfo_get0_algs(si, NULL, &signer, NULL, NULL); if (signer != NULL) scount++; } if (scount != sk_CMS_SignerInfo_num(sinfos)) scount += CMS_set1_signers_certs(cms, certs, flags); if (scount != sk_CMS_SignerInfo_num(sinfos)) { ERR_raise(ERR_LIB_CMS, CMS_R_SIGNER_CERTIFICATE_NOT_FOUND); goto err; } /* Attempt to verify all signers certs */ /* at this point scount == sk_CMS_SignerInfo_num(sinfos) */ if ((flags & CMS_NO_SIGNER_CERT_VERIFY) == 0 || cadesVerify) { if (cadesVerify) { /* Certificate trust chain is required to check CAdES signature */ si_chains = OPENSSL_zalloc(scount * sizeof(si_chains[0])); if (si_chains == NULL) goto err; } cms_certs = CMS_get1_certs(cms); if (!(flags & CMS_NOCRL)) crls = CMS_get1_crls(cms); for (i = 0; i < scount; i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (!cms_signerinfo_verify_cert(si, store, cms_certs, crls, si_chains ? &si_chains[i] : NULL, ctx)) goto err; } } /* Attempt to verify all SignerInfo signed attribute signatures */ if ((flags & CMS_NO_ATTR_VERIFY) == 0 || cadesVerify) { for (i = 0; i < scount; i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (CMS_signed_get_attr_count(si) < 0) continue; if (CMS_SignerInfo_verify(si) <= 0) goto err; if (cadesVerify) { STACK_OF(X509) *si_chain = si_chains ? si_chains[i] : NULL; if (ossl_cms_check_signing_certs(si, si_chain) <= 0) goto err; } } } /* * Performance optimization: if the content is a memory BIO then store * its contents in a temporary read only memory BIO. This avoids * potentially large numbers of slow copies of data which will occur when * reading from a read write memory BIO when signatures are calculated. */ if (dcont != NULL && (BIO_method_type(dcont) == BIO_TYPE_MEM)) { char *ptr; long len; len = BIO_get_mem_data(dcont, &ptr); tmpin = (len == 0) ? dcont : BIO_new_mem_buf(ptr, len); if (tmpin == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_BIO_LIB); goto err2; } } else { tmpin = dcont; } /* * If not binary mode and detached generate digests by *writing* through * the BIO. That makes it possible to canonicalise the input. */ if (!(flags & SMIME_BINARY) && dcont) { /* * Create output BIO so we can either handle text or to ensure * included content doesn't override detached content. */ tmpout = cms_get_text_bio(out, flags); if (tmpout == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } cmsbio = CMS_dataInit(cms, tmpout); if (cmsbio == NULL) goto err; /* * Don't use SMIME_TEXT for verify: it adds headers and we want to * remove them. */ if (!SMIME_crlf_copy(dcont, cmsbio, flags & ~SMIME_TEXT)) goto err; if (flags & CMS_TEXT) { if (!SMIME_text(tmpout, out)) { ERR_raise(ERR_LIB_CMS, CMS_R_SMIME_TEXT_ERROR); goto err; } } } else { cmsbio = CMS_dataInit(cms, tmpin); if (cmsbio == NULL) goto err; if (!cms_copy_content(out, cmsbio, flags)) goto err; } if (!(flags & CMS_NO_CONTENT_VERIFY)) { for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (CMS_SignerInfo_verify_content(si, cmsbio) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_VERIFY_ERROR); goto err; } } } ret = 1; err: if (!(flags & SMIME_BINARY) && dcont) { do_free_upto(cmsbio, tmpout); if (tmpin != dcont) BIO_free(tmpin); } else { if (dcont && (tmpin == dcont)) do_free_upto(cmsbio, dcont); else BIO_free_all(cmsbio); } if (out != tmpout) BIO_free_all(tmpout); err2: if (si_chains != NULL) { for (i = 0; i < scount; ++i) OSSL_STACK_OF_X509_free(si_chains[i]); OPENSSL_free(si_chains); } OSSL_STACK_OF_X509_free(cms_certs); sk_X509_CRL_pop_free(crls, X509_CRL_free); return ret; } int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms, STACK_OF(X509) *certs, X509_STORE *store, unsigned int flags) { int r; flags &= ~(CMS_DETACHED | CMS_TEXT); r = CMS_verify(rcms, certs, store, NULL, NULL, flags); if (r <= 0) return r; return ossl_cms_Receipt_verify(rcms, ocms); } CMS_ContentInfo *CMS_sign_ex(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, BIO *data, unsigned int flags, OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *cms; int i; cms = CMS_ContentInfo_new_ex(libctx, propq); if (cms == NULL || !CMS_SignedData_init(cms)) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } if (flags & CMS_ASCIICRLF && !CMS_set1_eContentType(cms, OBJ_nid2obj(NID_id_ct_asciiTextWithCRLF))) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } if (pkey != NULL && !CMS_add1_signer(cms, signcert, pkey, NULL, flags)) { ERR_raise(ERR_LIB_CMS, CMS_R_ADD_SIGNER_ERROR); goto err; } for (i = 0; i < sk_X509_num(certs); i++) { X509 *x = sk_X509_value(certs, i); if (!CMS_add1_cert(cms, x)) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } } if (!(flags & CMS_DETACHED)) CMS_set_detached(cms, 0); if ((flags & (CMS_STREAM | CMS_PARTIAL)) || CMS_final(cms, data, NULL, flags)) return cms; else goto err; err: CMS_ContentInfo_free(cms); return NULL; } CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, BIO *data, unsigned int flags) { return CMS_sign_ex(signcert, pkey, certs, data, flags, NULL, NULL); } CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si, X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, unsigned int flags) { CMS_SignerInfo *rct_si; CMS_ContentInfo *cms = NULL; ASN1_OCTET_STRING **pos, *os = NULL; BIO *rct_cont = NULL; int r = 0; const CMS_CTX *ctx = si->cms_ctx; flags &= ~(CMS_STREAM | CMS_TEXT); /* Not really detached but avoids content being allocated */ flags |= CMS_PARTIAL | CMS_BINARY | CMS_DETACHED; if (pkey == NULL || signcert == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY_OR_CERT); return NULL; } /* Initialize signed data */ cms = CMS_sign_ex(NULL, NULL, certs, NULL, flags, ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx)); if (cms == NULL) goto err; /* Set inner content type to signed receipt */ if (!CMS_set1_eContentType(cms, OBJ_nid2obj(NID_id_smime_ct_receipt))) goto err; rct_si = CMS_add1_signer(cms, signcert, pkey, NULL, flags); if (!rct_si) { ERR_raise(ERR_LIB_CMS, CMS_R_ADD_SIGNER_ERROR); goto err; } os = ossl_cms_encode_Receipt(si); if (os == NULL) goto err; /* Set content to digest */ rct_cont = BIO_new_mem_buf(os->data, os->length); if (rct_cont == NULL) goto err; /* Add msgSigDigest attribute */ if (!ossl_cms_msgSigDigest_add1(rct_si, si)) goto err; /* Finalize structure */ if (!CMS_final(cms, rct_cont, NULL, flags)) goto err; /* Set embedded content */ pos = CMS_get0_content(cms); if (pos == NULL) goto err; *pos = os; r = 1; err: BIO_free(rct_cont); if (r) return cms; CMS_ContentInfo_free(cms); ASN1_OCTET_STRING_free(os); return NULL; } CMS_ContentInfo *CMS_encrypt_ex(STACK_OF(X509) *certs, BIO *data, const EVP_CIPHER *cipher, unsigned int flags, OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *cms; int i; X509 *recip; cms = (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) ? CMS_AuthEnvelopedData_create_ex(cipher, libctx, propq) : CMS_EnvelopedData_create_ex(cipher, libctx, propq); if (cms == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } for (i = 0; i < sk_X509_num(certs); i++) { recip = sk_X509_value(certs, i); if (!CMS_add1_recipient_cert(cms, recip, flags)) { ERR_raise(ERR_LIB_CMS, CMS_R_RECIPIENT_ERROR); goto err; } } if (!(flags & CMS_DETACHED)) CMS_set_detached(cms, 0); if ((flags & (CMS_STREAM | CMS_PARTIAL)) || CMS_final(cms, data, NULL, flags)) return cms; else ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); err: CMS_ContentInfo_free(cms); return NULL; } CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *data, const EVP_CIPHER *cipher, unsigned int flags) { return CMS_encrypt_ex(certs, data, cipher, flags, NULL, NULL); } static int cms_kari_set1_pkey_and_peer(CMS_ContentInfo *cms, CMS_RecipientInfo *ri, EVP_PKEY *pk, X509 *cert, X509 *peer) { int i; STACK_OF(CMS_RecipientEncryptedKey) *reks; CMS_RecipientEncryptedKey *rek; reks = CMS_RecipientInfo_kari_get0_reks(ri); for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++) { int rv; rek = sk_CMS_RecipientEncryptedKey_value(reks, i); if (cert != NULL && CMS_RecipientEncryptedKey_cert_cmp(rek, cert)) continue; CMS_RecipientInfo_kari_set0_pkey_and_peer(ri, pk, peer); rv = CMS_RecipientInfo_kari_decrypt(cms, ri, rek); CMS_RecipientInfo_kari_set0_pkey(ri, NULL); if (rv > 0) return 1; return cert == NULL ? 0 : -1; } return 0; } int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert) { return CMS_decrypt_set1_pkey_and_peer(cms, pk, cert, NULL); } int CMS_decrypt_set1_pkey_and_peer(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert, X509 *peer) { STACK_OF(CMS_RecipientInfo) *ris = CMS_get0_RecipientInfos(cms); CMS_RecipientInfo *ri; int i, r, cms_pkey_ri_type; int debug = 0, match_ri = 0; CMS_EncryptedContentInfo *ec = ossl_cms_get0_env_enc_content(cms); /* Prevent mem leak on earlier CMS_decrypt_set1_{pkey_and_peer,password} */ if (ec != NULL) { OPENSSL_clear_free(ec->key, ec->keylen); ec->key = NULL; ec->keylen = 0; } if (ris != NULL && ec != NULL) debug = ec->debug; cms_pkey_ri_type = ossl_cms_pkey_get_ri_type(pk); if (cms_pkey_ri_type == CMS_RECIPINFO_NONE) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); return 0; } for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) { int ri_type; ri = sk_CMS_RecipientInfo_value(ris, i); ri_type = CMS_RecipientInfo_type(ri); if (!ossl_cms_pkey_is_ri_type_supported(pk, ri_type)) continue; match_ri = 1; if (ri_type == CMS_RECIPINFO_AGREE) { r = cms_kari_set1_pkey_and_peer(cms, ri, pk, cert, peer); if (r > 0) return 1; if (r < 0) return 0; } /* If we have a cert, try matching RecipientInfo, else try them all */ else if (cert == NULL || !CMS_RecipientInfo_ktri_cert_cmp(ri, cert)) { EVP_PKEY_up_ref(pk); CMS_RecipientInfo_set0_pkey(ri, pk); r = CMS_RecipientInfo_decrypt(cms, ri); CMS_RecipientInfo_set0_pkey(ri, NULL); if (cert != NULL) { /* * If not debugging clear any error and return success to * avoid leaking of information useful to MMA */ if (!debug) { ERR_clear_error(); return 1; } if (r > 0) return 1; ERR_raise(ERR_LIB_CMS, CMS_R_DECRYPT_ERROR); return 0; } /* * If no cert and not debugging don't leave loop after first * successful decrypt. Always attempt to decrypt all recipients * to avoid leaking timing of a successful decrypt. */ else if (r > 0 && (debug || cms_pkey_ri_type != CMS_RECIPINFO_TRANS)) return 1; } } /* If no cert, key transport and not debugging always return success */ if (cert == NULL && cms_pkey_ri_type == CMS_RECIPINFO_TRANS && match_ri && !debug) { ERR_clear_error(); return 1; } if (!match_ri) ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_RECIPIENT); return 0; } int CMS_decrypt_set1_key(CMS_ContentInfo *cms, unsigned char *key, size_t keylen, const unsigned char *id, size_t idlen) { STACK_OF(CMS_RecipientInfo) *ris; CMS_RecipientInfo *ri; int i, r, match_ri = 0; ris = CMS_get0_RecipientInfos(cms); for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) { ri = sk_CMS_RecipientInfo_value(ris, i); if (CMS_RecipientInfo_type(ri) != CMS_RECIPINFO_KEK) continue; /* If we have an id, try matching RecipientInfo, else try them all */ if (id == NULL || (CMS_RecipientInfo_kekri_id_cmp(ri, id, idlen) == 0)) { match_ri = 1; CMS_RecipientInfo_set0_key(ri, key, keylen); r = CMS_RecipientInfo_decrypt(cms, ri); CMS_RecipientInfo_set0_key(ri, NULL, 0); if (r > 0) return 1; if (id != NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_DECRYPT_ERROR); return 0; } ERR_clear_error(); } } if (!match_ri) ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_RECIPIENT); return 0; } int CMS_decrypt_set1_password(CMS_ContentInfo *cms, unsigned char *pass, ossl_ssize_t passlen) { STACK_OF(CMS_RecipientInfo) *ris = CMS_get0_RecipientInfos(cms); CMS_RecipientInfo *ri; int i, r, match_ri = 0; CMS_EncryptedContentInfo *ec = ossl_cms_get0_env_enc_content(cms); /* Prevent mem leak on earlier CMS_decrypt_set1_{pkey_and_peer,password} */ if (ec != NULL) { OPENSSL_clear_free(ec->key, ec->keylen); ec->key = NULL; ec->keylen = 0; } for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) { ri = sk_CMS_RecipientInfo_value(ris, i); if (CMS_RecipientInfo_type(ri) != CMS_RECIPINFO_PASS) continue; /* Must try each PasswordRecipientInfo */ match_ri = 1; CMS_RecipientInfo_set0_password(ri, pass, passlen); r = CMS_RecipientInfo_decrypt(cms, ri); CMS_RecipientInfo_set0_password(ri, NULL, 0); if (r > 0) return 1; } if (!match_ri) ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_RECIPIENT); return 0; } int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert, BIO *dcont, BIO *out, unsigned int flags) { int r; BIO *cont; CMS_EncryptedContentInfo *ec; int nid = OBJ_obj2nid(CMS_get0_type(cms)); if (nid != NID_pkcs7_enveloped && nid != NID_id_smime_ct_authEnvelopedData) { ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_ENVELOPED_DATA); return 0; } if (dcont == NULL && !check_content(cms)) return 0; ec = ossl_cms_get0_env_enc_content(cms); ec->debug = (flags & CMS_DEBUG_DECRYPT) != 0; ec->havenocert = cert == NULL; if (pk == NULL && cert == NULL && dcont == NULL && out == NULL) return 1; if (pk != NULL && !CMS_decrypt_set1_pkey(cms, pk, cert)) return 0; cont = CMS_dataInit(cms, dcont); if (cont == NULL) return 0; r = cms_copy_content(out, cont, flags); do_free_upto(cont, dcont); return r; } int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, unsigned int flags) { BIO *cmsbio; int ret = 0; if ((cmsbio = CMS_dataInit(cms, dcont)) == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_CMS_LIB); return 0; } if (!SMIME_crlf_copy(data, cmsbio, flags)) { goto err; } (void)BIO_flush(cmsbio); if (!CMS_dataFinal(cms, cmsbio)) { ERR_raise(ERR_LIB_CMS, CMS_R_CMS_DATAFINAL_ERROR); goto err; } ret = 1; err: do_free_upto(cmsbio, dcont); return ret; } int CMS_final_digest(CMS_ContentInfo *cms, const unsigned char *md, unsigned int mdlen, BIO *dcont, unsigned int flags) { BIO *cmsbio; int ret = 0; if ((cmsbio = CMS_dataInit(cms, dcont)) == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_CMS_LIB); return 0; } (void)BIO_flush(cmsbio); if (!ossl_cms_DataFinal(cms, cmsbio, md, mdlen)) { ERR_raise(ERR_LIB_CMS, CMS_R_CMS_DATAFINAL_ERROR); goto err; } ret = 1; err: do_free_upto(cmsbio, dcont); return ret; } #ifndef OPENSSL_NO_ZLIB int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out, unsigned int flags) { BIO *cont; int r; if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_id_smime_ct_compressedData) { ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_COMPRESSED_DATA); return 0; } if (dcont == NULL && !check_content(cms)) return 0; cont = CMS_dataInit(cms, dcont); if (cont == NULL) return 0; r = cms_copy_content(out, cont, flags); do_free_upto(cont, dcont); return r; } CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags) { CMS_ContentInfo *cms; if (comp_nid <= 0) comp_nid = NID_zlib_compression; cms = ossl_cms_CompressedData_create(comp_nid, NULL, NULL); if (cms == NULL) return NULL; if (!(flags & CMS_DETACHED)) CMS_set_detached(cms, 0); if ((flags & CMS_STREAM) || CMS_final(cms, in, NULL, flags)) return cms; CMS_ContentInfo_free(cms); return NULL; } #else int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out, unsigned int flags) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM); return 0; } CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM); return NULL; } #endif
./openssl/crypto/hpke/hpke.c
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* An OpenSSL-based HPKE implementation of RFC9180 */ #include <string.h> #include <openssl/rand.h> #include <openssl/kdf.h> #include <openssl/core_names.h> #include <openssl/hpke.h> #include <openssl/sha.h> #include <openssl/evp.h> #include <openssl/err.h> #include "internal/hpke_util.h" #include "internal/nelem.h" #include "internal/common.h" /* default buffer size for keys and internal buffers we use */ #define OSSL_HPKE_MAXSIZE 512 /* Define HPKE labels from RFC9180 in hex for EBCDIC compatibility */ /* "HPKE" - "suite_id" label for section 5.1 */ static const char OSSL_HPKE_SEC51LABEL[] = "\x48\x50\x4b\x45"; /* "psk_id_hash" - in key_schedule_context */ static const char OSSL_HPKE_PSKIDHASH_LABEL[] = "\x70\x73\x6b\x5f\x69\x64\x5f\x68\x61\x73\x68"; /* "info_hash" - in key_schedule_context */ static const char OSSL_HPKE_INFOHASH_LABEL[] = "\x69\x6e\x66\x6f\x5f\x68\x61\x73\x68"; /* "base_nonce" - base nonce calc label */ static const char OSSL_HPKE_NONCE_LABEL[] = "\x62\x61\x73\x65\x5f\x6e\x6f\x6e\x63\x65"; /* "exp" - internal exporter secret generation label */ static const char OSSL_HPKE_EXP_LABEL[] = "\x65\x78\x70"; /* "sec" - external label for exporting secret */ static const char OSSL_HPKE_EXP_SEC_LABEL[] = "\x73\x65\x63"; /* "key" - label for use when generating key from shared secret */ static const char OSSL_HPKE_KEY_LABEL[] = "\x6b\x65\x79"; /* "secret" - for generating shared secret */ static const char OSSL_HPKE_SECRET_LABEL[] = "\x73\x65\x63\x72\x65\x74"; /** * @brief sender or receiver context */ struct ossl_hpke_ctx_st { OSSL_LIB_CTX *libctx; /* library context */ char *propq; /* properties */ int mode; /* HPKE mode */ OSSL_HPKE_SUITE suite; /* suite */ const OSSL_HPKE_KEM_INFO *kem_info; const OSSL_HPKE_KDF_INFO *kdf_info; const OSSL_HPKE_AEAD_INFO *aead_info; EVP_CIPHER *aead_ciph; int role; /* sender(0) or receiver(1) */ uint64_t seq; /* aead sequence number */ unsigned char *shared_secret; /* KEM output, zz */ size_t shared_secretlen; unsigned char *key; /* final aead key */ size_t keylen; unsigned char *nonce; /* aead base nonce */ size_t noncelen; unsigned char *exportersec; /* exporter secret */ size_t exporterseclen; char *pskid; /* PSK stuff */ unsigned char *psk; size_t psklen; EVP_PKEY *authpriv; /* sender's authentication private key */ unsigned char *authpub; /* auth public key */ size_t authpublen; unsigned char *ikme; /* IKM for sender deterministic key gen */ size_t ikmelen; }; /** * @brief check if KEM uses NIST curve or not * @param kem_id is the externally supplied kem_id * @return 1 for NIST curves, 0 for other */ static int hpke_kem_id_nist_curve(uint16_t kem_id) { const OSSL_HPKE_KEM_INFO *kem_info; kem_info = ossl_HPKE_KEM_INFO_find_id(kem_id); return kem_info != NULL && kem_info->groupname != NULL; } /** * @brief wrapper to import NIST curve public key as easily as x25519/x448 * @param libctx is the context to use * @param propq is a properties string * @param gname is the curve groupname * @param buf is the binary buffer with the (uncompressed) public value * @param buflen is the length of the private key buffer * @return a working EVP_PKEY * or NULL * * Note that this could be a useful function to make public in * future, but would likely require a name change. */ static EVP_PKEY *evp_pkey_new_raw_nist_public_key(OSSL_LIB_CTX *libctx, const char *propq, const char *gname, const unsigned char *buf, size_t buflen) { OSSL_PARAM params[2]; EVP_PKEY *ret = NULL; EVP_PKEY_CTX *cctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", propq); params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, (char *)gname, 0); params[1] = OSSL_PARAM_construct_end(); if (cctx == NULL || EVP_PKEY_paramgen_init(cctx) <= 0 || EVP_PKEY_CTX_set_params(cctx, params) <= 0 || EVP_PKEY_paramgen(cctx, &ret) <= 0 || EVP_PKEY_set1_encoded_public_key(ret, buf, buflen) != 1) { EVP_PKEY_CTX_free(cctx); EVP_PKEY_free(ret); ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return NULL; } EVP_PKEY_CTX_free(cctx); return ret; } /** * @brief do the AEAD decryption * @param hctx is the context to use * @param iv is the initialisation vector * @param aad is the additional authenticated data * @param aadlen is the length of the aad * @param ct is the ciphertext buffer * @param ctlen is the ciphertext length (including tag). * @param pt is the output buffer * @param ptlen input/output, better be big enough on input, exact on output * @return 1 on success, 0 otherwise */ static int hpke_aead_dec(OSSL_HPKE_CTX *hctx, const unsigned char *iv, const unsigned char *aad, size_t aadlen, const unsigned char *ct, size_t ctlen, unsigned char *pt, size_t *ptlen) { int erv = 0; EVP_CIPHER_CTX *ctx = NULL; int len = 0; size_t taglen; taglen = hctx->aead_info->taglen; if (ctlen <= taglen || *ptlen < ctlen - taglen) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } /* Create and initialise the context */ if ((ctx = EVP_CIPHER_CTX_new()) == NULL) return 0; /* Initialise the decryption operation. */ if (EVP_DecryptInit_ex(ctx, hctx->aead_ciph, NULL, NULL, NULL) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, hctx->noncelen, NULL) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } /* Initialise key and IV */ if (EVP_DecryptInit_ex(ctx, NULL, NULL, hctx->key, iv) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } /* Provide AAD. */ if (aadlen != 0 && aad != NULL) { if (EVP_DecryptUpdate(ctx, NULL, &len, aad, aadlen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } } if (EVP_DecryptUpdate(ctx, pt, &len, ct, ctlen - taglen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } *ptlen = len; if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, (void *)(ct + ctlen - taglen))) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } /* Finalise decryption. */ if (EVP_DecryptFinal_ex(ctx, pt + len, &len) <= 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } erv = 1; err: if (erv != 1) OPENSSL_cleanse(pt, *ptlen); EVP_CIPHER_CTX_free(ctx); return erv; } /** * @brief do AEAD encryption as per the RFC * @param hctx is the context to use * @param iv is the initialisation vector * @param aad is the additional authenticated data * @param aadlen is the length of the aad * @param pt is the plaintext buffer * @param ptlen is the length of pt * @param ct is the output buffer * @param ctlen input/output, needs space for tag on input, exact on output * @return 1 for success, 0 otherwise */ static int hpke_aead_enc(OSSL_HPKE_CTX *hctx, const unsigned char *iv, const unsigned char *aad, size_t aadlen, const unsigned char *pt, size_t ptlen, unsigned char *ct, size_t *ctlen) { int erv = 0; EVP_CIPHER_CTX *ctx = NULL; int len; size_t taglen = 0; unsigned char tag[EVP_MAX_AEAD_TAG_LENGTH]; taglen = hctx->aead_info->taglen; if (*ctlen <= taglen || ptlen > *ctlen - taglen) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (!ossl_assert(taglen <= sizeof(tag))) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } /* Create and initialise the context */ if ((ctx = EVP_CIPHER_CTX_new()) == NULL) return 0; /* Initialise the encryption operation. */ if (EVP_EncryptInit_ex(ctx, hctx->aead_ciph, NULL, NULL, NULL) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, hctx->noncelen, NULL) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } /* Initialise key and IV */ if (EVP_EncryptInit_ex(ctx, NULL, NULL, hctx->key, iv) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } /* Provide any AAD data. */ if (aadlen != 0 && aad != NULL) { if (EVP_EncryptUpdate(ctx, NULL, &len, aad, aadlen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } } if (EVP_EncryptUpdate(ctx, ct, &len, pt, ptlen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } *ctlen = len; /* Finalise the encryption. */ if (EVP_EncryptFinal_ex(ctx, ct + len, &len) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } *ctlen += len; /* Get tag. Not a duplicate so needs to be added to the ciphertext */ if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } memcpy(ct + *ctlen, tag, taglen); *ctlen += taglen; erv = 1; err: if (erv != 1) OPENSSL_cleanse(ct, *ctlen); EVP_CIPHER_CTX_free(ctx); return erv; } /** * @brief check mode is in-range and supported * @param mode is the caller's chosen mode * @return 1 for good mode, 0 otherwise */ static int hpke_mode_check(unsigned int mode) { switch (mode) { case OSSL_HPKE_MODE_BASE: case OSSL_HPKE_MODE_PSK: case OSSL_HPKE_MODE_AUTH: case OSSL_HPKE_MODE_PSKAUTH: break; default: return 0; } return 1; } /** * @brief check if a suite is supported locally * @param suite is the suite to check * @return 1 for good, 0 otherwise */ static int hpke_suite_check(OSSL_HPKE_SUITE suite, const OSSL_HPKE_KEM_INFO **kem_info, const OSSL_HPKE_KDF_INFO **kdf_info, const OSSL_HPKE_AEAD_INFO **aead_info) { const OSSL_HPKE_KEM_INFO *kem_info_; const OSSL_HPKE_KDF_INFO *kdf_info_; const OSSL_HPKE_AEAD_INFO *aead_info_; /* check KEM, KDF and AEAD are supported here */ if ((kem_info_ = ossl_HPKE_KEM_INFO_find_id(suite.kem_id)) == NULL) return 0; if ((kdf_info_ = ossl_HPKE_KDF_INFO_find_id(suite.kdf_id)) == NULL) return 0; if ((aead_info_ = ossl_HPKE_AEAD_INFO_find_id(suite.aead_id)) == NULL) return 0; if (kem_info != NULL) *kem_info = kem_info_; if (kdf_info != NULL) *kdf_info = kdf_info_; if (aead_info != NULL) *aead_info = aead_info_; return 1; } /* * @brief randomly pick a suite * @param libctx is the context to use * @param propq is a properties string * @param suite is the result * @return 1 for success, 0 otherwise */ static int hpke_random_suite(OSSL_LIB_CTX *libctx, const char *propq, OSSL_HPKE_SUITE *suite) { const OSSL_HPKE_KEM_INFO *kem_info = NULL; const OSSL_HPKE_KDF_INFO *kdf_info = NULL; const OSSL_HPKE_AEAD_INFO *aead_info = NULL; /* random kem, kdf and aead */ kem_info = ossl_HPKE_KEM_INFO_find_random(libctx); if (kem_info == NULL) return 0; suite->kem_id = kem_info->kem_id; kdf_info = ossl_HPKE_KDF_INFO_find_random(libctx); if (kdf_info == NULL) return 0; suite->kdf_id = kdf_info->kdf_id; aead_info = ossl_HPKE_AEAD_INFO_find_random(libctx); if (aead_info == NULL) return 0; suite->aead_id = aead_info->aead_id; return 1; } /* * @brief tell the caller how big the ciphertext will be * * AEAD algorithms add a tag for data authentication. * Those are almost always, but not always, 16 octets * long, and who knows what will be true in the future. * So this function allows a caller to find out how * much data expansion they will see with a given suite. * * "enc" is the name used in RFC9180 for the encapsulated * public value of the sender, who calls OSSL_HPKE_seal(), * that is sent to the recipient, who calls OSSL_HPKE_open(). * * @param suite is the suite to be used * @param enclen points to what will be enc length * @param clearlen is the length of plaintext * @param cipherlen points to what will be ciphertext length (including tag) * @return 1 for success, 0 otherwise */ static int hpke_expansion(OSSL_HPKE_SUITE suite, size_t *enclen, size_t clearlen, size_t *cipherlen) { const OSSL_HPKE_AEAD_INFO *aead_info = NULL; const OSSL_HPKE_KEM_INFO *kem_info = NULL; if (cipherlen == NULL || enclen == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (hpke_suite_check(suite, &kem_info, NULL, &aead_info) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } *cipherlen = clearlen + aead_info->taglen; *enclen = kem_info->Nenc; return 1; } /* * @brief expand and XOR the 64-bit unsigned seq with (nonce) buffer * @param ctx is the HPKE context * @param buf is the buffer for the XOR'd seq and nonce * @param blen is the size of buf * @return 0 for error, otherwise blen */ static size_t hpke_seqnonce2buf(OSSL_HPKE_CTX *ctx, unsigned char *buf, size_t blen) { size_t i; uint64_t seq_copy; if (ctx == NULL || blen < sizeof(seq_copy) || blen != ctx->noncelen) return 0; seq_copy = ctx->seq; memset(buf, 0, blen); for (i = 0; i < sizeof(seq_copy); i++) { buf[blen - i - 1] = seq_copy & 0xff; seq_copy >>= 8; } for (i = 0; i < blen; i++) buf[i] ^= ctx->nonce[i]; return blen; } /* * @brief call the underlying KEM to encap * @param ctx is the OSSL_HPKE_CTX * @param enc is a buffer for the sender's ephemeral public value * @param enclen is the size of enc on input, number of octets used on output * @param pub is the recipient's public value * @param publen is the length of pub * @return 1 for success, 0 for error */ static int hpke_encap(OSSL_HPKE_CTX *ctx, unsigned char *enc, size_t *enclen, const unsigned char *pub, size_t publen) { int erv = 0; OSSL_PARAM params[3], *p = params; size_t lsslen = 0, lenclen = 0; EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *pkR = NULL; const OSSL_HPKE_KEM_INFO *kem_info = NULL; if (ctx == NULL || enc == NULL || enclen == NULL || *enclen == 0 || pub == NULL || publen == 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->shared_secret != NULL) { /* only run the KEM once per OSSL_HPKE_CTX */ ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } kem_info = ossl_HPKE_KEM_INFO_find_id(ctx->suite.kem_id); if (kem_info == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } if (hpke_kem_id_nist_curve(ctx->suite.kem_id) == 1) { pkR = evp_pkey_new_raw_nist_public_key(ctx->libctx, ctx->propq, kem_info->groupname, pub, publen); } else { pkR = EVP_PKEY_new_raw_public_key_ex(ctx->libctx, kem_info->keytype, ctx->propq, pub, publen); } if (pkR == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } pctx = EVP_PKEY_CTX_new_from_pkey(ctx->libctx, pkR, ctx->propq); if (pctx == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KEM_PARAM_OPERATION, OSSL_KEM_PARAM_OPERATION_DHKEM, 0); if (ctx->ikme != NULL) { *p++ = OSSL_PARAM_construct_octet_string(OSSL_KEM_PARAM_IKME, ctx->ikme, ctx->ikmelen); } *p = OSSL_PARAM_construct_end(); if (ctx->mode == OSSL_HPKE_MODE_AUTH || ctx->mode == OSSL_HPKE_MODE_PSKAUTH) { if (EVP_PKEY_auth_encapsulate_init(pctx, ctx->authpriv, params) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } } else { if (EVP_PKEY_encapsulate_init(pctx, params) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } } lenclen = *enclen; if (EVP_PKEY_encapsulate(pctx, NULL, &lenclen, NULL, &lsslen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } if (lenclen > *enclen) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); goto err; } ctx->shared_secret = OPENSSL_malloc(lsslen); if (ctx->shared_secret == NULL) goto err; ctx->shared_secretlen = lsslen; if (EVP_PKEY_encapsulate(pctx, enc, enclen, ctx->shared_secret, &ctx->shared_secretlen) != 1) { ctx->shared_secretlen = 0; OPENSSL_free(ctx->shared_secret); ctx->shared_secret = NULL; ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } erv = 1; err: EVP_PKEY_CTX_free(pctx); EVP_PKEY_free(pkR); return erv; } /* * @brief call the underlying KEM to decap * @param ctx is the OSSL_HPKE_CTX * @param enc is a buffer for the sender's ephemeral public value * @param enclen is the length of enc * @param priv is the recipient's private value * @return 1 for success, 0 for error */ static int hpke_decap(OSSL_HPKE_CTX *ctx, const unsigned char *enc, size_t enclen, EVP_PKEY *priv) { int erv = 0; EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *spub = NULL; OSSL_PARAM params[2], *p = params; size_t lsslen = 0; if (ctx == NULL || enc == NULL || enclen == 0 || priv == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->shared_secret != NULL) { /* only run the KEM once per OSSL_HPKE_CTX */ ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } pctx = EVP_PKEY_CTX_new_from_pkey(ctx->libctx, priv, ctx->propq); if (pctx == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KEM_PARAM_OPERATION, OSSL_KEM_PARAM_OPERATION_DHKEM, 0); *p = OSSL_PARAM_construct_end(); if (ctx->mode == OSSL_HPKE_MODE_AUTH || ctx->mode == OSSL_HPKE_MODE_PSKAUTH) { const OSSL_HPKE_KEM_INFO *kem_info = NULL; kem_info = ossl_HPKE_KEM_INFO_find_id(ctx->suite.kem_id); if (kem_info == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } if (hpke_kem_id_nist_curve(ctx->suite.kem_id) == 1) { spub = evp_pkey_new_raw_nist_public_key(ctx->libctx, ctx->propq, kem_info->groupname, ctx->authpub, ctx->authpublen); } else { spub = EVP_PKEY_new_raw_public_key_ex(ctx->libctx, kem_info->keytype, ctx->propq, ctx->authpub, ctx->authpublen); } if (spub == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } if (EVP_PKEY_auth_decapsulate_init(pctx, spub, params) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } } else { if (EVP_PKEY_decapsulate_init(pctx, params) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } } if (EVP_PKEY_decapsulate(pctx, NULL, &lsslen, enc, enclen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } ctx->shared_secret = OPENSSL_malloc(lsslen); if (ctx->shared_secret == NULL) goto err; if (EVP_PKEY_decapsulate(pctx, ctx->shared_secret, &lsslen, enc, enclen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } ctx->shared_secretlen = lsslen; erv = 1; err: EVP_PKEY_CTX_free(pctx); EVP_PKEY_free(spub); if (erv == 0) { OPENSSL_free(ctx->shared_secret); ctx->shared_secret = NULL; ctx->shared_secretlen = 0; } return erv; } /* * @brief do "middle" of HPKE, between KEM and AEAD * @param ctx is the OSSL_HPKE_CTX * @param info is a buffer for the added binding information * @param infolen is the length of info * @return 0 for error, 1 for success * * This does all the HPKE extracts and expands as defined in RFC9180 * section 5.1, (badly termed there as a "key schedule") and sets the * ctx fields for the shared_secret, nonce, key and exporter_secret */ static int hpke_do_middle(OSSL_HPKE_CTX *ctx, const unsigned char *info, size_t infolen) { int erv = 0; size_t ks_contextlen = OSSL_HPKE_MAXSIZE; unsigned char ks_context[OSSL_HPKE_MAXSIZE]; size_t halflen = 0; size_t pskidlen = 0; const OSSL_HPKE_AEAD_INFO *aead_info = NULL; const OSSL_HPKE_KDF_INFO *kdf_info = NULL; size_t secretlen = OSSL_HPKE_MAXSIZE; unsigned char secret[OSSL_HPKE_MAXSIZE]; EVP_KDF_CTX *kctx = NULL; unsigned char suitebuf[6]; const char *mdname = NULL; /* only let this be done once */ if (ctx->exportersec != NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (ossl_HPKE_KEM_INFO_find_id(ctx->suite.kem_id) == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } aead_info = ossl_HPKE_AEAD_INFO_find_id(ctx->suite.aead_id); if (aead_info == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } kdf_info = ossl_HPKE_KDF_INFO_find_id(ctx->suite.kdf_id); if (kdf_info == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } mdname = kdf_info->mdname; /* create key schedule context */ memset(ks_context, 0, sizeof(ks_context)); ks_context[0] = (unsigned char)(ctx->mode % 256); ks_contextlen--; /* remaining space */ halflen = kdf_info->Nh; if ((2 * halflen) > ks_contextlen) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } /* check a psk was set if in that mode */ if (ctx->mode == OSSL_HPKE_MODE_PSK || ctx->mode == OSSL_HPKE_MODE_PSKAUTH) { if (ctx->psk == NULL || ctx->psklen == 0 || ctx->pskid == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } } kctx = ossl_kdf_ctx_create("HKDF", mdname, ctx->libctx, ctx->propq); if (kctx == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } pskidlen = (ctx->psk == NULL ? 0 : strlen(ctx->pskid)); /* full suite details as per RFC9180 sec 5.1 */ suitebuf[0] = ctx->suite.kem_id / 256; suitebuf[1] = ctx->suite.kem_id % 256; suitebuf[2] = ctx->suite.kdf_id / 256; suitebuf[3] = ctx->suite.kdf_id % 256; suitebuf[4] = ctx->suite.aead_id / 256; suitebuf[5] = ctx->suite.aead_id % 256; /* Extract and Expand variously... */ if (ossl_hpke_labeled_extract(kctx, ks_context + 1, halflen, NULL, 0, OSSL_HPKE_SEC51LABEL, suitebuf, sizeof(suitebuf), OSSL_HPKE_PSKIDHASH_LABEL, (unsigned char *)ctx->pskid, pskidlen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } if (ossl_hpke_labeled_extract(kctx, ks_context + 1 + halflen, halflen, NULL, 0, OSSL_HPKE_SEC51LABEL, suitebuf, sizeof(suitebuf), OSSL_HPKE_INFOHASH_LABEL, (unsigned char *)info, infolen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } ks_contextlen = 1 + 2 * halflen; secretlen = kdf_info->Nh; if (secretlen > OSSL_HPKE_MAXSIZE) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } if (ossl_hpke_labeled_extract(kctx, secret, secretlen, ctx->shared_secret, ctx->shared_secretlen, OSSL_HPKE_SEC51LABEL, suitebuf, sizeof(suitebuf), OSSL_HPKE_SECRET_LABEL, ctx->psk, ctx->psklen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } if (ctx->suite.aead_id != OSSL_HPKE_AEAD_ID_EXPORTONLY) { /* we only need nonce/key for non export AEADs */ ctx->noncelen = aead_info->Nn; ctx->nonce = OPENSSL_malloc(ctx->noncelen); if (ctx->nonce == NULL) goto err; if (ossl_hpke_labeled_expand(kctx, ctx->nonce, ctx->noncelen, secret, secretlen, OSSL_HPKE_SEC51LABEL, suitebuf, sizeof(suitebuf), OSSL_HPKE_NONCE_LABEL, ks_context, ks_contextlen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } ctx->keylen = aead_info->Nk; ctx->key = OPENSSL_malloc(ctx->keylen); if (ctx->key == NULL) goto err; if (ossl_hpke_labeled_expand(kctx, ctx->key, ctx->keylen, secret, secretlen, OSSL_HPKE_SEC51LABEL, suitebuf, sizeof(suitebuf), OSSL_HPKE_KEY_LABEL, ks_context, ks_contextlen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } } ctx->exporterseclen = kdf_info->Nh; ctx->exportersec = OPENSSL_malloc(ctx->exporterseclen); if (ctx->exportersec == NULL) goto err; if (ossl_hpke_labeled_expand(kctx, ctx->exportersec, ctx->exporterseclen, secret, secretlen, OSSL_HPKE_SEC51LABEL, suitebuf, sizeof(suitebuf), OSSL_HPKE_EXP_LABEL, ks_context, ks_contextlen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } erv = 1; err: OPENSSL_cleanse(ks_context, OSSL_HPKE_MAXSIZE); OPENSSL_cleanse(secret, OSSL_HPKE_MAXSIZE); EVP_KDF_CTX_free(kctx); return erv; } /* * externally visible functions from below here, API documentation is * in doc/man3/OSSL_HPKE_CTX_new.pod to avoid duplication */ OSSL_HPKE_CTX *OSSL_HPKE_CTX_new(int mode, OSSL_HPKE_SUITE suite, int role, OSSL_LIB_CTX *libctx, const char *propq) { OSSL_HPKE_CTX *ctx = NULL; const OSSL_HPKE_KEM_INFO *kem_info; const OSSL_HPKE_KDF_INFO *kdf_info; const OSSL_HPKE_AEAD_INFO *aead_info; if (hpke_mode_check(mode) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } if (hpke_suite_check(suite, &kem_info, &kdf_info, &aead_info) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } if (role != OSSL_HPKE_ROLE_SENDER && role != OSSL_HPKE_ROLE_RECEIVER) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } 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) goto err; } if (suite.aead_id != OSSL_HPKE_AEAD_ID_EXPORTONLY) { ctx->aead_ciph = EVP_CIPHER_fetch(libctx, aead_info->name, propq); if (ctx->aead_ciph == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_FETCH_FAILED); goto err; } } ctx->role = role; ctx->mode = mode; ctx->suite = suite; ctx->kem_info = kem_info; ctx->kdf_info = kdf_info; ctx->aead_info = aead_info; return ctx; err: EVP_CIPHER_free(ctx->aead_ciph); OPENSSL_free(ctx); return NULL; } void OSSL_HPKE_CTX_free(OSSL_HPKE_CTX *ctx) { if (ctx == NULL) return; EVP_CIPHER_free(ctx->aead_ciph); OPENSSL_free(ctx->propq); OPENSSL_clear_free(ctx->exportersec, ctx->exporterseclen); OPENSSL_free(ctx->pskid); OPENSSL_clear_free(ctx->psk, ctx->psklen); OPENSSL_clear_free(ctx->key, ctx->keylen); OPENSSL_clear_free(ctx->nonce, ctx->noncelen); OPENSSL_clear_free(ctx->shared_secret, ctx->shared_secretlen); OPENSSL_clear_free(ctx->ikme, ctx->ikmelen); EVP_PKEY_free(ctx->authpriv); OPENSSL_free(ctx->authpub); OPENSSL_free(ctx); return; } int OSSL_HPKE_CTX_set1_psk(OSSL_HPKE_CTX *ctx, const char *pskid, const unsigned char *psk, size_t psklen) { if (ctx == NULL || pskid == NULL || psk == NULL || psklen == 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (psklen > OSSL_HPKE_MAX_PARMLEN) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (psklen < OSSL_HPKE_MIN_PSKLEN) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (strlen(pskid) > OSSL_HPKE_MAX_PARMLEN) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (strlen(pskid) == 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->mode != OSSL_HPKE_MODE_PSK && ctx->mode != OSSL_HPKE_MODE_PSKAUTH) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } /* free previous values if any */ OPENSSL_clear_free(ctx->psk, ctx->psklen); ctx->psk = OPENSSL_memdup(psk, psklen); if (ctx->psk == NULL) return 0; ctx->psklen = psklen; OPENSSL_free(ctx->pskid); ctx->pskid = OPENSSL_strdup(pskid); if (ctx->pskid == NULL) { OPENSSL_clear_free(ctx->psk, ctx->psklen); ctx->psk = NULL; ctx->psklen = 0; return 0; } return 1; } int OSSL_HPKE_CTX_set1_ikme(OSSL_HPKE_CTX *ctx, const unsigned char *ikme, size_t ikmelen) { if (ctx == NULL || ikme == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ikmelen == 0 || ikmelen > OSSL_HPKE_MAX_PARMLEN) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->role != OSSL_HPKE_ROLE_SENDER) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } OPENSSL_clear_free(ctx->ikme, ctx->ikmelen); ctx->ikme = OPENSSL_memdup(ikme, ikmelen); if (ctx->ikme == NULL) return 0; ctx->ikmelen = ikmelen; return 1; } int OSSL_HPKE_CTX_set1_authpriv(OSSL_HPKE_CTX *ctx, EVP_PKEY *priv) { if (ctx == NULL || priv == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ctx->mode != OSSL_HPKE_MODE_AUTH && ctx->mode != OSSL_HPKE_MODE_PSKAUTH) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->role != OSSL_HPKE_ROLE_SENDER) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } EVP_PKEY_free(ctx->authpriv); ctx->authpriv = EVP_PKEY_dup(priv); if (ctx->authpriv == NULL) return 0; return 1; } int OSSL_HPKE_CTX_set1_authpub(OSSL_HPKE_CTX *ctx, const unsigned char *pub, size_t publen) { int erv = 0; EVP_PKEY *pubp = NULL; unsigned char *lpub = NULL; size_t lpublen = 0; const OSSL_HPKE_KEM_INFO *kem_info = NULL; if (ctx == NULL || pub == NULL || publen == 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ctx->mode != OSSL_HPKE_MODE_AUTH && ctx->mode != OSSL_HPKE_MODE_PSKAUTH) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->role != OSSL_HPKE_ROLE_RECEIVER) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } /* check the value seems like a good public key for this kem */ kem_info = ossl_HPKE_KEM_INFO_find_id(ctx->suite.kem_id); if (kem_info == NULL) return 0; if (hpke_kem_id_nist_curve(ctx->suite.kem_id) == 1) { pubp = evp_pkey_new_raw_nist_public_key(ctx->libctx, ctx->propq, kem_info->groupname, pub, publen); } else { pubp = EVP_PKEY_new_raw_public_key_ex(ctx->libctx, kem_info->keytype, ctx->propq, pub, publen); } if (pubp == NULL) { /* can happen based on external input - buffer value may be garbage */ ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); goto err; } /* * extract out the public key in encoded form so we * should be fine even if given compressed form */ lpub = OPENSSL_malloc(OSSL_HPKE_MAXSIZE); if (lpub == NULL) goto err; if (EVP_PKEY_get_octet_string_param(pubp, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, lpub, OSSL_HPKE_MAXSIZE, &lpublen) != 1) { OPENSSL_free(lpub); ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } /* free up old value */ OPENSSL_free(ctx->authpub); ctx->authpub = lpub; ctx->authpublen = lpublen; erv = 1; err: EVP_PKEY_free(pubp); return erv; } int OSSL_HPKE_CTX_get_seq(OSSL_HPKE_CTX *ctx, uint64_t *seq) { if (ctx == NULL || seq == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } *seq = ctx->seq; return 1; } int OSSL_HPKE_CTX_set_seq(OSSL_HPKE_CTX *ctx, uint64_t seq) { if (ctx == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* * We disallow senders from doing this as it's dangerous * Receivers are ok to use this, as no harm should ensue * if they go wrong. */ if (ctx->role == OSSL_HPKE_ROLE_SENDER) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } ctx->seq = seq; return 1; } int OSSL_HPKE_encap(OSSL_HPKE_CTX *ctx, unsigned char *enc, size_t *enclen, const unsigned char *pub, size_t publen, const unsigned char *info, size_t infolen) { int erv = 1; size_t minenc = 0; if (ctx == NULL || enc == NULL || enclen == NULL || *enclen == 0 || pub == NULL || publen == 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->role != OSSL_HPKE_ROLE_SENDER) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (infolen > OSSL_HPKE_MAX_INFOLEN) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (infolen > 0 && info == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } minenc = OSSL_HPKE_get_public_encap_size(ctx->suite); if (minenc == 0 || minenc > *enclen) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->shared_secret != NULL) { /* only allow one encap per OSSL_HPKE_CTX */ ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (hpke_encap(ctx, enc, enclen, pub, publen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } /* * note that the info is not part of the context as it * only needs to be used once here so doesn't need to * be stored */ erv = hpke_do_middle(ctx, info, infolen); return erv; } int OSSL_HPKE_decap(OSSL_HPKE_CTX *ctx, const unsigned char *enc, size_t enclen, EVP_PKEY *recippriv, const unsigned char *info, size_t infolen) { int erv = 1; size_t minenc = 0; if (ctx == NULL || enc == NULL || enclen == 0 || recippriv == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->role != OSSL_HPKE_ROLE_RECEIVER) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (infolen > OSSL_HPKE_MAX_INFOLEN) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (infolen > 0 && info == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } minenc = OSSL_HPKE_get_public_encap_size(ctx->suite); if (minenc == 0 || minenc > enclen) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->shared_secret != NULL) { /* only allow one encap per OSSL_HPKE_CTX */ ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } erv = hpke_decap(ctx, enc, enclen, recippriv); if (erv != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } /* * note that the info is not part of the context as it * only needs to be used once here so doesn't need to * be stored */ erv = hpke_do_middle(ctx, info, infolen); return erv; } int OSSL_HPKE_seal(OSSL_HPKE_CTX *ctx, unsigned char *ct, size_t *ctlen, const unsigned char *aad, size_t aadlen, const unsigned char *pt, size_t ptlen) { unsigned char seqbuf[OSSL_HPKE_MAX_NONCELEN]; size_t seqlen = 0; if (ctx == NULL || ct == NULL || ctlen == NULL || *ctlen == 0 || pt == NULL || ptlen == 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->role != OSSL_HPKE_ROLE_SENDER) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if ((ctx->seq + 1) == 0) { /* wrap around imminent !!! */ ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (ctx->key == NULL || ctx->nonce == NULL) { /* need to have done an encap first, info can be NULL */ ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } seqlen = hpke_seqnonce2buf(ctx, seqbuf, sizeof(seqbuf)); if (seqlen == 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } if (hpke_aead_enc(ctx, seqbuf, aad, aadlen, pt, ptlen, ct, ctlen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); OPENSSL_cleanse(seqbuf, sizeof(seqbuf)); return 0; } else { ctx->seq++; } OPENSSL_cleanse(seqbuf, sizeof(seqbuf)); return 1; } int OSSL_HPKE_open(OSSL_HPKE_CTX *ctx, unsigned char *pt, size_t *ptlen, const unsigned char *aad, size_t aadlen, const unsigned char *ct, size_t ctlen) { unsigned char seqbuf[OSSL_HPKE_MAX_NONCELEN]; size_t seqlen = 0; if (ctx == NULL || pt == NULL || ptlen == NULL || *ptlen == 0 || ct == NULL || ctlen == 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->role != OSSL_HPKE_ROLE_RECEIVER) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if ((ctx->seq + 1) == 0) { /* wrap around imminent !!! */ ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (ctx->key == NULL || ctx->nonce == NULL) { /* need to have done an encap first, info can be NULL */ ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } seqlen = hpke_seqnonce2buf(ctx, seqbuf, sizeof(seqbuf)); if (seqlen == 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } if (hpke_aead_dec(ctx, seqbuf, aad, aadlen, ct, ctlen, pt, ptlen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); OPENSSL_cleanse(seqbuf, sizeof(seqbuf)); return 0; } ctx->seq++; OPENSSL_cleanse(seqbuf, sizeof(seqbuf)); return 1; } int OSSL_HPKE_export(OSSL_HPKE_CTX *ctx, unsigned char *secret, size_t secretlen, const unsigned char *label, size_t labellen) { int erv = 0; EVP_KDF_CTX *kctx = NULL; unsigned char suitebuf[6]; const char *mdname = NULL; const OSSL_HPKE_KDF_INFO *kdf_info = NULL; if (ctx == NULL || secret == NULL || secretlen == 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (labellen > OSSL_HPKE_MAX_PARMLEN) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (labellen > 0 && label == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->exportersec == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } kdf_info = ossl_HPKE_KDF_INFO_find_id(ctx->suite.kdf_id); if (kdf_info == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } mdname = kdf_info->mdname; kctx = ossl_kdf_ctx_create("HKDF", mdname, ctx->libctx, ctx->propq); if (kctx == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } /* full suiteid as per RFC9180 sec 5.3 */ suitebuf[0] = ctx->suite.kem_id / 256; suitebuf[1] = ctx->suite.kem_id % 256; suitebuf[2] = ctx->suite.kdf_id / 256; suitebuf[3] = ctx->suite.kdf_id % 256; suitebuf[4] = ctx->suite.aead_id / 256; suitebuf[5] = ctx->suite.aead_id % 256; erv = ossl_hpke_labeled_expand(kctx, secret, secretlen, ctx->exportersec, ctx->exporterseclen, OSSL_HPKE_SEC51LABEL, suitebuf, sizeof(suitebuf), OSSL_HPKE_EXP_SEC_LABEL, label, labellen); EVP_KDF_CTX_free(kctx); if (erv != 1) ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return erv; } int OSSL_HPKE_keygen(OSSL_HPKE_SUITE suite, unsigned char *pub, size_t *publen, EVP_PKEY **priv, const unsigned char *ikm, size_t ikmlen, OSSL_LIB_CTX *libctx, const char *propq) { int erv = 0; /* Our error return value - 1 is success */ EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *skR = NULL; const OSSL_HPKE_KEM_INFO *kem_info = NULL; OSSL_PARAM params[3], *p = params; if (pub == NULL || publen == NULL || *publen == 0 || priv == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (hpke_suite_check(suite, &kem_info, NULL, NULL) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if ((ikmlen > 0 && ikm == NULL) || (ikmlen == 0 && ikm != NULL) || ikmlen > OSSL_HPKE_MAX_PARMLEN) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (hpke_kem_id_nist_curve(suite.kem_id) == 1) { *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, (char *)kem_info->groupname, 0); pctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", propq); } else { pctx = EVP_PKEY_CTX_new_from_name(libctx, kem_info->keytype, propq); } if (pctx == NULL || EVP_PKEY_keygen_init(pctx) <= 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } if (ikm != NULL) *p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_DHKEM_IKM, (char *)ikm, ikmlen); *p = OSSL_PARAM_construct_end(); if (EVP_PKEY_CTX_set_params(pctx, params) <= 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } if (EVP_PKEY_generate(pctx, &skR) <= 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } EVP_PKEY_CTX_free(pctx); pctx = NULL; if (EVP_PKEY_get_octet_string_param(skR, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, pub, *publen, publen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } *priv = skR; erv = 1; err: if (erv != 1) EVP_PKEY_free(skR); EVP_PKEY_CTX_free(pctx); return erv; } int OSSL_HPKE_suite_check(OSSL_HPKE_SUITE suite) { return hpke_suite_check(suite, NULL, NULL, NULL); } int OSSL_HPKE_get_grease_value(const OSSL_HPKE_SUITE *suite_in, OSSL_HPKE_SUITE *suite, unsigned char *enc, size_t *enclen, unsigned char *ct, size_t ctlen, OSSL_LIB_CTX *libctx, const char *propq) { OSSL_HPKE_SUITE chosen; size_t plen = 0; const OSSL_HPKE_KEM_INFO *kem_info = NULL; const OSSL_HPKE_AEAD_INFO *aead_info = NULL; EVP_PKEY *fakepriv = NULL; if (enc == NULL || enclen == 0 || ct == NULL || ctlen == 0 || suite == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (suite_in == NULL) { /* choose a random suite */ if (hpke_random_suite(libctx, propq, &chosen) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } } else { chosen = *suite_in; } if (hpke_suite_check(chosen, &kem_info, NULL, &aead_info) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } *suite = chosen; /* make sure room for tag and one plaintext octet */ if (aead_info->taglen >= ctlen) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } /* publen */ plen = kem_info->Npk; if (plen > *enclen) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } /* * In order for our enc to look good for sure, we generate and then * delete a real key for that curve - bit OTT but it ensures we do * get the encoding right (e.g. 0x04 as 1st octet for NIST curves in * uncompressed form) and that the value really does map to a point on * the relevant curve. */ if (OSSL_HPKE_keygen(chosen, enc, enclen, &fakepriv, NULL, 0, libctx, propq) != 1) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } EVP_PKEY_free(fakepriv); if (RAND_bytes_ex(libctx, ct, ctlen, 0) <= 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto err; } return 1; err: return 0; } int OSSL_HPKE_str2suite(const char *str, OSSL_HPKE_SUITE *suite) { return ossl_hpke_str2suite(str, suite); } size_t OSSL_HPKE_get_ciphertext_size(OSSL_HPKE_SUITE suite, size_t clearlen) { size_t enclen = 0; size_t cipherlen = 0; if (hpke_expansion(suite, &enclen, clearlen, &cipherlen) != 1) return 0; return cipherlen; } size_t OSSL_HPKE_get_public_encap_size(OSSL_HPKE_SUITE suite) { size_t enclen = 0; size_t cipherlen = 0; size_t clearlen = 16; if (hpke_expansion(suite, &enclen, clearlen, &cipherlen) != 1) return 0; return enclen; } size_t OSSL_HPKE_get_recommended_ikmelen(OSSL_HPKE_SUITE suite) { const OSSL_HPKE_KEM_INFO *kem_info = NULL; if (hpke_suite_check(suite, &kem_info, NULL, NULL) != 1) return 0; if (kem_info == NULL) return 0; return kem_info->Nsk; }
./openssl/crypto/hpke/hpke_util.c
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/core_names.h> #include <openssl/kdf.h> #include <openssl/params.h> #include <openssl/err.h> #include <openssl/proverr.h> #include <openssl/hpke.h> #include <openssl/sha.h> #include <openssl/rand.h> #include "crypto/ecx.h" #include "crypto/rand.h" #include "internal/hpke_util.h" #include "internal/packet.h" #include "internal/nelem.h" #include "internal/common.h" /* * Delimiter used in OSSL_HPKE_str2suite */ #define OSSL_HPKE_STR_DELIMCHAR ',' /* * table with identifier and synonym strings * right now, there are 4 synonyms for each - a name, a hex string * a hex string with a leading zero and a decimal string - more * could be added but that seems like enough */ typedef struct { uint16_t id; char *synonyms[4]; } synonymttab_t; /* max length of string we'll try map to a suite */ #define OSSL_HPKE_MAX_SUITESTR 38 /* Define HPKE labels from RFC9180 in hex for EBCDIC compatibility */ /* ASCII: "HPKE-v1", in hex for EBCDIC compatibility */ static const char LABEL_HPKEV1[] = "\x48\x50\x4B\x45\x2D\x76\x31"; /* * Note that if additions are made to the set of IANA codepoints * and the tables below, corresponding additions should also be * made to the synonymtab tables a little further down so that * OSSL_HPKE_str2suite() continues to function correctly. * * The canonical place to check for IANA registered codepoints * is: https://www.iana.org/assignments/hpke/hpke.xhtml */ /* * @brief table of KEMs * See RFC9180 Section 7.1 "Table 2 KEM IDs" */ static const OSSL_HPKE_KEM_INFO hpke_kem_tab[] = { #ifndef OPENSSL_NO_EC { OSSL_HPKE_KEM_ID_P256, "EC", OSSL_HPKE_KEMSTR_P256, LN_sha256, SHA256_DIGEST_LENGTH, 65, 65, 32, 0xFF }, { OSSL_HPKE_KEM_ID_P384, "EC", OSSL_HPKE_KEMSTR_P384, LN_sha384, SHA384_DIGEST_LENGTH, 97, 97, 48, 0xFF }, { OSSL_HPKE_KEM_ID_P521, "EC", OSSL_HPKE_KEMSTR_P521, LN_sha512, SHA512_DIGEST_LENGTH, 133, 133, 66, 0x01 }, # ifndef OPENSSL_NO_ECX { OSSL_HPKE_KEM_ID_X25519, OSSL_HPKE_KEMSTR_X25519, NULL, LN_sha256, SHA256_DIGEST_LENGTH, X25519_KEYLEN, X25519_KEYLEN, X25519_KEYLEN, 0x00 }, { OSSL_HPKE_KEM_ID_X448, OSSL_HPKE_KEMSTR_X448, NULL, LN_sha512, SHA512_DIGEST_LENGTH, X448_KEYLEN, X448_KEYLEN, X448_KEYLEN, 0x00 } # endif #else { OSSL_HPKE_KEM_ID_RESERVED, NULL, NULL, NULL, 0, 0, 0, 0, 0x00 } #endif }; /* * @brief table of AEADs * See RFC9180 Section 7.2 "Table 3 KDF IDs" */ static const OSSL_HPKE_AEAD_INFO hpke_aead_tab[] = { { OSSL_HPKE_AEAD_ID_AES_GCM_128, LN_aes_128_gcm, 16, 16, OSSL_HPKE_MAX_NONCELEN }, { OSSL_HPKE_AEAD_ID_AES_GCM_256, LN_aes_256_gcm, 16, 32, OSSL_HPKE_MAX_NONCELEN }, #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) { OSSL_HPKE_AEAD_ID_CHACHA_POLY1305, LN_chacha20_poly1305, 16, 32, OSSL_HPKE_MAX_NONCELEN }, #endif { OSSL_HPKE_AEAD_ID_EXPORTONLY, NULL, 0, 0, 0 } }; /* * @brief table of KDFs * See RFC9180 Section 7.3 "Table 5 AEAD IDs" */ static const OSSL_HPKE_KDF_INFO hpke_kdf_tab[] = { { OSSL_HPKE_KDF_ID_HKDF_SHA256, LN_sha256, SHA256_DIGEST_LENGTH }, { OSSL_HPKE_KDF_ID_HKDF_SHA384, LN_sha384, SHA384_DIGEST_LENGTH }, { OSSL_HPKE_KDF_ID_HKDF_SHA512, LN_sha512, SHA512_DIGEST_LENGTH } }; /** * Synonym tables for KEMs, KDFs and AEADs: idea is to allow * mapping strings to suites with a little flexibility in terms * of allowing a name or a couple of forms of number (for * the IANA codepoint). If new IANA codepoints are allocated * then these tables should be updated at the same time as the * others above. * * The function to use these is ossl_hpke_str2suite() further down * this file and shouldn't need modification so long as the table * sizes (i.e. allow exactly 4 synonyms) don't change. */ static const synonymttab_t kemstrtab[] = { {OSSL_HPKE_KEM_ID_P256, {OSSL_HPKE_KEMSTR_P256, "0x10", "0x10", "16" }}, {OSSL_HPKE_KEM_ID_P384, {OSSL_HPKE_KEMSTR_P384, "0x11", "0x11", "17" }}, {OSSL_HPKE_KEM_ID_P521, {OSSL_HPKE_KEMSTR_P521, "0x12", "0x12", "18" }}, # ifndef OPENSSL_NO_ECX {OSSL_HPKE_KEM_ID_X25519, {OSSL_HPKE_KEMSTR_X25519, "0x20", "0x20", "32" }}, {OSSL_HPKE_KEM_ID_X448, {OSSL_HPKE_KEMSTR_X448, "0x21", "0x21", "33" }} # endif }; static const synonymttab_t kdfstrtab[] = { {OSSL_HPKE_KDF_ID_HKDF_SHA256, {OSSL_HPKE_KDFSTR_256, "0x1", "0x01", "1"}}, {OSSL_HPKE_KDF_ID_HKDF_SHA384, {OSSL_HPKE_KDFSTR_384, "0x2", "0x02", "2"}}, {OSSL_HPKE_KDF_ID_HKDF_SHA512, {OSSL_HPKE_KDFSTR_512, "0x3", "0x03", "3"}} }; static const synonymttab_t aeadstrtab[] = { {OSSL_HPKE_AEAD_ID_AES_GCM_128, {OSSL_HPKE_AEADSTR_AES128GCM, "0x1", "0x01", "1"}}, {OSSL_HPKE_AEAD_ID_AES_GCM_256, {OSSL_HPKE_AEADSTR_AES256GCM, "0x2", "0x02", "2"}}, {OSSL_HPKE_AEAD_ID_CHACHA_POLY1305, {OSSL_HPKE_AEADSTR_CP, "0x3", "0x03", "3"}}, {OSSL_HPKE_AEAD_ID_EXPORTONLY, {OSSL_HPKE_AEADSTR_EXP, "ff", "0xff", "255"}} }; /* Return an object containing KEM constants associated with a EC curve name */ const OSSL_HPKE_KEM_INFO *ossl_HPKE_KEM_INFO_find_curve(const char *curve) { int i, sz = OSSL_NELEM(hpke_kem_tab); for (i = 0; i < sz; ++i) { const char *group = hpke_kem_tab[i].groupname; if (group == NULL) group = hpke_kem_tab[i].keytype; if (OPENSSL_strcasecmp(curve, group) == 0) return &hpke_kem_tab[i]; } ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CURVE); return NULL; } const OSSL_HPKE_KEM_INFO *ossl_HPKE_KEM_INFO_find_id(uint16_t kemid) { int i, sz = OSSL_NELEM(hpke_kem_tab); /* * this check can happen if we're in a no-ec build and there are no * KEMS available */ if (kemid == OSSL_HPKE_KEM_ID_RESERVED) { ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CURVE); return NULL; } for (i = 0; i != sz; ++i) { if (hpke_kem_tab[i].kem_id == kemid) return &hpke_kem_tab[i]; } ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CURVE); return NULL; } const OSSL_HPKE_KEM_INFO *ossl_HPKE_KEM_INFO_find_random(OSSL_LIB_CTX *ctx) { uint32_t rval = 0; int err = 0; size_t sz = OSSL_NELEM(hpke_kem_tab); rval = ossl_rand_uniform_uint32(ctx, sz, &err); return (err == 1 ? NULL : &hpke_kem_tab[rval]); } const OSSL_HPKE_KDF_INFO *ossl_HPKE_KDF_INFO_find_id(uint16_t kdfid) { int i, sz = OSSL_NELEM(hpke_kdf_tab); for (i = 0; i != sz; ++i) { if (hpke_kdf_tab[i].kdf_id == kdfid) return &hpke_kdf_tab[i]; } ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KDF); return NULL; } const OSSL_HPKE_KDF_INFO *ossl_HPKE_KDF_INFO_find_random(OSSL_LIB_CTX *ctx) { uint32_t rval = 0; int err = 0; size_t sz = OSSL_NELEM(hpke_kdf_tab); rval = ossl_rand_uniform_uint32(ctx, sz, &err); return (err == 1 ? NULL : &hpke_kdf_tab[rval]); } const OSSL_HPKE_AEAD_INFO *ossl_HPKE_AEAD_INFO_find_id(uint16_t aeadid) { int i, sz = OSSL_NELEM(hpke_aead_tab); for (i = 0; i != sz; ++i) { if (hpke_aead_tab[i].aead_id == aeadid) return &hpke_aead_tab[i]; } ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_AEAD); return NULL; } const OSSL_HPKE_AEAD_INFO *ossl_HPKE_AEAD_INFO_find_random(OSSL_LIB_CTX *ctx) { uint32_t rval = 0; int err = 0; /* the minus 1 below is so we don't pick the EXPORTONLY codepoint */ size_t sz = OSSL_NELEM(hpke_aead_tab) - 1; rval = ossl_rand_uniform_uint32(ctx, sz, &err); return (err == 1 ? NULL : &hpke_aead_tab[rval]); } static int kdf_derive(EVP_KDF_CTX *kctx, unsigned char *out, size_t outlen, int mode, const unsigned char *salt, size_t saltlen, const unsigned char *ikm, size_t ikmlen, const unsigned char *info, size_t infolen) { int ret; OSSL_PARAM params[5], *p = params; *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode); if (salt != NULL) *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, (char *)salt, saltlen); if (ikm != NULL) *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY, (char *)ikm, ikmlen); if (info != NULL) *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_INFO, (char *)info, infolen); *p = OSSL_PARAM_construct_end(); ret = EVP_KDF_derive(kctx, out, outlen, params) > 0; if (!ret) ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_DURING_DERIVATION); return ret; } int ossl_hpke_kdf_extract(EVP_KDF_CTX *kctx, unsigned char *prk, size_t prklen, const unsigned char *salt, size_t saltlen, const unsigned char *ikm, size_t ikmlen) { return kdf_derive(kctx, prk, prklen, EVP_KDF_HKDF_MODE_EXTRACT_ONLY, salt, saltlen, ikm, ikmlen, NULL, 0); } /* Common code to perform a HKDF expand */ int ossl_hpke_kdf_expand(EVP_KDF_CTX *kctx, unsigned char *okm, size_t okmlen, const unsigned char *prk, size_t prklen, const unsigned char *info, size_t infolen) { return kdf_derive(kctx, okm, okmlen, EVP_KDF_HKDF_MODE_EXPAND_ONLY, NULL, 0, prk, prklen, info, infolen); } /* * See RFC 9180 Section 4 LabelExtract() */ int ossl_hpke_labeled_extract(EVP_KDF_CTX *kctx, unsigned char *prk, size_t prklen, const unsigned char *salt, size_t saltlen, const char *protocol_label, const unsigned char *suiteid, size_t suiteidlen, const char *label, const unsigned char *ikm, size_t ikmlen) { int ret = 0; size_t label_hpkev1len = 0; size_t protocol_labellen = 0; size_t labellen = 0; size_t labeled_ikmlen = 0; unsigned char *labeled_ikm = NULL; WPACKET pkt; label_hpkev1len = strlen(LABEL_HPKEV1); protocol_labellen = strlen(protocol_label); labellen = strlen(label); labeled_ikmlen = label_hpkev1len + protocol_labellen + suiteidlen + labellen + ikmlen; labeled_ikm = OPENSSL_malloc(labeled_ikmlen); if (labeled_ikm == NULL) return 0; /* labeled_ikm = concat("HPKE-v1", suiteid, label, ikm) */ if (!WPACKET_init_static_len(&pkt, labeled_ikm, labeled_ikmlen, 0) || !WPACKET_memcpy(&pkt, LABEL_HPKEV1, label_hpkev1len) || !WPACKET_memcpy(&pkt, protocol_label, protocol_labellen) || !WPACKET_memcpy(&pkt, suiteid, suiteidlen) || !WPACKET_memcpy(&pkt, label, labellen) || !WPACKET_memcpy(&pkt, ikm, ikmlen) || !WPACKET_get_total_written(&pkt, &labeled_ikmlen) || !WPACKET_finish(&pkt)) { ERR_raise(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL); goto end; } ret = ossl_hpke_kdf_extract(kctx, prk, prklen, salt, saltlen, labeled_ikm, labeled_ikmlen); end: WPACKET_cleanup(&pkt); OPENSSL_cleanse(labeled_ikm, labeled_ikmlen); OPENSSL_free(labeled_ikm); return ret; } /* * See RFC 9180 Section 4 LabelExpand() */ int ossl_hpke_labeled_expand(EVP_KDF_CTX *kctx, unsigned char *okm, size_t okmlen, const unsigned char *prk, size_t prklen, const char *protocol_label, const unsigned char *suiteid, size_t suiteidlen, const char *label, const unsigned char *info, size_t infolen) { int ret = 0; size_t label_hpkev1len = 0; size_t protocol_labellen = 0; size_t labellen = 0; size_t labeled_infolen = 0; unsigned char *labeled_info = NULL; WPACKET pkt; label_hpkev1len = strlen(LABEL_HPKEV1); protocol_labellen = strlen(protocol_label); labellen = strlen(label); labeled_infolen = 2 + okmlen + prklen + label_hpkev1len + protocol_labellen + suiteidlen + labellen + infolen; labeled_info = OPENSSL_malloc(labeled_infolen); if (labeled_info == NULL) return 0; /* labeled_info = concat(okmlen, "HPKE-v1", suiteid, label, info) */ if (!WPACKET_init_static_len(&pkt, labeled_info, labeled_infolen, 0) || !WPACKET_put_bytes_u16(&pkt, okmlen) || !WPACKET_memcpy(&pkt, LABEL_HPKEV1, label_hpkev1len) || !WPACKET_memcpy(&pkt, protocol_label, protocol_labellen) || !WPACKET_memcpy(&pkt, suiteid, suiteidlen) || !WPACKET_memcpy(&pkt, label, labellen) || !WPACKET_memcpy(&pkt, info, infolen) || !WPACKET_get_total_written(&pkt, &labeled_infolen) || !WPACKET_finish(&pkt)) { ERR_raise(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL); goto end; } ret = ossl_hpke_kdf_expand(kctx, okm, okmlen, prk, prklen, labeled_info, labeled_infolen); end: WPACKET_cleanup(&pkt); OPENSSL_free(labeled_info); return ret; } /* Common code to create a HKDF ctx */ EVP_KDF_CTX *ossl_kdf_ctx_create(const char *kdfname, const char *mdname, OSSL_LIB_CTX *libctx, const char *propq) { EVP_KDF *kdf; EVP_KDF_CTX *kctx = NULL; kdf = EVP_KDF_fetch(libctx, kdfname, propq); if (kdf == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_FETCH_FAILED); return NULL; } kctx = EVP_KDF_CTX_new(kdf); EVP_KDF_free(kdf); if (kctx != NULL && mdname != NULL) { OSSL_PARAM params[3], *p = params; if (mdname != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, (char *)mdname, 0); if (propq != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_PROPERTIES, (char *)propq, 0); *p = OSSL_PARAM_construct_end(); if (EVP_KDF_CTX_set_params(kctx, params) <= 0) { EVP_KDF_CTX_free(kctx); return NULL; } } return kctx; } /* * @brief look for a label into the synonym tables, and return its id * @param st is the string value * @param synp is the synonyms labels array * @param arrsize is the previous array size * @return 0 when not found, else the matching item id. */ static uint16_t synonyms_name2id(const char *st, const synonymttab_t *synp, size_t arrsize) { size_t i, j; for (i = 0; i < arrsize; ++i) { for (j = 0; j < OSSL_NELEM(synp[i].synonyms); ++j) { if (OPENSSL_strcasecmp(st, synp[i].synonyms[j]) == 0) return synp[i].id; } } return 0; } /* * @brief map a string to a HPKE suite based on synonym tables * @param str is the string value * @param suite is the resulting suite * @return 1 for success, otherwise failure */ int ossl_hpke_str2suite(const char *suitestr, OSSL_HPKE_SUITE *suite) { uint16_t kem = 0, kdf = 0, aead = 0; char *st = NULL, *instrcp = NULL; size_t inplen; int labels = 0, result = 0; int delim_count = 0; if (suitestr == NULL || suitestr[0] == 0x00 || suite == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } inplen = OPENSSL_strnlen(suitestr, OSSL_HPKE_MAX_SUITESTR); if (inplen >= OSSL_HPKE_MAX_SUITESTR) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } /* * we don't want a delimiter at the end of the string; * strtok_r/s() doesn't care about that, so we should */ if (suitestr[inplen - 1] == OSSL_HPKE_STR_DELIMCHAR) return 0; /* We want exactly two delimiters in the input string */ for (st = (char *)suitestr; *st != '\0'; st++) { if (*st == OSSL_HPKE_STR_DELIMCHAR) delim_count++; } if (delim_count != 2) return 0; /* Duplicate `suitestr` to allow its parsing */ instrcp = OPENSSL_memdup(suitestr, inplen + 1); if (instrcp == NULL) goto fail; /* See if it contains a mix of our strings and numbers */ st = instrcp; while (st != NULL && labels < 3) { char *cp = strchr(st, OSSL_HPKE_STR_DELIMCHAR); /* add a NUL like strtok would if we're not at the end */ if (cp != NULL) *cp = '\0'; /* check if string is known or number and if so handle appropriately */ if (labels == 0 && (kem = synonyms_name2id(st, kemstrtab, OSSL_NELEM(kemstrtab))) == 0) goto fail; else if (labels == 1 && (kdf = synonyms_name2id(st, kdfstrtab, OSSL_NELEM(kdfstrtab))) == 0) goto fail; else if (labels == 2 && (aead = synonyms_name2id(st, aeadstrtab, OSSL_NELEM(aeadstrtab))) == 0) goto fail; if (cp == NULL) st = NULL; else st = cp + 1; ++labels; } if (st != NULL || labels != 3) goto fail; suite->kem_id = kem; suite->kdf_id = kdf; suite->aead_id = aead; result = 1; fail: OPENSSL_free(instrcp); return result; }
./openssl/crypto/ocsp/ocsp_lib.c
/* * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/ocsp.h> #include "ocsp_local.h" #include <openssl/asn1t.h> /* Convert a certificate and its issuer to an OCSP_CERTID */ OCSP_CERTID *OCSP_cert_to_id(const EVP_MD *dgst, const X509 *subject, const X509 *issuer) { const X509_NAME *iname; const ASN1_INTEGER *serial; ASN1_BIT_STRING *ikey; if (!dgst) dgst = EVP_sha1(); if (subject) { iname = X509_get_issuer_name(subject); serial = X509_get0_serialNumber(subject); } else { iname = X509_get_subject_name(issuer); serial = NULL; } ikey = X509_get0_pubkey_bitstr(issuer); return OCSP_cert_id_new(dgst, iname, ikey, serial); } OCSP_CERTID *OCSP_cert_id_new(const EVP_MD *dgst, const X509_NAME *issuerName, const ASN1_BIT_STRING *issuerKey, const ASN1_INTEGER *serialNumber) { int nid; unsigned int i; X509_ALGOR *alg; OCSP_CERTID *cid = NULL; unsigned char md[EVP_MAX_MD_SIZE]; if ((cid = OCSP_CERTID_new()) == NULL) goto err; alg = &cid->hashAlgorithm; ASN1_OBJECT_free(alg->algorithm); if ((nid = EVP_MD_get_type(dgst)) == NID_undef) { ERR_raise(ERR_LIB_OCSP, OCSP_R_UNKNOWN_NID); goto err; } if ((alg->algorithm = OBJ_nid2obj(nid)) == NULL) goto err; if ((alg->parameter = ASN1_TYPE_new()) == NULL) goto err; alg->parameter->type = V_ASN1_NULL; if (!X509_NAME_digest(issuerName, dgst, md, &i)) goto digerr; if (!(ASN1_OCTET_STRING_set(&cid->issuerNameHash, md, i))) goto err; /* Calculate the issuerKey hash, excluding tag and length */ if (!EVP_Digest(issuerKey->data, issuerKey->length, md, &i, dgst, NULL)) goto err; if (!(ASN1_OCTET_STRING_set(&cid->issuerKeyHash, md, i))) goto err; if (serialNumber) { if (ASN1_STRING_copy(&cid->serialNumber, serialNumber) == 0) goto err; } return cid; digerr: ERR_raise(ERR_LIB_OCSP, OCSP_R_DIGEST_ERR); err: OCSP_CERTID_free(cid); return NULL; } int OCSP_id_issuer_cmp(const OCSP_CERTID *a, const OCSP_CERTID *b) { int ret; ret = OBJ_cmp(a->hashAlgorithm.algorithm, b->hashAlgorithm.algorithm); if (ret) return ret; ret = ASN1_OCTET_STRING_cmp(&a->issuerNameHash, &b->issuerNameHash); if (ret) return ret; return ASN1_OCTET_STRING_cmp(&a->issuerKeyHash, &b->issuerKeyHash); } int OCSP_id_cmp(const OCSP_CERTID *a, const OCSP_CERTID *b) { int ret; ret = OCSP_id_issuer_cmp(a, b); if (ret) return ret; return ASN1_INTEGER_cmp(&a->serialNumber, &b->serialNumber); } IMPLEMENT_ASN1_DUP_FUNCTION(OCSP_CERTID)
./openssl/crypto/ocsp/ocsp_srv.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/ocsp.h> #include "ocsp_local.h" /* * Utility functions related to sending OCSP responses and extracting * relevant information from the request. */ int OCSP_request_onereq_count(OCSP_REQUEST *req) { return sk_OCSP_ONEREQ_num(req->tbsRequest.requestList); } OCSP_ONEREQ *OCSP_request_onereq_get0(OCSP_REQUEST *req, int i) { return sk_OCSP_ONEREQ_value(req->tbsRequest.requestList, i); } OCSP_CERTID *OCSP_onereq_get0_id(OCSP_ONEREQ *one) { return one->reqCert; } int OCSP_id_get0_info(ASN1_OCTET_STRING **piNameHash, ASN1_OBJECT **pmd, ASN1_OCTET_STRING **pikeyHash, ASN1_INTEGER **pserial, OCSP_CERTID *cid) { if (!cid) return 0; if (pmd) *pmd = cid->hashAlgorithm.algorithm; if (piNameHash) *piNameHash = &cid->issuerNameHash; if (pikeyHash) *pikeyHash = &cid->issuerKeyHash; if (pserial) *pserial = &cid->serialNumber; return 1; } int OCSP_request_is_signed(OCSP_REQUEST *req) { if (req->optionalSignature) return 1; return 0; } /* Create an OCSP response and encode an optional basic response */ OCSP_RESPONSE *OCSP_response_create(int status, OCSP_BASICRESP *bs) { OCSP_RESPONSE *rsp = NULL; if ((rsp = OCSP_RESPONSE_new()) == NULL) goto err; if (!(ASN1_ENUMERATED_set(rsp->responseStatus, status))) goto err; if (!bs) return rsp; if ((rsp->responseBytes = OCSP_RESPBYTES_new()) == NULL) goto err; rsp->responseBytes->responseType = OBJ_nid2obj(NID_id_pkix_OCSP_basic); if (!ASN1_item_pack (bs, ASN1_ITEM_rptr(OCSP_BASICRESP), &rsp->responseBytes->response)) goto err; return rsp; err: OCSP_RESPONSE_free(rsp); return NULL; } OCSP_SINGLERESP *OCSP_basic_add1_status(OCSP_BASICRESP *rsp, OCSP_CERTID *cid, int status, int reason, ASN1_TIME *revtime, ASN1_TIME *thisupd, ASN1_TIME *nextupd) { OCSP_SINGLERESP *single = NULL; OCSP_CERTSTATUS *cs; OCSP_REVOKEDINFO *ri; if (rsp->tbsResponseData.responses == NULL && (rsp->tbsResponseData.responses = sk_OCSP_SINGLERESP_new_null()) == NULL) goto err; if ((single = OCSP_SINGLERESP_new()) == NULL) goto err; if (!ASN1_TIME_to_generalizedtime(thisupd, &single->thisUpdate)) goto err; if (nextupd && !ASN1_TIME_to_generalizedtime(nextupd, &single->nextUpdate)) goto err; OCSP_CERTID_free(single->certId); if ((single->certId = OCSP_CERTID_dup(cid)) == NULL) goto err; cs = single->certStatus; switch (cs->type = status) { case V_OCSP_CERTSTATUS_REVOKED: if (!revtime) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NO_REVOKED_TIME); goto err; } if ((cs->value.revoked = ri = OCSP_REVOKEDINFO_new()) == NULL) goto err; if (!ASN1_TIME_to_generalizedtime(revtime, &ri->revocationTime)) goto err; if (reason != OCSP_REVOKED_STATUS_NOSTATUS) { if ((ri->revocationReason = ASN1_ENUMERATED_new()) == NULL) goto err; if (!(ASN1_ENUMERATED_set(ri->revocationReason, reason))) goto err; } break; case V_OCSP_CERTSTATUS_GOOD: if ((cs->value.good = ASN1_NULL_new()) == NULL) goto err; break; case V_OCSP_CERTSTATUS_UNKNOWN: if ((cs->value.unknown = ASN1_NULL_new()) == NULL) goto err; break; default: goto err; } if (!(sk_OCSP_SINGLERESP_push(rsp->tbsResponseData.responses, single))) goto err; return single; err: OCSP_SINGLERESP_free(single); return NULL; } /* Add a certificate to an OCSP request */ int OCSP_basic_add1_cert(OCSP_BASICRESP *resp, X509 *cert) { return ossl_x509_add_cert_new(&resp->certs, cert, X509_ADD_FLAG_UP_REF); } /* * Sign an OCSP response using the parameters contained in the digest context, * set the responderID to the subject name in the signer's certificate, and * include one or more optional certificates in the response. */ int OCSP_basic_sign_ctx(OCSP_BASICRESP *brsp, X509 *signer, EVP_MD_CTX *ctx, STACK_OF(X509) *certs, unsigned long flags) { OCSP_RESPID *rid; EVP_PKEY *pkey; if (ctx == NULL || EVP_MD_CTX_get_pkey_ctx(ctx) == NULL) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NO_SIGNER_KEY); goto err; } pkey = EVP_PKEY_CTX_get0_pkey(EVP_MD_CTX_get_pkey_ctx(ctx)); if (pkey == NULL || !X509_check_private_key(signer, pkey)) { ERR_raise(ERR_LIB_OCSP, OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE); goto err; } if (!(flags & OCSP_NOCERTS)) { if (!OCSP_basic_add1_cert(brsp, signer) || !X509_add_certs(brsp->certs, certs, X509_ADD_FLAG_UP_REF)) goto err; } rid = &brsp->tbsResponseData.responderId; if (flags & OCSP_RESPID_KEY) { if (!OCSP_RESPID_set_by_key(rid, signer)) goto err; } else if (!OCSP_RESPID_set_by_name(rid, signer)) { goto err; } if (!(flags & OCSP_NOTIME) && !X509_gmtime_adj(brsp->tbsResponseData.producedAt, 0)) goto err; /* * Right now, I think that not doing double hashing is the right thing. * -- Richard Levitte */ if (!OCSP_BASICRESP_sign_ctx(brsp, ctx, 0)) goto err; return 1; err: return 0; } int OCSP_basic_sign(OCSP_BASICRESP *brsp, X509 *signer, EVP_PKEY *key, const EVP_MD *dgst, STACK_OF(X509) *certs, unsigned long flags) { EVP_MD_CTX *ctx = EVP_MD_CTX_new(); EVP_PKEY_CTX *pkctx = NULL; int i; if (ctx == NULL) return 0; if (!EVP_DigestSignInit_ex(ctx, &pkctx, EVP_MD_get0_name(dgst), signer->libctx, signer->propq, key, NULL)) { EVP_MD_CTX_free(ctx); return 0; } i = OCSP_basic_sign_ctx(brsp, signer, ctx, certs, flags); EVP_MD_CTX_free(ctx); return i; } int OCSP_RESPID_set_by_name(OCSP_RESPID *respid, X509 *cert) { if (!X509_NAME_set(&respid->value.byName, X509_get_subject_name(cert))) return 0; respid->type = V_OCSP_RESPID_NAME; return 1; } int OCSP_RESPID_set_by_key_ex(OCSP_RESPID *respid, X509 *cert, OSSL_LIB_CTX *libctx, const char *propq) { ASN1_OCTET_STRING *byKey = NULL; unsigned char md[SHA_DIGEST_LENGTH]; EVP_MD *sha1 = EVP_MD_fetch(libctx, "SHA1", propq); int ret = 0; if (sha1 == NULL) return 0; /* RFC2560 requires SHA1 */ if (!X509_pubkey_digest(cert, sha1, md, NULL)) goto err; byKey = ASN1_OCTET_STRING_new(); if (byKey == NULL) goto err; if (!(ASN1_OCTET_STRING_set(byKey, md, SHA_DIGEST_LENGTH))) { ASN1_OCTET_STRING_free(byKey); goto err; } respid->type = V_OCSP_RESPID_KEY; respid->value.byKey = byKey; ret = 1; err: EVP_MD_free(sha1); return ret; } int OCSP_RESPID_set_by_key(OCSP_RESPID *respid, X509 *cert) { if (cert == NULL) return 0; return OCSP_RESPID_set_by_key_ex(respid, cert, cert->libctx, cert->propq); } int OCSP_RESPID_match_ex(OCSP_RESPID *respid, X509 *cert, OSSL_LIB_CTX *libctx, const char *propq) { EVP_MD *sha1 = NULL; int ret = 0; if (respid->type == V_OCSP_RESPID_KEY) { unsigned char md[SHA_DIGEST_LENGTH]; sha1 = EVP_MD_fetch(libctx, "SHA1", propq); if (sha1 == NULL) goto err; if (respid->value.byKey == NULL) goto err; /* RFC2560 requires SHA1 */ if (!X509_pubkey_digest(cert, sha1, md, NULL)) goto err; ret = (ASN1_STRING_length(respid->value.byKey) == SHA_DIGEST_LENGTH) && (memcmp(ASN1_STRING_get0_data(respid->value.byKey), md, SHA_DIGEST_LENGTH) == 0); } else if (respid->type == V_OCSP_RESPID_NAME) { if (respid->value.byName == NULL) return 0; return X509_NAME_cmp(respid->value.byName, X509_get_subject_name(cert)) == 0; } err: EVP_MD_free(sha1); return ret; } int OCSP_RESPID_match(OCSP_RESPID *respid, X509 *cert) { if (cert == NULL) return 0; return OCSP_RESPID_match_ex(respid, cert, cert->libctx, cert->propq); }
./openssl/crypto/ocsp/ocsp_prn.c
/* * Copyright 2000-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/ocsp.h> #include "ocsp_local.h" #include "internal/cryptlib.h" #include <openssl/pem.h> static int ocsp_certid_print(BIO *bp, OCSP_CERTID *a, int indent) { BIO_printf(bp, "%*sCertificate ID:\n", indent, ""); indent += 2; BIO_printf(bp, "%*sHash Algorithm: ", indent, ""); i2a_ASN1_OBJECT(bp, a->hashAlgorithm.algorithm); BIO_printf(bp, "\n%*sIssuer Name Hash: ", indent, ""); i2a_ASN1_STRING(bp, &a->issuerNameHash, 0); BIO_printf(bp, "\n%*sIssuer Key Hash: ", indent, ""); i2a_ASN1_STRING(bp, &a->issuerKeyHash, 0); BIO_printf(bp, "\n%*sSerial Number: ", indent, ""); i2a_ASN1_INTEGER(bp, &a->serialNumber); BIO_printf(bp, "\n"); return 1; } typedef struct { long t; const char *m; } OCSP_TBLSTR; static const char *do_table2string(long s, const OCSP_TBLSTR *ts, size_t len) { size_t i; for (i = 0; i < len; i++, ts++) if (ts->t == s) return ts->m; return "(UNKNOWN)"; } #define table2string(s, tbl) do_table2string(s, tbl, OSSL_NELEM(tbl)) const char *OCSP_response_status_str(long s) { static const OCSP_TBLSTR rstat_tbl[] = { {OCSP_RESPONSE_STATUS_SUCCESSFUL, "successful"}, {OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, "malformedrequest"}, {OCSP_RESPONSE_STATUS_INTERNALERROR, "internalerror"}, {OCSP_RESPONSE_STATUS_TRYLATER, "trylater"}, {OCSP_RESPONSE_STATUS_SIGREQUIRED, "sigrequired"}, {OCSP_RESPONSE_STATUS_UNAUTHORIZED, "unauthorized"} }; return table2string(s, rstat_tbl); } const char *OCSP_cert_status_str(long s) { static const OCSP_TBLSTR cstat_tbl[] = { {V_OCSP_CERTSTATUS_GOOD, "good"}, {V_OCSP_CERTSTATUS_REVOKED, "revoked"}, {V_OCSP_CERTSTATUS_UNKNOWN, "unknown"} }; return table2string(s, cstat_tbl); } const char *OCSP_crl_reason_str(long s) { static const OCSP_TBLSTR reason_tbl[] = { {OCSP_REVOKED_STATUS_UNSPECIFIED, "unspecified"}, {OCSP_REVOKED_STATUS_KEYCOMPROMISE, "keyCompromise"}, {OCSP_REVOKED_STATUS_CACOMPROMISE, "cACompromise"}, {OCSP_REVOKED_STATUS_AFFILIATIONCHANGED, "affiliationChanged"}, {OCSP_REVOKED_STATUS_SUPERSEDED, "superseded"}, {OCSP_REVOKED_STATUS_CESSATIONOFOPERATION, "cessationOfOperation"}, {OCSP_REVOKED_STATUS_CERTIFICATEHOLD, "certificateHold"}, {OCSP_REVOKED_STATUS_REMOVEFROMCRL, "removeFromCRL"}, {OCSP_REVOKED_STATUS_PRIVILEGEWITHDRAWN, "privilegeWithdrawn"}, {OCSP_REVOKED_STATUS_AACOMPROMISE, "aACompromise"} }; return table2string(s, reason_tbl); } int OCSP_REQUEST_print(BIO *bp, OCSP_REQUEST *o, unsigned long flags) { int i; long l; OCSP_CERTID *cid = NULL; OCSP_ONEREQ *one = NULL; OCSP_REQINFO *inf = &o->tbsRequest; OCSP_SIGNATURE *sig = o->optionalSignature; if (BIO_write(bp, "OCSP Request Data:\n", 19) <= 0) goto err; l = ASN1_INTEGER_get(inf->version); if (BIO_printf(bp, " Version: %lu (0x%lx)", l + 1, l) <= 0) goto err; if (inf->requestorName != NULL) { if (BIO_write(bp, "\n Requestor Name: ", 21) <= 0) goto err; GENERAL_NAME_print(bp, inf->requestorName); } if (BIO_write(bp, "\n Requestor List:\n", 21) <= 0) goto err; for (i = 0; i < sk_OCSP_ONEREQ_num(inf->requestList); i++) { one = sk_OCSP_ONEREQ_value(inf->requestList, i); cid = one->reqCert; ocsp_certid_print(bp, cid, 8); if (!X509V3_extensions_print(bp, "Request Single Extensions", one->singleRequestExtensions, flags, 8)) goto err; } if (!X509V3_extensions_print(bp, "Request Extensions", inf->requestExtensions, flags, 4)) goto err; if (sig) { X509_signature_print(bp, &sig->signatureAlgorithm, sig->signature); for (i = 0; i < sk_X509_num(sig->certs); i++) { X509_print(bp, sk_X509_value(sig->certs, i)); PEM_write_bio_X509(bp, sk_X509_value(sig->certs, i)); } } return 1; err: return 0; } int OCSP_RESPONSE_print(BIO *bp, OCSP_RESPONSE *o, unsigned long flags) { int i, ret = 0; long l; OCSP_CERTID *cid = NULL; OCSP_BASICRESP *br = NULL; OCSP_RESPID *rid = NULL; OCSP_RESPDATA *rd = NULL; OCSP_CERTSTATUS *cst = NULL; OCSP_REVOKEDINFO *rev = NULL; OCSP_SINGLERESP *single = NULL; OCSP_RESPBYTES *rb = o->responseBytes; if (BIO_puts(bp, "OCSP Response Data:\n") <= 0) goto err; l = ASN1_ENUMERATED_get(o->responseStatus); if (BIO_printf(bp, " OCSP Response Status: %s (0x%lx)\n", OCSP_response_status_str(l), l) <= 0) goto err; if (rb == NULL) return 1; if (BIO_puts(bp, " Response Type: ") <= 0) goto err; if (i2a_ASN1_OBJECT(bp, rb->responseType) <= 0) goto err; if (OBJ_obj2nid(rb->responseType) != NID_id_pkix_OCSP_basic) { BIO_puts(bp, " (unknown response type)\n"); return 1; } if ((br = OCSP_response_get1_basic(o)) == NULL) goto err; rd = &br->tbsResponseData; l = ASN1_INTEGER_get(rd->version); if (BIO_printf(bp, "\n Version: %lu (0x%lx)\n", l + 1, l) <= 0) goto err; if (BIO_puts(bp, " Responder Id: ") <= 0) goto err; rid = &rd->responderId; switch (rid->type) { case V_OCSP_RESPID_NAME: X509_NAME_print_ex(bp, rid->value.byName, 0, XN_FLAG_ONELINE); break; case V_OCSP_RESPID_KEY: i2a_ASN1_STRING(bp, rid->value.byKey, 0); break; } if (BIO_printf(bp, "\n Produced At: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, rd->producedAt)) goto err; if (BIO_printf(bp, "\n Responses:\n") <= 0) goto err; for (i = 0; i < sk_OCSP_SINGLERESP_num(rd->responses); i++) { if (!sk_OCSP_SINGLERESP_value(rd->responses, i)) continue; single = sk_OCSP_SINGLERESP_value(rd->responses, i); cid = single->certId; if (ocsp_certid_print(bp, cid, 4) <= 0) goto err; cst = single->certStatus; if (BIO_printf(bp, " Cert Status: %s", OCSP_cert_status_str(cst->type)) <= 0) goto err; if (cst->type == V_OCSP_CERTSTATUS_REVOKED) { rev = cst->value.revoked; if (BIO_printf(bp, "\n Revocation Time: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, rev->revocationTime)) goto err; if (rev->revocationReason) { l = ASN1_ENUMERATED_get(rev->revocationReason); if (BIO_printf(bp, "\n Revocation Reason: %s (0x%lx)", OCSP_crl_reason_str(l), l) <= 0) goto err; } } if (BIO_printf(bp, "\n This Update: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, single->thisUpdate)) goto err; if (single->nextUpdate) { if (BIO_printf(bp, "\n Next Update: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, single->nextUpdate)) goto err; } if (BIO_write(bp, "\n", 1) <= 0) goto err; if (!X509V3_extensions_print(bp, "Response Single Extensions", single->singleExtensions, flags, 8)) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (!X509V3_extensions_print(bp, "Response Extensions", rd->responseExtensions, flags, 4)) goto err; if (X509_signature_print(bp, &br->signatureAlgorithm, br->signature) <= 0) goto err; for (i = 0; i < sk_X509_num(br->certs); i++) { X509_print(bp, sk_X509_value(br->certs, i)); PEM_write_bio_X509(bp, sk_X509_value(br->certs, i)); } ret = 1; err: OCSP_BASICRESP_free(br); return ret; }
./openssl/crypto/ocsp/ocsp_http.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/ocsp.h> #include <openssl/http.h> #ifndef OPENSSL_NO_OCSP OSSL_HTTP_REQ_CTX *OCSP_sendreq_new(BIO *io, const char *path, const OCSP_REQUEST *req, int buf_size) { OSSL_HTTP_REQ_CTX *rctx = OSSL_HTTP_REQ_CTX_new(io, io, buf_size); if (rctx == NULL) return NULL; /*- * by default: * no bio_update_fn (and consequently no arg) * no ssl * no proxy * no timeout (blocking indefinitely) * no expected content type * max_resp_len = 100 KiB */ if (!OSSL_HTTP_REQ_CTX_set_request_line(rctx, 1 /* POST */, NULL, NULL, path)) goto err; /* by default, no extra headers */ if (!OSSL_HTTP_REQ_CTX_set_expected(rctx, NULL /* content_type */, 1 /* asn1 */, 0 /* timeout */, 0 /* keep_alive */)) goto err; if (req != NULL && !OSSL_HTTP_REQ_CTX_set1_req(rctx, "application/ocsp-request", ASN1_ITEM_rptr(OCSP_REQUEST), (const ASN1_VALUE *)req)) goto err; return rctx; err: OSSL_HTTP_REQ_CTX_free(rctx); return NULL; } OCSP_RESPONSE *OCSP_sendreq_bio(BIO *b, const char *path, OCSP_REQUEST *req) { OCSP_RESPONSE *resp = NULL; OSSL_HTTP_REQ_CTX *ctx; BIO *mem; ctx = OCSP_sendreq_new(b, path, req, 0 /* default buf_size */); if (ctx == NULL) return NULL; mem = OSSL_HTTP_REQ_CTX_exchange(ctx); /* ASN1_item_d2i_bio handles NULL bio gracefully */ resp = (OCSP_RESPONSE *)ASN1_item_d2i_bio(ASN1_ITEM_rptr(OCSP_RESPONSE), mem, NULL); OSSL_HTTP_REQ_CTX_free(ctx); return resp; } #endif /* !defined(OPENSSL_NO_OCSP) */
./openssl/crypto/ocsp/ocsp_vfy.c
/* * Copyright 2001-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/ocsp.h> #include <openssl/err.h> #include "internal/sizes.h" #include "ocsp_local.h" static int ocsp_find_signer(X509 **psigner, OCSP_BASICRESP *bs, STACK_OF(X509) *certs, unsigned long flags); static X509 *ocsp_find_signer_sk(STACK_OF(X509) *certs, OCSP_RESPID *id); static int ocsp_check_issuer(OCSP_BASICRESP *bs, STACK_OF(X509) *chain); static int ocsp_check_ids(STACK_OF(OCSP_SINGLERESP) *sresp, OCSP_CERTID **ret); static int ocsp_match_issuerid(X509 *cert, OCSP_CERTID *cid, STACK_OF(OCSP_SINGLERESP) *sresp); static int ocsp_check_delegated(X509 *x); static int ocsp_req_find_signer(X509 **psigner, OCSP_REQUEST *req, const X509_NAME *nm, STACK_OF(X509) *certs, unsigned long flags); /* Returns 1 on success, 0 on failure, or -1 on fatal error */ static int ocsp_verify_signer(X509 *signer, int response, X509_STORE *st, unsigned long flags, STACK_OF(X509) *untrusted, STACK_OF(X509) **chain) { X509_STORE_CTX *ctx = X509_STORE_CTX_new(); X509_VERIFY_PARAM *vp; int ret = -1; if (ctx == NULL) { ERR_raise(ERR_LIB_OCSP, ERR_R_X509_LIB); goto end; } if (!X509_STORE_CTX_init(ctx, st, signer, untrusted)) { ERR_raise(ERR_LIB_OCSP, ERR_R_X509_LIB); goto end; } if ((vp = X509_STORE_CTX_get0_param(ctx)) == NULL) goto end; if ((flags & OCSP_PARTIAL_CHAIN) != 0) X509_VERIFY_PARAM_set_flags(vp, X509_V_FLAG_PARTIAL_CHAIN); if (response && X509_get_ext_by_NID(signer, NID_id_pkix_OCSP_noCheck, -1) >= 0) /* * Locally disable revocation status checking for OCSP responder cert. * Done here for CRLs; should be done also for OCSP-based checks. */ X509_VERIFY_PARAM_clear_flags(vp, X509_V_FLAG_CRL_CHECK); X509_STORE_CTX_set_purpose(ctx, X509_PURPOSE_OCSP_HELPER); X509_STORE_CTX_set_trust(ctx, X509_TRUST_OCSP_REQUEST); ret = X509_verify_cert(ctx); if (ret <= 0) { int err = X509_STORE_CTX_get_error(ctx); ERR_raise_data(ERR_LIB_OCSP, OCSP_R_CERTIFICATE_VERIFY_ERROR, "Verify error: %s", X509_verify_cert_error_string(err)); goto end; } if (chain != NULL) *chain = X509_STORE_CTX_get1_chain(ctx); end: X509_STORE_CTX_free(ctx); return ret; } static int ocsp_verify(OCSP_REQUEST *req, OCSP_BASICRESP *bs, X509 *signer, unsigned long flags) { EVP_PKEY *skey; int ret = 1; if ((flags & OCSP_NOSIGS) == 0) { if ((skey = X509_get0_pubkey(signer)) == NULL) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NO_SIGNER_KEY); return -1; } if (req != NULL) ret = OCSP_REQUEST_verify(req, skey, signer->libctx, signer->propq); else ret = OCSP_BASICRESP_verify(bs, skey, signer->libctx, signer->propq); if (ret <= 0) ERR_raise(ERR_LIB_OCSP, OCSP_R_SIGNATURE_FAILURE); } return ret; } /* Verify a basic response message */ int OCSP_basic_verify(OCSP_BASICRESP *bs, STACK_OF(X509) *certs, X509_STORE *st, unsigned long flags) { X509 *signer, *x; STACK_OF(X509) *chain = NULL; STACK_OF(X509) *untrusted = NULL; int ret = ocsp_find_signer(&signer, bs, certs, flags); if (ret == 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND); goto end; } if ((ret == 2) && (flags & OCSP_TRUSTOTHER) != 0) flags |= OCSP_NOVERIFY; if ((ret = ocsp_verify(NULL, bs, signer, flags)) <= 0) goto end; if ((flags & OCSP_NOVERIFY) == 0) { ret = -1; if ((flags & OCSP_NOCHAIN) == 0) { if ((untrusted = sk_X509_dup(bs->certs)) == NULL) goto end; if (!X509_add_certs(untrusted, certs, X509_ADD_FLAG_DEFAULT)) goto end; } ret = ocsp_verify_signer(signer, 1, st, flags, untrusted, &chain); if (ret <= 0) goto end; if ((flags & OCSP_NOCHECKS) != 0) { ret = 1; goto end; } /* * At this point we have a valid certificate chain need to verify it * against the OCSP issuer criteria. */ ret = ocsp_check_issuer(bs, chain); /* If fatal error or valid match then finish */ if (ret != 0) goto end; /* * Easy case: explicitly trusted. Get root CA and check for explicit * trust */ if ((flags & OCSP_NOEXPLICIT) != 0) goto end; x = sk_X509_value(chain, sk_X509_num(chain) - 1); if (X509_check_trust(x, NID_OCSP_sign, 0) != X509_TRUST_TRUSTED) { ERR_raise(ERR_LIB_OCSP, OCSP_R_ROOT_CA_NOT_TRUSTED); ret = 0; goto end; } ret = 1; } end: OSSL_STACK_OF_X509_free(chain); sk_X509_free(untrusted); return ret; } int OCSP_resp_get0_signer(OCSP_BASICRESP *bs, X509 **signer, STACK_OF(X509) *extra_certs) { return ocsp_find_signer(signer, bs, extra_certs, 0) > 0; } static int ocsp_find_signer(X509 **psigner, OCSP_BASICRESP *bs, STACK_OF(X509) *certs, unsigned long flags) { X509 *signer; OCSP_RESPID *rid = &bs->tbsResponseData.responderId; if ((signer = ocsp_find_signer_sk(certs, rid)) != NULL) { *psigner = signer; return 2; } if ((flags & OCSP_NOINTERN) == 0 && (signer = ocsp_find_signer_sk(bs->certs, rid))) { *psigner = signer; return 1; } /* Maybe lookup from store if by subject name */ *psigner = NULL; return 0; } static X509 *ocsp_find_signer_sk(STACK_OF(X509) *certs, OCSP_RESPID *id) { int i, r; unsigned char tmphash[SHA_DIGEST_LENGTH], *keyhash; EVP_MD *md; X509 *x; /* Easy if lookup by name */ if (id->type == V_OCSP_RESPID_NAME) return X509_find_by_subject(certs, id->value.byName); /* Lookup by key hash */ /* If key hash isn't SHA1 length then forget it */ if (id->value.byKey->length != SHA_DIGEST_LENGTH) return NULL; keyhash = id->value.byKey->data; /* Calculate hash of each key and compare */ for (i = 0; i < sk_X509_num(certs); i++) { if ((x = sk_X509_value(certs, i)) != NULL) { if ((md = EVP_MD_fetch(x->libctx, SN_sha1, x->propq)) == NULL) break; r = X509_pubkey_digest(x, md, tmphash, NULL); EVP_MD_free(md); if (!r) break; if (memcmp(keyhash, tmphash, SHA_DIGEST_LENGTH) == 0) return x; } } return NULL; } static int ocsp_check_issuer(OCSP_BASICRESP *bs, STACK_OF(X509) *chain) { STACK_OF(OCSP_SINGLERESP) *sresp = bs->tbsResponseData.responses; X509 *signer, *sca; OCSP_CERTID *caid = NULL; int ret; if (sk_X509_num(chain) <= 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NO_CERTIFICATES_IN_CHAIN); return -1; } /* See if the issuer IDs match. */ ret = ocsp_check_ids(sresp, &caid); /* If ID mismatch or other error then return */ if (ret <= 0) return ret; signer = sk_X509_value(chain, 0); /* Check to see if OCSP responder CA matches request CA */ if (sk_X509_num(chain) > 1) { sca = sk_X509_value(chain, 1); ret = ocsp_match_issuerid(sca, caid, sresp); if (ret < 0) return ret; if (ret != 0) { /* We have a match, if extensions OK then success */ if (ocsp_check_delegated(signer)) return 1; return 0; } } /* Otherwise check if OCSP request signed directly by request CA */ return ocsp_match_issuerid(signer, caid, sresp); } /* * Check the issuer certificate IDs for equality. If there is a mismatch with * the same algorithm then there's no point trying to match any certificates * against the issuer. If the issuer IDs all match then we just need to check * equality against one of them. */ static int ocsp_check_ids(STACK_OF(OCSP_SINGLERESP) *sresp, OCSP_CERTID **ret) { OCSP_CERTID *tmpid, *cid; int i, idcount; idcount = sk_OCSP_SINGLERESP_num(sresp); if (idcount <= 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_RESPONSE_CONTAINS_NO_REVOCATION_DATA); return -1; } cid = sk_OCSP_SINGLERESP_value(sresp, 0)->certId; *ret = NULL; for (i = 1; i < idcount; i++) { tmpid = sk_OCSP_SINGLERESP_value(sresp, i)->certId; /* Check to see if IDs match */ if (OCSP_id_issuer_cmp(cid, tmpid)) { /* If algorithm mismatch let caller deal with it */ if (OBJ_cmp(tmpid->hashAlgorithm.algorithm, cid->hashAlgorithm.algorithm)) return 2; /* Else mismatch */ return 0; } } /* All IDs match: only need to check one ID */ *ret = cid; return 1; } /* * Match the certificate issuer ID. * Returns -1 on fatal error, 0 if there is no match and 1 if there is a match. */ static int ocsp_match_issuerid(X509 *cert, OCSP_CERTID *cid, STACK_OF(OCSP_SINGLERESP) *sresp) { int ret = -1; EVP_MD *dgst = NULL; /* If only one ID to match then do it */ if (cid != NULL) { char name[OSSL_MAX_NAME_SIZE]; const X509_NAME *iname; int mdlen; unsigned char md[EVP_MAX_MD_SIZE]; OBJ_obj2txt(name, sizeof(name), cid->hashAlgorithm.algorithm, 0); (void)ERR_set_mark(); dgst = EVP_MD_fetch(NULL, name, NULL); if (dgst == NULL) dgst = (EVP_MD *)EVP_get_digestbyname(name); if (dgst == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_OCSP, OCSP_R_UNKNOWN_MESSAGE_DIGEST); goto end; } (void)ERR_pop_to_mark(); mdlen = EVP_MD_get_size(dgst); if (mdlen < 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_DIGEST_SIZE_ERR); goto end; } if (cid->issuerNameHash.length != mdlen || cid->issuerKeyHash.length != mdlen) { ret = 0; goto end; } iname = X509_get_subject_name(cert); if (!X509_NAME_digest(iname, dgst, md, NULL)) goto end; if (memcmp(md, cid->issuerNameHash.data, mdlen) != 0) { ret = 0; goto end; } if (!X509_pubkey_digest(cert, dgst, md, NULL)) { ERR_raise(ERR_LIB_OCSP, OCSP_R_DIGEST_ERR); goto end; } ret = memcmp(md, cid->issuerKeyHash.data, mdlen) == 0; goto end; } else { /* We have to match the whole lot */ int i; OCSP_CERTID *tmpid; for (i = 0; i < sk_OCSP_SINGLERESP_num(sresp); i++) { tmpid = sk_OCSP_SINGLERESP_value(sresp, i)->certId; ret = ocsp_match_issuerid(cert, tmpid, NULL); if (ret <= 0) return ret; } } return 1; end: EVP_MD_free(dgst); return ret; } static int ocsp_check_delegated(X509 *x) { if ((X509_get_extension_flags(x) & EXFLAG_XKUSAGE) && (X509_get_extended_key_usage(x) & XKU_OCSP_SIGN)) return 1; ERR_raise(ERR_LIB_OCSP, OCSP_R_MISSING_OCSPSIGNING_USAGE); return 0; } /* * Verify an OCSP request. This is much easier than OCSP response verify. * Just find the signer's certificate and verify it against a given trust value. * Returns 1 on success, 0 on failure and on fatal error. */ int OCSP_request_verify(OCSP_REQUEST *req, STACK_OF(X509) *certs, X509_STORE *store, unsigned long flags) { X509 *signer; const X509_NAME *nm; GENERAL_NAME *gen; int ret; if (!req->optionalSignature) { ERR_raise(ERR_LIB_OCSP, OCSP_R_REQUEST_NOT_SIGNED); return 0; } gen = req->tbsRequest.requestorName; if (!gen || gen->type != GEN_DIRNAME) { ERR_raise(ERR_LIB_OCSP, OCSP_R_UNSUPPORTED_REQUESTORNAME_TYPE); return 0; /* not returning -1 here for backward compatibility*/ } nm = gen->d.directoryName; ret = ocsp_req_find_signer(&signer, req, nm, certs, flags); if (ret <= 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND); return 0; /* not returning -1 here for backward compatibility*/ } if ((ret == 2) && (flags & OCSP_TRUSTOTHER) != 0) flags |= OCSP_NOVERIFY; if ((ret = ocsp_verify(req, NULL, signer, flags)) <= 0) return 0; /* not returning 'ret' here for backward compatibility*/ if ((flags & OCSP_NOVERIFY) != 0) return 1; return ocsp_verify_signer(signer, 0, store, flags, (flags & OCSP_NOCHAIN) != 0 ? NULL : req->optionalSignature->certs, NULL) > 0; /* using '> 0' here to avoid breaking backward compatibility returning -1 */ } static int ocsp_req_find_signer(X509 **psigner, OCSP_REQUEST *req, const X509_NAME *nm, STACK_OF(X509) *certs, unsigned long flags) { X509 *signer; if ((flags & OCSP_NOINTERN) == 0) { signer = X509_find_by_subject(req->optionalSignature->certs, nm); if (signer != NULL) { *psigner = signer; return 1; } } if ((signer = X509_find_by_subject(certs, nm)) != NULL) { *psigner = signer; return 2; } return 0; }
./openssl/crypto/ocsp/v3_ocsp.c
/* * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/asn1.h> #include <openssl/ocsp.h> #include "ocsp_local.h" #include <openssl/x509v3.h> #include "../x509/ext_dat.h" /* * OCSP extensions and a couple of CRL entry extensions */ static int i2r_ocsp_crlid(const X509V3_EXT_METHOD *method, void *nonce, BIO *out, int indent); static int i2r_ocsp_acutoff(const X509V3_EXT_METHOD *method, void *nonce, BIO *out, int indent); static int i2r_object(const X509V3_EXT_METHOD *method, void *obj, BIO *out, int indent); static void *ocsp_nonce_new(void); static int i2d_ocsp_nonce(const void *a, unsigned char **pp); static void *d2i_ocsp_nonce(void *a, const unsigned char **pp, long length); static void ocsp_nonce_free(void *a); static int i2r_ocsp_nonce(const X509V3_EXT_METHOD *method, void *nonce, BIO *out, int indent); static int i2r_ocsp_nocheck(const X509V3_EXT_METHOD *method, void *nocheck, BIO *out, int indent); static void *s2i_ocsp_nocheck(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str); static int i2r_ocsp_serviceloc(const X509V3_EXT_METHOD *method, void *in, BIO *bp, int ind); const X509V3_EXT_METHOD ossl_v3_ocsp_crlid = { NID_id_pkix_OCSP_CrlID, 0, ASN1_ITEM_ref(OCSP_CRLID), 0, 0, 0, 0, 0, 0, 0, 0, i2r_ocsp_crlid, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_ocsp_acutoff = { NID_id_pkix_OCSP_archiveCutoff, 0, ASN1_ITEM_ref(ASN1_GENERALIZEDTIME), 0, 0, 0, 0, 0, 0, 0, 0, i2r_ocsp_acutoff, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_crl_invdate = { NID_invalidity_date, 0, ASN1_ITEM_ref(ASN1_GENERALIZEDTIME), 0, 0, 0, 0, 0, 0, 0, 0, i2r_ocsp_acutoff, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_crl_hold = { NID_hold_instruction_code, 0, ASN1_ITEM_ref(ASN1_OBJECT), 0, 0, 0, 0, 0, 0, 0, 0, i2r_object, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_ocsp_nonce = { NID_id_pkix_OCSP_Nonce, 0, NULL, ocsp_nonce_new, ocsp_nonce_free, d2i_ocsp_nonce, i2d_ocsp_nonce, 0, 0, 0, 0, i2r_ocsp_nonce, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_ocsp_nocheck = { NID_id_pkix_OCSP_noCheck, 0, ASN1_ITEM_ref(ASN1_NULL), 0, 0, 0, 0, 0, s2i_ocsp_nocheck, 0, 0, i2r_ocsp_nocheck, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_ocsp_serviceloc = { NID_id_pkix_OCSP_serviceLocator, 0, ASN1_ITEM_ref(OCSP_SERVICELOC), 0, 0, 0, 0, 0, 0, 0, 0, i2r_ocsp_serviceloc, 0, NULL }; static int i2r_ocsp_crlid(const X509V3_EXT_METHOD *method, void *in, BIO *bp, int ind) { OCSP_CRLID *a = in; if (a->crlUrl) { if (BIO_printf(bp, "%*scrlUrl: ", ind, "") <= 0) goto err; if (!ASN1_STRING_print(bp, (ASN1_STRING *)a->crlUrl)) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (a->crlNum) { if (BIO_printf(bp, "%*scrlNum: ", ind, "") <= 0) goto err; if (i2a_ASN1_INTEGER(bp, a->crlNum) <= 0) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (a->crlTime) { if (BIO_printf(bp, "%*scrlTime: ", ind, "") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, a->crlTime)) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } return 1; err: return 0; } static int i2r_ocsp_acutoff(const X509V3_EXT_METHOD *method, void *cutoff, BIO *bp, int ind) { if (BIO_printf(bp, "%*s", ind, "") <= 0) return 0; if (!ASN1_GENERALIZEDTIME_print(bp, cutoff)) return 0; return 1; } static int i2r_object(const X509V3_EXT_METHOD *method, void *oid, BIO *bp, int ind) { if (BIO_printf(bp, "%*s", ind, "") <= 0) return 0; if (i2a_ASN1_OBJECT(bp, oid) <= 0) return 0; return 1; } /* * OCSP nonce. This is needs special treatment because it doesn't have an * ASN1 encoding at all: it just contains arbitrary data. */ static void *ocsp_nonce_new(void) { return ASN1_OCTET_STRING_new(); } static int i2d_ocsp_nonce(const void *a, unsigned char **pp) { const ASN1_OCTET_STRING *os = a; if (pp) { memcpy(*pp, os->data, os->length); *pp += os->length; } return os->length; } static void *d2i_ocsp_nonce(void *a, const unsigned char **pp, long length) { ASN1_OCTET_STRING *os, **pos; pos = a; if (pos == NULL || *pos == NULL) { os = ASN1_OCTET_STRING_new(); if (os == NULL) goto err; } else { os = *pos; } if (!ASN1_OCTET_STRING_set(os, *pp, length)) goto err; *pp += length; if (pos) *pos = os; return os; err: if ((pos == NULL) || (*pos != os)) ASN1_OCTET_STRING_free(os); ERR_raise(ERR_LIB_OCSP, ERR_R_ASN1_LIB); return NULL; } static void ocsp_nonce_free(void *a) { ASN1_OCTET_STRING_free(a); } static int i2r_ocsp_nonce(const X509V3_EXT_METHOD *method, void *nonce, BIO *out, int indent) { if (BIO_printf(out, "%*s", indent, "") <= 0) return 0; if (i2a_ASN1_STRING(out, nonce, V_ASN1_OCTET_STRING) <= 0) return 0; return 1; } /* Nocheck is just a single NULL. Don't print anything and always set it */ static int i2r_ocsp_nocheck(const X509V3_EXT_METHOD *method, void *nocheck, BIO *out, int indent) { return 1; } static void *s2i_ocsp_nocheck(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str) { return ASN1_NULL_new(); } static int i2r_ocsp_serviceloc(const X509V3_EXT_METHOD *method, void *in, BIO *bp, int ind) { int i; OCSP_SERVICELOC *a = in; ACCESS_DESCRIPTION *ad; if (BIO_printf(bp, "%*sIssuer: ", ind, "") <= 0) goto err; if (X509_NAME_print_ex(bp, a->issuer, 0, XN_FLAG_ONELINE) <= 0) goto err; for (i = 0; i < sk_ACCESS_DESCRIPTION_num(a->locator); i++) { ad = sk_ACCESS_DESCRIPTION_value(a->locator, i); if (BIO_printf(bp, "\n%*s", (2 * ind), "") <= 0) goto err; if (i2a_ASN1_OBJECT(bp, ad->method) <= 0) goto err; if (BIO_puts(bp, " - ") <= 0) goto err; if (GENERAL_NAME_print(bp, ad->location) <= 0) goto err; } return 1; err: return 0; }
./openssl/crypto/ocsp/ocsp_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/ocsperr.h> #include "crypto/ocsperr.h" #ifndef OPENSSL_NO_OCSP # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA OCSP_str_reasons[] = { {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_CERTIFICATE_VERIFY_ERROR), "certificate verify error"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_DIGEST_ERR), "digest err"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_DIGEST_NAME_ERR), "digest name err"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_DIGEST_SIZE_ERR), "digest size err"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_ERROR_IN_NEXTUPDATE_FIELD), "error in nextupdate field"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_ERROR_IN_THISUPDATE_FIELD), "error in thisupdate field"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_MISSING_OCSPSIGNING_USAGE), "missing ocspsigning usage"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NEXTUPDATE_BEFORE_THISUPDATE), "nextupdate before thisupdate"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NOT_BASIC_RESPONSE), "not basic response"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_CERTIFICATES_IN_CHAIN), "no certificates in chain"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_RESPONSE_DATA), "no response data"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_REVOKED_TIME), "no revoked time"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_SIGNER_KEY), "no signer key"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), "private key does not match certificate"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_REQUEST_NOT_SIGNED), "request not signed"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_RESPONSE_CONTAINS_NO_REVOCATION_DATA), "response contains no revocation data"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_ROOT_CA_NOT_TRUSTED), "root ca not trusted"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_SIGNATURE_FAILURE), "signature failure"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND), "signer certificate not found"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_STATUS_EXPIRED), "status expired"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_STATUS_NOT_YET_VALID), "status not yet valid"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_STATUS_TOO_OLD), "status too old"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_UNKNOWN_MESSAGE_DIGEST), "unknown message digest"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_UNKNOWN_NID), "unknown nid"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_UNSUPPORTED_REQUESTORNAME_TYPE), "unsupported requestorname type"}, {0, NULL} }; # endif int ossl_err_load_OCSP_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(OCSP_str_reasons[0].error) == NULL) ERR_load_strings_const(OCSP_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
./openssl/crypto/ocsp/ocsp_cl.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/ocsp.h> #include "ocsp_local.h" /* * Utility functions related to sending OCSP requests and extracting relevant * information from the response. */ /* * Add an OCSP_CERTID to an OCSP request. Return new OCSP_ONEREQ pointer: * useful if we want to add extensions. */ OCSP_ONEREQ *OCSP_request_add0_id(OCSP_REQUEST *req, OCSP_CERTID *cid) { OCSP_ONEREQ *one = NULL; if ((one = OCSP_ONEREQ_new()) == NULL) return NULL; OCSP_CERTID_free(one->reqCert); one->reqCert = cid; if (req && !sk_OCSP_ONEREQ_push(req->tbsRequest.requestList, one)) { one->reqCert = NULL; /* do not free on error */ OCSP_ONEREQ_free(one); return NULL; } return one; } /* Set requestorName from an X509_NAME structure */ int OCSP_request_set1_name(OCSP_REQUEST *req, const X509_NAME *nm) { GENERAL_NAME *gen = GENERAL_NAME_new(); if (gen == NULL) return 0; if (!X509_NAME_set(&gen->d.directoryName, nm)) { GENERAL_NAME_free(gen); return 0; } gen->type = GEN_DIRNAME; GENERAL_NAME_free(req->tbsRequest.requestorName); req->tbsRequest.requestorName = gen; return 1; } /* Add a certificate to an OCSP request */ int OCSP_request_add1_cert(OCSP_REQUEST *req, X509 *cert) { if (req->optionalSignature == NULL && (req->optionalSignature = OCSP_SIGNATURE_new()) == NULL) return 0; if (cert == NULL) return 1; return ossl_x509_add_cert_new(&req->optionalSignature->certs, cert, X509_ADD_FLAG_UP_REF); } /* * Sign an OCSP request set the requestorName to the subject name of an * optional signers certificate and include one or more optional certificates * in the request. Behaves like PKCS7_sign(). */ int OCSP_request_sign(OCSP_REQUEST *req, X509 *signer, EVP_PKEY *key, const EVP_MD *dgst, STACK_OF(X509) *certs, unsigned long flags) { if (!OCSP_request_set1_name(req, X509_get_subject_name(signer))) goto err; if ((req->optionalSignature = OCSP_SIGNATURE_new()) == NULL) goto err; if (key != NULL) { if (!X509_check_private_key(signer, key)) { ERR_raise(ERR_LIB_OCSP, OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE); goto err; } if (!OCSP_REQUEST_sign(req, key, dgst, signer->libctx, signer->propq)) goto err; } if ((flags & OCSP_NOCERTS) == 0) { if (!OCSP_request_add1_cert(req, signer) || !X509_add_certs(req->optionalSignature->certs, certs, X509_ADD_FLAG_UP_REF)) goto err; } return 1; err: OCSP_SIGNATURE_free(req->optionalSignature); req->optionalSignature = NULL; return 0; } /* Get response status */ int OCSP_response_status(OCSP_RESPONSE *resp) { return ASN1_ENUMERATED_get(resp->responseStatus); } /* * Extract basic response from OCSP_RESPONSE or NULL if no basic response * present. */ OCSP_BASICRESP *OCSP_response_get1_basic(OCSP_RESPONSE *resp) { OCSP_RESPBYTES *rb = resp->responseBytes; if (rb == NULL) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NO_RESPONSE_DATA); return NULL; } if (OBJ_obj2nid(rb->responseType) != NID_id_pkix_OCSP_basic) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NOT_BASIC_RESPONSE); return NULL; } return ASN1_item_unpack(rb->response, ASN1_ITEM_rptr(OCSP_BASICRESP)); } const ASN1_OCTET_STRING *OCSP_resp_get0_signature(const OCSP_BASICRESP *bs) { return bs->signature; } const X509_ALGOR *OCSP_resp_get0_tbs_sigalg(const OCSP_BASICRESP *bs) { return &bs->signatureAlgorithm; } const OCSP_RESPDATA *OCSP_resp_get0_respdata(const OCSP_BASICRESP *bs) { return &bs->tbsResponseData; } /* Return number of OCSP_SINGLERESP responses present in a basic response */ int OCSP_resp_count(OCSP_BASICRESP *bs) { if (bs == NULL) return -1; return sk_OCSP_SINGLERESP_num(bs->tbsResponseData.responses); } /* Extract an OCSP_SINGLERESP response with a given index */ OCSP_SINGLERESP *OCSP_resp_get0(OCSP_BASICRESP *bs, int idx) { if (bs == NULL) return NULL; return sk_OCSP_SINGLERESP_value(bs->tbsResponseData.responses, idx); } const ASN1_GENERALIZEDTIME *OCSP_resp_get0_produced_at(const OCSP_BASICRESP *bs) { return bs->tbsResponseData.producedAt; } const STACK_OF(X509) *OCSP_resp_get0_certs(const OCSP_BASICRESP *bs) { return bs->certs; } int OCSP_resp_get0_id(const OCSP_BASICRESP *bs, const ASN1_OCTET_STRING **pid, const X509_NAME **pname) { const OCSP_RESPID *rid = &bs->tbsResponseData.responderId; if (rid->type == V_OCSP_RESPID_NAME) { *pname = rid->value.byName; *pid = NULL; } else if (rid->type == V_OCSP_RESPID_KEY) { *pid = rid->value.byKey; *pname = NULL; } else { return 0; } return 1; } int OCSP_resp_get1_id(const OCSP_BASICRESP *bs, ASN1_OCTET_STRING **pid, X509_NAME **pname) { const OCSP_RESPID *rid = &bs->tbsResponseData.responderId; if (rid->type == V_OCSP_RESPID_NAME) { *pname = X509_NAME_dup(rid->value.byName); *pid = NULL; } else if (rid->type == V_OCSP_RESPID_KEY) { *pid = ASN1_OCTET_STRING_dup(rid->value.byKey); *pname = NULL; } else { return 0; } if (*pname == NULL && *pid == NULL) return 0; return 1; } /* Look single response matching a given certificate ID */ int OCSP_resp_find(OCSP_BASICRESP *bs, OCSP_CERTID *id, int last) { int i; STACK_OF(OCSP_SINGLERESP) *sresp; OCSP_SINGLERESP *single; if (bs == NULL) return -1; if (last < 0) last = 0; else last++; sresp = bs->tbsResponseData.responses; for (i = last; i < sk_OCSP_SINGLERESP_num(sresp); i++) { single = sk_OCSP_SINGLERESP_value(sresp, i); if (!OCSP_id_cmp(id, single->certId)) return i; } return -1; } /* * Extract status information from an OCSP_SINGLERESP structure. Note: the * revtime and reason values are only set if the certificate status is * revoked. Returns numerical value of status. */ int OCSP_single_get0_status(OCSP_SINGLERESP *single, int *reason, ASN1_GENERALIZEDTIME **revtime, ASN1_GENERALIZEDTIME **thisupd, ASN1_GENERALIZEDTIME **nextupd) { int ret; OCSP_CERTSTATUS *cst; if (single == NULL) return -1; cst = single->certStatus; ret = cst->type; if (ret == V_OCSP_CERTSTATUS_REVOKED) { OCSP_REVOKEDINFO *rev = cst->value.revoked; if (revtime) *revtime = rev->revocationTime; if (reason) { if (rev->revocationReason) *reason = ASN1_ENUMERATED_get(rev->revocationReason); else *reason = -1; } } if (thisupd != NULL) *thisupd = single->thisUpdate; if (nextupd != NULL) *nextupd = single->nextUpdate; return ret; } /* * This function combines the previous ones: look up a certificate ID and if * found extract status information. Return 0 is successful. */ int OCSP_resp_find_status(OCSP_BASICRESP *bs, OCSP_CERTID *id, int *status, int *reason, ASN1_GENERALIZEDTIME **revtime, ASN1_GENERALIZEDTIME **thisupd, ASN1_GENERALIZEDTIME **nextupd) { int i = OCSP_resp_find(bs, id, -1); OCSP_SINGLERESP *single; /* Maybe check for multiple responses and give an error? */ if (i < 0) return 0; single = OCSP_resp_get0(bs, i); i = OCSP_single_get0_status(single, reason, revtime, thisupd, nextupd); if (status != NULL) *status = i; return 1; } /* * Check validity of thisUpdate and nextUpdate fields. It is possible that * the request will take a few seconds to process and/or the time won't be * totally accurate. Therefore to avoid rejecting otherwise valid time we * allow the times to be within 'nsec' of the current time. Also to avoid * accepting very old responses without a nextUpdate field an optional maxage * parameter specifies the maximum age the thisUpdate field can be. */ int OCSP_check_validity(ASN1_GENERALIZEDTIME *thisupd, ASN1_GENERALIZEDTIME *nextupd, long nsec, long maxsec) { int ret = 1; time_t t_now, t_tmp; time(&t_now); /* Check thisUpdate is valid and not more than nsec in the future */ if (!ASN1_GENERALIZEDTIME_check(thisupd)) { ERR_raise(ERR_LIB_OCSP, OCSP_R_ERROR_IN_THISUPDATE_FIELD); ret = 0; } else { t_tmp = t_now + nsec; if (X509_cmp_time(thisupd, &t_tmp) > 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_STATUS_NOT_YET_VALID); ret = 0; } /* * If maxsec specified check thisUpdate is not more than maxsec in * the past */ if (maxsec >= 0) { t_tmp = t_now - maxsec; if (X509_cmp_time(thisupd, &t_tmp) < 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_STATUS_TOO_OLD); ret = 0; } } } if (nextupd == NULL) return ret; /* Check nextUpdate is valid and not more than nsec in the past */ if (!ASN1_GENERALIZEDTIME_check(nextupd)) { ERR_raise(ERR_LIB_OCSP, OCSP_R_ERROR_IN_NEXTUPDATE_FIELD); ret = 0; } else { t_tmp = t_now - nsec; if (X509_cmp_time(nextupd, &t_tmp) < 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_STATUS_EXPIRED); ret = 0; } } /* Also don't allow nextUpdate to precede thisUpdate */ if (ASN1_STRING_cmp(nextupd, thisupd) < 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NEXTUPDATE_BEFORE_THISUPDATE); ret = 0; } return ret; } const OCSP_CERTID *OCSP_SINGLERESP_get0_id(const OCSP_SINGLERESP *single) { return single->certId; }
./openssl/crypto/ocsp/ocsp_asn.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 <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/ocsp.h> #include "ocsp_local.h" ASN1_SEQUENCE(OCSP_SIGNATURE) = { ASN1_EMBED(OCSP_SIGNATURE, signatureAlgorithm, X509_ALGOR), ASN1_SIMPLE(OCSP_SIGNATURE, signature, ASN1_BIT_STRING), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_SIGNATURE, certs, X509, 0) } ASN1_SEQUENCE_END(OCSP_SIGNATURE) IMPLEMENT_ASN1_FUNCTIONS(OCSP_SIGNATURE) ASN1_SEQUENCE(OCSP_CERTID) = { ASN1_EMBED(OCSP_CERTID, hashAlgorithm, X509_ALGOR), ASN1_EMBED(OCSP_CERTID, issuerNameHash, ASN1_OCTET_STRING), ASN1_EMBED(OCSP_CERTID, issuerKeyHash, ASN1_OCTET_STRING), ASN1_EMBED(OCSP_CERTID, serialNumber, ASN1_INTEGER) } ASN1_SEQUENCE_END(OCSP_CERTID) IMPLEMENT_ASN1_FUNCTIONS(OCSP_CERTID) ASN1_SEQUENCE(OCSP_ONEREQ) = { ASN1_SIMPLE(OCSP_ONEREQ, reqCert, OCSP_CERTID), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_ONEREQ, singleRequestExtensions, X509_EXTENSION, 0) } ASN1_SEQUENCE_END(OCSP_ONEREQ) IMPLEMENT_ASN1_FUNCTIONS(OCSP_ONEREQ) ASN1_SEQUENCE(OCSP_REQINFO) = { ASN1_EXP_OPT(OCSP_REQINFO, version, ASN1_INTEGER, 0), ASN1_EXP_OPT(OCSP_REQINFO, requestorName, GENERAL_NAME, 1), ASN1_SEQUENCE_OF(OCSP_REQINFO, requestList, OCSP_ONEREQ), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_REQINFO, requestExtensions, X509_EXTENSION, 2) } ASN1_SEQUENCE_END(OCSP_REQINFO) IMPLEMENT_ASN1_FUNCTIONS(OCSP_REQINFO) ASN1_SEQUENCE(OCSP_REQUEST) = { ASN1_EMBED(OCSP_REQUEST, tbsRequest, OCSP_REQINFO), ASN1_EXP_OPT(OCSP_REQUEST, optionalSignature, OCSP_SIGNATURE, 0) } ASN1_SEQUENCE_END(OCSP_REQUEST) IMPLEMENT_ASN1_FUNCTIONS(OCSP_REQUEST) /* OCSP_RESPONSE templates */ ASN1_SEQUENCE(OCSP_RESPBYTES) = { ASN1_SIMPLE(OCSP_RESPBYTES, responseType, ASN1_OBJECT), ASN1_SIMPLE(OCSP_RESPBYTES, response, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(OCSP_RESPBYTES) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPBYTES) ASN1_SEQUENCE(OCSP_RESPONSE) = { ASN1_SIMPLE(OCSP_RESPONSE, responseStatus, ASN1_ENUMERATED), ASN1_EXP_OPT(OCSP_RESPONSE, responseBytes, OCSP_RESPBYTES, 0) } ASN1_SEQUENCE_END(OCSP_RESPONSE) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPONSE) ASN1_CHOICE(OCSP_RESPID) = { ASN1_EXP(OCSP_RESPID, value.byName, X509_NAME, 1), ASN1_EXP(OCSP_RESPID, value.byKey, ASN1_OCTET_STRING, 2) } ASN1_CHOICE_END(OCSP_RESPID) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPID) ASN1_SEQUENCE(OCSP_REVOKEDINFO) = { ASN1_SIMPLE(OCSP_REVOKEDINFO, revocationTime, ASN1_GENERALIZEDTIME), ASN1_EXP_OPT(OCSP_REVOKEDINFO, revocationReason, ASN1_ENUMERATED, 0) } ASN1_SEQUENCE_END(OCSP_REVOKEDINFO) IMPLEMENT_ASN1_FUNCTIONS(OCSP_REVOKEDINFO) ASN1_CHOICE(OCSP_CERTSTATUS) = { ASN1_IMP(OCSP_CERTSTATUS, value.good, ASN1_NULL, 0), ASN1_IMP(OCSP_CERTSTATUS, value.revoked, OCSP_REVOKEDINFO, 1), ASN1_IMP(OCSP_CERTSTATUS, value.unknown, ASN1_NULL, 2) } ASN1_CHOICE_END(OCSP_CERTSTATUS) IMPLEMENT_ASN1_FUNCTIONS(OCSP_CERTSTATUS) ASN1_SEQUENCE(OCSP_SINGLERESP) = { ASN1_SIMPLE(OCSP_SINGLERESP, certId, OCSP_CERTID), ASN1_SIMPLE(OCSP_SINGLERESP, certStatus, OCSP_CERTSTATUS), ASN1_SIMPLE(OCSP_SINGLERESP, thisUpdate, ASN1_GENERALIZEDTIME), ASN1_EXP_OPT(OCSP_SINGLERESP, nextUpdate, ASN1_GENERALIZEDTIME, 0), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_SINGLERESP, singleExtensions, X509_EXTENSION, 1) } ASN1_SEQUENCE_END(OCSP_SINGLERESP) IMPLEMENT_ASN1_FUNCTIONS(OCSP_SINGLERESP) ASN1_SEQUENCE(OCSP_RESPDATA) = { ASN1_EXP_OPT(OCSP_RESPDATA, version, ASN1_INTEGER, 0), ASN1_EMBED(OCSP_RESPDATA, responderId, OCSP_RESPID), ASN1_SIMPLE(OCSP_RESPDATA, producedAt, ASN1_GENERALIZEDTIME), ASN1_SEQUENCE_OF(OCSP_RESPDATA, responses, OCSP_SINGLERESP), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_RESPDATA, responseExtensions, X509_EXTENSION, 1) } ASN1_SEQUENCE_END(OCSP_RESPDATA) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPDATA) ASN1_SEQUENCE(OCSP_BASICRESP) = { ASN1_EMBED(OCSP_BASICRESP, tbsResponseData, OCSP_RESPDATA), ASN1_EMBED(OCSP_BASICRESP, signatureAlgorithm, X509_ALGOR), ASN1_SIMPLE(OCSP_BASICRESP, signature, ASN1_BIT_STRING), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_BASICRESP, certs, X509, 0) } ASN1_SEQUENCE_END(OCSP_BASICRESP) IMPLEMENT_ASN1_FUNCTIONS(OCSP_BASICRESP) ASN1_SEQUENCE(OCSP_CRLID) = { ASN1_EXP_OPT(OCSP_CRLID, crlUrl, ASN1_IA5STRING, 0), ASN1_EXP_OPT(OCSP_CRLID, crlNum, ASN1_INTEGER, 1), ASN1_EXP_OPT(OCSP_CRLID, crlTime, ASN1_GENERALIZEDTIME, 2) } ASN1_SEQUENCE_END(OCSP_CRLID) IMPLEMENT_ASN1_FUNCTIONS(OCSP_CRLID) ASN1_SEQUENCE(OCSP_SERVICELOC) = { ASN1_SIMPLE(OCSP_SERVICELOC, issuer, X509_NAME), ASN1_SEQUENCE_OF_OPT(OCSP_SERVICELOC, locator, ACCESS_DESCRIPTION) } ASN1_SEQUENCE_END(OCSP_SERVICELOC) IMPLEMENT_ASN1_FUNCTIONS(OCSP_SERVICELOC)
./openssl/crypto/ocsp/ocsp_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 "crypto/x509.h" /* for ossl_x509_add_cert_new() */ /*- CertID ::= SEQUENCE { * hashAlgorithm AlgorithmIdentifier, * issuerNameHash OCTET STRING, -- Hash of Issuer's DN * issuerKeyHash OCTET STRING, -- Hash of Issuers public key (excluding the tag & length fields) * serialNumber CertificateSerialNumber } */ struct ocsp_cert_id_st { X509_ALGOR hashAlgorithm; ASN1_OCTET_STRING issuerNameHash; ASN1_OCTET_STRING issuerKeyHash; ASN1_INTEGER serialNumber; }; /*- Request ::= SEQUENCE { * reqCert CertID, * singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } */ struct ocsp_one_request_st { OCSP_CERTID *reqCert; STACK_OF(X509_EXTENSION) *singleRequestExtensions; }; /*- TBSRequest ::= SEQUENCE { * version [0] EXPLICIT Version DEFAULT v1, * requestorName [1] EXPLICIT GeneralName OPTIONAL, * requestList SEQUENCE OF Request, * requestExtensions [2] EXPLICIT Extensions OPTIONAL } */ struct ocsp_req_info_st { ASN1_INTEGER *version; GENERAL_NAME *requestorName; STACK_OF(OCSP_ONEREQ) *requestList; STACK_OF(X509_EXTENSION) *requestExtensions; }; /*- Signature ::= SEQUENCE { * signatureAlgorithm AlgorithmIdentifier, * signature BIT STRING, * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } */ struct ocsp_signature_st { X509_ALGOR signatureAlgorithm; ASN1_BIT_STRING *signature; STACK_OF(X509) *certs; }; /*- OCSPRequest ::= SEQUENCE { * tbsRequest TBSRequest, * optionalSignature [0] EXPLICIT Signature OPTIONAL } */ struct ocsp_request_st { OCSP_REQINFO tbsRequest; OCSP_SIGNATURE *optionalSignature; /* OPTIONAL */ }; /*- OCSPResponseStatus ::= ENUMERATED { * successful (0), --Response has valid confirmations * malformedRequest (1), --Illegal confirmation request * internalError (2), --Internal error in issuer * tryLater (3), --Try again later * --(4) is not used * sigRequired (5), --Must sign the request * unauthorized (6) --Request unauthorized * } */ /*- ResponseBytes ::= SEQUENCE { * responseType OBJECT IDENTIFIER, * response OCTET STRING } */ struct ocsp_resp_bytes_st { ASN1_OBJECT *responseType; ASN1_OCTET_STRING *response; }; /*- OCSPResponse ::= SEQUENCE { * responseStatus OCSPResponseStatus, * responseBytes [0] EXPLICIT ResponseBytes OPTIONAL } */ struct ocsp_response_st { ASN1_ENUMERATED *responseStatus; OCSP_RESPBYTES *responseBytes; }; /*- ResponderID ::= CHOICE { * byName [1] Name, * byKey [2] KeyHash } */ struct ocsp_responder_id_st { int type; union { X509_NAME *byName; ASN1_OCTET_STRING *byKey; } value; }; /*- KeyHash ::= OCTET STRING --SHA-1 hash of responder's public key * --(excluding the tag and length fields) */ /*- RevokedInfo ::= SEQUENCE { * revocationTime GeneralizedTime, * revocationReason [0] EXPLICIT CRLReason OPTIONAL } */ struct ocsp_revoked_info_st { ASN1_GENERALIZEDTIME *revocationTime; ASN1_ENUMERATED *revocationReason; }; /*- CertStatus ::= CHOICE { * good [0] IMPLICIT NULL, * revoked [1] IMPLICIT RevokedInfo, * unknown [2] IMPLICIT UnknownInfo } */ struct ocsp_cert_status_st { int type; union { ASN1_NULL *good; OCSP_REVOKEDINFO *revoked; ASN1_NULL *unknown; } value; }; /*- SingleResponse ::= SEQUENCE { * certID CertID, * certStatus CertStatus, * thisUpdate GeneralizedTime, * nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL, * singleExtensions [1] EXPLICIT Extensions OPTIONAL } */ struct ocsp_single_response_st { OCSP_CERTID *certId; OCSP_CERTSTATUS *certStatus; ASN1_GENERALIZEDTIME *thisUpdate; ASN1_GENERALIZEDTIME *nextUpdate; STACK_OF(X509_EXTENSION) *singleExtensions; }; /*- ResponseData ::= SEQUENCE { * version [0] EXPLICIT Version DEFAULT v1, * responderID ResponderID, * producedAt GeneralizedTime, * responses SEQUENCE OF SingleResponse, * responseExtensions [1] EXPLICIT Extensions OPTIONAL } */ struct ocsp_response_data_st { ASN1_INTEGER *version; OCSP_RESPID responderId; ASN1_GENERALIZEDTIME *producedAt; STACK_OF(OCSP_SINGLERESP) *responses; STACK_OF(X509_EXTENSION) *responseExtensions; }; /*- BasicOCSPResponse ::= SEQUENCE { * tbsResponseData ResponseData, * signatureAlgorithm AlgorithmIdentifier, * signature BIT STRING, * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } */ /* * Note 1: The value for "signature" is specified in the OCSP rfc2560 as * follows: "The value for the signature SHALL be computed on the hash of * the DER encoding ResponseData." This means that you must hash the * DER-encoded tbsResponseData, and then run it through a crypto-signing * function, which will (at least w/RSA) do a hash-'n'-private-encrypt * operation. This seems a bit odd, but that's the spec. Also note that * the data structures do not leave anywhere to independently specify the * algorithm used for the initial hash. So, we look at the * signature-specification algorithm, and try to do something intelligent. * -- Kathy Weinhold, CertCo */ /* * Note 2: It seems that the mentioned passage from RFC 2560 (section * 4.2.1) is open for interpretation. I've done tests against another * responder, and found that it doesn't do the double hashing that the RFC * seems to say one should. Therefore, all relevant functions take a flag * saying which variant should be used. -- Richard Levitte, OpenSSL team * and CeloCom */ struct ocsp_basic_response_st { OCSP_RESPDATA tbsResponseData; X509_ALGOR signatureAlgorithm; ASN1_BIT_STRING *signature; STACK_OF(X509) *certs; }; /*- * CrlID ::= SEQUENCE { * crlUrl [0] EXPLICIT IA5String OPTIONAL, * crlNum [1] EXPLICIT INTEGER OPTIONAL, * crlTime [2] EXPLICIT GeneralizedTime OPTIONAL } */ struct ocsp_crl_id_st { ASN1_IA5STRING *crlUrl; ASN1_INTEGER *crlNum; ASN1_GENERALIZEDTIME *crlTime; }; /*- * ServiceLocator ::= SEQUENCE { * issuer Name, * locator AuthorityInfoAccessSyntax OPTIONAL } */ struct ocsp_service_locator_st { X509_NAME *issuer; STACK_OF(ACCESS_DESCRIPTION) *locator; }; # define OCSP_REQUEST_sign(o, pkey, md, libctx, propq)\ ASN1_item_sign_ex(ASN1_ITEM_rptr(OCSP_REQINFO),\ &(o)->optionalSignature->signatureAlgorithm, NULL,\ (o)->optionalSignature->signature, &(o)->tbsRequest,\ NULL, pkey, md, libctx, propq) # define OCSP_BASICRESP_sign(o, pkey, md, d, libctx, propq)\ ASN1_item_sign_ex(ASN1_ITEM_rptr(OCSP_RESPDATA),\ &(o)->signatureAlgorithm, NULL,\ (o)->signature, &(o)->tbsResponseData,\ NULL, pkey, md, libctx, propq) # define OCSP_BASICRESP_sign_ctx(o, ctx, d)\ ASN1_item_sign_ctx(ASN1_ITEM_rptr(OCSP_RESPDATA),\ &(o)->signatureAlgorithm, NULL,\ (o)->signature, &(o)->tbsResponseData, ctx) # define OCSP_REQUEST_verify(a, r, libctx, propq)\ ASN1_item_verify_ex(ASN1_ITEM_rptr(OCSP_REQINFO),\ &(a)->optionalSignature->signatureAlgorithm,\ (a)->optionalSignature->signature, &(a)->tbsRequest,\ NULL, r, libctx, propq) # define OCSP_BASICRESP_verify(a, r, libctx, propq)\ ASN1_item_verify_ex(ASN1_ITEM_rptr(OCSP_RESPDATA),\ &(a)->signatureAlgorithm, (a)->signature,\ &(a)->tbsResponseData, NULL, r, libctx, propq)
./openssl/crypto/ocsp/ocsp_ext.c
/* * Copyright 2000-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/ocsp.h> #include "ocsp_local.h" #include <openssl/rand.h> #include <openssl/x509v3.h> /* Standard wrapper functions for extensions */ /* OCSP request extensions */ int OCSP_REQUEST_get_ext_count(OCSP_REQUEST *x) { return X509v3_get_ext_count(x->tbsRequest.requestExtensions); } int OCSP_REQUEST_get_ext_by_NID(OCSP_REQUEST *x, int nid, int lastpos) { return (X509v3_get_ext_by_NID (x->tbsRequest.requestExtensions, nid, lastpos)); } int OCSP_REQUEST_get_ext_by_OBJ(OCSP_REQUEST *x, const ASN1_OBJECT *obj, int lastpos) { return (X509v3_get_ext_by_OBJ (x->tbsRequest.requestExtensions, obj, lastpos)); } int OCSP_REQUEST_get_ext_by_critical(OCSP_REQUEST *x, int crit, int lastpos) { return (X509v3_get_ext_by_critical (x->tbsRequest.requestExtensions, crit, lastpos)); } X509_EXTENSION *OCSP_REQUEST_get_ext(OCSP_REQUEST *x, int loc) { return X509v3_get_ext(x->tbsRequest.requestExtensions, loc); } X509_EXTENSION *OCSP_REQUEST_delete_ext(OCSP_REQUEST *x, int loc) { return X509v3_delete_ext(x->tbsRequest.requestExtensions, loc); } void *OCSP_REQUEST_get1_ext_d2i(OCSP_REQUEST *x, int nid, int *crit, int *idx) { return X509V3_get_d2i(x->tbsRequest.requestExtensions, nid, crit, idx); } int OCSP_REQUEST_add1_ext_i2d(OCSP_REQUEST *x, int nid, void *value, int crit, unsigned long flags) { return X509V3_add1_i2d(&x->tbsRequest.requestExtensions, nid, value, crit, flags); } int OCSP_REQUEST_add_ext(OCSP_REQUEST *x, X509_EXTENSION *ex, int loc) { return (X509v3_add_ext(&(x->tbsRequest.requestExtensions), ex, loc) != NULL); } /* Single extensions */ int OCSP_ONEREQ_get_ext_count(OCSP_ONEREQ *x) { return X509v3_get_ext_count(x->singleRequestExtensions); } int OCSP_ONEREQ_get_ext_by_NID(OCSP_ONEREQ *x, int nid, int lastpos) { return X509v3_get_ext_by_NID(x->singleRequestExtensions, nid, lastpos); } int OCSP_ONEREQ_get_ext_by_OBJ(OCSP_ONEREQ *x, const ASN1_OBJECT *obj, int lastpos) { return X509v3_get_ext_by_OBJ(x->singleRequestExtensions, obj, lastpos); } int OCSP_ONEREQ_get_ext_by_critical(OCSP_ONEREQ *x, int crit, int lastpos) { return (X509v3_get_ext_by_critical (x->singleRequestExtensions, crit, lastpos)); } X509_EXTENSION *OCSP_ONEREQ_get_ext(OCSP_ONEREQ *x, int loc) { return X509v3_get_ext(x->singleRequestExtensions, loc); } X509_EXTENSION *OCSP_ONEREQ_delete_ext(OCSP_ONEREQ *x, int loc) { return X509v3_delete_ext(x->singleRequestExtensions, loc); } void *OCSP_ONEREQ_get1_ext_d2i(OCSP_ONEREQ *x, int nid, int *crit, int *idx) { return X509V3_get_d2i(x->singleRequestExtensions, nid, crit, idx); } int OCSP_ONEREQ_add1_ext_i2d(OCSP_ONEREQ *x, int nid, void *value, int crit, unsigned long flags) { return X509V3_add1_i2d(&x->singleRequestExtensions, nid, value, crit, flags); } int OCSP_ONEREQ_add_ext(OCSP_ONEREQ *x, X509_EXTENSION *ex, int loc) { return (X509v3_add_ext(&(x->singleRequestExtensions), ex, loc) != NULL); } /* OCSP Basic response */ int OCSP_BASICRESP_get_ext_count(OCSP_BASICRESP *x) { return X509v3_get_ext_count(x->tbsResponseData.responseExtensions); } int OCSP_BASICRESP_get_ext_by_NID(OCSP_BASICRESP *x, int nid, int lastpos) { return (X509v3_get_ext_by_NID (x->tbsResponseData.responseExtensions, nid, lastpos)); } int OCSP_BASICRESP_get_ext_by_OBJ(OCSP_BASICRESP *x, const ASN1_OBJECT *obj, int lastpos) { return (X509v3_get_ext_by_OBJ (x->tbsResponseData.responseExtensions, obj, lastpos)); } int OCSP_BASICRESP_get_ext_by_critical(OCSP_BASICRESP *x, int crit, int lastpos) { return (X509v3_get_ext_by_critical (x->tbsResponseData.responseExtensions, crit, lastpos)); } X509_EXTENSION *OCSP_BASICRESP_get_ext(OCSP_BASICRESP *x, int loc) { return X509v3_get_ext(x->tbsResponseData.responseExtensions, loc); } X509_EXTENSION *OCSP_BASICRESP_delete_ext(OCSP_BASICRESP *x, int loc) { return X509v3_delete_ext(x->tbsResponseData.responseExtensions, loc); } void *OCSP_BASICRESP_get1_ext_d2i(OCSP_BASICRESP *x, int nid, int *crit, int *idx) { return X509V3_get_d2i(x->tbsResponseData.responseExtensions, nid, crit, idx); } int OCSP_BASICRESP_add1_ext_i2d(OCSP_BASICRESP *x, int nid, void *value, int crit, unsigned long flags) { return X509V3_add1_i2d(&x->tbsResponseData.responseExtensions, nid, value, crit, flags); } int OCSP_BASICRESP_add_ext(OCSP_BASICRESP *x, X509_EXTENSION *ex, int loc) { return (X509v3_add_ext(&(x->tbsResponseData.responseExtensions), ex, loc) != NULL); } /* OCSP single response extensions */ int OCSP_SINGLERESP_get_ext_count(OCSP_SINGLERESP *x) { return X509v3_get_ext_count(x->singleExtensions); } int OCSP_SINGLERESP_get_ext_by_NID(OCSP_SINGLERESP *x, int nid, int lastpos) { return X509v3_get_ext_by_NID(x->singleExtensions, nid, lastpos); } int OCSP_SINGLERESP_get_ext_by_OBJ(OCSP_SINGLERESP *x, const ASN1_OBJECT *obj, int lastpos) { return X509v3_get_ext_by_OBJ(x->singleExtensions, obj, lastpos); } int OCSP_SINGLERESP_get_ext_by_critical(OCSP_SINGLERESP *x, int crit, int lastpos) { return X509v3_get_ext_by_critical(x->singleExtensions, crit, lastpos); } X509_EXTENSION *OCSP_SINGLERESP_get_ext(OCSP_SINGLERESP *x, int loc) { return X509v3_get_ext(x->singleExtensions, loc); } X509_EXTENSION *OCSP_SINGLERESP_delete_ext(OCSP_SINGLERESP *x, int loc) { return X509v3_delete_ext(x->singleExtensions, loc); } void *OCSP_SINGLERESP_get1_ext_d2i(OCSP_SINGLERESP *x, int nid, int *crit, int *idx) { return X509V3_get_d2i(x->singleExtensions, nid, crit, idx); } int OCSP_SINGLERESP_add1_ext_i2d(OCSP_SINGLERESP *x, int nid, void *value, int crit, unsigned long flags) { return X509V3_add1_i2d(&x->singleExtensions, nid, value, crit, flags); } int OCSP_SINGLERESP_add_ext(OCSP_SINGLERESP *x, X509_EXTENSION *ex, int loc) { return (X509v3_add_ext(&(x->singleExtensions), ex, loc) != NULL); } /* also CRL Entry Extensions */ /* Nonce handling functions */ /* * Add a nonce to an extension stack. A nonce can be specified or if NULL a * random nonce will be generated. Note: OpenSSL 0.9.7d and later create an * OCTET STRING containing the nonce, previous versions used the raw nonce. */ static int ocsp_add1_nonce(STACK_OF(X509_EXTENSION) **exts, unsigned char *val, int len) { unsigned char *tmpval; ASN1_OCTET_STRING os; int ret = 0; if (len <= 0) len = OCSP_DEFAULT_NONCE_LENGTH; /* * Create the OCTET STRING manually by writing out the header and * appending the content octets. This avoids an extra memory allocation * operation in some cases. Applications should *NOT* do this because it * relies on library internals. */ os.length = ASN1_object_size(0, len, V_ASN1_OCTET_STRING); if (os.length < 0) return 0; os.data = OPENSSL_malloc(os.length); if (os.data == NULL) goto err; tmpval = os.data; ASN1_put_object(&tmpval, 0, len, V_ASN1_OCTET_STRING, V_ASN1_UNIVERSAL); if (val) memcpy(tmpval, val, len); else if (RAND_bytes(tmpval, len) <= 0) goto err; if (X509V3_add1_i2d(exts, NID_id_pkix_OCSP_Nonce, &os, 0, X509V3_ADD_REPLACE) <= 0) goto err; ret = 1; err: OPENSSL_free(os.data); return ret; } /* Add nonce to an OCSP request */ int OCSP_request_add1_nonce(OCSP_REQUEST *req, unsigned char *val, int len) { return ocsp_add1_nonce(&req->tbsRequest.requestExtensions, val, len); } /* Same as above but for a response */ int OCSP_basic_add1_nonce(OCSP_BASICRESP *resp, unsigned char *val, int len) { return ocsp_add1_nonce(&resp->tbsResponseData.responseExtensions, val, len); } /*- * Check nonce validity in a request and response. * Return value reflects result: * 1: nonces present and equal. * 2: nonces both absent. * 3: nonce present in response only. * 0: nonces both present and not equal. * -1: nonce in request only. * * For most responders clients can check return > 0. * If responder doesn't handle nonces return != 0 may be * necessary. return == 0 is always an error. */ int OCSP_check_nonce(OCSP_REQUEST *req, OCSP_BASICRESP *bs) { /* * Since we are only interested in the presence or absence of * the nonce and comparing its value there is no need to use * the X509V3 routines: this way we can avoid them allocating an * ASN1_OCTET_STRING structure for the value which would be * freed immediately anyway. */ int req_idx, resp_idx; X509_EXTENSION *req_ext, *resp_ext; req_idx = OCSP_REQUEST_get_ext_by_NID(req, NID_id_pkix_OCSP_Nonce, -1); resp_idx = OCSP_BASICRESP_get_ext_by_NID(bs, NID_id_pkix_OCSP_Nonce, -1); /* Check both absent */ if ((req_idx < 0) && (resp_idx < 0)) return 2; /* Check in request only */ if ((req_idx >= 0) && (resp_idx < 0)) return -1; /* Check in response but not request */ if ((req_idx < 0) && (resp_idx >= 0)) return 3; /* * Otherwise nonce in request and response so retrieve the extensions */ req_ext = OCSP_REQUEST_get_ext(req, req_idx); resp_ext = OCSP_BASICRESP_get_ext(bs, resp_idx); if (ASN1_OCTET_STRING_cmp(X509_EXTENSION_get_data(req_ext), X509_EXTENSION_get_data(resp_ext))) return 0; return 1; } /* * Copy the nonce value (if any) from an OCSP request to a response. */ int OCSP_copy_nonce(OCSP_BASICRESP *resp, OCSP_REQUEST *req) { X509_EXTENSION *req_ext; int req_idx; /* Check for nonce in request */ req_idx = OCSP_REQUEST_get_ext_by_NID(req, NID_id_pkix_OCSP_Nonce, -1); /* If no nonce that's OK */ if (req_idx < 0) return 2; req_ext = OCSP_REQUEST_get_ext(req, req_idx); return OCSP_BASICRESP_add_ext(resp, req_ext, -1); } X509_EXTENSION *OCSP_crlID_new(const char *url, long *n, char *tim) { X509_EXTENSION *x = NULL; OCSP_CRLID *cid = NULL; if ((cid = OCSP_CRLID_new()) == NULL) goto err; if (url) { if ((cid->crlUrl = ASN1_IA5STRING_new()) == NULL) goto err; if (!(ASN1_STRING_set(cid->crlUrl, url, -1))) goto err; } if (n) { if ((cid->crlNum = ASN1_INTEGER_new()) == NULL) goto err; if (!(ASN1_INTEGER_set(cid->crlNum, *n))) goto err; } if (tim) { if ((cid->crlTime = ASN1_GENERALIZEDTIME_new()) == NULL) goto err; if (!(ASN1_GENERALIZEDTIME_set_string(cid->crlTime, tim))) goto err; } x = X509V3_EXT_i2d(NID_id_pkix_OCSP_CrlID, 0, cid); err: OCSP_CRLID_free(cid); return x; } /* AcceptableResponses ::= SEQUENCE OF OBJECT IDENTIFIER */ X509_EXTENSION *OCSP_accept_responses_new(char **oids) { int nid; STACK_OF(ASN1_OBJECT) *sk = NULL; ASN1_OBJECT *o = NULL; X509_EXTENSION *x = NULL; if ((sk = sk_ASN1_OBJECT_new_null()) == NULL) goto err; while (oids && *oids) { if ((nid = OBJ_txt2nid(*oids)) != NID_undef && (o = OBJ_nid2obj(nid))) sk_ASN1_OBJECT_push(sk, o); oids++; } x = X509V3_EXT_i2d(NID_id_pkix_OCSP_acceptableResponses, 0, sk); err: sk_ASN1_OBJECT_pop_free(sk, ASN1_OBJECT_free); return x; } /* ArchiveCutoff ::= GeneralizedTime */ X509_EXTENSION *OCSP_archive_cutoff_new(char *tim) { X509_EXTENSION *x = NULL; ASN1_GENERALIZEDTIME *gt = NULL; if ((gt = ASN1_GENERALIZEDTIME_new()) == NULL) goto err; if (!(ASN1_GENERALIZEDTIME_set_string(gt, tim))) goto err; x = X509V3_EXT_i2d(NID_id_pkix_OCSP_archiveCutoff, 0, gt); err: ASN1_GENERALIZEDTIME_free(gt); return x; } /* * per ACCESS_DESCRIPTION parameter are oids, of which there are currently * two--NID_ad_ocsp, NID_id_ad_caIssuers--and GeneralName value. This method * forces NID_ad_ocsp and uniformResourceLocator [6] IA5String. */ X509_EXTENSION *OCSP_url_svcloc_new(const X509_NAME *issuer, const char **urls) { X509_EXTENSION *x = NULL; ASN1_IA5STRING *ia5 = NULL; OCSP_SERVICELOC *sloc = NULL; ACCESS_DESCRIPTION *ad = NULL; if ((sloc = OCSP_SERVICELOC_new()) == NULL) goto err; X509_NAME_free(sloc->issuer); if ((sloc->issuer = X509_NAME_dup(issuer)) == NULL) goto err; if (urls && *urls && (sloc->locator = sk_ACCESS_DESCRIPTION_new_null()) == NULL) goto err; while (urls && *urls) { if ((ad = ACCESS_DESCRIPTION_new()) == NULL) goto err; if ((ad->method = OBJ_nid2obj(NID_ad_OCSP)) == NULL) goto err; if ((ia5 = ASN1_IA5STRING_new()) == NULL) goto err; if (!ASN1_STRING_set((ASN1_STRING *)ia5, *urls, -1)) goto err; /* ad->location is allocated inside ACCESS_DESCRIPTION_new */ ad->location->type = GEN_URI; ad->location->d.ia5 = ia5; ia5 = NULL; if (!sk_ACCESS_DESCRIPTION_push(sloc->locator, ad)) goto err; ad = NULL; urls++; } x = X509V3_EXT_i2d(NID_id_pkix_OCSP_serviceLocator, 0, sloc); err: ASN1_IA5STRING_free(ia5); ACCESS_DESCRIPTION_free(ad); OCSP_SERVICELOC_free(sloc); return x; }
./openssl/crypto/md4/md4_dgst.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 */ /* * MD4 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <openssl/opensslv.h> #include "md4_local.h" /* * Implemented from RFC1186 The MD4 Message-Digest Algorithm */ #define INIT_DATA_A (unsigned long)0x67452301L #define INIT_DATA_B (unsigned long)0xefcdab89L #define INIT_DATA_C (unsigned long)0x98badcfeL #define INIT_DATA_D (unsigned long)0x10325476L int MD4_Init(MD4_CTX *c) { memset(c, 0, sizeof(*c)); c->A = INIT_DATA_A; c->B = INIT_DATA_B; c->C = INIT_DATA_C; c->D = INIT_DATA_D; return 1; } #ifndef md4_block_data_order # ifdef X # undef X # endif void md4_block_data_order(MD4_CTX *c, const void *data_, size_t num) { const unsigned char *data = data_; register unsigned MD32_REG_T A, B, C, D, l; # ifndef MD32_XARRAY /* See comment in crypto/sha/sha_local.h for details. */ unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, XX8, XX9, XX10, XX11, XX12, XX13, XX14, XX15; # define X(i) XX##i # else MD4_LONG XX[MD4_LBLOCK]; # define X(i) XX[i] # endif A = c->A; B = c->B; C = c->C; D = c->D; for (; num--;) { (void)HOST_c2l(data, l); X(0) = l; (void)HOST_c2l(data, l); X(1) = l; /* Round 0 */ R0(A, B, C, D, X(0), 3, 0); (void)HOST_c2l(data, l); X(2) = l; R0(D, A, B, C, X(1), 7, 0); (void)HOST_c2l(data, l); X(3) = l; R0(C, D, A, B, X(2), 11, 0); (void)HOST_c2l(data, l); X(4) = l; R0(B, C, D, A, X(3), 19, 0); (void)HOST_c2l(data, l); X(5) = l; R0(A, B, C, D, X(4), 3, 0); (void)HOST_c2l(data, l); X(6) = l; R0(D, A, B, C, X(5), 7, 0); (void)HOST_c2l(data, l); X(7) = l; R0(C, D, A, B, X(6), 11, 0); (void)HOST_c2l(data, l); X(8) = l; R0(B, C, D, A, X(7), 19, 0); (void)HOST_c2l(data, l); X(9) = l; R0(A, B, C, D, X(8), 3, 0); (void)HOST_c2l(data, l); X(10) = l; R0(D, A, B, C, X(9), 7, 0); (void)HOST_c2l(data, l); X(11) = l; R0(C, D, A, B, X(10), 11, 0); (void)HOST_c2l(data, l); X(12) = l; R0(B, C, D, A, X(11), 19, 0); (void)HOST_c2l(data, l); X(13) = l; R0(A, B, C, D, X(12), 3, 0); (void)HOST_c2l(data, l); X(14) = l; R0(D, A, B, C, X(13), 7, 0); (void)HOST_c2l(data, l); X(15) = l; R0(C, D, A, B, X(14), 11, 0); R0(B, C, D, A, X(15), 19, 0); /* Round 1 */ R1(A, B, C, D, X(0), 3, 0x5A827999L); R1(D, A, B, C, X(4), 5, 0x5A827999L); R1(C, D, A, B, X(8), 9, 0x5A827999L); R1(B, C, D, A, X(12), 13, 0x5A827999L); R1(A, B, C, D, X(1), 3, 0x5A827999L); R1(D, A, B, C, X(5), 5, 0x5A827999L); R1(C, D, A, B, X(9), 9, 0x5A827999L); R1(B, C, D, A, X(13), 13, 0x5A827999L); R1(A, B, C, D, X(2), 3, 0x5A827999L); R1(D, A, B, C, X(6), 5, 0x5A827999L); R1(C, D, A, B, X(10), 9, 0x5A827999L); R1(B, C, D, A, X(14), 13, 0x5A827999L); R1(A, B, C, D, X(3), 3, 0x5A827999L); R1(D, A, B, C, X(7), 5, 0x5A827999L); R1(C, D, A, B, X(11), 9, 0x5A827999L); R1(B, C, D, A, X(15), 13, 0x5A827999L); /* Round 2 */ R2(A, B, C, D, X(0), 3, 0x6ED9EBA1L); R2(D, A, B, C, X(8), 9, 0x6ED9EBA1L); R2(C, D, A, B, X(4), 11, 0x6ED9EBA1L); R2(B, C, D, A, X(12), 15, 0x6ED9EBA1L); R2(A, B, C, D, X(2), 3, 0x6ED9EBA1L); R2(D, A, B, C, X(10), 9, 0x6ED9EBA1L); R2(C, D, A, B, X(6), 11, 0x6ED9EBA1L); R2(B, C, D, A, X(14), 15, 0x6ED9EBA1L); R2(A, B, C, D, X(1), 3, 0x6ED9EBA1L); R2(D, A, B, C, X(9), 9, 0x6ED9EBA1L); R2(C, D, A, B, X(5), 11, 0x6ED9EBA1L); R2(B, C, D, A, X(13), 15, 0x6ED9EBA1L); R2(A, B, C, D, X(3), 3, 0x6ED9EBA1L); R2(D, A, B, C, X(11), 9, 0x6ED9EBA1L); R2(C, D, A, B, X(7), 11, 0x6ED9EBA1L); R2(B, C, D, A, X(15), 15, 0x6ED9EBA1L); A = c->A += A; B = c->B += B; C = c->C += C; D = c->D += D; } } #endif
./openssl/crypto/md4/md4_local.h
/* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdlib.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/md4.h> void md4_block_data_order(MD4_CTX *c, const void *p, size_t num); #define DATA_ORDER_IS_LITTLE_ENDIAN #define HASH_LONG MD4_LONG #define HASH_CTX MD4_CTX #define HASH_CBLOCK MD4_CBLOCK #define HASH_UPDATE MD4_Update #define HASH_TRANSFORM MD4_Transform #define HASH_FINAL MD4_Final #define HASH_MAKE_STRING(c,s) do { \ unsigned long ll; \ ll=(c)->A; (void)HOST_l2c(ll,(s)); \ ll=(c)->B; (void)HOST_l2c(ll,(s)); \ ll=(c)->C; (void)HOST_l2c(ll,(s)); \ ll=(c)->D; (void)HOST_l2c(ll,(s)); \ } while (0) #define HASH_BLOCK_DATA_ORDER md4_block_data_order #include "crypto/md32_common.h" /*- #define F(x,y,z) (((x) & (y)) | ((~(x)) & (z))) #define G(x,y,z) (((x) & (y)) | ((x) & ((z))) | ((y) & ((z)))) */ /* * As pointed out by Wei Dai, the above can be simplified to the code * below. Wei attributes these optimizations to Peter Gutmann's SHS code, * and he attributes it to Rich Schroeppel. */ #define F(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) #define G(b,c,d) (((b) & (c)) | ((b) & (d)) | ((c) & (d))) #define H(b,c,d) ((b) ^ (c) ^ (d)) #define R0(a,b,c,d,k,s,t) { \ a+=((k)+(t)+F((b),(c),(d))); \ a=ROTATE(a,s); }; #define R1(a,b,c,d,k,s,t) { \ a+=((k)+(t)+G((b),(c),(d))); \ a=ROTATE(a,s); }; #define R2(a,b,c,d,k,s,t) { \ a+=((k)+(t)+H((b),(c),(d))); \ a=ROTATE(a,s); };
./openssl/crypto/md4/md4_one.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 */ /* * MD4 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include <openssl/md4.h> #include <openssl/crypto.h> #ifdef CHARSET_EBCDIC # include <openssl/ebcdic.h> #endif unsigned char *MD4(const unsigned char *d, size_t n, unsigned char *md) { MD4_CTX c; static unsigned char m[MD4_DIGEST_LENGTH]; if (md == NULL) md = m; if (!MD4_Init(&c)) return NULL; #ifndef CHARSET_EBCDIC MD4_Update(&c, d, n); #else { char temp[1024]; unsigned long chunk; while (n > 0) { chunk = (n > sizeof(temp)) ? sizeof(temp) : n; ebcdic2ascii(temp, d, chunk); MD4_Update(&c, temp, chunk); n -= chunk; d += chunk; } } #endif MD4_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* security consideration */ return md; }
./openssl/crypto/dsa/dsa_local.h
/* * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/dsa.h> #include "internal/refcount.h" #include "internal/ffc.h" struct dsa_st { /* * This first variable is used to pick up errors where a DSA is passed * instead of an EVP_PKEY */ int pad; int32_t version; FFC_PARAMS params; BIGNUM *pub_key; /* y public key */ BIGNUM *priv_key; /* x private key */ int flags; /* Normally used to cache montgomery values */ BN_MONT_CTX *method_mont_p; CRYPTO_REF_COUNT references; #ifndef FIPS_MODULE CRYPTO_EX_DATA ex_data; #endif const DSA_METHOD *meth; /* functional reference if 'meth' is ENGINE-provided */ ENGINE *engine; CRYPTO_RWLOCK *lock; OSSL_LIB_CTX *libctx; /* Provider data */ size_t dirty_cnt; /* If any key material changes, increment this */ }; struct DSA_SIG_st { BIGNUM *r; BIGNUM *s; }; struct dsa_method { char *name; DSA_SIG *(*dsa_do_sign) (const unsigned char *dgst, int dlen, DSA *dsa); int (*dsa_sign_setup) (DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp); int (*dsa_do_verify) (const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa); int (*dsa_mod_exp) (DSA *dsa, BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1, const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont); /* Can be null */ int (*bn_mod_exp) (DSA *dsa, BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); int (*init) (DSA *dsa); int (*finish) (DSA *dsa); int flags; void *app_data; /* If this is non-NULL, it is used to generate DSA parameters */ int (*dsa_paramgen) (DSA *dsa, int bits, const unsigned char *seed, int seed_len, int *counter_ret, unsigned long *h_ret, BN_GENCB *cb); /* If this is non-NULL, it is used to generate DSA keys */ int (*dsa_keygen) (DSA *dsa); }; DSA_SIG *ossl_dsa_do_sign_int(const unsigned char *dgst, int dlen, DSA *dsa, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq);
./openssl/crypto/dsa/dsa_pmeth.c
/* * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> #include <openssl/evp.h> #include <openssl/bn.h> #include "crypto/evp.h" #include "dsa_local.h" /* DSA pkey context structure */ typedef struct { /* Parameter gen parameters */ int nbits; /* size of p in bits (default: 2048) */ int qbits; /* size of q in bits (default: 224) */ const EVP_MD *pmd; /* MD for parameter generation */ /* Keygen callback info */ int gentmp[2]; /* message digest */ const EVP_MD *md; /* MD for the signature */ } DSA_PKEY_CTX; static int pkey_dsa_init(EVP_PKEY_CTX *ctx) { DSA_PKEY_CTX *dctx = OPENSSL_malloc(sizeof(*dctx)); if (dctx == NULL) return 0; dctx->nbits = 2048; dctx->qbits = 224; dctx->pmd = NULL; dctx->md = NULL; ctx->data = dctx; ctx->keygen_info = dctx->gentmp; ctx->keygen_info_count = 2; return 1; } static int pkey_dsa_copy(EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src) { DSA_PKEY_CTX *dctx, *sctx; if (!pkey_dsa_init(dst)) return 0; sctx = src->data; dctx = dst->data; dctx->nbits = sctx->nbits; dctx->qbits = sctx->qbits; dctx->pmd = sctx->pmd; dctx->md = sctx->md; return 1; } static void pkey_dsa_cleanup(EVP_PKEY_CTX *ctx) { DSA_PKEY_CTX *dctx = ctx->data; OPENSSL_free(dctx); } static int pkey_dsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen) { int ret; unsigned int sltmp; DSA_PKEY_CTX *dctx = ctx->data; /* * Discard const. Its marked as const because this may be a cached copy of * the "real" key. These calls don't make any modifications that need to * be reflected back in the "original" key. */ DSA *dsa = (DSA *)EVP_PKEY_get0_DSA(ctx->pkey); if (dctx->md != NULL && tbslen != (size_t)EVP_MD_get_size(dctx->md)) return 0; ret = DSA_sign(0, tbs, tbslen, sig, &sltmp, dsa); if (ret <= 0) return ret; *siglen = sltmp; return 1; } static int pkey_dsa_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig, size_t siglen, const unsigned char *tbs, size_t tbslen) { int ret; DSA_PKEY_CTX *dctx = ctx->data; /* * Discard const. Its marked as const because this may be a cached copy of * the "real" key. These calls don't make any modifications that need to * be reflected back in the "original" key. */ DSA *dsa = (DSA *)EVP_PKEY_get0_DSA(ctx->pkey); if (dctx->md != NULL && tbslen != (size_t)EVP_MD_get_size(dctx->md)) return 0; ret = DSA_verify(0, tbs, tbslen, sig, siglen, dsa); return ret; } static int pkey_dsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { DSA_PKEY_CTX *dctx = ctx->data; switch (type) { case EVP_PKEY_CTRL_DSA_PARAMGEN_BITS: if (p1 < 256) return -2; dctx->nbits = p1; return 1; case EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS: if (p1 != 160 && p1 != 224 && p1 && p1 != 256) return -2; dctx->qbits = p1; return 1; case EVP_PKEY_CTRL_DSA_PARAMGEN_MD: if (EVP_MD_get_type((const EVP_MD *)p2) != NID_sha1 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha224 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha256) { ERR_raise(ERR_LIB_DSA, DSA_R_INVALID_DIGEST_TYPE); return 0; } dctx->pmd = p2; return 1; case EVP_PKEY_CTRL_MD: if (EVP_MD_get_type((const EVP_MD *)p2) != NID_sha1 && EVP_MD_get_type((const EVP_MD *)p2) != NID_dsa && EVP_MD_get_type((const EVP_MD *)p2) != NID_dsaWithSHA && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha224 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha256 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha384 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha512 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_224 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_256 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_384 && EVP_MD_get_type((const EVP_MD *)p2) != NID_sha3_512) { ERR_raise(ERR_LIB_DSA, DSA_R_INVALID_DIGEST_TYPE); return 0; } dctx->md = p2; return 1; case EVP_PKEY_CTRL_GET_MD: *(const EVP_MD **)p2 = dctx->md; return 1; case EVP_PKEY_CTRL_DIGESTINIT: case EVP_PKEY_CTRL_PKCS7_SIGN: case EVP_PKEY_CTRL_CMS_SIGN: return 1; case EVP_PKEY_CTRL_PEER_KEY: ERR_raise(ERR_LIB_DSA, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return -2; default: return -2; } } static int pkey_dsa_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { if (strcmp(type, "dsa_paramgen_bits") == 0) { int nbits; nbits = atoi(value); return EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, nbits); } if (strcmp(type, "dsa_paramgen_q_bits") == 0) { int qbits = atoi(value); return EVP_PKEY_CTX_set_dsa_paramgen_q_bits(ctx, qbits); } if (strcmp(type, "dsa_paramgen_md") == 0) { const EVP_MD *md = EVP_get_digestbyname(value); if (md == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_INVALID_DIGEST_TYPE); return 0; } return EVP_PKEY_CTX_set_dsa_paramgen_md(ctx, md); } return -2; } static int pkey_dsa_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { DSA *dsa = NULL; DSA_PKEY_CTX *dctx = ctx->data; BN_GENCB *pcb; int ret, res; if (ctx->pkey_gencb) { pcb = BN_GENCB_new(); if (pcb == NULL) return 0; evp_pkey_set_cb_translate(pcb, ctx); } else pcb = NULL; dsa = DSA_new(); if (dsa == NULL) { BN_GENCB_free(pcb); return 0; } if (dctx->md != NULL) ossl_ffc_set_digest(&dsa->params, EVP_MD_get0_name(dctx->md), NULL); ret = ossl_ffc_params_FIPS186_4_generate(NULL, &dsa->params, FFC_PARAM_TYPE_DSA, dctx->nbits, dctx->qbits, &res, pcb); BN_GENCB_free(pcb); if (ret > 0) EVP_PKEY_assign_DSA(pkey, dsa); else DSA_free(dsa); return ret; } static int pkey_dsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { DSA *dsa = NULL; if (ctx->pkey == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_NO_PARAMETERS_SET); return 0; } dsa = DSA_new(); if (dsa == NULL) return 0; EVP_PKEY_assign_DSA(pkey, dsa); /* Note: if error return, pkey is freed by parent routine */ if (!EVP_PKEY_copy_parameters(pkey, ctx->pkey)) return 0; return DSA_generate_key((DSA *)EVP_PKEY_get0_DSA(pkey)); } static const EVP_PKEY_METHOD dsa_pkey_meth = { EVP_PKEY_DSA, EVP_PKEY_FLAG_AUTOARGLEN, pkey_dsa_init, pkey_dsa_copy, pkey_dsa_cleanup, 0, pkey_dsa_paramgen, 0, pkey_dsa_keygen, 0, pkey_dsa_sign, 0, pkey_dsa_verify, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, pkey_dsa_ctrl, pkey_dsa_ctrl_str }; const EVP_PKEY_METHOD *ossl_dsa_pkey_method(void) { return &dsa_pkey_meth; }
./openssl/crypto/dsa/dsa_sign.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/bn.h> #include "internal/cryptlib.h" #include "dsa_local.h" #include "crypto/asn1_dsa.h" #include "crypto/dsa.h" DSA_SIG *DSA_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) { return dsa->meth->dsa_do_sign(dgst, dlen, dsa); } #ifndef OPENSSL_NO_DEPRECATED_3_0 int DSA_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { return dsa->meth->dsa_sign_setup(dsa, ctx_in, kinvp, rp); } #endif DSA_SIG *DSA_SIG_new(void) { DSA_SIG *sig = OPENSSL_zalloc(sizeof(*sig)); return sig; } void DSA_SIG_free(DSA_SIG *sig) { if (sig == NULL) return; BN_clear_free(sig->r); BN_clear_free(sig->s); OPENSSL_free(sig); } DSA_SIG *d2i_DSA_SIG(DSA_SIG **psig, const unsigned char **ppin, long len) { DSA_SIG *sig; if (len < 0) return NULL; if (psig != NULL && *psig != NULL) { sig = *psig; } else { sig = DSA_SIG_new(); if (sig == NULL) return NULL; } if (sig->r == NULL) sig->r = BN_new(); if (sig->s == NULL) sig->s = BN_new(); if (sig->r == NULL || sig->s == NULL || ossl_decode_der_dsa_sig(sig->r, sig->s, ppin, (size_t)len) == 0) { if (psig == NULL || *psig == NULL) DSA_SIG_free(sig); return NULL; } if (psig != NULL && *psig == NULL) *psig = sig; return sig; } int i2d_DSA_SIG(const DSA_SIG *sig, unsigned char **ppout) { BUF_MEM *buf = NULL; size_t encoded_len; WPACKET pkt; if (ppout == NULL) { if (!WPACKET_init_null(&pkt, 0)) return -1; } else if (*ppout == NULL) { if ((buf = BUF_MEM_new()) == NULL || !WPACKET_init_len(&pkt, buf, 0)) { BUF_MEM_free(buf); return -1; } } else { if (!WPACKET_init_static_len(&pkt, *ppout, SIZE_MAX, 0)) return -1; } if (!ossl_encode_der_dsa_sig(&pkt, sig->r, sig->s) || !WPACKET_get_total_written(&pkt, &encoded_len) || !WPACKET_finish(&pkt)) { BUF_MEM_free(buf); WPACKET_cleanup(&pkt); return -1; } if (ppout != NULL) { if (*ppout == NULL) { *ppout = (unsigned char *)buf->data; buf->data = NULL; BUF_MEM_free(buf); } else { *ppout += encoded_len; } } return (int)encoded_len; } int DSA_size(const DSA *dsa) { int ret = -1; DSA_SIG sig; if (dsa->params.q != NULL) { sig.r = sig.s = dsa->params.q; ret = i2d_DSA_SIG(&sig, NULL); if (ret < 0) ret = 0; } return ret; } void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps) { if (pr != NULL) *pr = sig->r; if (ps != NULL) *ps = sig->s; } int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s) { if (r == NULL || s == NULL) return 0; BN_clear_free(sig->r); BN_clear_free(sig->s); sig->r = r; sig->s = s; return 1; } int ossl_dsa_sign_int(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, DSA *dsa, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq) { DSA_SIG *s; /* legacy case uses the method table */ if (dsa->libctx == NULL || dsa->meth != DSA_get_default_method()) s = DSA_do_sign(dgst, dlen, dsa); else s = ossl_dsa_do_sign_int(dgst, dlen, dsa, nonce_type, digestname, libctx, propq); if (s == NULL) { *siglen = 0; return 0; } *siglen = i2d_DSA_SIG(s, sig != NULL ? &sig : NULL); DSA_SIG_free(s); return 1; } int DSA_sign(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, DSA *dsa) { return ossl_dsa_sign_int(type, dgst, dlen, sig, siglen, dsa, 0, NULL, NULL, NULL); } /* data has already been hashed (probably with SHA or SHA-1). */ /*- * returns * 1: correct signature * 0: incorrect signature * -1: error */ int DSA_verify(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int siglen, DSA *dsa) { DSA_SIG *s; const unsigned char *p = sigbuf; unsigned char *der = NULL; int derlen = -1; int ret = -1; s = DSA_SIG_new(); if (s == NULL) return ret; if (d2i_DSA_SIG(&s, &p, siglen) == NULL) goto err; /* Ensure signature uses DER and doesn't have trailing garbage */ derlen = i2d_DSA_SIG(s, &der); if (derlen != siglen || memcmp(sigbuf, der, derlen)) goto err; ret = DSA_do_verify(dgst, dgst_len, s, dsa); err: OPENSSL_clear_free(der, derlen); DSA_SIG_free(s); return ret; }
./openssl/crypto/dsa/dsa_backend.c
/* * Copyright 2020-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/core_names.h> #include <openssl/err.h> #ifndef FIPS_MODULE # include <openssl/x509.h> #endif #include "crypto/dsa.h" #include "dsa_local.h" /* * The intention with the "backend" source file is to offer backend support * for legacy backends (EVP_PKEY_ASN1_METHOD and EVP_PKEY_METHOD) and provider * implementations alike. */ int ossl_dsa_key_fromdata(DSA *dsa, const OSSL_PARAM params[], int include_private) { const OSSL_PARAM *param_priv_key = NULL, *param_pub_key; BIGNUM *priv_key = NULL, *pub_key = NULL; if (dsa == NULL) return 0; if (include_private) { param_priv_key = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY); } param_pub_key = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY); /* It's ok if neither half is present */ if (param_priv_key == NULL && param_pub_key == NULL) return 1; if (param_pub_key != NULL && !OSSL_PARAM_get_BN(param_pub_key, &pub_key)) goto err; if (param_priv_key != NULL && !OSSL_PARAM_get_BN(param_priv_key, &priv_key)) goto err; if (!DSA_set0_key(dsa, pub_key, priv_key)) goto err; return 1; err: BN_clear_free(priv_key); BN_free(pub_key); return 0; } int ossl_dsa_is_foreign(const DSA *dsa) { #ifndef FIPS_MODULE if (dsa->engine != NULL || DSA_get_method((DSA *)dsa) != DSA_OpenSSL()) return 1; #endif return 0; } static ossl_inline int dsa_bn_dup_check(BIGNUM **out, const BIGNUM *f) { if (f != NULL && (*out = BN_dup(f)) == NULL) return 0; return 1; } DSA *ossl_dsa_dup(const DSA *dsa, int selection) { DSA *dupkey = NULL; /* Do not try to duplicate foreign DSA keys */ if (ossl_dsa_is_foreign(dsa)) return NULL; if ((dupkey = ossl_dsa_new(dsa->libctx)) == NULL) return NULL; if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0 && !ossl_ffc_params_copy(&dupkey->params, &dsa->params)) goto err; dupkey->flags = dsa->flags; if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0 && ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0 || !dsa_bn_dup_check(&dupkey->pub_key, dsa->pub_key))) goto err; if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0 && ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0 || !dsa_bn_dup_check(&dupkey->priv_key, dsa->priv_key))) goto err; #ifndef FIPS_MODULE if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_DSA, &dupkey->ex_data, &dsa->ex_data)) goto err; #endif return dupkey; err: DSA_free(dupkey); return NULL; } #ifndef FIPS_MODULE DSA *ossl_dsa_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *libctx, const char *propq) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; const void *pval; const ASN1_STRING *pstr; const X509_ALGOR *palg; ASN1_INTEGER *privkey = NULL; const BIGNUM *dsa_p, *dsa_g; BIGNUM *dsa_pubkey = NULL, *dsa_privkey = NULL; BN_CTX *ctx = NULL; DSA *dsa = NULL; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8inf)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if ((privkey = d2i_ASN1_INTEGER(NULL, &p, pklen)) == NULL) goto decerr; if (privkey->type == V_ASN1_NEG_INTEGER || ptype != V_ASN1_SEQUENCE) goto decerr; pstr = pval; pm = pstr->data; pmlen = pstr->length; if ((dsa = d2i_DSAparams(NULL, &pm, pmlen)) == NULL) goto decerr; /* We have parameters now set private key */ if ((dsa_privkey = BN_secure_new()) == NULL || !ASN1_INTEGER_to_BN(privkey, dsa_privkey)) { ERR_raise(ERR_LIB_DSA, DSA_R_BN_ERROR); goto dsaerr; } /* Calculate public key */ if ((dsa_pubkey = BN_new()) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_BN_LIB); goto dsaerr; } if ((ctx = BN_CTX_new()) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_BN_LIB); goto dsaerr; } dsa_p = DSA_get0_p(dsa); dsa_g = DSA_get0_g(dsa); BN_set_flags(dsa_privkey, BN_FLG_CONSTTIME); if (!BN_mod_exp(dsa_pubkey, dsa_g, dsa_privkey, dsa_p, ctx)) { ERR_raise(ERR_LIB_DSA, DSA_R_BN_ERROR); goto dsaerr; } if (!DSA_set0_key(dsa, dsa_pubkey, dsa_privkey)) { ERR_raise(ERR_LIB_DSA, ERR_R_INTERNAL_ERROR); goto dsaerr; } goto done; decerr: ERR_raise(ERR_LIB_DSA, DSA_R_DECODE_ERROR); dsaerr: BN_free(dsa_privkey); BN_free(dsa_pubkey); DSA_free(dsa); dsa = NULL; done: BN_CTX_free(ctx); ASN1_STRING_clear_free(privkey); return dsa; } #endif
./openssl/crypto/dsa/dsa_key.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/self_test.h> #include "prov/providercommon.h" #include "crypto/dsa.h" #include "dsa_local.h" #ifdef FIPS_MODULE # define MIN_STRENGTH 112 #else # define MIN_STRENGTH 80 #endif static int dsa_keygen(DSA *dsa); int DSA_generate_key(DSA *dsa) { #ifndef FIPS_MODULE if (dsa->meth->dsa_keygen != NULL) return dsa->meth->dsa_keygen(dsa); #endif return dsa_keygen(dsa); } int ossl_dsa_generate_public_key(BN_CTX *ctx, const DSA *dsa, const BIGNUM *priv_key, BIGNUM *pub_key) { int ret = 0; BIGNUM *prk = BN_new(); if (prk == NULL) return 0; BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME); /* pub_key = g ^ priv_key mod p */ if (!BN_mod_exp(pub_key, dsa->params.g, prk, dsa->params.p, ctx)) goto err; ret = 1; err: BN_clear_free(prk); return ret; } #ifdef FIPS_MODULE /* * Refer: FIPS 140-3 IG 10.3.A Additional Comment 1 * Perform a KAT by duplicating the public key generation. * * NOTE: This issue requires a background understanding, provided in a separate * document; the current IG 10.3.A AC1 is insufficient regarding the PCT for * the key agreement scenario. * * Currently IG 10.3.A requires PCT in the mode of use prior to use of the * key pair, citing the PCT defined in the associated standard. For key * agreement, the only PCT defined in SP 800-56A is that of Section 5.6.2.4: * the comparison of the original public key to a newly calculated public key. */ static int dsa_keygen_knownanswer_test(DSA *dsa, BN_CTX *ctx, OSSL_CALLBACK *cb, void *cbarg) { int len, ret = 0; OSSL_SELF_TEST *st = NULL; unsigned char bytes[512] = {0}; BIGNUM *pub_key2 = BN_new(); if (pub_key2 == NULL) return 0; st = OSSL_SELF_TEST_new(cb, cbarg); if (st == NULL) goto err; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT_KAT, OSSL_SELF_TEST_DESC_PCT_DSA); if (!ossl_dsa_generate_public_key(ctx, dsa, dsa->priv_key, pub_key2)) goto err; if (BN_num_bytes(pub_key2) > (int)sizeof(bytes)) goto err; len = BN_bn2bin(pub_key2, bytes); OSSL_SELF_TEST_oncorrupt_byte(st, bytes); if (BN_bin2bn(bytes, len, pub_key2) != NULL) ret = !BN_cmp(dsa->pub_key, pub_key2); err: OSSL_SELF_TEST_onend(st, ret); OSSL_SELF_TEST_free(st); BN_free(pub_key2); return ret; } /* * FIPS 140-2 IG 9.9 AS09.33 * Perform a sign/verify operation. */ static int dsa_keygen_pairwise_test(DSA *dsa, OSSL_CALLBACK *cb, void *cbarg) { int ret = 0; unsigned char dgst[16] = {0}; unsigned int dgst_len = (unsigned int)sizeof(dgst); DSA_SIG *sig = NULL; OSSL_SELF_TEST *st = NULL; st = OSSL_SELF_TEST_new(cb, cbarg); if (st == NULL) goto err; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT, OSSL_SELF_TEST_DESC_PCT_DSA); sig = DSA_do_sign(dgst, (int)dgst_len, dsa); if (sig == NULL) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, dgst); if (DSA_do_verify(dgst, dgst_len, sig, dsa) != 1) goto err; ret = 1; err: OSSL_SELF_TEST_onend(st, ret); OSSL_SELF_TEST_free(st); DSA_SIG_free(sig); return ret; } #endif /* FIPS_MODULE */ static int dsa_keygen(DSA *dsa) { int ok = 0; BN_CTX *ctx = NULL; BIGNUM *pub_key = NULL, *priv_key = NULL; if ((ctx = BN_CTX_new_ex(dsa->libctx)) == NULL) goto err; if (dsa->priv_key == NULL) { if ((priv_key = BN_secure_new()) == NULL) goto err; } else { priv_key = dsa->priv_key; } /* Do a partial check for invalid p, q, g */ if (!ossl_ffc_params_simple_validate(dsa->libctx, &dsa->params, FFC_PARAM_TYPE_DSA, NULL)) goto err; /* * For FFC FIPS 186-4 keygen * security strength s = 112, * Max Private key size N = len(q) */ if (!ossl_ffc_generate_private_key(ctx, &dsa->params, BN_num_bits(dsa->params.q), MIN_STRENGTH, priv_key)) goto err; if (dsa->pub_key == NULL) { if ((pub_key = BN_new()) == NULL) goto err; } else { pub_key = dsa->pub_key; } if (!ossl_dsa_generate_public_key(ctx, dsa, priv_key, pub_key)) goto err; dsa->priv_key = priv_key; dsa->pub_key = pub_key; ok = 1; #ifdef FIPS_MODULE { OSSL_CALLBACK *cb = NULL; void *cbarg = NULL; OSSL_SELF_TEST_get_callback(dsa->libctx, &cb, &cbarg); ok = dsa_keygen_pairwise_test(dsa, cb, cbarg) && dsa_keygen_knownanswer_test(dsa, ctx, cb, cbarg); if (!ok) { ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT); BN_free(dsa->pub_key); BN_clear_free(dsa->priv_key); dsa->pub_key = NULL; dsa->priv_key = NULL; BN_CTX_free(ctx); return ok; } } #endif dsa->dirty_cnt++; err: if (pub_key != dsa->pub_key) BN_free(pub_key); if (priv_key != dsa->priv_key) BN_free(priv_key); BN_CTX_free(ctx); return ok; }
./openssl/crypto/dsa/dsa_vrf.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "internal/cryptlib.h" #include "dsa_local.h" int DSA_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa) { return dsa->meth->dsa_do_verify(dgst, dgst_len, sig, dsa); }
./openssl/crypto/dsa/dsa_depr.c
/* * Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * This file contains deprecated function(s) that are now wrappers to the new * version(s). */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/opensslconf.h> #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/bn.h> #include <openssl/dsa.h> #include <openssl/sha.h> DSA *DSA_generate_parameters(int bits, unsigned char *seed_in, int seed_len, int *counter_ret, unsigned long *h_ret, void (*callback) (int, int, void *), void *cb_arg) { BN_GENCB *cb; DSA *ret; if ((ret = DSA_new()) == NULL) return NULL; cb = BN_GENCB_new(); if (cb == NULL) goto err; BN_GENCB_set_old(cb, callback, cb_arg); if (DSA_generate_parameters_ex(ret, bits, seed_in, seed_len, counter_ret, h_ret, cb)) { BN_GENCB_free(cb); return ret; } BN_GENCB_free(cb); err: DSA_free(ret); return NULL; }
./openssl/crypto/dsa/dsa_ameth.c
/* * Copyright 2006-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <openssl/x509.h> #include <openssl/asn1.h> #include <openssl/bn.h> #include <openssl/core_names.h> #include <openssl/param_build.h> #include "internal/cryptlib.h" #include "crypto/asn1.h" #include "crypto/dsa.h" #include "crypto/evp.h" #include "internal/ffc.h" #include "dsa_local.h" static int dsa_pub_decode(EVP_PKEY *pkey, const X509_PUBKEY *pubkey) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; const void *pval; const ASN1_STRING *pstr; X509_ALGOR *palg; ASN1_INTEGER *public_key = NULL; DSA *dsa = NULL; if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if (ptype == V_ASN1_SEQUENCE) { pstr = pval; pm = pstr->data; pmlen = pstr->length; if ((dsa = d2i_DSAparams(NULL, &pm, pmlen)) == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_DECODE_ERROR); goto err; } } else if ((ptype == V_ASN1_NULL) || (ptype == V_ASN1_UNDEF)) { if ((dsa = DSA_new()) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_DSA_LIB); goto err; } } else { ERR_raise(ERR_LIB_DSA, DSA_R_PARAMETER_ENCODING_ERROR); goto err; } if ((public_key = d2i_ASN1_INTEGER(NULL, &p, pklen)) == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_DECODE_ERROR); goto err; } if ((dsa->pub_key = ASN1_INTEGER_to_BN(public_key, NULL)) == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_BN_DECODE_ERROR); goto err; } dsa->dirty_cnt++; ASN1_INTEGER_free(public_key); EVP_PKEY_assign_DSA(pkey, dsa); return 1; err: ASN1_INTEGER_free(public_key); DSA_free(dsa); return 0; } static int dsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) { DSA *dsa; int ptype; unsigned char *penc = NULL; int penclen; ASN1_STRING *str = NULL; ASN1_INTEGER *pubint = NULL; ASN1_OBJECT *aobj; dsa = pkey->pkey.dsa; if (pkey->save_parameters && dsa->params.p != NULL && dsa->params.q != NULL && dsa->params.g != NULL) { str = ASN1_STRING_new(); if (str == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } str->length = i2d_DSAparams(dsa, &str->data); if (str->length <= 0) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } ptype = V_ASN1_SEQUENCE; } else ptype = V_ASN1_UNDEF; pubint = BN_to_ASN1_INTEGER(dsa->pub_key, NULL); if (pubint == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } penclen = i2d_ASN1_INTEGER(pubint, &penc); ASN1_INTEGER_free(pubint); if (penclen <= 0) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } aobj = OBJ_nid2obj(EVP_PKEY_DSA); if (aobj == NULL) goto err; if (X509_PUBKEY_set0_param(pk, aobj, ptype, str, penc, penclen)) return 1; err: OPENSSL_free(penc); ASN1_STRING_free(str); return 0; } /* * In PKCS#8 DSA: you just get a private key integer and parameters in the * AlgorithmIdentifier the pubkey must be recalculated. */ static int dsa_priv_decode(EVP_PKEY *pkey, const PKCS8_PRIV_KEY_INFO *p8) { int ret = 0; DSA *dsa = ossl_dsa_key_from_pkcs8(p8, NULL, NULL); if (dsa != NULL) { ret = 1; EVP_PKEY_assign_DSA(pkey, dsa); } return ret; } static int dsa_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey) { ASN1_STRING *params = NULL; ASN1_INTEGER *prkey = NULL; unsigned char *dp = NULL; int dplen; if (pkey->pkey.dsa == NULL|| pkey->pkey.dsa->priv_key == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_MISSING_PARAMETERS); goto err; } params = ASN1_STRING_new(); if (params == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } params->length = i2d_DSAparams(pkey->pkey.dsa, &params->data); if (params->length <= 0) { ERR_raise(ERR_LIB_DSA, ERR_R_ASN1_LIB); goto err; } params->type = V_ASN1_SEQUENCE; /* Get private key into integer */ prkey = BN_to_ASN1_INTEGER(pkey->pkey.dsa->priv_key, NULL); if (prkey == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_BN_ERROR); goto err; } dplen = i2d_ASN1_INTEGER(prkey, &dp); ASN1_STRING_clear_free(prkey); if (dplen <= 0) { ERR_raise(ERR_LIB_DSA, DSA_R_BN_ERROR); goto err; } if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_dsa), 0, V_ASN1_SEQUENCE, params, dp, dplen)) { OPENSSL_clear_free(dp, dplen); goto err; } return 1; err: ASN1_STRING_free(params); return 0; } static int int_dsa_size(const EVP_PKEY *pkey) { return DSA_size(pkey->pkey.dsa); } static int dsa_bits(const EVP_PKEY *pkey) { return DSA_bits(pkey->pkey.dsa); } static int dsa_security_bits(const EVP_PKEY *pkey) { return DSA_security_bits(pkey->pkey.dsa); } static int dsa_missing_parameters(const EVP_PKEY *pkey) { DSA *dsa; dsa = pkey->pkey.dsa; return dsa == NULL || dsa->params.p == NULL || dsa->params.q == NULL || dsa->params.g == NULL; } static int dsa_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) { if (to->pkey.dsa == NULL) { to->pkey.dsa = DSA_new(); if (to->pkey.dsa == NULL) return 0; } if (!ossl_ffc_params_copy(&to->pkey.dsa->params, &from->pkey.dsa->params)) return 0; to->pkey.dsa->dirty_cnt++; return 1; } static int dsa_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { return ossl_ffc_params_cmp(&a->pkey.dsa->params, &b->pkey.dsa->params, 1); } static int dsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { return BN_cmp(b->pkey.dsa->pub_key, a->pkey.dsa->pub_key) == 0; } static void int_dsa_free(EVP_PKEY *pkey) { DSA_free(pkey->pkey.dsa); } static int do_dsa_print(BIO *bp, const DSA *x, int off, int ptype) { int ret = 0; const char *ktype = NULL; const BIGNUM *priv_key, *pub_key; int mod_len = 0; if (x->params.p != NULL) mod_len = DSA_bits(x); if (ptype == 2) priv_key = x->priv_key; else priv_key = NULL; if (ptype > 0) pub_key = x->pub_key; else pub_key = NULL; if (ptype == 2) ktype = "Private-Key"; else if (ptype == 1) ktype = "Public-Key"; else ktype = "DSA-Parameters"; if (priv_key != NULL) { if (!BIO_indent(bp, off, 128)) goto err; if (BIO_printf(bp, "%s: (%d bit)\n", ktype, mod_len) <= 0) goto err; } else { if (BIO_printf(bp, "Public-Key: (%d bit)\n", mod_len) <= 0) goto err; } if (!ASN1_bn_print(bp, "priv:", priv_key, NULL, off)) goto err; if (!ASN1_bn_print(bp, "pub: ", pub_key, NULL, off)) goto err; if (!ossl_ffc_params_print(bp, &x->params, off)) goto err; ret = 1; err: return ret; } static int dsa_param_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { DSA *dsa; if ((dsa = d2i_DSAparams(NULL, pder, derlen)) == NULL) return 0; dsa->dirty_cnt++; EVP_PKEY_assign_DSA(pkey, dsa); return 1; } static int dsa_param_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_DSAparams(pkey->pkey.dsa, pder); } static int dsa_param_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dsa_print(bp, pkey->pkey.dsa, indent, 0); } static int dsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dsa_print(bp, pkey->pkey.dsa, indent, 1); } static int dsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dsa_print(bp, pkey->pkey.dsa, indent, 2); } static int old_dsa_priv_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { DSA *dsa; if ((dsa = d2i_DSAPrivateKey(NULL, pder, derlen)) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_DSA_LIB); return 0; } dsa->dirty_cnt++; EVP_PKEY_assign_DSA(pkey, dsa); return 1; } static int old_dsa_priv_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_DSAPrivateKey(pkey->pkey.dsa, pder); } static int dsa_sig_print(BIO *bp, const X509_ALGOR *sigalg, const ASN1_STRING *sig, int indent, ASN1_PCTX *pctx) { DSA_SIG *dsa_sig; const unsigned char *p; if (sig == NULL) { if (BIO_puts(bp, "\n") <= 0) return 0; else return 1; } p = sig->data; dsa_sig = d2i_DSA_SIG(NULL, &p, sig->length); if (dsa_sig != NULL) { int rv = 0; const BIGNUM *r, *s; DSA_SIG_get0(dsa_sig, &r, &s); if (BIO_write(bp, "\n", 1) != 1) goto err; if (!ASN1_bn_print(bp, "r: ", r, NULL, indent)) goto err; if (!ASN1_bn_print(bp, "s: ", s, NULL, indent)) goto err; rv = 1; err: DSA_SIG_free(dsa_sig); return rv; } if (BIO_puts(bp, "\n") <= 0) return 0; return X509_signature_dump(bp, sig, indent); } static int dsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) { switch (op) { case ASN1_PKEY_CTRL_DEFAULT_MD_NID: *(int *)arg2 = NID_sha256; return 1; default: return -2; } } static size_t dsa_pkey_dirty_cnt(const EVP_PKEY *pkey) { return pkey->pkey.dsa->dirty_cnt; } static int dsa_pkey_export_to(const EVP_PKEY *from, void *to_keydata, OSSL_FUNC_keymgmt_import_fn *importer, OSSL_LIB_CTX *libctx, const char *propq) { DSA *dsa = from->pkey.dsa; OSSL_PARAM_BLD *tmpl; const BIGNUM *p = DSA_get0_p(dsa), *g = DSA_get0_g(dsa); const BIGNUM *q = DSA_get0_q(dsa), *pub_key = DSA_get0_pub_key(dsa); const BIGNUM *priv_key = DSA_get0_priv_key(dsa); OSSL_PARAM *params; int selection = 0; int rv = 0; if (p == NULL || q == NULL || g == NULL) return 0; tmpl = OSSL_PARAM_BLD_new(); if (tmpl == NULL) return 0; if (!OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_Q, q) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)) goto err; selection |= OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS; if (pub_key != NULL) { if (!OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PUB_KEY, pub_key)) goto err; selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY; } if (priv_key != NULL) { if (!OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PRIV_KEY, priv_key)) goto err; selection |= OSSL_KEYMGMT_SELECT_PRIVATE_KEY; } if ((params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) goto err; /* We export, the provider imports */ rv = importer(to_keydata, selection, params); OSSL_PARAM_free(params); err: OSSL_PARAM_BLD_free(tmpl); return rv; } static int dsa_pkey_import_from(const OSSL_PARAM params[], void *vpctx) { EVP_PKEY_CTX *pctx = vpctx; EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pctx); DSA *dsa = ossl_dsa_new(pctx->libctx); if (dsa == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_DSA_LIB); return 0; } if (!ossl_dsa_ffc_params_fromdata(dsa, params) || !ossl_dsa_key_fromdata(dsa, params, 1) || !EVP_PKEY_assign_DSA(pkey, dsa)) { DSA_free(dsa); return 0; } return 1; } static int dsa_pkey_copy(EVP_PKEY *to, EVP_PKEY *from) { DSA *dsa = from->pkey.dsa; DSA *dupkey = NULL; int ret; if (dsa != NULL) { dupkey = ossl_dsa_dup(dsa, OSSL_KEYMGMT_SELECT_ALL); if (dupkey == NULL) return 0; } ret = EVP_PKEY_assign_DSA(to, dupkey); if (!ret) DSA_free(dupkey); return ret; } /* NB these are sorted in pkey_id order, lowest first */ const EVP_PKEY_ASN1_METHOD ossl_dsa_asn1_meths[5] = { { EVP_PKEY_DSA2, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA1, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA4, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA3, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA, EVP_PKEY_DSA, 0, "DSA", "OpenSSL DSA method", dsa_pub_decode, dsa_pub_encode, dsa_pub_cmp, dsa_pub_print, dsa_priv_decode, dsa_priv_encode, dsa_priv_print, int_dsa_size, dsa_bits, dsa_security_bits, dsa_param_decode, dsa_param_encode, dsa_missing_parameters, dsa_copy_parameters, dsa_cmp_parameters, dsa_param_print, dsa_sig_print, int_dsa_free, dsa_pkey_ctrl, old_dsa_priv_decode, old_dsa_priv_encode, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, dsa_pkey_dirty_cnt, dsa_pkey_export_to, dsa_pkey_import_from, dsa_pkey_copy } };
./openssl/crypto/dsa/dsa_check.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include "dsa_local.h" #include "crypto/dsa.h" int ossl_dsa_check_params(const DSA *dsa, int checktype, int *ret) { if (checktype == OSSL_KEYMGMT_VALIDATE_QUICK_CHECK) return ossl_ffc_params_simple_validate(dsa->libctx, &dsa->params, FFC_PARAM_TYPE_DSA, ret); else /* * Do full FFC domain params validation according to FIPS-186-4 * - always in FIPS_MODULE * - only if possible (i.e., seed is set) in default provider */ return ossl_ffc_params_full_validate(dsa->libctx, &dsa->params, FFC_PARAM_TYPE_DSA, ret); } /* * See SP800-56Ar3 Section 5.6.2.3.1 : FFC Full public key validation. */ int ossl_dsa_check_pub_key(const DSA *dsa, const BIGNUM *pub_key, int *ret) { return ossl_ffc_validate_public_key(&dsa->params, pub_key, ret) && *ret == 0; } /* * See SP800-56Ar3 Section 5.6.2.3.1 : FFC Partial public key validation. * To only be used with ephemeral FFC public keys generated using the approved * safe-prime groups. */ int ossl_dsa_check_pub_key_partial(const DSA *dsa, const BIGNUM *pub_key, int *ret) { return ossl_ffc_validate_public_key_partial(&dsa->params, pub_key, ret) && *ret == 0; } int ossl_dsa_check_priv_key(const DSA *dsa, const BIGNUM *priv_key, int *ret) { *ret = 0; return (dsa->params.q != NULL && ossl_ffc_validate_private_key(dsa->params.q, priv_key, ret)); } /* * FFC pairwise check from SP800-56A R3. * Section 5.6.2.1.4 Owner Assurance of Pair-wise Consistency */ int ossl_dsa_check_pairwise(const DSA *dsa) { int ret = 0; BN_CTX *ctx = NULL; BIGNUM *pub_key = NULL; if (dsa->params.p == NULL || dsa->params.g == NULL || dsa->priv_key == NULL || dsa->pub_key == NULL) return 0; ctx = BN_CTX_new_ex(dsa->libctx); if (ctx == NULL) goto err; pub_key = BN_new(); if (pub_key == NULL) goto err; /* recalculate the public key = (g ^ priv) mod p */ if (!ossl_dsa_generate_public_key(ctx, dsa, dsa->priv_key, pub_key)) goto err; /* check it matches the existing pubic_key */ ret = BN_cmp(pub_key, dsa->pub_key) == 0; err: BN_free(pub_key); BN_CTX_free(ctx); return ret; }
./openssl/crypto/dsa/dsa_lib.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/bn.h> #ifndef FIPS_MODULE # include <openssl/engine.h> #endif #include "internal/cryptlib.h" #include "internal/refcount.h" #include "crypto/dsa.h" #include "crypto/dh.h" /* required by DSA_dup_DH() */ #include "dsa_local.h" static DSA *dsa_new_intern(ENGINE *engine, OSSL_LIB_CTX *libctx); #ifndef FIPS_MODULE int DSA_set_ex_data(DSA *d, int idx, void *arg) { return CRYPTO_set_ex_data(&d->ex_data, idx, arg); } void *DSA_get_ex_data(const DSA *d, int idx) { return CRYPTO_get_ex_data(&d->ex_data, idx); } # ifndef OPENSSL_NO_DH DH *DSA_dup_DH(const DSA *r) { /* * DSA has p, q, g, optional pub_key, optional priv_key. * DH has p, optional length, g, optional pub_key, * optional priv_key, optional q. */ DH *ret = NULL; BIGNUM *pub_key = NULL, *priv_key = NULL; if (r == NULL) goto err; ret = DH_new(); if (ret == NULL) goto err; if (!ossl_ffc_params_copy(ossl_dh_get0_params(ret), &r->params)) goto err; if (r->pub_key != NULL) { pub_key = BN_dup(r->pub_key); if (pub_key == NULL) goto err; if (r->priv_key != NULL) { priv_key = BN_dup(r->priv_key); if (priv_key == NULL) goto err; } if (!DH_set0_key(ret, pub_key, priv_key)) goto err; } else if (r->priv_key != NULL) { /* Shouldn't happen */ goto err; } return ret; err: BN_free(pub_key); BN_free(priv_key); DH_free(ret); return NULL; } # endif /* OPENSSL_NO_DH */ void DSA_clear_flags(DSA *d, int flags) { d->flags &= ~flags; } int DSA_test_flags(const DSA *d, int flags) { return d->flags & flags; } void DSA_set_flags(DSA *d, int flags) { d->flags |= flags; } ENGINE *DSA_get0_engine(DSA *d) { return d->engine; } int DSA_set_method(DSA *dsa, const DSA_METHOD *meth) { /* * NB: The caller is specifically setting a method, so it's not up to us * to deal with which ENGINE it comes from. */ const DSA_METHOD *mtmp; mtmp = dsa->meth; if (mtmp->finish) mtmp->finish(dsa); #ifndef OPENSSL_NO_ENGINE ENGINE_finish(dsa->engine); dsa->engine = NULL; #endif dsa->meth = meth; if (meth->init) meth->init(dsa); return 1; } #endif /* FIPS_MODULE */ const DSA_METHOD *DSA_get_method(DSA *d) { return d->meth; } static DSA *dsa_new_intern(ENGINE *engine, OSSL_LIB_CTX *libctx) { DSA *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_CRYPTO_LIB); OPENSSL_free(ret); return NULL; } if (!CRYPTO_NEW_REF(&ret->references, 1)) { CRYPTO_THREAD_lock_free(ret->lock); OPENSSL_free(ret); return NULL; } ret->libctx = libctx; ret->meth = DSA_get_default_method(); #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_ENGINE) ret->flags = ret->meth->flags & ~DSA_FLAG_NON_FIPS_ALLOW; /* early default init */ if (engine) { if (!ENGINE_init(engine)) { ERR_raise(ERR_LIB_DSA, ERR_R_ENGINE_LIB); goto err; } ret->engine = engine; } else ret->engine = ENGINE_get_default_DSA(); if (ret->engine) { ret->meth = ENGINE_get_DSA(ret->engine); if (ret->meth == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_ENGINE_LIB); goto err; } } #endif ret->flags = ret->meth->flags & ~DSA_FLAG_NON_FIPS_ALLOW; #ifndef FIPS_MODULE if (!ossl_crypto_new_ex_data_ex(libctx, CRYPTO_EX_INDEX_DSA, ret, &ret->ex_data)) goto err; #endif ossl_ffc_params_init(&ret->params); if ((ret->meth->init != NULL) && !ret->meth->init(ret)) { ERR_raise(ERR_LIB_DSA, ERR_R_INIT_FAIL); goto err; } return ret; err: DSA_free(ret); return NULL; } DSA *DSA_new_method(ENGINE *engine) { return dsa_new_intern(engine, NULL); } DSA *ossl_dsa_new(OSSL_LIB_CTX *libctx) { return dsa_new_intern(NULL, libctx); } #ifndef FIPS_MODULE DSA *DSA_new(void) { return dsa_new_intern(NULL, NULL); } #endif void DSA_free(DSA *r) { int i; if (r == NULL) return; CRYPTO_DOWN_REF(&r->references, &i); REF_PRINT_COUNT("DSA", r); if (i > 0) return; REF_ASSERT_ISNT(i < 0); if (r->meth != NULL && r->meth->finish != NULL) r->meth->finish(r); #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_ENGINE) ENGINE_finish(r->engine); #endif #ifndef FIPS_MODULE CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DSA, r, &r->ex_data); #endif CRYPTO_THREAD_lock_free(r->lock); CRYPTO_FREE_REF(&r->references); ossl_ffc_params_cleanup(&r->params); BN_clear_free(r->pub_key); BN_clear_free(r->priv_key); OPENSSL_free(r); } int DSA_up_ref(DSA *r) { int i; if (CRYPTO_UP_REF(&r->references, &i) <= 0) return 0; REF_PRINT_COUNT("DSA", r); REF_ASSERT_ISNT(i < 2); return ((i > 1) ? 1 : 0); } void ossl_dsa_set0_libctx(DSA *d, OSSL_LIB_CTX *libctx) { d->libctx = libctx; } void DSA_get0_pqg(const DSA *d, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g) { ossl_ffc_params_get0_pqg(&d->params, p, q, g); } int DSA_set0_pqg(DSA *d, BIGNUM *p, BIGNUM *q, BIGNUM *g) { /* If the fields p, q and g in d are NULL, the corresponding input * parameters MUST be non-NULL. */ if ((d->params.p == NULL && p == NULL) || (d->params.q == NULL && q == NULL) || (d->params.g == NULL && g == NULL)) return 0; ossl_ffc_params_set0_pqg(&d->params, p, q, g); d->dirty_cnt++; return 1; } const BIGNUM *DSA_get0_p(const DSA *d) { return d->params.p; } const BIGNUM *DSA_get0_q(const DSA *d) { return d->params.q; } const BIGNUM *DSA_get0_g(const DSA *d) { return d->params.g; } const BIGNUM *DSA_get0_pub_key(const DSA *d) { return d->pub_key; } const BIGNUM *DSA_get0_priv_key(const DSA *d) { return d->priv_key; } void DSA_get0_key(const DSA *d, const BIGNUM **pub_key, const BIGNUM **priv_key) { if (pub_key != NULL) *pub_key = d->pub_key; if (priv_key != NULL) *priv_key = d->priv_key; } int DSA_set0_key(DSA *d, BIGNUM *pub_key, BIGNUM *priv_key) { if (pub_key != NULL) { BN_free(d->pub_key); d->pub_key = pub_key; } if (priv_key != NULL) { BN_free(d->priv_key); d->priv_key = priv_key; } d->dirty_cnt++; return 1; } int DSA_security_bits(const DSA *d) { if (d->params.p != NULL && d->params.q != NULL) return BN_security_bits(BN_num_bits(d->params.p), BN_num_bits(d->params.q)); return -1; } int DSA_bits(const DSA *dsa) { if (dsa->params.p != NULL) return BN_num_bits(dsa->params.p); return -1; } FFC_PARAMS *ossl_dsa_get0_params(DSA *dsa) { return &dsa->params; } int ossl_dsa_ffc_params_fromdata(DSA *dsa, const OSSL_PARAM params[]) { int ret; FFC_PARAMS *ffc = ossl_dsa_get0_params(dsa); ret = ossl_ffc_params_fromdata(ffc, params); if (ret) dsa->dirty_cnt++; return ret; }
./openssl/crypto/dsa/dsa_prn.c
/* * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/dsa.h> #ifndef OPENSSL_NO_STDIO int DSA_print_fp(FILE *fp, const DSA *x, int off) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = DSA_print(b, x, off); BIO_free(b); return ret; } int DSAparams_print_fp(FILE *fp, const DSA *x) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_DSA, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = DSAparams_print(b, x); BIO_free(b); return ret; } #endif int DSA_print(BIO *bp, const DSA *x, int off) { EVP_PKEY *pk; int ret; pk = EVP_PKEY_new(); if (pk == NULL) return 0; ret = EVP_PKEY_set1_DSA(pk, (DSA *)x); if (ret) ret = EVP_PKEY_print_private(bp, pk, off, NULL); EVP_PKEY_free(pk); return ret; } int DSAparams_print(BIO *bp, const DSA *x) { EVP_PKEY *pk; int ret; pk = EVP_PKEY_new(); if (pk == NULL) return 0; ret = EVP_PKEY_set1_DSA(pk, (DSA *)x); if (ret) ret = EVP_PKEY_print_params(bp, pk, 4, NULL); EVP_PKEY_free(pk); return ret; }
./openssl/crypto/dsa/dsa_meth.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "dsa_local.h" #include <string.h> #include <openssl/err.h> #ifndef OPENSSL_NO_DEPRECATED_3_0 DSA_METHOD *DSA_meth_new(const char *name, int flags) { DSA_METHOD *dsam = OPENSSL_zalloc(sizeof(*dsam)); if (dsam != NULL) { dsam->flags = flags; dsam->name = OPENSSL_strdup(name); if (dsam->name != NULL) return dsam; OPENSSL_free(dsam); } return NULL; } void DSA_meth_free(DSA_METHOD *dsam) { if (dsam != NULL) { OPENSSL_free(dsam->name); OPENSSL_free(dsam); } } DSA_METHOD *DSA_meth_dup(const DSA_METHOD *dsam) { DSA_METHOD *ret = OPENSSL_malloc(sizeof(*ret)); if (ret != NULL) { memcpy(ret, dsam, sizeof(*dsam)); ret->name = OPENSSL_strdup(dsam->name); if (ret->name != NULL) return ret; OPENSSL_free(ret); } return NULL; } const char *DSA_meth_get0_name(const DSA_METHOD *dsam) { return dsam->name; } int DSA_meth_set1_name(DSA_METHOD *dsam, const char *name) { char *tmpname = OPENSSL_strdup(name); if (tmpname == NULL) return 0; OPENSSL_free(dsam->name); dsam->name = tmpname; return 1; } int DSA_meth_get_flags(const DSA_METHOD *dsam) { return dsam->flags; } int DSA_meth_set_flags(DSA_METHOD *dsam, int flags) { dsam->flags = flags; return 1; } void *DSA_meth_get0_app_data(const DSA_METHOD *dsam) { return dsam->app_data; } int DSA_meth_set0_app_data(DSA_METHOD *dsam, void *app_data) { dsam->app_data = app_data; return 1; } DSA_SIG *(*DSA_meth_get_sign(const DSA_METHOD *dsam)) (const unsigned char *, int, DSA *) { return dsam->dsa_do_sign; } int DSA_meth_set_sign(DSA_METHOD *dsam, DSA_SIG *(*sign) (const unsigned char *, int, DSA *)) { dsam->dsa_do_sign = sign; return 1; } int (*DSA_meth_get_sign_setup(const DSA_METHOD *dsam)) (DSA *, BN_CTX *, BIGNUM **, BIGNUM **) { return dsam->dsa_sign_setup; } int DSA_meth_set_sign_setup(DSA_METHOD *dsam, int (*sign_setup) (DSA *, BN_CTX *, BIGNUM **, BIGNUM **)) { dsam->dsa_sign_setup = sign_setup; return 1; } int (*DSA_meth_get_verify(const DSA_METHOD *dsam)) (const unsigned char *, int, DSA_SIG *, DSA *) { return dsam->dsa_do_verify; } int DSA_meth_set_verify(DSA_METHOD *dsam, int (*verify) (const unsigned char *, int, DSA_SIG *, DSA *)) { dsam->dsa_do_verify = verify; return 1; } int (*DSA_meth_get_mod_exp(const DSA_METHOD *dsam)) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *) { return dsam->dsa_mod_exp; } int DSA_meth_set_mod_exp(DSA_METHOD *dsam, int (*mod_exp) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *)) { dsam->dsa_mod_exp = mod_exp; return 1; } int (*DSA_meth_get_bn_mod_exp(const DSA_METHOD *dsam)) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *) { return dsam->bn_mod_exp; } int DSA_meth_set_bn_mod_exp(DSA_METHOD *dsam, int (*bn_mod_exp) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *)) { dsam->bn_mod_exp = bn_mod_exp; return 1; } int (*DSA_meth_get_init(const DSA_METHOD *dsam))(DSA *) { return dsam->init; } int DSA_meth_set_init(DSA_METHOD *dsam, int (*init)(DSA *)) { dsam->init = init; return 1; } int (*DSA_meth_get_finish(const DSA_METHOD *dsam)) (DSA *) { return dsam->finish; } int DSA_meth_set_finish(DSA_METHOD *dsam, int (*finish) (DSA *)) { dsam->finish = finish; return 1; } int (*DSA_meth_get_paramgen(const DSA_METHOD *dsam)) (DSA *, int, const unsigned char *, int, int *, unsigned long *, BN_GENCB *) { return dsam->dsa_paramgen; } int DSA_meth_set_paramgen(DSA_METHOD *dsam, int (*paramgen) (DSA *, int, const unsigned char *, int, int *, unsigned long *, BN_GENCB *)) { dsam->dsa_paramgen = paramgen; return 1; } int (*DSA_meth_get_keygen(const DSA_METHOD *dsam)) (DSA *) { return dsam->dsa_keygen; } int DSA_meth_set_keygen(DSA_METHOD *dsam, int (*keygen) (DSA *)) { dsam->dsa_keygen = keygen; return 1; } #endif
./openssl/crypto/dsa/dsa_gen.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/opensslconf.h> #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/bn.h> #include <openssl/rand.h> #include <openssl/sha.h> #include "crypto/dsa.h" #include "dsa_local.h" int ossl_dsa_generate_ffc_parameters(DSA *dsa, int type, int pbits, int qbits, BN_GENCB *cb) { int ret = 0, res; #ifndef FIPS_MODULE if (type == DSA_PARAMGEN_TYPE_FIPS_186_2) ret = ossl_ffc_params_FIPS186_2_generate(dsa->libctx, &dsa->params, FFC_PARAM_TYPE_DSA, pbits, qbits, &res, cb); else #endif ret = ossl_ffc_params_FIPS186_4_generate(dsa->libctx, &dsa->params, FFC_PARAM_TYPE_DSA, pbits, qbits, &res, cb); if (ret > 0) dsa->dirty_cnt++; return ret; } #ifndef FIPS_MODULE int DSA_generate_parameters_ex(DSA *dsa, int bits, const unsigned char *seed_in, int seed_len, int *counter_ret, unsigned long *h_ret, BN_GENCB *cb) { if (dsa->meth->dsa_paramgen) return dsa->meth->dsa_paramgen(dsa, bits, seed_in, seed_len, counter_ret, h_ret, cb); if (seed_in != NULL && !ossl_ffc_params_set_validate_params(&dsa->params, seed_in, seed_len, -1)) return 0; /* The old code used FIPS 186-2 DSA Parameter generation */ if (bits < 2048 && seed_len <= 20) { if (!ossl_dsa_generate_ffc_parameters(dsa, DSA_PARAMGEN_TYPE_FIPS_186_2, bits, 160, cb)) return 0; } else { if (!ossl_dsa_generate_ffc_parameters(dsa, DSA_PARAMGEN_TYPE_FIPS_186_4, bits, 0, cb)) return 0; } if (counter_ret != NULL) *counter_ret = dsa->params.pcounter; if (h_ret != NULL) *h_ret = dsa->params.h; return 1; } #endif
./openssl/crypto/dsa/dsa_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/dsaerr.h> #include "crypto/dsaerr.h" #ifndef OPENSSL_NO_DSA # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA DSA_str_reasons[] = { {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_BAD_FFC_PARAMETERS), "bad ffc parameters"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_BAD_Q_VALUE), "bad q value"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_BN_DECODE_ERROR), "bn decode error"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_BN_ERROR), "bn error"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_DECODE_ERROR), "decode error"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_INVALID_DIGEST_TYPE), "invalid digest type"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_INVALID_PARAMETERS), "invalid parameters"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_MISSING_PARAMETERS), "missing parameters"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_MISSING_PRIVATE_KEY), "missing private key"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_MODULUS_TOO_LARGE), "modulus too large"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_NO_PARAMETERS_SET), "no parameters set"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_PARAMETER_ENCODING_ERROR), "parameter encoding error"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_P_NOT_PRIME), "p not prime"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_Q_NOT_PRIME), "q not prime"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_SEED_LEN_SMALL), "seed_len is less than the length of q"}, {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_TOO_MANY_RETRIES), "too many retries"}, {0, NULL} }; # endif int ossl_err_load_DSA_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(DSA_str_reasons[0].error) == NULL) ERR_load_strings_const(DSA_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
./openssl/crypto/dsa/dsa_ossl.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include "crypto/bn.h" #include <openssl/bn.h> #include <openssl/sha.h> #include "dsa_local.h" #include <openssl/asn1.h> #include "internal/deterministic_nonce.h" #define MIN_DSA_SIGN_QBITS 128 #define MAX_DSA_SIGN_RETRIES 8 static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa); static int dsa_sign_setup_no_digest(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp); static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp, const unsigned char *dgst, int dlen, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq); static int dsa_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa); static int dsa_init(DSA *dsa); static int dsa_finish(DSA *dsa); static BIGNUM *dsa_mod_inverse_fermat(const BIGNUM *k, const BIGNUM *q, BN_CTX *ctx); static DSA_METHOD openssl_dsa_meth = { "OpenSSL DSA method", dsa_do_sign, dsa_sign_setup_no_digest, dsa_do_verify, NULL, /* dsa_mod_exp, */ NULL, /* dsa_bn_mod_exp, */ dsa_init, dsa_finish, DSA_FLAG_FIPS_METHOD, NULL, NULL, NULL }; static const DSA_METHOD *default_DSA_method = &openssl_dsa_meth; #ifndef FIPS_MODULE void DSA_set_default_method(const DSA_METHOD *meth) { default_DSA_method = meth; } #endif /* FIPS_MODULE */ const DSA_METHOD *DSA_get_default_method(void) { return default_DSA_method; } const DSA_METHOD *DSA_OpenSSL(void) { return &openssl_dsa_meth; } DSA_SIG *ossl_dsa_do_sign_int(const unsigned char *dgst, int dlen, DSA *dsa, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq) { BIGNUM *kinv = NULL; BIGNUM *m, *blind, *blindm, *tmp; BN_CTX *ctx = NULL; int reason = ERR_R_BN_LIB; DSA_SIG *ret = NULL; int rv = 0; int retries = 0; if (dsa->params.p == NULL || dsa->params.q == NULL || dsa->params.g == NULL) { reason = DSA_R_MISSING_PARAMETERS; goto err; } if (dsa->priv_key == NULL) { reason = DSA_R_MISSING_PRIVATE_KEY; goto err; } ret = DSA_SIG_new(); if (ret == NULL) goto err; ret->r = BN_new(); ret->s = BN_new(); if (ret->r == NULL || ret->s == NULL) goto err; ctx = BN_CTX_new_ex(dsa->libctx); if (ctx == NULL) goto err; m = BN_CTX_get(ctx); blind = BN_CTX_get(ctx); blindm = BN_CTX_get(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) goto err; redo: if (!dsa_sign_setup(dsa, ctx, &kinv, &ret->r, dgst, dlen, nonce_type, digestname, libctx, propq)) goto err; if (dlen > BN_num_bytes(dsa->params.q)) /* * if the digest length is greater than the size of q use the * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3, * 4.2 */ dlen = BN_num_bytes(dsa->params.q); if (BN_bin2bn(dgst, dlen, m) == NULL) goto err; /* * The normal signature calculation is: * * s := k^-1 * (m + r * priv_key) mod q * * We will blind this to protect against side channel attacks * * s := blind^-1 * k^-1 * (blind * m + blind * r * priv_key) mod q */ /* * Generate a blinding value * The size of q is tested in dsa_sign_setup() so there should not be an infinite loop here. */ do { if (!BN_priv_rand_ex(blind, BN_num_bits(dsa->params.q) - 1, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY, 0, ctx)) goto err; } while (BN_is_zero(blind)); BN_set_flags(blind, BN_FLG_CONSTTIME); BN_set_flags(blindm, BN_FLG_CONSTTIME); BN_set_flags(tmp, BN_FLG_CONSTTIME); /* tmp := blind * priv_key * r mod q */ if (!BN_mod_mul(tmp, blind, dsa->priv_key, dsa->params.q, ctx)) goto err; if (!BN_mod_mul(tmp, tmp, ret->r, dsa->params.q, ctx)) goto err; /* blindm := blind * m mod q */ if (!BN_mod_mul(blindm, blind, m, dsa->params.q, ctx)) goto err; /* s : = (blind * priv_key * r) + (blind * m) mod q */ if (!BN_mod_add_quick(ret->s, tmp, blindm, dsa->params.q)) goto err; /* s := s * k^-1 mod q */ if (!BN_mod_mul(ret->s, ret->s, kinv, dsa->params.q, ctx)) goto err; /* s:= s * blind^-1 mod q */ if (BN_mod_inverse(blind, blind, dsa->params.q, ctx) == NULL) goto err; if (!BN_mod_mul(ret->s, ret->s, blind, dsa->params.q, ctx)) goto err; /* * Redo if r or s is zero as required by FIPS 186-4: Section 4.6 * This is very unlikely. * Limit the retries so there is no possibility of an infinite * loop for bad domain parameter values. */ if (BN_is_zero(ret->r) || BN_is_zero(ret->s)) { if (retries++ > MAX_DSA_SIGN_RETRIES) { reason = DSA_R_TOO_MANY_RETRIES; goto err; } goto redo; } rv = 1; err: if (rv == 0) { ERR_raise(ERR_LIB_DSA, reason); DSA_SIG_free(ret); ret = NULL; } BN_CTX_free(ctx); BN_clear_free(kinv); return ret; } static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) { return ossl_dsa_do_sign_int(dgst, dlen, dsa, 0, NULL, NULL, NULL); } static int dsa_sign_setup_no_digest(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { return dsa_sign_setup(dsa, ctx_in, kinvp, rp, NULL, 0, 0, NULL, NULL, NULL); } static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp, const unsigned char *dgst, int dlen, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq) { BN_CTX *ctx = NULL; BIGNUM *k, *kinv = NULL, *r = *rp; BIGNUM *l; int ret = 0; int q_bits, q_words; if (!dsa->params.p || !dsa->params.q || !dsa->params.g) { ERR_raise(ERR_LIB_DSA, DSA_R_MISSING_PARAMETERS); return 0; } /* Reject obviously invalid parameters */ if (BN_is_zero(dsa->params.p) || BN_is_zero(dsa->params.q) || BN_is_zero(dsa->params.g) || BN_is_negative(dsa->params.p) || BN_is_negative(dsa->params.q) || BN_is_negative(dsa->params.g)) { ERR_raise(ERR_LIB_DSA, DSA_R_INVALID_PARAMETERS); return 0; } if (dsa->priv_key == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_MISSING_PRIVATE_KEY); return 0; } k = BN_new(); l = BN_new(); if (k == NULL || l == NULL) goto err; if (ctx_in == NULL) { /* if you don't pass in ctx_in you get a default libctx */ if ((ctx = BN_CTX_new_ex(NULL)) == NULL) goto err; } else ctx = ctx_in; /* Preallocate space */ q_bits = BN_num_bits(dsa->params.q); q_words = bn_get_top(dsa->params.q); if (q_bits < MIN_DSA_SIGN_QBITS || !bn_wexpand(k, q_words + 2) || !bn_wexpand(l, q_words + 2)) goto err; /* Get random k */ do { if (dgst != NULL) { if (nonce_type == 1) { #ifndef FIPS_MODULE if (!ossl_gen_deterministic_nonce_rfc6979(k, dsa->params.q, dsa->priv_key, dgst, dlen, digestname, libctx, propq)) #endif goto err; } else { /* * We calculate k from SHA512(private_key + H(message) + random). * This protects the private key from a weak PRNG. */ if (!BN_generate_dsa_nonce(k, dsa->params.q, dsa->priv_key, dgst, dlen, ctx)) goto err; } } else if (!BN_priv_rand_range_ex(k, dsa->params.q, 0, ctx)) goto err; } while (BN_is_zero(k)); BN_set_flags(k, BN_FLG_CONSTTIME); BN_set_flags(l, BN_FLG_CONSTTIME); if (dsa->flags & DSA_FLAG_CACHE_MONT_P) { if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p, dsa->lock, dsa->params.p, ctx)) goto err; } /* Compute r = (g^k mod p) mod q */ /* * We do not want timing information to leak the length of k, so we * compute G^k using an equivalent scalar of fixed bit-length. * * We unconditionally perform both of these additions to prevent a * small timing information leakage. We then choose the sum that is * one bit longer than the modulus. * * There are some concerns about the efficacy of doing this. More * specifically refer to the discussion starting with: * https://github.com/openssl/openssl/pull/7486#discussion_r228323705 * The fix is to rework BN so these gymnastics aren't required. */ if (!BN_add(l, k, dsa->params.q) || !BN_add(k, l, dsa->params.q)) goto err; BN_consttime_swap(BN_is_bit_set(l, q_bits), k, l, q_words + 2); if ((dsa)->meth->bn_mod_exp != NULL) { if (!dsa->meth->bn_mod_exp(dsa, r, dsa->params.g, k, dsa->params.p, ctx, dsa->method_mont_p)) goto err; } else { if (!BN_mod_exp_mont(r, dsa->params.g, k, dsa->params.p, ctx, dsa->method_mont_p)) goto err; } if (!BN_mod(r, r, dsa->params.q, ctx)) goto err; /* Compute part of 's = inv(k) (m + xr) mod q' */ if ((kinv = dsa_mod_inverse_fermat(k, dsa->params.q, ctx)) == NULL) goto err; BN_clear_free(*kinvp); *kinvp = kinv; kinv = NULL; ret = 1; err: if (!ret) ERR_raise(ERR_LIB_DSA, ERR_R_BN_LIB); if (ctx != ctx_in) BN_CTX_free(ctx); BN_clear_free(k); BN_clear_free(l); return ret; } static int dsa_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa) { BN_CTX *ctx; BIGNUM *u1, *u2, *t1; BN_MONT_CTX *mont = NULL; const BIGNUM *r, *s; int ret = -1, i; if (dsa->params.p == NULL || dsa->params.q == NULL || dsa->params.g == NULL) { ERR_raise(ERR_LIB_DSA, DSA_R_MISSING_PARAMETERS); return -1; } i = BN_num_bits(dsa->params.q); /* fips 186-3 allows only different sizes for q */ if (i != 160 && i != 224 && i != 256) { ERR_raise(ERR_LIB_DSA, DSA_R_BAD_Q_VALUE); return -1; } if (BN_num_bits(dsa->params.p) > OPENSSL_DSA_MAX_MODULUS_BITS) { ERR_raise(ERR_LIB_DSA, DSA_R_MODULUS_TOO_LARGE); return -1; } u1 = BN_new(); u2 = BN_new(); t1 = BN_new(); ctx = BN_CTX_new_ex(NULL); /* verify does not need a libctx */ if (u1 == NULL || u2 == NULL || t1 == NULL || ctx == NULL) goto err; DSA_SIG_get0(sig, &r, &s); if (BN_is_zero(r) || BN_is_negative(r) || BN_ucmp(r, dsa->params.q) >= 0) { ret = 0; goto err; } if (BN_is_zero(s) || BN_is_negative(s) || BN_ucmp(s, dsa->params.q) >= 0) { ret = 0; goto err; } /* * Calculate W = inv(S) mod Q save W in u2 */ if ((BN_mod_inverse(u2, s, dsa->params.q, ctx)) == NULL) goto err; /* save M in u1 */ if (dgst_len > (i >> 3)) /* * if the digest length is greater than the size of q use the * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3, * 4.2 */ dgst_len = (i >> 3); if (BN_bin2bn(dgst, dgst_len, u1) == NULL) goto err; /* u1 = M * w mod q */ if (!BN_mod_mul(u1, u1, u2, dsa->params.q, ctx)) goto err; /* u2 = r * w mod q */ if (!BN_mod_mul(u2, r, u2, dsa->params.q, ctx)) goto err; if (dsa->flags & DSA_FLAG_CACHE_MONT_P) { mont = BN_MONT_CTX_set_locked(&dsa->method_mont_p, dsa->lock, dsa->params.p, ctx); if (!mont) goto err; } if (dsa->meth->dsa_mod_exp != NULL) { if (!dsa->meth->dsa_mod_exp(dsa, t1, dsa->params.g, u1, dsa->pub_key, u2, dsa->params.p, ctx, mont)) goto err; } else { if (!BN_mod_exp2_mont(t1, dsa->params.g, u1, dsa->pub_key, u2, dsa->params.p, ctx, mont)) goto err; } /* let u1 = u1 mod q */ if (!BN_mod(u1, t1, dsa->params.q, ctx)) goto err; /* * V is now in u1. If the signature is correct, it will be equal to R. */ ret = (BN_ucmp(u1, r) == 0); err: if (ret < 0) ERR_raise(ERR_LIB_DSA, ERR_R_BN_LIB); BN_CTX_free(ctx); BN_free(u1); BN_free(u2); BN_free(t1); return ret; } static int dsa_init(DSA *dsa) { dsa->flags |= DSA_FLAG_CACHE_MONT_P; dsa->dirty_cnt++; return 1; } static int dsa_finish(DSA *dsa) { BN_MONT_CTX_free(dsa->method_mont_p); return 1; } /* * Compute the inverse of k modulo q. * Since q is prime, Fermat's Little Theorem applies, which reduces this to * mod-exp operation. Both the exponent and modulus are public information * so a mod-exp that doesn't leak the base is sufficient. A newly allocated * BIGNUM is returned which the caller must free. */ static BIGNUM *dsa_mod_inverse_fermat(const BIGNUM *k, const BIGNUM *q, BN_CTX *ctx) { BIGNUM *res = NULL; BIGNUM *r, *e; if ((r = BN_new()) == NULL) return NULL; BN_CTX_start(ctx); if ((e = BN_CTX_get(ctx)) != NULL && BN_set_word(r, 2) && BN_sub(e, q, r) && BN_mod_exp_mont(r, k, e, q, ctx, NULL)) res = r; else BN_free(r); BN_CTX_end(ctx); return res; }
./openssl/crypto/dsa/dsa_asn1.c
/* * Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include "dsa_local.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/rand.h> #include "crypto/asn1_dsa.h" /* Override the default free and new methods */ static int dsa_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_NEW_PRE) { *pval = (ASN1_VALUE *)DSA_new(); if (*pval != NULL) return 2; return 0; } else if (operation == ASN1_OP_FREE_PRE) { DSA_free((DSA *)*pval); *pval = NULL; return 2; } return 1; } ASN1_SEQUENCE_cb(DSAPrivateKey, dsa_cb) = { ASN1_EMBED(DSA, version, INT32), ASN1_SIMPLE(DSA, params.p, BIGNUM), ASN1_SIMPLE(DSA, params.q, BIGNUM), ASN1_SIMPLE(DSA, params.g, BIGNUM), ASN1_SIMPLE(DSA, pub_key, BIGNUM), ASN1_SIMPLE(DSA, priv_key, CBIGNUM) } static_ASN1_SEQUENCE_END_cb(DSA, DSAPrivateKey) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(DSA, DSAPrivateKey, DSAPrivateKey) ASN1_SEQUENCE_cb(DSAparams, dsa_cb) = { ASN1_SIMPLE(DSA, params.p, BIGNUM), ASN1_SIMPLE(DSA, params.q, BIGNUM), ASN1_SIMPLE(DSA, params.g, BIGNUM), } static_ASN1_SEQUENCE_END_cb(DSA, DSAparams) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(DSA, DSAparams, DSAparams) ASN1_SEQUENCE_cb(DSAPublicKey, dsa_cb) = { ASN1_SIMPLE(DSA, pub_key, BIGNUM), ASN1_SIMPLE(DSA, params.p, BIGNUM), ASN1_SIMPLE(DSA, params.q, BIGNUM), ASN1_SIMPLE(DSA, params.g, BIGNUM) } static_ASN1_SEQUENCE_END_cb(DSA, DSAPublicKey) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(DSA, DSAPublicKey, DSAPublicKey) DSA *DSAparams_dup(const DSA *dsa) { return ASN1_item_dup(ASN1_ITEM_rptr(DSAparams), dsa); }
./openssl/crypto/crmf/crmf_local.h
/*- * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * CRMF implementation by Martin Peylo, Miikka Viljanen, and David von Oheimb. */ #ifndef OSSL_CRYPTO_CRMF_LOCAL_H # define OSSL_CRYPTO_CRMF_LOCAL_H # include <openssl/crmf.h> # include <openssl/err.h> /* explicit #includes not strictly needed since implied by the above: */ # include <openssl/types.h> # include <openssl/safestack.h> # include <openssl/x509.h> # include <openssl/x509v3.h> /*- * EncryptedValue ::= SEQUENCE { * intendedAlg [0] AlgorithmIdentifier OPTIONAL, * -- the intended algorithm for which the value will be used * symmAlg [1] AlgorithmIdentifier OPTIONAL, * -- the symmetric algorithm used to encrypt the value * encSymmKey [2] BIT STRING OPTIONAL, * -- the (encrypted) symmetric key used to encrypt the value * keyAlg [3] AlgorithmIdentifier OPTIONAL, * -- algorithm used to encrypt the symmetric key * valueHint [4] OCTET STRING OPTIONAL, * -- a brief description or identifier of the encValue content * -- (may be meaningful only to the sending entity, and * -- used only if EncryptedValue might be re-examined * -- by the sending entity in the future) * encValue BIT STRING * -- the encrypted value itself * } */ struct ossl_crmf_encryptedvalue_st { X509_ALGOR *intendedAlg; /* 0 */ X509_ALGOR *symmAlg; /* 1 */ ASN1_BIT_STRING *encSymmKey; /* 2 */ X509_ALGOR *keyAlg; /* 3 */ ASN1_OCTET_STRING *valueHint; /* 4 */ ASN1_BIT_STRING *encValue; } /* OSSL_CRMF_ENCRYPTEDVALUE */; /*- * Attributes ::= SET OF Attribute * => X509_ATTRIBUTE * * PrivateKeyInfo ::= SEQUENCE { * version INTEGER, * privateKeyAlgorithm AlgorithmIdentifier, * privateKey OCTET STRING, * attributes [0] IMPLICIT Attributes OPTIONAL * } */ typedef struct ossl_crmf_privatekeyinfo_st { ASN1_INTEGER *version; X509_ALGOR *privateKeyAlgorithm; ASN1_OCTET_STRING *privateKey; STACK_OF(X509_ATTRIBUTE) *attributes; /* [ 0 ] */ } OSSL_CRMF_PRIVATEKEYINFO; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_PRIVATEKEYINFO) /*- * section 4.2.1 Private Key Info Content Type * id-ct-encKeyWithID OBJECT IDENTIFIER ::= {id-ct 21} * * EncKeyWithID ::= SEQUENCE { * privateKey PrivateKeyInfo, * identifier CHOICE { * string UTF8String, * generalName GeneralName * } OPTIONAL * } */ typedef struct ossl_crmf_enckeywithid_identifier_st { int type; union { ASN1_UTF8STRING *string; GENERAL_NAME *generalName; } value; } OSSL_CRMF_ENCKEYWITHID_IDENTIFIER; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER) typedef struct ossl_crmf_enckeywithid_st { OSSL_CRMF_PRIVATEKEYINFO *privateKey; /* [0] */ OSSL_CRMF_ENCKEYWITHID_IDENTIFIER *identifier; } OSSL_CRMF_ENCKEYWITHID; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_ENCKEYWITHID) /*- * CertId ::= SEQUENCE { * issuer GeneralName, * serialNumber INTEGER * } */ struct ossl_crmf_certid_st { GENERAL_NAME *issuer; ASN1_INTEGER *serialNumber; } /* OSSL_CRMF_CERTID */; /*- * SinglePubInfo ::= SEQUENCE { * pubMethod INTEGER { * dontCare (0), * x500 (1), * web (2), * ldap (3) }, * pubLocation GeneralName OPTIONAL * } */ struct ossl_crmf_singlepubinfo_st { ASN1_INTEGER *pubMethod; GENERAL_NAME *pubLocation; } /* OSSL_CRMF_SINGLEPUBINFO */; DEFINE_STACK_OF(OSSL_CRMF_SINGLEPUBINFO) typedef STACK_OF(OSSL_CRMF_SINGLEPUBINFO) OSSL_CRMF_PUBINFOS; /*- * PKIPublicationInfo ::= SEQUENCE { * action INTEGER { * dontPublish (0), * pleasePublish (1) }, * pubInfos SEQUENCE SIZE (1..MAX) OF SinglePubInfo OPTIONAL * -- pubInfos MUST NOT be present if action is "dontPublish" * -- (if action is "pleasePublish" and pubInfos is omitted, * -- "dontCare" is assumed) * } */ struct ossl_crmf_pkipublicationinfo_st { ASN1_INTEGER *action; OSSL_CRMF_PUBINFOS *pubInfos; } /* OSSL_CRMF_PKIPUBLICATIONINFO */; DECLARE_ASN1_DUP_FUNCTION(OSSL_CRMF_PKIPUBLICATIONINFO) /*- * PKMACValue ::= SEQUENCE { * algId AlgorithmIdentifier, * -- algorithm value shall be PasswordBasedMac {1 2 840 113533 7 66 13} * -- parameter value is PBMParameter * value BIT STRING * } */ typedef struct ossl_crmf_pkmacvalue_st { X509_ALGOR *algId; ASN1_BIT_STRING *value; } OSSL_CRMF_PKMACVALUE; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_PKMACVALUE) /*- * SubsequentMessage ::= INTEGER { * encrCert (0), * -- requests that resulting certificate be encrypted for the * -- end entity (following which, POP will be proven in a * -- confirmation message) * challengeResp (1) * -- requests that CA engage in challenge-response exchange with * -- end entity in order to prove private key possession * } * * POPOPrivKey ::= CHOICE { * thisMessage [0] BIT STRING, -- Deprecated * -- possession is proven in this message (which contains the private * -- key itself (encrypted for the CA)) * subsequentMessage [1] SubsequentMessage, * -- possession will be proven in a subsequent message * dhMAC [2] BIT STRING, -- Deprecated * agreeMAC [3] PKMACValue, * encryptedKey [4] EnvelopedData * } */ typedef struct ossl_crmf_popoprivkey_st { int type; union { ASN1_BIT_STRING *thisMessage; /* 0 */ /* Deprecated */ ASN1_INTEGER *subsequentMessage; /* 1 */ ASN1_BIT_STRING *dhMAC; /* 2 */ /* Deprecated */ OSSL_CRMF_PKMACVALUE *agreeMAC; /* 3 */ ASN1_NULL *encryptedKey; /* 4 */ /* When supported, ASN1_NULL needs to be replaced by CMS_ENVELOPEDDATA */ } value; } OSSL_CRMF_POPOPRIVKEY; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_POPOPRIVKEY) /*- * PBMParameter ::= SEQUENCE { * salt OCTET STRING, * owf AlgorithmIdentifier, * -- AlgId for a One-Way Function (SHA-1 recommended) * iterationCount INTEGER, * -- number of times the OWF is applied * mac AlgorithmIdentifier * -- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11], * -- or HMAC [HMAC, RFC2202]) * } */ struct ossl_crmf_pbmparameter_st { ASN1_OCTET_STRING *salt; X509_ALGOR *owf; ASN1_INTEGER *iterationCount; X509_ALGOR *mac; } /* OSSL_CRMF_PBMPARAMETER */; # define OSSL_CRMF_PBM_MAX_ITERATION_COUNT 100000 /* if too large allows DoS */ /*- * POPOSigningKeyInput ::= SEQUENCE { * authInfo CHOICE { * sender [0] GeneralName, * -- used only if an authenticated identity has been * -- established for the sender (e.g., a DN from a * -- previously-issued and currently-valid certificate) * publicKeyMAC PKMACValue }, * -- used if no authenticated GeneralName currently exists for * -- the sender; publicKeyMAC contains a password-based MAC * -- on the DER-encoded value of publicKey * publicKey SubjectPublicKeyInfo -- from CertTemplate * } */ typedef struct ossl_crmf_poposigningkeyinput_authinfo_st { int type; union { /* 0 */ GENERAL_NAME *sender; /* 1 */ OSSL_CRMF_PKMACVALUE *publicKeyMAC; } value; } OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO) typedef struct ossl_crmf_poposigningkeyinput_st { OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO *authInfo; X509_PUBKEY *publicKey; } OSSL_CRMF_POPOSIGNINGKEYINPUT; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEYINPUT) /*- * POPOSigningKey ::= SEQUENCE { * poposkInput [0] POPOSigningKeyInput OPTIONAL, * algorithmIdentifier AlgorithmIdentifier, * signature BIT STRING * } */ struct ossl_crmf_poposigningkey_st { OSSL_CRMF_POPOSIGNINGKEYINPUT *poposkInput; X509_ALGOR *algorithmIdentifier; ASN1_BIT_STRING *signature; } /* OSSL_CRMF_POPOSIGNINGKEY */; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEY) /*- * ProofOfPossession ::= CHOICE { * raVerified [0] NULL, * -- used if the RA has already verified that the requester is in * -- possession of the private key * signature [1] POPOSigningKey, * keyEncipherment [2] POPOPrivKey, * keyAgreement [3] POPOPrivKey * } */ typedef struct ossl_crmf_popo_st { int type; union { ASN1_NULL *raVerified; /* 0 */ OSSL_CRMF_POPOSIGNINGKEY *signature; /* 1 */ OSSL_CRMF_POPOPRIVKEY *keyEncipherment; /* 2 */ OSSL_CRMF_POPOPRIVKEY *keyAgreement; /* 3 */ } value; } OSSL_CRMF_POPO; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_POPO) /*- * OptionalValidity ::= SEQUENCE { * notBefore [0] Time OPTIONAL, * notAfter [1] Time OPTIONAL -- at least one MUST be present * } */ struct ossl_crmf_optionalvalidity_st { /* 0 */ ASN1_TIME *notBefore; /* 1 */ ASN1_TIME *notAfter; } /* OSSL_CRMF_OPTIONALVALIDITY */; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_OPTIONALVALIDITY) /*- * CertTemplate ::= SEQUENCE { * version [0] Version OPTIONAL, * serialNumber [1] INTEGER OPTIONAL, * signingAlg [2] AlgorithmIdentifier OPTIONAL, * issuer [3] Name OPTIONAL, * validity [4] OptionalValidity OPTIONAL, * subject [5] Name OPTIONAL, * publicKey [6] SubjectPublicKeyInfo OPTIONAL, * issuerUID [7] UniqueIdentifier OPTIONAL, * subjectUID [8] UniqueIdentifier OPTIONAL, * extensions [9] Extensions OPTIONAL * } */ struct ossl_crmf_certtemplate_st { ASN1_INTEGER *version; ASN1_INTEGER *serialNumber; /* serialNumber MUST be omitted */ /* This field is assigned by the CA during certificate creation */ X509_ALGOR *signingAlg; /* signingAlg MUST be omitted */ /* This field is assigned by the CA during certificate creation */ const X509_NAME *issuer; OSSL_CRMF_OPTIONALVALIDITY *validity; const X509_NAME *subject; X509_PUBKEY *publicKey; ASN1_BIT_STRING *issuerUID; /* deprecated in version 2 */ /* According to rfc 3280: UniqueIdentifier ::= BIT STRING */ ASN1_BIT_STRING *subjectUID; /* deprecated in version 2 */ /* Could be X509_EXTENSION*S*, but that's only cosmetic */ STACK_OF(X509_EXTENSION) *extensions; } /* OSSL_CRMF_CERTTEMPLATE */; /*- * CertRequest ::= SEQUENCE { * certReqId INTEGER, -- ID for matching request and reply * certTemplate CertTemplate, -- Selected fields of cert to be issued * controls Controls OPTIONAL -- Attributes affecting issuance * } */ struct ossl_crmf_certrequest_st { ASN1_INTEGER *certReqId; OSSL_CRMF_CERTTEMPLATE *certTemplate; STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE /* Controls expanded */) *controls; } /* OSSL_CRMF_CERTREQUEST */; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_CERTREQUEST) DECLARE_ASN1_DUP_FUNCTION(OSSL_CRMF_CERTREQUEST) struct ossl_crmf_attributetypeandvalue_st { ASN1_OBJECT *type; union { /* NID_id_regCtrl_regToken */ ASN1_UTF8STRING *regToken; /* NID_id_regCtrl_authenticator */ ASN1_UTF8STRING *authenticator; /* NID_id_regCtrl_pkiPublicationInfo */ OSSL_CRMF_PKIPUBLICATIONINFO *pkiPublicationInfo; /* NID_id_regCtrl_oldCertID */ OSSL_CRMF_CERTID *oldCertID; /* NID_id_regCtrl_protocolEncrKey */ X509_PUBKEY *protocolEncrKey; /* NID_id_regInfo_utf8Pairs */ ASN1_UTF8STRING *utf8Pairs; /* NID_id_regInfo_certReq */ OSSL_CRMF_CERTREQUEST *certReq; ASN1_TYPE *other; } value; } /* OSSL_CRMF_ATTRIBUTETYPEANDVALUE */; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) DEFINE_STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) DECLARE_ASN1_DUP_FUNCTION(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) /*- * CertReqMessages ::= SEQUENCE SIZE (1..MAX) OF CertReqMsg * CertReqMsg ::= SEQUENCE { * certReq CertRequest, * popo ProofOfPossession OPTIONAL, * -- content depends upon key type * regInfo SEQUENCE SIZE(1..MAX) OF AttributeTypeAndValue OPTIONAL * } */ struct ossl_crmf_msg_st { OSSL_CRMF_CERTREQUEST *certReq; /* 0 */ OSSL_CRMF_POPO *popo; /* 1 */ STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) *regInfo; } /* OSSL_CRMF_MSG */; #endif
./openssl/crypto/crmf/crmf_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/crmferr.h> #include "crypto/crmferr.h" #ifndef OPENSSL_NO_CRMF # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA CRMF_str_reasons[] = { {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_BAD_PBM_ITERATIONCOUNT), "bad pbm iterationcount"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_CRMFERROR), "crmferror"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_ERROR), "error"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_ERROR_DECODING_CERTIFICATE), "error decoding certificate"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_ERROR_DECRYPTING_CERTIFICATE), "error decrypting certificate"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_ERROR_DECRYPTING_SYMMETRIC_KEY), "error decrypting symmetric key"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_FAILURE_OBTAINING_RANDOM), "failure obtaining random"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_ITERATIONCOUNT_BELOW_100), "iterationcount below 100"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_MALFORMED_IV), "malformed iv"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_NULL_ARGUMENT), "null argument"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPOSKINPUT_NOT_SUPPORTED), "poposkinput not supported"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPO_INCONSISTENT_PUBLIC_KEY), "popo inconsistent public key"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPO_MISSING), "popo missing"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPO_MISSING_PUBLIC_KEY), "popo missing public key"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPO_MISSING_SUBJECT), "popo missing subject"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPO_RAVERIFIED_NOT_ACCEPTED), "popo raverified not accepted"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_SETTING_MAC_ALGOR_FAILURE), "setting mac algor failure"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_SETTING_OWF_ALGOR_FAILURE), "setting owf algor failure"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_UNSUPPORTED_ALGORITHM), "unsupported algorithm"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_UNSUPPORTED_CIPHER), "unsupported cipher"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_UNSUPPORTED_METHOD_FOR_CREATING_POPO), "unsupported method for creating popo"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_UNSUPPORTED_POPO_METHOD), "unsupported popo method"}, {0, NULL} }; # endif int ossl_err_load_CRMF_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(CRMF_str_reasons[0].error) == NULL) ERR_load_strings_const(CRMF_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
./openssl/crypto/crmf/crmf_asn.c
/*- * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * CRMF implementation by Martin Peylo, Miikka Viljanen, and David von Oheimb. */ #include <openssl/asn1t.h> #include "crmf_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/crmf.h> ASN1_SEQUENCE(OSSL_CRMF_PRIVATEKEYINFO) = { ASN1_SIMPLE(OSSL_CRMF_PRIVATEKEYINFO, version, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CRMF_PRIVATEKEYINFO, privateKeyAlgorithm, X509_ALGOR), ASN1_SIMPLE(OSSL_CRMF_PRIVATEKEYINFO, privateKey, ASN1_OCTET_STRING), ASN1_IMP_SET_OF_OPT(OSSL_CRMF_PRIVATEKEYINFO, attributes, X509_ATTRIBUTE, 0) } ASN1_SEQUENCE_END(OSSL_CRMF_PRIVATEKEYINFO) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_PRIVATEKEYINFO) ASN1_CHOICE(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER) = { ASN1_SIMPLE(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER, value.string, ASN1_UTF8STRING), ASN1_SIMPLE(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER, value.generalName, GENERAL_NAME) } ASN1_CHOICE_END(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER) ASN1_SEQUENCE(OSSL_CRMF_ENCKEYWITHID) = { ASN1_SIMPLE(OSSL_CRMF_ENCKEYWITHID, privateKey, OSSL_CRMF_PRIVATEKEYINFO), ASN1_OPT(OSSL_CRMF_ENCKEYWITHID, identifier, OSSL_CRMF_ENCKEYWITHID_IDENTIFIER) } ASN1_SEQUENCE_END(OSSL_CRMF_ENCKEYWITHID) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_ENCKEYWITHID) ASN1_SEQUENCE(OSSL_CRMF_CERTID) = { ASN1_SIMPLE(OSSL_CRMF_CERTID, issuer, GENERAL_NAME), ASN1_SIMPLE(OSSL_CRMF_CERTID, serialNumber, ASN1_INTEGER) } ASN1_SEQUENCE_END(OSSL_CRMF_CERTID) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_CERTID) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CRMF_CERTID) ASN1_SEQUENCE(OSSL_CRMF_ENCRYPTEDVALUE) = { ASN1_IMP_OPT(OSSL_CRMF_ENCRYPTEDVALUE, intendedAlg, X509_ALGOR, 0), ASN1_IMP_OPT(OSSL_CRMF_ENCRYPTEDVALUE, symmAlg, X509_ALGOR, 1), ASN1_IMP_OPT(OSSL_CRMF_ENCRYPTEDVALUE, encSymmKey, ASN1_BIT_STRING, 2), ASN1_IMP_OPT(OSSL_CRMF_ENCRYPTEDVALUE, keyAlg, X509_ALGOR, 3), ASN1_IMP_OPT(OSSL_CRMF_ENCRYPTEDVALUE, valueHint, ASN1_OCTET_STRING, 4), ASN1_SIMPLE(OSSL_CRMF_ENCRYPTEDVALUE, encValue, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(OSSL_CRMF_ENCRYPTEDVALUE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_ENCRYPTEDVALUE) ASN1_SEQUENCE(OSSL_CRMF_SINGLEPUBINFO) = { ASN1_SIMPLE(OSSL_CRMF_SINGLEPUBINFO, pubMethod, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CRMF_SINGLEPUBINFO, pubLocation, GENERAL_NAME) } ASN1_SEQUENCE_END(OSSL_CRMF_SINGLEPUBINFO) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_SINGLEPUBINFO) ASN1_SEQUENCE(OSSL_CRMF_PKIPUBLICATIONINFO) = { ASN1_SIMPLE(OSSL_CRMF_PKIPUBLICATIONINFO, action, ASN1_INTEGER), ASN1_SEQUENCE_OF_OPT(OSSL_CRMF_PKIPUBLICATIONINFO, pubInfos, OSSL_CRMF_SINGLEPUBINFO) } ASN1_SEQUENCE_END(OSSL_CRMF_PKIPUBLICATIONINFO) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_PKIPUBLICATIONINFO) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CRMF_PKIPUBLICATIONINFO) ASN1_SEQUENCE(OSSL_CRMF_PKMACVALUE) = { ASN1_SIMPLE(OSSL_CRMF_PKMACVALUE, algId, X509_ALGOR), ASN1_SIMPLE(OSSL_CRMF_PKMACVALUE, value, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(OSSL_CRMF_PKMACVALUE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_PKMACVALUE) ASN1_CHOICE(OSSL_CRMF_POPOPRIVKEY) = { ASN1_IMP(OSSL_CRMF_POPOPRIVKEY, value.thisMessage, ASN1_BIT_STRING, 0), ASN1_IMP(OSSL_CRMF_POPOPRIVKEY, value.subsequentMessage, ASN1_INTEGER, 1), ASN1_IMP(OSSL_CRMF_POPOPRIVKEY, value.dhMAC, ASN1_BIT_STRING, 2), ASN1_IMP(OSSL_CRMF_POPOPRIVKEY, value.agreeMAC, OSSL_CRMF_PKMACVALUE, 3), ASN1_IMP(OSSL_CRMF_POPOPRIVKEY, value.encryptedKey, ASN1_NULL, 4), /* When supported, ASN1_NULL needs to be replaced by CMS_ENVELOPEDDATA */ } ASN1_CHOICE_END(OSSL_CRMF_POPOPRIVKEY) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPOPRIVKEY) ASN1_SEQUENCE(OSSL_CRMF_PBMPARAMETER) = { ASN1_SIMPLE(OSSL_CRMF_PBMPARAMETER, salt, ASN1_OCTET_STRING), ASN1_SIMPLE(OSSL_CRMF_PBMPARAMETER, owf, X509_ALGOR), ASN1_SIMPLE(OSSL_CRMF_PBMPARAMETER, iterationCount, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CRMF_PBMPARAMETER, mac, X509_ALGOR) } ASN1_SEQUENCE_END(OSSL_CRMF_PBMPARAMETER) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_PBMPARAMETER) ASN1_CHOICE(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO) = { ASN1_EXP(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO, value.sender, GENERAL_NAME, 0), ASN1_SIMPLE(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO, value.publicKeyMAC, OSSL_CRMF_PKMACVALUE) } ASN1_CHOICE_END(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO) ASN1_SEQUENCE(OSSL_CRMF_POPOSIGNINGKEYINPUT) = { ASN1_SIMPLE(OSSL_CRMF_POPOSIGNINGKEYINPUT, authInfo, OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO), ASN1_SIMPLE(OSSL_CRMF_POPOSIGNINGKEYINPUT, publicKey, X509_PUBKEY) } ASN1_SEQUENCE_END(OSSL_CRMF_POPOSIGNINGKEYINPUT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEYINPUT) ASN1_SEQUENCE(OSSL_CRMF_POPOSIGNINGKEY) = { ASN1_IMP_OPT(OSSL_CRMF_POPOSIGNINGKEY, poposkInput, OSSL_CRMF_POPOSIGNINGKEYINPUT, 0), ASN1_SIMPLE(OSSL_CRMF_POPOSIGNINGKEY, algorithmIdentifier, X509_ALGOR), ASN1_SIMPLE(OSSL_CRMF_POPOSIGNINGKEY, signature, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(OSSL_CRMF_POPOSIGNINGKEY) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEY) ASN1_CHOICE(OSSL_CRMF_POPO) = { ASN1_IMP(OSSL_CRMF_POPO, value.raVerified, ASN1_NULL, 0), ASN1_IMP(OSSL_CRMF_POPO, value.signature, OSSL_CRMF_POPOSIGNINGKEY, 1), ASN1_EXP(OSSL_CRMF_POPO, value.keyEncipherment, OSSL_CRMF_POPOPRIVKEY, 2), ASN1_EXP(OSSL_CRMF_POPO, value.keyAgreement, OSSL_CRMF_POPOPRIVKEY, 3) } ASN1_CHOICE_END(OSSL_CRMF_POPO) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPO) ASN1_ADB_TEMPLATE(attributetypeandvalue_default) = ASN1_OPT(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.other, ASN1_ANY); ASN1_ADB(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) = { ADB_ENTRY(NID_id_regCtrl_regToken, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.regToken, ASN1_UTF8STRING)), ADB_ENTRY(NID_id_regCtrl_authenticator, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.authenticator, ASN1_UTF8STRING)), ADB_ENTRY(NID_id_regCtrl_pkiPublicationInfo, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.pkiPublicationInfo, OSSL_CRMF_PKIPUBLICATIONINFO)), ADB_ENTRY(NID_id_regCtrl_oldCertID, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.oldCertID, OSSL_CRMF_CERTID)), ADB_ENTRY(NID_id_regCtrl_protocolEncrKey, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.protocolEncrKey, X509_PUBKEY)), ADB_ENTRY(NID_id_regInfo_utf8Pairs, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.utf8Pairs, ASN1_UTF8STRING)), ADB_ENTRY(NID_id_regInfo_certReq, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.certReq, OSSL_CRMF_CERTREQUEST)), } ASN1_ADB_END(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, 0, type, 0, &attributetypeandvalue_default_tt, NULL); ASN1_SEQUENCE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) = { ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, type, ASN1_OBJECT), ASN1_ADB_OBJECT(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) } ASN1_SEQUENCE_END(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) ASN1_SEQUENCE(OSSL_CRMF_OPTIONALVALIDITY) = { ASN1_EXP_OPT(OSSL_CRMF_OPTIONALVALIDITY, notBefore, ASN1_TIME, 0), ASN1_EXP_OPT(OSSL_CRMF_OPTIONALVALIDITY, notAfter, ASN1_TIME, 1) } ASN1_SEQUENCE_END(OSSL_CRMF_OPTIONALVALIDITY) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_OPTIONALVALIDITY) ASN1_SEQUENCE(OSSL_CRMF_CERTTEMPLATE) = { ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, version, ASN1_INTEGER, 0), /* * serialNumber MUST be omitted. This field is assigned by the CA * during certificate creation. */ ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, serialNumber, ASN1_INTEGER, 1), /* * signingAlg MUST be omitted. This field is assigned by the CA * during certificate creation. */ ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, signingAlg, X509_ALGOR, 2), ASN1_EXP_OPT(OSSL_CRMF_CERTTEMPLATE, issuer, X509_NAME, 3), ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, validity, OSSL_CRMF_OPTIONALVALIDITY, 4), ASN1_EXP_OPT(OSSL_CRMF_CERTTEMPLATE, subject, X509_NAME, 5), ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, publicKey, X509_PUBKEY, 6), /* issuerUID is deprecated in version 2 */ ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, issuerUID, ASN1_BIT_STRING, 7), /* subjectUID is deprecated in version 2 */ ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, subjectUID, ASN1_BIT_STRING, 8), ASN1_IMP_SEQUENCE_OF_OPT(OSSL_CRMF_CERTTEMPLATE, extensions, X509_EXTENSION, 9), } ASN1_SEQUENCE_END(OSSL_CRMF_CERTTEMPLATE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_CERTTEMPLATE) ASN1_SEQUENCE(OSSL_CRMF_CERTREQUEST) = { ASN1_SIMPLE(OSSL_CRMF_CERTREQUEST, certReqId, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CRMF_CERTREQUEST, certTemplate, OSSL_CRMF_CERTTEMPLATE), ASN1_SEQUENCE_OF_OPT(OSSL_CRMF_CERTREQUEST, controls, OSSL_CRMF_ATTRIBUTETYPEANDVALUE) } ASN1_SEQUENCE_END(OSSL_CRMF_CERTREQUEST) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_CERTREQUEST) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CRMF_CERTREQUEST) ASN1_SEQUENCE(OSSL_CRMF_MSG) = { ASN1_SIMPLE(OSSL_CRMF_MSG, certReq, OSSL_CRMF_CERTREQUEST), ASN1_OPT(OSSL_CRMF_MSG, popo, OSSL_CRMF_POPO), ASN1_SEQUENCE_OF_OPT(OSSL_CRMF_MSG, regInfo, OSSL_CRMF_ATTRIBUTETYPEANDVALUE) } ASN1_SEQUENCE_END(OSSL_CRMF_MSG) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_MSG) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CRMF_MSG) ASN1_ITEM_TEMPLATE(OSSL_CRMF_MSGS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CRMF_MSGS, OSSL_CRMF_MSG) ASN1_ITEM_TEMPLATE_END(OSSL_CRMF_MSGS) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_MSGS)
./openssl/crypto/crmf/crmf_lib.c
/*- * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2018 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * CRMF implementation by Martin Peylo, Miikka Viljanen, and David von Oheimb. */ /* * This file contains the functions that handle the individual items inside * the CRMF structures */ /* * NAMING * * The 0 functions use the supplied structure pointer directly in the parent and * it will be freed up when the parent is freed. * * The 1 functions use a copy of the supplied structure pointer (or in some * cases increases its link count) in the parent and so both should be freed up. */ #include <openssl/asn1t.h> #include "crmf_local.h" #include "internal/sizes.h" #include "crypto/evp.h" #include "crypto/x509.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/crmf.h> #include <openssl/err.h> #include <openssl/evp.h> /*- * atyp = Attribute Type * valt = Value Type * ctrlinf = "regCtrl" or "regInfo" */ #define IMPLEMENT_CRMF_CTRL_FUNC(atyp, valt, ctrlinf) \ valt *OSSL_CRMF_MSG_get0_##ctrlinf##_##atyp(const OSSL_CRMF_MSG *msg) \ { \ int i; \ STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) *controls; \ OSSL_CRMF_ATTRIBUTETYPEANDVALUE *atav = NULL; \ \ if (msg == NULL || msg->certReq == NULL) \ return NULL; \ controls = msg->certReq->controls; \ for (i = 0; i < sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_num(controls); i++) { \ atav = sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_value(controls, i); \ if (OBJ_obj2nid(atav->type) == NID_id_##ctrlinf##_##atyp) \ return atav->value.atyp; \ } \ return NULL; \ } \ \ int OSSL_CRMF_MSG_set1_##ctrlinf##_##atyp(OSSL_CRMF_MSG *msg, const valt *in) \ { \ OSSL_CRMF_ATTRIBUTETYPEANDVALUE *atav = NULL; \ \ if (msg == NULL || in == NULL) \ goto err; \ if ((atav = OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new()) == NULL) \ goto err; \ if ((atav->type = OBJ_nid2obj(NID_id_##ctrlinf##_##atyp)) == NULL) \ goto err; \ if ((atav->value.atyp = valt##_dup(in)) == NULL) \ goto err; \ if (!OSSL_CRMF_MSG_push0_##ctrlinf(msg, atav)) \ goto err; \ return 1; \ err: \ OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(atav); \ return 0; \ } /*- * Pushes the given control attribute into the controls stack of a CertRequest * (section 6) * returns 1 on success, 0 on error */ static int OSSL_CRMF_MSG_push0_regCtrl(OSSL_CRMF_MSG *crm, OSSL_CRMF_ATTRIBUTETYPEANDVALUE *ctrl) { int new = 0; if (crm == NULL || crm->certReq == NULL || ctrl == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (crm->certReq->controls == NULL) { crm->certReq->controls = sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new_null(); if (crm->certReq->controls == NULL) goto err; new = 1; } if (!sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_push(crm->certReq->controls, ctrl)) goto err; return 1; err: if (new != 0) { sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(crm->certReq->controls); crm->certReq->controls = NULL; } return 0; } /* id-regCtrl-regToken Control (section 6.1) */ IMPLEMENT_CRMF_CTRL_FUNC(regToken, ASN1_STRING, regCtrl) /* id-regCtrl-authenticator Control (section 6.2) */ #define ASN1_UTF8STRING_dup ASN1_STRING_dup IMPLEMENT_CRMF_CTRL_FUNC(authenticator, ASN1_UTF8STRING, regCtrl) int OSSL_CRMF_MSG_set0_SinglePubInfo(OSSL_CRMF_SINGLEPUBINFO *spi, int method, GENERAL_NAME *nm) { if (spi == NULL || method < OSSL_CRMF_PUB_METHOD_DONTCARE || method > OSSL_CRMF_PUB_METHOD_LDAP) { ERR_raise(ERR_LIB_CRMF, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (!ASN1_INTEGER_set(spi->pubMethod, method)) return 0; GENERAL_NAME_free(spi->pubLocation); spi->pubLocation = nm; return 1; } int OSSL_CRMF_MSG_PKIPublicationInfo_push0_SinglePubInfo(OSSL_CRMF_PKIPUBLICATIONINFO *pi, OSSL_CRMF_SINGLEPUBINFO *spi) { if (pi == NULL || spi == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (pi->pubInfos == NULL) pi->pubInfos = sk_OSSL_CRMF_SINGLEPUBINFO_new_null(); if (pi->pubInfos == NULL) return 0; return sk_OSSL_CRMF_SINGLEPUBINFO_push(pi->pubInfos, spi); } int OSSL_CRMF_MSG_set_PKIPublicationInfo_action(OSSL_CRMF_PKIPUBLICATIONINFO *pi, int action) { if (pi == NULL || action < OSSL_CRMF_PUB_ACTION_DONTPUBLISH || action > OSSL_CRMF_PUB_ACTION_PLEASEPUBLISH) { ERR_raise(ERR_LIB_CRMF, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } return ASN1_INTEGER_set(pi->action, action); } /* id-regCtrl-pkiPublicationInfo Control (section 6.3) */ IMPLEMENT_CRMF_CTRL_FUNC(pkiPublicationInfo, OSSL_CRMF_PKIPUBLICATIONINFO, regCtrl) /* id-regCtrl-oldCertID Control (section 6.5) from the given */ IMPLEMENT_CRMF_CTRL_FUNC(oldCertID, OSSL_CRMF_CERTID, regCtrl) OSSL_CRMF_CERTID *OSSL_CRMF_CERTID_gen(const X509_NAME *issuer, const ASN1_INTEGER *serial) { OSSL_CRMF_CERTID *cid = NULL; if (issuer == NULL || serial == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return NULL; } if ((cid = OSSL_CRMF_CERTID_new()) == NULL) goto err; if (!X509_NAME_set(&cid->issuer->d.directoryName, issuer)) goto err; cid->issuer->type = GEN_DIRNAME; ASN1_INTEGER_free(cid->serialNumber); if ((cid->serialNumber = ASN1_INTEGER_dup(serial)) == NULL) goto err; return cid; err: OSSL_CRMF_CERTID_free(cid); return NULL; } /* * id-regCtrl-protocolEncrKey Control (section 6.6) */ IMPLEMENT_CRMF_CTRL_FUNC(protocolEncrKey, X509_PUBKEY, regCtrl) /*- * Pushes the attribute given in regInfo in to the CertReqMsg->regInfo stack. * (section 7) * returns 1 on success, 0 on error */ static int OSSL_CRMF_MSG_push0_regInfo(OSSL_CRMF_MSG *crm, OSSL_CRMF_ATTRIBUTETYPEANDVALUE *ri) { STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) *info = NULL; if (crm == NULL || ri == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (crm->regInfo == NULL) crm->regInfo = info = sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new_null(); if (crm->regInfo == NULL) goto err; if (!sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_push(crm->regInfo, ri)) goto err; return 1; err: if (info != NULL) crm->regInfo = NULL; sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(info); return 0; } /* id-regInfo-utf8Pairs to regInfo (section 7.1) */ IMPLEMENT_CRMF_CTRL_FUNC(utf8Pairs, ASN1_UTF8STRING, regInfo) /* id-regInfo-certReq to regInfo (section 7.2) */ IMPLEMENT_CRMF_CTRL_FUNC(certReq, OSSL_CRMF_CERTREQUEST, regInfo) /* retrieves the certificate template of crm */ OSSL_CRMF_CERTTEMPLATE *OSSL_CRMF_MSG_get0_tmpl(const OSSL_CRMF_MSG *crm) { if (crm == NULL || crm->certReq == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return NULL; } return crm->certReq->certTemplate; } int OSSL_CRMF_MSG_set0_validity(OSSL_CRMF_MSG *crm, ASN1_TIME *notBefore, ASN1_TIME *notAfter) { OSSL_CRMF_OPTIONALVALIDITY *vld; OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm); if (tmpl == NULL) { /* also crm == NULL implies this */ ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if ((vld = OSSL_CRMF_OPTIONALVALIDITY_new()) == NULL) return 0; vld->notBefore = notBefore; vld->notAfter = notAfter; tmpl->validity = vld; return 1; } int OSSL_CRMF_MSG_set_certReqId(OSSL_CRMF_MSG *crm, int rid) { if (crm == NULL || crm->certReq == NULL || crm->certReq->certReqId == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } return ASN1_INTEGER_set(crm->certReq->certReqId, rid); } /* get ASN.1 encoded integer, return -1 on error */ static int crmf_asn1_get_int(const ASN1_INTEGER *a) { int64_t res; if (!ASN1_INTEGER_get_int64(&res, a)) { ERR_raise(ERR_LIB_CRMF, ASN1_R_INVALID_NUMBER); return -1; } if (res < INT_MIN) { ERR_raise(ERR_LIB_CRMF, ASN1_R_TOO_SMALL); return -1; } if (res > INT_MAX) { ERR_raise(ERR_LIB_CRMF, ASN1_R_TOO_LARGE); return -1; } return (int)res; } int OSSL_CRMF_MSG_get_certReqId(const OSSL_CRMF_MSG *crm) { if (crm == NULL || /* not really needed: */ crm->certReq == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return -1; } return crmf_asn1_get_int(crm->certReq->certReqId); } int OSSL_CRMF_MSG_set0_extensions(OSSL_CRMF_MSG *crm, X509_EXTENSIONS *exts) { OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm); if (tmpl == NULL) { /* also crm == NULL implies this */ ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (sk_X509_EXTENSION_num(exts) == 0) { sk_X509_EXTENSION_free(exts); exts = NULL; /* do not include empty extensions list */ } sk_X509_EXTENSION_pop_free(tmpl->extensions, X509_EXTENSION_free); tmpl->extensions = exts; return 1; } int OSSL_CRMF_MSG_push0_extension(OSSL_CRMF_MSG *crm, X509_EXTENSION *ext) { int new = 0; OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm); if (tmpl == NULL || ext == NULL) { /* also crm == NULL implies this */ ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (tmpl->extensions == NULL) { if ((tmpl->extensions = sk_X509_EXTENSION_new_null()) == NULL) goto err; new = 1; } if (!sk_X509_EXTENSION_push(tmpl->extensions, ext)) goto err; return 1; err: if (new != 0) { sk_X509_EXTENSION_free(tmpl->extensions); tmpl->extensions = NULL; } return 0; } static int create_popo_signature(OSSL_CRMF_POPOSIGNINGKEY *ps, const OSSL_CRMF_CERTREQUEST *cr, EVP_PKEY *pkey, const EVP_MD *digest, OSSL_LIB_CTX *libctx, const char *propq) { char name[80] = ""; EVP_PKEY *pub; if (ps == NULL || cr == NULL || pkey == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } pub = X509_PUBKEY_get0(cr->certTemplate->publicKey); if (!ossl_x509_check_private_key(pub, pkey)) return 0; if (ps->poposkInput != NULL) { /* We do not support cases 1+2 defined in RFC 4211, section 4.1 */ ERR_raise(ERR_LIB_CRMF, CRMF_R_POPOSKINPUT_NOT_SUPPORTED); return 0; } if (EVP_PKEY_get_default_digest_name(pkey, name, sizeof(name)) > 0 && strcmp(name, "UNDEF") == 0) /* at least for Ed25519, Ed448 */ digest = NULL; return ASN1_item_sign_ex(ASN1_ITEM_rptr(OSSL_CRMF_CERTREQUEST), ps->algorithmIdentifier, /* sets this X509_ALGOR */ NULL, ps->signature, /* sets the ASN1_BIT_STRING */ cr, NULL, pkey, digest, libctx, propq); } int OSSL_CRMF_MSG_create_popo(int meth, OSSL_CRMF_MSG *crm, EVP_PKEY *pkey, const EVP_MD *digest, OSSL_LIB_CTX *libctx, const char *propq) { OSSL_CRMF_POPO *pp = NULL; ASN1_INTEGER *tag = NULL; if (crm == NULL || (meth == OSSL_CRMF_POPO_SIGNATURE && pkey == NULL)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (meth == OSSL_CRMF_POPO_NONE) goto end; if ((pp = OSSL_CRMF_POPO_new()) == NULL) goto err; pp->type = meth; switch (meth) { case OSSL_CRMF_POPO_RAVERIFIED: if ((pp->value.raVerified = ASN1_NULL_new()) == NULL) goto err; break; case OSSL_CRMF_POPO_SIGNATURE: { OSSL_CRMF_POPOSIGNINGKEY *ps = OSSL_CRMF_POPOSIGNINGKEY_new(); if (ps == NULL) goto err; if (!create_popo_signature(ps, crm->certReq, pkey, digest, libctx, propq)) { OSSL_CRMF_POPOSIGNINGKEY_free(ps); goto err; } pp->value.signature = ps; } break; case OSSL_CRMF_POPO_KEYENC: if ((pp->value.keyEncipherment = OSSL_CRMF_POPOPRIVKEY_new()) == NULL) goto err; tag = ASN1_INTEGER_new(); pp->value.keyEncipherment->type = OSSL_CRMF_POPOPRIVKEY_SUBSEQUENTMESSAGE; pp->value.keyEncipherment->value.subsequentMessage = tag; if (tag == NULL || !ASN1_INTEGER_set(tag, OSSL_CRMF_SUBSEQUENTMESSAGE_ENCRCERT)) goto err; break; default: ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_METHOD_FOR_CREATING_POPO); goto err; } end: OSSL_CRMF_POPO_free(crm->popo); crm->popo = pp; return 1; err: OSSL_CRMF_POPO_free(pp); return 0; } /* verifies the Proof-of-Possession of the request with the given rid in reqs */ int OSSL_CRMF_MSGS_verify_popo(const OSSL_CRMF_MSGS *reqs, int rid, int acceptRAVerified, OSSL_LIB_CTX *libctx, const char *propq) { OSSL_CRMF_MSG *req = NULL; X509_PUBKEY *pubkey = NULL; OSSL_CRMF_POPOSIGNINGKEY *sig = NULL; const ASN1_ITEM *it; void *asn; if (reqs == NULL || (req = sk_OSSL_CRMF_MSG_value(reqs, rid)) == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (req->popo == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING); return 0; } switch (req->popo->type) { case OSSL_CRMF_POPO_RAVERIFIED: if (!acceptRAVerified) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_RAVERIFIED_NOT_ACCEPTED); return 0; } break; case OSSL_CRMF_POPO_SIGNATURE: pubkey = req->certReq->certTemplate->publicKey; if (pubkey == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING_PUBLIC_KEY); return 0; } sig = req->popo->value.signature; if (sig->poposkInput != NULL) { /* * According to RFC 4211: publicKey contains a copy of * the public key from the certificate template. This MUST be * exactly the same value as contained in the certificate template. */ if (sig->poposkInput->publicKey == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING_PUBLIC_KEY); return 0; } if (X509_PUBKEY_eq(pubkey, sig->poposkInput->publicKey) != 1) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_INCONSISTENT_PUBLIC_KEY); return 0; } /* * Should check at this point the contents of the authInfo sub-field * as requested in FR #19807 according to RFC 4211 section 4.1. */ it = ASN1_ITEM_rptr(OSSL_CRMF_POPOSIGNINGKEYINPUT); asn = sig->poposkInput; } else { if (req->certReq->certTemplate->subject == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING_SUBJECT); return 0; } it = ASN1_ITEM_rptr(OSSL_CRMF_CERTREQUEST); asn = req->certReq; } if (ASN1_item_verify_ex(it, sig->algorithmIdentifier, sig->signature, asn, NULL, X509_PUBKEY_get0(pubkey), libctx, propq) < 1) return 0; break; case OSSL_CRMF_POPO_KEYENC: /* * When OSSL_CMP_certrep_new() supports encrypted certs, * should return 1 if the type of req->popo->value.keyEncipherment * is OSSL_CRMF_POPOPRIVKEY_SUBSEQUENTMESSAGE and * its value.subsequentMessage == OSSL_CRMF_SUBSEQUENTMESSAGE_ENCRCERT */ case OSSL_CRMF_POPO_KEYAGREE: default: ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_POPO_METHOD); return 0; } return 1; } X509_PUBKEY *OSSL_CRMF_CERTTEMPLATE_get0_publicKey(const OSSL_CRMF_CERTTEMPLATE *tmpl) { return tmpl != NULL ? tmpl->publicKey : NULL; } const ASN1_INTEGER *OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(const OSSL_CRMF_CERTTEMPLATE *tmpl) { return tmpl != NULL ? tmpl->serialNumber : NULL; } const X509_NAME *OSSL_CRMF_CERTTEMPLATE_get0_subject(const OSSL_CRMF_CERTTEMPLATE *tmpl) { return tmpl != NULL ? tmpl->subject : NULL; } const X509_NAME *OSSL_CRMF_CERTTEMPLATE_get0_issuer(const OSSL_CRMF_CERTTEMPLATE *tmpl) { return tmpl != NULL ? tmpl->issuer : NULL; } X509_EXTENSIONS *OSSL_CRMF_CERTTEMPLATE_get0_extensions(const OSSL_CRMF_CERTTEMPLATE *tmpl) { return tmpl != NULL ? tmpl->extensions : NULL; } const X509_NAME *OSSL_CRMF_CERTID_get0_issuer(const OSSL_CRMF_CERTID *cid) { return cid != NULL && cid->issuer->type == GEN_DIRNAME ? cid->issuer->d.directoryName : NULL; } const ASN1_INTEGER *OSSL_CRMF_CERTID_get0_serialNumber(const OSSL_CRMF_CERTID *cid) { return cid != NULL ? cid->serialNumber : NULL; } /*- * Fill in the certificate template |tmpl|. * Any other NULL argument will leave the respective field unchanged. */ int OSSL_CRMF_CERTTEMPLATE_fill(OSSL_CRMF_CERTTEMPLATE *tmpl, EVP_PKEY *pubkey, const X509_NAME *subject, const X509_NAME *issuer, const ASN1_INTEGER *serial) { if (tmpl == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (subject != NULL && !X509_NAME_set((X509_NAME **)&tmpl->subject, subject)) return 0; if (issuer != NULL && !X509_NAME_set((X509_NAME **)&tmpl->issuer, issuer)) return 0; if (serial != NULL) { ASN1_INTEGER_free(tmpl->serialNumber); if ((tmpl->serialNumber = ASN1_INTEGER_dup(serial)) == NULL) return 0; } if (pubkey != NULL && !X509_PUBKEY_set(&tmpl->publicKey, pubkey)) return 0; return 1; } /*- * Decrypts the certificate in the given encryptedValue using private key pkey. * This is needed for the indirect PoP method as in RFC 4210 section 5.2.8.2. * * returns a pointer to the decrypted certificate * returns NULL on error or if no certificate available */ X509 *OSSL_CRMF_ENCRYPTEDVALUE_get1_encCert(const OSSL_CRMF_ENCRYPTEDVALUE *ecert, OSSL_LIB_CTX *libctx, const char *propq, EVP_PKEY *pkey) { X509 *cert = NULL; /* decrypted certificate */ EVP_CIPHER_CTX *evp_ctx = NULL; /* context for symmetric encryption */ unsigned char *ek = NULL; /* decrypted symmetric encryption key */ size_t eksize = 0; /* size of decrypted symmetric encryption key */ EVP_CIPHER *cipher = NULL; /* used cipher */ int cikeysize = 0; /* key size from cipher */ unsigned char *iv = NULL; /* initial vector for symmetric encryption */ unsigned char *outbuf = NULL; /* decryption output buffer */ const unsigned char *p = NULL; /* needed for decoding ASN1 */ int n, outlen = 0; EVP_PKEY_CTX *pkctx = NULL; /* private key context */ char name[OSSL_MAX_NAME_SIZE]; if (ecert == NULL || ecert->symmAlg == NULL || ecert->encSymmKey == NULL || ecert->encValue == NULL || pkey == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return NULL; } /* select symmetric cipher based on algorithm given in message */ OBJ_obj2txt(name, sizeof(name), ecert->symmAlg->algorithm, 0); (void)ERR_set_mark(); cipher = EVP_CIPHER_fetch(NULL, name, NULL); if (cipher == NULL) cipher = (EVP_CIPHER *)EVP_get_cipherbyname(name); if (cipher == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_CIPHER); goto end; } (void)ERR_pop_to_mark(); cikeysize = EVP_CIPHER_get_key_length(cipher); /* first the symmetric key needs to be decrypted */ pkctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (pkctx == NULL || EVP_PKEY_decrypt_init(pkctx) <= 0 || evp_pkey_decrypt_alloc(pkctx, &ek, &eksize, (size_t)cikeysize, ecert->encSymmKey->data, ecert->encSymmKey->length) <= 0) goto end; if ((iv = OPENSSL_malloc(EVP_CIPHER_get_iv_length(cipher))) == NULL) goto end; if (ASN1_TYPE_get_octetstring(ecert->symmAlg->parameter, iv, EVP_CIPHER_get_iv_length(cipher)) != EVP_CIPHER_get_iv_length(cipher)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_MALFORMED_IV); goto end; } /* * d2i_X509 changes the given pointer, so use p for decoding the message and * keep the original pointer in outbuf so the memory can be freed later */ if ((p = outbuf = OPENSSL_malloc(ecert->encValue->length + EVP_CIPHER_get_block_size(cipher))) == NULL || (evp_ctx = EVP_CIPHER_CTX_new()) == NULL) goto end; EVP_CIPHER_CTX_set_padding(evp_ctx, 0); if (!EVP_DecryptInit(evp_ctx, cipher, ek, iv) || !EVP_DecryptUpdate(evp_ctx, outbuf, &outlen, ecert->encValue->data, ecert->encValue->length) || !EVP_DecryptFinal(evp_ctx, outbuf + outlen, &n)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_ERROR_DECRYPTING_CERTIFICATE); goto end; } outlen += n; /* convert decrypted certificate from DER to internal ASN.1 structure */ if ((cert = X509_new_ex(libctx, propq)) == NULL) goto end; if (d2i_X509(&cert, &p, outlen) == NULL) ERR_raise(ERR_LIB_CRMF, CRMF_R_ERROR_DECODING_CERTIFICATE); end: EVP_PKEY_CTX_free(pkctx); OPENSSL_free(outbuf); EVP_CIPHER_CTX_free(evp_ctx); EVP_CIPHER_free(cipher); OPENSSL_clear_free(ek, eksize); OPENSSL_free(iv); return cert; }
./openssl/crypto/crmf/crmf_pbm.c
/*- * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * CRMF implementation by Martin Peylo, Miikka Viljanen, and David von Oheimb. */ #include <string.h> #include <openssl/rand.h> #include <openssl/evp.h> #include <openssl/hmac.h> /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/asn1t.h> #include <openssl/crmf.h> #include <openssl/err.h> #include <openssl/params.h> #include <openssl/core_names.h> #include "internal/sizes.h" #include "crmf_local.h" /*- * creates and initializes OSSL_CRMF_PBMPARAMETER (section 4.4) * |slen| SHOULD be at least 8 (16 is common) * |owfnid| e.g., NID_sha256 * |itercnt| MUST be >= 100 (e.g., 500) and <= OSSL_CRMF_PBM_MAX_ITERATION_COUNT * |macnid| e.g., NID_hmac_sha1 * returns pointer to OSSL_CRMF_PBMPARAMETER on success, NULL on error */ OSSL_CRMF_PBMPARAMETER *OSSL_CRMF_pbmp_new(OSSL_LIB_CTX *libctx, size_t slen, int owfnid, size_t itercnt, int macnid) { OSSL_CRMF_PBMPARAMETER *pbm = NULL; unsigned char *salt = NULL; if ((pbm = OSSL_CRMF_PBMPARAMETER_new()) == NULL) goto err; /* * salt contains a randomly generated value used in computing the key * of the MAC process. The salt SHOULD be at least 8 octets (64 * bits) long. */ if ((salt = OPENSSL_malloc(slen)) == NULL) goto err; if (RAND_bytes_ex(libctx, salt, slen, 0) <= 0) { ERR_raise(ERR_LIB_CRMF, CRMF_R_FAILURE_OBTAINING_RANDOM); goto err; } if (!ASN1_OCTET_STRING_set(pbm->salt, salt, (int)slen)) goto err; /* * owf identifies the hash algorithm and associated parameters used to * compute the key used in the MAC process. All implementations MUST * support SHA-1. */ if (!X509_ALGOR_set0(pbm->owf, OBJ_nid2obj(owfnid), V_ASN1_UNDEF, NULL)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_SETTING_OWF_ALGOR_FAILURE); goto err; } /* * iterationCount identifies the number of times the hash is applied * during the key computation process. The iterationCount MUST be a * minimum of 100. Many people suggest using values as high as 1000 * iterations as the minimum value. The trade off here is between * protection of the password from attacks and the time spent by the * server processing all of the different iterations in deriving * passwords. Hashing is generally considered a cheap operation but * this may not be true with all hash functions in the future. */ if (itercnt < 100) { ERR_raise(ERR_LIB_CRMF, CRMF_R_ITERATIONCOUNT_BELOW_100); goto err; } if (itercnt > OSSL_CRMF_PBM_MAX_ITERATION_COUNT) { ERR_raise(ERR_LIB_CRMF, CRMF_R_BAD_PBM_ITERATIONCOUNT); goto err; } if (!ASN1_INTEGER_set(pbm->iterationCount, itercnt)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_CRMFERROR); goto err; } /* * mac identifies the algorithm and associated parameters of the MAC * function to be used. All implementations MUST support HMAC-SHA1 [HMAC]. * All implementations SHOULD support DES-MAC and Triple-DES-MAC [PKCS11]. */ if (!X509_ALGOR_set0(pbm->mac, OBJ_nid2obj(macnid), V_ASN1_UNDEF, NULL)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_SETTING_MAC_ALGOR_FAILURE); goto err; } OPENSSL_free(salt); return pbm; err: OPENSSL_free(salt); OSSL_CRMF_PBMPARAMETER_free(pbm); return NULL; } /*- * calculates the PBM based on the settings of the given OSSL_CRMF_PBMPARAMETER * |pbmp| identifies the algorithms, salt to use * |msg| message to apply the PBM for * |msglen| length of the message * |sec| key to use * |seclen| length of the key * |out| pointer to the computed mac, will be set on success * |outlen| if not NULL, will set variable to the length of the mac on success * returns 1 on success, 0 on error */ /* could be combined with other MAC calculations in the library */ int OSSL_CRMF_pbm_new(OSSL_LIB_CTX *libctx, const char *propq, const OSSL_CRMF_PBMPARAMETER *pbmp, const unsigned char *msg, size_t msglen, const unsigned char *sec, size_t seclen, unsigned char **out, size_t *outlen) { int mac_nid, hmac_md_nid = NID_undef; char mdname[OSSL_MAX_NAME_SIZE]; char hmac_mdname[OSSL_MAX_NAME_SIZE]; EVP_MD *owf = NULL; EVP_MD_CTX *ctx = NULL; unsigned char basekey[EVP_MAX_MD_SIZE]; unsigned int bklen = EVP_MAX_MD_SIZE; int64_t iterations; unsigned char *mac_res = 0; int ok = 0; if (out == NULL || pbmp == NULL || pbmp->mac == NULL || pbmp->mac->algorithm == NULL || msg == NULL || sec == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); goto err; } if ((mac_res = OPENSSL_malloc(EVP_MAX_MD_SIZE)) == NULL) goto err; /* * owf identifies the hash algorithm and associated parameters used to * compute the key used in the MAC process. All implementations MUST * support SHA-1. */ OBJ_obj2txt(mdname, sizeof(mdname), pbmp->owf->algorithm, 0); if ((owf = EVP_MD_fetch(libctx, mdname, propq)) == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_ALGORITHM); goto err; } if ((ctx = EVP_MD_CTX_new()) == NULL) goto err; /* compute the basekey of the salted secret */ if (!EVP_DigestInit_ex(ctx, owf, NULL)) goto err; /* first the secret */ if (!EVP_DigestUpdate(ctx, sec, seclen)) goto err; /* then the salt */ if (!EVP_DigestUpdate(ctx, pbmp->salt->data, pbmp->salt->length)) goto err; if (!EVP_DigestFinal_ex(ctx, basekey, &bklen)) goto err; if (!ASN1_INTEGER_get_int64(&iterations, pbmp->iterationCount) || iterations < 100 /* min from RFC */ || iterations > OSSL_CRMF_PBM_MAX_ITERATION_COUNT) { ERR_raise(ERR_LIB_CRMF, CRMF_R_BAD_PBM_ITERATIONCOUNT); goto err; } /* the first iteration was already done above */ while (--iterations > 0) { if (!EVP_DigestInit_ex(ctx, owf, NULL)) goto err; if (!EVP_DigestUpdate(ctx, basekey, bklen)) goto err; if (!EVP_DigestFinal_ex(ctx, basekey, &bklen)) goto err; } /* * mac identifies the algorithm and associated parameters of the MAC * function to be used. All implementations MUST support HMAC-SHA1 [HMAC]. * All implementations SHOULD support DES-MAC and Triple-DES-MAC [PKCS11]. */ mac_nid = OBJ_obj2nid(pbmp->mac->algorithm); if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, mac_nid, NULL, &hmac_md_nid, NULL) || OBJ_obj2txt(hmac_mdname, sizeof(hmac_mdname), OBJ_nid2obj(hmac_md_nid), 0) <= 0) { ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_ALGORITHM); goto err; } /* could be generalized to allow non-HMAC: */ if (EVP_Q_mac(libctx, "HMAC", propq, hmac_mdname, NULL, basekey, bklen, msg, msglen, mac_res, EVP_MAX_MD_SIZE, outlen) == NULL) goto err; ok = 1; err: OPENSSL_cleanse(basekey, bklen); EVP_MD_free(owf); EVP_MD_CTX_free(ctx); if (ok == 1) { *out = mac_res; return 1; } OPENSSL_free(mac_res); if (pbmp != NULL && pbmp->mac != NULL) { char buf[128]; if (OBJ_obj2txt(buf, sizeof(buf), pbmp->mac->algorithm, 0)) ERR_add_error_data(1, buf); } return 0; }
./openssl/crypto/store/store_init.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 "crypto/store.h" #include "store_local.h" void ossl_store_cleanup_int(void) { ossl_store_destroy_loaders_int(); }
./openssl/crypto/store/store_strings.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 */ #include <openssl/store.h> static char *type_strings[] = { "Name", /* OSSL_STORE_INFO_NAME */ "Parameters", /* OSSL_STORE_INFO_PARAMS */ "Public key", /* OSSL_STORE_INFO_PUBKEY */ "Pkey", /* OSSL_STORE_INFO_PKEY */ "Certificate", /* OSSL_STORE_INFO_CERT */ "CRL" /* OSSL_STORE_INFO_CRL */ }; const char *OSSL_STORE_INFO_type_string(int type) { int types = sizeof(type_strings) / sizeof(type_strings[0]); if (type < 1 || type > types) return NULL; return type_strings[type - 1]; }
./openssl/crypto/store/store_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/storeerr.h> #include "crypto/storeerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA OSSL_STORE_str_reasons[] = { {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE), "ambiguous content type"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_BAD_PASSWORD_READ), "bad password read"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC), "error verifying pkcs12 mac"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_FINGERPRINT_SIZE_DOES_NOT_MATCH_DIGEST), "fingerprint size does not match digest"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_INVALID_SCHEME), "invalid scheme"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_IS_NOT_A), "is not a"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_LOADER_INCOMPLETE), "loader incomplete"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_LOADING_STARTED), "loading started"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_CERTIFICATE), "not a certificate"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_CRL), "not a crl"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_NAME), "not a name"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_PRIVATE_KEY), "not a private key"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_PUBLIC_KEY), "not a public key"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_PARAMETERS), "not parameters"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NO_LOADERS_FOUND), "no loaders found"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR), "passphrase callback error"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE), "path must be absolute"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES), "search only supported for directories"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED), "ui process interrupted or cancelled"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNREGISTERED_SCHEME), "unregistered scheme"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE), "unsupported content type"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNSUPPORTED_OPERATION), "unsupported operation"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE), "unsupported search type"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED), "uri authority unsupported"}, {0, NULL} }; #endif int ossl_err_load_OSSL_STORE_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(OSSL_STORE_str_reasons[0].error) == NULL) ERR_load_strings_const(OSSL_STORE_str_reasons); #endif return 1; }
./openssl/crypto/store/store_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/crypto.h> #include "crypto/store.h" #include "internal/core.h" #include "internal/namemap.h" #include "internal/property.h" #include "internal/provider.h" #include "store_local.h" #include "crypto/context.h" int OSSL_STORE_LOADER_up_ref(OSSL_STORE_LOADER *loader) { int ref = 0; if (loader->prov != NULL) CRYPTO_UP_REF(&loader->refcnt, &ref); return 1; } void OSSL_STORE_LOADER_free(OSSL_STORE_LOADER *loader) { if (loader != NULL && loader->prov != NULL) { int i; CRYPTO_DOWN_REF(&loader->refcnt, &i); if (i > 0) return; ossl_provider_free(loader->prov); CRYPTO_FREE_REF(&loader->refcnt); } OPENSSL_free(loader); } /* * OSSL_STORE_LOADER_new() expects the scheme as a constant string, * which we currently don't have, so we need an alternative allocator. */ static OSSL_STORE_LOADER *new_loader(OSSL_PROVIDER *prov) { OSSL_STORE_LOADER *loader; if ((loader = OPENSSL_zalloc(sizeof(*loader))) == NULL || !CRYPTO_NEW_REF(&loader->refcnt, 1)) { OPENSSL_free(loader); return NULL; } loader->prov = prov; ossl_provider_up_ref(prov); return loader; } static int up_ref_loader(void *method) { return OSSL_STORE_LOADER_up_ref(method); } static void free_loader(void *method) { OSSL_STORE_LOADER_free(method); } /* Data to be passed through ossl_method_construct() */ struct loader_data_st { OSSL_LIB_CTX *libctx; int scheme_id; /* For get_loader_from_store() */ const char *scheme; /* For get_loader_from_store() */ const char *propquery; /* For get_loader_from_store() */ OSSL_METHOD_STORE *tmp_store; /* For get_tmp_loader_store() */ unsigned int flag_construct_error_occurred : 1; }; /* * Generic routines to fetch / create OSSL_STORE methods with * ossl_method_construct() */ /* Temporary loader method store, constructor and destructor */ static void *get_tmp_loader_store(void *data) { struct loader_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_loader_store(void *store) { if (store != NULL) ossl_method_store_free(store); } /* Get the permanent loader store */ static OSSL_METHOD_STORE *get_loader_store(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_STORE_LOADER_STORE_INDEX); } static int reserve_loader_store(void *store, void *data) { struct loader_data_st *methdata = data; if (store == NULL && (store = get_loader_store(methdata->libctx)) == NULL) return 0; return ossl_method_lock_store(store); } static int unreserve_loader_store(void *store, void *data) { struct loader_data_st *methdata = data; if (store == NULL && (store = get_loader_store(methdata->libctx)) == NULL) return 0; return ossl_method_unlock_store(store); } /* Get loader methods from a store, or put one in */ static void *get_loader_from_store(void *store, const OSSL_PROVIDER **prov, void *data) { struct loader_data_st *methdata = data; void *method = NULL; int id; if ((id = methdata->scheme_id) == 0) { OSSL_NAMEMAP *namemap = ossl_namemap_stored(methdata->libctx); id = ossl_namemap_name2num(namemap, methdata->scheme); } if (store == NULL && (store = get_loader_store(methdata->libctx)) == NULL) return NULL; if (!ossl_method_store_fetch(store, id, methdata->propquery, prov, &method)) return NULL; return method; } static int put_loader_in_store(void *store, void *method, const OSSL_PROVIDER *prov, const char *scheme, const char *propdef, void *data) { struct loader_data_st *methdata = data; OSSL_NAMEMAP *namemap; int id; if ((namemap = ossl_namemap_stored(methdata->libctx)) == NULL || (id = ossl_namemap_name2num(namemap, scheme)) == 0) return 0; if (store == NULL && (store = get_loader_store(methdata->libctx)) == NULL) return 0; return ossl_method_store_add(store, prov, id, propdef, method, up_ref_loader, free_loader); } static void *loader_from_algorithm(int scheme_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { OSSL_STORE_LOADER *loader = NULL; const OSSL_DISPATCH *fns = algodef->implementation; if ((loader = new_loader(prov)) == NULL) return NULL; loader->scheme_id = scheme_id; loader->propdef = algodef->property_definition; loader->description = algodef->algorithm_description; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_STORE_OPEN: if (loader->p_open == NULL) loader->p_open = OSSL_FUNC_store_open(fns); break; case OSSL_FUNC_STORE_ATTACH: if (loader->p_attach == NULL) loader->p_attach = OSSL_FUNC_store_attach(fns); break; case OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS: if (loader->p_settable_ctx_params == NULL) loader->p_settable_ctx_params = OSSL_FUNC_store_settable_ctx_params(fns); break; case OSSL_FUNC_STORE_SET_CTX_PARAMS: if (loader->p_set_ctx_params == NULL) loader->p_set_ctx_params = OSSL_FUNC_store_set_ctx_params(fns); break; case OSSL_FUNC_STORE_LOAD: if (loader->p_load == NULL) loader->p_load = OSSL_FUNC_store_load(fns); break; case OSSL_FUNC_STORE_EOF: if (loader->p_eof == NULL) loader->p_eof = OSSL_FUNC_store_eof(fns); break; case OSSL_FUNC_STORE_CLOSE: if (loader->p_close == NULL) loader->p_close = OSSL_FUNC_store_close(fns); break; case OSSL_FUNC_STORE_EXPORT_OBJECT: if (loader->p_export_object == NULL) loader->p_export_object = OSSL_FUNC_store_export_object(fns); break; case OSSL_FUNC_STORE_DELETE: if (loader->p_delete == NULL) loader->p_delete = OSSL_FUNC_store_delete(fns); break; case OSSL_FUNC_STORE_OPEN_EX: if (loader->p_open_ex == NULL) loader->p_open_ex = OSSL_FUNC_store_open_ex(fns); break; } } if ((loader->p_open == NULL && loader->p_attach == NULL) || loader->p_load == NULL || loader->p_eof == NULL || loader->p_close == NULL) { /* Only set_ctx_params is optional */ OSSL_STORE_LOADER_free(loader); ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_LOADER_INCOMPLETE); return NULL; } return loader; } /* * The core fetching functionality passes the scheme of the implementation. * This function is responsible to getting an identity number for them, * then call loader_from_algorithm() with that identity number. */ static void *construct_loader(const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov, void *data) { /* * This function is only called if get_loader_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 scheme already exist there, we * know that ossl_namemap_add() will return its corresponding number. */ struct loader_data_st *methdata = data; OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); const char *scheme = algodef->algorithm_names; int id = ossl_namemap_add_name(namemap, 0, scheme); void *method = NULL; if (id != 0) method = loader_from_algorithm(id, algodef, prov); /* * Flag to indicate that there was actual construction errors. This * helps inner_loader_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_loader(void *method, void *data) { OSSL_STORE_LOADER_free(method); } /* Fetching support. Can fetch by numeric identity or by scheme */ static OSSL_STORE_LOADER * inner_loader_fetch(struct loader_data_st *methdata, const char *scheme, const char *properties) { OSSL_METHOD_STORE *store = get_loader_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_STORE, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } /* If we haven't received a name id yet, try to get one for the name */ id = scheme != NULL ? ossl_namemap_name2num(namemap, scheme) : 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_loader_store, reserve_loader_store, unreserve_loader_store, get_loader_from_store, put_loader_in_store, construct_loader, destruct_loader }; OSSL_PROVIDER *prov = NULL; methdata->scheme_id = id; methdata->scheme = scheme; methdata->propquery = propq; methdata->flag_construct_error_occurred = 0; if ((method = ossl_method_construct(methdata->libctx, OSSL_OP_STORE, &prov, 0 /* !force_cache */, &mcm, methdata)) != NULL) { /* * If construction did create a method for us, we know that there * is a correct scheme_id, since those have already been calculated * in get_loader_from_store() and put_loader_in_store() above. */ if (id == 0) id = ossl_namemap_name2num(namemap, scheme); ossl_method_store_cache_set(store, prov, id, propq, method, up_ref_loader, free_loader); } /* * If we never were in the constructor, the algorithm to be fetched * is unsupported. */ unsupported = !methdata->flag_construct_error_occurred; } if ((id != 0 || scheme != NULL) && method == NULL) { int code = unsupported ? ERR_R_UNSUPPORTED : ERR_R_FETCH_FAILED; const char *helpful_msg = unsupported ? ( "No store loader found. For standard store loaders you need " "at least one of the default or base providers available. " "Did you forget to load them? Info: " ) : ""; if (scheme == NULL) scheme = ossl_namemap_num2name(namemap, id, 0); ERR_raise_data(ERR_LIB_OSSL_STORE, code, "%s%s, Scheme (%s : %d), Properties (%s)", helpful_msg, ossl_lib_ctx_get_descriptor(methdata->libctx), scheme == NULL ? "<null>" : scheme, id, properties == NULL ? "<null>" : properties); } return method; } OSSL_STORE_LOADER *OSSL_STORE_LOADER_fetch(OSSL_LIB_CTX *libctx, const char *scheme, const char *properties) { struct loader_data_st methdata; void *method; methdata.libctx = libctx; methdata.tmp_store = NULL; method = inner_loader_fetch(&methdata, scheme, properties); dealloc_tmp_loader_store(methdata.tmp_store); return method; } int ossl_store_loader_store_cache_flush(OSSL_LIB_CTX *libctx) { OSSL_METHOD_STORE *store = get_loader_store(libctx); if (store != NULL) return ossl_method_store_cache_flush_all(store); return 1; } int ossl_store_loader_store_remove_all_provided(const OSSL_PROVIDER *prov) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_METHOD_STORE *store = get_loader_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_STORE_LOADER_get0_provider(const OSSL_STORE_LOADER *loader) { if (!ossl_assert(loader != NULL)) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_NULL_PARAMETER); return 0; } return loader->prov; } const char *OSSL_STORE_LOADER_get0_properties(const OSSL_STORE_LOADER *loader) { if (!ossl_assert(loader != NULL)) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_NULL_PARAMETER); return 0; } return loader->propdef; } int ossl_store_loader_get_number(const OSSL_STORE_LOADER *loader) { if (!ossl_assert(loader != NULL)) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_NULL_PARAMETER); return 0; } return loader->scheme_id; } const char *OSSL_STORE_LOADER_get0_description(const OSSL_STORE_LOADER *loader) { return loader->description; } int OSSL_STORE_LOADER_is_a(const OSSL_STORE_LOADER *loader, const char *name) { if (loader->prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(loader->prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_name2num(namemap, name) == loader->scheme_id; } return 0; } struct do_one_data_st { void (*user_fn)(OSSL_STORE_LOADER *loader, 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_STORE_LOADER_do_all_provided(OSSL_LIB_CTX *libctx, void (*user_fn)(OSSL_STORE_LOADER *loader, void *arg), void *user_arg) { struct loader_data_st methdata; struct do_one_data_st data; methdata.libctx = libctx; methdata.tmp_store = NULL; (void)inner_loader_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_loader_store(libctx), &do_one, &data); dealloc_tmp_loader_store(methdata.tmp_store); } int OSSL_STORE_LOADER_names_do_all(const OSSL_STORE_LOADER *loader, void (*fn)(const char *name, void *data), void *data) { if (loader == NULL) return 0; if (loader->prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(loader->prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_doall_names(namemap, loader->scheme_id, fn, data); } return 1; }
./openssl/crypto/store/store_local.h
/* * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core_dispatch.h> #include "internal/thread_once.h" #include "internal/refcount.h" #include <openssl/dsa.h> #include <openssl/engine.h> #include <openssl/evp.h> #include <openssl/lhash.h> #include <openssl/x509.h> #include <openssl/store.h> #include "internal/passphrase.h" /*- * OSSL_STORE_INFO stuff * --------------------- */ struct ossl_store_info_st { int type; union { void *data; /* used internally as generic pointer */ struct { char *name; char *desc; } name; /* when type == OSSL_STORE_INFO_NAME */ EVP_PKEY *params; /* when type == OSSL_STORE_INFO_PARAMS */ EVP_PKEY *pubkey; /* when type == OSSL_STORE_INFO_PUBKEY */ EVP_PKEY *pkey; /* when type == OSSL_STORE_INFO_PKEY */ X509 *x509; /* when type == OSSL_STORE_INFO_CERT */ X509_CRL *crl; /* when type == OSSL_STORE_INFO_CRL */ } _; }; DEFINE_STACK_OF(OSSL_STORE_INFO) /*- * OSSL_STORE_SEARCH stuff * ----------------------- */ struct ossl_store_search_st { int search_type; /* * Used by OSSL_STORE_SEARCH_BY_NAME and * OSSL_STORE_SEARCH_BY_ISSUER_SERIAL */ X509_NAME *name; /* Used by OSSL_STORE_SEARCH_BY_ISSUER_SERIAL */ const ASN1_INTEGER *serial; /* Used by OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT */ const EVP_MD *digest; /* * Used by OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT and * OSSL_STORE_SEARCH_BY_ALIAS */ const unsigned char *string; size_t stringlength; }; /*- * OSSL_STORE_LOADER stuff * ----------------------- */ int ossl_store_register_loader_int(OSSL_STORE_LOADER *loader); OSSL_STORE_LOADER *ossl_store_unregister_loader_int(const char *scheme); /* loader stuff */ struct ossl_store_loader_st { #ifndef OPENSSL_NO_DEPRECATED_3_0 /* Legacy stuff */ const char *scheme; ENGINE *engine; OSSL_STORE_open_fn open; OSSL_STORE_attach_fn attach; OSSL_STORE_ctrl_fn ctrl; OSSL_STORE_expect_fn expect; OSSL_STORE_find_fn find; OSSL_STORE_load_fn load; OSSL_STORE_eof_fn eof; OSSL_STORE_error_fn error; OSSL_STORE_close_fn closefn; OSSL_STORE_open_ex_fn open_ex; #endif /* Provider stuff */ OSSL_PROVIDER *prov; int scheme_id; const char *propdef; const char *description; CRYPTO_REF_COUNT refcnt; OSSL_FUNC_store_open_fn *p_open; OSSL_FUNC_store_attach_fn *p_attach; OSSL_FUNC_store_settable_ctx_params_fn *p_settable_ctx_params; OSSL_FUNC_store_set_ctx_params_fn *p_set_ctx_params; OSSL_FUNC_store_load_fn *p_load; OSSL_FUNC_store_eof_fn *p_eof; OSSL_FUNC_store_close_fn *p_close; OSSL_FUNC_store_export_object_fn *p_export_object; OSSL_FUNC_store_delete_fn *p_delete; OSSL_FUNC_store_open_ex_fn *p_open_ex; }; DEFINE_LHASH_OF_EX(OSSL_STORE_LOADER); const OSSL_STORE_LOADER *ossl_store_get0_loader_int(const char *scheme); void ossl_store_destroy_loaders_int(void); #ifdef OPENSSL_NO_DEPRECATED_3_0 /* struct ossl_store_loader_ctx_st is defined differently by each loader */ typedef struct ossl_store_loader_ctx_st OSSL_STORE_LOADER_CTX; #endif /*- * OSSL_STORE_CTX stuff * --------------------- */ struct ossl_store_ctx_st { const OSSL_STORE_LOADER *loader; /* legacy */ OSSL_STORE_LOADER *fetched_loader; OSSL_STORE_LOADER_CTX *loader_ctx; OSSL_STORE_post_process_info_fn post_process; void *post_process_data; int expected_type; char *properties; /* 0 before the first STORE_load(), 1 otherwise */ int loading; /* 1 on load error, only valid for fetched loaders */ int error_flag; /* * Cache of stuff, to be able to return the contents of a PKCS#12 * blob, one object at a time. */ STACK_OF(OSSL_STORE_INFO) *cached_info; struct ossl_passphrase_data_st pwdata; }; /*- * 'file' scheme stuff * ------------------- */ OSSL_STORE_LOADER_CTX *ossl_store_file_attach_pem_bio_int(BIO *bp); int ossl_store_file_detach_pem_bio_int(OSSL_STORE_LOADER_CTX *ctx); /*- * Provider stuff * ------------------- */ OSSL_STORE_LOADER *ossl_store_loader_fetch(OSSL_LIB_CTX *libctx, const char *scheme, const char *properties); /* Standard function to handle the result from OSSL_FUNC_store_load() */ struct ossl_load_result_data_st { OSSL_STORE_INFO *v; /* To be filled in */ OSSL_STORE_CTX *ctx; }; OSSL_CALLBACK ossl_store_handle_load_result;
./openssl/crypto/store/store_result.c
/* * Copyright 2020-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/e_os.h" #include <string.h> #include <openssl/core.h> #include <openssl/core_names.h> #include <openssl/core_object.h> #include <openssl/err.h> #include <openssl/pkcs12.h> #include <openssl/provider.h> #include <openssl/decoder.h> #include <openssl/store.h> #include "internal/provider.h" #include "internal/passphrase.h" #include "crypto/evp.h" #include "crypto/x509.h" #include "store_local.h" #ifndef OSSL_OBJECT_PKCS12 /* * The object abstraction doesn't know PKCS#12, but we want to indicate * it anyway, so we create our own. Since the public macros use positive * numbers, negative ones should be fine. They must never slip out from * this translation unit anyway. */ # define OSSL_OBJECT_PKCS12 -1 #endif /* * ossl_store_handle_load_result() is initially written to be a companion * to our 'file:' scheme provider implementation, but has been made generic * to serve others as well. * * This result handler takes any object abstraction (see provider-object(7)) * and does the best it can with it. If the object is passed by value (not * by reference), the contents are currently expected to be DER encoded. * If an object type is specified, that will be respected; otherwise, this * handler will guess the contents, by trying the following in order: * * 1. Decode it into an EVP_PKEY, using OSSL_DECODER. * 2. Decode it into an X.509 certificate, using d2i_X509 / d2i_X509_AUX. * 3. Decode it into an X.509 CRL, using d2i_X509_CRL. * 4. Decode it into a PKCS#12 structure, using d2i_PKCS12 (*). * * For the 'file:' scheme implementation, this is division of labor. Since * the libcrypto <-> provider interface currently doesn't support certain * structures as first class objects, they must be unpacked from DER here * rather than in the provider. The current exception is asymmetric keys, * which can reside within the provider boundary, most of all thanks to * OSSL_FUNC_keymgmt_load(), which allows loading the key material by * reference. */ struct extracted_param_data_st { int object_type; const char *data_type; const char *data_structure; const char *utf8_data; const void *octet_data; size_t octet_data_size; const void *ref; size_t ref_size; const char *desc; }; static int try_name(struct extracted_param_data_st *, OSSL_STORE_INFO **); static int try_key(struct extracted_param_data_st *, OSSL_STORE_INFO **, OSSL_STORE_CTX *, const OSSL_PROVIDER *, OSSL_LIB_CTX *, const char *); static int try_cert(struct extracted_param_data_st *, OSSL_STORE_INFO **, OSSL_LIB_CTX *, const char *); static int try_crl(struct extracted_param_data_st *, OSSL_STORE_INFO **, OSSL_LIB_CTX *, const char *); static int try_pkcs12(struct extracted_param_data_st *, OSSL_STORE_INFO **, OSSL_STORE_CTX *, OSSL_LIB_CTX *, const char *); int ossl_store_handle_load_result(const OSSL_PARAM params[], void *arg) { struct ossl_load_result_data_st *cbdata = arg; OSSL_STORE_INFO **v = &cbdata->v; OSSL_STORE_CTX *ctx = cbdata->ctx; const OSSL_PROVIDER *provider = OSSL_STORE_LOADER_get0_provider(ctx->fetched_loader); OSSL_LIB_CTX *libctx = ossl_provider_libctx(provider); const char *propq = ctx->properties; const OSSL_PARAM *p; struct extracted_param_data_st helper_data; memset(&helper_data, 0, sizeof(helper_data)); helper_data.object_type = OSSL_OBJECT_UNKNOWN; if ((p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_TYPE)) != NULL && !OSSL_PARAM_get_int(p, &helper_data.object_type)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE); if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &helper_data.data_type)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA); if (p != NULL && !OSSL_PARAM_get_octet_string_ptr(p, &helper_data.octet_data, &helper_data.octet_data_size) && !OSSL_PARAM_get_utf8_string_ptr(p, &helper_data.utf8_data)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_STRUCTURE); if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &helper_data.data_structure)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_REFERENCE); if (p != NULL && !OSSL_PARAM_get_octet_string_ptr(p, &helper_data.ref, &helper_data.ref_size)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DESC); if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &helper_data.desc)) return 0; /* * The helper functions return 0 on actual errors, otherwise 1, even if * they didn't fill out |*v|. */ ERR_set_mark(); if (*v == NULL && !try_name(&helper_data, v)) goto err; ERR_pop_to_mark(); ERR_set_mark(); if (*v == NULL && !try_key(&helper_data, v, ctx, provider, libctx, propq)) goto err; ERR_pop_to_mark(); ERR_set_mark(); if (*v == NULL && !try_cert(&helper_data, v, libctx, propq)) goto err; ERR_pop_to_mark(); ERR_set_mark(); if (*v == NULL && !try_crl(&helper_data, v, libctx, propq)) goto err; ERR_pop_to_mark(); ERR_set_mark(); if (*v == NULL && !try_pkcs12(&helper_data, v, ctx, libctx, propq)) goto err; ERR_pop_to_mark(); if (*v == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_UNSUPPORTED); return (*v != NULL); err: ERR_clear_last_mark(); return 0; } static int try_name(struct extracted_param_data_st *data, OSSL_STORE_INFO **v) { if (data->object_type == OSSL_OBJECT_NAME) { char *newname = NULL, *newdesc = NULL; if (data->utf8_data == NULL) return 0; if ((newname = OPENSSL_strdup(data->utf8_data)) == NULL || (data->desc != NULL && (newdesc = OPENSSL_strdup(data->desc)) == NULL) || (*v = OSSL_STORE_INFO_new_NAME(newname)) == NULL) { OPENSSL_free(newname); OPENSSL_free(newdesc); return 0; } OSSL_STORE_INFO_set0_NAME_description(*v, newdesc); } return 1; } /* * For the rest of the object types, the provider code may not know what * type of data it gave us, so we may need to figure that out on our own. * Therefore, we do check for OSSL_OBJECT_UNKNOWN everywhere below, and * only return 0 on error if the object type is known. */ static EVP_PKEY *try_key_ref(struct extracted_param_data_st *data, OSSL_STORE_CTX *ctx, const OSSL_PROVIDER *provider, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pk = NULL; EVP_KEYMGMT *keymgmt = NULL; void *keydata = NULL; int try_fallback = 2; /* If we have an object reference, we must have a data type */ if (data->data_type == NULL) return 0; keymgmt = EVP_KEYMGMT_fetch(libctx, data->data_type, propq); ERR_set_mark(); while (keymgmt != NULL && keydata == NULL && try_fallback-- > 0) { /* * There are two possible cases * * 1. The keymgmt is from the same provider as the loader, * so we can use evp_keymgmt_load() * 2. The keymgmt is from another provider, then we must * do the export/import dance. */ if (EVP_KEYMGMT_get0_provider(keymgmt) == provider) { /* no point trying fallback here */ try_fallback = 0; keydata = evp_keymgmt_load(keymgmt, data->ref, data->ref_size); } else { struct evp_keymgmt_util_try_import_data_st import_data; OSSL_FUNC_store_export_object_fn *export_object = ctx->fetched_loader->p_export_object; import_data.keymgmt = keymgmt; import_data.keydata = NULL; import_data.selection = OSSL_KEYMGMT_SELECT_ALL; if (export_object != NULL) { /* * No need to check for errors here, the value of * |import_data.keydata| is as much an indicator. */ (void)export_object(ctx->loader_ctx, data->ref, data->ref_size, &evp_keymgmt_util_try_import, &import_data); } keydata = import_data.keydata; } if (keydata == NULL && try_fallback > 0) { EVP_KEYMGMT_free(keymgmt); keymgmt = evp_keymgmt_fetch_from_prov((OSSL_PROVIDER *)provider, data->data_type, propq); if (keymgmt != NULL) { ERR_pop_to_mark(); ERR_set_mark(); } } } if (keydata != NULL) { ERR_pop_to_mark(); pk = evp_keymgmt_util_make_pkey(keymgmt, keydata); } else { ERR_clear_last_mark(); } EVP_KEYMGMT_free(keymgmt); return pk; } static EVP_PKEY *try_key_value(struct extracted_param_data_st *data, OSSL_STORE_CTX *ctx, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pk = NULL; OSSL_DECODER_CTX *decoderctx = NULL; const unsigned char *pdata = data->octet_data; size_t pdatalen = data->octet_data_size; int selection = 0; switch (ctx->expected_type) { case 0: break; case OSSL_STORE_INFO_PARAMS: selection = OSSL_KEYMGMT_SELECT_ALL_PARAMETERS; break; case OSSL_STORE_INFO_PUBKEY: selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY | OSSL_KEYMGMT_SELECT_ALL_PARAMETERS; break; case OSSL_STORE_INFO_PKEY: selection = OSSL_KEYMGMT_SELECT_ALL; break; default: return NULL; } decoderctx = OSSL_DECODER_CTX_new_for_pkey(&pk, NULL, data->data_structure, data->data_type, selection, libctx, propq); (void)OSSL_DECODER_CTX_set_passphrase_cb(decoderctx, cb, cbarg); /* No error if this couldn't be decoded */ (void)OSSL_DECODER_from_data(decoderctx, &pdata, &pdatalen); OSSL_DECODER_CTX_free(decoderctx); return pk; } typedef OSSL_STORE_INFO *store_info_new_fn(EVP_PKEY *); static EVP_PKEY *try_key_value_legacy(struct extracted_param_data_st *data, store_info_new_fn **store_info_new, OSSL_STORE_CTX *ctx, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pk = NULL; const unsigned char *der = data->octet_data, *derp; long der_len = (long)data->octet_data_size; /* Try PUBKEY first, that's a real easy target */ if (ctx->expected_type == 0 || ctx->expected_type == OSSL_STORE_INFO_PUBKEY) { derp = der; pk = d2i_PUBKEY_ex(NULL, &derp, der_len, libctx, propq); if (pk != NULL) *store_info_new = OSSL_STORE_INFO_new_PUBKEY; } /* Try private keys next */ if (pk == NULL && (ctx->expected_type == 0 || ctx->expected_type == OSSL_STORE_INFO_PKEY)) { unsigned char *new_der = NULL; X509_SIG *p8 = NULL; PKCS8_PRIV_KEY_INFO *p8info = NULL; /* See if it's an encrypted PKCS#8 and decrypt it. */ derp = der; p8 = d2i_X509_SIG(NULL, &derp, der_len); if (p8 != NULL) { char pbuf[PEM_BUFSIZE]; size_t plen = 0; if (!cb(pbuf, sizeof(pbuf), &plen, NULL, cbarg)) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_BAD_PASSWORD_READ); } else { const X509_ALGOR *alg = NULL; const ASN1_OCTET_STRING *oct = NULL; int len = 0; X509_SIG_get0(p8, &alg, &oct); /* * No need to check the returned value, |new_der| * will be NULL on error anyway. */ PKCS12_pbe_crypt(alg, pbuf, plen, oct->data, oct->length, &new_der, &len, 0); der_len = len; der = new_der; } X509_SIG_free(p8); } /* * If the encrypted PKCS#8 couldn't be decrypted, * |der| is NULL */ if (der != NULL) { /* Try to unpack an unencrypted PKCS#8, that's easy */ derp = der; p8info = d2i_PKCS8_PRIV_KEY_INFO(NULL, &derp, der_len); if (p8info != NULL) { pk = EVP_PKCS82PKEY_ex(p8info, libctx, propq); PKCS8_PRIV_KEY_INFO_free(p8info); } } if (pk != NULL) *store_info_new = OSSL_STORE_INFO_new_PKEY; OPENSSL_free(new_der); } return pk; } static int try_key(struct extracted_param_data_st *data, OSSL_STORE_INFO **v, OSSL_STORE_CTX *ctx, const OSSL_PROVIDER *provider, OSSL_LIB_CTX *libctx, const char *propq) { store_info_new_fn *store_info_new = NULL; if (data->object_type == OSSL_OBJECT_UNKNOWN || data->object_type == OSSL_OBJECT_PKEY) { EVP_PKEY *pk = NULL; /* Prefer key by reference than key by value */ if (data->object_type == OSSL_OBJECT_PKEY && data->ref != NULL) { pk = try_key_ref(data, ctx, provider, libctx, propq); /* * If for some reason we couldn't get a key, it's an error. * It indicates that while decoders could make a key reference, * the keymgmt somehow couldn't handle it, or doesn't have a * OSSL_FUNC_keymgmt_load function. */ if (pk == NULL) return 0; } else if (data->octet_data != NULL) { OSSL_PASSPHRASE_CALLBACK *cb = ossl_pw_passphrase_callback_dec; void *cbarg = &ctx->pwdata; pk = try_key_value(data, ctx, cb, cbarg, libctx, propq); /* * Desperate last maneuver, in case the decoders don't support * the data we have, then we try on our own to at least get an * engine provided legacy key. * This is the same as der2key_decode() does, but in a limited * way and within the walls of libcrypto. */ if (pk == NULL) pk = try_key_value_legacy(data, &store_info_new, ctx, cb, cbarg, libctx, propq); } if (pk != NULL) { data->object_type = OSSL_OBJECT_PKEY; if (store_info_new == NULL) { /* * We determined the object type for OSSL_STORE_INFO, which * makes an explicit difference between an EVP_PKEY with just * (domain) parameters and an EVP_PKEY with actual key * material. * The logic is that an EVP_PKEY with actual key material * always has the public half. */ if (evp_keymgmt_util_has(pk, OSSL_KEYMGMT_SELECT_PRIVATE_KEY)) store_info_new = OSSL_STORE_INFO_new_PKEY; else if (evp_keymgmt_util_has(pk, OSSL_KEYMGMT_SELECT_PUBLIC_KEY)) store_info_new = OSSL_STORE_INFO_new_PUBKEY; else store_info_new = OSSL_STORE_INFO_new_PARAMS; } *v = store_info_new(pk); } if (*v == NULL) EVP_PKEY_free(pk); } return 1; } static int try_cert(struct extracted_param_data_st *data, OSSL_STORE_INFO **v, OSSL_LIB_CTX *libctx, const char *propq) { if (data->object_type == OSSL_OBJECT_UNKNOWN || data->object_type == OSSL_OBJECT_CERT) { /* * In most cases, we can try to interpret the serialized * data as a trusted cert (X509 + X509_AUX) and fall back * to reading it as a normal cert (just X509), but if * |data_type| (the PEM name) specifically declares it as a * trusted cert, then no fallback should be engaged. * |ignore_trusted| tells if the fallback can be used (1) * or not (0). */ int ignore_trusted = 1; X509 *cert = X509_new_ex(libctx, propq); if (cert == NULL) return 0; /* If we have a data type, it should be a PEM name */ if (data->data_type != NULL && (OPENSSL_strcasecmp(data->data_type, PEM_STRING_X509_TRUSTED) == 0)) ignore_trusted = 0; if (d2i_X509_AUX(&cert, (const unsigned char **)&data->octet_data, data->octet_data_size) == NULL && (!ignore_trusted || d2i_X509(&cert, (const unsigned char **)&data->octet_data, data->octet_data_size) == NULL)) { X509_free(cert); cert = NULL; } if (cert != NULL) { /* We determined the object type */ data->object_type = OSSL_OBJECT_CERT; *v = OSSL_STORE_INFO_new_CERT(cert); if (*v == NULL) X509_free(cert); } } return 1; } static int try_crl(struct extracted_param_data_st *data, OSSL_STORE_INFO **v, OSSL_LIB_CTX *libctx, const char *propq) { if (data->object_type == OSSL_OBJECT_UNKNOWN || data->object_type == OSSL_OBJECT_CRL) { X509_CRL *crl; crl = d2i_X509_CRL(NULL, (const unsigned char **)&data->octet_data, data->octet_data_size); if (crl != NULL) /* We determined the object type */ data->object_type = OSSL_OBJECT_CRL; if (crl != NULL && !ossl_x509_crl_set0_libctx(crl, libctx, propq)) { X509_CRL_free(crl); crl = NULL; } if (crl != NULL) *v = OSSL_STORE_INFO_new_CRL(crl); if (*v == NULL) X509_CRL_free(crl); } return 1; } static int try_pkcs12(struct extracted_param_data_st *data, OSSL_STORE_INFO **v, OSSL_STORE_CTX *ctx, OSSL_LIB_CTX *libctx, const char *propq) { int ok = 1; /* There is no specific object type for PKCS12 */ if (data->object_type == OSSL_OBJECT_UNKNOWN) { /* Initial parsing */ PKCS12 *p12; p12 = d2i_PKCS12(NULL, (const unsigned char **)&data->octet_data, data->octet_data_size); if (p12 != NULL) { char *pass = NULL; char tpass[PEM_BUFSIZE + 1]; size_t tpass_len; EVP_PKEY *pkey = NULL; X509 *cert = NULL; STACK_OF(X509) *chain = NULL; data->object_type = OSSL_OBJECT_PKCS12; ok = 0; /* Assume decryption or parse error */ if (!PKCS12_mac_present(p12) || PKCS12_verify_mac(p12, NULL, 0)) { pass = NULL; } else if (PKCS12_verify_mac(p12, "", 0)) { pass = ""; } else { static char prompt_info[] = "PKCS12 import pass phrase"; OSSL_PARAM pw_params[] = { OSSL_PARAM_utf8_string(OSSL_PASSPHRASE_PARAM_INFO, prompt_info, sizeof(prompt_info) - 1), OSSL_PARAM_END }; if (!ossl_pw_get_passphrase(tpass, sizeof(tpass) - 1, &tpass_len, pw_params, 0, &ctx->pwdata)) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR); goto p12_end; } pass = tpass; /* * ossl_pw_get_passphrase() does not NUL terminate but * we must do it for PKCS12_parse() */ pass[tpass_len] = '\0'; if (!PKCS12_verify_mac(p12, pass, tpass_len)) { ERR_raise_data(ERR_LIB_OSSL_STORE, OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC, tpass_len == 0 ? "empty password" : "maybe wrong password"); goto p12_end; } } if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) { STACK_OF(OSSL_STORE_INFO) *infos = NULL; OSSL_STORE_INFO *osi_pkey = NULL; OSSL_STORE_INFO *osi_cert = NULL; OSSL_STORE_INFO *osi_ca = NULL; ok = 1; /* Parsing went through correctly! */ if ((infos = sk_OSSL_STORE_INFO_new_null()) != NULL) { if (pkey != NULL) { if ((osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL /* clearing pkey here avoids case distinctions */ && (pkey = NULL) == NULL && sk_OSSL_STORE_INFO_push(infos, osi_pkey) != 0) osi_pkey = NULL; else ok = 0; } if (ok && cert != NULL) { if ((osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL /* clearing cert here avoids case distinctions */ && (cert = NULL) == NULL && sk_OSSL_STORE_INFO_push(infos, osi_cert) != 0) osi_cert = NULL; else ok = 0; } while (ok && sk_X509_num(chain) > 0) { X509 *ca = sk_X509_value(chain, 0); if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) != NULL && sk_X509_shift(chain) != NULL && sk_OSSL_STORE_INFO_push(infos, osi_ca) != 0) osi_ca = NULL; else ok = 0; } } EVP_PKEY_free(pkey); X509_free(cert); OSSL_STACK_OF_X509_free(chain); OSSL_STORE_INFO_free(osi_pkey); OSSL_STORE_INFO_free(osi_cert); OSSL_STORE_INFO_free(osi_ca); if (!ok) { sk_OSSL_STORE_INFO_pop_free(infos, OSSL_STORE_INFO_free); infos = NULL; } ctx->cached_info = infos; } p12_end: OPENSSL_cleanse(tpass, sizeof(tpass)); PKCS12_free(p12); } *v = sk_OSSL_STORE_INFO_shift(ctx->cached_info); } return ok; }
./openssl/crypto/store/store_register.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 "crypto/ctype.h" #include <assert.h> #include <openssl/err.h> #include <openssl/lhash.h> #include "store_local.h" static CRYPTO_RWLOCK *registry_lock; static CRYPTO_ONCE registry_init = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(do_registry_init) { registry_lock = CRYPTO_THREAD_lock_new(); return registry_lock != NULL; } /* * Functions for manipulating OSSL_STORE_LOADERs */ OSSL_STORE_LOADER *OSSL_STORE_LOADER_new(ENGINE *e, const char *scheme) { OSSL_STORE_LOADER *res = NULL; /* * We usually don't check NULL arguments. For loaders, though, the * scheme is crucial and must never be NULL, or the user will get * mysterious errors when trying to register the created loader * later on. */ if (scheme == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_INVALID_SCHEME); return NULL; } if ((res = OPENSSL_zalloc(sizeof(*res))) == NULL) return NULL; res->engine = e; res->scheme = scheme; return res; } const ENGINE *OSSL_STORE_LOADER_get0_engine(const OSSL_STORE_LOADER *loader) { return loader->engine; } const char *OSSL_STORE_LOADER_get0_scheme(const OSSL_STORE_LOADER *loader) { return loader->scheme; } int OSSL_STORE_LOADER_set_open(OSSL_STORE_LOADER *loader, OSSL_STORE_open_fn open_function) { loader->open = open_function; return 1; } int OSSL_STORE_LOADER_set_open_ex (OSSL_STORE_LOADER *loader, OSSL_STORE_open_ex_fn open_ex_function) { loader->open_ex = open_ex_function; return 1; } int OSSL_STORE_LOADER_set_attach(OSSL_STORE_LOADER *loader, OSSL_STORE_attach_fn attach_function) { loader->attach = attach_function; return 1; } int OSSL_STORE_LOADER_set_ctrl(OSSL_STORE_LOADER *loader, OSSL_STORE_ctrl_fn ctrl_function) { loader->ctrl = ctrl_function; return 1; } int OSSL_STORE_LOADER_set_expect(OSSL_STORE_LOADER *loader, OSSL_STORE_expect_fn expect_function) { loader->expect = expect_function; return 1; } int OSSL_STORE_LOADER_set_find(OSSL_STORE_LOADER *loader, OSSL_STORE_find_fn find_function) { loader->find = find_function; return 1; } int OSSL_STORE_LOADER_set_load(OSSL_STORE_LOADER *loader, OSSL_STORE_load_fn load_function) { loader->load = load_function; return 1; } int OSSL_STORE_LOADER_set_eof(OSSL_STORE_LOADER *loader, OSSL_STORE_eof_fn eof_function) { loader->eof = eof_function; return 1; } int OSSL_STORE_LOADER_set_error(OSSL_STORE_LOADER *loader, OSSL_STORE_error_fn error_function) { loader->error = error_function; return 1; } int OSSL_STORE_LOADER_set_close(OSSL_STORE_LOADER *loader, OSSL_STORE_close_fn close_function) { loader->closefn = close_function; return 1; } /* * Functions for registering OSSL_STORE_LOADERs */ static unsigned long store_loader_hash(const OSSL_STORE_LOADER *v) { return OPENSSL_LH_strhash(v->scheme); } static int store_loader_cmp(const OSSL_STORE_LOADER *a, const OSSL_STORE_LOADER *b) { assert(a->scheme != NULL && b->scheme != NULL); return strcmp(a->scheme, b->scheme); } static LHASH_OF(OSSL_STORE_LOADER) *loader_register = NULL; static int ossl_store_register_init(void) { if (loader_register == NULL) { loader_register = lh_OSSL_STORE_LOADER_new(store_loader_hash, store_loader_cmp); } return loader_register != NULL; } int ossl_store_register_loader_int(OSSL_STORE_LOADER *loader) { const char *scheme = loader->scheme; int ok = 0; /* * Check that the given scheme conforms to correct scheme syntax as per * RFC 3986: * * scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */ if (ossl_isalpha(*scheme)) while (*scheme != '\0' && (ossl_isalpha(*scheme) || ossl_isdigit(*scheme) || strchr("+-.", *scheme) != NULL)) scheme++; if (*scheme != '\0') { ERR_raise_data(ERR_LIB_OSSL_STORE, OSSL_STORE_R_INVALID_SCHEME, "scheme=%s", loader->scheme); return 0; } /* Check that functions we absolutely require are present */ if (loader->open == NULL || loader->load == NULL || loader->eof == NULL || loader->error == NULL || loader->closefn == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_LOADER_INCOMPLETE); return 0; } if (!RUN_ONCE(&registry_init, do_registry_init)) { /* Should this error be raised in do_registry_init()? */ ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_CRYPTO_LIB); return 0; } if (!CRYPTO_THREAD_write_lock(registry_lock)) return 0; if (ossl_store_register_init() && (lh_OSSL_STORE_LOADER_insert(loader_register, loader) != NULL || lh_OSSL_STORE_LOADER_error(loader_register) == 0)) ok = 1; CRYPTO_THREAD_unlock(registry_lock); return ok; } int OSSL_STORE_register_loader(OSSL_STORE_LOADER *loader) { return ossl_store_register_loader_int(loader); } const OSSL_STORE_LOADER *ossl_store_get0_loader_int(const char *scheme) { OSSL_STORE_LOADER template; OSSL_STORE_LOADER *loader = NULL; template.scheme = scheme; template.open = NULL; template.load = NULL; template.eof = NULL; template.closefn = NULL; template.open_ex = NULL; if (!RUN_ONCE(&registry_init, do_registry_init)) { /* Should this error be raised in do_registry_init()? */ ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_CRYPTO_LIB); return NULL; } if (!CRYPTO_THREAD_write_lock(registry_lock)) return NULL; if (!ossl_store_register_init()) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_INTERNAL_ERROR); else if ((loader = lh_OSSL_STORE_LOADER_retrieve(loader_register, &template)) == NULL) ERR_raise_data(ERR_LIB_OSSL_STORE, OSSL_STORE_R_UNREGISTERED_SCHEME, "scheme=%s", scheme); CRYPTO_THREAD_unlock(registry_lock); return loader; } OSSL_STORE_LOADER *ossl_store_unregister_loader_int(const char *scheme) { OSSL_STORE_LOADER template; OSSL_STORE_LOADER *loader = NULL; template.scheme = scheme; template.open = NULL; template.load = NULL; template.eof = NULL; template.closefn = NULL; if (!RUN_ONCE(&registry_init, do_registry_init)) { /* Should this error be raised in do_registry_init()? */ ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_CRYPTO_LIB); return NULL; } if (!CRYPTO_THREAD_write_lock(registry_lock)) return NULL; if (!ossl_store_register_init()) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_INTERNAL_ERROR); else if ((loader = lh_OSSL_STORE_LOADER_delete(loader_register, &template)) == NULL) ERR_raise_data(ERR_LIB_OSSL_STORE, OSSL_STORE_R_UNREGISTERED_SCHEME, "scheme=%s", scheme); CRYPTO_THREAD_unlock(registry_lock); return loader; } OSSL_STORE_LOADER *OSSL_STORE_unregister_loader(const char *scheme) { return ossl_store_unregister_loader_int(scheme); } void ossl_store_destroy_loaders_int(void) { lh_OSSL_STORE_LOADER_free(loader_register); loader_register = NULL; CRYPTO_THREAD_lock_free(registry_lock); registry_lock = NULL; } /* * Functions to list OSSL_STORE loaders */ IMPLEMENT_LHASH_DOALL_ARG_CONST(OSSL_STORE_LOADER, void); int OSSL_STORE_do_all_loaders(void (*do_function) (const OSSL_STORE_LOADER *loader, void *do_arg), void *do_arg) { if (ossl_store_register_init()) lh_OSSL_STORE_LOADER_doall_void(loader_register, do_function, do_arg); return 1; }
./openssl/crypto/store/store_lib.c
/* * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdlib.h> #include <string.h> #include <assert.h> /* We need to use some STORE deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include "internal/e_os.h" #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/trace.h> #include <openssl/core_names.h> #include <openssl/provider.h> #include <openssl/param_build.h> #include <openssl/store.h> #include "internal/thread_once.h" #include "internal/cryptlib.h" #include "internal/provider.h" #include "internal/bio.h" #include "crypto/store.h" #include "store_local.h" static int ossl_store_close_it(OSSL_STORE_CTX *ctx); static int loader_set_params(OSSL_STORE_LOADER *loader, OSSL_STORE_LOADER_CTX *loader_ctx, const OSSL_PARAM params[], const char *propq) { if (params != NULL) { if (!loader->p_set_ctx_params(loader_ctx, params)) return 0; } if (propq != NULL) { OSSL_PARAM propp[2]; if (OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_PROPERTIES) != NULL) /* use the propq from params */ return 1; propp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_PROPERTIES, (char *)propq, 0); propp[1] = OSSL_PARAM_construct_end(); if (!loader->p_set_ctx_params(loader_ctx, propp)) return 0; } return 1; } OSSL_STORE_CTX * OSSL_STORE_open_ex(const char *uri, OSSL_LIB_CTX *libctx, const char *propq, const UI_METHOD *ui_method, void *ui_data, const OSSL_PARAM params[], OSSL_STORE_post_process_info_fn post_process, void *post_process_data) { struct ossl_passphrase_data_st pwdata = { 0 }; const OSSL_STORE_LOADER *loader = NULL; OSSL_STORE_LOADER *fetched_loader = NULL; OSSL_STORE_LOADER_CTX *loader_ctx = NULL; OSSL_STORE_CTX *ctx = NULL; char *propq_copy = NULL; int no_loader_found = 1; char scheme_copy[256], *p, *schemes[2], *scheme = NULL; size_t schemes_n = 0; size_t i; /* * Put the file scheme first. If the uri does represent an existing file, * possible device name and all, then it should be loaded. Only a failed * attempt at loading a local file should have us try something else. */ schemes[schemes_n++] = "file"; /* * Now, check if we have something that looks like a scheme, and add it * as a second scheme. However, also check if there's an authority start * (://), because that will invalidate the previous file scheme. Also, * check that this isn't actually the file scheme, as there's no point * going through that one twice! */ OPENSSL_strlcpy(scheme_copy, uri, sizeof(scheme_copy)); if ((p = strchr(scheme_copy, ':')) != NULL) { *p++ = '\0'; if (OPENSSL_strcasecmp(scheme_copy, "file") != 0) { if (HAS_PREFIX(p, "//")) schemes_n--; /* Invalidate the file scheme */ schemes[schemes_n++] = scheme_copy; } } ERR_set_mark(); if (ui_method != NULL && (!ossl_pw_set_ui_method(&pwdata, ui_method, ui_data) || !ossl_pw_enable_passphrase_caching(&pwdata))) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_CRYPTO_LIB); goto err; } /* * Try each scheme until we find one that could open the URI. * * For each scheme, we look for the engine implementation first, and * failing that, we then try to fetch a provided implementation. * This is consistent with how we handle legacy / engine implementations * elsewhere. */ for (i = 0; loader_ctx == NULL && i < schemes_n; i++) { scheme = schemes[i]; OSSL_TRACE1(STORE, "Looking up scheme %s\n", scheme); #ifndef OPENSSL_NO_DEPRECATED_3_0 ERR_set_mark(); if ((loader = ossl_store_get0_loader_int(scheme)) != NULL) { ERR_clear_last_mark(); no_loader_found = 0; if (loader->open_ex != NULL) loader_ctx = loader->open_ex(loader, uri, libctx, propq, ui_method, ui_data); else loader_ctx = loader->open(loader, uri, ui_method, ui_data); } else { ERR_pop_to_mark(); } #endif if (loader == NULL && (fetched_loader = OSSL_STORE_LOADER_fetch(libctx, scheme, propq)) != NULL) { const OSSL_PROVIDER *provider = OSSL_STORE_LOADER_get0_provider(fetched_loader); void *provctx = OSSL_PROVIDER_get0_provider_ctx(provider); no_loader_found = 0; if (fetched_loader->p_open_ex != NULL) { loader_ctx = fetched_loader->p_open_ex(provctx, uri, params, ossl_pw_passphrase_callback_dec, &pwdata); } else { loader_ctx = fetched_loader->p_open(provctx, uri); if (loader_ctx != NULL && !loader_set_params(fetched_loader, loader_ctx, params, propq)) { (void)fetched_loader->p_close(loader_ctx); loader_ctx = NULL; } } if (loader_ctx == NULL) { OSSL_STORE_LOADER_free(fetched_loader); fetched_loader = NULL; } loader = fetched_loader; /* Clear any internally cached passphrase */ (void)ossl_pw_clear_passphrase_cache(&pwdata); } } if (no_loader_found) /* * It's assumed that ossl_store_get0_loader_int() and * OSSL_STORE_LOADER_fetch() report their own errors */ goto err; OSSL_TRACE1(STORE, "Found loader for scheme %s\n", scheme); if (loader_ctx == NULL) /* * It's assumed that the loader's open() method reports its own * errors */ goto err; OSSL_TRACE2(STORE, "Opened %s => %p\n", uri, (void *)loader_ctx); if ((propq != NULL && (propq_copy = OPENSSL_strdup(propq)) == NULL) || (ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) goto err; ctx->properties = propq_copy; ctx->fetched_loader = fetched_loader; ctx->loader = loader; ctx->loader_ctx = loader_ctx; ctx->post_process = post_process; ctx->post_process_data = post_process_data; ctx->pwdata = pwdata; /* * If the attempt to open with the 'file' scheme loader failed and the * other scheme loader succeeded, the failure to open with the 'file' * scheme loader leaves an error on the error stack. Let's remove it. */ ERR_pop_to_mark(); return ctx; err: ERR_clear_last_mark(); if (loader_ctx != NULL) { /* * Temporary structure so OSSL_STORE_close() can work even when * |ctx| couldn't be allocated properly */ OSSL_STORE_CTX tmpctx = { NULL, }; tmpctx.fetched_loader = fetched_loader; tmpctx.loader = loader; tmpctx.loader_ctx = loader_ctx; /* * We ignore a returned error because we will return NULL anyway in * this case, so if something goes wrong when closing, that'll simply * just add another entry on the error stack. */ (void)ossl_store_close_it(&tmpctx); } /* Coverity false positive, the reference counting is confusing it */ /* coverity[pass_freed_arg] */ OSSL_STORE_LOADER_free(fetched_loader); OPENSSL_free(propq_copy); OPENSSL_free(ctx); return NULL; } OSSL_STORE_CTX *OSSL_STORE_open(const char *uri, const UI_METHOD *ui_method, void *ui_data, OSSL_STORE_post_process_info_fn post_process, void *post_process_data) { return OSSL_STORE_open_ex(uri, NULL, NULL, ui_method, ui_data, NULL, post_process, post_process_data); } #ifndef OPENSSL_NO_DEPRECATED_3_0 int OSSL_STORE_ctrl(OSSL_STORE_CTX *ctx, int cmd, ...) { va_list args; int ret; va_start(args, cmd); ret = OSSL_STORE_vctrl(ctx, cmd, args); va_end(args); return ret; } int OSSL_STORE_vctrl(OSSL_STORE_CTX *ctx, int cmd, va_list args) { if (ctx->fetched_loader != NULL) { if (ctx->fetched_loader->p_set_ctx_params != NULL) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; switch (cmd) { case OSSL_STORE_C_USE_SECMEM: { int on = *(va_arg(args, int *)); params[0] = OSSL_PARAM_construct_int("use_secmem", &on); } break; default: break; } return ctx->fetched_loader->p_set_ctx_params(ctx->loader_ctx, params); } } else if (ctx->loader->ctrl != NULL) { return ctx->loader->ctrl(ctx->loader_ctx, cmd, args); } /* * If the fetched loader doesn't have a set_ctx_params or a ctrl, it's as * if there was one that ignored our params, which usually returns 1. */ return 1; } #endif int OSSL_STORE_expect(OSSL_STORE_CTX *ctx, int expected_type) { int ret = 1; if (ctx == NULL || expected_type < 0 || expected_type > OSSL_STORE_INFO_CRL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->loading) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_LOADING_STARTED); return 0; } ctx->expected_type = expected_type; if (ctx->fetched_loader != NULL && ctx->fetched_loader->p_set_ctx_params != NULL) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_int(OSSL_STORE_PARAM_EXPECT, &expected_type); ret = ctx->fetched_loader->p_set_ctx_params(ctx->loader_ctx, params); } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL && ctx->loader->expect != NULL) { ret = ctx->loader->expect(ctx->loader_ctx, expected_type); } #endif return ret; } int OSSL_STORE_find(OSSL_STORE_CTX *ctx, const OSSL_STORE_SEARCH *search) { int ret = 1; if (ctx->loading) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_LOADING_STARTED); return 0; } if (search == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ctx->fetched_loader != NULL) { OSSL_PARAM_BLD *bld; OSSL_PARAM *params; /* OSSL_STORE_SEARCH_BY_NAME, OSSL_STORE_SEARCH_BY_ISSUER_SERIAL*/ void *name_der = NULL; int name_der_sz; /* OSSL_STORE_SEARCH_BY_ISSUER_SERIAL */ BIGNUM *number = NULL; if (ctx->fetched_loader->p_set_ctx_params == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_UNSUPPORTED_OPERATION); return 0; } if ((bld = OSSL_PARAM_BLD_new()) == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_CRYPTO_LIB); return 0; } ret = 0; /* Assume the worst */ switch (search->search_type) { case OSSL_STORE_SEARCH_BY_NAME: if ((name_der_sz = i2d_X509_NAME(search->name, (unsigned char **)&name_der)) > 0 && OSSL_PARAM_BLD_push_octet_string(bld, OSSL_STORE_PARAM_SUBJECT, name_der, name_der_sz)) ret = 1; break; case OSSL_STORE_SEARCH_BY_ISSUER_SERIAL: if ((name_der_sz = i2d_X509_NAME(search->name, (unsigned char **)&name_der)) > 0 && (number = ASN1_INTEGER_to_BN(search->serial, NULL)) != NULL && OSSL_PARAM_BLD_push_octet_string(bld, OSSL_STORE_PARAM_ISSUER, name_der, name_der_sz) && OSSL_PARAM_BLD_push_BN(bld, OSSL_STORE_PARAM_SERIAL, number)) ret = 1; break; case OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT: if (OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_STORE_PARAM_DIGEST, EVP_MD_get0_name(search->digest), 0) && OSSL_PARAM_BLD_push_octet_string(bld, OSSL_STORE_PARAM_FINGERPRINT, search->string, search->stringlength)) ret = 1; break; case OSSL_STORE_SEARCH_BY_ALIAS: if (OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_STORE_PARAM_ALIAS, (char *)search->string, search->stringlength)) ret = 1; break; } if (ret) { params = OSSL_PARAM_BLD_to_param(bld); ret = ctx->fetched_loader->p_set_ctx_params(ctx->loader_ctx, params); OSSL_PARAM_free(params); } OSSL_PARAM_BLD_free(bld); OPENSSL_free(name_der); BN_free(number); } else { #ifndef OPENSSL_NO_DEPRECATED_3_0 /* legacy loader section */ if (ctx->loader->find == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_UNSUPPORTED_OPERATION); return 0; } ret = ctx->loader->find(ctx->loader_ctx, search); #endif } return ret; } OSSL_STORE_INFO *OSSL_STORE_load(OSSL_STORE_CTX *ctx) { OSSL_STORE_INFO *v = NULL; ctx->loading = 1; again: if (OSSL_STORE_eof(ctx)) return NULL; if (ctx->loader != NULL) OSSL_TRACE(STORE, "Loading next object\n"); if (ctx->cached_info != NULL && sk_OSSL_STORE_INFO_num(ctx->cached_info) == 0) { sk_OSSL_STORE_INFO_free(ctx->cached_info); ctx->cached_info = NULL; } if (ctx->cached_info != NULL) { v = sk_OSSL_STORE_INFO_shift(ctx->cached_info); } else { if (ctx->fetched_loader != NULL) { struct ossl_load_result_data_st load_data; load_data.v = NULL; load_data.ctx = ctx; ctx->error_flag = 0; if (!ctx->fetched_loader->p_load(ctx->loader_ctx, ossl_store_handle_load_result, &load_data, ossl_pw_passphrase_callback_dec, &ctx->pwdata)) { ctx->error_flag = 1; return NULL; } v = load_data.v; } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL) v = ctx->loader->load(ctx->loader_ctx, ctx->pwdata._.ui_method.ui_method, ctx->pwdata._.ui_method.ui_method_data); #endif } if (ctx->post_process != NULL && v != NULL) { v = ctx->post_process(v, ctx->post_process_data); /* * By returning NULL, the callback decides that this object should * be ignored. */ if (v == NULL) goto again; } /* Clear any internally cached passphrase */ (void)ossl_pw_clear_passphrase_cache(&ctx->pwdata); if (v != NULL && ctx->expected_type != 0) { int returned_type = OSSL_STORE_INFO_get_type(v); if (returned_type != OSSL_STORE_INFO_NAME && returned_type != 0) { if (ctx->expected_type != returned_type) { OSSL_STORE_INFO_free(v); goto again; } } } if (v != NULL) OSSL_TRACE1(STORE, "Got a %s\n", OSSL_STORE_INFO_type_string(OSSL_STORE_INFO_get_type(v))); return v; } int OSSL_STORE_delete(const char *uri, OSSL_LIB_CTX *libctx, const char *propq, const UI_METHOD *ui_method, void *ui_data, const OSSL_PARAM params[]) { OSSL_STORE_LOADER *fetched_loader = NULL; char scheme[256], *p; int res = 0; struct ossl_passphrase_data_st pwdata = {0}; OPENSSL_strlcpy(scheme, uri, sizeof(scheme)); if ((p = strchr(scheme, ':')) != NULL) *p++ = '\0'; else /* We don't work without explicit scheme */ return 0; if (ui_method != NULL && (!ossl_pw_set_ui_method(&pwdata, ui_method, ui_data) || !ossl_pw_enable_passphrase_caching(&pwdata))) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_CRYPTO_LIB); return 0; } OSSL_TRACE1(STORE, "Looking up scheme %s\n", scheme); fetched_loader = OSSL_STORE_LOADER_fetch(libctx, scheme, propq); if (fetched_loader != NULL && fetched_loader->p_delete != NULL) { const OSSL_PROVIDER *provider = OSSL_STORE_LOADER_get0_provider(fetched_loader); void *provctx = OSSL_PROVIDER_get0_provider_ctx(provider); /* * It's assumed that the loader's delete() method reports its own * errors */ OSSL_TRACE1(STORE, "Performing URI delete %s\n", uri); res = fetched_loader->p_delete(provctx, uri, params, ossl_pw_passphrase_callback_dec, &pwdata); } /* Clear any internally cached passphrase */ (void)ossl_pw_clear_passphrase_cache(&pwdata); OSSL_STORE_LOADER_free(fetched_loader); return res; } int OSSL_STORE_error(OSSL_STORE_CTX *ctx) { int ret = 1; if (ctx->fetched_loader != NULL) ret = ctx->error_flag; #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL) ret = ctx->loader->error(ctx->loader_ctx); #endif return ret; } int OSSL_STORE_eof(OSSL_STORE_CTX *ctx) { int ret = 1; if (ctx->fetched_loader != NULL) ret = ctx->loader->p_eof(ctx->loader_ctx); #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL) ret = ctx->loader->eof(ctx->loader_ctx); #endif return ret != 0; } static int ossl_store_close_it(OSSL_STORE_CTX *ctx) { int ret = 0; if (ctx == NULL) return 1; OSSL_TRACE1(STORE, "Closing %p\n", (void *)ctx->loader_ctx); if (ctx->fetched_loader != NULL) ret = ctx->loader->p_close(ctx->loader_ctx); #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL) ret = ctx->loader->closefn(ctx->loader_ctx); #endif sk_OSSL_STORE_INFO_pop_free(ctx->cached_info, OSSL_STORE_INFO_free); OSSL_STORE_LOADER_free(ctx->fetched_loader); OPENSSL_free(ctx->properties); ossl_pw_clear_passphrase_data(&ctx->pwdata); return ret; } int OSSL_STORE_close(OSSL_STORE_CTX *ctx) { int ret = ossl_store_close_it(ctx); OPENSSL_free(ctx); return ret; } /* * Functions to generate OSSL_STORE_INFOs, one function for each type we * support having in them as well as a generic constructor. * * In all cases, ownership of the object is transferred to the OSSL_STORE_INFO * and will therefore be freed when the OSSL_STORE_INFO is freed. */ OSSL_STORE_INFO *OSSL_STORE_INFO_new(int type, void *data) { OSSL_STORE_INFO *info = OPENSSL_zalloc(sizeof(*info)); if (info == NULL) return NULL; info->type = type; info->_.data = data; return info; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_NAME(char *name) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_NAME, NULL); if (info == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_OSSL_STORE_LIB); return NULL; } info->_.name.name = name; info->_.name.desc = NULL; return info; } int OSSL_STORE_INFO_set0_NAME_description(OSSL_STORE_INFO *info, char *desc) { if (info->type != OSSL_STORE_INFO_NAME) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } info->_.name.desc = desc; return 1; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_PARAMS(EVP_PKEY *params) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_PARAMS, params); if (info == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_OSSL_STORE_LIB); return info; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_PUBKEY(EVP_PKEY *pkey) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_PUBKEY, pkey); if (info == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_OSSL_STORE_LIB); return info; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_PKEY(EVP_PKEY *pkey) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_PKEY, pkey); if (info == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_OSSL_STORE_LIB); return info; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_CERT(X509 *x509) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_CERT, x509); if (info == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_OSSL_STORE_LIB); return info; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_CRL(X509_CRL *crl) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_CRL, crl); if (info == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_OSSL_STORE_LIB); return info; } /* * Functions to try to extract data from an OSSL_STORE_INFO. */ int OSSL_STORE_INFO_get_type(const OSSL_STORE_INFO *info) { return info->type; } void *OSSL_STORE_INFO_get0_data(int type, const OSSL_STORE_INFO *info) { if (info->type == type) return info->_.data; return NULL; } const char *OSSL_STORE_INFO_get0_NAME(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_NAME) return info->_.name.name; return NULL; } char *OSSL_STORE_INFO_get1_NAME(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_NAME) return OPENSSL_strdup(info->_.name.name); ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_NAME); return NULL; } const char *OSSL_STORE_INFO_get0_NAME_description(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_NAME) return info->_.name.desc; return NULL; } char *OSSL_STORE_INFO_get1_NAME_description(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_NAME) return OPENSSL_strdup(info->_.name.desc ? info->_.name.desc : ""); ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_NAME); return NULL; } EVP_PKEY *OSSL_STORE_INFO_get0_PARAMS(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PARAMS) return info->_.params; return NULL; } EVP_PKEY *OSSL_STORE_INFO_get1_PARAMS(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PARAMS) { EVP_PKEY_up_ref(info->_.params); return info->_.params; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_PARAMETERS); return NULL; } EVP_PKEY *OSSL_STORE_INFO_get0_PUBKEY(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PUBKEY) return info->_.pubkey; return NULL; } EVP_PKEY *OSSL_STORE_INFO_get1_PUBKEY(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PUBKEY) { EVP_PKEY_up_ref(info->_.pubkey); return info->_.pubkey; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_PUBLIC_KEY); return NULL; } EVP_PKEY *OSSL_STORE_INFO_get0_PKEY(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PKEY) return info->_.pkey; return NULL; } EVP_PKEY *OSSL_STORE_INFO_get1_PKEY(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PKEY) { EVP_PKEY_up_ref(info->_.pkey); return info->_.pkey; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_PRIVATE_KEY); return NULL; } X509 *OSSL_STORE_INFO_get0_CERT(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_CERT) return info->_.x509; return NULL; } X509 *OSSL_STORE_INFO_get1_CERT(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_CERT) { X509_up_ref(info->_.x509); return info->_.x509; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_CERTIFICATE); return NULL; } X509_CRL *OSSL_STORE_INFO_get0_CRL(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_CRL) return info->_.crl; return NULL; } X509_CRL *OSSL_STORE_INFO_get1_CRL(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_CRL) { X509_CRL_up_ref(info->_.crl); return info->_.crl; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_CRL); return NULL; } /* * Free the OSSL_STORE_INFO */ void OSSL_STORE_INFO_free(OSSL_STORE_INFO *info) { if (info != NULL) { switch (info->type) { case OSSL_STORE_INFO_NAME: OPENSSL_free(info->_.name.name); OPENSSL_free(info->_.name.desc); break; case OSSL_STORE_INFO_PARAMS: EVP_PKEY_free(info->_.params); break; case OSSL_STORE_INFO_PUBKEY: EVP_PKEY_free(info->_.pubkey); break; case OSSL_STORE_INFO_PKEY: EVP_PKEY_free(info->_.pkey); break; case OSSL_STORE_INFO_CERT: X509_free(info->_.x509); break; case OSSL_STORE_INFO_CRL: X509_CRL_free(info->_.crl); break; } OPENSSL_free(info); } } int OSSL_STORE_supports_search(OSSL_STORE_CTX *ctx, int search_type) { int ret = 0; if (ctx->fetched_loader != NULL) { void *provctx = ossl_provider_ctx(OSSL_STORE_LOADER_get0_provider(ctx->fetched_loader)); const OSSL_PARAM *params; const OSSL_PARAM *p_subject = NULL; const OSSL_PARAM *p_issuer = NULL; const OSSL_PARAM *p_serial = NULL; const OSSL_PARAM *p_fingerprint = NULL; const OSSL_PARAM *p_alias = NULL; if (ctx->fetched_loader->p_settable_ctx_params == NULL) return 0; params = ctx->fetched_loader->p_settable_ctx_params(provctx); p_subject = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_SUBJECT); p_issuer = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_ISSUER); p_serial = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_SERIAL); p_fingerprint = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_FINGERPRINT); p_alias = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_ALIAS); switch (search_type) { case OSSL_STORE_SEARCH_BY_NAME: ret = (p_subject != NULL); break; case OSSL_STORE_SEARCH_BY_ISSUER_SERIAL: ret = (p_issuer != NULL && p_serial != NULL); break; case OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT: ret = (p_fingerprint != NULL); break; case OSSL_STORE_SEARCH_BY_ALIAS: ret = (p_alias != NULL); break; } } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL) { OSSL_STORE_SEARCH tmp_search; if (ctx->loader->find == NULL) return 0; tmp_search.search_type = search_type; ret = ctx->loader->find(NULL, &tmp_search); } #endif return ret; } /* Search term constructors */ OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_name(X509_NAME *name) { OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); if (search == NULL) return NULL; search->search_type = OSSL_STORE_SEARCH_BY_NAME; search->name = name; return search; } OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_issuer_serial(X509_NAME *name, const ASN1_INTEGER *serial) { OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); if (search == NULL) return NULL; search->search_type = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL; search->name = name; search->serial = serial; return search; } OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_key_fingerprint(const EVP_MD *digest, const unsigned char *bytes, size_t len) { OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); if (search == NULL) return NULL; if (digest != NULL && len != (size_t)EVP_MD_get_size(digest)) { ERR_raise_data(ERR_LIB_OSSL_STORE, OSSL_STORE_R_FINGERPRINT_SIZE_DOES_NOT_MATCH_DIGEST, "%s size is %d, fingerprint size is %zu", EVP_MD_get0_name(digest), EVP_MD_get_size(digest), len); OPENSSL_free(search); return NULL; } search->search_type = OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT; search->digest = digest; search->string = bytes; search->stringlength = len; return search; } OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_alias(const char *alias) { OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); if (search == NULL) return NULL; search->search_type = OSSL_STORE_SEARCH_BY_ALIAS; search->string = (const unsigned char *)alias; search->stringlength = strlen(alias); return search; } /* Search term destructor */ void OSSL_STORE_SEARCH_free(OSSL_STORE_SEARCH *search) { OPENSSL_free(search); } /* Search term accessors */ int OSSL_STORE_SEARCH_get_type(const OSSL_STORE_SEARCH *criterion) { return criterion->search_type; } X509_NAME *OSSL_STORE_SEARCH_get0_name(const OSSL_STORE_SEARCH *criterion) { return criterion->name; } const ASN1_INTEGER *OSSL_STORE_SEARCH_get0_serial(const OSSL_STORE_SEARCH *criterion) { return criterion->serial; } const unsigned char *OSSL_STORE_SEARCH_get0_bytes(const OSSL_STORE_SEARCH *criterion, size_t *length) { *length = criterion->stringlength; return criterion->string; } const char *OSSL_STORE_SEARCH_get0_string(const OSSL_STORE_SEARCH *criterion) { return (const char *)criterion->string; } const EVP_MD *OSSL_STORE_SEARCH_get0_digest(const OSSL_STORE_SEARCH *criterion) { return criterion->digest; } OSSL_STORE_CTX *OSSL_STORE_attach(BIO *bp, const char *scheme, OSSL_LIB_CTX *libctx, const char *propq, const UI_METHOD *ui_method, void *ui_data, const OSSL_PARAM params[], OSSL_STORE_post_process_info_fn post_process, void *post_process_data) { const OSSL_STORE_LOADER *loader = NULL; OSSL_STORE_LOADER *fetched_loader = NULL; OSSL_STORE_LOADER_CTX *loader_ctx = NULL; OSSL_STORE_CTX *ctx = NULL; if (scheme == NULL) scheme = "file"; OSSL_TRACE1(STORE, "Looking up scheme %s\n", scheme); ERR_set_mark(); #ifndef OPENSSL_NO_DEPRECATED_3_0 if ((loader = ossl_store_get0_loader_int(scheme)) != NULL) loader_ctx = loader->attach(loader, bp, libctx, propq, ui_method, ui_data); #endif if (loader == NULL && (fetched_loader = OSSL_STORE_LOADER_fetch(libctx, scheme, propq)) != NULL) { const OSSL_PROVIDER *provider = OSSL_STORE_LOADER_get0_provider(fetched_loader); void *provctx = OSSL_PROVIDER_get0_provider_ctx(provider); OSSL_CORE_BIO *cbio = ossl_core_bio_new_from_bio(bp); if (cbio == NULL || (loader_ctx = fetched_loader->p_attach(provctx, cbio)) == NULL) { OSSL_STORE_LOADER_free(fetched_loader); fetched_loader = NULL; } else if (!loader_set_params(fetched_loader, loader_ctx, params, propq)) { (void)fetched_loader->p_close(loader_ctx); OSSL_STORE_LOADER_free(fetched_loader); fetched_loader = NULL; } loader = fetched_loader; ossl_core_bio_free(cbio); } if (loader_ctx == NULL) { ERR_clear_last_mark(); return NULL; } if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) { ERR_clear_last_mark(); return NULL; } if (ui_method != NULL && !ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data)) { ERR_clear_last_mark(); OPENSSL_free(ctx); return NULL; } ctx->fetched_loader = fetched_loader; ctx->loader = loader; ctx->loader_ctx = loader_ctx; ctx->post_process = post_process; ctx->post_process_data = post_process_data; /* * ossl_store_get0_loader_int will raise an error if the loader for * the scheme cannot be retrieved. But if a loader was successfully * fetched then we remove this error from the error stack. */ ERR_pop_to_mark(); return ctx; }
./openssl/crypto/cmp/cmp_protect.c
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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 "cmp_local.h" #include "crypto/asn1.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/asn1t.h> #include <openssl/cmp.h> #include <openssl/crmf.h> #include <openssl/err.h> #include <openssl/x509.h> /* * This function is also used by the internal verify_PBMAC() in cmp_vfy.c. * * Calculate protection for |msg| according to |msg->header->protectionAlg| * using the credentials, library context, and property criteria in the ctx. * Unless |msg->header->protectionAlg| is PasswordBasedMAC, * its value is completed according to |ctx->pkey| and |ctx->digest|, * where the latter irrelevant in the case of Edwards curves. * * returns ASN1_BIT_STRING representing the protection on success, else NULL */ ASN1_BIT_STRING *ossl_cmp_calc_protection(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg) { ASN1_BIT_STRING *prot = NULL; OSSL_CMP_PROTECTEDPART prot_part; const ASN1_OBJECT *algorOID = NULL; const void *ppval = NULL; int pptype = 0; if (!ossl_assert(ctx != NULL && msg != NULL)) return NULL; /* construct data to be signed */ prot_part.header = msg->header; prot_part.body = msg->body; if (msg->header->protectionAlg == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_UNKNOWN_ALGORITHM_ID); return NULL; } X509_ALGOR_get0(&algorOID, &pptype, &ppval, msg->header->protectionAlg); if (OBJ_obj2nid(algorOID) == NID_id_PasswordBasedMAC) { int len; size_t prot_part_der_len; unsigned char *prot_part_der = NULL; size_t sig_len; unsigned char *protection = NULL; OSSL_CRMF_PBMPARAMETER *pbm = NULL; ASN1_STRING *pbm_str = NULL; const unsigned char *pbm_str_uc = NULL; if (ctx->secretValue == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PBM_SECRET); return NULL; } if (ppval == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CALCULATING_PROTECTION); return NULL; } len = i2d_OSSL_CMP_PROTECTEDPART(&prot_part, &prot_part_der); if (len < 0 || prot_part_der == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CALCULATING_PROTECTION); goto end; } prot_part_der_len = (size_t)len; pbm_str = (ASN1_STRING *)ppval; pbm_str_uc = pbm_str->data; pbm = d2i_OSSL_CRMF_PBMPARAMETER(NULL, &pbm_str_uc, pbm_str->length); if (pbm == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_ALGORITHM_OID); goto end; } if (!OSSL_CRMF_pbm_new(ctx->libctx, ctx->propq, pbm, prot_part_der, prot_part_der_len, ctx->secretValue->data, ctx->secretValue->length, &protection, &sig_len)) goto end; if ((prot = ASN1_BIT_STRING_new()) == NULL) goto end; /* OpenSSL by default encodes all bit strings as ASN.1 NamedBitList */ ossl_asn1_string_set_bits_left(prot, 0); if (!ASN1_BIT_STRING_set(prot, protection, sig_len)) { ASN1_BIT_STRING_free(prot); prot = NULL; } end: OSSL_CRMF_PBMPARAMETER_free(pbm); OPENSSL_free(protection); OPENSSL_free(prot_part_der); return prot; } else { const EVP_MD *md = ctx->digest; char name[80] = ""; if (ctx->pkey == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_INPUT_FOR_CREATING_PROTECTION); return NULL; } if (EVP_PKEY_get_default_digest_name(ctx->pkey, name, sizeof(name)) > 0 && strcmp(name, "UNDEF") == 0) /* at least for Ed25519, Ed448 */ md = NULL; if ((prot = ASN1_BIT_STRING_new()) == NULL) return NULL; if (ASN1_item_sign_ex(ASN1_ITEM_rptr(OSSL_CMP_PROTECTEDPART), msg->header->protectionAlg, /* sets X509_ALGOR */ NULL, prot, &prot_part, NULL, ctx->pkey, md, ctx->libctx, ctx->propq)) return prot; ASN1_BIT_STRING_free(prot); return NULL; } } /* ctx is not const just because ctx->chain may get adapted */ int ossl_cmp_msg_add_extraCerts(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg) { if (!ossl_assert(ctx != NULL && msg != NULL)) return 0; /* Add first ctx->cert and its chain if using signature-based protection */ if (!ctx->unprotectedSend && ctx->secretValue == NULL && ctx->cert != NULL && ctx->pkey != NULL) { int prepend = X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP | X509_ADD_FLAG_PREPEND | X509_ADD_FLAG_NO_SS; /* if not yet done try to build chain using available untrusted certs */ if (ctx->chain == NULL) { ossl_cmp_debug(ctx, "trying to build chain for own CMP signer cert"); ctx->chain = X509_build_chain(ctx->cert, ctx->untrusted, NULL, 0, ctx->libctx, ctx->propq); if (ctx->chain != NULL) { ossl_cmp_debug(ctx, "success building chain for own CMP signer cert"); } else { /* dump errors to avoid confusion when printing further ones */ OSSL_CMP_CTX_print_errors(ctx); ossl_cmp_warn(ctx, "could not build chain for own CMP signer cert"); } } if (ctx->chain != NULL) { if (!ossl_x509_add_certs_new(&msg->extraCerts, ctx->chain, prepend)) return 0; } else { /* make sure that at least our own signer cert is included first */ if (!ossl_x509_add_cert_new(&msg->extraCerts, ctx->cert, prepend)) return 0; ossl_cmp_debug(ctx, "fallback: adding just own CMP signer cert"); } } /* add any additional certificates from ctx->extraCertsOut */ if (!ossl_x509_add_certs_new(&msg->extraCerts, ctx->extraCertsOut, X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP)) return 0; /* in case extraCerts are empty list avoid empty ASN.1 sequence */ if (sk_X509_num(msg->extraCerts) == 0) { sk_X509_free(msg->extraCerts); msg->extraCerts = NULL; } return 1; } /* * Create an X509_ALGOR structure for PasswordBasedMAC protection based on * the pbm settings in the context */ static X509_ALGOR *pbmac_algor(const OSSL_CMP_CTX *ctx) { OSSL_CRMF_PBMPARAMETER *pbm = NULL; unsigned char *pbm_der = NULL; int pbm_der_len; ASN1_STRING *pbm_str = NULL; X509_ALGOR *alg = NULL; if (!ossl_assert(ctx != NULL)) return NULL; pbm = OSSL_CRMF_pbmp_new(ctx->libctx, ctx->pbm_slen, EVP_MD_get_type(ctx->pbm_owf), ctx->pbm_itercnt, ctx->pbm_mac); pbm_str = ASN1_STRING_new(); if (pbm == NULL || pbm_str == NULL) goto err; if ((pbm_der_len = i2d_OSSL_CRMF_PBMPARAMETER(pbm, &pbm_der)) < 0) goto err; if (!ASN1_STRING_set(pbm_str, pbm_der, pbm_der_len)) goto err; alg = ossl_X509_ALGOR_from_nid(NID_id_PasswordBasedMAC, V_ASN1_SEQUENCE, pbm_str); err: if (alg == NULL) ASN1_STRING_free(pbm_str); OPENSSL_free(pbm_der); OSSL_CRMF_PBMPARAMETER_free(pbm); return alg; } static int set_senderKID(const OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg, const ASN1_OCTET_STRING *id) { if (id == NULL) id = ctx->referenceValue; /* standard for PBM, fallback for sig-based */ return id == NULL || ossl_cmp_hdr_set1_senderKID(msg->header, id); } /* ctx is not const just because ctx->chain may get adapted */ int ossl_cmp_msg_protect(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg) { if (!ossl_assert(ctx != NULL && msg != NULL)) return 0; /* * For the case of re-protection remove pre-existing protection. * Does not remove any pre-existing extraCerts. */ X509_ALGOR_free(msg->header->protectionAlg); msg->header->protectionAlg = NULL; ASN1_BIT_STRING_free(msg->protection); msg->protection = NULL; if (ctx->unprotectedSend) { if (!set_senderKID(ctx, msg, NULL)) goto err; } else if (ctx->secretValue != NULL) { /* use PasswordBasedMac according to 5.1.3.1 if secretValue is given */ if ((msg->header->protectionAlg = pbmac_algor(ctx)) == NULL) goto err; if (!set_senderKID(ctx, msg, NULL)) goto err; /* * will add any additional certificates from ctx->extraCertsOut * while not needed to validate the protection certificate, * the option to do this might be handy for certain use cases */ } else if (ctx->cert != NULL && ctx->pkey != NULL) { /* use MSG_SIG_ALG according to 5.1.3.3 if client cert and key given */ /* make sure that key and certificate match */ if (!X509_check_private_key(ctx->cert, ctx->pkey)) { ERR_raise(ERR_LIB_CMP, CMP_R_CERT_AND_KEY_DO_NOT_MATCH); goto err; } if ((msg->header->protectionAlg = X509_ALGOR_new()) == NULL) goto err; /* set senderKID to keyIdentifier of the cert according to 5.1.1 */ if (!set_senderKID(ctx, msg, X509_get0_subject_key_id(ctx->cert))) goto err; /* * will add ctx->cert followed, if possible, by its chain built * from ctx->untrusted, and then ctx->extraCertsOut */ } else { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_INPUT_FOR_CREATING_PROTECTION); goto err; } if (!ctx->unprotectedSend /* protect according to msg->header->protectionAlg partly set above */ && ((msg->protection = ossl_cmp_calc_protection(ctx, msg)) == NULL)) goto err; /* * For signature-based protection add ctx->cert followed by its chain. * Finally add any additional certificates from ctx->extraCertsOut; * even if not needed to validate the protection * the option to do this might be handy for certain use cases. */ if (!ossl_cmp_msg_add_extraCerts(ctx, msg)) goto err; /* * As required by RFC 4210 section 5.1.1., if the sender name is not known * to the client it set to NULL-DN. In this case for identification at least * the senderKID must be set, where we took the referenceValue as fallback. */ if (!(ossl_cmp_general_name_is_NULL_DN(msg->header->sender) && msg->header->senderKID == NULL)) return 1; ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_SENDER_IDENTIFICATION); err: ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROTECTING_MESSAGE); return 0; }
./openssl/crypto/cmp/cmp_status.c
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* CMP functions for PKIStatusInfo handling and PKIMessage decomposition */ #include <string.h> #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <time.h> #include <openssl/cmp.h> #include <openssl/crmf.h> #include <openssl/err.h> /* needed in case config no-deprecated */ #include <openssl/engine.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/asn1err.h> /* for ASN1_R_TOO_SMALL and ASN1_R_TOO_LARGE */ /* CMP functions related to PKIStatus */ int ossl_cmp_pkisi_get_status(const OSSL_CMP_PKISI *si) { int res ; if (!ossl_assert(si != NULL && si->status != NULL)) return -1; res = ossl_cmp_asn1_get_int(si->status); return res == -2 ? -1 : res; } const char *ossl_cmp_PKIStatus_to_string(int status) { switch (status) { case OSSL_CMP_PKISTATUS_accepted: return "PKIStatus: accepted"; case OSSL_CMP_PKISTATUS_grantedWithMods: return "PKIStatus: granted with modifications"; case OSSL_CMP_PKISTATUS_rejection: return "PKIStatus: rejection"; case OSSL_CMP_PKISTATUS_waiting: return "PKIStatus: waiting"; case OSSL_CMP_PKISTATUS_revocationWarning: return "PKIStatus: revocation warning - a revocation of the cert is imminent"; case OSSL_CMP_PKISTATUS_revocationNotification: return "PKIStatus: revocation notification - a revocation of the cert has occurred"; case OSSL_CMP_PKISTATUS_keyUpdateWarning: return "PKIStatus: key update warning - update already done for the cert"; default: ERR_raise_data(ERR_LIB_CMP, CMP_R_ERROR_PARSING_PKISTATUS, "PKIStatus: invalid=%d", status); return NULL; } } OSSL_CMP_PKIFREETEXT *ossl_cmp_pkisi_get0_statusString(const OSSL_CMP_PKISI *si) { if (!ossl_assert(si != NULL)) return NULL; return si->statusString; } int ossl_cmp_pkisi_get_pkifailureinfo(const OSSL_CMP_PKISI *si) { int i; int res = 0; if (!ossl_assert(si != NULL)) return -1; if (si->failInfo != NULL) for (i = 0; i <= OSSL_CMP_PKIFAILUREINFO_MAX; i++) if (ASN1_BIT_STRING_get_bit(si->failInfo, i)) res |= 1 << i; return res; } /*- * convert PKIFailureInfo number to human-readable string * returns pointer to static string, or NULL on error */ static const char *CMP_PKIFAILUREINFO_to_string(int number) { switch (number) { case OSSL_CMP_PKIFAILUREINFO_badAlg: return "badAlg"; case OSSL_CMP_PKIFAILUREINFO_badMessageCheck: return "badMessageCheck"; case OSSL_CMP_PKIFAILUREINFO_badRequest: return "badRequest"; case OSSL_CMP_PKIFAILUREINFO_badTime: return "badTime"; case OSSL_CMP_PKIFAILUREINFO_badCertId: return "badCertId"; case OSSL_CMP_PKIFAILUREINFO_badDataFormat: return "badDataFormat"; case OSSL_CMP_PKIFAILUREINFO_wrongAuthority: return "wrongAuthority"; case OSSL_CMP_PKIFAILUREINFO_incorrectData: return "incorrectData"; case OSSL_CMP_PKIFAILUREINFO_missingTimeStamp: return "missingTimeStamp"; case OSSL_CMP_PKIFAILUREINFO_badPOP: return "badPOP"; case OSSL_CMP_PKIFAILUREINFO_certRevoked: return "certRevoked"; case OSSL_CMP_PKIFAILUREINFO_certConfirmed: return "certConfirmed"; case OSSL_CMP_PKIFAILUREINFO_wrongIntegrity: return "wrongIntegrity"; case OSSL_CMP_PKIFAILUREINFO_badRecipientNonce: return "badRecipientNonce"; case OSSL_CMP_PKIFAILUREINFO_timeNotAvailable: return "timeNotAvailable"; case OSSL_CMP_PKIFAILUREINFO_unacceptedPolicy: return "unacceptedPolicy"; case OSSL_CMP_PKIFAILUREINFO_unacceptedExtension: return "unacceptedExtension"; case OSSL_CMP_PKIFAILUREINFO_addInfoNotAvailable: return "addInfoNotAvailable"; case OSSL_CMP_PKIFAILUREINFO_badSenderNonce: return "badSenderNonce"; case OSSL_CMP_PKIFAILUREINFO_badCertTemplate: return "badCertTemplate"; case OSSL_CMP_PKIFAILUREINFO_signerNotTrusted: return "signerNotTrusted"; case OSSL_CMP_PKIFAILUREINFO_transactionIdInUse: return "transactionIdInUse"; case OSSL_CMP_PKIFAILUREINFO_unsupportedVersion: return "unsupportedVersion"; case OSSL_CMP_PKIFAILUREINFO_notAuthorized: return "notAuthorized"; case OSSL_CMP_PKIFAILUREINFO_systemUnavail: return "systemUnavail"; case OSSL_CMP_PKIFAILUREINFO_systemFailure: return "systemFailure"; case OSSL_CMP_PKIFAILUREINFO_duplicateCertReq: return "duplicateCertReq"; default: return NULL; /* illegal failure number */ } } int ossl_cmp_pkisi_check_pkifailureinfo(const OSSL_CMP_PKISI *si, int bit_index) { if (!ossl_assert(si != NULL && si->failInfo != NULL)) return -1; if (bit_index < 0 || bit_index > OSSL_CMP_PKIFAILUREINFO_MAX) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return -1; } return ASN1_BIT_STRING_get_bit(si->failInfo, bit_index); } /*- * place human-readable error string created from PKIStatusInfo in given buffer * returns pointer to the same buffer containing the string, or NULL on error */ static char *snprint_PKIStatusInfo_parts(int status, int fail_info, const OSSL_CMP_PKIFREETEXT *status_strings, char *buf, size_t bufsize) { int failure; const char *status_string, *failure_string; ASN1_UTF8STRING *text; int i; int printed_chars; int failinfo_found = 0; int n_status_strings; char *write_ptr = buf; if (buf == NULL || status < 0 || (status_string = ossl_cmp_PKIStatus_to_string(status)) == NULL) return NULL; #define ADVANCE_BUFFER \ if (printed_chars < 0 || (size_t)printed_chars >= bufsize) \ return NULL; \ write_ptr += printed_chars; \ bufsize -= printed_chars; printed_chars = BIO_snprintf(write_ptr, bufsize, "%s", status_string); ADVANCE_BUFFER; /* * failInfo is optional and may be empty; * if present, print failInfo before statusString because it is more concise */ if (fail_info != -1 && fail_info != 0) { printed_chars = BIO_snprintf(write_ptr, bufsize, "; PKIFailureInfo: "); ADVANCE_BUFFER; for (failure = 0; failure <= OSSL_CMP_PKIFAILUREINFO_MAX; failure++) { if ((fail_info & (1 << failure)) != 0) { failure_string = CMP_PKIFAILUREINFO_to_string(failure); if (failure_string != NULL) { printed_chars = BIO_snprintf(write_ptr, bufsize, "%s%s", failinfo_found ? ", " : "", failure_string); ADVANCE_BUFFER; failinfo_found = 1; } } } } if (!failinfo_found && status != OSSL_CMP_PKISTATUS_accepted && status != OSSL_CMP_PKISTATUS_grantedWithMods) { printed_chars = BIO_snprintf(write_ptr, bufsize, "; <no failure info>"); ADVANCE_BUFFER; } /* statusString sequence is optional and may be empty */ n_status_strings = sk_ASN1_UTF8STRING_num(status_strings); if (n_status_strings > 0) { printed_chars = BIO_snprintf(write_ptr, bufsize, "; StatusString%s: ", n_status_strings > 1 ? "s" : ""); ADVANCE_BUFFER; for (i = 0; i < n_status_strings; i++) { text = sk_ASN1_UTF8STRING_value(status_strings, i); printed_chars = BIO_snprintf(write_ptr, bufsize, "\"%.*s\"%s", ASN1_STRING_length(text), ASN1_STRING_get0_data(text), i < n_status_strings - 1 ? ", " : ""); ADVANCE_BUFFER; } } #undef ADVANCE_BUFFER return buf; } char *OSSL_CMP_snprint_PKIStatusInfo(const OSSL_CMP_PKISI *statusInfo, char *buf, size_t bufsize) { int failure_info; if (statusInfo == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } failure_info = ossl_cmp_pkisi_get_pkifailureinfo(statusInfo); return snprint_PKIStatusInfo_parts(ASN1_INTEGER_get(statusInfo->status), failure_info, statusInfo->statusString, buf, bufsize); } char *OSSL_CMP_CTX_snprint_PKIStatus(const OSSL_CMP_CTX *ctx, char *buf, size_t bufsize) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return snprint_PKIStatusInfo_parts(OSSL_CMP_CTX_get_status(ctx), OSSL_CMP_CTX_get_failInfoCode(ctx), OSSL_CMP_CTX_get0_statusString(ctx), buf, bufsize); } /*- * Creates a new PKIStatusInfo structure and fills it in * returns a pointer to the structure on success, NULL on error * note: strongly overlaps with TS_RESP_CTX_set_status_info() * and TS_RESP_CTX_add_failure_info() in ../ts/ts_rsp_sign.c */ OSSL_CMP_PKISI *OSSL_CMP_STATUSINFO_new(int status, int fail_info, const char *text) { OSSL_CMP_PKISI *si = OSSL_CMP_PKISI_new(); ASN1_UTF8STRING *utf8_text = NULL; int failure; if (si == NULL) goto err; if (!ASN1_INTEGER_set(si->status, status)) goto err; if (text != NULL) { if ((utf8_text = ASN1_UTF8STRING_new()) == NULL || !ASN1_STRING_set(utf8_text, text, -1)) goto err; if ((si->statusString = sk_ASN1_UTF8STRING_new_null()) == NULL) goto err; if (!sk_ASN1_UTF8STRING_push(si->statusString, utf8_text)) goto err; /* Ownership is lost. */ utf8_text = NULL; } for (failure = 0; failure <= OSSL_CMP_PKIFAILUREINFO_MAX; failure++) { if ((fail_info & (1 << failure)) != 0) { if (si->failInfo == NULL && (si->failInfo = ASN1_BIT_STRING_new()) == NULL) goto err; if (!ASN1_BIT_STRING_set_bit(si->failInfo, failure, 1)) goto err; } } return si; err: OSSL_CMP_PKISI_free(si); ASN1_UTF8STRING_free(utf8_text); return NULL; }
./openssl/crypto/cmp/cmp_msg.c
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* CMP functions for PKIMessage construction */ #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/asn1t.h> #include <openssl/cmp.h> #include <openssl/crmf.h> #include <openssl/err.h> #include <openssl/x509.h> OSSL_CMP_MSG *OSSL_CMP_MSG_new(OSSL_LIB_CTX *libctx, const char *propq) { OSSL_CMP_MSG *msg = NULL; msg = (OSSL_CMP_MSG *)ASN1_item_new_ex(ASN1_ITEM_rptr(OSSL_CMP_MSG), libctx, propq); if (!ossl_cmp_msg_set0_libctx(msg, libctx, propq)) { OSSL_CMP_MSG_free(msg); msg = NULL; } return msg; } void OSSL_CMP_MSG_free(OSSL_CMP_MSG *msg) { ASN1_item_free((ASN1_VALUE *)msg, ASN1_ITEM_rptr(OSSL_CMP_MSG)); } /* * This should only be used if the X509 object was embedded inside another * asn1 object and it needs a libctx to operate. * Use OSSL_CMP_MSG_new() instead if possible. */ int ossl_cmp_msg_set0_libctx(OSSL_CMP_MSG *msg, OSSL_LIB_CTX *libctx, const char *propq) { if (msg != NULL) { msg->libctx = libctx; OPENSSL_free(msg->propq); msg->propq = NULL; if (propq != NULL) { msg->propq = OPENSSL_strdup(propq); if (msg->propq == NULL) return 0; } } return 1; } OSSL_CMP_PKIHEADER *OSSL_CMP_MSG_get0_header(const OSSL_CMP_MSG *msg) { if (msg == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return msg->header; } const char *ossl_cmp_bodytype_to_string(int type) { static const char *type_names[] = { "IR", "IP", "CR", "CP", "P10CR", "POPDECC", "POPDECR", "KUR", "KUP", "KRR", "KRP", "RR", "RP", "CCR", "CCP", "CKUANN", "CANN", "RANN", "CRLANN", "PKICONF", "NESTED", "GENM", "GENP", "ERROR", "CERTCONF", "POLLREQ", "POLLREP", }; if (type < 0 || type > OSSL_CMP_PKIBODY_TYPE_MAX) return "illegal body type"; return type_names[type]; } int ossl_cmp_msg_set_bodytype(OSSL_CMP_MSG *msg, int type) { if (!ossl_assert(msg != NULL && msg->body != NULL)) return 0; msg->body->type = type; return 1; } int OSSL_CMP_MSG_get_bodytype(const OSSL_CMP_MSG *msg) { if (!ossl_assert(msg != NULL && msg->body != NULL)) return -1; return msg->body->type; } /* Add an extension to the referenced extension stack, which may be NULL */ static int add1_extension(X509_EXTENSIONS **pexts, int nid, int crit, void *ex) { X509_EXTENSION *ext; int res; if (!ossl_assert(pexts != NULL)) /* pointer to var must not be NULL */ return 0; if ((ext = X509V3_EXT_i2d(nid, crit, ex)) == NULL) return 0; res = X509v3_add_ext(pexts, ext, 0) != NULL; X509_EXTENSION_free(ext); return res; } /* Add extension list to the referenced extension stack, which may be NULL */ static int add_extensions(STACK_OF(X509_EXTENSION) **target, const STACK_OF(X509_EXTENSION) *exts) { int i; if (target == NULL) return 0; for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) { X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i); ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext); int idx = X509v3_get_ext_by_OBJ(*target, obj, -1); /* Does extension exist in target? */ if (idx != -1) { /* Delete all extensions of same type */ do { X509_EXTENSION_free(sk_X509_EXTENSION_delete(*target, idx)); idx = X509v3_get_ext_by_OBJ(*target, obj, -1); } while (idx != -1); } if (!X509v3_add_ext(target, ext, -1)) return 0; } return 1; } /* Add a CRL revocation reason code to extension stack, which may be NULL */ static int add_crl_reason_extension(X509_EXTENSIONS **pexts, int reason_code) { ASN1_ENUMERATED *val = ASN1_ENUMERATED_new(); int res = 0; if (val != NULL && ASN1_ENUMERATED_set(val, reason_code)) res = add1_extension(pexts, NID_crl_reason, 0 /* non-critical */, val); ASN1_ENUMERATED_free(val); return res; } OSSL_CMP_MSG *ossl_cmp_msg_create(OSSL_CMP_CTX *ctx, int bodytype) { OSSL_CMP_MSG *msg = NULL; if (!ossl_assert(ctx != NULL)) return NULL; if ((msg = OSSL_CMP_MSG_new(ctx->libctx, ctx->propq)) == NULL) return NULL; if (!ossl_cmp_hdr_init(ctx, msg->header) || !ossl_cmp_msg_set_bodytype(msg, bodytype)) goto err; if (ctx->geninfo_ITAVs != NULL && !ossl_cmp_hdr_generalInfo_push1_items(msg->header, ctx->geninfo_ITAVs)) goto err; switch (bodytype) { case OSSL_CMP_PKIBODY_IR: case OSSL_CMP_PKIBODY_CR: case OSSL_CMP_PKIBODY_KUR: if ((msg->body->value.ir = OSSL_CRMF_MSGS_new()) == NULL) goto err; return msg; case OSSL_CMP_PKIBODY_P10CR: if (ctx->p10CSR == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_P10CSR); goto err; } if ((msg->body->value.p10cr = X509_REQ_dup(ctx->p10CSR)) == NULL) goto err; return msg; case OSSL_CMP_PKIBODY_IP: case OSSL_CMP_PKIBODY_CP: case OSSL_CMP_PKIBODY_KUP: if ((msg->body->value.ip = OSSL_CMP_CERTREPMESSAGE_new()) == NULL) goto err; return msg; case OSSL_CMP_PKIBODY_RR: if ((msg->body->value.rr = sk_OSSL_CMP_REVDETAILS_new_null()) == NULL) goto err; return msg; case OSSL_CMP_PKIBODY_RP: if ((msg->body->value.rp = OSSL_CMP_REVREPCONTENT_new()) == NULL) goto err; return msg; case OSSL_CMP_PKIBODY_CERTCONF: if ((msg->body->value.certConf = sk_OSSL_CMP_CERTSTATUS_new_null()) == NULL) goto err; return msg; case OSSL_CMP_PKIBODY_PKICONF: if ((msg->body->value.pkiconf = ASN1_TYPE_new()) == NULL) goto err; ASN1_TYPE_set(msg->body->value.pkiconf, V_ASN1_NULL, NULL); return msg; case OSSL_CMP_PKIBODY_POLLREQ: if ((msg->body->value.pollReq = sk_OSSL_CMP_POLLREQ_new_null()) == NULL) goto err; return msg; case OSSL_CMP_PKIBODY_POLLREP: if ((msg->body->value.pollRep = sk_OSSL_CMP_POLLREP_new_null()) == NULL) goto err; return msg; case OSSL_CMP_PKIBODY_GENM: case OSSL_CMP_PKIBODY_GENP: if ((msg->body->value.genm = sk_OSSL_CMP_ITAV_new_null()) == NULL) goto err; return msg; case OSSL_CMP_PKIBODY_ERROR: if ((msg->body->value.error = OSSL_CMP_ERRORMSGCONTENT_new()) == NULL) goto err; return msg; default: ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); goto err; } err: OSSL_CMP_MSG_free(msg); return NULL; } #define HAS_SAN(ctx) \ (sk_GENERAL_NAME_num((ctx)->subjectAltNames) > 0 \ || OSSL_CMP_CTX_reqExtensions_have_SAN(ctx) == 1) static const X509_NAME *determine_subj(OSSL_CMP_CTX *ctx, int for_KUR, const X509_NAME *ref_subj) { if (ctx->subjectName != NULL) return IS_NULL_DN(ctx->subjectName) ? NULL : ctx->subjectName; if (ctx->p10CSR != NULL) /* first default is from any given CSR */ return X509_REQ_get_subject_name(ctx->p10CSR); if (for_KUR || !HAS_SAN(ctx)) /* * For KUR, copy subject from any reference cert as fallback. * For IR or CR, do the same only if there is no subjectAltName. */ return ref_subj; return NULL; } OSSL_CRMF_MSG *OSSL_CMP_CTX_setup_CRM(OSSL_CMP_CTX *ctx, int for_KUR, int rid) { OSSL_CRMF_MSG *crm = NULL; X509 *refcert = ctx->oldCert != NULL ? ctx->oldCert : ctx->cert; /* refcert defaults to current client cert */ EVP_PKEY *rkey = ossl_cmp_ctx_get0_newPubkey(ctx); STACK_OF(GENERAL_NAME) *default_sans = NULL; const X509_NAME *ref_subj = refcert != NULL ? X509_get_subject_name(refcert) : NULL; const X509_NAME *subject = determine_subj(ctx, for_KUR, ref_subj); const X509_NAME *issuer = ctx->issuer != NULL || refcert == NULL ? (IS_NULL_DN(ctx->issuer) ? NULL : ctx->issuer) : X509_get_issuer_name(refcert); int crit = ctx->setSubjectAltNameCritical || subject == NULL; /* RFC5280: subjectAltName MUST be critical if subject is null */ X509_EXTENSIONS *exts = NULL; if (rkey == NULL) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PUBLIC_KEY); return NULL; #endif } if (for_KUR && refcert == NULL && ctx->p10CSR == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_REFERENCE_CERT); return NULL; } if ((crm = OSSL_CRMF_MSG_new()) == NULL) return NULL; if (!OSSL_CRMF_MSG_set_certReqId(crm, rid) /* * fill certTemplate, corresponding to CertificationRequestInfo * of PKCS#10. The rkey param cannot be NULL so far - * it could be NULL if centralized key creation was supported */ || !OSSL_CRMF_CERTTEMPLATE_fill(OSSL_CRMF_MSG_get0_tmpl(crm), rkey, subject, issuer, NULL /* serial */)) goto err; if (ctx->days != 0) { time_t now = time(NULL); ASN1_TIME *notBefore = ASN1_TIME_adj(NULL, now, 0, 0); ASN1_TIME *notAfter = ASN1_TIME_adj(NULL, now, ctx->days, 0); if (notBefore == NULL || notAfter == NULL || !OSSL_CRMF_MSG_set0_validity(crm, notBefore, notAfter)) { ASN1_TIME_free(notBefore); ASN1_TIME_free(notAfter); goto err; } } /* extensions */ if (ctx->p10CSR != NULL && (exts = X509_REQ_get_extensions(ctx->p10CSR)) == NULL) goto err; if (!ctx->SubjectAltName_nodefault && !HAS_SAN(ctx) && refcert != NULL && (default_sans = X509V3_get_d2i(X509_get0_extensions(refcert), NID_subject_alt_name, NULL, NULL)) != NULL && !add1_extension(&exts, NID_subject_alt_name, crit, default_sans)) goto err; if (ctx->reqExtensions != NULL /* augment/override existing ones */ && !add_extensions(&exts, ctx->reqExtensions)) goto err; if (sk_GENERAL_NAME_num(ctx->subjectAltNames) > 0 && !add1_extension(&exts, NID_subject_alt_name, crit, ctx->subjectAltNames)) goto err; if (ctx->policies != NULL && !add1_extension(&exts, NID_certificate_policies, ctx->setPoliciesCritical, ctx->policies)) goto err; if (!OSSL_CRMF_MSG_set0_extensions(crm, exts)) goto err; exts = NULL; /* end fill certTemplate, now set any controls */ /* for KUR, set OldCertId according to D.6 */ if (for_KUR && refcert != NULL) { OSSL_CRMF_CERTID *cid = OSSL_CRMF_CERTID_gen(X509_get_issuer_name(refcert), X509_get0_serialNumber(refcert)); int ret; if (cid == NULL) goto err; ret = OSSL_CRMF_MSG_set1_regCtrl_oldCertID(crm, cid); OSSL_CRMF_CERTID_free(cid); if (ret == 0) goto err; } goto end; err: OSSL_CRMF_MSG_free(crm); crm = NULL; end: sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); sk_GENERAL_NAME_pop_free(default_sans, GENERAL_NAME_free); return crm; } OSSL_CMP_MSG *ossl_cmp_certreq_new(OSSL_CMP_CTX *ctx, int type, const OSSL_CRMF_MSG *crm) { OSSL_CMP_MSG *msg; OSSL_CRMF_MSG *local_crm = NULL; if (!ossl_assert(ctx != NULL)) return NULL; if (type != OSSL_CMP_PKIBODY_IR && type != OSSL_CMP_PKIBODY_CR && type != OSSL_CMP_PKIBODY_KUR && type != OSSL_CMP_PKIBODY_P10CR) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return NULL; } if (type == OSSL_CMP_PKIBODY_P10CR && crm != NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return NULL; } if ((msg = ossl_cmp_msg_create(ctx, type)) == NULL) goto err; /* header */ if (ctx->implicitConfirm && !ossl_cmp_hdr_set_implicitConfirm(msg->header)) goto err; /* body */ /* For P10CR the content has already been set in OSSL_CMP_MSG_create */ if (type != OSSL_CMP_PKIBODY_P10CR) { EVP_PKEY *privkey = OSSL_CMP_CTX_get0_newPkey(ctx, 1); /* privkey is ctx->newPkey (if private, else NULL) or ctx->pkey */ if (ctx->popoMethod >= OSSL_CRMF_POPO_SIGNATURE && privkey == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PRIVATE_KEY_FOR_POPO); goto err; } if (crm == NULL) { local_crm = OSSL_CMP_CTX_setup_CRM(ctx, type == OSSL_CMP_PKIBODY_KUR, OSSL_CMP_CERTREQID); if (local_crm == NULL || !OSSL_CRMF_MSG_create_popo(ctx->popoMethod, local_crm, privkey, ctx->digest, ctx->libctx, ctx->propq)) goto err; } else { if ((local_crm = OSSL_CRMF_MSG_dup(crm)) == NULL) goto err; } /* value.ir is same for cr and kur */ if (!sk_OSSL_CRMF_MSG_push(msg->body->value.ir, local_crm)) goto err; local_crm = NULL; } if (!ossl_cmp_msg_protect(ctx, msg)) goto err; return msg; err: ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_CERTREQ); OSSL_CRMF_MSG_free(local_crm); OSSL_CMP_MSG_free(msg); return NULL; } OSSL_CMP_MSG *ossl_cmp_certrep_new(OSSL_CMP_CTX *ctx, int bodytype, int certReqId, const OSSL_CMP_PKISI *si, X509 *cert, const X509 *encryption_recip, STACK_OF(X509) *chain, STACK_OF(X509) *caPubs, int unprotectedErrors) { OSSL_CMP_MSG *msg = NULL; OSSL_CMP_CERTREPMESSAGE *repMsg = NULL; OSSL_CMP_CERTRESPONSE *resp = NULL; int status = OSSL_CMP_PKISTATUS_unspecified; if (!ossl_assert(ctx != NULL && si != NULL)) return NULL; if ((msg = ossl_cmp_msg_create(ctx, bodytype)) == NULL) goto err; repMsg = msg->body->value.ip; /* value.ip is same for cp and kup */ /* header */ if (ctx->implicitConfirm && !ossl_cmp_hdr_set_implicitConfirm(msg->header)) goto err; /* body */ if ((resp = OSSL_CMP_CERTRESPONSE_new()) == NULL) goto err; OSSL_CMP_PKISI_free(resp->status); if ((resp->status = OSSL_CMP_PKISI_dup(si)) == NULL || !ASN1_INTEGER_set(resp->certReqId, certReqId)) goto err; status = ossl_cmp_pkisi_get_status(resp->status); if (status != OSSL_CMP_PKISTATUS_rejection && status != OSSL_CMP_PKISTATUS_waiting && cert != NULL) { if (encryption_recip != NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_UNSUPPORTED); goto err; } if ((resp->certifiedKeyPair = OSSL_CMP_CERTIFIEDKEYPAIR_new()) == NULL) goto err; resp->certifiedKeyPair->certOrEncCert->type = OSSL_CMP_CERTORENCCERT_CERTIFICATE; if (!X509_up_ref(cert)) goto err; resp->certifiedKeyPair->certOrEncCert->value.certificate = cert; } if (!sk_OSSL_CMP_CERTRESPONSE_push(repMsg->response, resp)) goto err; resp = NULL; if (bodytype == OSSL_CMP_PKIBODY_IP && caPubs != NULL && (repMsg->caPubs = X509_chain_up_ref(caPubs)) == NULL) goto err; if (sk_X509_num(chain) > 0 && !ossl_x509_add_certs_new(&msg->extraCerts, chain, X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP)) goto err; if (!unprotectedErrors || ossl_cmp_pkisi_get_status(si) != OSSL_CMP_PKISTATUS_rejection) if (!ossl_cmp_msg_protect(ctx, msg)) goto err; return msg; err: ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_CERTREP); OSSL_CMP_CERTRESPONSE_free(resp); OSSL_CMP_MSG_free(msg); return NULL; } OSSL_CMP_MSG *ossl_cmp_rr_new(OSSL_CMP_CTX *ctx) { OSSL_CMP_MSG *msg = NULL; const X509_NAME *issuer = NULL; const X509_NAME *subject = NULL; const ASN1_INTEGER *serialNumber = NULL; EVP_PKEY *pubkey = NULL; OSSL_CMP_REVDETAILS *rd; int ret; if (!ossl_assert(ctx != NULL && (ctx->oldCert != NULL || ctx->p10CSR != NULL || (ctx->serialNumber != NULL && ctx->issuer != NULL)))) return NULL; if ((rd = OSSL_CMP_REVDETAILS_new()) == NULL) goto err; if (ctx->serialNumber != NULL && ctx->issuer != NULL) { issuer = ctx->issuer; serialNumber = ctx->serialNumber; } else if (ctx->oldCert != NULL) { issuer = X509_get_issuer_name(ctx->oldCert); serialNumber = X509_get0_serialNumber(ctx->oldCert); } else if (ctx->p10CSR != NULL) { pubkey = X509_REQ_get0_pubkey(ctx->p10CSR); subject = X509_REQ_get_subject_name(ctx->p10CSR); } else { goto err; } /* Fill the template from the contents of the certificate to be revoked */ ret = OSSL_CRMF_CERTTEMPLATE_fill(rd->certDetails, pubkey, subject, issuer, serialNumber); if (!ret) goto err; /* revocation reason code is optional */ if (ctx->revocationReason != CRL_REASON_NONE && !add_crl_reason_extension(&rd->crlEntryDetails, ctx->revocationReason)) goto err; if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_RR)) == NULL) goto err; if (!sk_OSSL_CMP_REVDETAILS_push(msg->body->value.rr, rd)) goto err; rd = NULL; /* Revocation Passphrase according to section 5.3.19.9 could be set here */ if (!ossl_cmp_msg_protect(ctx, msg)) goto err; return msg; err: ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_RR); OSSL_CMP_MSG_free(msg); OSSL_CMP_REVDETAILS_free(rd); return NULL; } OSSL_CMP_MSG *ossl_cmp_rp_new(OSSL_CMP_CTX *ctx, const OSSL_CMP_PKISI *si, const OSSL_CRMF_CERTID *cid, int unprotectedErrors) { OSSL_CMP_REVREPCONTENT *rep = NULL; OSSL_CMP_PKISI *si1 = NULL; OSSL_CRMF_CERTID *cid_copy = NULL; OSSL_CMP_MSG *msg = NULL; if (!ossl_assert(ctx != NULL && si != NULL)) return NULL; if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_RP)) == NULL) goto err; rep = msg->body->value.rp; if ((si1 = OSSL_CMP_PKISI_dup(si)) == NULL) goto err; if (!sk_OSSL_CMP_PKISI_push(rep->status, si1)) { OSSL_CMP_PKISI_free(si1); goto err; } if ((rep->revCerts = sk_OSSL_CRMF_CERTID_new_null()) == NULL) goto err; if (cid != NULL) { if ((cid_copy = OSSL_CRMF_CERTID_dup(cid)) == NULL) goto err; if (!sk_OSSL_CRMF_CERTID_push(rep->revCerts, cid_copy)) { OSSL_CRMF_CERTID_free(cid_copy); goto err; } } if (!unprotectedErrors || ossl_cmp_pkisi_get_status(si) != OSSL_CMP_PKISTATUS_rejection) if (!ossl_cmp_msg_protect(ctx, msg)) goto err; return msg; err: ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_RP); OSSL_CMP_MSG_free(msg); return NULL; } OSSL_CMP_MSG *ossl_cmp_pkiconf_new(OSSL_CMP_CTX *ctx) { OSSL_CMP_MSG *msg; if (!ossl_assert(ctx != NULL)) return NULL; if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_PKICONF)) == NULL) goto err; if (ossl_cmp_msg_protect(ctx, msg)) return msg; err: ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_PKICONF); OSSL_CMP_MSG_free(msg); return NULL; } int ossl_cmp_msg_gen_push0_ITAV(OSSL_CMP_MSG *msg, OSSL_CMP_ITAV *itav) { int bodytype; if (!ossl_assert(msg != NULL && itav != NULL)) return 0; bodytype = OSSL_CMP_MSG_get_bodytype(msg); if (bodytype != OSSL_CMP_PKIBODY_GENM && bodytype != OSSL_CMP_PKIBODY_GENP) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return 0; } /* value.genp has the same structure, so this works for genp as well */ return OSSL_CMP_ITAV_push0_stack_item(&msg->body->value.genm, itav); } int ossl_cmp_msg_gen_push1_ITAVs(OSSL_CMP_MSG *msg, const STACK_OF(OSSL_CMP_ITAV) *itavs) { int i; OSSL_CMP_ITAV *itav = NULL; if (!ossl_assert(msg != NULL)) return 0; for (i = 0; i < sk_OSSL_CMP_ITAV_num(itavs); i++) { itav = OSSL_CMP_ITAV_dup(sk_OSSL_CMP_ITAV_value(itavs, i)); if (itav == NULL || !ossl_cmp_msg_gen_push0_ITAV(msg, itav)) { OSSL_CMP_ITAV_free(itav); return 0; } } return 1; } /* * Creates a new General Message/Response with a copy of the given itav stack * returns a pointer to the PKIMessage on success, NULL on error */ static OSSL_CMP_MSG *gen_new(OSSL_CMP_CTX *ctx, const STACK_OF(OSSL_CMP_ITAV) *itavs, int body_type, int err_code) { OSSL_CMP_MSG *msg = NULL; if (!ossl_assert(ctx != NULL)) return NULL; if ((msg = ossl_cmp_msg_create(ctx, body_type)) == NULL) return NULL; if (itavs != NULL && !ossl_cmp_msg_gen_push1_ITAVs(msg, itavs)) goto err; if (!ossl_cmp_msg_protect(ctx, msg)) goto err; return msg; err: ERR_raise(ERR_LIB_CMP, err_code); OSSL_CMP_MSG_free(msg); return NULL; } OSSL_CMP_MSG *ossl_cmp_genm_new(OSSL_CMP_CTX *ctx) { return gen_new(ctx, ctx->genm_ITAVs, OSSL_CMP_PKIBODY_GENM, CMP_R_ERROR_CREATING_GENM); } OSSL_CMP_MSG *ossl_cmp_genp_new(OSSL_CMP_CTX *ctx, const STACK_OF(OSSL_CMP_ITAV) *itavs) { return gen_new(ctx, itavs, OSSL_CMP_PKIBODY_GENP, CMP_R_ERROR_CREATING_GENP); } OSSL_CMP_MSG *ossl_cmp_error_new(OSSL_CMP_CTX *ctx, const OSSL_CMP_PKISI *si, int64_t errorCode, const char *details, int unprotected) { OSSL_CMP_MSG *msg = NULL; const char *lib = NULL, *reason = NULL; OSSL_CMP_PKIFREETEXT *ft; if (!ossl_assert(ctx != NULL && si != NULL)) return NULL; if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_ERROR)) == NULL) goto err; OSSL_CMP_PKISI_free(msg->body->value.error->pKIStatusInfo); if ((msg->body->value.error->pKIStatusInfo = OSSL_CMP_PKISI_dup(si)) == NULL) goto err; if ((msg->body->value.error->errorCode = ASN1_INTEGER_new()) == NULL) goto err; if (!ASN1_INTEGER_set_int64(msg->body->value.error->errorCode, errorCode)) goto err; if (errorCode > 0 && (uint64_t)errorCode < ((uint64_t)ERR_SYSTEM_FLAG << 1)) { lib = ERR_lib_error_string((unsigned long)errorCode); reason = ERR_reason_error_string((unsigned long)errorCode); } if (lib != NULL || reason != NULL || details != NULL) { if ((ft = sk_ASN1_UTF8STRING_new_null()) == NULL) goto err; msg->body->value.error->errorDetails = ft; if (lib != NULL && *lib != '\0' && !ossl_cmp_sk_ASN1_UTF8STRING_push_str(ft, lib, -1)) goto err; if (reason != NULL && *reason != '\0' && !ossl_cmp_sk_ASN1_UTF8STRING_push_str(ft, reason, -1)) goto err; if (details != NULL && !ossl_cmp_sk_ASN1_UTF8STRING_push_str(ft, details, -1)) goto err; } if (!unprotected && !ossl_cmp_msg_protect(ctx, msg)) goto err; return msg; err: ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_ERROR); OSSL_CMP_MSG_free(msg); return NULL; } /* * Set the certHash field of a OSSL_CMP_CERTSTATUS structure. * This is used in the certConf message, for example, * to confirm that the certificate was received successfully. */ int ossl_cmp_certstatus_set0_certHash(OSSL_CMP_CERTSTATUS *certStatus, ASN1_OCTET_STRING *hash) { if (!ossl_assert(certStatus != NULL)) return 0; ASN1_OCTET_STRING_free(certStatus->certHash); certStatus->certHash = hash; return 1; } OSSL_CMP_MSG *ossl_cmp_certConf_new(OSSL_CMP_CTX *ctx, int certReqId, int fail_info, const char *text) { OSSL_CMP_MSG *msg = NULL; OSSL_CMP_CERTSTATUS *certStatus = NULL; EVP_MD *md; int is_fallback; ASN1_OCTET_STRING *certHash = NULL; OSSL_CMP_PKISI *sinfo; if (!ossl_assert(ctx != NULL && ctx->newCert != NULL && (certReqId == OSSL_CMP_CERTREQID || certReqId == OSSL_CMP_CERTREQID_NONE))) return NULL; if ((unsigned)fail_info > OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN) { ERR_raise(ERR_LIB_CMP, CMP_R_FAIL_INFO_OUT_OF_RANGE); return NULL; } if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_CERTCONF)) == NULL) goto err; if ((certStatus = OSSL_CMP_CERTSTATUS_new()) == NULL) goto err; /* consume certStatus into msg right away so it gets deallocated with msg */ if (sk_OSSL_CMP_CERTSTATUS_push(msg->body->value.certConf, certStatus) < 1) { OSSL_CMP_CERTSTATUS_free(certStatus); goto err; } /* set the ID of the certReq */ if (!ASN1_INTEGER_set(certStatus->certReqId, certReqId)) goto err; certStatus->hashAlg = NULL; /* * The hash of the certificate, using the same hash algorithm * as is used to create and verify the certificate signature. * If not available, a fallback hash algorithm is used. */ if ((certHash = X509_digest_sig(ctx->newCert, &md, &is_fallback)) == NULL) goto err; if (is_fallback) { if (!ossl_cmp_hdr_set_pvno(msg->header, OSSL_CMP_PVNO_3)) goto err; if ((certStatus->hashAlg = X509_ALGOR_new()) == NULL) goto err; X509_ALGOR_set_md(certStatus->hashAlg, md); } EVP_MD_free(md); if (!ossl_cmp_certstatus_set0_certHash(certStatus, certHash)) goto err; certHash = NULL; /* * For any particular CertStatus, omission of the statusInfo field * indicates ACCEPTANCE of the specified certificate. Alternatively, * explicit status details (with respect to acceptance or rejection) MAY * be provided in the statusInfo field, perhaps for auditing purposes at * the CA/RA. */ sinfo = fail_info != 0 ? OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_rejection, fail_info, text) : OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_accepted, 0, text); if (sinfo == NULL) goto err; certStatus->statusInfo = sinfo; if (!ossl_cmp_msg_protect(ctx, msg)) goto err; return msg; err: ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_CERTCONF); OSSL_CMP_MSG_free(msg); ASN1_OCTET_STRING_free(certHash); return NULL; } OSSL_CMP_MSG *ossl_cmp_pollReq_new(OSSL_CMP_CTX *ctx, int crid) { OSSL_CMP_MSG *msg = NULL; OSSL_CMP_POLLREQ *preq = NULL; if (!ossl_assert(ctx != NULL)) return NULL; if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_POLLREQ)) == NULL) goto err; if ((preq = OSSL_CMP_POLLREQ_new()) == NULL || !ASN1_INTEGER_set(preq->certReqId, crid) || !sk_OSSL_CMP_POLLREQ_push(msg->body->value.pollReq, preq)) goto err; preq = NULL; if (!ossl_cmp_msg_protect(ctx, msg)) goto err; return msg; err: ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_POLLREQ); OSSL_CMP_POLLREQ_free(preq); OSSL_CMP_MSG_free(msg); return NULL; } OSSL_CMP_MSG *ossl_cmp_pollRep_new(OSSL_CMP_CTX *ctx, int crid, int64_t poll_after) { OSSL_CMP_MSG *msg; OSSL_CMP_POLLREP *prep; if (!ossl_assert(ctx != NULL)) return NULL; if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_POLLREP)) == NULL) goto err; if ((prep = OSSL_CMP_POLLREP_new()) == NULL) goto err; if (!sk_OSSL_CMP_POLLREP_push(msg->body->value.pollRep, prep)) goto err; if (!ASN1_INTEGER_set(prep->certReqId, crid)) goto err; if (!ASN1_INTEGER_set_int64(prep->checkAfter, poll_after)) goto err; if (!ossl_cmp_msg_protect(ctx, msg)) goto err; return msg; err: ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_POLLREP); OSSL_CMP_MSG_free(msg); return NULL; } /*- * returns the status field of the RevRepContent with the given * request/sequence id inside a revocation response. * RevRepContent has the revocation statuses in same order as they were sent in * RevReqContent. * returns NULL on error */ OSSL_CMP_PKISI * ossl_cmp_revrepcontent_get_pkisi(OSSL_CMP_REVREPCONTENT *rrep, int rsid) { OSSL_CMP_PKISI *status; if (!ossl_assert(rrep != NULL)) return NULL; if ((status = sk_OSSL_CMP_PKISI_value(rrep->status, rsid)) != NULL) return status; ERR_raise(ERR_LIB_CMP, CMP_R_PKISTATUSINFO_NOT_FOUND); return NULL; } /* * returns the CertId field in the revCerts part of the RevRepContent * with the given request/sequence id inside a revocation response. * RevRepContent has the CertIds in same order as they were sent in * RevReqContent. * returns NULL on error */ OSSL_CRMF_CERTID * ossl_cmp_revrepcontent_get_CertId(OSSL_CMP_REVREPCONTENT *rrep, int rsid) { OSSL_CRMF_CERTID *cid = NULL; if (!ossl_assert(rrep != NULL)) return NULL; if ((cid = sk_OSSL_CRMF_CERTID_value(rrep->revCerts, rsid)) != NULL) return cid; ERR_raise(ERR_LIB_CMP, CMP_R_CERTID_NOT_FOUND); return NULL; } static int suitable_rid(const ASN1_INTEGER *certReqId, int rid) { int trid; if (rid == OSSL_CMP_CERTREQID_NONE) return 1; trid = ossl_cmp_asn1_get_int(certReqId); if (trid <= OSSL_CMP_CERTREQID_INVALID) { ERR_raise(ERR_LIB_CMP, CMP_R_BAD_REQUEST_ID); return 0; } return rid == trid; } /* * returns a pointer to the PollResponse with the given CertReqId * (or the first one in case -1) inside a PollRepContent * returns NULL on error or if no suitable PollResponse available */ OSSL_CMP_POLLREP * ossl_cmp_pollrepcontent_get0_pollrep(const OSSL_CMP_POLLREPCONTENT *prc, int rid) { OSSL_CMP_POLLREP *pollRep = NULL; int i; if (!ossl_assert(prc != NULL)) return NULL; for (i = 0; i < sk_OSSL_CMP_POLLREP_num(prc); i++) { pollRep = sk_OSSL_CMP_POLLREP_value(prc, i); if (suitable_rid(pollRep->certReqId, rid)) return pollRep; } ERR_raise_data(ERR_LIB_CMP, CMP_R_CERTRESPONSE_NOT_FOUND, "expected certReqId = %d", rid); return NULL; } /* * returns a pointer to the CertResponse with the given CertReqId * (or the first one in case -1) inside a CertRepMessage * returns NULL on error or if no suitable CertResponse available */ OSSL_CMP_CERTRESPONSE * ossl_cmp_certrepmessage_get0_certresponse(const OSSL_CMP_CERTREPMESSAGE *crm, int rid) { OSSL_CMP_CERTRESPONSE *crep = NULL; int i; if (!ossl_assert(crm != NULL && crm->response != NULL)) return NULL; for (i = 0; i < sk_OSSL_CMP_CERTRESPONSE_num(crm->response); i++) { crep = sk_OSSL_CMP_CERTRESPONSE_value(crm->response, i); if (suitable_rid(crep->certReqId, rid)) return crep; } ERR_raise_data(ERR_LIB_CMP, CMP_R_CERTRESPONSE_NOT_FOUND, "expected certReqId = %d", rid); return NULL; } /*- * Retrieve the newly enrolled certificate from the given certResponse crep. * Uses libctx and propq from ctx, in case of indirect POPO also private key. * Returns a pointer to a copy of the found certificate, or NULL if not found. */ X509 *ossl_cmp_certresponse_get1_cert(const OSSL_CMP_CTX *ctx, const OSSL_CMP_CERTRESPONSE *crep) { OSSL_CMP_CERTORENCCERT *coec; X509 *crt = NULL; EVP_PKEY *pkey; if (!ossl_assert(crep != NULL && ctx != NULL)) return NULL; if (crep->certifiedKeyPair && (coec = crep->certifiedKeyPair->certOrEncCert) != NULL) { switch (coec->type) { case OSSL_CMP_CERTORENCCERT_CERTIFICATE: crt = X509_dup(coec->value.certificate); break; case OSSL_CMP_CERTORENCCERT_ENCRYPTEDCERT: /* cert encrypted for indirect PoP; RFC 4210, 5.2.8.2 */ pkey = OSSL_CMP_CTX_get0_newPkey(ctx, 1); /* pkey is ctx->newPkey (if private, else NULL) or ctx->pkey */ if (pkey == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PRIVATE_KEY); return NULL; } crt = OSSL_CRMF_ENCRYPTEDVALUE_get1_encCert(coec->value.encryptedCert, ctx->libctx, ctx->propq, pkey); break; default: ERR_raise(ERR_LIB_CMP, CMP_R_UNKNOWN_CERT_TYPE); return NULL; } } if (crt == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_CERTIFICATE_NOT_FOUND); else (void)ossl_x509_set0_libctx(crt, ctx->libctx, ctx->propq); return crt; } int OSSL_CMP_MSG_update_transactionID(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg) { if (ctx == NULL || msg == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (!ossl_cmp_hdr_set_transactionID(ctx, msg->header)) return 0; return msg->header->protectionAlg == NULL || ossl_cmp_msg_protect(ctx, msg); } int OSSL_CMP_MSG_update_recipNonce(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg) { if (ctx == NULL || msg == NULL || msg->header == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (ctx->recipNonce == NULL) /* nothing to do for 1st msg in transaction */ return 1; if (!ossl_cmp_asn1_octet_string_set1(&msg->header->recipNonce, ctx->recipNonce)) return 0; return msg->header->protectionAlg == NULL || ossl_cmp_msg_protect(ctx, msg); } OSSL_CMP_MSG *OSSL_CMP_MSG_read(const char *file, OSSL_LIB_CTX *libctx, const char *propq) { OSSL_CMP_MSG *msg; BIO *bio = NULL; if (file == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } msg = OSSL_CMP_MSG_new(libctx, propq); if (msg == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_CMP_LIB); return NULL; } if ((bio = BIO_new_file(file, "rb")) == NULL || d2i_OSSL_CMP_MSG_bio(bio, &msg) == NULL) { OSSL_CMP_MSG_free(msg); msg = NULL; } BIO_free(bio); return msg; } int OSSL_CMP_MSG_write(const char *file, const OSSL_CMP_MSG *msg) { BIO *bio; int res; if (file == NULL || msg == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return -1; } bio = BIO_new_file(file, "wb"); if (bio == NULL) return -2; res = i2d_OSSL_CMP_MSG_bio(bio, msg); BIO_free(bio); return res; } OSSL_CMP_MSG *d2i_OSSL_CMP_MSG(OSSL_CMP_MSG **msg, const unsigned char **in, long len) { OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; if (msg != NULL && *msg != NULL) { libctx = (*msg)->libctx; propq = (*msg)->propq; } return (OSSL_CMP_MSG *)ASN1_item_d2i_ex((ASN1_VALUE **)msg, in, len, ASN1_ITEM_rptr(OSSL_CMP_MSG), libctx, propq); } int i2d_OSSL_CMP_MSG(const OSSL_CMP_MSG *msg, unsigned char **out) { return ASN1_item_i2d((const ASN1_VALUE *)msg, out, ASN1_ITEM_rptr(OSSL_CMP_MSG)); } OSSL_CMP_MSG *d2i_OSSL_CMP_MSG_bio(BIO *bio, OSSL_CMP_MSG **msg) { OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; if (msg != NULL && *msg != NULL) { libctx = (*msg)->libctx; propq = (*msg)->propq; } return ASN1_item_d2i_bio_ex(ASN1_ITEM_rptr(OSSL_CMP_MSG), bio, msg, libctx, propq); } int i2d_OSSL_CMP_MSG_bio(BIO *bio, const OSSL_CMP_MSG *msg) { return ASN1_i2d_bio_of(OSSL_CMP_MSG, i2d_OSSL_CMP_MSG, bio, msg); } int ossl_cmp_is_error_with_waiting(const OSSL_CMP_MSG *msg) { if (!ossl_assert(msg != NULL)) return 0; return (OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_ERROR && ossl_cmp_pkisi_get_status(msg->body->value.error->pKIStatusInfo) == OSSL_CMP_PKISTATUS_waiting); }
./openssl/crypto/cmp/cmp_hdr.c
/* * Copyright 2007-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* CMP functions for PKIHeader handling */ #include "cmp_local.h" #include <openssl/rand.h> /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/asn1t.h> #include <openssl/cmp.h> #include <openssl/err.h> int ossl_cmp_hdr_set_pvno(OSSL_CMP_PKIHEADER *hdr, int pvno) { if (!ossl_assert(hdr != NULL)) return 0; return ASN1_INTEGER_set(hdr->pvno, pvno); } int ossl_cmp_hdr_get_pvno(const OSSL_CMP_PKIHEADER *hdr) { int64_t pvno; if (!ossl_assert(hdr != NULL)) return -1; if (!ASN1_INTEGER_get_int64(&pvno, hdr->pvno) || pvno < 0 || pvno > INT_MAX) return -1; return (int)pvno; } int ossl_cmp_hdr_get_protection_nid(const OSSL_CMP_PKIHEADER *hdr) { if (!ossl_assert(hdr != NULL) || hdr->protectionAlg == NULL) return NID_undef; return OBJ_obj2nid(hdr->protectionAlg->algorithm); } ASN1_OCTET_STRING *OSSL_CMP_HDR_get0_transactionID(const OSSL_CMP_PKIHEADER *hdr) { if (hdr == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return hdr->transactionID; } ASN1_OCTET_STRING *ossl_cmp_hdr_get0_senderNonce(const OSSL_CMP_PKIHEADER *hdr) { if (!ossl_assert(hdr != NULL)) return NULL; return hdr->senderNonce; } ASN1_OCTET_STRING *OSSL_CMP_HDR_get0_recipNonce(const OSSL_CMP_PKIHEADER *hdr) { if (hdr == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return hdr->recipNonce; } STACK_OF(OSSL_CMP_ITAV) *OSSL_CMP_HDR_get0_geninfo_ITAVs(const OSSL_CMP_PKIHEADER *hdr) { if (hdr == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return hdr->generalInfo; } /* a NULL-DN as an empty sequence of RDNs */ int ossl_cmp_general_name_is_NULL_DN(GENERAL_NAME *name) { return name == NULL || (name->type == GEN_DIRNAME && IS_NULL_DN(name->d.directoryName)); } /* assign to *tgt a copy of src (which may be NULL to indicate an empty DN) */ static int set1_general_name(GENERAL_NAME **tgt, const X509_NAME *src) { GENERAL_NAME *name; if (!ossl_assert(tgt != NULL)) return 0; if ((name = GENERAL_NAME_new()) == NULL) goto err; name->type = GEN_DIRNAME; if (src == NULL) { /* NULL-DN */ if ((name->d.directoryName = X509_NAME_new()) == NULL) goto err; } else if (!X509_NAME_set(&name->d.directoryName, src)) { goto err; } GENERAL_NAME_free(*tgt); *tgt = name; return 1; err: GENERAL_NAME_free(name); return 0; } /* * Set the sender name in PKIHeader. * when nm is NULL, sender is set to an empty string * returns 1 on success, 0 on error */ int ossl_cmp_hdr_set1_sender(OSSL_CMP_PKIHEADER *hdr, const X509_NAME *nm) { if (!ossl_assert(hdr != NULL)) return 0; return set1_general_name(&hdr->sender, nm); } int ossl_cmp_hdr_set1_recipient(OSSL_CMP_PKIHEADER *hdr, const X509_NAME *nm) { if (!ossl_assert(hdr != NULL)) return 0; return set1_general_name(&hdr->recipient, nm); } int ossl_cmp_hdr_update_messageTime(OSSL_CMP_PKIHEADER *hdr) { if (!ossl_assert(hdr != NULL)) return 0; if (hdr->messageTime == NULL && (hdr->messageTime = ASN1_GENERALIZEDTIME_new()) == NULL) return 0; return ASN1_GENERALIZEDTIME_set(hdr->messageTime, time(NULL)) != NULL; } /* assign to *tgt a random byte array of given length */ static int set_random(ASN1_OCTET_STRING **tgt, OSSL_CMP_CTX *ctx, size_t len) { unsigned char *bytes = OPENSSL_malloc(len); int res = 0; if (bytes == NULL || RAND_bytes_ex(ctx->libctx, bytes, len, 0) <= 0) ERR_raise(ERR_LIB_CMP, CMP_R_FAILURE_OBTAINING_RANDOM); else res = ossl_cmp_asn1_octet_string_set1_bytes(tgt, bytes, len); OPENSSL_free(bytes); return res; } int ossl_cmp_hdr_set1_senderKID(OSSL_CMP_PKIHEADER *hdr, const ASN1_OCTET_STRING *senderKID) { if (!ossl_assert(hdr != NULL)) return 0; return ossl_cmp_asn1_octet_string_set1(&hdr->senderKID, senderKID); } /* push the given text string to the given PKIFREETEXT ft */ int ossl_cmp_hdr_push0_freeText(OSSL_CMP_PKIHEADER *hdr, ASN1_UTF8STRING *text) { if (!ossl_assert(hdr != NULL && text != NULL)) return 0; if (hdr->freeText == NULL && (hdr->freeText = sk_ASN1_UTF8STRING_new_null()) == NULL) return 0; return sk_ASN1_UTF8STRING_push(hdr->freeText, text); } int ossl_cmp_hdr_push1_freeText(OSSL_CMP_PKIHEADER *hdr, ASN1_UTF8STRING *text) { if (!ossl_assert(hdr != NULL && text != NULL)) return 0; if (hdr->freeText == NULL && (hdr->freeText = sk_ASN1_UTF8STRING_new_null()) == NULL) return 0; return ossl_cmp_sk_ASN1_UTF8STRING_push_str(hdr->freeText, (char *)text->data, text->length); } int ossl_cmp_hdr_generalInfo_push0_item(OSSL_CMP_PKIHEADER *hdr, OSSL_CMP_ITAV *itav) { if (!ossl_assert(hdr != NULL && itav != NULL)) return 0; return OSSL_CMP_ITAV_push0_stack_item(&hdr->generalInfo, itav); } int ossl_cmp_hdr_generalInfo_push1_items(OSSL_CMP_PKIHEADER *hdr, const STACK_OF(OSSL_CMP_ITAV) *itavs) { int i; OSSL_CMP_ITAV *itav; if (!ossl_assert(hdr != NULL)) return 0; for (i = 0; i < sk_OSSL_CMP_ITAV_num(itavs); i++) { itav = OSSL_CMP_ITAV_dup(sk_OSSL_CMP_ITAV_value(itavs, i)); if (itav == NULL) return 0; if (!ossl_cmp_hdr_generalInfo_push0_item(hdr, itav)) { OSSL_CMP_ITAV_free(itav); return 0; } } return 1; } int ossl_cmp_hdr_set_implicitConfirm(OSSL_CMP_PKIHEADER *hdr) { OSSL_CMP_ITAV *itav; ASN1_TYPE *asn1null; if (!ossl_assert(hdr != NULL)) return 0; asn1null = (ASN1_TYPE *)ASN1_NULL_new(); if (asn1null == NULL) return 0; if ((itav = OSSL_CMP_ITAV_create(OBJ_nid2obj(NID_id_it_implicitConfirm), asn1null)) == NULL) goto err; if (!ossl_cmp_hdr_generalInfo_push0_item(hdr, itav)) goto err; return 1; err: ASN1_TYPE_free(asn1null); OSSL_CMP_ITAV_free(itav); return 0; } /* return 1 if implicitConfirm in the generalInfo field of the header is set */ int ossl_cmp_hdr_has_implicitConfirm(const OSSL_CMP_PKIHEADER *hdr) { int itavCount; int i; OSSL_CMP_ITAV *itav; if (!ossl_assert(hdr != NULL)) return 0; itavCount = sk_OSSL_CMP_ITAV_num(hdr->generalInfo); for (i = 0; i < itavCount; i++) { itav = sk_OSSL_CMP_ITAV_value(hdr->generalInfo, i); if (itav != NULL && OBJ_obj2nid(itav->infoType) == NID_id_it_implicitConfirm) return 1; } return 0; } /* * set ctx->transactionID in CMP header * if ctx->transactionID is NULL, a random one is created with 128 bit * according to section 5.1.1: * * It is RECOMMENDED that the clients fill the transactionID field with * 128 bits of (pseudo-) random data for the start of a transaction to * reduce the probability of having the transactionID in use at the server. */ int ossl_cmp_hdr_set_transactionID(OSSL_CMP_CTX *ctx, OSSL_CMP_PKIHEADER *hdr) { if (ctx->transactionID == NULL) { char *tid; if (!set_random(&ctx->transactionID, ctx, OSSL_CMP_TRANSACTIONID_LENGTH)) return 0; tid = i2s_ASN1_OCTET_STRING(NULL, ctx->transactionID); if (tid != NULL) ossl_cmp_log1(DEBUG, ctx, "Starting new transaction with ID=%s", tid); OPENSSL_free(tid); } return ossl_cmp_asn1_octet_string_set1(&hdr->transactionID, ctx->transactionID); } /* fill in all fields of the hdr according to the info given in ctx */ int ossl_cmp_hdr_init(OSSL_CMP_CTX *ctx, OSSL_CMP_PKIHEADER *hdr) { const X509_NAME *sender; const X509_NAME *rcp = NULL; if (!ossl_assert(ctx != NULL && hdr != NULL)) return 0; /* set the CMP version */ if (!ossl_cmp_hdr_set_pvno(hdr, OSSL_CMP_PVNO)) return 0; /* * If no protection cert nor oldCert nor CSR nor subject is given, * sender name is not known to the client and thus set to NULL-DN */ sender = ctx->cert != NULL ? X509_get_subject_name(ctx->cert) : ctx->oldCert != NULL ? X509_get_subject_name(ctx->oldCert) : ctx->p10CSR != NULL ? X509_REQ_get_subject_name(ctx->p10CSR) : ctx->subjectName; if (!ossl_cmp_hdr_set1_sender(hdr, sender)) return 0; /* determine recipient entry in PKIHeader */ if (ctx->recipient != NULL) rcp = ctx->recipient; else if (ctx->srvCert != NULL) rcp = X509_get_subject_name(ctx->srvCert); else if (ctx->issuer != NULL) rcp = ctx->issuer; else if (ctx->oldCert != NULL) rcp = X509_get_issuer_name(ctx->oldCert); else if (ctx->cert != NULL) rcp = X509_get_issuer_name(ctx->cert); if (!ossl_cmp_hdr_set1_recipient(hdr, rcp)) return 0; /* set current time as message time */ if (!ossl_cmp_hdr_update_messageTime(hdr)) return 0; if (ctx->recipNonce != NULL && !ossl_cmp_asn1_octet_string_set1(&hdr->recipNonce, ctx->recipNonce)) return 0; if (!ossl_cmp_hdr_set_transactionID(ctx, hdr)) return 0; /*- * set random senderNonce * according to section 5.1.1: * * senderNonce present * -- 128 (pseudo-)random bits * The senderNonce and recipNonce fields protect the PKIMessage against * replay attacks. The senderNonce will typically be 128 bits of * (pseudo-) random data generated by the sender, whereas the recipNonce * is copied from the senderNonce of the previous message in the * transaction. */ if (!set_random(&hdr->senderNonce, ctx, OSSL_CMP_SENDERNONCE_LENGTH)) return 0; /* store senderNonce - for cmp with recipNonce in next outgoing msg */ if (!OSSL_CMP_CTX_set1_senderNonce(ctx, hdr->senderNonce)) return 0; /*- * freeText [7] PKIFreeText OPTIONAL, * -- this may be used to indicate context-specific instructions * -- (this field is intended for human consumption) */ if (ctx->freeText != NULL && !ossl_cmp_hdr_push1_freeText(hdr, ctx->freeText)) return 0; return 1; }
./openssl/crypto/cmp/cmp_http.c
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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 <stdio.h> #include <openssl/asn1t.h> #include <openssl/http.h> #include <openssl/cmp.h> #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <ctype.h> #include <fcntl.h> #include <stdlib.h> #include <openssl/bio.h> #include <openssl/buffer.h> #include <openssl/err.h> static int keep_alive(int keep_alive, int body_type) { if (keep_alive != 0 /* * Ask for persistent connection only if may need more round trips. * Do so even with disableConfirm because polling might be needed. */ && body_type != OSSL_CMP_PKIBODY_IR && body_type != OSSL_CMP_PKIBODY_CR && body_type != OSSL_CMP_PKIBODY_P10CR && body_type != OSSL_CMP_PKIBODY_KUR && body_type != OSSL_CMP_PKIBODY_POLLREQ) keep_alive = 0; return keep_alive; } /* * Send the PKIMessage req and on success return the response, else NULL. */ OSSL_CMP_MSG *OSSL_CMP_MSG_http_perform(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req) { char server_port[32] = { '\0' }; STACK_OF(CONF_VALUE) *headers = NULL; const char content_type_pkix[] = "application/pkixcmp"; int tls_used; const ASN1_ITEM *it = ASN1_ITEM_rptr(OSSL_CMP_MSG); BIO *req_mem, *rsp; OSSL_CMP_MSG *res = NULL; if (ctx == NULL || req == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } if (!X509V3_add_value("Pragma", "no-cache", &headers)) return NULL; if ((req_mem = ASN1_item_i2d_mem_bio(it, (const ASN1_VALUE *)req)) == NULL) goto err; if (ctx->serverPort != 0) BIO_snprintf(server_port, sizeof(server_port), "%d", ctx->serverPort); tls_used = ctx->tls_used >= 0 ? ctx->tls_used != 0 : OSSL_CMP_CTX_get_http_cb_arg(ctx) != NULL; /* backward compat */ if (ctx->http_ctx == NULL) ossl_cmp_log3(DEBUG, ctx, "connecting to CMP server %s:%s%s", ctx->server, server_port, tls_used ? " using TLS" : ""); rsp = OSSL_HTTP_transfer(&ctx->http_ctx, ctx->server, server_port, ctx->serverPath, tls_used, ctx->proxy, ctx->no_proxy, NULL /* bio */, NULL /* rbio */, ctx->http_cb, OSSL_CMP_CTX_get_http_cb_arg(ctx), 0 /* buf_size */, headers, content_type_pkix, req_mem, content_type_pkix, 1 /* expect_asn1 */, OSSL_HTTP_DEFAULT_MAX_RESP_LEN, ctx->msg_timeout, keep_alive(ctx->keep_alive, req->body->type)); BIO_free(req_mem); res = (OSSL_CMP_MSG *)ASN1_item_d2i_bio(it, rsp, NULL); BIO_free(rsp); if (ctx->http_ctx == NULL) ossl_cmp_debug(ctx, "disconnected from CMP server"); /* * Note that on normal successful end of the transaction the connection * is not closed at this level, but this will be done by the CMP client * application via OSSL_CMP_CTX_free() or OSSL_CMP_CTX_reinit(). */ if (res != NULL) ossl_cmp_debug(ctx, "finished reading response from CMP server"); err: sk_CONF_VALUE_pop_free(headers, X509V3_conf_free); return res; }
./openssl/crypto/cmp/cmp_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/cmperr.h> #include "crypto/cmperr.h" #ifndef OPENSSL_NO_CMP # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA CMP_str_reasons[] = { {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ALGORITHM_NOT_SUPPORTED), "algorithm not supported"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_BAD_CHECKAFTER_IN_POLLREP), "bad checkafter in pollrep"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_BAD_REQUEST_ID), "bad request id"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTHASH_UNMATCHED), "certhash unmatched"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTID_NOT_FOUND), "certid not found"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTIFICATE_NOT_ACCEPTED), "certificate not accepted"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTIFICATE_NOT_FOUND), "certificate not found"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTREQMSG_NOT_FOUND), "certreqmsg not found"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTRESPONSE_NOT_FOUND), "certresponse not found"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERT_AND_KEY_DO_NOT_MATCH), "cert and key do not match"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CHECKAFTER_OUT_OF_RANGE), "checkafter out of range"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ENCOUNTERED_KEYUPDATEWARNING), "encountered keyupdatewarning"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ENCOUNTERED_WAITING), "encountered waiting"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CALCULATING_PROTECTION), "error calculating protection"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_CERTCONF), "error creating certconf"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_CERTREP), "error creating certrep"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_CERTREQ), "error creating certreq"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_ERROR), "error creating error"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_GENM), "error creating genm"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_GENP), "error creating genp"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_PKICONF), "error creating pkiconf"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_POLLREP), "error creating pollrep"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_POLLREQ), "error creating pollreq"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_RP), "error creating rp"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_RR), "error creating rr"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_PARSING_PKISTATUS), "error parsing pkistatus"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_PROCESSING_MESSAGE), "error processing message"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_PROTECTING_MESSAGE), "error protecting message"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_SETTING_CERTHASH), "error setting certhash"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_UNEXPECTED_CERTCONF), "error unexpected certconf"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_VALIDATING_PROTECTION), "error validating protection"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_VALIDATING_SIGNATURE), "error validating signature"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_EXPECTED_POLLREQ), "expected pollreq"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_FAILED_BUILDING_OWN_CHAIN), "failed building own chain"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_FAILED_EXTRACTING_PUBKEY), "failed extracting pubkey"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_FAILURE_OBTAINING_RANDOM), "failure obtaining random"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_FAIL_INFO_OUT_OF_RANGE), "fail info out of range"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_GETTING_GENP), "getting genp"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_INVALID_ARGS), "invalid args"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_INVALID_GENP), "invalid genp"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_INVALID_OPTION), "invalid option"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_INVALID_ROOTCAKEYUPDATE), "invalid rootcakeyupdate"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_CERTID), "missing certid"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_KEY_INPUT_FOR_CREATING_PROTECTION), "missing key input for creating protection"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE), "missing key usage digitalsignature"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_P10CSR), "missing p10csr"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_PBM_SECRET), "missing pbm secret"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_PRIVATE_KEY), "missing private key"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_PRIVATE_KEY_FOR_POPO), "missing private key for popo"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_PROTECTION), "missing protection"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_PUBLIC_KEY), "missing public key"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_REFERENCE_CERT), "missing reference cert"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_SECRET), "missing secret"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_SENDER_IDENTIFICATION), "missing sender identification"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_TRUST_ANCHOR), "missing trust anchor"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_TRUST_STORE), "missing trust store"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MULTIPLE_REQUESTS_NOT_SUPPORTED), "multiple requests not supported"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED), "multiple responses not supported"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MULTIPLE_SAN_SOURCES), "multiple san sources"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_NO_STDIO), "no stdio"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_NO_SUITABLE_SENDER_CERT), "no suitable sender cert"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_NULL_ARGUMENT), "null argument"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_PKIBODY_ERROR), "pkibody error"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_PKISTATUSINFO_NOT_FOUND), "pkistatusinfo not found"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_POLLING_FAILED), "polling failed"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_POTENTIALLY_INVALID_CERTIFICATE), "potentially invalid certificate"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_RECEIVED_ERROR), "received error"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_RECIPNONCE_UNMATCHED), "recipnonce unmatched"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_REQUEST_NOT_ACCEPTED), "request not accepted"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_REQUEST_REJECTED_BY_SERVER), "request rejected by server"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED), "sender generalname type not supported"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_SRVCERT_DOES_NOT_VALIDATE_MSG), "srvcert does not validate msg"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_TOTAL_TIMEOUT), "total timeout"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_TRANSACTIONID_UNMATCHED), "transactionid unmatched"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_TRANSFER_ERROR), "transfer error"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNCLEAN_CTX), "unclean ctx"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNEXPECTED_CERTPROFILE), "unexpected certprofile"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNEXPECTED_PKIBODY), "unexpected pkibody"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNEXPECTED_PKISTATUS), "unexpected pkistatus"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNEXPECTED_POLLREQ), "unexpected pollreq"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNEXPECTED_PVNO), "unexpected pvno"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNEXPECTED_SENDER), "unexpected sender"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNKNOWN_ALGORITHM_ID), "unknown algorithm id"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNKNOWN_CERT_TYPE), "unknown cert type"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNKNOWN_PKISTATUS), "unknown pkistatus"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNSUPPORTED_ALGORITHM), "unsupported algorithm"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNSUPPORTED_KEY_TYPE), "unsupported key type"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNSUPPORTED_PKIBODY), "unsupported pkibody"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC), "unsupported protection alg dhbasedmac"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_VALUE_TOO_LARGE), "value too large"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_VALUE_TOO_SMALL), "value too small"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_ALGORITHM_OID), "wrong algorithm oid"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_CERTID), "wrong certid"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_CERTID_IN_RP), "wrong certid in rp"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_PBM_VALUE), "wrong pbm value"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_RP_COMPONENT_COUNT), "wrong rp component count"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_SERIAL_IN_RP), "wrong serial in rp"}, {0, NULL} }; # endif int ossl_err_load_CMP_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(CMP_str_reasons[0].error) == NULL) ERR_load_strings_const(CMP_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
./openssl/crypto/cmp/cmp_ctx.c
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/trace.h> #include <openssl/bio.h> #include <openssl/ocsp.h> /* for OCSP_REVOKED_STATUS_* */ #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/cmp.h> #include <openssl/crmf.h> #include <openssl/err.h> #define DEFINE_OSSL_CMP_CTX_get0(FIELD, TYPE) \ DEFINE_OSSL_CMP_CTX_get0_NAME(FIELD, FIELD, TYPE) #define DEFINE_OSSL_CMP_CTX_get0_NAME(NAME, FIELD, TYPE) \ TYPE *OSSL_CMP_CTX_get0_##NAME(const OSSL_CMP_CTX *ctx) \ { \ if (ctx == NULL) { \ ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \ return NULL; \ } \ return ctx->FIELD; \ } /* * Get current certificate store containing trusted root CA certs */ DEFINE_OSSL_CMP_CTX_get0_NAME(trusted, trusted, X509_STORE) #define DEFINE_OSSL_set0(PREFIX, FIELD, TYPE) \ DEFINE_OSSL_set0_NAME(PREFIX, FIELD, FIELD, TYPE) #define DEFINE_OSSL_set0_NAME(PREFIX, NAME, FIELD, TYPE) \ int PREFIX##_set0##_##NAME(OSSL_CMP_CTX *ctx, TYPE *val) \ { \ if (ctx == NULL) { \ ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \ return 0; \ } \ TYPE##_free(ctx->FIELD); \ ctx->FIELD = val; \ return 1; \ } /* * Set certificate store containing trusted (root) CA certs and possibly CRLs * and a cert verification callback function used for CMP server authentication. * Any already existing store entry is freed. Given NULL, the entry is reset. */ DEFINE_OSSL_set0_NAME(OSSL_CMP_CTX, trusted, trusted, X509_STORE) DEFINE_OSSL_CMP_CTX_get0(libctx, OSSL_LIB_CTX) DEFINE_OSSL_CMP_CTX_get0(propq, const char) /* Get current list of non-trusted intermediate certs */ DEFINE_OSSL_CMP_CTX_get0(untrusted, STACK_OF(X509)) /* * Set untrusted certificates for path construction in authentication of * the CMP server and potentially others (TLS server, newly enrolled cert). */ int OSSL_CMP_CTX_set1_untrusted(OSSL_CMP_CTX *ctx, STACK_OF(X509) *certs) { STACK_OF(X509) *untrusted = NULL; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (!ossl_x509_add_certs_new(&untrusted, certs, X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP)) goto err; OSSL_STACK_OF_X509_free(ctx->untrusted); ctx->untrusted = untrusted; return 1; err: OSSL_STACK_OF_X509_free(untrusted); return 0; } static int cmp_ctx_set_md(OSSL_CMP_CTX *ctx, EVP_MD **pmd, int nid) { EVP_MD *md = EVP_MD_fetch(ctx->libctx, OBJ_nid2sn(nid), ctx->propq); /* fetching in advance to be able to throw error early if unsupported */ if (md == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_ALGORITHM); return 0; } EVP_MD_free(*pmd); *pmd = md; return 1; } /* * Allocates and initializes OSSL_CMP_CTX context structure with default values. * Returns new context on success, NULL on error */ OSSL_CMP_CTX *OSSL_CMP_CTX_new(OSSL_LIB_CTX *libctx, const char *propq) { OSSL_CMP_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) goto err; ctx->libctx = libctx; if (propq != NULL && (ctx->propq = OPENSSL_strdup(propq)) == NULL) goto err; ctx->log_verbosity = OSSL_CMP_LOG_INFO; ctx->status = OSSL_CMP_PKISTATUS_unspecified; ctx->failInfoCode = -1; ctx->keep_alive = 1; ctx->msg_timeout = -1; ctx->tls_used = -1; /* default for backward compatibility */ if ((ctx->untrusted = sk_X509_new_null()) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } ctx->pbm_slen = 16; if (!cmp_ctx_set_md(ctx, &ctx->pbm_owf, NID_sha256)) goto err; ctx->pbm_itercnt = 500; ctx->pbm_mac = NID_hmac_sha1; if (!cmp_ctx_set_md(ctx, &ctx->digest, NID_sha256)) goto err; ctx->popoMethod = OSSL_CRMF_POPO_SIGNATURE; ctx->revocationReason = CRL_REASON_NONE; /* all other elements are initialized to 0 or NULL, respectively */ return ctx; err: OSSL_CMP_CTX_free(ctx); return NULL; } #define OSSL_CMP_ITAVs_free(itavs) \ sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free); #define X509_EXTENSIONS_free(exts) \ sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free) #define OSSL_CMP_PKIFREETEXT_free(text) \ sk_ASN1_UTF8STRING_pop_free(text, ASN1_UTF8STRING_free) /* Prepare the OSSL_CMP_CTX for next use, partly re-initializing OSSL_CMP_CTX */ int OSSL_CMP_CTX_reinit(OSSL_CMP_CTX *ctx) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } #ifndef OPENSSL_NO_HTTP if (ctx->http_ctx != NULL) { (void)OSSL_HTTP_close(ctx->http_ctx, 1); ossl_cmp_debug(ctx, "disconnected from CMP server"); ctx->http_ctx = NULL; } #endif ctx->status = OSSL_CMP_PKISTATUS_unspecified; ctx->failInfoCode = -1; OSSL_CMP_ITAVs_free(ctx->genm_ITAVs); ctx->genm_ITAVs = NULL; return ossl_cmp_ctx_set0_statusString(ctx, NULL) && ossl_cmp_ctx_set0_newCert(ctx, NULL) && ossl_cmp_ctx_set1_newChain(ctx, NULL) && ossl_cmp_ctx_set1_caPubs(ctx, NULL) && ossl_cmp_ctx_set1_extraCertsIn(ctx, NULL) && ossl_cmp_ctx_set1_validatedSrvCert(ctx, NULL) && ossl_cmp_ctx_set1_first_senderNonce(ctx, NULL) && OSSL_CMP_CTX_set1_transactionID(ctx, NULL) && OSSL_CMP_CTX_set1_senderNonce(ctx, NULL) && ossl_cmp_ctx_set1_recipNonce(ctx, NULL); } /* Frees OSSL_CMP_CTX variables allocated in OSSL_CMP_CTX_new() */ void OSSL_CMP_CTX_free(OSSL_CMP_CTX *ctx) { if (ctx == NULL) return; #ifndef OPENSSL_NO_HTTP if (ctx->http_ctx != NULL) { (void)OSSL_HTTP_close(ctx->http_ctx, 1); ossl_cmp_debug(ctx, "disconnected from CMP server"); } #endif OPENSSL_free(ctx->propq); OPENSSL_free(ctx->serverPath); OPENSSL_free(ctx->server); OPENSSL_free(ctx->proxy); OPENSSL_free(ctx->no_proxy); X509_free(ctx->srvCert); X509_free(ctx->validatedSrvCert); X509_NAME_free(ctx->expected_sender); X509_STORE_free(ctx->trusted); OSSL_STACK_OF_X509_free(ctx->untrusted); X509_free(ctx->cert); OSSL_STACK_OF_X509_free(ctx->chain); EVP_PKEY_free(ctx->pkey); ASN1_OCTET_STRING_free(ctx->referenceValue); if (ctx->secretValue != NULL) OPENSSL_cleanse(ctx->secretValue->data, ctx->secretValue->length); ASN1_OCTET_STRING_free(ctx->secretValue); EVP_MD_free(ctx->pbm_owf); X509_NAME_free(ctx->recipient); EVP_MD_free(ctx->digest); ASN1_OCTET_STRING_free(ctx->transactionID); ASN1_OCTET_STRING_free(ctx->senderNonce); ASN1_OCTET_STRING_free(ctx->recipNonce); ASN1_OCTET_STRING_free(ctx->first_senderNonce); OSSL_CMP_ITAVs_free(ctx->geninfo_ITAVs); OSSL_STACK_OF_X509_free(ctx->extraCertsOut); EVP_PKEY_free(ctx->newPkey); X509_NAME_free(ctx->issuer); ASN1_INTEGER_free(ctx->serialNumber); X509_NAME_free(ctx->subjectName); sk_GENERAL_NAME_pop_free(ctx->subjectAltNames, GENERAL_NAME_free); X509_EXTENSIONS_free(ctx->reqExtensions); sk_POLICYINFO_pop_free(ctx->policies, POLICYINFO_free); X509_free(ctx->oldCert); X509_REQ_free(ctx->p10CSR); OSSL_CMP_ITAVs_free(ctx->genm_ITAVs); OSSL_CMP_PKIFREETEXT_free(ctx->statusString); X509_free(ctx->newCert); OSSL_STACK_OF_X509_free(ctx->newChain); OSSL_STACK_OF_X509_free(ctx->caPubs); OSSL_STACK_OF_X509_free(ctx->extraCertsIn); OPENSSL_free(ctx); } #define DEFINE_OSSL_set(PREFIX, FIELD, TYPE) \ int PREFIX##_set_##FIELD(OSSL_CMP_CTX *ctx, TYPE val) \ { \ if (ctx == NULL) { \ ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \ return 0; \ } \ ctx->FIELD = val; \ return 1; \ } DEFINE_OSSL_set(ossl_cmp_ctx, status, int) #define DEFINE_OSSL_get(PREFIX, FIELD, TYPE, ERR_RET) \ TYPE PREFIX##_get_##FIELD(const OSSL_CMP_CTX *ctx) \ { \ if (ctx == NULL) { \ ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \ return ERR_RET; \ } \ return ctx->FIELD; \ } /* * Returns the PKIStatus from the last CertRepMessage * or Revocation Response or error message, -1 on error */ DEFINE_OSSL_get(OSSL_CMP_CTX, status, int, -1) /* * Returns the statusString from the last CertRepMessage * or Revocation Response or error message, NULL on error */ DEFINE_OSSL_CMP_CTX_get0(statusString, OSSL_CMP_PKIFREETEXT) DEFINE_OSSL_set0(ossl_cmp_ctx, statusString, OSSL_CMP_PKIFREETEXT) /* Set callback function for checking if the cert is ok or should be rejected */ DEFINE_OSSL_set(OSSL_CMP_CTX, certConf_cb, OSSL_CMP_certConf_cb_t) /* * Set argument, respectively a pointer to a structure containing arguments, * optionally to be used by the certConf callback. */ DEFINE_OSSL_set(OSSL_CMP_CTX, certConf_cb_arg, void *) /* * Get argument, respectively the pointer to a structure containing arguments, * optionally to be used by certConf callback. * Returns callback argument set previously (NULL if not set or on error) */ DEFINE_OSSL_get(OSSL_CMP_CTX, certConf_cb_arg, void *, NULL) #ifndef OPENSSL_NO_TRACE static size_t ossl_cmp_log_trace_cb(const char *buf, size_t cnt, int category, int cmd, void *vdata) { OSSL_CMP_CTX *ctx = vdata; const char *msg; OSSL_CMP_severity level = -1; char *func = NULL; char *file = NULL; int line = 0; if (buf == NULL || cnt == 0 || cmd != OSSL_TRACE_CTRL_WRITE || ctx == NULL) return 0; if (ctx->log_cb == NULL) return 1; /* silently drop message */ msg = ossl_cmp_log_parse_metadata(buf, &level, &func, &file, &line); if (level > ctx->log_verbosity) /* excludes the case level is unknown */ goto end; /* suppress output since severity is not sufficient */ if (!ctx->log_cb(func != NULL ? func : "(no func)", file != NULL ? file : "(no file)", line, level, msg)) cnt = 0; end: OPENSSL_free(func); OPENSSL_free(file); return cnt; } #endif /* Print CMP log messages (i.e., diagnostic info) via the log cb of the ctx */ int ossl_cmp_print_log(OSSL_CMP_severity level, const OSSL_CMP_CTX *ctx, const char *func, const char *file, int line, const char *level_str, const char *format, ...) { va_list args; char hugebuf[1024 * 2]; int res = 0; if (ctx == NULL || ctx->log_cb == NULL) return 1; /* silently drop message */ if (level > ctx->log_verbosity) /* excludes the case level is unknown */ return 1; /* suppress output since severity is not sufficient */ if (format == NULL) return 0; va_start(args, format); if (func == NULL) func = "(unset function name)"; if (file == NULL) file = "(unset file name)"; if (level_str == NULL) level_str = "(unset level string)"; #ifndef OPENSSL_NO_TRACE if (OSSL_TRACE_ENABLED(CMP)) { OSSL_TRACE_BEGIN(CMP) { int printed = BIO_snprintf(hugebuf, sizeof(hugebuf), "%s:%s:%d:" OSSL_CMP_LOG_PREFIX "%s: ", func, file, line, level_str); if (printed > 0 && (size_t)printed < sizeof(hugebuf)) { if (BIO_vsnprintf(hugebuf + printed, sizeof(hugebuf) - printed, format, args) > 0) res = BIO_puts(trc_out, hugebuf) > 0; } } OSSL_TRACE_END(CMP); } #else /* compensate for disabled trace API */ { if (BIO_vsnprintf(hugebuf, sizeof(hugebuf), format, args) > 0) res = ctx->log_cb(func, file, line, level, hugebuf); } #endif va_end(args); return res; } /* Set a callback function for error reporting and logging messages */ int OSSL_CMP_CTX_set_log_cb(OSSL_CMP_CTX *ctx, OSSL_CMP_log_cb_t cb) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } ctx->log_cb = cb; #ifndef OPENSSL_NO_TRACE /* do also in case cb == NULL, to switch off logging output: */ if (!OSSL_trace_set_callback(OSSL_TRACE_CATEGORY_CMP, ossl_cmp_log_trace_cb, ctx)) return 0; #endif return 1; } /* Print OpenSSL and CMP errors via the log cb of the ctx or ERR_print_errors */ void OSSL_CMP_CTX_print_errors(const OSSL_CMP_CTX *ctx) { if (ctx != NULL && OSSL_CMP_LOG_ERR > ctx->log_verbosity) return; /* suppress output since severity is not sufficient */ OSSL_CMP_print_errors_cb(ctx == NULL ? NULL : ctx->log_cb); } /* * Set or clear the reference value to be used for identification * (i.e., the user name) when using PBMAC. */ int OSSL_CMP_CTX_set1_referenceValue(OSSL_CMP_CTX *ctx, const unsigned char *ref, int len) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } return ossl_cmp_asn1_octet_string_set1_bytes(&ctx->referenceValue, ref, len); } /* Set or clear the password to be used for protecting messages with PBMAC */ int OSSL_CMP_CTX_set1_secretValue(OSSL_CMP_CTX *ctx, const unsigned char *sec, int len) { ASN1_OCTET_STRING *secretValue = NULL; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (ossl_cmp_asn1_octet_string_set1_bytes(&secretValue, sec, len) != 1) return 0; if (ctx->secretValue != NULL) { OPENSSL_cleanse(ctx->secretValue->data, ctx->secretValue->length); ASN1_OCTET_STRING_free(ctx->secretValue); } ctx->secretValue = secretValue; return 1; } #define DEFINE_OSSL_CMP_CTX_get1_certs(FIELD) \ STACK_OF(X509) *OSSL_CMP_CTX_get1_##FIELD(const OSSL_CMP_CTX *ctx) \ { \ if (ctx == NULL) { \ ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \ return NULL; \ } \ return X509_chain_up_ref(ctx->FIELD); \ } /* Returns the cert chain computed by OSSL_CMP_certConf_cb(), NULL on error */ DEFINE_OSSL_CMP_CTX_get1_certs(newChain) #define DEFINE_OSSL_set1_certs(PREFIX, FIELD) \ int PREFIX##_set1_##FIELD(OSSL_CMP_CTX *ctx, STACK_OF(X509) *certs) \ { \ if (ctx == NULL) { \ ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \ return 0; \ } \ OSSL_STACK_OF_X509_free(ctx->FIELD); \ ctx->FIELD = NULL; \ return certs == NULL || (ctx->FIELD = X509_chain_up_ref(certs)) != NULL; \ } /* * Copies any given stack of inbound X509 certificates to newChain * of the OSSL_CMP_CTX structure so that they may be retrieved later. */ DEFINE_OSSL_set1_certs(ossl_cmp_ctx, newChain) /* Returns the stack of extraCerts received in CertRepMessage, NULL on error */ DEFINE_OSSL_CMP_CTX_get1_certs(extraCertsIn) /* * Copies any given stack of inbound X509 certificates to extraCertsIn * of the OSSL_CMP_CTX structure so that they may be retrieved later. */ DEFINE_OSSL_set1_certs(ossl_cmp_ctx, extraCertsIn) /* * Copies any given stack as the new stack of X509 * certificates to send out in the extraCerts field. */ DEFINE_OSSL_set1_certs(OSSL_CMP_CTX, extraCertsOut) /* * Add the given policy info object * to the X509_EXTENSIONS of the requested certificate template. */ int OSSL_CMP_CTX_push0_policy(OSSL_CMP_CTX *ctx, POLICYINFO *pinfo) { if (ctx == NULL || pinfo == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (ctx->policies == NULL && (ctx->policies = CERTIFICATEPOLICIES_new()) == NULL) return 0; return sk_POLICYINFO_push(ctx->policies, pinfo); } /* Add an ITAV for geninfo of the PKI message header */ int OSSL_CMP_CTX_push0_geninfo_ITAV(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *itav) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } return OSSL_CMP_ITAV_push0_stack_item(&ctx->geninfo_ITAVs, itav); } int OSSL_CMP_CTX_reset_geninfo_ITAVs(OSSL_CMP_CTX *ctx) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } OSSL_CMP_ITAVs_free(ctx->geninfo_ITAVs); ctx->geninfo_ITAVs = NULL; return 1; } DEFINE_OSSL_CMP_CTX_get0(geninfo_ITAVs, STACK_OF(OSSL_CMP_ITAV)) /* Add an itav for the body of outgoing general messages */ int OSSL_CMP_CTX_push0_genm_ITAV(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *itav) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } return OSSL_CMP_ITAV_push0_stack_item(&ctx->genm_ITAVs, itav); } /* * Returns a duplicate of the stack of X509 certificates that * were received in the caPubs field of the last CertRepMessage. * Returns NULL on error */ DEFINE_OSSL_CMP_CTX_get1_certs(caPubs) /* * Copies any given stack of certificates to the given * OSSL_CMP_CTX structure so that they may be retrieved later. */ DEFINE_OSSL_set1_certs(ossl_cmp_ctx, caPubs) #define char_dup OPENSSL_strdup #define char_free OPENSSL_free #define DEFINE_OSSL_CMP_CTX_set1(FIELD, TYPE) /* this uses _dup */ \ int OSSL_CMP_CTX_set1_##FIELD(OSSL_CMP_CTX *ctx, const TYPE *val) \ { \ TYPE *val_dup = NULL; \ \ if (ctx == NULL) { \ ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \ return 0; \ } \ \ if (val != NULL && (val_dup = TYPE##_dup(val)) == NULL) \ return 0; \ TYPE##_free(ctx->FIELD); \ ctx->FIELD = val_dup; \ return 1; \ } #define X509_invalid(cert) (!ossl_x509v3_cache_extensions(cert)) #define EVP_PKEY_invalid(key) 0 #define DEFINE_OSSL_set1_up_ref(PREFIX, FIELD, TYPE) \ int PREFIX##_set1_##FIELD(OSSL_CMP_CTX *ctx, TYPE *val) \ { \ if (ctx == NULL) { \ ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \ return 0; \ } \ \ /* prevent misleading error later on malformed cert or provider issue */ \ if (val != NULL && TYPE##_invalid(val)) { \ ERR_raise(ERR_LIB_CMP, CMP_R_POTENTIALLY_INVALID_CERTIFICATE); \ return 0; \ } \ if (val != NULL && !TYPE##_up_ref(val)) \ return 0; \ TYPE##_free(ctx->FIELD); \ ctx->FIELD = val; \ return 1; \ } DEFINE_OSSL_set1_up_ref(ossl_cmp_ctx, validatedSrvCert, X509) /* * Pins the server certificate to be directly trusted (even if it is expired) * for verifying response messages. * Cert pointer is not consumed. It may be NULL to clear the entry. */ DEFINE_OSSL_set1_up_ref(OSSL_CMP_CTX, srvCert, X509) /* Set the X509 name of the recipient to be placed in the PKIHeader */ DEFINE_OSSL_CMP_CTX_set1(recipient, X509_NAME) /* Store the X509 name of the expected sender in the PKIHeader of responses */ DEFINE_OSSL_CMP_CTX_set1(expected_sender, X509_NAME) /* Set the X509 name of the issuer to be placed in the certTemplate */ DEFINE_OSSL_CMP_CTX_set1(issuer, X509_NAME) /* Set the ASN1_INTEGER serial to be placed in the certTemplate for rr */ DEFINE_OSSL_CMP_CTX_set1(serialNumber, ASN1_INTEGER) /* * Set the subject name that will be placed in the certificate * request. This will be the subject name on the received certificate. */ DEFINE_OSSL_CMP_CTX_set1(subjectName, X509_NAME) /* Set the X.509v3 certificate request extensions to be used in IR/CR/KUR */ int OSSL_CMP_CTX_set0_reqExtensions(OSSL_CMP_CTX *ctx, X509_EXTENSIONS *exts) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (sk_GENERAL_NAME_num(ctx->subjectAltNames) > 0 && exts != NULL && X509v3_get_ext_by_NID(exts, NID_subject_alt_name, -1) >= 0) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_SAN_SOURCES); return 0; } X509_EXTENSIONS_free(ctx->reqExtensions); ctx->reqExtensions = exts; return 1; } /* returns 1 if ctx contains a Subject Alternative Name extension, else 0 */ int OSSL_CMP_CTX_reqExtensions_have_SAN(OSSL_CMP_CTX *ctx) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return -1; } /* if one of the following conditions 'fail' this is not an error */ return ctx->reqExtensions != NULL && X509v3_get_ext_by_NID(ctx->reqExtensions, NID_subject_alt_name, -1) >= 0; } /* * Add a GENERAL_NAME structure that will be added to the CRMF * request's extensions field to request subject alternative names. */ int OSSL_CMP_CTX_push1_subjectAltName(OSSL_CMP_CTX *ctx, const GENERAL_NAME *name) { GENERAL_NAME *name_dup; if (ctx == NULL || name == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (OSSL_CMP_CTX_reqExtensions_have_SAN(ctx) == 1) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_SAN_SOURCES); return 0; } if (ctx->subjectAltNames == NULL && (ctx->subjectAltNames = sk_GENERAL_NAME_new_null()) == NULL) return 0; if ((name_dup = GENERAL_NAME_dup(name)) == NULL) return 0; if (!sk_GENERAL_NAME_push(ctx->subjectAltNames, name_dup)) { GENERAL_NAME_free(name_dup); return 0; } return 1; } /* * Set our own client certificate, used for example in KUR and when * doing the IR with existing certificate. */ DEFINE_OSSL_set1_up_ref(OSSL_CMP_CTX, cert, X509) int OSSL_CMP_CTX_build_cert_chain(OSSL_CMP_CTX *ctx, X509_STORE *own_trusted, STACK_OF(X509) *candidates) { STACK_OF(X509) *chain; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (!ossl_x509_add_certs_new(&ctx->untrusted, candidates, X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP)) return 0; ossl_cmp_debug(ctx, "trying to build chain for own CMP signer cert"); chain = X509_build_chain(ctx->cert, ctx->untrusted, own_trusted, 0, ctx->libctx, ctx->propq); if (chain == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_FAILED_BUILDING_OWN_CHAIN); return 0; } ossl_cmp_debug(ctx, "success building chain for own CMP signer cert"); ctx->chain = chain; return 1; } /* * Set the old certificate that we are updating in KUR * or the certificate to be revoked in RR, respectively. * Also used as reference cert (defaulting to cert) for deriving subject DN * and SANs. Its issuer is used as default recipient in the CMP message header. */ DEFINE_OSSL_set1_up_ref(OSSL_CMP_CTX, oldCert, X509) /* Set the PKCS#10 CSR to be sent in P10CR */ DEFINE_OSSL_CMP_CTX_set1(p10CSR, X509_REQ) /* * Set the (newly received in IP/KUP/CP) certificate in the context. * This only permits for one cert to be enrolled at a time. */ DEFINE_OSSL_set0(ossl_cmp_ctx, newCert, X509) /* Get successfully validated server cert, if any, of current transaction */ DEFINE_OSSL_CMP_CTX_get0(validatedSrvCert, X509) /* * Get the (newly received in IP/KUP/CP) client certificate from the context * This only permits for one client cert to be received... */ DEFINE_OSSL_CMP_CTX_get0(newCert, X509) /* Set the client's current private key */ DEFINE_OSSL_set1_up_ref(OSSL_CMP_CTX, pkey, EVP_PKEY) /* Set new key pair. Used e.g. when doing Key Update */ int OSSL_CMP_CTX_set0_newPkey(OSSL_CMP_CTX *ctx, int priv, EVP_PKEY *pkey) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } EVP_PKEY_free(ctx->newPkey); ctx->newPkey = pkey; ctx->newPkey_priv = priv; return 1; } /* Get the private/public key to use for cert enrollment, or NULL on error */ /* In case |priv| == 0, better use ossl_cmp_ctx_get0_newPubkey() below */ EVP_PKEY *OSSL_CMP_CTX_get0_newPkey(const OSSL_CMP_CTX *ctx, int priv) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } if (ctx->newPkey != NULL) return priv && !ctx->newPkey_priv ? NULL : ctx->newPkey; if (ctx->p10CSR != NULL) return priv ? NULL : X509_REQ_get0_pubkey(ctx->p10CSR); return ctx->pkey; /* may be NULL */ } EVP_PKEY *ossl_cmp_ctx_get0_newPubkey(const OSSL_CMP_CTX *ctx) { if (!ossl_assert(ctx != NULL)) return NULL; if (ctx->newPkey != NULL) return ctx->newPkey; if (ctx->p10CSR != NULL) return X509_REQ_get0_pubkey(ctx->p10CSR); if (ctx->oldCert != NULL) return X509_get0_pubkey(ctx->oldCert); if (ctx->cert != NULL) return X509_get0_pubkey(ctx->cert); return ctx->pkey; } #define DEFINE_set1_ASN1_OCTET_STRING(PREFIX, FIELD) \ int PREFIX##_set1_##FIELD(OSSL_CMP_CTX *ctx, const ASN1_OCTET_STRING *id) \ { \ if (ctx == NULL) { \ ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \ return 0; \ } \ return ossl_cmp_asn1_octet_string_set1(&ctx->FIELD, id); \ } /* Set the given transactionID to the context */ DEFINE_set1_ASN1_OCTET_STRING(OSSL_CMP_CTX, transactionID) /* Set the nonce to be used for the recipNonce in the message created next */ DEFINE_set1_ASN1_OCTET_STRING(ossl_cmp_ctx, recipNonce) /* Stores the given nonce as the last senderNonce sent out */ DEFINE_set1_ASN1_OCTET_STRING(OSSL_CMP_CTX, senderNonce) /* store the first req sender nonce for verifying delayed delivery */ DEFINE_set1_ASN1_OCTET_STRING(ossl_cmp_ctx, first_senderNonce) /* Set the proxy server to use for HTTP(S) connections */ DEFINE_OSSL_CMP_CTX_set1(proxy, char) /* Set the (HTTP) hostname of the CMP server */ DEFINE_OSSL_CMP_CTX_set1(server, char) /* Set the server exclusion list of the HTTP proxy server */ DEFINE_OSSL_CMP_CTX_set1(no_proxy, char) #ifndef OPENSSL_NO_HTTP /* Set the http connect/disconnect callback function to be used for HTTP(S) */ DEFINE_OSSL_set(OSSL_CMP_CTX, http_cb, OSSL_HTTP_bio_cb_t) /* Set argument optionally to be used by the http connect/disconnect callback */ DEFINE_OSSL_set(OSSL_CMP_CTX, http_cb_arg, void *) /* * Get argument optionally to be used by the http connect/disconnect callback * Returns callback argument set previously (NULL if not set or on error) */ DEFINE_OSSL_get(OSSL_CMP_CTX, http_cb_arg, void *, NULL) #endif /* Set callback function for sending CMP request and receiving response */ DEFINE_OSSL_set(OSSL_CMP_CTX, transfer_cb, OSSL_CMP_transfer_cb_t) /* Set argument optionally to be used by the transfer callback */ DEFINE_OSSL_set(OSSL_CMP_CTX, transfer_cb_arg, void *) /* * Get argument optionally to be used by the transfer callback. * Returns callback argument set previously (NULL if not set or on error) */ DEFINE_OSSL_get(OSSL_CMP_CTX, transfer_cb_arg, void *, NULL) /** Set the HTTP server port to be used */ DEFINE_OSSL_set(OSSL_CMP_CTX, serverPort, int) /* Set the HTTP path to be used on the server (e.g "pkix/") */ DEFINE_OSSL_CMP_CTX_set1(serverPath, char) /* Set the failInfo error code as bit encoding in OSSL_CMP_CTX */ DEFINE_OSSL_set(ossl_cmp_ctx, failInfoCode, int) /* * Get the failInfo error code in OSSL_CMP_CTX as bit encoding. * Returns bit string as integer on success, -1 on error */ DEFINE_OSSL_get(OSSL_CMP_CTX, failInfoCode, int, -1) /* Set a Boolean or integer option of the context to the "val" arg */ int OSSL_CMP_CTX_set_option(OSSL_CMP_CTX *ctx, int opt, int val) { int min_val; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } switch (opt) { case OSSL_CMP_OPT_REVOCATION_REASON: min_val = OCSP_REVOKED_STATUS_NOSTATUS; break; case OSSL_CMP_OPT_POPO_METHOD: min_val = OSSL_CRMF_POPO_NONE; break; default: min_val = 0; break; } if (val < min_val) { ERR_raise(ERR_LIB_CMP, CMP_R_VALUE_TOO_SMALL); return 0; } switch (opt) { case OSSL_CMP_OPT_LOG_VERBOSITY: if (val > OSSL_CMP_LOG_MAX) { ERR_raise(ERR_LIB_CMP, CMP_R_VALUE_TOO_LARGE); return 0; } ctx->log_verbosity = val; break; case OSSL_CMP_OPT_IMPLICIT_CONFIRM: ctx->implicitConfirm = val; break; case OSSL_CMP_OPT_DISABLE_CONFIRM: ctx->disableConfirm = val; break; case OSSL_CMP_OPT_UNPROTECTED_SEND: ctx->unprotectedSend = val; break; case OSSL_CMP_OPT_UNPROTECTED_ERRORS: ctx->unprotectedErrors = val; break; case OSSL_CMP_OPT_NO_CACHE_EXTRACERTS: ctx->noCacheExtraCerts = val; break; case OSSL_CMP_OPT_VALIDITY_DAYS: ctx->days = val; break; case OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT: ctx->SubjectAltName_nodefault = val; break; case OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL: ctx->setSubjectAltNameCritical = val; break; case OSSL_CMP_OPT_POLICIES_CRITICAL: ctx->setPoliciesCritical = val; break; case OSSL_CMP_OPT_IGNORE_KEYUSAGE: ctx->ignore_keyusage = val; break; case OSSL_CMP_OPT_POPO_METHOD: if (val > OSSL_CRMF_POPO_KEYAGREE) { ERR_raise(ERR_LIB_CMP, CMP_R_VALUE_TOO_LARGE); return 0; } ctx->popoMethod = val; break; case OSSL_CMP_OPT_DIGEST_ALGNID: if (!cmp_ctx_set_md(ctx, &ctx->digest, val)) return 0; break; case OSSL_CMP_OPT_OWF_ALGNID: if (!cmp_ctx_set_md(ctx, &ctx->pbm_owf, val)) return 0; break; case OSSL_CMP_OPT_MAC_ALGNID: ctx->pbm_mac = val; break; case OSSL_CMP_OPT_KEEP_ALIVE: ctx->keep_alive = val; break; case OSSL_CMP_OPT_MSG_TIMEOUT: ctx->msg_timeout = val; break; case OSSL_CMP_OPT_TOTAL_TIMEOUT: ctx->total_timeout = val; break; case OSSL_CMP_OPT_USE_TLS: ctx->tls_used = val; break; case OSSL_CMP_OPT_PERMIT_TA_IN_EXTRACERTS_FOR_IR: ctx->permitTAInExtraCertsForIR = val; break; case OSSL_CMP_OPT_REVOCATION_REASON: if (val > OCSP_REVOKED_STATUS_AACOMPROMISE) { ERR_raise(ERR_LIB_CMP, CMP_R_VALUE_TOO_LARGE); return 0; } ctx->revocationReason = val; break; default: ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_OPTION); return 0; } return 1; } /* * Reads a Boolean or integer option value from the context. * Returns -1 on error (which is the default OSSL_CMP_OPT_REVOCATION_REASON) */ int OSSL_CMP_CTX_get_option(const OSSL_CMP_CTX *ctx, int opt) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return -1; } switch (opt) { case OSSL_CMP_OPT_LOG_VERBOSITY: return ctx->log_verbosity; case OSSL_CMP_OPT_IMPLICIT_CONFIRM: return ctx->implicitConfirm; case OSSL_CMP_OPT_DISABLE_CONFIRM: return ctx->disableConfirm; case OSSL_CMP_OPT_UNPROTECTED_SEND: return ctx->unprotectedSend; case OSSL_CMP_OPT_UNPROTECTED_ERRORS: return ctx->unprotectedErrors; case OSSL_CMP_OPT_NO_CACHE_EXTRACERTS: return ctx->noCacheExtraCerts; case OSSL_CMP_OPT_VALIDITY_DAYS: return ctx->days; case OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT: return ctx->SubjectAltName_nodefault; case OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL: return ctx->setSubjectAltNameCritical; case OSSL_CMP_OPT_POLICIES_CRITICAL: return ctx->setPoliciesCritical; case OSSL_CMP_OPT_IGNORE_KEYUSAGE: return ctx->ignore_keyusage; case OSSL_CMP_OPT_POPO_METHOD: return ctx->popoMethod; case OSSL_CMP_OPT_DIGEST_ALGNID: return EVP_MD_get_type(ctx->digest); case OSSL_CMP_OPT_OWF_ALGNID: return EVP_MD_get_type(ctx->pbm_owf); case OSSL_CMP_OPT_MAC_ALGNID: return ctx->pbm_mac; case OSSL_CMP_OPT_KEEP_ALIVE: return ctx->keep_alive; case OSSL_CMP_OPT_MSG_TIMEOUT: return ctx->msg_timeout; case OSSL_CMP_OPT_TOTAL_TIMEOUT: return ctx->total_timeout; case OSSL_CMP_OPT_USE_TLS: return ctx->tls_used; case OSSL_CMP_OPT_PERMIT_TA_IN_EXTRACERTS_FOR_IR: return ctx->permitTAInExtraCertsForIR; case OSSL_CMP_OPT_REVOCATION_REASON: return ctx->revocationReason; default: ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_OPTION); return -1; } }
./openssl/crypto/cmp/cmp_local.h
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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_CMP_LOCAL_H # define OSSL_CRYPTO_CMP_LOCAL_H # include "internal/cryptlib.h" # include <openssl/cmp.h> # include <openssl/err.h> /* explicit #includes not strictly needed since implied by the above: */ # include <openssl/crmf.h> # include <openssl/types.h> # include <openssl/safestack.h> # include <openssl/x509.h> # include <openssl/x509v3.h> # include "crypto/x509.h" # define IS_NULL_DN(name) (X509_NAME_get_entry(name, 0) == NULL) /* * this structure is used to store the context for CMP sessions */ struct ossl_cmp_ctx_st { OSSL_LIB_CTX *libctx; char *propq; OSSL_CMP_log_cb_t log_cb; /* log callback for error/debug/etc. output */ OSSL_CMP_severity log_verbosity; /* level of verbosity of log output */ /* message transfer */ OSSL_CMP_transfer_cb_t transfer_cb; /* default: OSSL_CMP_MSG_http_perform */ void *transfer_cb_arg; /* allows to store optional argument to cb */ /* HTTP-based transfer */ OSSL_HTTP_REQ_CTX *http_ctx; char *serverPath; char *server; int serverPort; char *proxy; char *no_proxy; int keep_alive; /* persistent connection: 0=no, 1=prefer, 2=require */ int msg_timeout; /* max seconds to wait for each CMP message round trip */ int total_timeout; /* max number of seconds an enrollment may take, incl. */ int tls_used; /* whether to use TLS for client-side HTTP connections */ /* attempts polling for a response if a 'waiting' PKIStatus is received */ time_t end_time; /* session start time + totaltimeout */ # ifndef OPENSSL_NO_HTTP OSSL_HTTP_bio_cb_t http_cb; void *http_cb_arg; /* allows to store optional argument to cb */ # endif /* server authentication */ /* * unprotectedErrors may be set as workaround for broken server responses: * accept missing or invalid protection of regular error messages, negative * certificate responses (ip/cp/kup), revocation responses (rp), and PKIConf */ int unprotectedErrors; int noCacheExtraCerts; X509 *srvCert; /* certificate used to identify the server */ X509 *validatedSrvCert; /* caches any already validated server cert */ X509_NAME *expected_sender; /* expected sender in header of response */ X509_STORE *trusted; /* trust store maybe w CRLs and cert verify callback */ STACK_OF(X509) *untrusted; /* untrusted (intermediate CA) certs */ int ignore_keyusage; /* ignore key usage entry when validating certs */ /* * permitTAInExtraCertsForIR allows use of root certs in extracerts * when validating message protection; this is used for 3GPP-style E.7 */ int permitTAInExtraCertsForIR; /* client authentication */ int unprotectedSend; /* send unprotected PKI messages */ X509 *cert; /* protection cert used to identify and sign for MSG_SIG_ALG */ STACK_OF(X509) *chain; /* (cached) chain of protection cert including it */ EVP_PKEY *pkey; /* the key pair corresponding to cert */ ASN1_OCTET_STRING *referenceValue; /* optional username for MSG_MAC_ALG */ ASN1_OCTET_STRING *secretValue; /* password/shared secret for MSG_MAC_ALG */ /* PBMParameters for MSG_MAC_ALG */ size_t pbm_slen; /* salt length, currently fixed to 16 */ EVP_MD *pbm_owf; /* one-way function (OWF), default: SHA256 */ int pbm_itercnt; /* OWF iteration count, currently fixed to 500 */ int pbm_mac; /* NID of MAC algorithm, default: HMAC-SHA1 as per RFC 4210 */ /* CMP message header and extra certificates */ X509_NAME *recipient; /* to set in recipient in pkiheader */ EVP_MD *digest; /* digest used in MSG_SIG_ALG and POPO, default SHA256 */ ASN1_OCTET_STRING *transactionID; /* the current transaction ID */ ASN1_OCTET_STRING *senderNonce; /* last nonce sent */ ASN1_OCTET_STRING *recipNonce; /* last nonce received */ ASN1_OCTET_STRING *first_senderNonce; /* sender nonce when starting to poll */ ASN1_UTF8STRING *freeText; /* optional string to include each msg */ STACK_OF(OSSL_CMP_ITAV) *geninfo_ITAVs; int implicitConfirm; /* set implicitConfirm in IR/KUR/CR messages */ int disableConfirm; /* disable certConf in IR/KUR/CR for broken servers */ STACK_OF(X509) *extraCertsOut; /* to be included in request messages */ /* certificate template */ EVP_PKEY *newPkey; /* explicit new private/public key for cert enrollment */ int newPkey_priv; /* flag indicating if newPkey contains private key */ X509_NAME *issuer; /* issuer name to used in cert template, also in rr */ ASN1_INTEGER *serialNumber; /* certificate serial number to use in rr */ int days; /* Number of days new certificates are asked to be valid for */ X509_NAME *subjectName; /* subject name to be used in cert template */ STACK_OF(GENERAL_NAME) *subjectAltNames; /* to add to the cert template */ int SubjectAltName_nodefault; int setSubjectAltNameCritical; X509_EXTENSIONS *reqExtensions; /* exts to be added to cert template */ CERTIFICATEPOLICIES *policies; /* policies to be included in extensions */ int setPoliciesCritical; int popoMethod; /* Proof-of-possession mechanism; default: signature */ X509 *oldCert; /* cert to be updated (via KUR) or to be revoked (via RR) */ X509_REQ *p10CSR; /* for P10CR: PKCS#10 CSR to be sent */ /* misc body contents */ int revocationReason; /* revocation reason code to be included in RR */ STACK_OF(OSSL_CMP_ITAV) *genm_ITAVs; /* content of general message */ /* result returned in responses, so far supporting only one certResponse */ int status; /* PKIStatus of last received IP/CP/KUP/RP/error or -1 */ OSSL_CMP_PKIFREETEXT *statusString; /* of last IP/CP/KUP/RP/error */ int failInfoCode; /* failInfoCode of last received IP/CP/KUP/error, or -1 */ X509 *newCert; /* newly enrolled cert received from the CA */ STACK_OF(X509) *newChain; /* chain of newly enrolled cert received */ STACK_OF(X509) *caPubs; /* CA certs received from server (in IP message) */ STACK_OF(X509) *extraCertsIn; /* extraCerts received from server */ /* certificate confirmation */ OSSL_CMP_certConf_cb_t certConf_cb; /* callback for app checking new cert */ void *certConf_cb_arg; /* allows to store an argument individual to cb */ } /* OSSL_CMP_CTX */; /* * ########################################################################## * ASN.1 DECLARATIONS * ########################################################################## */ /*- * RevAnnContent ::= SEQUENCE { * status PKIStatus, * certId CertId, * willBeRevokedAt GeneralizedTime, * badSinceDate GeneralizedTime, * crlDetails Extensions OPTIONAL * -- extra CRL details (e.g., crl number, reason, location, etc.) * } */ typedef struct ossl_cmp_revanncontent_st { ASN1_INTEGER *status; OSSL_CRMF_CERTID *certId; ASN1_GENERALIZEDTIME *willBeRevokedAt; ASN1_GENERALIZEDTIME *badSinceDate; X509_EXTENSIONS *crlDetails; } OSSL_CMP_REVANNCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_REVANNCONTENT) /*- * Challenge ::= SEQUENCE { * owf AlgorithmIdentifier OPTIONAL, * * -- MUST be present in the first Challenge; MAY be omitted in * -- any subsequent Challenge in POPODecKeyChallContent (if * -- omitted, then the owf used in the immediately preceding * -- Challenge is to be used). * * witness OCTET STRING, * -- the result of applying the one-way function (owf) to a * -- randomly-generated INTEGER, A. [Note that a different * -- INTEGER MUST be used for each Challenge.] * challenge OCTET STRING * -- the encryption (under the public key for which the cert. * -- request is being made) of Rand, where Rand is specified as * -- Rand ::= SEQUENCE { * -- int INTEGER, * -- - the randomly-generated INTEGER A (above) * -- sender GeneralName * -- - the sender's name (as included in PKIHeader) * -- } * } */ typedef struct ossl_cmp_challenge_st { X509_ALGOR *owf; ASN1_OCTET_STRING *witness; ASN1_OCTET_STRING *challenge; } OSSL_CMP_CHALLENGE; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_CHALLENGE) /*- * CAKeyUpdAnnContent ::= SEQUENCE { * oldWithNew Certificate, * newWithOld Certificate, * newWithNew Certificate * } */ typedef struct ossl_cmp_cakeyupdanncontent_st { X509 *oldWithNew; X509 *newWithOld; X509 *newWithNew; } OSSL_CMP_CAKEYUPDANNCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_CAKEYUPDANNCONTENT) typedef struct ossl_cmp_rootcakeyupdate_st OSSL_CMP_ROOTCAKEYUPDATE; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_ROOTCAKEYUPDATE) /*- * declared already here as it will be used in OSSL_CMP_MSG (nested) and * infoType and infoValue */ typedef STACK_OF(OSSL_CMP_MSG) OSSL_CMP_MSGS; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_MSGS) /*- * InfoTypeAndValue ::= SEQUENCE { * infoType OBJECT IDENTIFIER, * infoValue ANY DEFINED BY infoType OPTIONAL * } */ struct ossl_cmp_itav_st { ASN1_OBJECT *infoType; union { char *ptr; /* NID_id_it_caProtEncCert - CA Protocol Encryption Certificate */ X509 *caProtEncCert; /* NID_id_it_signKeyPairTypes - Signing Key Pair Types */ STACK_OF(X509_ALGOR) *signKeyPairTypes; /* NID_id_it_encKeyPairTypes - Encryption/Key Agreement Key Pair Types */ STACK_OF(X509_ALGOR) *encKeyPairTypes; /* NID_id_it_preferredSymmAlg - Preferred Symmetric Algorithm */ X509_ALGOR *preferredSymmAlg; /* NID_id_it_caKeyUpdateInfo - Updated CA Key Pair */ OSSL_CMP_CAKEYUPDANNCONTENT *caKeyUpdateInfo; /* NID_id_it_currentCRL - CRL */ X509_CRL *currentCRL; /* NID_id_it_unsupportedOIDs - Unsupported Object Identifiers */ STACK_OF(ASN1_OBJECT) *unsupportedOIDs; /* NID_id_it_keyPairParamReq - Key Pair Parameters Request */ ASN1_OBJECT *keyPairParamReq; /* NID_id_it_keyPairParamRep - Key Pair Parameters Response */ X509_ALGOR *keyPairParamRep; /* NID_id_it_revPassphrase - Revocation Passphrase */ OSSL_CRMF_ENCRYPTEDVALUE *revPassphrase; /* NID_id_it_implicitConfirm - ImplicitConfirm */ ASN1_NULL *implicitConfirm; /* NID_id_it_confirmWaitTime - ConfirmWaitTime */ ASN1_GENERALIZEDTIME *confirmWaitTime; /* NID_id_it_origPKIMessage - origPKIMessage */ OSSL_CMP_MSGS *origPKIMessage; /* NID_id_it_suppLangTags - Supported Language Tags */ STACK_OF(ASN1_UTF8STRING) *suppLangTagsValue; /* NID_id_it_certProfile - Certificate Profile */ STACK_OF(ASN1_UTF8STRING) *certProfile; /* NID_id_it_caCerts - CA Certificates */ STACK_OF(X509) *caCerts; /* NID_id_it_rootCaCert - Root CA Certificate */ X509 *rootCaCert; /* NID_id_it_rootCaKeyUpdate - Root CA Certificate Update */ OSSL_CMP_ROOTCAKEYUPDATE *rootCaKeyUpdate; /* this is to be used for so far undeclared objects */ ASN1_TYPE *other; } infoValue; } /* OSSL_CMP_ITAV */; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_ITAV) typedef struct ossl_cmp_certorenccert_st { int type; union { X509 *certificate; OSSL_CRMF_ENCRYPTEDVALUE *encryptedCert; } value; } OSSL_CMP_CERTORENCCERT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_CERTORENCCERT) /*- * CertifiedKeyPair ::= SEQUENCE { * certOrEncCert CertOrEncCert, * privateKey [0] EncryptedValue OPTIONAL, * -- see [CRMF] for comment on encoding * publicationInfo [1] PKIPublicationInfo OPTIONAL * } */ typedef struct ossl_cmp_certifiedkeypair_st { OSSL_CMP_CERTORENCCERT *certOrEncCert; OSSL_CRMF_ENCRYPTEDVALUE *privateKey; OSSL_CRMF_PKIPUBLICATIONINFO *publicationInfo; } OSSL_CMP_CERTIFIEDKEYPAIR; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_CERTIFIEDKEYPAIR) /*- * PKIStatusInfo ::= SEQUENCE { * status PKIStatus, * statusString PKIFreeText OPTIONAL, * failInfo PKIFailureInfo OPTIONAL * } */ struct ossl_cmp_pkisi_st { OSSL_CMP_PKISTATUS *status; OSSL_CMP_PKIFREETEXT *statusString; OSSL_CMP_PKIFAILUREINFO *failInfo; } /* OSSL_CMP_PKISI */; /*- * RevReqContent ::= SEQUENCE OF RevDetails * * RevDetails ::= SEQUENCE { * certDetails CertTemplate, * crlEntryDetails Extensions OPTIONAL * } */ struct ossl_cmp_revdetails_st { OSSL_CRMF_CERTTEMPLATE *certDetails; X509_EXTENSIONS *crlEntryDetails; } /* OSSL_CMP_REVDETAILS */; typedef struct ossl_cmp_revdetails_st OSSL_CMP_REVDETAILS; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_REVDETAILS) DEFINE_STACK_OF(OSSL_CMP_REVDETAILS) /*- * RevRepContent ::= SEQUENCE { * status SEQUENCE SIZE (1..MAX) OF PKIStatusInfo, * -- in same order as was sent in RevReqContent * revCerts [0] SEQUENCE SIZE (1..MAX) OF CertId * OPTIONAL, * -- IDs for which revocation was requested * -- (same order as status) * crls [1] SEQUENCE SIZE (1..MAX) OF CertificateList * OPTIONAL * -- the resulting CRLs (there may be more than one) * } */ struct ossl_cmp_revrepcontent_st { STACK_OF(OSSL_CMP_PKISI) *status; STACK_OF(OSSL_CRMF_CERTID) *revCerts; STACK_OF(X509_CRL) *crls; } /* OSSL_CMP_REVREPCONTENT */; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_REVREPCONTENT) /*- * KeyRecRepContent ::= SEQUENCE { * status PKIStatusInfo, * newSigCert [0] Certificate OPTIONAL, * caCerts [1] SEQUENCE SIZE (1..MAX) OF * Certificate OPTIONAL, * keyPairHist [2] SEQUENCE SIZE (1..MAX) OF * CertifiedKeyPair OPTIONAL * } */ typedef struct ossl_cmp_keyrecrepcontent_st { OSSL_CMP_PKISI *status; X509 *newSigCert; STACK_OF(X509) *caCerts; STACK_OF(OSSL_CMP_CERTIFIEDKEYPAIR) *keyPairHist; } OSSL_CMP_KEYRECREPCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_KEYRECREPCONTENT) /*- * ErrorMsgContent ::= SEQUENCE { * pKIStatusInfo PKIStatusInfo, * errorCode INTEGER OPTIONAL, * -- implementation-specific error codes * errorDetails PKIFreeText OPTIONAL * -- implementation-specific error details * } */ typedef struct ossl_cmp_errormsgcontent_st { OSSL_CMP_PKISI *pKIStatusInfo; ASN1_INTEGER *errorCode; OSSL_CMP_PKIFREETEXT *errorDetails; } OSSL_CMP_ERRORMSGCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_ERRORMSGCONTENT) /*- * CertConfirmContent ::= SEQUENCE OF CertStatus * * CertStatus ::= SEQUENCE { * certHash OCTET STRING, * -- the hash of the certificate, using the same hash algorithm * -- as is used to create and verify the certificate signature * certReqId INTEGER, * -- to match this confirmation with the corresponding req/rep * statusInfo PKIStatusInfo OPTIONAL, * hashAlg [0] AlgorithmIdentifier OPTIONAL * } */ struct ossl_cmp_certstatus_st { ASN1_OCTET_STRING *certHash; ASN1_INTEGER *certReqId; OSSL_CMP_PKISI *statusInfo; X509_ALGOR *hashAlg; /* 0 */ } /* OSSL_CMP_CERTSTATUS */; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_CERTSTATUS) typedef STACK_OF(OSSL_CMP_CERTSTATUS) OSSL_CMP_CERTCONFIRMCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_CERTCONFIRMCONTENT) /*- * CertResponse ::= SEQUENCE { * certReqId INTEGER, * -- to match this response with corresponding request (a value * -- of -1 is to be used if certReqId is not specified in the * -- corresponding request) * status PKIStatusInfo, * certifiedKeyPair CertifiedKeyPair OPTIONAL, * rspInfo OCTET STRING OPTIONAL * -- analogous to the id-regInfo-utf8Pairs string defined * -- for regInfo in CertReqMsg [CRMF] * } */ struct ossl_cmp_certresponse_st { ASN1_INTEGER *certReqId; OSSL_CMP_PKISI *status; OSSL_CMP_CERTIFIEDKEYPAIR *certifiedKeyPair; ASN1_OCTET_STRING *rspInfo; } /* OSSL_CMP_CERTRESPONSE */; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_CERTRESPONSE) /*- * CertRepMessage ::= SEQUENCE { * caPubs [1] SEQUENCE SIZE (1..MAX) OF CMPCertificate * OPTIONAL, * response SEQUENCE OF CertResponse * } */ struct ossl_cmp_certrepmessage_st { STACK_OF(X509) *caPubs; STACK_OF(OSSL_CMP_CERTRESPONSE) *response; } /* OSSL_CMP_CERTREPMESSAGE */; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_CERTREPMESSAGE) /*- * PollReqContent ::= SEQUENCE OF SEQUENCE { * certReqId INTEGER * } */ typedef struct ossl_cmp_pollreq_st { ASN1_INTEGER *certReqId; } OSSL_CMP_POLLREQ; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_POLLREQ) DEFINE_STACK_OF(OSSL_CMP_POLLREQ) typedef STACK_OF(OSSL_CMP_POLLREQ) OSSL_CMP_POLLREQCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_POLLREQCONTENT) /*- * PollRepContent ::= SEQUENCE OF SEQUENCE { * certReqId INTEGER, * checkAfter INTEGER, -- time in seconds * reason PKIFreeText OPTIONAL * } */ struct ossl_cmp_pollrep_st { ASN1_INTEGER *certReqId; ASN1_INTEGER *checkAfter; OSSL_CMP_PKIFREETEXT *reason; } /* OSSL_CMP_POLLREP */; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_POLLREP) DEFINE_STACK_OF(OSSL_CMP_POLLREP) DECLARE_ASN1_FUNCTIONS(OSSL_CMP_POLLREPCONTENT) /*- * PKIHeader ::= SEQUENCE { * pvno INTEGER { cmp1999(1), cmp2000(2), cmp2021(3) }, * sender GeneralName, * -- identifies the sender * recipient GeneralName, * -- identifies the intended recipient * messageTime [0] GeneralizedTime OPTIONAL, * -- time of production of this message (used when sender * -- believes that the transport will be "suitable"; i.e., * -- that the time will still be meaningful upon receipt) * protectionAlg [1] AlgorithmIdentifier OPTIONAL, * -- algorithm used for calculation of protection bits * senderKID [2] KeyIdentifier OPTIONAL, * recipKID [3] KeyIdentifier OPTIONAL, * -- to identify specific keys used for protection * transactionID [4] OCTET STRING OPTIONAL, * -- identifies the transaction; i.e., this will be the same in * -- corresponding request, response, certConf, and PKIConf * -- messages * senderNonce [5] OCTET STRING OPTIONAL, * recipNonce [6] OCTET STRING OPTIONAL, * -- nonces used to provide replay protection, senderNonce * -- is inserted by the creator of this message; recipNonce * -- is a nonce previously inserted in a related message by * -- the intended recipient of this message * freeText [7] PKIFreeText OPTIONAL, * -- this may be used to indicate context-specific instructions * -- (this field is intended for human consumption) * generalInfo [8] SEQUENCE SIZE (1..MAX) OF * InfoTypeAndValue OPTIONAL * -- this may be used to convey context-specific information * -- (this field not primarily intended for human consumption) * } */ struct ossl_cmp_pkiheader_st { ASN1_INTEGER *pvno; GENERAL_NAME *sender; GENERAL_NAME *recipient; ASN1_GENERALIZEDTIME *messageTime; /* 0 */ X509_ALGOR *protectionAlg; /* 1 */ ASN1_OCTET_STRING *senderKID; /* 2 */ ASN1_OCTET_STRING *recipKID; /* 3 */ ASN1_OCTET_STRING *transactionID; /* 4 */ ASN1_OCTET_STRING *senderNonce; /* 5 */ ASN1_OCTET_STRING *recipNonce; /* 6 */ OSSL_CMP_PKIFREETEXT *freeText; /* 7 */ STACK_OF(OSSL_CMP_ITAV) *generalInfo; /* 8 */ } /* OSSL_CMP_PKIHEADER */; typedef STACK_OF(OSSL_CMP_CHALLENGE) OSSL_CMP_POPODECKEYCHALLCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_POPODECKEYCHALLCONTENT) typedef STACK_OF(ASN1_INTEGER) OSSL_CMP_POPODECKEYRESPCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_POPODECKEYRESPCONTENT) typedef STACK_OF(OSSL_CMP_REVDETAILS) OSSL_CMP_REVREQCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_REVREQCONTENT) typedef STACK_OF(X509_CRL) OSSL_CMP_CRLANNCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_CRLANNCONTENT) typedef STACK_OF(OSSL_CMP_ITAV) OSSL_CMP_GENMSGCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_GENMSGCONTENT) typedef STACK_OF(OSSL_CMP_ITAV) OSSL_CMP_GENREPCONTENT; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_GENREPCONTENT) /*- * PKIBody ::= CHOICE { -- message-specific body elements * ir [0] CertReqMessages, --Initialization Request * ip [1] CertRepMessage, --Initialization Response * cr [2] CertReqMessages, --Certification Request * cp [3] CertRepMessage, --Certification Response * p10cr [4] CertificationRequest, --imported from [PKCS10] * popdecc [5] POPODecKeyChallContent, --pop Challenge * popdecr [6] POPODecKeyRespContent, --pop Response * kur [7] CertReqMessages, --Key Update Request * kup [8] CertRepMessage, --Key Update Response * krr [9] CertReqMessages, --Key Recovery Request * krp [10] KeyRecRepContent, --Key Recovery Response * rr [11] RevReqContent, --Revocation Request * rp [12] RevRepContent, --Revocation Response * ccr [13] CertReqMessages, --Cross-Cert. Request * ccp [14] CertRepMessage, --Cross-Cert. Response * ckuann [15] CAKeyUpdAnnContent, --CA Key Update Ann. * cann [16] CertAnnContent, --Certificate Ann. * rann [17] RevAnnContent, --Revocation Ann. * crlann [18] CRLAnnContent, --CRL Announcement * pkiconf [19] PKIConfirmContent, --Confirmation * nested [20] NestedMessageContent, --Nested Message * genm [21] GenMsgContent, --General Message * genp [22] GenRepContent, --General Response * error [23] ErrorMsgContent, --Error Message * certConf [24] CertConfirmContent, --Certificate confirm * pollReq [25] PollReqContent, --Polling request * pollRep [26] PollRepContent --Polling response * } */ typedef struct ossl_cmp_pkibody_st { int type; union { OSSL_CRMF_MSGS *ir; /* 0 */ OSSL_CMP_CERTREPMESSAGE *ip; /* 1 */ OSSL_CRMF_MSGS *cr; /* 2 */ OSSL_CMP_CERTREPMESSAGE *cp; /* 3 */ /*- * p10cr [4] CertificationRequest, --imported from [PKCS10] * * PKCS10_CERTIFICATIONREQUEST is effectively X509_REQ * so it is used directly */ X509_REQ *p10cr; /* 4 */ /*- * popdecc [5] POPODecKeyChallContent, --pop Challenge * * POPODecKeyChallContent ::= SEQUENCE OF Challenge */ OSSL_CMP_POPODECKEYCHALLCONTENT *popdecc; /* 5 */ /*- * popdecr [6] POPODecKeyRespContent, --pop Response * * POPODecKeyRespContent ::= SEQUENCE OF INTEGER */ OSSL_CMP_POPODECKEYRESPCONTENT *popdecr; /* 6 */ OSSL_CRMF_MSGS *kur; /* 7 */ OSSL_CMP_CERTREPMESSAGE *kup; /* 8 */ OSSL_CRMF_MSGS *krr; /* 9 */ /*- * krp [10] KeyRecRepContent, --Key Recovery Response */ OSSL_CMP_KEYRECREPCONTENT *krp; /* 10 */ /*- * rr [11] RevReqContent, --Revocation Request */ OSSL_CMP_REVREQCONTENT *rr; /* 11 */ /*- * rp [12] RevRepContent, --Revocation Response */ OSSL_CMP_REVREPCONTENT *rp; /* 12 */ /*- * ccr [13] CertReqMessages, --Cross-Cert. Request */ OSSL_CRMF_MSGS *ccr; /* 13 */ /*- * ccp [14] CertRepMessage, --Cross-Cert. Response */ OSSL_CMP_CERTREPMESSAGE *ccp; /* 14 */ /*- * ckuann [15] CAKeyUpdAnnContent, --CA Key Update Ann. */ OSSL_CMP_CAKEYUPDANNCONTENT *ckuann; /* 15 */ /*- * cann [16] CertAnnContent, --Certificate Ann. * OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ X509 *cann; /* 16 */ /*- * rann [17] RevAnnContent, --Revocation Ann. */ OSSL_CMP_REVANNCONTENT *rann; /* 17 */ /*- * crlann [18] CRLAnnContent, --CRL Announcement * CRLAnnContent ::= SEQUENCE OF CertificateList */ OSSL_CMP_CRLANNCONTENT *crlann; /* 18 */ /*- * PKIConfirmContent ::= NULL * pkiconf [19] PKIConfirmContent, --Confirmation * OSSL_CMP_PKICONFIRMCONTENT would be only a typedef of ASN1_NULL * OSSL_CMP_CONFIRMCONTENT *pkiconf; * * NOTE: this should ASN1_NULL according to the RFC * but there might be a struct in it when sent from faulty servers... */ ASN1_TYPE *pkiconf; /* 19 */ /*- * nested [20] NestedMessageContent, --Nested Message * NestedMessageContent ::= PKIMessages */ OSSL_CMP_MSGS *nested; /* 20 */ /*- * genm [21] GenMsgContent, --General Message * GenMsgContent ::= SEQUENCE OF InfoTypeAndValue */ OSSL_CMP_GENMSGCONTENT *genm; /* 21 */ /*- * genp [22] GenRepContent, --General Response * GenRepContent ::= SEQUENCE OF InfoTypeAndValue */ OSSL_CMP_GENREPCONTENT *genp; /* 22 */ /*- * error [23] ErrorMsgContent, --Error Message */ OSSL_CMP_ERRORMSGCONTENT *error; /* 23 */ /*- * certConf [24] CertConfirmContent, --Certificate confirm */ OSSL_CMP_CERTCONFIRMCONTENT *certConf; /* 24 */ /*- * pollReq [25] PollReqContent, --Polling request */ OSSL_CMP_POLLREQCONTENT *pollReq; /* 25 */ /*- * pollRep [26] PollRepContent --Polling response */ OSSL_CMP_POLLREPCONTENT *pollRep; /* 26 */ } value; } OSSL_CMP_PKIBODY; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_PKIBODY) /*- * PKIProtection ::= BIT STRING * * PKIMessages ::= SEQUENCE SIZE (1..MAX) OF PKIMessage * * PKIMessage ::= SEQUENCE { * header PKIHeader, * body PKIBody, * protection [0] PKIProtection OPTIONAL, * extraCerts [1] SEQUENCE SIZE (1..MAX) OF CMPCertificate * OPTIONAL * } */ struct ossl_cmp_msg_st { OSSL_CMP_PKIHEADER *header; OSSL_CMP_PKIBODY *body; ASN1_BIT_STRING *protection; /* 0 */ /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ STACK_OF(X509) *extraCerts; /* 1 */ OSSL_LIB_CTX *libctx; char *propq; } /* OSSL_CMP_MSG */; OSSL_CMP_MSG *OSSL_CMP_MSG_new(OSSL_LIB_CTX *libctx, const char *propq); void OSSL_CMP_MSG_free(OSSL_CMP_MSG *msg); /*- * ProtectedPart ::= SEQUENCE { * header PKIHeader, * body PKIBody * } */ typedef struct ossl_cmp_protectedpart_st { OSSL_CMP_PKIHEADER *header; OSSL_CMP_PKIBODY *body; } OSSL_CMP_PROTECTEDPART; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_PROTECTEDPART) /*- * this is not defined here as it is already in CRMF: * id-PasswordBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 13} * PBMParameter ::= SEQUENCE { * salt OCTET STRING, * -- note: implementations MAY wish to limit acceptable sizes * -- of this string to values appropriate for their environment * -- in order to reduce the risk of denial-of-service attacks * owf AlgorithmIdentifier, * -- AlgId for a One-Way Function (SHA-1 recommended) * iterationCount INTEGER, * -- number of times the OWF is applied * -- note: implementations MAY wish to limit acceptable sizes * -- of this integer to values appropriate for their environment * -- in order to reduce the risk of denial-of-service attacks * mac AlgorithmIdentifier * -- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11], * } -- or HMAC [RFC2104, RFC2202]) */ /*- * Not supported: * id-DHBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 30} * DHBMParameter ::= SEQUENCE { * owf AlgorithmIdentifier, * -- AlgId for a One-Way Function (SHA-1 recommended) * mac AlgorithmIdentifier * -- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11], * } -- or HMAC [RFC2104, RFC2202]) */ /*- * The following is not cared for, because it is described in section 5.2.5 * that this is beyond the scope of CMP * OOBCert ::= CMPCertificate * * OOBCertHash ::= SEQUENCE { * hashAlg [0] AlgorithmIdentifier OPTIONAL, * certId [1] CertId OPTIONAL, * hashVal BIT STRING * -- hashVal is calculated over the DER encoding of the * -- self-signed certificate with the identifier certID. * } */ /* * RootCaKeyUpdateContent ::= SEQUENCE { * newWithNew CMPCertificate, * newWithOld [0] CMPCertificate OPTIONAL, * oldWithNew [1] CMPCertificate OPTIONAL * } */ struct ossl_cmp_rootcakeyupdate_st { X509 *newWithNew; X509 *newWithOld; X509 *oldWithNew; } /* OSSL_CMP_ROOTCAKEYUPDATE */; DECLARE_ASN1_FUNCTIONS(OSSL_CMP_ROOTCAKEYUPDATE) /* from cmp_asn.c */ int ossl_cmp_asn1_get_int(const ASN1_INTEGER *a); /* from cmp_util.c */ const char *ossl_cmp_log_parse_metadata(const char *buf, OSSL_CMP_severity *level, char **func, char **file, int *line); # define ossl_cmp_add_error_data(txt) ERR_add_error_txt(" : ", txt) # define ossl_cmp_add_error_line(txt) ERR_add_error_txt("\n", txt) /* The two functions manipulating X509_STORE could be generally useful */ int ossl_cmp_X509_STORE_add1_certs(X509_STORE *store, STACK_OF(X509) *certs, int only_self_issued); STACK_OF(X509) *ossl_cmp_X509_STORE_get1_certs(X509_STORE *store); int ossl_cmp_sk_ASN1_UTF8STRING_push_str(STACK_OF(ASN1_UTF8STRING) *sk, const char *text, int len); int ossl_cmp_asn1_octet_string_set1(ASN1_OCTET_STRING **tgt, const ASN1_OCTET_STRING *src); int ossl_cmp_asn1_octet_string_set1_bytes(ASN1_OCTET_STRING **tgt, const unsigned char *bytes, int len); /* from cmp_ctx.c */ int ossl_cmp_print_log(OSSL_CMP_severity level, const OSSL_CMP_CTX *ctx, const char *func, const char *file, int line, const char *level_str, const char *format, ...); # define ossl_cmp_log(level, ctx, msg) \ ossl_cmp_print_log(OSSL_CMP_LOG_##level, ctx, OPENSSL_FUNC, OPENSSL_FILE, \ OPENSSL_LINE, #level, "%s", msg) # define ossl_cmp_log1(level, ctx, fmt, arg1) \ ossl_cmp_print_log(OSSL_CMP_LOG_##level, ctx, OPENSSL_FUNC, OPENSSL_FILE, \ OPENSSL_LINE, #level, fmt, arg1) # define ossl_cmp_log2(level, ctx, fmt, arg1, arg2) \ ossl_cmp_print_log(OSSL_CMP_LOG_##level, ctx, OPENSSL_FUNC, OPENSSL_FILE, \ OPENSSL_LINE, #level, fmt, arg1, arg2) # define ossl_cmp_log3(level, ctx, fmt, arg1, arg2, arg3) \ ossl_cmp_print_log(OSSL_CMP_LOG_##level, ctx, OPENSSL_FUNC, OPENSSL_FILE, \ OPENSSL_LINE, #level, fmt, arg1, arg2, arg3) # define ossl_cmp_log4(level, ctx, fmt, arg1, arg2, arg3, arg4) \ ossl_cmp_print_log(OSSL_CMP_LOG_##level, ctx, OPENSSL_FUNC, OPENSSL_FILE, \ OPENSSL_LINE, #level, fmt, arg1, arg2, arg3, arg4) # define OSSL_CMP_LOG_ERROR OSSL_CMP_LOG_ERR # define OSSL_CMP_LOG_WARN OSSL_CMP_LOG_WARNING # define ossl_cmp_alert(ctx, msg) ossl_cmp_log(ALERT, ctx, msg) # define ossl_cmp_err(ctx, msg) ossl_cmp_log(ERROR, ctx, msg) # define ossl_cmp_warn(ctx, msg) ossl_cmp_log(WARN, ctx, msg) # define ossl_cmp_info(ctx, msg) ossl_cmp_log(INFO, ctx, msg) # define ossl_cmp_debug(ctx, msg) ossl_cmp_log(DEBUG, ctx, msg) # define ossl_cmp_trace(ctx, msg) ossl_cmp_log(TRACE, ctx, msg) int ossl_cmp_ctx_set1_validatedSrvCert(OSSL_CMP_CTX *ctx, X509 *cert); int ossl_cmp_ctx_set_status(OSSL_CMP_CTX *ctx, int status); int ossl_cmp_ctx_set0_statusString(OSSL_CMP_CTX *ctx, OSSL_CMP_PKIFREETEXT *text); int ossl_cmp_ctx_set_failInfoCode(OSSL_CMP_CTX *ctx, int fail_info); int ossl_cmp_ctx_set0_newCert(OSSL_CMP_CTX *ctx, X509 *cert); int ossl_cmp_ctx_set1_newChain(OSSL_CMP_CTX *ctx, STACK_OF(X509) *newChain); int ossl_cmp_ctx_set1_caPubs(OSSL_CMP_CTX *ctx, STACK_OF(X509) *caPubs); int ossl_cmp_ctx_set1_extraCertsIn(OSSL_CMP_CTX *ctx, STACK_OF(X509) *extraCertsIn); int ossl_cmp_ctx_set1_recipNonce(OSSL_CMP_CTX *ctx, const ASN1_OCTET_STRING *nonce); EVP_PKEY *ossl_cmp_ctx_get0_newPubkey(const OSSL_CMP_CTX *ctx); int ossl_cmp_ctx_set1_first_senderNonce(OSSL_CMP_CTX *ctx, const ASN1_OCTET_STRING *nonce); /* from cmp_status.c */ int ossl_cmp_pkisi_get_status(const OSSL_CMP_PKISI *si); const char *ossl_cmp_PKIStatus_to_string(int status); OSSL_CMP_PKIFREETEXT *ossl_cmp_pkisi_get0_statusString(const OSSL_CMP_PKISI *s); int ossl_cmp_pkisi_get_pkifailureinfo(const OSSL_CMP_PKISI *si); int ossl_cmp_pkisi_check_pkifailureinfo(const OSSL_CMP_PKISI *si, int index); /* from cmp_hdr.c */ int ossl_cmp_hdr_set_pvno(OSSL_CMP_PKIHEADER *hdr, int pvno); int ossl_cmp_hdr_get_pvno(const OSSL_CMP_PKIHEADER *hdr); int ossl_cmp_hdr_get_protection_nid(const OSSL_CMP_PKIHEADER *hdr); ASN1_OCTET_STRING *ossl_cmp_hdr_get0_senderNonce(const OSSL_CMP_PKIHEADER *hdr); int ossl_cmp_general_name_is_NULL_DN(GENERAL_NAME *name); int ossl_cmp_hdr_set1_sender(OSSL_CMP_PKIHEADER *hdr, const X509_NAME *nm); int ossl_cmp_hdr_set1_recipient(OSSL_CMP_PKIHEADER *hdr, const X509_NAME *nm); int ossl_cmp_hdr_update_messageTime(OSSL_CMP_PKIHEADER *hdr); int ossl_cmp_hdr_set1_senderKID(OSSL_CMP_PKIHEADER *hdr, const ASN1_OCTET_STRING *senderKID); int ossl_cmp_hdr_push0_freeText(OSSL_CMP_PKIHEADER *hdr, ASN1_UTF8STRING *text); int ossl_cmp_hdr_push1_freeText(OSSL_CMP_PKIHEADER *hdr, ASN1_UTF8STRING *text); int ossl_cmp_hdr_generalInfo_push0_item(OSSL_CMP_PKIHEADER *hdr, OSSL_CMP_ITAV *itav); int ossl_cmp_hdr_generalInfo_push1_items(OSSL_CMP_PKIHEADER *hdr, const STACK_OF(OSSL_CMP_ITAV) *itavs); int ossl_cmp_hdr_set_implicitConfirm(OSSL_CMP_PKIHEADER *hdr); int ossl_cmp_hdr_has_implicitConfirm(const OSSL_CMP_PKIHEADER *hdr); # define OSSL_CMP_TRANSACTIONID_LENGTH 16 # define OSSL_CMP_SENDERNONCE_LENGTH 16 int ossl_cmp_hdr_set_transactionID(OSSL_CMP_CTX *ctx, OSSL_CMP_PKIHEADER *hdr); int ossl_cmp_hdr_init(OSSL_CMP_CTX *ctx, OSSL_CMP_PKIHEADER *hdr); /* from cmp_msg.c */ /* OSSL_CMP_MSG bodytype ASN.1 choice IDs */ # define OSSL_CMP_PKIBODY_IR 0 # define OSSL_CMP_PKIBODY_IP 1 # define OSSL_CMP_PKIBODY_CR 2 # define OSSL_CMP_PKIBODY_CP 3 # define OSSL_CMP_PKIBODY_P10CR 4 # define OSSL_CMP_PKIBODY_POPDECC 5 # define OSSL_CMP_PKIBODY_POPDECR 6 # define OSSL_CMP_PKIBODY_KUR 7 # define OSSL_CMP_PKIBODY_KUP 8 # define OSSL_CMP_PKIBODY_KRR 9 # define OSSL_CMP_PKIBODY_KRP 10 # define OSSL_CMP_PKIBODY_RR 11 # define OSSL_CMP_PKIBODY_RP 12 # define OSSL_CMP_PKIBODY_CCR 13 # define OSSL_CMP_PKIBODY_CCP 14 # define OSSL_CMP_PKIBODY_CKUANN 15 # define OSSL_CMP_PKIBODY_CANN 16 # define OSSL_CMP_PKIBODY_RANN 17 # define OSSL_CMP_PKIBODY_CRLANN 18 # define OSSL_CMP_PKIBODY_PKICONF 19 # define OSSL_CMP_PKIBODY_NESTED 20 # define OSSL_CMP_PKIBODY_GENM 21 # define OSSL_CMP_PKIBODY_GENP 22 # define OSSL_CMP_PKIBODY_ERROR 23 # define OSSL_CMP_PKIBODY_CERTCONF 24 # define OSSL_CMP_PKIBODY_POLLREQ 25 # define OSSL_CMP_PKIBODY_POLLREP 26 # define OSSL_CMP_PKIBODY_TYPE_MAX OSSL_CMP_PKIBODY_POLLREP /* certReqId for the first - and so far only - certificate request */ # define OSSL_CMP_CERTREQID 0 # define OSSL_CMP_CERTREQID_NONE -1 # define OSSL_CMP_CERTREQID_INVALID -2 /* sequence id for the first - and so far only - revocation request */ # define OSSL_CMP_REVREQSID 0 int ossl_cmp_msg_set0_libctx(OSSL_CMP_MSG *msg, OSSL_LIB_CTX *libctx, const char *propq); const char *ossl_cmp_bodytype_to_string(int type); int ossl_cmp_msg_set_bodytype(OSSL_CMP_MSG *msg, int type); OSSL_CMP_MSG *ossl_cmp_msg_create(OSSL_CMP_CTX *ctx, int bodytype); OSSL_CMP_MSG *ossl_cmp_certreq_new(OSSL_CMP_CTX *ctx, int bodytype, const OSSL_CRMF_MSG *crm); OSSL_CMP_MSG *ossl_cmp_certrep_new(OSSL_CMP_CTX *ctx, int bodytype, int certReqId, const OSSL_CMP_PKISI *si, X509 *cert, const X509 *encryption_recip, STACK_OF(X509) *chain, STACK_OF(X509) *caPubs, int unprotectedErrors); OSSL_CMP_MSG *ossl_cmp_rr_new(OSSL_CMP_CTX *ctx); OSSL_CMP_MSG *ossl_cmp_rp_new(OSSL_CMP_CTX *ctx, const OSSL_CMP_PKISI *si, const OSSL_CRMF_CERTID *cid, int unprotectedErrors); OSSL_CMP_MSG *ossl_cmp_pkiconf_new(OSSL_CMP_CTX *ctx); OSSL_CMP_MSG *ossl_cmp_pollRep_new(OSSL_CMP_CTX *ctx, int crid, int64_t poll_after); int ossl_cmp_msg_gen_push0_ITAV(OSSL_CMP_MSG *msg, OSSL_CMP_ITAV *itav); int ossl_cmp_msg_gen_push1_ITAVs(OSSL_CMP_MSG *msg, const STACK_OF(OSSL_CMP_ITAV) *itavs); OSSL_CMP_MSG *ossl_cmp_genm_new(OSSL_CMP_CTX *ctx); OSSL_CMP_MSG *ossl_cmp_genp_new(OSSL_CMP_CTX *ctx, const STACK_OF(OSSL_CMP_ITAV) *itavs); OSSL_CMP_MSG *ossl_cmp_error_new(OSSL_CMP_CTX *ctx, const OSSL_CMP_PKISI *si, int64_t errorCode, const char *details, int unprotected); int ossl_cmp_certstatus_set0_certHash(OSSL_CMP_CERTSTATUS *certStatus, ASN1_OCTET_STRING *hash); OSSL_CMP_MSG *ossl_cmp_certConf_new(OSSL_CMP_CTX *ctx, int certReqId, int fail_info, const char *text); OSSL_CMP_MSG *ossl_cmp_pollReq_new(OSSL_CMP_CTX *ctx, int crid); OSSL_CMP_MSG *ossl_cmp_pollRep_new(OSSL_CMP_CTX *ctx, int crid, int64_t poll_after); OSSL_CMP_PKISI * ossl_cmp_revrepcontent_get_pkisi(OSSL_CMP_REVREPCONTENT *rrep, int rsid); OSSL_CRMF_CERTID *ossl_cmp_revrepcontent_get_CertId(OSSL_CMP_REVREPCONTENT *rc, int rsid); OSSL_CMP_POLLREP * ossl_cmp_pollrepcontent_get0_pollrep(const OSSL_CMP_POLLREPCONTENT *prc, int rid); OSSL_CMP_CERTRESPONSE * ossl_cmp_certrepmessage_get0_certresponse(const OSSL_CMP_CERTREPMESSAGE *crm, int rid); X509 *ossl_cmp_certresponse_get1_cert(const OSSL_CMP_CTX *ctx, const OSSL_CMP_CERTRESPONSE *crep); OSSL_CMP_MSG *ossl_cmp_msg_load(const char *file); int ossl_cmp_is_error_with_waiting(const OSSL_CMP_MSG *msg); /* from cmp_protect.c */ int ossl_cmp_msg_add_extraCerts(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg); ASN1_BIT_STRING *ossl_cmp_calc_protection(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg); int ossl_cmp_msg_protect(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg); /* from cmp_vfy.c */ typedef int (*ossl_cmp_allow_unprotected_cb_t)(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg, int invalid_protection, int arg); int ossl_cmp_msg_check_update(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg, ossl_cmp_allow_unprotected_cb_t cb, int cb_arg); int ossl_cmp_msg_check_received(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg, ossl_cmp_allow_unprotected_cb_t cb, int cb_arg); int ossl_cmp_verify_popo(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg, int accept_RAVerified); /* from cmp_client.c */ /* expected max time per msg round trip, used for last try during polling: */ # define OSSL_CMP_EXPECTED_RESP_TIME 2 int ossl_cmp_exchange_certConf(OSSL_CMP_CTX *ctx, int certReqId, int fail_info, const char *txt); int ossl_cmp_exchange_error(OSSL_CMP_CTX *ctx, int status, int fail_info, const char *txt, int errorCode, const char *detail); #endif /* !defined(OSSL_CRYPTO_CMP_LOCAL_H) */
./openssl/crypto/cmp/cmp_util.c
/* * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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/cmp_util.h> #include "cmp_local.h" /* just for decls of internal functions defined here */ #include <openssl/cmperr.h> #include <openssl/err.h> /* should be implied by cmperr.h */ #include <openssl/x509v3.h> /* * use trace API for CMP-specific logging, prefixed by "CMP " and severity */ int OSSL_CMP_log_open(void) /* is designed to be idempotent */ { #ifdef OPENSSL_NO_TRACE return 1; #else # ifndef OPENSSL_NO_STDIO BIO *bio = BIO_new_fp(stdout, BIO_NOCLOSE); if (bio != NULL && OSSL_trace_set_channel(OSSL_TRACE_CATEGORY_CMP, bio)) return 1; BIO_free(bio); # endif ERR_raise(ERR_LIB_CMP, CMP_R_NO_STDIO); return 0; #endif } void OSSL_CMP_log_close(void) /* is designed to be idempotent */ { (void)OSSL_trace_set_channel(OSSL_TRACE_CATEGORY_CMP, NULL); } /* return >= 0 if level contains logging level, possibly preceded by "CMP " */ #define max_level_len 5 /* = max length of the below strings, e.g., "EMERG" */ static OSSL_CMP_severity parse_level(const char *level) { const char *end_level = strchr(level, ':'); int len; char level_copy[max_level_len + 1]; if (end_level == NULL) return -1; if (HAS_PREFIX(level, OSSL_CMP_LOG_PREFIX)) level += strlen(OSSL_CMP_LOG_PREFIX); len = end_level - level; if (len > max_level_len) return -1; OPENSSL_strlcpy(level_copy, level, len + 1); return strcmp(level_copy, "EMERG") == 0 ? OSSL_CMP_LOG_EMERG : strcmp(level_copy, "ALERT") == 0 ? OSSL_CMP_LOG_ALERT : strcmp(level_copy, "CRIT") == 0 ? OSSL_CMP_LOG_CRIT : strcmp(level_copy, "ERROR") == 0 ? OSSL_CMP_LOG_ERR : strcmp(level_copy, "WARN") == 0 ? OSSL_CMP_LOG_WARNING : strcmp(level_copy, "NOTE") == 0 ? OSSL_CMP_LOG_NOTICE : strcmp(level_copy, "INFO") == 0 ? OSSL_CMP_LOG_INFO : strcmp(level_copy, "DEBUG") == 0 ? OSSL_CMP_LOG_DEBUG : -1; } const char *ossl_cmp_log_parse_metadata(const char *buf, OSSL_CMP_severity *level, char **func, char **file, int *line) { const char *p_func = buf; const char *p_file = buf == NULL ? NULL : strchr(buf, ':'); const char *p_level = buf; const char *msg = buf; *level = -1; *func = NULL; *file = NULL; *line = 0; if (p_file != NULL) { const char *p_line = strchr(++p_file, ':'); if ((*level = parse_level(buf)) < 0 && p_line != NULL) { /* check if buf contains location info and logging level */ char *p_level_tmp = (char *)p_level; const long line_number = strtol(++p_line, &p_level_tmp, 10); p_level = p_level_tmp; if (p_level > p_line && *(p_level++) == ':') { if ((*level = parse_level(p_level)) >= 0) { *func = OPENSSL_strndup(p_func, p_file - 1 - p_func); *file = OPENSSL_strndup(p_file, p_line - 1 - p_file); /* no real problem if OPENSSL_strndup() returns NULL */ *line = (int)line_number; msg = strchr(p_level, ':'); if (msg != NULL && *++msg == ' ') msg++; } } } } return msg; } #define UNKNOWN_FUNC "(unknown function)" /* the default for OPENSSL_FUNC */ /* * substitute fallback if component/function name is NULL or empty or contains * just pseudo-information "(unknown function)" due to -pedantic and macros.h */ static const char *improve_location_name(const char *func, const char *fallback) { if (fallback == NULL) return func == NULL ? UNKNOWN_FUNC : func; return func == NULL || *func == '\0' || strcmp(func, UNKNOWN_FUNC) == 0 ? fallback : func; } int OSSL_CMP_print_to_bio(BIO *bio, const char *component, const char *file, int line, OSSL_CMP_severity level, const char *msg) { const char *level_string = level == OSSL_CMP_LOG_EMERG ? "EMERG" : level == OSSL_CMP_LOG_ALERT ? "ALERT" : level == OSSL_CMP_LOG_CRIT ? "CRIT" : level == OSSL_CMP_LOG_ERR ? "error" : level == OSSL_CMP_LOG_WARNING ? "warning" : level == OSSL_CMP_LOG_NOTICE ? "NOTE" : level == OSSL_CMP_LOG_INFO ? "info" : level == OSSL_CMP_LOG_DEBUG ? "DEBUG" : "(unknown level)"; #ifndef NDEBUG if (BIO_printf(bio, "%s:%s:%d:", improve_location_name(component, "CMP"), file, line) < 0) return 0; #endif return BIO_printf(bio, OSSL_CMP_LOG_PREFIX"%s: %s\n", level_string, msg) >= 0; } #define ERR_PRINT_BUF_SIZE 4096 /* this is similar to ERR_print_errors_cb, but uses the CMP-specific cb type */ void OSSL_CMP_print_errors_cb(OSSL_CMP_log_cb_t log_fn) { unsigned long err; char msg[ERR_PRINT_BUF_SIZE]; const char *file = NULL, *func = NULL, *data = NULL; int line, flags; while ((err = ERR_get_error_all(&file, &line, &func, &data, &flags)) != 0) { const char *component = improve_location_name(func, ERR_lib_error_string(err)); unsigned long reason = ERR_GET_REASON(err); const char *rs = NULL; char rsbuf[256]; #ifndef OPENSSL_NO_ERR if (ERR_SYSTEM_ERROR(err)) { if (openssl_strerror_r(reason, rsbuf, sizeof(rsbuf))) rs = rsbuf; } else { rs = ERR_reason_error_string(err); } #endif if (rs == NULL) { BIO_snprintf(rsbuf, sizeof(rsbuf), "reason(%lu)", reason); rs = rsbuf; } if (data != NULL && (flags & ERR_TXT_STRING) != 0) BIO_snprintf(msg, sizeof(msg), "%s:%s", rs, data); else BIO_snprintf(msg, sizeof(msg), "%s", rs); if (log_fn == NULL) { #ifndef OPENSSL_NO_STDIO BIO *bio = BIO_new_fp(stderr, BIO_NOCLOSE); if (bio != NULL) { OSSL_CMP_print_to_bio(bio, component, file, line, OSSL_CMP_LOG_ERR, msg); BIO_free(bio); } #else /* ERR_raise(..., CMP_R_NO_STDIO) would make no sense here */ #endif } else { if (log_fn(component, file, line, OSSL_CMP_LOG_ERR, msg) <= 0) break; /* abort outputting the error report */ } } } int ossl_cmp_X509_STORE_add1_certs(X509_STORE *store, STACK_OF(X509) *certs, int only_self_signed) { int i; if (store == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (certs == NULL) return 1; for (i = 0; i < sk_X509_num(certs); i++) { X509 *cert = sk_X509_value(certs, i); if (!only_self_signed || X509_self_signed(cert, 0) == 1) if (!X509_STORE_add_cert(store, cert)) /* ups cert ref counter */ return 0; } return 1; } int ossl_cmp_sk_ASN1_UTF8STRING_push_str(STACK_OF(ASN1_UTF8STRING) *sk, const char *text, int len) { ASN1_UTF8STRING *utf8string; if (!ossl_assert(sk != NULL && text != NULL)) return 0; if ((utf8string = ASN1_UTF8STRING_new()) == NULL) return 0; if (!ASN1_STRING_set(utf8string, text, len)) goto err; if (!sk_ASN1_UTF8STRING_push(sk, utf8string)) goto err; return 1; err: ASN1_UTF8STRING_free(utf8string); return 0; } int ossl_cmp_asn1_octet_string_set1(ASN1_OCTET_STRING **tgt, const ASN1_OCTET_STRING *src) { ASN1_OCTET_STRING *new; if (tgt == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (*tgt == src) /* self-assignment */ return 1; if (src != NULL) { if ((new = ASN1_OCTET_STRING_dup(src)) == NULL) return 0; } else { new = NULL; } ASN1_OCTET_STRING_free(*tgt); *tgt = new; return 1; } int ossl_cmp_asn1_octet_string_set1_bytes(ASN1_OCTET_STRING **tgt, const unsigned char *bytes, int len) { ASN1_OCTET_STRING *new = NULL; if (tgt == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (bytes != NULL) { if ((new = ASN1_OCTET_STRING_new()) == NULL || !(ASN1_OCTET_STRING_set(new, bytes, len))) { ASN1_OCTET_STRING_free(new); return 0; } } ASN1_OCTET_STRING_free(*tgt); *tgt = new; return 1; }
./openssl/crypto/cmp/cmp_asn.c
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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/asn1t.h> #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/cmp.h> #include <openssl/crmf.h> /* ASN.1 declarations from RFC4210 */ ASN1_SEQUENCE(OSSL_CMP_REVANNCONTENT) = { /* OSSL_CMP_PKISTATUS is effectively ASN1_INTEGER so it is used directly */ ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, status, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, certId, OSSL_CRMF_CERTID), ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, willBeRevokedAt, ASN1_GENERALIZEDTIME), ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, badSinceDate, ASN1_GENERALIZEDTIME), ASN1_OPT(OSSL_CMP_REVANNCONTENT, crlDetails, X509_EXTENSIONS) } ASN1_SEQUENCE_END(OSSL_CMP_REVANNCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_REVANNCONTENT) ASN1_SEQUENCE(OSSL_CMP_CHALLENGE) = { ASN1_OPT(OSSL_CMP_CHALLENGE, owf, X509_ALGOR), ASN1_SIMPLE(OSSL_CMP_CHALLENGE, witness, ASN1_OCTET_STRING), ASN1_SIMPLE(OSSL_CMP_CHALLENGE, challenge, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(OSSL_CMP_CHALLENGE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CHALLENGE) ASN1_ITEM_TEMPLATE(OSSL_CMP_POPODECKEYCHALLCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POPODECKEYCHALLCONTENT, OSSL_CMP_CHALLENGE) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POPODECKEYCHALLCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_POPODECKEYRESPCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POPODECKEYRESPCONTENT, ASN1_INTEGER) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POPODECKEYRESPCONTENT) ASN1_SEQUENCE(OSSL_CMP_CAKEYUPDANNCONTENT) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_SIMPLE(OSSL_CMP_CAKEYUPDANNCONTENT, oldWithNew, X509), /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_SIMPLE(OSSL_CMP_CAKEYUPDANNCONTENT, newWithOld, X509), /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_SIMPLE(OSSL_CMP_CAKEYUPDANNCONTENT, newWithNew, X509) } ASN1_SEQUENCE_END(OSSL_CMP_CAKEYUPDANNCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CAKEYUPDANNCONTENT) ASN1_SEQUENCE(OSSL_CMP_ERRORMSGCONTENT) = { ASN1_SIMPLE(OSSL_CMP_ERRORMSGCONTENT, pKIStatusInfo, OSSL_CMP_PKISI), ASN1_OPT(OSSL_CMP_ERRORMSGCONTENT, errorCode, ASN1_INTEGER), /* OSSL_CMP_PKIFREETEXT is a ASN1_UTF8STRING sequence, so used directly */ ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ERRORMSGCONTENT, errorDetails, ASN1_UTF8STRING) } ASN1_SEQUENCE_END(OSSL_CMP_ERRORMSGCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_ERRORMSGCONTENT) ASN1_ADB_TEMPLATE(infotypeandvalue_default) = ASN1_OPT(OSSL_CMP_ITAV, infoValue.other, ASN1_ANY); /* ITAV means InfoTypeAndValue */ ASN1_ADB(OSSL_CMP_ITAV) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ADB_ENTRY(NID_id_it_caProtEncCert, ASN1_OPT(OSSL_CMP_ITAV, infoValue.caProtEncCert, X509)), ADB_ENTRY(NID_id_it_signKeyPairTypes, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.signKeyPairTypes, X509_ALGOR)), ADB_ENTRY(NID_id_it_encKeyPairTypes, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.encKeyPairTypes, X509_ALGOR)), ADB_ENTRY(NID_id_it_preferredSymmAlg, ASN1_OPT(OSSL_CMP_ITAV, infoValue.preferredSymmAlg, X509_ALGOR)), ADB_ENTRY(NID_id_it_caKeyUpdateInfo, ASN1_OPT(OSSL_CMP_ITAV, infoValue.caKeyUpdateInfo, OSSL_CMP_CAKEYUPDANNCONTENT)), ADB_ENTRY(NID_id_it_currentCRL, ASN1_OPT(OSSL_CMP_ITAV, infoValue.currentCRL, X509_CRL)), ADB_ENTRY(NID_id_it_unsupportedOIDs, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.unsupportedOIDs, ASN1_OBJECT)), ADB_ENTRY(NID_id_it_keyPairParamReq, ASN1_OPT(OSSL_CMP_ITAV, infoValue.keyPairParamReq, ASN1_OBJECT)), ADB_ENTRY(NID_id_it_keyPairParamRep, ASN1_OPT(OSSL_CMP_ITAV, infoValue.keyPairParamRep, X509_ALGOR)), ADB_ENTRY(NID_id_it_revPassphrase, ASN1_OPT(OSSL_CMP_ITAV, infoValue.revPassphrase, OSSL_CRMF_ENCRYPTEDVALUE)), ADB_ENTRY(NID_id_it_implicitConfirm, ASN1_OPT(OSSL_CMP_ITAV, infoValue.implicitConfirm, ASN1_NULL)), ADB_ENTRY(NID_id_it_confirmWaitTime, ASN1_OPT(OSSL_CMP_ITAV, infoValue.confirmWaitTime, ASN1_GENERALIZEDTIME)), ADB_ENTRY(NID_id_it_origPKIMessage, ASN1_OPT(OSSL_CMP_ITAV, infoValue.origPKIMessage, OSSL_CMP_MSGS)), ADB_ENTRY(NID_id_it_suppLangTags, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.suppLangTagsValue, ASN1_UTF8STRING)), ADB_ENTRY(NID_id_it_caCerts, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.caCerts, X509)), ADB_ENTRY(NID_id_it_rootCaCert, ASN1_OPT(OSSL_CMP_ITAV, infoValue.rootCaCert, X509)), ADB_ENTRY(NID_id_it_rootCaKeyUpdate, ASN1_OPT(OSSL_CMP_ITAV, infoValue.rootCaKeyUpdate, OSSL_CMP_ROOTCAKEYUPDATE)), ADB_ENTRY(NID_id_it_certProfile, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.certProfile, ASN1_UTF8STRING)), } ASN1_ADB_END(OSSL_CMP_ITAV, 0, infoType, 0, &infotypeandvalue_default_tt, NULL); ASN1_SEQUENCE(OSSL_CMP_ITAV) = { ASN1_SIMPLE(OSSL_CMP_ITAV, infoType, ASN1_OBJECT), ASN1_ADB_OBJECT(OSSL_CMP_ITAV) } ASN1_SEQUENCE_END(OSSL_CMP_ITAV) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_ITAV) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CMP_ITAV) ASN1_SEQUENCE(OSSL_CMP_ROOTCAKEYUPDATE) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_SIMPLE(OSSL_CMP_ROOTCAKEYUPDATE, newWithNew, X509), ASN1_EXP_OPT(OSSL_CMP_ROOTCAKEYUPDATE, newWithOld, X509, 0), ASN1_EXP_OPT(OSSL_CMP_ROOTCAKEYUPDATE, oldWithNew, X509, 1) } ASN1_SEQUENCE_END(OSSL_CMP_ROOTCAKEYUPDATE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_ROOTCAKEYUPDATE) OSSL_CMP_ITAV *OSSL_CMP_ITAV_create(ASN1_OBJECT *type, ASN1_TYPE *value) { OSSL_CMP_ITAV *itav; if (type == NULL || (itav = OSSL_CMP_ITAV_new()) == NULL) return NULL; OSSL_CMP_ITAV_set0(itav, type, value); return itav; } void OSSL_CMP_ITAV_set0(OSSL_CMP_ITAV *itav, ASN1_OBJECT *type, ASN1_TYPE *value) { itav->infoType = type; itav->infoValue.other = value; } ASN1_OBJECT *OSSL_CMP_ITAV_get0_type(const OSSL_CMP_ITAV *itav) { if (itav == NULL) return NULL; return itav->infoType; } ASN1_TYPE *OSSL_CMP_ITAV_get0_value(const OSSL_CMP_ITAV *itav) { if (itav == NULL) return NULL; return itav->infoValue.other; } int OSSL_CMP_ITAV_push0_stack_item(STACK_OF(OSSL_CMP_ITAV) **itav_sk_p, OSSL_CMP_ITAV *itav) { int created = 0; if (itav_sk_p == NULL || itav == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); goto err; } if (*itav_sk_p == NULL) { if ((*itav_sk_p = sk_OSSL_CMP_ITAV_new_null()) == NULL) goto err; created = 1; } if (!sk_OSSL_CMP_ITAV_push(*itav_sk_p, itav)) goto err; return 1; err: if (created) { sk_OSSL_CMP_ITAV_free(*itav_sk_p); *itav_sk_p = NULL; } return 0; } OSSL_CMP_ITAV *OSSL_CMP_ITAV_new0_certProfile(STACK_OF(ASN1_UTF8STRING) *certProfile) { OSSL_CMP_ITAV *itav; if ((itav = OSSL_CMP_ITAV_new()) == NULL) return NULL; itav->infoType = OBJ_nid2obj(NID_id_it_certProfile); itav->infoValue.certProfile = certProfile; return itav; } int OSSL_CMP_ITAV_get0_certProfile(const OSSL_CMP_ITAV *itav, STACK_OF(ASN1_UTF8STRING) **out) { if (itav == NULL || out == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (OBJ_obj2nid(itav->infoType) != NID_id_it_certProfile) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } *out = itav->infoValue.certProfile; return 1; } OSSL_CMP_ITAV *OSSL_CMP_ITAV_new_caCerts(const STACK_OF(X509) *caCerts) { OSSL_CMP_ITAV *itav = OSSL_CMP_ITAV_new(); if (itav == NULL) return NULL; if (sk_X509_num(caCerts) > 0 && (itav->infoValue.caCerts = sk_X509_deep_copy(caCerts, X509_dup, X509_free)) == NULL) { OSSL_CMP_ITAV_free(itav); return NULL; } itav->infoType = OBJ_nid2obj(NID_id_it_caCerts); return itav; } int OSSL_CMP_ITAV_get0_caCerts(const OSSL_CMP_ITAV *itav, STACK_OF(X509) **out) { if (itav == NULL || out == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (OBJ_obj2nid(itav->infoType) != NID_id_it_caCerts) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } *out = sk_X509_num(itav->infoValue.caCerts) > 0 ? itav->infoValue.caCerts : NULL; return 1; } OSSL_CMP_ITAV *OSSL_CMP_ITAV_new_rootCaCert(const X509 *rootCaCert) { OSSL_CMP_ITAV *itav = OSSL_CMP_ITAV_new(); if (itav == NULL) return NULL; if (rootCaCert != NULL && (itav->infoValue.rootCaCert = X509_dup(rootCaCert)) == NULL) { OSSL_CMP_ITAV_free(itav); return NULL; } itav->infoType = OBJ_nid2obj(NID_id_it_rootCaCert); return itav; } int OSSL_CMP_ITAV_get0_rootCaCert(const OSSL_CMP_ITAV *itav, X509 **out) { if (itav == NULL || out == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (OBJ_obj2nid(itav->infoType) != NID_id_it_rootCaCert) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } *out = itav->infoValue.rootCaCert; return 1; } OSSL_CMP_ITAV *OSSL_CMP_ITAV_new_rootCaKeyUpdate(const X509 *newWithNew, const X509 *newWithOld, const X509 *oldWithNew) { OSSL_CMP_ITAV *itav; OSSL_CMP_ROOTCAKEYUPDATE *upd = OSSL_CMP_ROOTCAKEYUPDATE_new(); if (upd == NULL) return NULL; if (newWithNew != NULL && (upd->newWithNew = X509_dup(newWithNew)) == NULL) goto err; if (newWithOld != NULL && (upd->newWithOld = X509_dup(newWithOld)) == NULL) goto err; if (oldWithNew != NULL && (upd->oldWithNew = X509_dup(oldWithNew)) == NULL) goto err; if ((itav = OSSL_CMP_ITAV_new()) == NULL) goto err; itav->infoType = OBJ_nid2obj(NID_id_it_rootCaKeyUpdate); itav->infoValue.rootCaKeyUpdate = upd; return itav; err: OSSL_CMP_ROOTCAKEYUPDATE_free(upd); return NULL; } int OSSL_CMP_ITAV_get0_rootCaKeyUpdate(const OSSL_CMP_ITAV *itav, X509 **newWithNew, X509 **newWithOld, X509 **oldWithNew) { OSSL_CMP_ROOTCAKEYUPDATE *upd; if (itav == NULL || newWithNew == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (OBJ_obj2nid(itav->infoType) != NID_id_it_rootCaKeyUpdate) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } upd = itav->infoValue.rootCaKeyUpdate; *newWithNew = upd->newWithNew; if (newWithOld != NULL) *newWithOld = upd->newWithOld; if (oldWithNew != NULL) *oldWithNew = upd->oldWithNew; return 1; } /* get ASN.1 encoded integer, return -2 on error; -1 is valid for certReqId */ int ossl_cmp_asn1_get_int(const ASN1_INTEGER *a) { int64_t res; if (!ASN1_INTEGER_get_int64(&res, a)) { ERR_raise(ERR_LIB_CMP, ASN1_R_INVALID_NUMBER); return -2; } if (res < INT_MIN) { ERR_raise(ERR_LIB_CMP, ASN1_R_TOO_SMALL); return -2; } if (res > INT_MAX) { ERR_raise(ERR_LIB_CMP, ASN1_R_TOO_LARGE); return -2; } return (int)res; } static int ossl_cmp_msg_cb(int operation, ASN1_VALUE **pval, ossl_unused const ASN1_ITEM *it, void *exarg) { OSSL_CMP_MSG *msg = (OSSL_CMP_MSG *)*pval; switch (operation) { case ASN1_OP_FREE_POST: OPENSSL_free(msg->propq); break; case ASN1_OP_DUP_POST: { OSSL_CMP_MSG *old = exarg; if (!ossl_cmp_msg_set0_libctx(msg, old->libctx, old->propq)) return 0; } break; case ASN1_OP_GET0_LIBCTX: { OSSL_LIB_CTX **libctx = exarg; *libctx = msg->libctx; } break; case ASN1_OP_GET0_PROPQ: { const char **propq = exarg; *propq = msg->propq; } break; default: break; } return 1; } ASN1_CHOICE(OSSL_CMP_CERTORENCCERT) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_EXP(OSSL_CMP_CERTORENCCERT, value.certificate, X509, 0), ASN1_EXP(OSSL_CMP_CERTORENCCERT, value.encryptedCert, OSSL_CRMF_ENCRYPTEDVALUE, 1), } ASN1_CHOICE_END(OSSL_CMP_CERTORENCCERT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTORENCCERT) ASN1_SEQUENCE(OSSL_CMP_CERTIFIEDKEYPAIR) = { ASN1_SIMPLE(OSSL_CMP_CERTIFIEDKEYPAIR, certOrEncCert, OSSL_CMP_CERTORENCCERT), ASN1_EXP_OPT(OSSL_CMP_CERTIFIEDKEYPAIR, privateKey, OSSL_CRMF_ENCRYPTEDVALUE, 0), ASN1_EXP_OPT(OSSL_CMP_CERTIFIEDKEYPAIR, publicationInfo, OSSL_CRMF_PKIPUBLICATIONINFO, 1) } ASN1_SEQUENCE_END(OSSL_CMP_CERTIFIEDKEYPAIR) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTIFIEDKEYPAIR) ASN1_SEQUENCE(OSSL_CMP_REVDETAILS) = { ASN1_SIMPLE(OSSL_CMP_REVDETAILS, certDetails, OSSL_CRMF_CERTTEMPLATE), ASN1_OPT(OSSL_CMP_REVDETAILS, crlEntryDetails, X509_EXTENSIONS) } ASN1_SEQUENCE_END(OSSL_CMP_REVDETAILS) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_REVDETAILS) ASN1_ITEM_TEMPLATE(OSSL_CMP_REVREQCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_REVREQCONTENT, OSSL_CMP_REVDETAILS) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_REVREQCONTENT) ASN1_SEQUENCE(OSSL_CMP_REVREPCONTENT) = { ASN1_SEQUENCE_OF(OSSL_CMP_REVREPCONTENT, status, OSSL_CMP_PKISI), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_REVREPCONTENT, revCerts, OSSL_CRMF_CERTID, 0), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_REVREPCONTENT, crls, X509_CRL, 1) } ASN1_SEQUENCE_END(OSSL_CMP_REVREPCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_REVREPCONTENT) ASN1_SEQUENCE(OSSL_CMP_KEYRECREPCONTENT) = { ASN1_SIMPLE(OSSL_CMP_KEYRECREPCONTENT, status, OSSL_CMP_PKISI), ASN1_EXP_OPT(OSSL_CMP_KEYRECREPCONTENT, newSigCert, X509, 0), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_KEYRECREPCONTENT, caCerts, X509, 1), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_KEYRECREPCONTENT, keyPairHist, OSSL_CMP_CERTIFIEDKEYPAIR, 2) } ASN1_SEQUENCE_END(OSSL_CMP_KEYRECREPCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_KEYRECREPCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_PKISTATUS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_UNIVERSAL, 0, status, ASN1_INTEGER) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_PKISTATUS) ASN1_SEQUENCE(OSSL_CMP_PKISI) = { ASN1_SIMPLE(OSSL_CMP_PKISI, status, OSSL_CMP_PKISTATUS), /* OSSL_CMP_PKIFREETEXT is a ASN1_UTF8STRING sequence, so used directly */ ASN1_SEQUENCE_OF_OPT(OSSL_CMP_PKISI, statusString, ASN1_UTF8STRING), /* OSSL_CMP_PKIFAILUREINFO is effectively ASN1_BIT_STRING, used directly */ ASN1_OPT(OSSL_CMP_PKISI, failInfo, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(OSSL_CMP_PKISI) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PKISI) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CMP_PKISI) ASN1_SEQUENCE(OSSL_CMP_CERTSTATUS) = { ASN1_SIMPLE(OSSL_CMP_CERTSTATUS, certHash, ASN1_OCTET_STRING), ASN1_SIMPLE(OSSL_CMP_CERTSTATUS, certReqId, ASN1_INTEGER), ASN1_OPT(OSSL_CMP_CERTSTATUS, statusInfo, OSSL_CMP_PKISI), ASN1_EXP_OPT(OSSL_CMP_CERTSTATUS, hashAlg, X509_ALGOR, 0) } ASN1_SEQUENCE_END(OSSL_CMP_CERTSTATUS) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTSTATUS) ASN1_ITEM_TEMPLATE(OSSL_CMP_CERTCONFIRMCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_CERTCONFIRMCONTENT, OSSL_CMP_CERTSTATUS) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_CERTCONFIRMCONTENT) ASN1_SEQUENCE(OSSL_CMP_CERTRESPONSE) = { ASN1_SIMPLE(OSSL_CMP_CERTRESPONSE, certReqId, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_CERTRESPONSE, status, OSSL_CMP_PKISI), ASN1_OPT(OSSL_CMP_CERTRESPONSE, certifiedKeyPair, OSSL_CMP_CERTIFIEDKEYPAIR), ASN1_OPT(OSSL_CMP_CERTRESPONSE, rspInfo, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(OSSL_CMP_CERTRESPONSE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTRESPONSE) ASN1_SEQUENCE(OSSL_CMP_POLLREQ) = { ASN1_SIMPLE(OSSL_CMP_POLLREQ, certReqId, ASN1_INTEGER) } ASN1_SEQUENCE_END(OSSL_CMP_POLLREQ) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_POLLREQ) ASN1_ITEM_TEMPLATE(OSSL_CMP_POLLREQCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POLLREQCONTENT, OSSL_CMP_POLLREQ) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POLLREQCONTENT) ASN1_SEQUENCE(OSSL_CMP_POLLREP) = { ASN1_SIMPLE(OSSL_CMP_POLLREP, certReqId, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_POLLREP, checkAfter, ASN1_INTEGER), ASN1_SEQUENCE_OF_OPT(OSSL_CMP_POLLREP, reason, ASN1_UTF8STRING), } ASN1_SEQUENCE_END(OSSL_CMP_POLLREP) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_POLLREP) ASN1_ITEM_TEMPLATE(OSSL_CMP_POLLREPCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POLLREPCONTENT, OSSL_CMP_POLLREP) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POLLREPCONTENT) ASN1_SEQUENCE(OSSL_CMP_CERTREPMESSAGE) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_CERTREPMESSAGE, caPubs, X509, 1), ASN1_SEQUENCE_OF(OSSL_CMP_CERTREPMESSAGE, response, OSSL_CMP_CERTRESPONSE) } ASN1_SEQUENCE_END(OSSL_CMP_CERTREPMESSAGE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTREPMESSAGE) ASN1_ITEM_TEMPLATE(OSSL_CMP_GENMSGCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_GENMSGCONTENT, OSSL_CMP_ITAV) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_GENMSGCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_GENREPCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_GENREPCONTENT, OSSL_CMP_ITAV) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_GENREPCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_CRLANNCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_CRLANNCONTENT, X509_CRL) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_CRLANNCONTENT) ASN1_CHOICE(OSSL_CMP_PKIBODY) = { ASN1_EXP(OSSL_CMP_PKIBODY, value.ir, OSSL_CRMF_MSGS, 0), ASN1_EXP(OSSL_CMP_PKIBODY, value.ip, OSSL_CMP_CERTREPMESSAGE, 1), ASN1_EXP(OSSL_CMP_PKIBODY, value.cr, OSSL_CRMF_MSGS, 2), ASN1_EXP(OSSL_CMP_PKIBODY, value.cp, OSSL_CMP_CERTREPMESSAGE, 3), ASN1_EXP(OSSL_CMP_PKIBODY, value.p10cr, X509_REQ, 4), ASN1_EXP(OSSL_CMP_PKIBODY, value.popdecc, OSSL_CMP_POPODECKEYCHALLCONTENT, 5), ASN1_EXP(OSSL_CMP_PKIBODY, value.popdecr, OSSL_CMP_POPODECKEYRESPCONTENT, 6), ASN1_EXP(OSSL_CMP_PKIBODY, value.kur, OSSL_CRMF_MSGS, 7), ASN1_EXP(OSSL_CMP_PKIBODY, value.kup, OSSL_CMP_CERTREPMESSAGE, 8), ASN1_EXP(OSSL_CMP_PKIBODY, value.krr, OSSL_CRMF_MSGS, 9), ASN1_EXP(OSSL_CMP_PKIBODY, value.krp, OSSL_CMP_KEYRECREPCONTENT, 10), ASN1_EXP(OSSL_CMP_PKIBODY, value.rr, OSSL_CMP_REVREQCONTENT, 11), ASN1_EXP(OSSL_CMP_PKIBODY, value.rp, OSSL_CMP_REVREPCONTENT, 12), ASN1_EXP(OSSL_CMP_PKIBODY, value.ccr, OSSL_CRMF_MSGS, 13), ASN1_EXP(OSSL_CMP_PKIBODY, value.ccp, OSSL_CMP_CERTREPMESSAGE, 14), ASN1_EXP(OSSL_CMP_PKIBODY, value.ckuann, OSSL_CMP_CAKEYUPDANNCONTENT, 15), ASN1_EXP(OSSL_CMP_PKIBODY, value.cann, X509, 16), ASN1_EXP(OSSL_CMP_PKIBODY, value.rann, OSSL_CMP_REVANNCONTENT, 17), ASN1_EXP(OSSL_CMP_PKIBODY, value.crlann, OSSL_CMP_CRLANNCONTENT, 18), ASN1_EXP(OSSL_CMP_PKIBODY, value.pkiconf, ASN1_ANY, 19), ASN1_EXP(OSSL_CMP_PKIBODY, value.nested, OSSL_CMP_MSGS, 20), ASN1_EXP(OSSL_CMP_PKIBODY, value.genm, OSSL_CMP_GENMSGCONTENT, 21), ASN1_EXP(OSSL_CMP_PKIBODY, value.genp, OSSL_CMP_GENREPCONTENT, 22), ASN1_EXP(OSSL_CMP_PKIBODY, value.error, OSSL_CMP_ERRORMSGCONTENT, 23), ASN1_EXP(OSSL_CMP_PKIBODY, value.certConf, OSSL_CMP_CERTCONFIRMCONTENT, 24), ASN1_EXP(OSSL_CMP_PKIBODY, value.pollReq, OSSL_CMP_POLLREQCONTENT, 25), ASN1_EXP(OSSL_CMP_PKIBODY, value.pollRep, OSSL_CMP_POLLREPCONTENT, 26), } ASN1_CHOICE_END(OSSL_CMP_PKIBODY) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PKIBODY) ASN1_SEQUENCE(OSSL_CMP_PKIHEADER) = { ASN1_SIMPLE(OSSL_CMP_PKIHEADER, pvno, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_PKIHEADER, sender, GENERAL_NAME), ASN1_SIMPLE(OSSL_CMP_PKIHEADER, recipient, GENERAL_NAME), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, messageTime, ASN1_GENERALIZEDTIME, 0), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, protectionAlg, X509_ALGOR, 1), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, senderKID, ASN1_OCTET_STRING, 2), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, recipKID, ASN1_OCTET_STRING, 3), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, transactionID, ASN1_OCTET_STRING, 4), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, senderNonce, ASN1_OCTET_STRING, 5), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, recipNonce, ASN1_OCTET_STRING, 6), /* OSSL_CMP_PKIFREETEXT is a ASN1_UTF8STRING sequence, so used directly */ ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_PKIHEADER, freeText, ASN1_UTF8STRING, 7), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_PKIHEADER, generalInfo, OSSL_CMP_ITAV, 8) } ASN1_SEQUENCE_END(OSSL_CMP_PKIHEADER) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PKIHEADER) ASN1_SEQUENCE(OSSL_CMP_PROTECTEDPART) = { ASN1_SIMPLE(OSSL_CMP_MSG, header, OSSL_CMP_PKIHEADER), ASN1_SIMPLE(OSSL_CMP_MSG, body, OSSL_CMP_PKIBODY) } ASN1_SEQUENCE_END(OSSL_CMP_PROTECTEDPART) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PROTECTEDPART) ASN1_SEQUENCE_cb(OSSL_CMP_MSG, ossl_cmp_msg_cb) = { ASN1_SIMPLE(OSSL_CMP_MSG, header, OSSL_CMP_PKIHEADER), ASN1_SIMPLE(OSSL_CMP_MSG, body, OSSL_CMP_PKIBODY), ASN1_EXP_OPT(OSSL_CMP_MSG, protection, ASN1_BIT_STRING, 0), /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_MSG, extraCerts, X509, 1) } ASN1_SEQUENCE_END_cb(OSSL_CMP_MSG, OSSL_CMP_MSG) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CMP_MSG) ASN1_ITEM_TEMPLATE(OSSL_CMP_MSGS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_MSGS, OSSL_CMP_MSG) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_MSGS)
./openssl/crypto/cmp/cmp_genm.c
/* * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Siemens AG 2022 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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 "cmp_local.h" #include <openssl/cmp_util.h> static const X509_VERIFY_PARAM *get0_trustedStore_vpm(const OSSL_CMP_CTX *ctx) { const X509_STORE *ts = OSSL_CMP_CTX_get0_trustedStore(ctx); return ts == NULL ? NULL : X509_STORE_get0_param(ts); } static void cert_msg(const char *func, const char *file, int lineno, OSSL_CMP_severity level, OSSL_CMP_CTX *ctx, const char *source, X509 *cert, const char *msg) { char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0); ossl_cmp_print_log(level, ctx, func, file, lineno, level == OSSL_CMP_LOG_WARNING ? "WARN" : "ERR", "certificate from '%s' with subject '%s' %s", source, subj, msg); OPENSSL_free(subj); } /* use |type_CA| -1 (no CA type check) or 0 (must be EE) or 1 (must be CA) */ static int ossl_X509_check(OSSL_CMP_CTX *ctx, const char *source, X509 *cert, int type_CA, const X509_VERIFY_PARAM *vpm) { uint32_t ex_flags = X509_get_extension_flags(cert); int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert), X509_get0_notAfter(cert)); int ret = res == 0; OSSL_CMP_severity level = vpm == NULL ? OSSL_CMP_LOG_WARNING : OSSL_CMP_LOG_ERR; if (!ret) cert_msg(OPENSSL_FUNC, OPENSSL_FILE, OPENSSL_LINE, level, ctx, source, cert, res > 0 ? "has expired" : "not yet valid"); if (type_CA >= 0 && (ex_flags & EXFLAG_V1) == 0) { int is_CA = (ex_flags & EXFLAG_CA) != 0; if ((type_CA != 0) != is_CA) { cert_msg(OPENSSL_FUNC, OPENSSL_FILE, OPENSSL_LINE, level, ctx, source, cert, is_CA ? "is not an EE cert" : "is not a CA cert"); ret = 0; } } return ret; } static int ossl_X509_check_all(OSSL_CMP_CTX *ctx, const char *source, STACK_OF(X509) *certs, int type_CA, const X509_VERIFY_PARAM *vpm) { int i; int ret = 1; for (i = 0; i < sk_X509_num(certs /* may be NULL */); i++) ret = ossl_X509_check(ctx, source, sk_X509_value(certs, i), type_CA, vpm) && ret; /* Having 'ret' after the '&&', all certs are checked. */ return ret; } static OSSL_CMP_ITAV *get_genm_itav(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *req, /* gets consumed */ int expected, const char *desc) { STACK_OF(OSSL_CMP_ITAV) *itavs = NULL; int i, n; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); goto err; } if (OSSL_CMP_CTX_get_status(ctx) != OSSL_CMP_PKISTATUS_unspecified) { ERR_raise_data(ERR_LIB_CMP, CMP_R_UNCLEAN_CTX, "client context in unsuitable state; should call CMPclient_reinit() before"); goto err; } if (!OSSL_CMP_CTX_push0_genm_ITAV(ctx, req)) goto err; req = NULL; itavs = OSSL_CMP_exec_GENM_ses(ctx); if (itavs == NULL) { if (OSSL_CMP_CTX_get_status(ctx) != OSSL_CMP_PKISTATUS_request) ERR_raise_data(ERR_LIB_CMP, CMP_R_GETTING_GENP, "with infoType %s", desc); return NULL; } if ((n = sk_OSSL_CMP_ITAV_num(itavs)) <= 0) { ERR_raise_data(ERR_LIB_CMP, CMP_R_INVALID_GENP, "response on genm requesting infoType %s does not include suitable value", desc); sk_OSSL_CMP_ITAV_free(itavs); return NULL; } if (n > 1) ossl_cmp_log2(WARN, ctx, "response on genm contains %d ITAVs; will use the first ITAV with infoType id-it-%s", n, desc); for (i = 0; i < n; i++) { OSSL_CMP_ITAV *itav = sk_OSSL_CMP_ITAV_shift(itavs); ASN1_OBJECT *obj = OSSL_CMP_ITAV_get0_type(itav); char name[128] = "genp contains InfoType '"; size_t offset = strlen(name); if (OBJ_obj2nid(obj) == expected) { for (i++; i < n; i++) OSSL_CMP_ITAV_free(sk_OSSL_CMP_ITAV_shift(itavs)); sk_OSSL_CMP_ITAV_free(itavs); return itav; } if (OBJ_obj2txt(name + offset, sizeof(name) - offset, obj, 0) < 0) strcat(name, "<unknown>"); ossl_cmp_log2(WARN, ctx, "%s' while expecting 'id-it-%s'", name, desc); OSSL_CMP_ITAV_free(itav); } ERR_raise_data(ERR_LIB_CMP, CMP_R_INVALID_GENP, "could not find any ITAV for %s", desc); err: sk_OSSL_CMP_ITAV_free(itavs); OSSL_CMP_ITAV_free(req); return NULL; } int OSSL_CMP_get1_caCerts(OSSL_CMP_CTX *ctx, STACK_OF(X509) **out) { OSSL_CMP_ITAV *req, *itav; STACK_OF(X509) *certs = NULL; int ret = 0; if (out == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } *out = NULL; if ((req = OSSL_CMP_ITAV_new_caCerts(NULL)) == NULL) return 0; if ((itav = get_genm_itav(ctx, req, NID_id_it_caCerts, "caCerts")) == NULL) return 0; if (!OSSL_CMP_ITAV_get0_caCerts(itav, &certs)) goto end; ret = 1; if (certs == NULL) /* no CA certificate available */ goto end; if (!ossl_X509_check_all(ctx, "genp", certs, 1 /* CA */, get0_trustedStore_vpm(ctx))) { ret = 0; goto end; } *out = sk_X509_new_reserve(NULL, sk_X509_num(certs)); if (!X509_add_certs(*out, certs, X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP)) { sk_X509_pop_free(*out, X509_free); *out = NULL; ret = 0; } end: OSSL_CMP_ITAV_free(itav); return ret; } static int selfsigned_verify_cb(int ok, X509_STORE_CTX *store_ctx) { if (ok == 0 && X509_STORE_CTX_get_error_depth(store_ctx) == 0 && X509_STORE_CTX_get_error(store_ctx) == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) { /* in this case, custom chain building */ int i; STACK_OF(X509) *trust; STACK_OF(X509) *chain = X509_STORE_CTX_get0_chain(store_ctx); STACK_OF(X509) *untrusted = X509_STORE_CTX_get0_untrusted(store_ctx); X509_STORE_CTX_check_issued_fn check_issued = X509_STORE_CTX_get_check_issued(store_ctx); X509 *cert = sk_X509_value(chain, 0); /* target cert */ X509 *issuer; for (i = 0; i < sk_X509_num(untrusted); i++) { cert = sk_X509_value(untrusted, i); if (!X509_add_cert(chain, cert, X509_ADD_FLAG_UP_REF)) return 0; } trust = X509_STORE_get1_all_certs(X509_STORE_CTX_get0_store(store_ctx)); for (i = 0; i < sk_X509_num(trust); i++) { issuer = sk_X509_value(trust, i); if ((*check_issued)(store_ctx, cert, issuer)) { if (X509_add_cert(chain, cert, X509_ADD_FLAG_UP_REF)) ok = 1; break; } } sk_X509_pop_free(trust, X509_free); return ok; } else { X509_STORE *ts = X509_STORE_CTX_get0_store(store_ctx); X509_STORE_CTX_verify_cb verify_cb; if (ts == NULL || (verify_cb = X509_STORE_get_verify_cb(ts)) == NULL) return ok; return (*verify_cb)(ok, store_ctx); } } /* vanilla X509_verify_cert() does not support self-signed certs as target */ static int verify_ss_cert(OSSL_LIB_CTX *libctx, const char *propq, X509_STORE *ts, STACK_OF(X509) *untrusted, X509 *target) { X509_STORE_CTX *csc = NULL; int ok = 0; if (ts == NULL || target == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((csc = X509_STORE_CTX_new_ex(libctx, propq)) == NULL || !X509_STORE_CTX_init(csc, ts, target, untrusted)) goto err; X509_STORE_CTX_set_verify_cb(csc, selfsigned_verify_cb); ok = X509_verify_cert(csc) > 0; err: X509_STORE_CTX_free(csc); return ok; } static int verify_ss_cert_trans(OSSL_CMP_CTX *ctx, X509 *trusted /* may be NULL */, X509 *trans /* the only untrusted cert, may be NULL */, X509 *target, const char *desc) { X509_STORE *ts = OSSL_CMP_CTX_get0_trusted(ctx); STACK_OF(X509) *untrusted = NULL; int res = 0; if (trusted != NULL) { X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts); if ((ts = X509_STORE_new()) == NULL) return 0; if (!X509_STORE_set1_param(ts, vpm) || !X509_STORE_add_cert(ts, trusted)) goto err; } if (trans != NULL && !ossl_x509_add_cert_new(&untrusted, trans, X509_ADD_FLAG_UP_REF)) goto err; res = verify_ss_cert(OSSL_CMP_CTX_get0_libctx(ctx), OSSL_CMP_CTX_get0_propq(ctx), ts, untrusted, target); if (!res) ERR_raise_data(ERR_LIB_CMP, CMP_R_INVALID_ROOTCAKEYUPDATE, "failed to validate %s certificate received in genp %s", desc, trusted == NULL ? "using trust store" : "with given certificate as trust anchor"); err: sk_X509_pop_free(untrusted, X509_free); if (trusted != NULL) X509_STORE_free(ts); return res; } int OSSL_CMP_get1_rootCaKeyUpdate(OSSL_CMP_CTX *ctx, const X509 *oldWithOld, X509 **newWithNew, X509 **newWithOld, X509 **oldWithNew) { X509 *oldWithOld_copy = NULL, *my_newWithOld, *my_oldWithNew; OSSL_CMP_ITAV *req, *itav; int res = 0; if (newWithNew == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_NULL_PARAMETER); return 0; } *newWithNew = NULL; if ((req = OSSL_CMP_ITAV_new_rootCaCert(oldWithOld)) == NULL) return 0; itav = get_genm_itav(ctx, req, NID_id_it_rootCaKeyUpdate, "rootCaKeyUpdate"); if (itav == NULL) return 0; if (!OSSL_CMP_ITAV_get0_rootCaKeyUpdate(itav, newWithNew, &my_newWithOld, &my_oldWithNew)) goto end; if (*newWithNew == NULL) /* no root CA cert update available */ goto end; if ((oldWithOld_copy = X509_dup(oldWithOld)) == NULL && oldWithOld != NULL) goto end; if (!verify_ss_cert_trans(ctx, oldWithOld_copy, my_newWithOld, *newWithNew, "newWithNew")) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ROOTCAKEYUPDATE); goto end; } if (oldWithOld != NULL && my_oldWithNew != NULL && !verify_ss_cert_trans(ctx, *newWithNew, my_oldWithNew, oldWithOld_copy, "oldWithOld")) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ROOTCAKEYUPDATE); goto end; } if (!X509_up_ref(*newWithNew)) goto end; if (newWithOld != NULL && (*newWithOld = my_newWithOld) != NULL && !X509_up_ref(*newWithOld)) goto free; if (oldWithNew == NULL || (*oldWithNew = my_oldWithNew) == NULL || X509_up_ref(*oldWithNew)) { res = 1; goto end; } if (newWithOld != NULL) X509_free(*newWithOld); free: X509_free(*newWithNew); end: OSSL_CMP_ITAV_free(itav); X509_free(oldWithOld_copy); return res; }
./openssl/crypto/cmp/cmp_server.c
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* general CMP server functions */ #include <openssl/asn1t.h> #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/cmp.h> #include <openssl/err.h> /* the context for the generic CMP server */ struct ossl_cmp_srv_ctx_st { OSSL_CMP_CTX *ctx; /* CMP client context reused for transactionID etc. */ void *custom_ctx; /* application-specific server context */ int certReqId; /* of ir/cr/kur, OSSL_CMP_CERTREQID_NONE for p10cr */ int polling; /* current transaction is in polling mode */ OSSL_CMP_SRV_cert_request_cb_t process_cert_request; OSSL_CMP_SRV_rr_cb_t process_rr; OSSL_CMP_SRV_genm_cb_t process_genm; OSSL_CMP_SRV_error_cb_t process_error; OSSL_CMP_SRV_certConf_cb_t process_certConf; OSSL_CMP_SRV_pollReq_cb_t process_pollReq; OSSL_CMP_SRV_delayed_delivery_cb_t delayed_delivery; OSSL_CMP_SRV_clean_transaction_cb_t clean_transaction; int sendUnprotectedErrors; /* Send error and rejection msgs unprotected */ int acceptUnprotected; /* Accept requests with no/invalid prot. */ int acceptRAVerified; /* Accept ir/cr/kur with POPO RAVerified */ int grantImplicitConfirm; /* Grant implicit confirmation if requested */ }; /* OSSL_CMP_SRV_CTX */ void OSSL_CMP_SRV_CTX_free(OSSL_CMP_SRV_CTX *srv_ctx) { if (srv_ctx == NULL) return; OSSL_CMP_CTX_free(srv_ctx->ctx); OPENSSL_free(srv_ctx); } OSSL_CMP_SRV_CTX *OSSL_CMP_SRV_CTX_new(OSSL_LIB_CTX *libctx, const char *propq) { OSSL_CMP_SRV_CTX *ctx = OPENSSL_zalloc(sizeof(OSSL_CMP_SRV_CTX)); if (ctx == NULL) goto err; if ((ctx->ctx = OSSL_CMP_CTX_new(libctx, propq)) == NULL) goto err; ctx->certReqId = OSSL_CMP_CERTREQID_INVALID; ctx->polling = 0; /* all other elements are initialized to 0 or NULL, respectively */ return ctx; err: OSSL_CMP_SRV_CTX_free(ctx); return NULL; } int OSSL_CMP_SRV_CTX_init(OSSL_CMP_SRV_CTX *srv_ctx, void *custom_ctx, OSSL_CMP_SRV_cert_request_cb_t process_cert_request, OSSL_CMP_SRV_rr_cb_t process_rr, OSSL_CMP_SRV_genm_cb_t process_genm, OSSL_CMP_SRV_error_cb_t process_error, OSSL_CMP_SRV_certConf_cb_t process_certConf, OSSL_CMP_SRV_pollReq_cb_t process_pollReq) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } srv_ctx->custom_ctx = custom_ctx; srv_ctx->process_cert_request = process_cert_request; srv_ctx->process_rr = process_rr; srv_ctx->process_genm = process_genm; srv_ctx->process_error = process_error; srv_ctx->process_certConf = process_certConf; srv_ctx->process_pollReq = process_pollReq; return 1; } int OSSL_CMP_SRV_CTX_init_trans(OSSL_CMP_SRV_CTX *srv_ctx, OSSL_CMP_SRV_delayed_delivery_cb_t delay, OSSL_CMP_SRV_clean_transaction_cb_t clean) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } srv_ctx->delayed_delivery = delay; srv_ctx->clean_transaction = clean; return 1; } OSSL_CMP_CTX *OSSL_CMP_SRV_CTX_get0_cmp_ctx(const OSSL_CMP_SRV_CTX *srv_ctx) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return srv_ctx->ctx; } void *OSSL_CMP_SRV_CTX_get0_custom_ctx(const OSSL_CMP_SRV_CTX *srv_ctx) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return srv_ctx->custom_ctx; } int OSSL_CMP_SRV_CTX_set_send_unprotected_errors(OSSL_CMP_SRV_CTX *srv_ctx, int val) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } srv_ctx->sendUnprotectedErrors = val != 0; return 1; } int OSSL_CMP_SRV_CTX_set_accept_unprotected(OSSL_CMP_SRV_CTX *srv_ctx, int val) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } srv_ctx->acceptUnprotected = val != 0; return 1; } int OSSL_CMP_SRV_CTX_set_accept_raverified(OSSL_CMP_SRV_CTX *srv_ctx, int val) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } srv_ctx->acceptRAVerified = val != 0; return 1; } int OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(OSSL_CMP_SRV_CTX *srv_ctx, int val) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } srv_ctx->grantImplicitConfirm = val != 0; return 1; } /* return error msg with waiting status if polling is initiated, else NULL */ static OSSL_CMP_MSG *delayed_delivery(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { int ret; unsigned long err; int status = OSSL_CMP_PKISTATUS_waiting, fail_info = 0, errorCode = 0; const char *txt = NULL, *details = NULL; OSSL_CMP_PKISI *si; OSSL_CMP_MSG *msg; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL && srv_ctx->delayed_delivery != NULL)) return NULL; ret = srv_ctx->delayed_delivery(srv_ctx, req); if (ret == 0) return NULL; if (ret == 1) { srv_ctx->polling = 1; } else { status = OSSL_CMP_PKISTATUS_rejection; fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_systemFailure; txt = "server application error"; err = ERR_peek_error(); errorCode = ERR_GET_REASON(err); details = ERR_reason_error_string(err); } si = OSSL_CMP_STATUSINFO_new(status, fail_info, txt); if (si == NULL) return NULL; msg = ossl_cmp_error_new(srv_ctx->ctx, si, errorCode, details, srv_ctx->sendUnprotectedErrors); OSSL_CMP_PKISI_free(si); return msg; } /* * Processes an ir/cr/p10cr/kur and returns a certification response. * Only handles the first certification request contained in req * returns an ip/cp/kup on success and NULL on error */ static OSSL_CMP_MSG *process_cert_request(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_MSG *msg = NULL; OSSL_CMP_PKISI *si = NULL; X509 *certOut = NULL; STACK_OF(X509) *chainOut = NULL, *caPubs = NULL; const OSSL_CRMF_MSG *crm = NULL; const X509_REQ *p10cr = NULL; int bodytype; int certReqId; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; switch (OSSL_CMP_MSG_get_bodytype(req)) { case OSSL_CMP_PKIBODY_P10CR: case OSSL_CMP_PKIBODY_CR: bodytype = OSSL_CMP_PKIBODY_CP; break; case OSSL_CMP_PKIBODY_IR: bodytype = OSSL_CMP_PKIBODY_IP; break; case OSSL_CMP_PKIBODY_KUR: bodytype = OSSL_CMP_PKIBODY_KUP; break; default: ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); return NULL; } if (OSSL_CMP_MSG_get_bodytype(req) == OSSL_CMP_PKIBODY_P10CR) { certReqId = OSSL_CMP_CERTREQID_NONE; /* p10cr does not include an Id */ p10cr = req->body->value.p10cr; } else { OSSL_CRMF_MSGS *reqs = req->body->value.ir; /* same for cr and kur */ if (sk_OSSL_CRMF_MSG_num(reqs) != 1) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_REQUESTS_NOT_SUPPORTED); return NULL; } if ((crm = sk_OSSL_CRMF_MSG_value(reqs, 0)) == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_CERTREQMSG_NOT_FOUND); return NULL; } certReqId = OSSL_CRMF_MSG_get_certReqId(crm); if (certReqId != OSSL_CMP_CERTREQID) { /* so far, only possible value */ ERR_raise(ERR_LIB_CMP, CMP_R_BAD_REQUEST_ID); return NULL; } } srv_ctx->certReqId = certReqId; if (!ossl_cmp_verify_popo(srv_ctx->ctx, req, srv_ctx->acceptRAVerified)) { /* Proof of possession could not be verified */ si = OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_rejection, 1 << OSSL_CMP_PKIFAILUREINFO_badPOP, ERR_reason_error_string(ERR_peek_error())); if (si == NULL) return NULL; } else { OSSL_CMP_PKIHEADER *hdr = OSSL_CMP_MSG_get0_header(req); si = srv_ctx->process_cert_request(srv_ctx, req, certReqId, crm, p10cr, &certOut, &chainOut, &caPubs); if (si == NULL) goto err; if (ossl_cmp_pkisi_get_status(si) == OSSL_CMP_PKISTATUS_waiting) srv_ctx->polling = 1; /* set OSSL_CMP_OPT_IMPLICIT_CONFIRM if and only if transaction ends */ if (!OSSL_CMP_CTX_set_option(srv_ctx->ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM, ossl_cmp_hdr_has_implicitConfirm(hdr) && srv_ctx->grantImplicitConfirm /* do not set if polling starts: */ && certOut != NULL)) goto err; } msg = ossl_cmp_certrep_new(srv_ctx->ctx, bodytype, certReqId, si, certOut, NULL /* enc */, chainOut, caPubs, srv_ctx->sendUnprotectedErrors); /* When supporting OSSL_CRMF_POPO_KEYENC, "enc" will need to be set */ if (msg == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_CERTREP); err: OSSL_CMP_PKISI_free(si); X509_free(certOut); OSSL_STACK_OF_X509_free(chainOut); OSSL_STACK_OF_X509_free(caPubs); return msg; } static OSSL_CMP_MSG *process_rr(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_MSG *msg = NULL; OSSL_CMP_REVDETAILS *details; OSSL_CRMF_CERTID *certId = NULL; OSSL_CRMF_CERTTEMPLATE *tmpl; const X509_NAME *issuer; const ASN1_INTEGER *serial; OSSL_CMP_PKISI *si; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; if (sk_OSSL_CMP_REVDETAILS_num(req->body->value.rr) != 1) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_REQUESTS_NOT_SUPPORTED); return NULL; } details = sk_OSSL_CMP_REVDETAILS_value(req->body->value.rr, 0); if (details == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return NULL; } tmpl = details->certDetails; issuer = OSSL_CRMF_CERTTEMPLATE_get0_issuer(tmpl); serial = OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(tmpl); if (issuer != NULL && serial != NULL && (certId = OSSL_CRMF_CERTID_gen(issuer, serial)) == NULL) return NULL; if ((si = srv_ctx->process_rr(srv_ctx, req, issuer, serial)) == NULL) goto err; if ((msg = ossl_cmp_rp_new(srv_ctx->ctx, si, certId, srv_ctx->sendUnprotectedErrors)) == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_RR); err: OSSL_CRMF_CERTID_free(certId); OSSL_CMP_PKISI_free(si); return msg; } /* * Processes genm and creates a genp message mirroring the contents of the * incoming message */ static OSSL_CMP_MSG *process_genm(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_GENMSGCONTENT *itavs; OSSL_CMP_MSG *msg; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; if (!srv_ctx->process_genm(srv_ctx, req, req->body->value.genm, &itavs)) return NULL; msg = ossl_cmp_genp_new(srv_ctx->ctx, itavs); sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free); return msg; } static OSSL_CMP_MSG *process_error(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_ERRORMSGCONTENT *errorContent; OSSL_CMP_MSG *msg; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; errorContent = req->body->value.error; srv_ctx->process_error(srv_ctx, req, errorContent->pKIStatusInfo, errorContent->errorCode, errorContent->errorDetails); if ((msg = ossl_cmp_pkiconf_new(srv_ctx->ctx)) == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_PKICONF); return msg; } static OSSL_CMP_MSG *process_certConf(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_CTX *ctx; OSSL_CMP_CERTCONFIRMCONTENT *ccc; int num; OSSL_CMP_MSG *msg = NULL; OSSL_CMP_CERTSTATUS *status = NULL; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; ctx = srv_ctx->ctx; ccc = req->body->value.certConf; num = sk_OSSL_CMP_CERTSTATUS_num(ccc); if (OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM) == 1 || ctx->status != OSSL_CMP_PKISTATUS_trans) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_UNEXPECTED_CERTCONF); return NULL; } if (num == 0) { ossl_cmp_err(ctx, "certificate rejected by client"); } else { if (num > 1) ossl_cmp_warn(ctx, "All CertStatus but the first will be ignored"); status = sk_OSSL_CMP_CERTSTATUS_value(ccc, 0); } if (status != NULL) { int certReqId = ossl_cmp_asn1_get_int(status->certReqId); ASN1_OCTET_STRING *certHash = status->certHash; OSSL_CMP_PKISI *si = status->statusInfo; if (certReqId != srv_ctx->certReqId) { ERR_raise(ERR_LIB_CMP, CMP_R_BAD_REQUEST_ID); return NULL; } if (!srv_ctx->process_certConf(srv_ctx, req, certReqId, certHash, si)) return NULL; /* reason code may be: CMP_R_CERTHASH_UNMATCHED */ if (si != NULL && ossl_cmp_pkisi_get_status(si) != OSSL_CMP_PKISTATUS_accepted) { int pki_status = ossl_cmp_pkisi_get_status(si); const char *str = ossl_cmp_PKIStatus_to_string(pki_status); ossl_cmp_log2(INFO, ctx, "certificate rejected by client %s %s", str == NULL ? "without" : "with", str == NULL ? "PKIStatus" : str); } } if ((msg = ossl_cmp_pkiconf_new(ctx)) == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_PKICONF); return msg; } /* pollReq is handled separately, to avoid recursive call */ static OSSL_CMP_MSG *process_non_polling_request(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_MSG *rsp = NULL; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL && req->body != NULL)) return NULL; switch (OSSL_CMP_MSG_get_bodytype(req)) { case OSSL_CMP_PKIBODY_IR: case OSSL_CMP_PKIBODY_CR: case OSSL_CMP_PKIBODY_P10CR: case OSSL_CMP_PKIBODY_KUR: if (srv_ctx->process_cert_request == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PKIBODY); else rsp = process_cert_request(srv_ctx, req); break; case OSSL_CMP_PKIBODY_RR: if (srv_ctx->process_rr == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PKIBODY); else rsp = process_rr(srv_ctx, req); break; case OSSL_CMP_PKIBODY_GENM: if (srv_ctx->process_genm == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PKIBODY); else rsp = process_genm(srv_ctx, req); break; case OSSL_CMP_PKIBODY_ERROR: if (srv_ctx->process_error == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PKIBODY); else rsp = process_error(srv_ctx, req); break; case OSSL_CMP_PKIBODY_CERTCONF: if (srv_ctx->process_certConf == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PKIBODY); else rsp = process_certConf(srv_ctx, req); break; case OSSL_CMP_PKIBODY_POLLREQ: ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); break; default: ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PKIBODY); break; } return rsp; } static OSSL_CMP_MSG *process_pollReq(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_POLLREQCONTENT *prc; OSSL_CMP_POLLREQ *pr; int certReqId; OSSL_CMP_MSG *orig_req; int64_t check_after = 0; OSSL_CMP_MSG *msg = NULL; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; if (!srv_ctx->polling) { ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); return NULL; } prc = req->body->value.pollReq; if (sk_OSSL_CMP_POLLREQ_num(prc) != 1) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_REQUESTS_NOT_SUPPORTED); return NULL; } pr = sk_OSSL_CMP_POLLREQ_value(prc, 0); certReqId = ossl_cmp_asn1_get_int(pr->certReqId); if (!srv_ctx->process_pollReq(srv_ctx, req, certReqId, &orig_req, &check_after)) return NULL; if (orig_req != NULL) { srv_ctx->polling = 0; msg = process_non_polling_request(srv_ctx, orig_req); OSSL_CMP_MSG_free(orig_req); } else { if ((msg = ossl_cmp_pollRep_new(srv_ctx->ctx, certReqId, check_after)) == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_POLLREP); } return msg; } /* * Determine whether missing/invalid protection of request message is allowed. * Return 1 on acceptance, 0 on rejection, or -1 on (internal) error. */ static int unprotected_exception(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req, int invalid_protection, int accept_unprotected_requests) { if (!ossl_assert(ctx != NULL && req != NULL)) return -1; if (accept_unprotected_requests) { ossl_cmp_log1(WARN, ctx, "ignoring %s protection of request message", invalid_protection ? "invalid" : "missing"); return 1; } if (OSSL_CMP_MSG_get_bodytype(req) == OSSL_CMP_PKIBODY_ERROR && OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS) == 1) { ossl_cmp_warn(ctx, "ignoring missing protection of error message"); return 1; } return 0; } /* * returns created message and NULL on internal error */ OSSL_CMP_MSG *OSSL_CMP_SRV_process_request(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_CTX *ctx; ASN1_OCTET_STRING *backup_secret; OSSL_CMP_PKIHEADER *hdr; int req_type, rsp_type; int req_verified = 0; OSSL_CMP_MSG *rsp = NULL; if (srv_ctx == NULL || srv_ctx->ctx == NULL || req == NULL || req->body == NULL || (hdr = OSSL_CMP_MSG_get0_header(req)) == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } ctx = srv_ctx->ctx; backup_secret = ctx->secretValue; req_type = OSSL_CMP_MSG_get_bodytype(req); ossl_cmp_log1(DEBUG, ctx, "received %s", ossl_cmp_bodytype_to_string(req_type)); /* * Some things need to be done already before validating the message in * order to be able to send an error message as far as needed and possible. */ if (hdr->sender->type != GEN_DIRNAME) { ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED); goto err; } if (!OSSL_CMP_CTX_set1_recipient(ctx, hdr->sender->d.directoryName)) goto err; if (srv_ctx->polling && req_type != OSSL_CMP_PKIBODY_POLLREQ && req_type != OSSL_CMP_PKIBODY_ERROR) { ERR_raise(ERR_LIB_CMP, CMP_R_EXPECTED_POLLREQ); goto err; } switch (req_type) { case OSSL_CMP_PKIBODY_IR: case OSSL_CMP_PKIBODY_CR: case OSSL_CMP_PKIBODY_P10CR: case OSSL_CMP_PKIBODY_KUR: case OSSL_CMP_PKIBODY_RR: case OSSL_CMP_PKIBODY_GENM: case OSSL_CMP_PKIBODY_ERROR: if (ctx->transactionID != NULL) { char *tid = i2s_ASN1_OCTET_STRING(NULL, ctx->transactionID); if (tid != NULL) ossl_cmp_log1(WARN, ctx, "Assuming that last transaction with ID=%s got aborted", tid); OPENSSL_free(tid); } /* start of a new transaction, reset transactionID and senderNonce */ if (!OSSL_CMP_CTX_set1_transactionID(ctx, NULL) || !OSSL_CMP_CTX_set1_senderNonce(ctx, NULL)) goto err; if (srv_ctx->clean_transaction != NULL && !srv_ctx->clean_transaction(srv_ctx, NULL)) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); goto err; } break; default: /* transactionID should be already initialized */ if (ctx->transactionID == NULL) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); goto err; #endif } } req_verified = ossl_cmp_msg_check_update(ctx, req, unprotected_exception, srv_ctx->acceptUnprotected); if (ctx->secretValue != NULL && ctx->pkey != NULL && ossl_cmp_hdr_get_protection_nid(hdr) != NID_id_PasswordBasedMAC) ctx->secretValue = NULL; /* use MSG_SIG_ALG when protecting rsp */ if (!req_verified) goto err; if (req_type == OSSL_CMP_PKIBODY_POLLREQ) { if (srv_ctx->process_pollReq == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PKIBODY); else rsp = process_pollReq(srv_ctx, req); } else { if (srv_ctx->delayed_delivery != NULL && (rsp = delayed_delivery(srv_ctx, req)) != NULL) { goto err; } rsp = process_non_polling_request(srv_ctx, req); } err: if (rsp == NULL) { /* on error, try to respond with CMP error message to client */ const char *data = NULL, *reason = NULL; int flags = 0; unsigned long err = ERR_peek_error_data(&data, &flags); int fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_badRequest; /* fail_info is not very specific */ OSSL_CMP_PKISI *si = NULL; if (!req_verified) { /* * Above ossl_cmp_msg_check_update() was not successfully executed, * which normally would set ctx->transactionID and ctx->recipNonce. * So anyway try to provide the right transactionID and recipNonce, * while ignoring any (extra) error in next two function calls. */ if (ctx->transactionID == NULL) (void)OSSL_CMP_CTX_set1_transactionID(ctx, hdr->transactionID); (void)ossl_cmp_ctx_set1_recipNonce(ctx, hdr->senderNonce); } if ((flags & ERR_TXT_STRING) == 0 || *data == '\0') data = NULL; reason = ERR_reason_error_string(err); if ((si = OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_rejection, fail_info, reason)) != NULL) { rsp = ossl_cmp_error_new(srv_ctx->ctx, si, err, data, srv_ctx->sendUnprotectedErrors); OSSL_CMP_PKISI_free(si); } } OSSL_CMP_CTX_print_errors(ctx); ctx->secretValue = backup_secret; rsp_type = rsp != NULL ? OSSL_CMP_MSG_get_bodytype(rsp) : OSSL_CMP_PKIBODY_ERROR; if (rsp != NULL) ossl_cmp_log1(DEBUG, ctx, "sending %s", ossl_cmp_bodytype_to_string(rsp_type)); else ossl_cmp_log(ERR, ctx, "cannot send proper CMP response"); /* determine whether to keep the transaction open or not */ ctx->status = OSSL_CMP_PKISTATUS_trans; switch (rsp_type) { case OSSL_CMP_PKIBODY_IP: case OSSL_CMP_PKIBODY_CP: case OSSL_CMP_PKIBODY_KUP: if (OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM) == 0) break; /* fall through */ case OSSL_CMP_PKIBODY_ERROR: if (rsp != NULL && ossl_cmp_is_error_with_waiting(rsp)) break; /* fall through */ case OSSL_CMP_PKIBODY_RP: case OSSL_CMP_PKIBODY_PKICONF: case OSSL_CMP_PKIBODY_GENP: /* Other terminating response message types are not supported */ srv_ctx->certReqId = OSSL_CMP_CERTREQID_INVALID; /* Prepare for next transaction, ignoring any errors here: */ if (srv_ctx->clean_transaction != NULL) (void)srv_ctx->clean_transaction(srv_ctx, ctx->transactionID); (void)OSSL_CMP_CTX_set1_transactionID(ctx, NULL); (void)OSSL_CMP_CTX_set1_senderNonce(ctx, NULL); ctx->status = OSSL_CMP_PKISTATUS_unspecified; /* transaction closed */ default: /* not closing transaction in other cases */ break; } return rsp; } /* * Server interface that may substitute OSSL_CMP_MSG_http_perform at the client. * The OSSL_CMP_SRV_CTX must be set as client_ctx->transfer_cb_arg. * returns received message on success, else NULL and pushes an element on the * error stack. */ OSSL_CMP_MSG *OSSL_CMP_CTX_server_perform(OSSL_CMP_CTX *client_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_SRV_CTX *srv_ctx = NULL; if (client_ctx == NULL || req == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } if ((srv_ctx = OSSL_CMP_CTX_get_transfer_cb_arg(client_ctx)) == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_TRANSFER_ERROR); return NULL; } return OSSL_CMP_SRV_process_request(srv_ctx, req); }
./openssl/crypto/cmp/cmp_vfy.c
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2020 * Copyright Siemens AG 2015-2020 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* CMP functions for PKIMessage checking */ #include "cmp_local.h" #include <openssl/cmp_util.h> /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/asn1t.h> #include <openssl/cmp.h> #include <openssl/crmf.h> #include <openssl/err.h> #include <openssl/x509.h> /* Verify a message protected by signature according to RFC section 5.1.3.3 */ static int verify_signature(const OSSL_CMP_CTX *cmp_ctx, const OSSL_CMP_MSG *msg, X509 *cert) { OSSL_CMP_PROTECTEDPART prot_part; EVP_PKEY *pubkey = NULL; BIO *bio; int res = 0; if (!ossl_assert(cmp_ctx != NULL && msg != NULL && cert != NULL)) return 0; bio = BIO_new(BIO_s_mem()); /* may be NULL */ if (bio == NULL) return 0; /* verify that keyUsage, if present, contains digitalSignature */ if (!cmp_ctx->ignore_keyusage && (X509_get_key_usage(cert) & X509v3_KU_DIGITAL_SIGNATURE) == 0) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE); goto sig_err; } pubkey = X509_get_pubkey(cert); if (pubkey == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_FAILED_EXTRACTING_PUBKEY); goto sig_err; } prot_part.header = msg->header; prot_part.body = msg->body; if (ASN1_item_verify_ex(ASN1_ITEM_rptr(OSSL_CMP_PROTECTEDPART), msg->header->protectionAlg, msg->protection, &prot_part, NULL, pubkey, cmp_ctx->libctx, cmp_ctx->propq) > 0) { res = 1; goto end; } sig_err: res = ossl_x509_print_ex_brief(bio, cert, X509_FLAG_NO_EXTENSIONS); ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_SIGNATURE); if (res) ERR_add_error_mem_bio("\n", bio); res = 0; end: EVP_PKEY_free(pubkey); BIO_free(bio); return res; } /* Verify a message protected with PBMAC */ static int verify_PBMAC(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg) { ASN1_BIT_STRING *protection = NULL; int valid = 0; /* generate expected protection for the message */ if ((protection = ossl_cmp_calc_protection(ctx, msg)) == NULL) return 0; /* failed to generate protection string! */ valid = msg->protection != NULL && msg->protection->length >= 0 && msg->protection->type == protection->type && msg->protection->length == protection->length && CRYPTO_memcmp(msg->protection->data, protection->data, protection->length) == 0; ASN1_BIT_STRING_free(protection); if (!valid) ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_PBM_VALUE); return valid; } /*- * Attempt to validate certificate and path using any given store with trusted * certs (possibly including CRLs and a cert verification callback function) * and non-trusted intermediate certs from the given ctx. * * Returns 1 on successful validation and 0 otherwise. */ int OSSL_CMP_validate_cert_path(const OSSL_CMP_CTX *ctx, X509_STORE *trusted_store, X509 *cert) { int valid = 0; X509_STORE_CTX *csc = NULL; int err; if (ctx == NULL || cert == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (trusted_store == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_STORE); return 0; } if ((csc = X509_STORE_CTX_new_ex(ctx->libctx, ctx->propq)) == NULL || !X509_STORE_CTX_init(csc, trusted_store, cert, ctx->untrusted)) goto err; valid = X509_verify_cert(csc) > 0; /* make sure suitable error is queued even if callback did not do */ err = ERR_peek_last_error(); if (!valid && ERR_GET_REASON(err) != CMP_R_POTENTIALLY_INVALID_CERTIFICATE) ERR_raise(ERR_LIB_CMP, CMP_R_POTENTIALLY_INVALID_CERTIFICATE); err: /* directly output any fresh errors, needed for check_msg_find_cert() */ OSSL_CMP_CTX_print_errors(ctx); X509_STORE_CTX_free(csc); return valid; } static int verify_cb_cert(X509_STORE *ts, X509 *cert, int err) { X509_STORE_CTX_verify_cb verify_cb; X509_STORE_CTX *csc; int ok = 0; if (ts == NULL || (verify_cb = X509_STORE_get_verify_cb(ts)) == NULL) return ok; if ((csc = X509_STORE_CTX_new()) != NULL && X509_STORE_CTX_init(csc, ts, cert, NULL)) { X509_STORE_CTX_set_error(csc, err); X509_STORE_CTX_set_current_cert(csc, cert); ok = (*verify_cb)(0, csc); } X509_STORE_CTX_free(csc); return ok; } /* Return 0 if expect_name != NULL and there is no matching actual_name */ static int check_name(const OSSL_CMP_CTX *ctx, int log_success, const char *actual_desc, const X509_NAME *actual_name, const char *expect_desc, const X509_NAME *expect_name) { char *str; if (expect_name == NULL) return 1; /* no expectation, thus trivially fulfilled */ /* make sure that a matching name is there */ if (actual_name == NULL) { ossl_cmp_log1(WARN, ctx, "missing %s", actual_desc); return 0; } str = X509_NAME_oneline(actual_name, NULL, 0); if (X509_NAME_cmp(actual_name, expect_name) == 0) { if (log_success && str != NULL) ossl_cmp_log3(INFO, ctx, " %s matches %s: %s", actual_desc, expect_desc, str); OPENSSL_free(str); return 1; } if (str != NULL) ossl_cmp_log2(INFO, ctx, " actual name in %s = %s", actual_desc, str); OPENSSL_free(str); if ((str = X509_NAME_oneline(expect_name, NULL, 0)) != NULL) ossl_cmp_log2(INFO, ctx, " does not match %s = %s", expect_desc, str); OPENSSL_free(str); return 0; } /* Return 0 if skid != NULL and there is no matching subject key ID in cert */ static int check_kid(const OSSL_CMP_CTX *ctx, const ASN1_OCTET_STRING *ckid, const ASN1_OCTET_STRING *skid) { char *str; if (skid == NULL) return 1; /* no expectation, thus trivially fulfilled */ /* make sure that the expected subject key identifier is there */ if (ckid == NULL) { ossl_cmp_warn(ctx, "missing Subject Key Identifier in certificate"); return 0; } str = i2s_ASN1_OCTET_STRING(NULL, ckid); if (ASN1_OCTET_STRING_cmp(ckid, skid) == 0) { if (str != NULL) ossl_cmp_log1(INFO, ctx, " subjectKID matches senderKID: %s", str); OPENSSL_free(str); return 1; } if (str != NULL) ossl_cmp_log1(INFO, ctx, " cert Subject Key Identifier = %s", str); OPENSSL_free(str); if ((str = i2s_ASN1_OCTET_STRING(NULL, skid)) != NULL) ossl_cmp_log1(INFO, ctx, " does not match senderKID = %s", str); OPENSSL_free(str); return 0; } static int already_checked(const X509 *cert, const STACK_OF(X509) *already_checked) { int i; for (i = sk_X509_num(already_checked /* may be NULL */); i > 0; i--) if (X509_cmp(sk_X509_value(already_checked, i - 1), cert) == 0) return 1; return 0; } /*- * Check if the given cert is acceptable as sender cert of the given message. * The subject DN must match, the subject key ID as well if present in the msg, * and the cert must be current (checked if ctx->trusted is not NULL). * Note that cert revocation etc. is checked by OSSL_CMP_validate_cert_path(). * * Returns 0 on error or not acceptable, else 1. */ static int cert_acceptable(const OSSL_CMP_CTX *ctx, const char *desc1, const char *desc2, X509 *cert, const STACK_OF(X509) *already_checked1, const STACK_OF(X509) *already_checked2, const OSSL_CMP_MSG *msg) { X509_STORE *ts = ctx->trusted; int self_issued = X509_check_issued(cert, cert) == X509_V_OK; char *str; X509_VERIFY_PARAM *vpm = ts != NULL ? X509_STORE_get0_param(ts) : NULL; int time_cmp; ossl_cmp_log3(INFO, ctx, " considering %s%s %s with..", self_issued ? "self-issued ": "", desc1, desc2); if ((str = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0)) != NULL) ossl_cmp_log1(INFO, ctx, " subject = %s", str); OPENSSL_free(str); if (!self_issued) { str = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0); if (str != NULL) ossl_cmp_log1(INFO, ctx, " issuer = %s", str); OPENSSL_free(str); } if (already_checked(cert, already_checked1) || already_checked(cert, already_checked2)) { ossl_cmp_info(ctx, " cert has already been checked"); return 0; } time_cmp = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert), X509_get0_notAfter(cert)); if (time_cmp != 0) { int err = time_cmp > 0 ? X509_V_ERR_CERT_HAS_EXPIRED : X509_V_ERR_CERT_NOT_YET_VALID; ossl_cmp_warn(ctx, time_cmp > 0 ? "cert has expired" : "cert is not yet valid"); if (ctx->log_cb != NULL /* logging not temporarily disabled */ && verify_cb_cert(ts, cert, err) <= 0) return 0; } if (!check_name(ctx, 1, "cert subject", X509_get_subject_name(cert), "sender field", msg->header->sender->d.directoryName)) return 0; if (!check_kid(ctx, X509_get0_subject_key_id(cert), msg->header->senderKID)) return 0; /* prevent misleading error later in case x509v3_cache_extensions() fails */ if (!ossl_x509v3_cache_extensions(cert)) { ossl_cmp_warn(ctx, "cert appears to be invalid"); return 0; } if (!verify_signature(ctx, msg, cert)) { ossl_cmp_warn(ctx, "msg signature verification failed"); return 0; } /* acceptable also if there is no senderKID in msg header */ ossl_cmp_info(ctx, " cert seems acceptable"); return 1; } static int check_cert_path(const OSSL_CMP_CTX *ctx, X509_STORE *store, X509 *scrt) { if (OSSL_CMP_validate_cert_path(ctx, store, scrt)) return 1; ossl_cmp_warn(ctx, "msg signature validates but cert path validation failed"); return 0; } /* * Exceptional handling for 3GPP TS 33.310 [3G/LTE Network Domain Security * (NDS); Authentication Framework (AF)], only to use for IP messages * and if the ctx option is explicitly set: use self-issued certificates * from extraCerts as trust anchor to validate sender cert - * provided it also can validate the newly enrolled certificate */ static int check_cert_path_3gpp(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg, X509 *scrt) { int valid = 0; X509_STORE *store; if (!ctx->permitTAInExtraCertsForIR) return 0; if ((store = X509_STORE_new()) == NULL || !ossl_cmp_X509_STORE_add1_certs(store, msg->extraCerts, 1 /* self-issued only */)) goto err; /* store does not include CRLs */ valid = OSSL_CMP_validate_cert_path(ctx, store, scrt); if (!valid) { ossl_cmp_warn(ctx, "also exceptional 3GPP mode cert path validation failed"); } else { /* * verify that the newly enrolled certificate (which assumed rid == * OSSL_CMP_CERTREQID) can also be validated with the same trusted store */ OSSL_CMP_CERTRESPONSE *crep = ossl_cmp_certrepmessage_get0_certresponse(msg->body->value.ip, OSSL_CMP_CERTREQID); X509 *newcrt = ossl_cmp_certresponse_get1_cert(ctx, crep); /* * maybe better use get_cert_status() from cmp_client.c, which catches * errors */ valid = OSSL_CMP_validate_cert_path(ctx, store, newcrt); X509_free(newcrt); } err: X509_STORE_free(store); return valid; } static int check_msg_given_cert(const OSSL_CMP_CTX *ctx, X509 *cert, const OSSL_CMP_MSG *msg) { return cert_acceptable(ctx, "previously validated", "sender cert", cert, NULL, NULL, msg) && (check_cert_path(ctx, ctx->trusted, cert) || check_cert_path_3gpp(ctx, msg, cert)); } /*- * Try all certs in given list for verifying msg, normally or in 3GPP mode. * If already_checked1 == NULL then certs are assumed to be the msg->extraCerts. * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert(). */ static int check_msg_with_certs(OSSL_CMP_CTX *ctx, const STACK_OF(X509) *certs, const char *desc, const STACK_OF(X509) *already_checked1, const STACK_OF(X509) *already_checked2, const OSSL_CMP_MSG *msg, int mode_3gpp) { int in_extraCerts = already_checked1 == NULL; int n_acceptable_certs = 0; int i; if (sk_X509_num(certs) <= 0) { ossl_cmp_log1(WARN, ctx, "no %s", desc); return 0; } for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */ X509 *cert = sk_X509_value(certs, i); if (!ossl_assert(cert != NULL)) return 0; if (!cert_acceptable(ctx, "cert from", desc, cert, already_checked1, already_checked2, msg)) continue; n_acceptable_certs++; if (mode_3gpp ? check_cert_path_3gpp(ctx, msg, cert) : check_cert_path(ctx, ctx->trusted, cert)) { /* store successful sender cert for further msgs in transaction */ return ossl_cmp_ctx_set1_validatedSrvCert(ctx, cert); } } if (in_extraCerts && n_acceptable_certs == 0) ossl_cmp_warn(ctx, "no acceptable cert in extraCerts"); return 0; } /*- * Verify msg trying first ctx->untrusted, which should include extraCerts * at its front, then trying the trusted certs in truststore (if any) of ctx. * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert(). */ static int check_msg_all_certs(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg, int mode_3gpp) { int ret = 0; if (ctx->permitTAInExtraCertsForIR && OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_IP) ossl_cmp_info(ctx, mode_3gpp ? "normal mode failed; trying now 3GPP mode trusting extraCerts" : "trying first normal mode using trust store"); else if (mode_3gpp) return 0; if (check_msg_with_certs(ctx, msg->extraCerts, "extraCerts", NULL, NULL, msg, mode_3gpp)) return 1; if (check_msg_with_certs(ctx, ctx->untrusted, "untrusted certs", msg->extraCerts, NULL, msg, mode_3gpp)) return 1; if (ctx->trusted == NULL) { ossl_cmp_warn(ctx, mode_3gpp ? "no self-issued extraCerts" : "no trusted store"); } else { STACK_OF(X509) *trusted = X509_STORE_get1_all_certs(ctx->trusted); ret = check_msg_with_certs(ctx, trusted, mode_3gpp ? "self-issued extraCerts" : "certs in trusted store", msg->extraCerts, ctx->untrusted, msg, mode_3gpp); OSSL_STACK_OF_X509_free(trusted); } return ret; } /*- * Verify message signature with any acceptable and valid candidate cert. * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert(). */ static int check_msg_find_cert(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg) { X509 *scrt = ctx->validatedSrvCert; /* previous successful sender cert */ GENERAL_NAME *sender = msg->header->sender; char *sname = NULL; char *skid_str = NULL; const ASN1_OCTET_STRING *skid = msg->header->senderKID; OSSL_CMP_log_cb_t backup_log_cb = ctx->log_cb; int res = 0; if (sender == NULL || msg->body == NULL) return 0; /* other NULL cases already have been checked */ if (sender->type != GEN_DIRNAME) { /* So far, only X509_NAME is supported */ ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED); return 0; } /* dump any hitherto errors to avoid confusion when printing further ones */ OSSL_CMP_CTX_print_errors(ctx); /* enable clearing irrelevant errors in attempts to validate sender certs */ (void)ERR_set_mark(); ctx->log_cb = NULL; /* temporarily disable logging */ /* * try first cached scrt, used successfully earlier in same transaction, * for validating this and any further msgs where extraCerts may be left out */ if (scrt != NULL) { if (check_msg_given_cert(ctx, scrt, msg)) { ctx->log_cb = backup_log_cb; (void)ERR_pop_to_mark(); return 1; } /* cached sender cert has shown to be no more successfully usable */ (void)ossl_cmp_ctx_set1_validatedSrvCert(ctx, NULL); /* re-do the above check (just) for adding diagnostic information */ ossl_cmp_info(ctx, "trying to verify msg signature with previously validated cert"); (void)check_msg_given_cert(ctx, scrt, msg); } res = check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */) || check_msg_all_certs(ctx, msg, 1 /* 3gpp */); ctx->log_cb = backup_log_cb; if (res) { /* discard any diagnostic information on trying to use certs */ (void)ERR_pop_to_mark(); goto end; } /* failed finding a sender cert that verifies the message signature */ (void)ERR_clear_last_mark(); sname = X509_NAME_oneline(sender->d.directoryName, NULL, 0); skid_str = skid == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, skid); if (ctx->log_cb != NULL) { ossl_cmp_info(ctx, "trying to verify msg signature with a valid cert that.."); if (sname != NULL) ossl_cmp_log1(INFO, ctx, "matches msg sender = %s", sname); if (skid_str != NULL) ossl_cmp_log1(INFO, ctx, "matches msg senderKID = %s", skid_str); else ossl_cmp_info(ctx, "while msg header does not contain senderKID"); /* re-do the above checks (just) for adding diagnostic information */ (void)check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */); (void)check_msg_all_certs(ctx, msg, 1 /* 3gpp */); } ERR_raise(ERR_LIB_CMP, CMP_R_NO_SUITABLE_SENDER_CERT); if (sname != NULL) { ERR_add_error_txt(NULL, "for msg sender name = "); ERR_add_error_txt(NULL, sname); } if (skid_str != NULL) { ERR_add_error_txt(" and ", "for msg senderKID = "); ERR_add_error_txt(NULL, skid_str); } end: OPENSSL_free(sname); OPENSSL_free(skid_str); return res; } /*- * Validate the protection of the given PKIMessage using either password- * based mac (PBM) or a signature algorithm. In the case of signature algorithm, * the sender certificate can have been pinned by providing it in ctx->srvCert, * else it is searched in msg->extraCerts, ctx->untrusted, in ctx->trusted * (in this order) and is path is validated against ctx->trusted. * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert(). * * If ctx->permitTAInExtraCertsForIR is true and when validating a CMP IP msg, * the trust anchor for validating the IP msg may be taken from msg->extraCerts * if a self-issued certificate is found there that can be used to * validate the enrolled certificate returned in the IP. * This is according to the need given in 3GPP TS 33.310. * * Returns 1 on success, 0 on error or validation failed. */ int OSSL_CMP_validate_msg(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg) { X509 *scrt; ossl_cmp_debug(ctx, "validating CMP message"); if (ctx == NULL || msg == NULL || msg->header == NULL || msg->body == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (msg->header->protectionAlg == NULL /* unprotected message */ || msg->protection == NULL || msg->protection->data == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION); return 0; } switch (ossl_cmp_hdr_get_protection_nid(msg->header)) { /* 5.1.3.1. Shared Secret Information */ case NID_id_PasswordBasedMAC: if (ctx->secretValue == NULL) { ossl_cmp_info(ctx, "no secret available for verifying PBM-based CMP message protection"); ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_SECRET); return 0; } if (verify_PBMAC(ctx, msg)) { /* * RFC 4210, 5.3.2: 'Note that if the PKI Message Protection is * "shared secret information", then any certificate transported in * the caPubs field may be directly trusted as a root CA * certificate by the initiator.' */ switch (OSSL_CMP_MSG_get_bodytype(msg)) { case -1: return 0; case OSSL_CMP_PKIBODY_IP: case OSSL_CMP_PKIBODY_CP: case OSSL_CMP_PKIBODY_KUP: case OSSL_CMP_PKIBODY_CCP: if (ctx->trusted != NULL) { STACK_OF(X509) *certs = msg->body->value.ip->caPubs; /* value.ip is same for cp, kup, and ccp */ if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0)) /* adds both self-issued and not self-issued certs */ return 0; } break; default: break; } ossl_cmp_debug(ctx, "successfully validated PBM-based CMP message protection"); return 1; } ossl_cmp_warn(ctx, "verifying PBM-based CMP message protection failed"); break; /* * 5.1.3.2 DH Key Pairs * Not yet supported */ case NID_id_DHBasedMac: ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC); break; /* * 5.1.3.3. Signature */ default: scrt = ctx->srvCert; if (scrt == NULL) { if (ctx->trusted == NULL) { ossl_cmp_info(ctx, "no trust store nor pinned server cert available for verifying signature-based CMP message protection"); ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_ANCHOR); return 0; } if (check_msg_find_cert(ctx, msg)) { ossl_cmp_debug(ctx, "successfully validated signature-based CMP message protection using trust store"); return 1; } } else { /* use pinned sender cert */ /* use ctx->srvCert for signature check even if not acceptable */ if (verify_signature(ctx, msg, scrt)) { ossl_cmp_debug(ctx, "successfully validated signature-based CMP message protection using pinned server cert"); return ossl_cmp_ctx_set1_validatedSrvCert(ctx, scrt); } ossl_cmp_warn(ctx, "CMP message signature verification failed"); ERR_raise(ERR_LIB_CMP, CMP_R_SRVCERT_DOES_NOT_VALIDATE_MSG); } break; } return 0; } static int check_transactionID_or_nonce(ASN1_OCTET_STRING *expected, ASN1_OCTET_STRING *actual, int reason) { if (expected != NULL && (actual == NULL || ASN1_OCTET_STRING_cmp(expected, actual) != 0)) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION char *expected_str, *actual_str; expected_str = i2s_ASN1_OCTET_STRING(NULL, expected); actual_str = actual == NULL ? NULL: i2s_ASN1_OCTET_STRING(NULL, actual); ERR_raise_data(ERR_LIB_CMP, reason, "expected = %s, actual = %s", expected_str == NULL ? "?" : expected_str, actual == NULL ? "(none)" : actual_str == NULL ? "?" : actual_str); OPENSSL_free(expected_str); OPENSSL_free(actual_str); return 0; #endif } return 1; } /*- * Check received message (i.e., response by server or request from client) * Any msg->extraCerts are prepended to ctx->untrusted. * * Ensures that: * its sender is of appropriate type (currently only X509_NAME) and * matches any expected sender or srvCert subject given in the ctx * it has a valid body type * its protection is valid (or invalid/absent, but only if a callback function * is present and yields a positive result using also the supplied argument) * its transaction ID matches the previous transaction ID stored in ctx (if any) * its recipNonce matches the previous senderNonce stored in the ctx (if any) * * If everything is fine: * learns the senderNonce from the received message, * learns the transaction ID if it is not yet in ctx, * and makes any certs in caPubs directly trusted. * * Returns 1 on success, 0 on error. */ int ossl_cmp_msg_check_update(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg, ossl_cmp_allow_unprotected_cb_t cb, int cb_arg) { OSSL_CMP_PKIHEADER *hdr; const X509_NAME *expected_sender; int num_untrusted, num_added, res; if (!ossl_assert(ctx != NULL && msg != NULL && msg->header != NULL)) return 0; hdr = OSSL_CMP_MSG_get0_header(msg); /* If expected_sender is given, validate sender name of received msg */ expected_sender = ctx->expected_sender; if (expected_sender == NULL && ctx->srvCert != NULL) expected_sender = X509_get_subject_name(ctx->srvCert); if (expected_sender != NULL) { const X509_NAME *actual_sender; char *str; if (hdr->sender->type != GEN_DIRNAME) { ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED); return 0; } actual_sender = hdr->sender->d.directoryName; /* * Compare actual sender name of response with expected sender name. * Mitigates risk of accepting misused PBM secret or * misused certificate of an unauthorized entity of a trusted hierarchy. */ if (!check_name(ctx, 0, "sender DN field", actual_sender, "expected sender", expected_sender)) { str = X509_NAME_oneline(actual_sender, NULL, 0); ERR_raise_data(ERR_LIB_CMP, CMP_R_UNEXPECTED_SENDER, str != NULL ? str : "<unknown>"); OPENSSL_free(str); return 0; } } /* Note: if recipient was NULL-DN it could be learned here if needed */ num_added = sk_X509_num(msg->extraCerts); if (num_added > 10) ossl_cmp_log1(WARN, ctx, "received CMP message contains %d extraCerts", num_added); /* * Store any provided extraCerts in ctx for use in OSSL_CMP_validate_msg() * and for future use, such that they are available to ctx->certConf_cb and * the peer does not need to send them again in the same transaction. * Note that it does not help validating the message before storing the * extraCerts because they do not belong to the protected msg part anyway. * The extraCerts are prepended. Allows simple removal if they shall not be * cached. Also they get used first, which is likely good for efficiency. */ num_untrusted = ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted); res = ossl_x509_add_certs_new(&ctx->untrusted, msg->extraCerts, /* this allows self-signed certs */ X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP | X509_ADD_FLAG_PREPEND); num_added = (ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted)) - num_untrusted; if (!res) { while (num_added-- > 0) X509_free(sk_X509_shift(ctx->untrusted)); return 0; } if (hdr->protectionAlg != NULL) res = OSSL_CMP_validate_msg(ctx, msg) /* explicitly permitted exceptions for invalid protection: */ || (cb != NULL && (*cb)(ctx, msg, 1, cb_arg) > 0); else /* explicitly permitted exceptions for missing protection: */ res = cb != NULL && (*cb)(ctx, msg, 0, cb_arg) > 0; #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION res = 1; /* support more aggressive fuzzing by letting invalid msg pass */ #endif /* remove extraCerts again if not caching */ if (ctx->noCacheExtraCerts) while (num_added-- > 0) X509_free(sk_X509_shift(ctx->untrusted)); if (!res) { if (hdr->protectionAlg != NULL) ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_PROTECTION); else ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION); return 0; } /* check CMP version number in header */ if (ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_2 && ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_3) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PVNO); return 0; #endif } if (OSSL_CMP_MSG_get_bodytype(msg) < 0) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR); return 0; #endif } /* compare received transactionID with the expected one in previous msg */ if (!check_transactionID_or_nonce(ctx->transactionID, hdr->transactionID, CMP_R_TRANSACTIONID_UNMATCHED)) return 0; /* * enable clearing irrelevant errors * in attempts to validate recipient nonce in case of delayed delivery. */ (void)ERR_set_mark(); /* compare received nonce with the one we sent */ if (!check_transactionID_or_nonce(ctx->senderNonce, hdr->recipNonce, CMP_R_RECIPNONCE_UNMATCHED)) { /* check if we are polling and received final response */ if (ctx->first_senderNonce == NULL || OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_POLLREP /* compare received nonce with our sender nonce at poll start */ || !check_transactionID_or_nonce(ctx->first_senderNonce, hdr->recipNonce, CMP_R_RECIPNONCE_UNMATCHED)) { (void)ERR_clear_last_mark(); return 0; } } (void)ERR_pop_to_mark(); /* if not yet present, learn transactionID */ if (ctx->transactionID == NULL && !OSSL_CMP_CTX_set1_transactionID(ctx, hdr->transactionID)) return 0; /* * RFC 4210 section 5.1.1 states: the recipNonce is copied from * the senderNonce of the previous message in the transaction. * --> Store for setting in next message */ if (!ossl_cmp_ctx_set1_recipNonce(ctx, hdr->senderNonce)) return 0; if (ossl_cmp_hdr_get_protection_nid(hdr) == NID_id_PasswordBasedMAC) { /* * RFC 4210, 5.3.2: 'Note that if the PKI Message Protection is * "shared secret information", then any certificate transported in * the caPubs field may be directly trusted as a root CA * certificate by the initiator.' */ switch (OSSL_CMP_MSG_get_bodytype(msg)) { case OSSL_CMP_PKIBODY_IP: case OSSL_CMP_PKIBODY_CP: case OSSL_CMP_PKIBODY_KUP: case OSSL_CMP_PKIBODY_CCP: if (ctx->trusted != NULL) { STACK_OF(X509) *certs = msg->body->value.ip->caPubs; /* value.ip is same for cp, kup, and ccp */ if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0)) /* adds both self-issued and not self-issued certs */ return 0; } break; default: break; } } return 1; } int ossl_cmp_verify_popo(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg, int acceptRAVerified) { if (!ossl_assert(msg != NULL && msg->body != NULL)) return 0; switch (msg->body->type) { case OSSL_CMP_PKIBODY_P10CR: { X509_REQ *req = msg->body->value.p10cr; if (X509_REQ_verify_ex(req, X509_REQ_get0_pubkey(req), ctx->libctx, ctx->propq) <= 0) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_NOT_ACCEPTED); return 0; #endif } } break; case OSSL_CMP_PKIBODY_IR: case OSSL_CMP_PKIBODY_CR: case OSSL_CMP_PKIBODY_KUR: if (!OSSL_CRMF_MSGS_verify_popo(msg->body->value.ir, OSSL_CMP_CERTREQID, acceptRAVerified, ctx->libctx, ctx->propq)) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION return 0; #endif } break; default: ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR); return 0; } return 1; }
./openssl/crypto/cmp/cmp_client.c
/* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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 "cmp_local.h" #include "internal/cryptlib.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/bio.h> #include <openssl/cmp.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509v3.h> #include <openssl/cmp_util.h> #define IS_CREP(t) ((t) == OSSL_CMP_PKIBODY_IP || (t) == OSSL_CMP_PKIBODY_CP \ || (t) == OSSL_CMP_PKIBODY_KUP) /*- * Evaluate whether there's an exception (violating the standard) configured for * handling negative responses without protection or with invalid protection. * Returns 1 on acceptance, 0 on rejection, or -1 on (internal) error. */ static int unprotected_exception(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *rep, int invalid_protection, ossl_unused int expected_type) { int rcvd_type = OSSL_CMP_MSG_get_bodytype(rep /* may be NULL */); const char *msg_type = NULL; if (!ossl_assert(ctx != NULL && rep != NULL)) return -1; if (!ctx->unprotectedErrors) return 0; switch (rcvd_type) { case OSSL_CMP_PKIBODY_ERROR: msg_type = "error response"; break; case OSSL_CMP_PKIBODY_RP: { OSSL_CMP_PKISI *si = ossl_cmp_revrepcontent_get_pkisi(rep->body->value.rp, OSSL_CMP_REVREQSID); if (si == NULL) return -1; if (ossl_cmp_pkisi_get_status(si) == OSSL_CMP_PKISTATUS_rejection) msg_type = "revocation response message with rejection status"; break; } case OSSL_CMP_PKIBODY_PKICONF: msg_type = "PKI Confirmation message"; break; default: if (IS_CREP(rcvd_type)) { int any_rid = OSSL_CMP_CERTREQID_NONE; OSSL_CMP_CERTREPMESSAGE *crepmsg = rep->body->value.ip; OSSL_CMP_CERTRESPONSE *crep = ossl_cmp_certrepmessage_get0_certresponse(crepmsg, any_rid); if (sk_OSSL_CMP_CERTRESPONSE_num(crepmsg->response) > 1) return -1; if (crep == NULL) return -1; if (ossl_cmp_pkisi_get_status(crep->status) == OSSL_CMP_PKISTATUS_rejection) msg_type = "CertRepMessage with rejection status"; } } if (msg_type == NULL) return 0; ossl_cmp_log2(WARN, ctx, "ignoring %s protection of %s", invalid_protection ? "invalid" : "missing", msg_type); return 1; } /* Save error info from PKIStatusInfo field of a certresponse into ctx */ static int save_statusInfo(OSSL_CMP_CTX *ctx, OSSL_CMP_PKISI *si) { int i; OSSL_CMP_PKIFREETEXT *ss; if (!ossl_assert(ctx != NULL && si != NULL)) return 0; ctx->status = ossl_cmp_pkisi_get_status(si); if (ctx->status < OSSL_CMP_PKISTATUS_accepted) return 0; ctx->failInfoCode = ossl_cmp_pkisi_get_pkifailureinfo(si); if (!ossl_cmp_ctx_set0_statusString(ctx, sk_ASN1_UTF8STRING_new_null()) || (ctx->statusString == NULL)) return 0; ss = si->statusString; /* may be NULL */ for (i = 0; i < sk_ASN1_UTF8STRING_num(ss); i++) { ASN1_UTF8STRING *str = sk_ASN1_UTF8STRING_value(ss, i); if (!sk_ASN1_UTF8STRING_push(ctx->statusString, ASN1_STRING_dup(str))) return 0; } return 1; } static int is_crep_with_waiting(const OSSL_CMP_MSG *resp, int rid) { OSSL_CMP_CERTREPMESSAGE *crepmsg; OSSL_CMP_CERTRESPONSE *crep; int bt = OSSL_CMP_MSG_get_bodytype(resp); if (!IS_CREP(bt)) return 0; crepmsg = resp->body->value.ip; /* same for cp and kup */ crep = ossl_cmp_certrepmessage_get0_certresponse(crepmsg, rid); return (crep != NULL && ossl_cmp_pkisi_get_status(crep->status) == OSSL_CMP_PKISTATUS_waiting); } /*- * Perform the generic aspects of sending a request and receiving a response. * Returns 1 on success and provides the received PKIMESSAGE in *rep. * Returns 0 on error. * Regardless of success, caller is responsible for freeing *rep (unless NULL). */ static int send_receive_check(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req, OSSL_CMP_MSG **rep, int expected_type) { int begin_transaction = expected_type != OSSL_CMP_PKIBODY_POLLREP && expected_type != OSSL_CMP_PKIBODY_PKICONF; const char *req_type_str = ossl_cmp_bodytype_to_string(OSSL_CMP_MSG_get_bodytype(req)); const char *expected_type_str = ossl_cmp_bodytype_to_string(expected_type); int bak_msg_timeout = ctx->msg_timeout; int bt; time_t now = time(NULL); int time_left; OSSL_CMP_transfer_cb_t transfer_cb = ctx->transfer_cb; #ifndef OPENSSL_NO_HTTP if (transfer_cb == NULL) transfer_cb = OSSL_CMP_MSG_http_perform; #endif *rep = NULL; if (ctx->total_timeout != 0 /* not waiting indefinitely */) { if (begin_transaction) ctx->end_time = now + ctx->total_timeout; if (now >= ctx->end_time) { ERR_raise(ERR_LIB_CMP, CMP_R_TOTAL_TIMEOUT); return 0; } if (!ossl_assert(ctx->end_time - now < INT_MAX)) { /* actually cannot happen due to assignment in initial_certreq() */ ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return 0; } time_left = (int)(ctx->end_time - now); if (ctx->msg_timeout == 0 || time_left < ctx->msg_timeout) ctx->msg_timeout = time_left; } /* should print error queue since transfer_cb may call ERR_clear_error() */ OSSL_CMP_CTX_print_errors(ctx); ossl_cmp_log1(INFO, ctx, "sending %s", req_type_str); *rep = (*transfer_cb)(ctx, req); ctx->msg_timeout = bak_msg_timeout; if (*rep == NULL) { ERR_raise_data(ERR_LIB_CMP, ctx->total_timeout != 0 && time(NULL) >= ctx->end_time ? CMP_R_TOTAL_TIMEOUT : CMP_R_TRANSFER_ERROR, "request sent: %s, expected response: %s", req_type_str, expected_type_str); return 0; } bt = OSSL_CMP_MSG_get_bodytype(*rep); /* * The body type in the 'bt' variable is not yet verified. * Still we use this preliminary value already for a progress report because * the following msg verification may also produce log entries and may fail. */ ossl_cmp_log2(INFO, ctx, "received %s%s", ossl_cmp_bodytype_to_string(bt), ossl_cmp_is_error_with_waiting(*rep) ? " (waiting)" : ""); /* copy received extraCerts to ctx->extraCertsIn so they can be retrieved */ if (bt != OSSL_CMP_PKIBODY_POLLREP && bt != OSSL_CMP_PKIBODY_PKICONF && !ossl_cmp_ctx_set1_extraCertsIn(ctx, (*rep)->extraCerts)) return 0; if (!ossl_cmp_msg_check_update(ctx, *rep, unprotected_exception, expected_type)) return 0; /* * rep can have the expected response type, which during polling is pollRep. * When polling, also any other non-error response (the final response) * is fine here. When not yet polling, delayed delivery may be initiated * by the server returning an error message with 'waiting' status (or a * response message of expected type ip/cp/kup with 'waiting' status). */ if (bt == expected_type || (expected_type == OSSL_CMP_PKIBODY_POLLREP ? bt != OSSL_CMP_PKIBODY_ERROR : ossl_cmp_is_error_with_waiting(*rep))) return 1; /* received message type is not one of the expected ones (e.g., error) */ ERR_raise(ERR_LIB_CMP, bt == OSSL_CMP_PKIBODY_ERROR ? CMP_R_RECEIVED_ERROR : CMP_R_UNEXPECTED_PKIBODY); /* in next line for mkerr.pl */ if (bt != OSSL_CMP_PKIBODY_ERROR) { ERR_add_error_data(3, "message type is '", ossl_cmp_bodytype_to_string(bt), "'"); } else { OSSL_CMP_ERRORMSGCONTENT *emc = (*rep)->body->value.error; OSSL_CMP_PKISI *si = emc->pKIStatusInfo; char buf[OSSL_CMP_PKISI_BUFLEN]; if (save_statusInfo(ctx, si) && OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf, sizeof(buf)) != NULL) ERR_add_error_data(1, buf); if (emc->errorCode != NULL && BIO_snprintf(buf, sizeof(buf), "; errorCode: %08lX", ASN1_INTEGER_get(emc->errorCode)) > 0) ERR_add_error_data(1, buf); if (emc->errorDetails != NULL) { char *text = ossl_sk_ASN1_UTF8STRING2text(emc->errorDetails, ", ", OSSL_CMP_PKISI_BUFLEN - 1); if (text != NULL && *text != '\0') ERR_add_error_data(2, "; errorDetails: ", text); OPENSSL_free(text); } if (ctx->status != OSSL_CMP_PKISTATUS_rejection) { ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKISTATUS); if (ctx->status == OSSL_CMP_PKISTATUS_waiting) ctx->status = OSSL_CMP_PKISTATUS_rejection; } } return 0; } /*- * When a 'waiting' PKIStatus has been received, this function is used to * poll, which should yield a pollRep or the final response. * On receiving a pollRep, which includes a checkAfter value, it return this * value if sleep == 0, else it sleeps as long as indicated and retries. * * A transaction timeout is enabled if ctx->total_timeout is != 0. * In this case polling will continue until the timeout is reached and then * polling is done a last time even if this is before the "checkAfter" time. * * Returns -1 on receiving pollRep if sleep == 0, setting the checkAfter value. * Returns 1 on success and provides the received PKIMESSAGE in *rep. * In this case the caller is responsible for freeing *rep. * Returns 0 on error (which includes the cases that timeout has been reached * or a response with 'waiting' status has been received). */ static int poll_for_response(OSSL_CMP_CTX *ctx, int sleep, int rid, OSSL_CMP_MSG **rep, int *checkAfter) { OSSL_CMP_MSG *preq = NULL; OSSL_CMP_MSG *prep = NULL; ossl_cmp_info(ctx, "received 'waiting' PKIStatus, starting to poll for response"); *rep = NULL; for (;;) { if ((preq = ossl_cmp_pollReq_new(ctx, rid)) == NULL) goto err; if (!send_receive_check(ctx, preq, &prep, OSSL_CMP_PKIBODY_POLLREP)) goto err; /* handle potential pollRep */ if (OSSL_CMP_MSG_get_bodytype(prep) == OSSL_CMP_PKIBODY_POLLREP) { OSSL_CMP_POLLREPCONTENT *prc = prep->body->value.pollRep; OSSL_CMP_POLLREP *pollRep = NULL; int64_t check_after; char str[OSSL_CMP_PKISI_BUFLEN]; int len; if (sk_OSSL_CMP_POLLREP_num(prc) > 1) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED); goto err; } pollRep = ossl_cmp_pollrepcontent_get0_pollrep(prc, rid); if (pollRep == NULL) goto err; if (!ASN1_INTEGER_get_int64(&check_after, pollRep->checkAfter)) { ERR_raise(ERR_LIB_CMP, CMP_R_BAD_CHECKAFTER_IN_POLLREP); goto err; } if (check_after < 0 || (uint64_t)check_after > (sleep ? ULONG_MAX / 1000 : INT_MAX)) { ERR_raise(ERR_LIB_CMP, CMP_R_CHECKAFTER_OUT_OF_RANGE); if (BIO_snprintf(str, OSSL_CMP_PKISI_BUFLEN, "value = %jd", check_after) >= 0) ERR_add_error_data(1, str); goto err; } if (pollRep->reason == NULL || (len = BIO_snprintf(str, OSSL_CMP_PKISI_BUFLEN, " with reason = '")) < 0) { *str = '\0'; } else { char *text = ossl_sk_ASN1_UTF8STRING2text(pollRep->reason, ", ", sizeof(str) - len - 2); if (text == NULL || BIO_snprintf(str + len, sizeof(str) - len, "%s'", text) < 0) *str = '\0'; OPENSSL_free(text); } ossl_cmp_log2(INFO, ctx, "received polling response%s; checkAfter = %ld seconds", str, check_after); if (ctx->total_timeout != 0) { /* timeout is not infinite */ const int exp = OSSL_CMP_EXPECTED_RESP_TIME; int64_t time_left = (int64_t)(ctx->end_time - exp - time(NULL)); if (time_left <= 0) { ERR_raise(ERR_LIB_CMP, CMP_R_TOTAL_TIMEOUT); goto err; } if (time_left < check_after) check_after = time_left; /* poll one last time just when timeout was reached */ } OSSL_CMP_MSG_free(preq); preq = NULL; OSSL_CMP_MSG_free(prep); prep = NULL; if (sleep) { OSSL_sleep((unsigned long)(1000 * check_after)); } else { if (checkAfter != NULL) *checkAfter = (int)check_after; return -1; /* exits the loop */ } } else if (is_crep_with_waiting(prep, rid) || ossl_cmp_is_error_with_waiting(prep)) { /* received status must not be 'waiting' */ (void)ossl_cmp_exchange_error(ctx, OSSL_CMP_PKISTATUS_rejection, OSSL_CMP_CTX_FAILINFO_badRequest, "polling already started", 0 /* errorCode */, NULL); ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKISTATUS); goto err; } else { ossl_cmp_info(ctx, "received final response after polling"); if (!ossl_cmp_ctx_set1_first_senderNonce(ctx, NULL)) return 0; break; } } if (prep == NULL) goto err; OSSL_CMP_MSG_free(preq); *rep = prep; return 1; err: (void)ossl_cmp_ctx_set1_first_senderNonce(ctx, NULL); OSSL_CMP_MSG_free(preq); OSSL_CMP_MSG_free(prep); return 0; } static int save_senderNonce_if_waiting(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *rep, int rid) { /* * Lightweight CMP Profile section 4.4 states: the senderNonce of the * preceding request message because this value will be needed for checking * the recipNonce of the final response to be received after polling. */ if ((is_crep_with_waiting(rep, rid) || ossl_cmp_is_error_with_waiting(rep)) && !ossl_cmp_ctx_set1_first_senderNonce(ctx, ctx->senderNonce)) return 0; return 1; } /* * Send request and get response possibly with polling initiated by error msg. * Polling for ip/cp/kup/ with 'waiting' status is handled by cert_response(). */ static int send_receive_also_delayed(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req, OSSL_CMP_MSG **rep, int expected_type) { if (!send_receive_check(ctx, req, rep, expected_type)) return 0; if (ossl_cmp_is_error_with_waiting(*rep)) { if (!save_senderNonce_if_waiting(ctx, *rep, OSSL_CMP_CERTREQID_NONE)) return 0; /* not modifying ctx->status during certConf and error exchanges */ if (expected_type != OSSL_CMP_PKIBODY_PKICONF && !save_statusInfo(ctx, (*rep)->body->value.error->pKIStatusInfo)) return 0; OSSL_CMP_MSG_free(*rep); *rep = NULL; if (poll_for_response(ctx, 1 /* can sleep */, OSSL_CMP_CERTREQID_NONE, rep, NULL /* checkAfter */) <= 0) { ERR_raise(ERR_LIB_CMP, CMP_R_POLLING_FAILED); return 0; } } if (OSSL_CMP_MSG_get_bodytype(*rep) != expected_type) { ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); return 0; } return 1; } /* * Send certConf for IR, CR or KUR sequences and check response, * not modifying ctx->status during the certConf exchange */ int ossl_cmp_exchange_certConf(OSSL_CMP_CTX *ctx, int certReqId, int fail_info, const char *txt) { OSSL_CMP_MSG *certConf; OSSL_CMP_MSG *PKIconf = NULL; int res = 0; /* OSSL_CMP_certConf_new() also checks if all necessary options are set */ certConf = ossl_cmp_certConf_new(ctx, certReqId, fail_info, txt); if (certConf == NULL) goto err; res = send_receive_also_delayed(ctx, certConf, &PKIconf, OSSL_CMP_PKIBODY_PKICONF); err: OSSL_CMP_MSG_free(certConf); OSSL_CMP_MSG_free(PKIconf); return res; } /* Send given error and check response */ int ossl_cmp_exchange_error(OSSL_CMP_CTX *ctx, int status, int fail_info, const char *txt, int errorCode, const char *details) { OSSL_CMP_MSG *error = NULL; OSSL_CMP_PKISI *si = NULL; OSSL_CMP_MSG *PKIconf = NULL; int res = 0; /* not overwriting ctx->status on error exchange */ if ((si = OSSL_CMP_STATUSINFO_new(status, fail_info, txt)) == NULL) goto err; /* ossl_cmp_error_new() also checks if all necessary options are set */ if ((error = ossl_cmp_error_new(ctx, si, errorCode, details, 0)) == NULL) goto err; res = send_receive_also_delayed(ctx, error, &PKIconf, OSSL_CMP_PKIBODY_PKICONF); err: OSSL_CMP_MSG_free(error); OSSL_CMP_PKISI_free(si); OSSL_CMP_MSG_free(PKIconf); return res; } /*- * Retrieve a copy of the certificate, if any, from the given CertResponse. * Take into account PKIStatusInfo of CertResponse in ctx, report it on error. * Returns NULL if not found or on error. */ static X509 *get1_cert_status(OSSL_CMP_CTX *ctx, int bodytype, OSSL_CMP_CERTRESPONSE *crep) { char buf[OSSL_CMP_PKISI_BUFLEN]; X509 *crt = NULL; if (!ossl_assert(ctx != NULL && crep != NULL)) return NULL; switch (ossl_cmp_pkisi_get_status(crep->status)) { case OSSL_CMP_PKISTATUS_waiting: ossl_cmp_err(ctx, "received \"waiting\" status for cert when actually aiming to extract cert"); ERR_raise(ERR_LIB_CMP, CMP_R_ENCOUNTERED_WAITING); goto err; case OSSL_CMP_PKISTATUS_grantedWithMods: ossl_cmp_warn(ctx, "received \"grantedWithMods\" for certificate"); break; case OSSL_CMP_PKISTATUS_accepted: break; /* get all information in case of a rejection before going to error */ case OSSL_CMP_PKISTATUS_rejection: ossl_cmp_err(ctx, "received \"rejection\" status rather than cert"); ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_REJECTED_BY_SERVER); goto err; case OSSL_CMP_PKISTATUS_revocationWarning: ossl_cmp_warn(ctx, "received \"revocationWarning\" - a revocation of the cert is imminent"); break; case OSSL_CMP_PKISTATUS_revocationNotification: ossl_cmp_warn(ctx, "received \"revocationNotification\" - a revocation of the cert has occurred"); break; case OSSL_CMP_PKISTATUS_keyUpdateWarning: if (bodytype != OSSL_CMP_PKIBODY_KUR) { ERR_raise(ERR_LIB_CMP, CMP_R_ENCOUNTERED_KEYUPDATEWARNING); goto err; } break; default: ossl_cmp_log1(ERROR, ctx, "received unsupported PKIStatus %d for certificate", ctx->status); ERR_raise(ERR_LIB_CMP, CMP_R_UNKNOWN_PKISTATUS); goto err; } crt = ossl_cmp_certresponse_get1_cert(ctx, crep); if (crt == NULL) /* according to PKIStatus, we can expect a cert */ ERR_raise(ERR_LIB_CMP, CMP_R_CERTIFICATE_NOT_FOUND); return crt; err: if (OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf, sizeof(buf)) != NULL) ERR_add_error_data(1, buf); return NULL; } /*- * Callback fn validating that the new certificate can be verified, using * ctx->certConf_cb_arg, which has been initialized using opt_out_trusted, and * ctx->untrusted, which at this point already contains msg->extraCerts. * Returns 0 on acceptance, else a bit field reflecting PKIFailureInfo. * Quoting from RFC 4210 section 5.1. Overall PKI Message: * The extraCerts field can contain certificates that may be useful to * the recipient. For example, this can be used by a CA or RA to * present an end entity with certificates that it needs to verify its * own new certificate (if, for example, the CA that issued the end * entity's certificate is not a root CA for the end entity). Note that * this field does not necessarily contain a certification path; the * recipient may have to sort, select from, or otherwise process the * extra certificates in order to use them. * Note: While often handy, there is no hard requirement by CMP that * an EE must be able to validate the certificates it gets enrolled. */ int OSSL_CMP_certConf_cb(OSSL_CMP_CTX *ctx, X509 *cert, int fail_info, const char **text) { X509_STORE *out_trusted = OSSL_CMP_CTX_get_certConf_cb_arg(ctx); STACK_OF(X509) *chain = NULL; (void)text; /* make (artificial) use of var to prevent compiler warning */ if (fail_info != 0) /* accept any error flagged by CMP core library */ return fail_info; if (out_trusted == NULL) { ossl_cmp_debug(ctx, "trying to build chain for newly enrolled cert"); chain = X509_build_chain(cert, ctx->untrusted, out_trusted, 0, ctx->libctx, ctx->propq); } else { X509_STORE_CTX *csc = X509_STORE_CTX_new_ex(ctx->libctx, ctx->propq); ossl_cmp_debug(ctx, "validating newly enrolled cert"); if (csc == NULL) goto err; if (!X509_STORE_CTX_init(csc, out_trusted, cert, ctx->untrusted)) goto err; /* disable any cert status/revocation checking etc. */ X509_VERIFY_PARAM_clear_flags(X509_STORE_CTX_get0_param(csc), ~(X509_V_FLAG_USE_CHECK_TIME | X509_V_FLAG_NO_CHECK_TIME | X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_POLICY_CHECK)); if (X509_verify_cert(csc) <= 0) goto err; if (!ossl_x509_add_certs_new(&chain, X509_STORE_CTX_get0_chain(csc), X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP | X509_ADD_FLAG_NO_SS)) { sk_X509_free(chain); chain = NULL; } err: X509_STORE_CTX_free(csc); } if (sk_X509_num(chain) > 0) X509_free(sk_X509_shift(chain)); /* remove leaf (EE) cert */ if (out_trusted != NULL) { if (chain == NULL) { ossl_cmp_err(ctx, "failed to validate newly enrolled cert"); fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_incorrectData; } else { ossl_cmp_debug(ctx, "success validating newly enrolled cert"); } } else if (chain == NULL) { ossl_cmp_warn(ctx, "could not build approximate chain for newly enrolled cert, resorting to received extraCerts"); chain = OSSL_CMP_CTX_get1_extraCertsIn(ctx); } else { ossl_cmp_debug(ctx, "success building approximate chain for newly enrolled cert"); } (void)ossl_cmp_ctx_set1_newChain(ctx, chain); OSSL_STACK_OF_X509_free(chain); return fail_info; } /*- * Perform the generic handling of certificate responses for IR/CR/KUR/P10CR. * |rid| must be OSSL_CMP_CERTREQID_NONE if not available, namely for p10cr * Returns -1 on receiving pollRep if sleep == 0, setting the checkAfter value. * Returns 1 on success and provides the received PKIMESSAGE in *resp. * Returns 0 on error (which includes the case that timeout has been reached). * Regardless of success, caller is responsible for freeing *resp (unless NULL). */ static int cert_response(OSSL_CMP_CTX *ctx, int sleep, int rid, OSSL_CMP_MSG **resp, int *checkAfter, ossl_unused int req_type, ossl_unused int expected_type) { EVP_PKEY *rkey = ossl_cmp_ctx_get0_newPubkey(ctx); int fail_info = 0; /* no failure */ const char *txt = NULL; OSSL_CMP_CERTREPMESSAGE *crepmsg = NULL; OSSL_CMP_CERTRESPONSE *crep = NULL; OSSL_CMP_certConf_cb_t cb; X509 *cert; char *subj = NULL; int ret = 1; int rcvd_type; OSSL_CMP_PKISI *si; if (!ossl_assert(ctx != NULL)) return 0; retry: rcvd_type = OSSL_CMP_MSG_get_bodytype(*resp); if (IS_CREP(rcvd_type)) { crepmsg = (*resp)->body->value.ip; /* same for cp and kup */ if (sk_OSSL_CMP_CERTRESPONSE_num(crepmsg->response) > 1) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED); return 0; } crep = ossl_cmp_certrepmessage_get0_certresponse(crepmsg, rid); if (crep == NULL) return 0; si = crep->status; if (rid == OSSL_CMP_CERTREQID_NONE) { /* for OSSL_CMP_PKIBODY_P10CR learn CertReqId from response */ rid = ossl_cmp_asn1_get_int(crep->certReqId); if (rid < OSSL_CMP_CERTREQID_NONE) { ERR_raise(ERR_LIB_CMP, CMP_R_BAD_REQUEST_ID); return 0; } } } else if (rcvd_type == OSSL_CMP_PKIBODY_ERROR) { si = (*resp)->body->value.error->pKIStatusInfo; } else { ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); return 0; } if (!save_statusInfo(ctx, si)) return 0; if (ossl_cmp_pkisi_get_status(si) == OSSL_CMP_PKISTATUS_waiting) { /* * Here we allow both and error message with waiting indication * as well as a certificate response with waiting indication, where * its flavor (ip, cp, or kup) may not strictly match ir/cr/p10cr/kur. */ OSSL_CMP_MSG_free(*resp); *resp = NULL; if ((ret = poll_for_response(ctx, sleep, rid, resp, checkAfter)) != 0) { if (ret == -1) /* at this point implies sleep == 0 */ return ret; /* waiting */ goto retry; /* got some response other than pollRep */ } else { ERR_raise(ERR_LIB_CMP, CMP_R_POLLING_FAILED); return 0; } } /* at this point, we have received ip/cp/kup/error without waiting */ if (rcvd_type == OSSL_CMP_PKIBODY_ERROR) { ERR_raise(ERR_LIB_CMP, CMP_R_RECEIVED_ERROR); return 0; } /* here we are strict on the flavor of ip/cp/kup: must match request */ if (rcvd_type != expected_type) { ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); return 0; } cert = get1_cert_status(ctx, (*resp)->body->type, crep); if (cert == NULL) { ERR_add_error_data(1, "; cannot extract certificate from response"); return 0; } if (!ossl_cmp_ctx_set0_newCert(ctx, cert)) return 0; /* * if the CMP server returned certificates in the caPubs field, copy them * to the context so that they can be retrieved if necessary */ if (crepmsg != NULL && crepmsg->caPubs != NULL && !ossl_cmp_ctx_set1_caPubs(ctx, crepmsg->caPubs)) return 0; subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0); if (rkey != NULL /* X509_check_private_key() also works if rkey is just public key */ && !(X509_check_private_key(ctx->newCert, rkey))) { fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_incorrectData; txt = "public key in new certificate does not match our enrollment key"; /*- * not calling (void)ossl_cmp_exchange_error(ctx, * OSSL_CMP_PKISTATUS_rejection, fail_info, txt) * not throwing CMP_R_CERTIFICATE_NOT_ACCEPTED with txt * not returning 0 * since we better leave this for the certConf_cb to decide */ } /* * Execute the certification checking callback function, * which can determine whether to accept a newly enrolled certificate. * It may overrule the pre-decision reflected in 'fail_info' and '*txt'. */ cb = ctx->certConf_cb != NULL ? ctx->certConf_cb : OSSL_CMP_certConf_cb; if ((fail_info = cb(ctx, ctx->newCert, fail_info, &txt)) != 0 && txt == NULL) txt = "CMP client did not accept it"; if (fail_info != 0) /* immediately log error before any certConf exchange */ ossl_cmp_log1(ERROR, ctx, "rejecting newly enrolled cert with subject: %s", subj); /* * certConf exchange should better be moved to do_certreq_seq() such that * also more low-level errors with CertReqMessages get reported to server */ if (!ctx->disableConfirm && !ossl_cmp_hdr_has_implicitConfirm((*resp)->header)) { if (!ossl_cmp_exchange_certConf(ctx, rid, fail_info, txt)) ret = 0; } /* not throwing failure earlier as transfer_cb may call ERR_clear_error() */ if (fail_info != 0) { ERR_raise_data(ERR_LIB_CMP, CMP_R_CERTIFICATE_NOT_ACCEPTED, "rejecting newly enrolled cert with subject: %s; %s", subj, txt); ctx->status = OSSL_CMP_PKISTATUS_rejection; ret = 0; } OPENSSL_free(subj); return ret; } static int initial_certreq(OSSL_CMP_CTX *ctx, int req_type, const OSSL_CRMF_MSG *crm, OSSL_CMP_MSG **p_rep, int rep_type) { OSSL_CMP_MSG *req; int res; ctx->status = OSSL_CMP_PKISTATUS_request; if (!ossl_cmp_ctx_set0_newCert(ctx, NULL)) return 0; /* also checks if all necessary options are set */ if ((req = ossl_cmp_certreq_new(ctx, req_type, crm)) == NULL) return 0; ctx->status = OSSL_CMP_PKISTATUS_trans; res = send_receive_check(ctx, req, p_rep, rep_type); OSSL_CMP_MSG_free(req); return res; } int OSSL_CMP_try_certreq(OSSL_CMP_CTX *ctx, int req_type, const OSSL_CRMF_MSG *crm, int *checkAfter) { OSSL_CMP_MSG *rep = NULL; int is_p10 = req_type == OSSL_CMP_PKIBODY_P10CR; int rid = is_p10 ? OSSL_CMP_CERTREQID_NONE : OSSL_CMP_CERTREQID; int rep_type = is_p10 ? OSSL_CMP_PKIBODY_CP : req_type + 1; int res = 0; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (ctx->status != OSSL_CMP_PKISTATUS_waiting) { /* not polling already */ if (!initial_certreq(ctx, req_type, crm, &rep, rep_type)) goto err; if (!save_senderNonce_if_waiting(ctx, rep, rid)) return 0; } else { if (req_type < 0) return ossl_cmp_exchange_error(ctx, OSSL_CMP_PKISTATUS_rejection, 0, "polling aborted", 0 /* errorCode */, "by application"); res = poll_for_response(ctx, 0 /* no sleep */, rid, &rep, checkAfter); if (res <= 0) /* waiting or error */ return res; } res = cert_response(ctx, 0 /* no sleep */, rid, &rep, checkAfter, req_type, rep_type); err: OSSL_CMP_MSG_free(rep); return res; } /*- * Do the full sequence CR/IR/KUR/P10CR, CP/IP/KUP/CP, * certConf, PKIconf, and polling if required. * Will sleep as long as indicated by the server (according to checkAfter). * All enrollment options need to be present in the context. * Returns pointer to received certificate, or NULL if none was received. */ X509 *OSSL_CMP_exec_certreq(OSSL_CMP_CTX *ctx, int req_type, const OSSL_CRMF_MSG *crm) { OSSL_CMP_MSG *rep = NULL; int is_p10 = req_type == OSSL_CMP_PKIBODY_P10CR; int rid = is_p10 ? OSSL_CMP_CERTREQID_NONE : OSSL_CMP_CERTREQID; int rep_type = is_p10 ? OSSL_CMP_PKIBODY_CP : req_type + 1; X509 *result = NULL; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } if (!initial_certreq(ctx, req_type, crm, &rep, rep_type)) goto err; if (!save_senderNonce_if_waiting(ctx, rep, rid)) return 0; if (cert_response(ctx, 1 /* sleep */, rid, &rep, NULL, req_type, rep_type) <= 0) goto err; result = ctx->newCert; err: OSSL_CMP_MSG_free(rep); return result; } int OSSL_CMP_exec_RR_ses(OSSL_CMP_CTX *ctx) { OSSL_CMP_MSG *rr = NULL; OSSL_CMP_MSG *rp = NULL; const int num_RevDetails = 1; const int rsid = OSSL_CMP_REVREQSID; OSSL_CMP_REVREPCONTENT *rrep = NULL; OSSL_CMP_PKISI *si = NULL; char buf[OSSL_CMP_PKISI_BUFLEN]; int ret = 0; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return 0; } ctx->status = OSSL_CMP_PKISTATUS_request; if (ctx->oldCert == NULL && ctx->p10CSR == NULL && (ctx->serialNumber == NULL || ctx->issuer == NULL)) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_REFERENCE_CERT); return 0; } /* OSSL_CMP_rr_new() also checks if all necessary options are set */ if ((rr = ossl_cmp_rr_new(ctx)) == NULL) goto end; ctx->status = OSSL_CMP_PKISTATUS_trans; if (!send_receive_also_delayed(ctx, rr, &rp, OSSL_CMP_PKIBODY_RP)) goto end; rrep = rp->body->value.rp; #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION if (sk_OSSL_CMP_PKISI_num(rrep->status) != num_RevDetails) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT); goto end; } #else if (sk_OSSL_CMP_PKISI_num(rrep->status) < 1) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT); goto end; } #endif /* evaluate PKIStatus field */ si = ossl_cmp_revrepcontent_get_pkisi(rrep, rsid); if (!save_statusInfo(ctx, si)) goto err; switch (ossl_cmp_pkisi_get_status(si)) { case OSSL_CMP_PKISTATUS_accepted: ossl_cmp_info(ctx, "revocation accepted (PKIStatus=accepted)"); ret = 1; break; case OSSL_CMP_PKISTATUS_grantedWithMods: ossl_cmp_info(ctx, "revocation accepted (PKIStatus=grantedWithMods)"); ret = 1; break; case OSSL_CMP_PKISTATUS_rejection: ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_REJECTED_BY_SERVER); goto err; case OSSL_CMP_PKISTATUS_revocationWarning: ossl_cmp_info(ctx, "revocation accepted (PKIStatus=revocationWarning)"); ret = 1; break; case OSSL_CMP_PKISTATUS_revocationNotification: /* interpretation as warning or error depends on CA */ ossl_cmp_warn(ctx, "revocation accepted (PKIStatus=revocationNotification)"); ret = 1; break; case OSSL_CMP_PKISTATUS_waiting: case OSSL_CMP_PKISTATUS_keyUpdateWarning: ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKISTATUS); goto err; default: ERR_raise(ERR_LIB_CMP, CMP_R_UNKNOWN_PKISTATUS); goto err; } /* check any present CertId in optional revCerts field */ if (sk_OSSL_CRMF_CERTID_num(rrep->revCerts) >= 1) { OSSL_CRMF_CERTID *cid; OSSL_CRMF_CERTTEMPLATE *tmpl = sk_OSSL_CMP_REVDETAILS_value(rr->body->value.rr, rsid)->certDetails; const X509_NAME *issuer = OSSL_CRMF_CERTTEMPLATE_get0_issuer(tmpl); const ASN1_INTEGER *serial = OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(tmpl); if (sk_OSSL_CRMF_CERTID_num(rrep->revCerts) != num_RevDetails) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT); ret = 0; goto err; } if ((cid = ossl_cmp_revrepcontent_get_CertId(rrep, rsid)) == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_CERTID); ret = 0; goto err; } if (X509_NAME_cmp(issuer, OSSL_CRMF_CERTID_get0_issuer(cid)) != 0) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_CERTID_IN_RP); ret = 0; goto err; #endif } if (ASN1_INTEGER_cmp(serial, OSSL_CRMF_CERTID_get0_serialNumber(cid)) != 0) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_SERIAL_IN_RP); ret = 0; goto err; #endif } } /* check number of any optionally present crls */ if (rrep->crls != NULL && sk_X509_CRL_num(rrep->crls) != num_RevDetails) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT); ret = 0; goto err; } err: if (ret == 0 && OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf, sizeof(buf)) != NULL) ERR_add_error_data(1, buf); end: OSSL_CMP_MSG_free(rr); OSSL_CMP_MSG_free(rp); return ret; } STACK_OF(OSSL_CMP_ITAV) *OSSL_CMP_exec_GENM_ses(OSSL_CMP_CTX *ctx) { OSSL_CMP_MSG *genm; OSSL_CMP_MSG *genp = NULL; STACK_OF(OSSL_CMP_ITAV) *itavs = NULL; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return NULL; } ctx->status = OSSL_CMP_PKISTATUS_request; if ((genm = ossl_cmp_genm_new(ctx)) == NULL) goto err; ctx->status = OSSL_CMP_PKISTATUS_trans; if (!send_receive_also_delayed(ctx, genm, &genp, OSSL_CMP_PKIBODY_GENP)) goto err; ctx->status = OSSL_CMP_PKISTATUS_accepted; itavs = genp->body->value.genp; if (itavs == NULL) itavs = sk_OSSL_CMP_ITAV_new_null(); /* received stack of itavs not to be freed with the genp */ genp->body->value.genp = NULL; err: OSSL_CMP_MSG_free(genm); OSSL_CMP_MSG_free(genp); return itavs; /* NULL indicates error case */ }
./openssl/crypto/comp/comp_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/comperr.h> #include "crypto/comperr.h" #ifndef OPENSSL_NO_COMP # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA COMP_str_reasons[] = { {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_BROTLI_DECODE_ERROR), "brotli decode error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_BROTLI_ENCODE_ERROR), "brotli encode error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_BROTLI_NOT_SUPPORTED), "brotli not supported"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZLIB_DEFLATE_ERROR), "zlib deflate error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZLIB_INFLATE_ERROR), "zlib inflate error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZLIB_NOT_SUPPORTED), "zlib not supported"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZSTD_COMPRESS_ERROR), "zstd compress error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZSTD_DECODE_ERROR), "zstd decode error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZSTD_DECOMPRESS_ERROR), "zstd decompress error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZSTD_NOT_SUPPORTED), "zstd not supported"}, {0, NULL} }; # endif int ossl_err_load_COMP_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(COMP_str_reasons[0].error) == NULL) ERR_load_strings_const(COMP_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
./openssl/crypto/comp/c_brotli.c
/* * Copyright 1998-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * Uses brotli compression library from https://github.com/google/brotli */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/objects.h> #include "internal/comp.h" #include <openssl/err.h> #include "crypto/cryptlib.h" #include "internal/bio.h" #include "internal/thread_once.h" #include "comp_local.h" COMP_METHOD *COMP_brotli(void); #ifdef OPENSSL_NO_BROTLI # undef BROTLI_SHARED #else # include <brotli/decode.h> # include <brotli/encode.h> /* memory allocations functions for brotli initialisation */ static void *brotli_alloc(void *opaque, size_t size) { return OPENSSL_zalloc(size); } static void brotli_free(void *opaque, void *address) { OPENSSL_free(address); } /* * When OpenSSL is built on Windows, we do not want to require that * the BROTLI.DLL be available in order for the OpenSSL DLLs to * work. Therefore, all BROTLI routines are loaded at run time * and we do not link to a .LIB file when BROTLI_SHARED is set. */ # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # include <windows.h> # endif # ifdef BROTLI_SHARED # include "internal/dso.h" /* Function pointers */ typedef BrotliEncoderState *(*encode_init_ft)(brotli_alloc_func, brotli_free_func, void *); typedef BROTLI_BOOL (*encode_stream_ft)(BrotliEncoderState *, BrotliEncoderOperation, size_t *, const uint8_t **, size_t *, uint8_t **, size_t *); typedef BROTLI_BOOL (*encode_has_more_ft)(BrotliEncoderState *); typedef void (*encode_end_ft)(BrotliEncoderState *); typedef BROTLI_BOOL (*encode_oneshot_ft)(int, int, BrotliEncoderMode, size_t, const uint8_t in[], size_t *, uint8_t out[]); typedef BrotliDecoderState *(*decode_init_ft)(brotli_alloc_func, brotli_free_func, void *); typedef BROTLI_BOOL (*decode_stream_ft)(BrotliDecoderState *, size_t *, const uint8_t **, size_t *, uint8_t **, size_t *); typedef BROTLI_BOOL (*decode_has_more_ft)(BrotliDecoderState *); typedef void (*decode_end_ft)(BrotliDecoderState *); typedef BrotliDecoderErrorCode (*decode_error_ft)(BrotliDecoderState *); typedef const char *(*decode_error_string_ft)(BrotliDecoderErrorCode); typedef BROTLI_BOOL (*decode_is_finished_ft)(BrotliDecoderState *); typedef BrotliDecoderResult (*decode_oneshot_ft)(size_t, const uint8_t in[], size_t *, uint8_t out[]); static encode_init_ft p_encode_init = NULL; static encode_stream_ft p_encode_stream = NULL; static encode_has_more_ft p_encode_has_more = NULL; static encode_end_ft p_encode_end = NULL; static encode_oneshot_ft p_encode_oneshot = NULL; static decode_init_ft p_decode_init = NULL; static decode_stream_ft p_decode_stream = NULL; static decode_has_more_ft p_decode_has_more = NULL; static decode_end_ft p_decode_end = NULL; static decode_error_ft p_decode_error = NULL; static decode_error_string_ft p_decode_error_string = NULL; static decode_is_finished_ft p_decode_is_finished = NULL; static decode_oneshot_ft p_decode_oneshot = NULL; static DSO *brotli_encode_dso = NULL; static DSO *brotli_decode_dso = NULL; # define BrotliEncoderCreateInstance p_encode_init # define BrotliEncoderCompressStream p_encode_stream # define BrotliEncoderHasMoreOutput p_encode_has_more # define BrotliEncoderDestroyInstance p_encode_end # define BrotliEncoderCompress p_encode_oneshot # define BrotliDecoderCreateInstance p_decode_init # define BrotliDecoderDecompressStream p_decode_stream # define BrotliDecoderHasMoreOutput p_decode_has_more # define BrotliDecoderDestroyInstance p_decode_end # define BrotliDecoderGetErrorCode p_decode_error # define BrotliDecoderErrorString p_decode_error_string # define BrotliDecoderIsFinished p_decode_is_finished # define BrotliDecoderDecompress p_decode_oneshot # endif /* ifdef BROTLI_SHARED */ struct brotli_state { BrotliEncoderState *encoder; BrotliDecoderState *decoder; }; static int brotli_stateful_init(COMP_CTX *ctx) { struct brotli_state *state = OPENSSL_zalloc(sizeof(*state)); if (state == NULL) return 0; state->encoder = BrotliEncoderCreateInstance(brotli_alloc, brotli_free, NULL); if (state->encoder == NULL) goto err; state->decoder = BrotliDecoderCreateInstance(brotli_alloc, brotli_free, NULL); if (state->decoder == NULL) goto err; ctx->data = state; return 1; err: BrotliDecoderDestroyInstance(state->decoder); BrotliEncoderDestroyInstance(state->encoder); OPENSSL_free(state); return 0; } static void brotli_stateful_finish(COMP_CTX *ctx) { struct brotli_state *state = ctx->data; if (state != NULL) { BrotliDecoderDestroyInstance(state->decoder); BrotliEncoderDestroyInstance(state->encoder); OPENSSL_free(state); ctx->data = NULL; } } static ossl_ssize_t brotli_stateful_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { BROTLI_BOOL done; struct brotli_state *state = ctx->data; size_t in_avail = ilen; size_t out_avail = olen; if (state == NULL || olen > OSSL_SSIZE_MAX) return -1; if (ilen == 0) return 0; /* * The finish API does not provide a final output buffer, * so each compress operation has to be flushed, if all * the input data can't be accepted, or there is more output, * this has to be considered an error, since there is no more * output buffer space */ done = BrotliEncoderCompressStream(state->encoder, BROTLI_OPERATION_FLUSH, &in_avail, (const uint8_t**)&in, &out_avail, &out, NULL); if (done == BROTLI_FALSE || in_avail != 0 || BrotliEncoderHasMoreOutput(state->encoder)) return -1; if (out_avail > olen) return -1; return (ossl_ssize_t)(olen - out_avail); } static ossl_ssize_t brotli_stateful_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { BrotliDecoderResult result; struct brotli_state *state = ctx->data; size_t in_avail = ilen; size_t out_avail = olen; if (state == NULL || olen > OSSL_SSIZE_MAX) return -1; if (ilen == 0) return 0; result = BrotliDecoderDecompressStream(state->decoder, &in_avail, (const uint8_t**)&in, &out_avail, &out, NULL); if (result == BROTLI_DECODER_RESULT_ERROR || in_avail != 0 || BrotliDecoderHasMoreOutput(state->decoder)) return -1; if (out_avail > olen) return -1; return (ossl_ssize_t)(olen - out_avail); } static COMP_METHOD brotli_stateful_method = { NID_brotli, LN_brotli, brotli_stateful_init, brotli_stateful_finish, brotli_stateful_compress_block, brotli_stateful_expand_block }; static int brotli_oneshot_init(COMP_CTX *ctx) { return 1; } static void brotli_oneshot_finish(COMP_CTX *ctx) { } static ossl_ssize_t brotli_oneshot_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { size_t out_size = olen; ossl_ssize_t ret; if (ilen == 0) return 0; if (BrotliEncoderCompress(BROTLI_DEFAULT_QUALITY, BROTLI_DEFAULT_WINDOW, BROTLI_DEFAULT_MODE, ilen, in, &out_size, out) == BROTLI_FALSE) return -1; if (out_size > OSSL_SSIZE_MAX) return -1; ret = (ossl_ssize_t)out_size; if (ret < 0) return -1; return ret; } static ossl_ssize_t brotli_oneshot_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { size_t out_size = olen; ossl_ssize_t ret; if (ilen == 0) return 0; if (BrotliDecoderDecompress(ilen, in, &out_size, out) != BROTLI_DECODER_RESULT_SUCCESS) return -1; if (out_size > OSSL_SSIZE_MAX) return -1; ret = (ossl_ssize_t)out_size; if (ret < 0) return -1; return ret; } static COMP_METHOD brotli_oneshot_method = { NID_brotli, LN_brotli, brotli_oneshot_init, brotli_oneshot_finish, brotli_oneshot_compress_block, brotli_oneshot_expand_block }; static CRYPTO_ONCE brotli_once = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_comp_brotli_init) { # ifdef BROTLI_SHARED # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # define LIBBROTLIENC "BROTLIENC" # define LIBBROTLIDEC "BROTLIDEC" # else # define LIBBROTLIENC "brotlienc" # define LIBBROTLIDEC "brotlidec" # endif brotli_encode_dso = DSO_load(NULL, LIBBROTLIENC, NULL, 0); if (brotli_encode_dso != NULL) { p_encode_init = (encode_init_ft)DSO_bind_func(brotli_encode_dso, "BrotliEncoderCreateInstance"); p_encode_stream = (encode_stream_ft)DSO_bind_func(brotli_encode_dso, "BrotliEncoderCompressStream"); p_encode_has_more = (encode_has_more_ft)DSO_bind_func(brotli_encode_dso, "BrotliEncoderHasMoreOutput"); p_encode_end = (encode_end_ft)DSO_bind_func(brotli_encode_dso, "BrotliEncoderDestroyInstance"); p_encode_oneshot = (encode_oneshot_ft)DSO_bind_func(brotli_encode_dso, "BrotliEncoderCompress"); } brotli_decode_dso = DSO_load(NULL, LIBBROTLIDEC, NULL, 0); if (brotli_decode_dso != NULL) { p_decode_init = (decode_init_ft)DSO_bind_func(brotli_decode_dso, "BrotliDecoderCreateInstance"); p_decode_stream = (decode_stream_ft)DSO_bind_func(brotli_decode_dso, "BrotliDecoderDecompressStream"); p_decode_has_more = (decode_has_more_ft)DSO_bind_func(brotli_decode_dso, "BrotliDecoderHasMoreOutput"); p_decode_end = (decode_end_ft)DSO_bind_func(brotli_decode_dso, "BrotliDecoderDestroyInstance"); p_decode_error = (decode_error_ft)DSO_bind_func(brotli_decode_dso, "BrotliDecoderGetErrorCode"); p_decode_error_string = (decode_error_string_ft)DSO_bind_func(brotli_decode_dso, "BrotliDecoderErrorString"); p_decode_is_finished = (decode_is_finished_ft)DSO_bind_func(brotli_decode_dso, "BrotliDecoderIsFinished"); p_decode_oneshot = (decode_oneshot_ft)DSO_bind_func(brotli_decode_dso, "BrotliDecoderDecompress"); } if (p_encode_init == NULL || p_encode_stream == NULL || p_encode_has_more == NULL || p_encode_end == NULL || p_encode_oneshot == NULL || p_decode_init == NULL || p_decode_stream == NULL || p_decode_has_more == NULL || p_decode_end == NULL || p_decode_error == NULL || p_decode_error_string == NULL || p_decode_is_finished == NULL || p_decode_oneshot == NULL) { ossl_comp_brotli_cleanup(); return 0; } # endif return 1; } #endif /* ifndef BROTLI / else */ COMP_METHOD *COMP_brotli(void) { COMP_METHOD *meth = NULL; #ifndef OPENSSL_NO_BROTLI if (RUN_ONCE(&brotli_once, ossl_comp_brotli_init)) meth = &brotli_stateful_method; #endif return meth; } COMP_METHOD *COMP_brotli_oneshot(void) { COMP_METHOD *meth = NULL; #ifndef OPENSSL_NO_BROTLI if (RUN_ONCE(&brotli_once, ossl_comp_brotli_init)) meth = &brotli_oneshot_method; #endif return meth; } /* Also called from OPENSSL_cleanup() */ void ossl_comp_brotli_cleanup(void) { #ifdef BROTLI_SHARED DSO_free(brotli_encode_dso); brotli_encode_dso = NULL; DSO_free(brotli_decode_dso); brotli_decode_dso = NULL; p_encode_init = NULL; p_encode_stream = NULL; p_encode_has_more = NULL; p_encode_end = NULL; p_encode_oneshot = NULL; p_decode_init = NULL; p_decode_stream = NULL; p_decode_has_more = NULL; p_decode_end = NULL; p_decode_error = NULL; p_decode_error_string = NULL; p_decode_is_finished = NULL; p_decode_oneshot = NULL; #endif } #ifndef OPENSSL_NO_BROTLI /* Brotli-based compression/decompression filter BIO */ typedef struct { struct { /* input structure */ size_t avail_in; unsigned char *next_in; size_t avail_out; unsigned char *next_out; unsigned char *buf; size_t bufsize; BrotliDecoderState *state; } decode; struct { /* output structure */ size_t avail_in; unsigned char *next_in; size_t avail_out; unsigned char *next_out; unsigned char *buf; size_t bufsize; BrotliEncoderState *state; int mode; /* Encoder mode to use */ int done; unsigned char *ptr; size_t count; } encode; } BIO_BROTLI_CTX; # define BROTLI_DEFAULT_BUFSIZE 1024 static int bio_brotli_new(BIO *bi); static int bio_brotli_free(BIO *bi); static int bio_brotli_read(BIO *b, char *out, int outl); static int bio_brotli_write(BIO *b, const char *in, int inl); static long bio_brotli_ctrl(BIO *b, int cmd, long num, void *ptr); static long bio_brotli_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp); static const BIO_METHOD bio_meth_brotli = { BIO_TYPE_COMP, "brotli", /* TODO: Convert to new style write function */ bwrite_conv, bio_brotli_write, /* TODO: Convert to new style read function */ bread_conv, bio_brotli_read, NULL, /* bio_brotli_puts, */ NULL, /* bio_brotli_gets, */ bio_brotli_ctrl, bio_brotli_new, bio_brotli_free, bio_brotli_callback_ctrl }; #endif const BIO_METHOD *BIO_f_brotli(void) { #ifndef OPENSSL_NO_BROTLI if (RUN_ONCE(&brotli_once, ossl_comp_brotli_init)) return &bio_meth_brotli; #endif return NULL; } #ifndef OPENSSL_NO_BROTLI static int bio_brotli_new(BIO *bi) { BIO_BROTLI_CTX *ctx; # ifdef BROTLI_SHARED if (!RUN_ONCE(&brotli_once, ossl_comp_brotli_init)) { ERR_raise(ERR_LIB_COMP, COMP_R_BROTLI_NOT_SUPPORTED); return 0; } # endif ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) { ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); return 0; } ctx->decode.bufsize = BROTLI_DEFAULT_BUFSIZE; ctx->decode.state = BrotliDecoderCreateInstance(brotli_alloc, brotli_free, NULL); if (ctx->decode.state == NULL) goto err; ctx->encode.bufsize = BROTLI_DEFAULT_BUFSIZE; ctx->encode.state = BrotliEncoderCreateInstance(brotli_alloc, brotli_free, NULL); if (ctx->encode.state == NULL) goto err; ctx->encode.mode = BROTLI_DEFAULT_MODE; BIO_set_init(bi, 1); BIO_set_data(bi, ctx); return 1; err: ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); BrotliDecoderDestroyInstance(ctx->decode.state); BrotliEncoderDestroyInstance(ctx->encode.state); OPENSSL_free(ctx); return 0; } static int bio_brotli_free(BIO *bi) { BIO_BROTLI_CTX *ctx; if (bi == NULL) return 0; ctx = BIO_get_data(bi); if (ctx != NULL) { BrotliDecoderDestroyInstance(ctx->decode.state); OPENSSL_free(ctx->decode.buf); BrotliEncoderDestroyInstance(ctx->encode.state); OPENSSL_free(ctx->encode.buf); OPENSSL_free(ctx); } BIO_set_data(bi, NULL); BIO_set_init(bi, 0); return 1; } static int bio_brotli_read(BIO *b, char *out, int outl) { BIO_BROTLI_CTX *ctx; BrotliDecoderResult bret; int ret; BIO *next = BIO_next(b); if (out == NULL || outl <= 0) { ERR_raise(ERR_LIB_COMP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } #if INT_MAX > SIZE_MAX if ((unsigned int)outl > SIZE_MAX) { ERR_raise(ERR_LIB_COMP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } #endif ctx = BIO_get_data(b); BIO_clear_retry_flags(b); if (ctx->decode.buf == NULL) { ctx->decode.buf = OPENSSL_malloc(ctx->decode.bufsize); if (ctx->decode.buf == NULL) { ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); return 0; } ctx->decode.next_in = ctx->decode.buf; ctx->decode.avail_in = 0; } /* Copy output data directly to supplied buffer */ ctx->decode.next_out = (unsigned char *)out; ctx->decode.avail_out = (size_t)outl; for (;;) { /* Decompress while data available */ while (ctx->decode.avail_in > 0 || BrotliDecoderHasMoreOutput(ctx->decode.state)) { bret = BrotliDecoderDecompressStream(ctx->decode.state, &ctx->decode.avail_in, (const uint8_t**)&ctx->decode.next_in, &ctx->decode.avail_out, &ctx->decode.next_out, NULL); if (bret == BROTLI_DECODER_RESULT_ERROR) { ERR_raise(ERR_LIB_COMP, COMP_R_BROTLI_DECODE_ERROR); ERR_add_error_data(1, BrotliDecoderErrorString(BrotliDecoderGetErrorCode(ctx->decode.state))); return 0; } /* If EOF or we've read everything then return */ if (BrotliDecoderIsFinished(ctx->decode.state) || ctx->decode.avail_out == 0) return (int)(outl - ctx->decode.avail_out); } /* If EOF */ if (BrotliDecoderIsFinished(ctx->decode.state)) return 0; /* * No data in input buffer try to read some in, if an error then * return the total data read. */ ret = BIO_read(next, ctx->decode.buf, ctx->decode.bufsize); if (ret <= 0) { /* Total data read */ int tot = outl - ctx->decode.avail_out; BIO_copy_next_retry(b); if (ret < 0) return (tot > 0) ? tot : ret; return tot; } ctx->decode.avail_in = ret; ctx->decode.next_in = ctx->decode.buf; } } static int bio_brotli_write(BIO *b, const char *in, int inl) { BIO_BROTLI_CTX *ctx; BROTLI_BOOL brret; int ret; BIO *next = BIO_next(b); if (in == NULL || inl <= 0) { ERR_raise(ERR_LIB_COMP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } #if INT_MAX > SIZE_MAX if ((unsigned int)inl > SIZE_MAX) { ERR_raise(ERR_LIB_COMP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } #endif ctx = BIO_get_data(b); if (ctx->encode.done) return 0; BIO_clear_retry_flags(b); if (ctx->encode.buf == NULL) { ctx->encode.buf = OPENSSL_malloc(ctx->encode.bufsize); if (ctx->encode.buf == NULL) { ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); return 0; } ctx->encode.ptr = ctx->encode.buf; ctx->encode.count = 0; ctx->encode.next_out = ctx->encode.buf; ctx->encode.avail_out = ctx->encode.bufsize; } /* Obtain input data directly from supplied buffer */ ctx->encode.next_in = (unsigned char *)in; ctx->encode.avail_in = (size_t)inl; for (;;) { /* If data in output buffer write it first */ while (ctx->encode.count > 0) { ret = BIO_write(next, ctx->encode.ptr, ctx->encode.count); if (ret <= 0) { /* Total data written */ int tot = inl - ctx->encode.avail_in; BIO_copy_next_retry(b); if (ret < 0) return (tot > 0) ? tot : ret; return tot; } ctx->encode.ptr += ret; ctx->encode.count -= ret; } /* Have we consumed all supplied data? */ if (ctx->encode.avail_in == 0 && !BrotliEncoderHasMoreOutput(ctx->encode.state)) return inl; /* Compress some more */ /* Reset buffer */ ctx->encode.ptr = ctx->encode.buf; ctx->encode.next_out = ctx->encode.buf; ctx->encode.avail_out = ctx->encode.bufsize; /* Compress some more */ brret = BrotliEncoderCompressStream(ctx->encode.state, BROTLI_OPERATION_FLUSH, &ctx->encode.avail_in, (const uint8_t**)&ctx->encode.next_in, &ctx->encode.avail_out, &ctx->encode.next_out, NULL); if (brret != BROTLI_TRUE) { ERR_raise(ERR_LIB_COMP, COMP_R_BROTLI_ENCODE_ERROR); ERR_add_error_data(1, "brotli encoder error"); return 0; } ctx->encode.count = ctx->encode.bufsize - ctx->encode.avail_out; } } static int bio_brotli_flush(BIO *b) { BIO_BROTLI_CTX *ctx; BROTLI_BOOL brret; int ret; BIO *next = BIO_next(b); ctx = BIO_get_data(b); /* If no data written or already flush show success */ if (ctx->encode.buf == NULL || (ctx->encode.done && ctx->encode.count == 0)) return 1; BIO_clear_retry_flags(b); /* No more input data */ ctx->encode.next_in = NULL; ctx->encode.avail_in = 0; for (;;) { /* If data in output buffer write it first */ while (ctx->encode.count > 0) { ret = BIO_write(next, ctx->encode.ptr, ctx->encode.count); if (ret <= 0) { BIO_copy_next_retry(b); return ret; } ctx->encode.ptr += ret; ctx->encode.count -= ret; } if (ctx->encode.done) return 1; /* Compress some more */ /* Reset buffer */ ctx->encode.ptr = ctx->encode.buf; ctx->encode.next_out = ctx->encode.buf; ctx->encode.avail_out = ctx->encode.bufsize; /* Compress some more */ brret = BrotliEncoderCompressStream(ctx->encode.state, BROTLI_OPERATION_FINISH, &ctx->encode.avail_in, (const uint8_t**)&ctx->encode.next_in, &ctx->encode.avail_out, &ctx->encode.next_out, NULL); if (brret != BROTLI_TRUE) { ERR_raise(ERR_LIB_COMP, COMP_R_BROTLI_DECODE_ERROR); ERR_add_error_data(1, "brotli encoder error"); return 0; } if (!BrotliEncoderHasMoreOutput(ctx->encode.state) && ctx->encode.avail_in == 0) ctx->encode.done = 1; ctx->encode.count = ctx->encode.bufsize - ctx->encode.avail_out; } } static long bio_brotli_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO_BROTLI_CTX *ctx; unsigned char *tmp; int ret = 0, *ip; size_t ibs, obs; BIO *next = BIO_next(b); if (next == NULL) return 0; ctx = BIO_get_data(b); switch (cmd) { case BIO_CTRL_RESET: ctx->encode.count = 0; ctx->encode.done = 0; ret = 1; break; case BIO_CTRL_FLUSH: ret = bio_brotli_flush(b); if (ret > 0) { ret = BIO_flush(next); BIO_copy_next_retry(b); } break; case BIO_C_SET_BUFF_SIZE: ibs = ctx->decode.bufsize; obs = ctx->encode.bufsize; if (ptr != NULL) { ip = ptr; if (*ip == 0) ibs = (size_t)num; else obs = (size_t)num; } else { ibs = (size_t)num; obs = ibs; } if (ibs > 0 && ibs != ctx->decode.bufsize) { /* Do not free/alloc, only reallocate */ if (ctx->decode.buf != NULL) { tmp = OPENSSL_realloc(ctx->decode.buf, ibs); if (tmp == NULL) return 0; ctx->decode.buf = tmp; } ctx->decode.bufsize = ibs; } if (obs > 0 && obs != ctx->encode.bufsize) { /* Do not free/alloc, only reallocate */ if (ctx->encode.buf != NULL) { tmp = OPENSSL_realloc(ctx->encode.buf, obs); if (tmp == NULL) return 0; ctx->encode.buf = tmp; } ctx->encode.bufsize = obs; } ret = 1; break; case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_WPENDING: if (BrotliEncoderHasMoreOutput(ctx->encode.state)) ret = 1; else ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_PENDING: if (!BrotliDecoderIsFinished(ctx->decode.state)) ret = 1; else ret = BIO_ctrl(next, cmd, num, ptr); break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static long bio_brotli_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } #endif
./openssl/crypto/comp/comp_lib.c
/* * Copyright 1998-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 <stdlib.h> #include <string.h> #include <openssl/objects.h> #include <openssl/comp.h> #include <openssl/err.h> #include "comp_local.h" COMP_CTX *COMP_CTX_new(COMP_METHOD *meth) { COMP_CTX *ret; if (meth == NULL) return NULL; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; ret->meth = meth; if ((ret->meth->init != NULL) && !ret->meth->init(ret)) { OPENSSL_free(ret); ret = NULL; } return ret; } const COMP_METHOD *COMP_CTX_get_method(const COMP_CTX *ctx) { return ctx->meth; } int COMP_get_type(const COMP_METHOD *meth) { if (meth == NULL) return NID_undef; return meth->type; } const char *COMP_get_name(const COMP_METHOD *meth) { if (meth == NULL) return NULL; return meth->name; } void COMP_CTX_free(COMP_CTX *ctx) { if (ctx == NULL) return; if (ctx->meth->finish != NULL) ctx->meth->finish(ctx); OPENSSL_free(ctx); } int COMP_compress_block(COMP_CTX *ctx, unsigned char *out, int olen, unsigned char *in, int ilen) { int ret; if (ctx->meth->compress == NULL) { return -1; } ret = ctx->meth->compress(ctx, out, olen, in, ilen); if (ret > 0) { ctx->compress_in += ilen; ctx->compress_out += ret; } return ret; } int COMP_expand_block(COMP_CTX *ctx, unsigned char *out, int olen, unsigned char *in, int ilen) { int ret; if (ctx->meth->expand == NULL) { return -1; } ret = ctx->meth->expand(ctx, out, olen, in, ilen); if (ret > 0) { ctx->expand_in += ilen; ctx->expand_out += ret; } return ret; } int COMP_CTX_get_type(const COMP_CTX* comp) { return comp->meth ? comp->meth->type : NID_undef; }
./openssl/crypto/comp/c_zstd.c
/* * Copyright 1998-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * Uses zstd compression library from https://github.com/facebook/zstd * Requires version 1.4.x (latest as of this writing is 1.4.5) * Using custom free functions require static linking, so that is disabled when * using the shared library. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/objects.h> #include "internal/comp.h" #include <openssl/err.h> #include "crypto/cryptlib.h" #include "internal/bio.h" #include "internal/thread_once.h" #include "comp_local.h" COMP_METHOD *COMP_zstd(void); #ifdef OPENSSL_NO_ZSTD # undef ZSTD_SHARED #else # ifndef ZSTD_SHARED # define ZSTD_STATIC_LINKING_ONLY # endif # include <zstd.h> /* Note: There is also a linux zstd.h file in the kernel source */ # ifndef ZSTD_H_235446 # error Wrong (i.e. linux) zstd.h included. # endif # if ZSTD_VERSION_MAJOR != 1 && ZSTD_VERSION_MINOR < 4 # error Expecting version 1.4 or greater of ZSTD # endif # ifndef ZSTD_SHARED /* memory allocations functions for zstd initialisation */ static void *zstd_alloc(void *opaque, size_t size) { return OPENSSL_zalloc(size); } static void zstd_free(void *opaque, void *address) { OPENSSL_free(address); } static ZSTD_customMem zstd_mem_funcs = { zstd_alloc, zstd_free, NULL }; # endif /* * When OpenSSL is built on Windows, we do not want to require that * the LIBZSTD.DLL be available in order for the OpenSSL DLLs to * work. Therefore, all ZSTD routines are loaded at run time * and we do not link to a .LIB file when ZSTD_SHARED is set. */ # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # include <windows.h> # endif # ifdef ZSTD_SHARED # include "internal/dso.h" /* Function pointers */ typedef ZSTD_CStream* (*createCStream_ft)(void); typedef size_t (*initCStream_ft)(ZSTD_CStream*, int); typedef size_t (*freeCStream_ft)(ZSTD_CStream*); typedef size_t (*compressStream2_ft)(ZSTD_CCtx*, ZSTD_outBuffer*, ZSTD_inBuffer*, ZSTD_EndDirective); typedef size_t (*flushStream_ft)(ZSTD_CStream*, ZSTD_outBuffer*); typedef size_t (*endStream_ft)(ZSTD_CStream*, ZSTD_outBuffer*); typedef size_t (*compress_ft)(void*, size_t, const void*, size_t, int); typedef ZSTD_DStream* (*createDStream_ft)(void); typedef size_t (*initDStream_ft)(ZSTD_DStream*); typedef size_t (*freeDStream_ft)(ZSTD_DStream*); typedef size_t (*decompressStream_ft)(ZSTD_DStream*, ZSTD_outBuffer*, ZSTD_inBuffer*); typedef size_t (*decompress_ft)(void*, size_t, const void*, size_t); typedef unsigned (*isError_ft)(size_t); typedef const char* (*getErrorName_ft)(size_t); typedef size_t (*DStreamInSize_ft)(void); typedef size_t (*CStreamInSize_ft)(void); static createCStream_ft p_createCStream = NULL; static initCStream_ft p_initCStream = NULL; static freeCStream_ft p_freeCStream = NULL; static compressStream2_ft p_compressStream2 = NULL; static flushStream_ft p_flushStream = NULL; static endStream_ft p_endStream = NULL; static compress_ft p_compress = NULL; static createDStream_ft p_createDStream = NULL; static initDStream_ft p_initDStream = NULL; static freeDStream_ft p_freeDStream = NULL; static decompressStream_ft p_decompressStream = NULL; static decompress_ft p_decompress = NULL; static isError_ft p_isError = NULL; static getErrorName_ft p_getErrorName = NULL; static DStreamInSize_ft p_DStreamInSize = NULL; static CStreamInSize_ft p_CStreamInSize = NULL; static DSO *zstd_dso = NULL; # define ZSTD_createCStream p_createCStream # define ZSTD_initCStream p_initCStream # define ZSTD_freeCStream p_freeCStream # define ZSTD_compressStream2 p_compressStream2 # define ZSTD_flushStream p_flushStream # define ZSTD_endStream p_endStream # define ZSTD_compress p_compress # define ZSTD_createDStream p_createDStream # define ZSTD_initDStream p_initDStream # define ZSTD_freeDStream p_freeDStream # define ZSTD_decompressStream p_decompressStream # define ZSTD_decompress p_decompress # define ZSTD_isError p_isError # define ZSTD_getErrorName p_getErrorName # define ZSTD_DStreamInSize p_DStreamInSize # define ZSTD_CStreamInSize p_CStreamInSize # endif /* ifdef ZSTD_SHARED */ struct zstd_state { ZSTD_CStream *compressor; ZSTD_DStream *decompressor; }; static int zstd_stateful_init(COMP_CTX *ctx) { struct zstd_state *state = OPENSSL_zalloc(sizeof(*state)); if (state == NULL) return 0; # ifdef ZSTD_SHARED state->compressor = ZSTD_createCStream(); # else state->compressor = ZSTD_createCStream_advanced(zstd_mem_funcs); # endif if (state->compressor == NULL) goto err; ZSTD_initCStream(state->compressor, ZSTD_CLEVEL_DEFAULT); # ifdef ZSTD_SHARED state->decompressor = ZSTD_createDStream(); # else state->decompressor = ZSTD_createDStream_advanced(zstd_mem_funcs); # endif if (state->decompressor == NULL) goto err; ZSTD_initDStream(state->decompressor); ctx->data = state; return 1; err: ZSTD_freeCStream(state->compressor); ZSTD_freeDStream(state->decompressor); OPENSSL_free(state); return 0; } static void zstd_stateful_finish(COMP_CTX *ctx) { struct zstd_state *state = ctx->data; if (state != NULL) { ZSTD_freeCStream(state->compressor); ZSTD_freeDStream(state->decompressor); OPENSSL_free(state); ctx->data = NULL; } } static ossl_ssize_t zstd_stateful_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { ZSTD_inBuffer inbuf; ZSTD_outBuffer outbuf; size_t ret; ossl_ssize_t fret; struct zstd_state *state = ctx->data; inbuf.src = in; inbuf.size = ilen; inbuf.pos = 0; outbuf.dst = out; outbuf.size = olen; outbuf.pos = 0; if (state == NULL) return -1; /* If input length is zero, end the stream/frame ? */ if (ilen == 0) { ret = ZSTD_endStream(state->compressor, &outbuf); if (ZSTD_isError(ret)) return -1; goto end; } /* * The finish API does not provide a final output buffer, * so each compress operation has to be ended, if all * the input data can't be accepted, or there is more output, * this has to be considered an error, since there is no more * output buffer space. */ do { ret = ZSTD_compressStream2(state->compressor, &outbuf, &inbuf, ZSTD_e_continue); if (ZSTD_isError(ret)) return -1; /* do I need to check for ret == 0 ? */ } while (inbuf.pos < inbuf.size); /* Did not consume all the data */ if (inbuf.pos < inbuf.size) return -1; ret = ZSTD_flushStream(state->compressor, &outbuf); if (ZSTD_isError(ret)) return -1; end: if (outbuf.pos > OSSL_SSIZE_MAX) return -1; fret = (ossl_ssize_t)outbuf.pos; if (fret < 0) return -1; return fret; } static ossl_ssize_t zstd_stateful_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { ZSTD_inBuffer inbuf; ZSTD_outBuffer outbuf; size_t ret; ossl_ssize_t fret; struct zstd_state *state = ctx->data; inbuf.src = in; inbuf.size = ilen; inbuf.pos = 0; outbuf.dst = out; outbuf.size = olen; outbuf.pos = 0; if (state == NULL) return -1; if (ilen == 0) return 0; do { ret = ZSTD_decompressStream(state->decompressor, &outbuf, &inbuf); if (ZSTD_isError(ret)) return -1; /* If we completed a frame, and there's more data, try again */ } while (ret == 0 && inbuf.pos < inbuf.size); /* Did not consume all the data */ if (inbuf.pos < inbuf.size) return -1; if (outbuf.pos > OSSL_SSIZE_MAX) return -1; fret = (ossl_ssize_t)outbuf.pos; if (fret < 0) return -1; return fret; } static COMP_METHOD zstd_stateful_method = { NID_zstd, LN_zstd, zstd_stateful_init, zstd_stateful_finish, zstd_stateful_compress_block, zstd_stateful_expand_block }; static int zstd_oneshot_init(COMP_CTX *ctx) { return 1; } static void zstd_oneshot_finish(COMP_CTX *ctx) { } static ossl_ssize_t zstd_oneshot_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { size_t out_size; ossl_ssize_t ret; if (ilen == 0) return 0; /* Note: uses STDLIB memory allocators */ out_size = ZSTD_compress(out, olen, in, ilen, ZSTD_CLEVEL_DEFAULT); if (ZSTD_isError(out_size)) return -1; if (out_size > OSSL_SSIZE_MAX) return -1; ret = (ossl_ssize_t)out_size; if (ret < 0) return -1; return ret; } static ossl_ssize_t zstd_oneshot_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { size_t out_size; ossl_ssize_t ret; if (ilen == 0) return 0; /* Note: uses STDLIB memory allocators */ out_size = ZSTD_decompress(out, olen, in, ilen); if (ZSTD_isError(out_size)) return -1; if (out_size > OSSL_SSIZE_MAX) return -1; ret = (ossl_ssize_t)out_size; if (ret < 0) return -1; return ret; } static COMP_METHOD zstd_oneshot_method = { NID_zstd, LN_zstd, zstd_oneshot_init, zstd_oneshot_finish, zstd_oneshot_compress_block, zstd_oneshot_expand_block }; static CRYPTO_ONCE zstd_once = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_comp_zstd_init) { # ifdef ZSTD_SHARED # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # define LIBZSTD "LIBZSTD" # else # define LIBZSTD "zstd" # endif zstd_dso = DSO_load(NULL, LIBZSTD, NULL, 0); if (zstd_dso != NULL) { p_createCStream = (createCStream_ft)DSO_bind_func(zstd_dso, "ZSTD_createCStream"); p_initCStream = (initCStream_ft)DSO_bind_func(zstd_dso, "ZSTD_initCStream"); p_freeCStream = (freeCStream_ft)DSO_bind_func(zstd_dso, "ZSTD_freeCStream"); p_compressStream2 = (compressStream2_ft)DSO_bind_func(zstd_dso, "ZSTD_compressStream2"); p_flushStream = (flushStream_ft)DSO_bind_func(zstd_dso, "ZSTD_flushStream"); p_endStream = (endStream_ft)DSO_bind_func(zstd_dso, "ZSTD_endStream"); p_compress = (compress_ft)DSO_bind_func(zstd_dso, "ZSTD_compress"); p_createDStream = (createDStream_ft)DSO_bind_func(zstd_dso, "ZSTD_createDStream"); p_initDStream = (initDStream_ft)DSO_bind_func(zstd_dso, "ZSTD_initDStream"); p_freeDStream = (freeDStream_ft)DSO_bind_func(zstd_dso, "ZSTD_freeDStream"); p_decompressStream = (decompressStream_ft)DSO_bind_func(zstd_dso, "ZSTD_decompressStream"); p_decompress = (decompress_ft)DSO_bind_func(zstd_dso, "ZSTD_decompress"); p_isError = (isError_ft)DSO_bind_func(zstd_dso, "ZSTD_isError"); p_getErrorName = (getErrorName_ft)DSO_bind_func(zstd_dso, "ZSTD_getErrorName"); p_DStreamInSize = (DStreamInSize_ft)DSO_bind_func(zstd_dso, "ZSTD_DStreamInSize"); p_CStreamInSize = (CStreamInSize_ft)DSO_bind_func(zstd_dso, "ZSTD_CStreamInSize"); } if (p_createCStream == NULL || p_initCStream == NULL || p_freeCStream == NULL || p_compressStream2 == NULL || p_flushStream == NULL || p_endStream == NULL || p_compress == NULL || p_createDStream == NULL || p_initDStream == NULL || p_freeDStream == NULL || p_decompressStream == NULL || p_decompress == NULL || p_isError == NULL || p_getErrorName == NULL || p_DStreamInSize == NULL || p_CStreamInSize == NULL) { ossl_comp_zstd_cleanup(); return 0; } # endif return 1; } #endif /* ifndef ZSTD / else */ COMP_METHOD *COMP_zstd(void) { COMP_METHOD *meth = NULL; #ifndef OPENSSL_NO_ZSTD if (RUN_ONCE(&zstd_once, ossl_comp_zstd_init)) meth = &zstd_stateful_method; #endif return meth; } COMP_METHOD *COMP_zstd_oneshot(void) { COMP_METHOD *meth = NULL; #ifndef OPENSSL_NO_ZSTD if (RUN_ONCE(&zstd_once, ossl_comp_zstd_init)) meth = &zstd_oneshot_method; #endif return meth; } /* Also called from OPENSSL_cleanup() */ void ossl_comp_zstd_cleanup(void) { #ifdef ZSTD_SHARED DSO_free(zstd_dso); zstd_dso = NULL; p_createCStream = NULL; p_initCStream = NULL; p_freeCStream = NULL; p_compressStream2 = NULL; p_flushStream = NULL; p_endStream = NULL; p_compress = NULL; p_createDStream = NULL; p_initDStream = NULL; p_freeDStream = NULL; p_decompressStream = NULL; p_decompress = NULL; p_isError = NULL; p_getErrorName = NULL; p_DStreamInSize = NULL; p_CStreamInSize = NULL; #endif } #ifndef OPENSSL_NO_ZSTD /* Zstd-based compression/decompression filter BIO */ typedef struct { struct { /* input structure */ ZSTD_DStream *state; ZSTD_inBuffer inbuf; /* has const src */ size_t bufsize; void* buffer; } decompress; struct { /* output structure */ ZSTD_CStream *state; ZSTD_outBuffer outbuf; size_t bufsize; size_t write_pos; } compress; } BIO_ZSTD_CTX; # define ZSTD_DEFAULT_BUFSIZE 1024 static int bio_zstd_new(BIO *bi); static int bio_zstd_free(BIO *bi); static int bio_zstd_read(BIO *b, char *out, int outl); static int bio_zstd_write(BIO *b, const char *in, int inl); static long bio_zstd_ctrl(BIO *b, int cmd, long num, void *ptr); static long bio_zstd_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp); static const BIO_METHOD bio_meth_zstd = { BIO_TYPE_COMP, "zstd", /* TODO: Convert to new style write function */ bwrite_conv, bio_zstd_write, /* TODO: Convert to new style read function */ bread_conv, bio_zstd_read, NULL, /* bio_zstd_puts, */ NULL, /* bio_zstd_gets, */ bio_zstd_ctrl, bio_zstd_new, bio_zstd_free, bio_zstd_callback_ctrl }; #endif const BIO_METHOD *BIO_f_zstd(void) { #ifndef OPENSSL_NO_ZSTD if (RUN_ONCE(&zstd_once, ossl_comp_zstd_init)) return &bio_meth_zstd; #endif return NULL; } #ifndef OPENSSL_NO_ZSTD static int bio_zstd_new(BIO *bi) { BIO_ZSTD_CTX *ctx; # ifdef ZSTD_SHARED (void)COMP_zstd(); if (zstd_dso == NULL) { ERR_raise(ERR_LIB_COMP, COMP_R_ZSTD_NOT_SUPPORTED); return 0; } # endif ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) { ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); return 0; } # ifdef ZSTD_SHARED ctx->decompress.state = ZSTD_createDStream(); # else ctx->decompress.state = ZSTD_createDStream_advanced(zstd_mem_funcs); # endif if (ctx->decompress.state == NULL) goto err; ZSTD_initDStream(ctx->decompress.state); ctx->decompress.bufsize = ZSTD_DStreamInSize(); # ifdef ZSTD_SHARED ctx->compress.state = ZSTD_createCStream(); # else ctx->compress.state = ZSTD_createCStream_advanced(zstd_mem_funcs); # endif if (ctx->compress.state == NULL) goto err; ZSTD_initCStream(ctx->compress.state, ZSTD_CLEVEL_DEFAULT); ctx->compress.bufsize = ZSTD_CStreamInSize(); BIO_set_init(bi, 1); BIO_set_data(bi, ctx); return 1; err: ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); ZSTD_freeDStream(ctx->decompress.state); ZSTD_freeCStream(ctx->compress.state); OPENSSL_free(ctx); return 0; } static int bio_zstd_free(BIO *bi) { BIO_ZSTD_CTX *ctx; if (bi == NULL) return 0; ctx = BIO_get_data(bi); if (ctx != NULL) { ZSTD_freeDStream(ctx->decompress.state); OPENSSL_free(ctx->decompress.buffer); ZSTD_freeCStream(ctx->compress.state); OPENSSL_free(ctx->compress.outbuf.dst); OPENSSL_free(ctx); } BIO_set_data(bi, NULL); BIO_set_init(bi, 0); return 1; } static int bio_zstd_read(BIO *b, char *out, int outl) { BIO_ZSTD_CTX *ctx; size_t zret; int ret; ZSTD_outBuffer outBuf; BIO *next = BIO_next(b); if (out == NULL || outl <= 0) return 0; ctx = BIO_get_data(b); BIO_clear_retry_flags(b); if (ctx->decompress.buffer == NULL) { ctx->decompress.buffer = OPENSSL_malloc(ctx->decompress.bufsize); if (ctx->decompress.buffer == NULL) { ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); return 0; } ctx->decompress.inbuf.src = ctx->decompress.buffer; ctx->decompress.inbuf.size = 0; ctx->decompress.inbuf.pos = 0; } /* Copy output data directly to supplied buffer */ outBuf.dst = out; outBuf.size = (size_t)outl; outBuf.pos = 0; for (;;) { /* Decompress while data available */ do { zret = ZSTD_decompressStream(ctx->decompress.state, &outBuf, &ctx->decompress.inbuf); if (ZSTD_isError(zret)) { ERR_raise(ERR_LIB_COMP, COMP_R_ZSTD_DECOMPRESS_ERROR); ERR_add_error_data(1, ZSTD_getErrorName(zret)); return -1; } /* No more output space */ if (outBuf.pos == outBuf.size) return outBuf.pos; } while (ctx->decompress.inbuf.pos < ctx->decompress.inbuf.size); /* * No data in input buffer try to read some in, if an error then * return the total data read. */ ret = BIO_read(next, ctx->decompress.buffer, ctx->decompress.bufsize); if (ret <= 0) { BIO_copy_next_retry(b); if (ret < 0 && outBuf.pos == 0) return ret; return outBuf.pos; } ctx->decompress.inbuf.size = ret; ctx->decompress.inbuf.pos = 0; } } static int bio_zstd_write(BIO *b, const char *in, int inl) { BIO_ZSTD_CTX *ctx; size_t zret; ZSTD_inBuffer inBuf; int ret; int done = 0; BIO *next = BIO_next(b); if (in == NULL || inl <= 0) return 0; ctx = BIO_get_data(b); BIO_clear_retry_flags(b); if (ctx->compress.outbuf.dst == NULL) { ctx->compress.outbuf.dst = OPENSSL_malloc(ctx->compress.bufsize); if (ctx->compress.outbuf.dst == NULL) { ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); return 0; } ctx->compress.outbuf.size = ctx->compress.bufsize; ctx->compress.outbuf.pos = 0; ctx->compress.write_pos = 0; } /* Obtain input data directly from supplied buffer */ inBuf.src = in; inBuf.size = inl; inBuf.pos = 0; for (;;) { /* If data in output buffer write it first */ while (ctx->compress.write_pos < ctx->compress.outbuf.pos) { ret = BIO_write(next, (unsigned char*)ctx->compress.outbuf.dst + ctx->compress.write_pos, ctx->compress.outbuf.pos - ctx->compress.write_pos); if (ret <= 0) { BIO_copy_next_retry(b); if (ret < 0 && inBuf.pos == 0) return ret; return inBuf.pos; } ctx->compress.write_pos += ret; } /* Have we consumed all supplied data? */ if (done) return inBuf.pos; /* Reset buffer */ ctx->compress.outbuf.pos = 0; ctx->compress.outbuf.size = ctx->compress.bufsize; ctx->compress.write_pos = 0; /* Compress some more */ zret = ZSTD_compressStream2(ctx->compress.state, &ctx->compress.outbuf, &inBuf, ZSTD_e_end); if (ZSTD_isError(zret)) { ERR_raise(ERR_LIB_COMP, COMP_R_ZSTD_COMPRESS_ERROR); ERR_add_error_data(1, ZSTD_getErrorName(zret)); return 0; } else if (zret == 0) { done = 1; } } } static int bio_zstd_flush(BIO *b) { BIO_ZSTD_CTX *ctx; size_t zret; int ret; BIO *next = BIO_next(b); ctx = BIO_get_data(b); /* If no data written or already flush show success */ if (ctx->compress.outbuf.dst == NULL) return 1; BIO_clear_retry_flags(b); /* No more input data */ ctx->compress.outbuf.pos = 0; ctx->compress.outbuf.size = ctx->compress.bufsize; ctx->compress.write_pos = 0; for (;;) { /* If data in output buffer write it first */ while (ctx->compress.write_pos < ctx->compress.outbuf.pos) { ret = BIO_write(next, (unsigned char*)ctx->compress.outbuf.dst + ctx->compress.write_pos, ctx->compress.outbuf.pos - ctx->compress.write_pos); if (ret <= 0) { BIO_copy_next_retry(b); return ret; } ctx->compress.write_pos += ret; } /* Reset buffer */ ctx->compress.outbuf.pos = 0; ctx->compress.outbuf.size = ctx->compress.bufsize; ctx->compress.write_pos = 0; /* Compress some more */ zret = ZSTD_flushStream(ctx->compress.state, &ctx->compress.outbuf); if (ZSTD_isError(zret)) { ERR_raise(ERR_LIB_COMP, COMP_R_ZSTD_DECODE_ERROR); ERR_add_error_data(1, ZSTD_getErrorName(zret)); return 0; } if (zret == 0) return 1; } } static long bio_zstd_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO_ZSTD_CTX *ctx; int ret = 0, *ip; size_t ibs, obs; unsigned char *tmp; BIO *next = BIO_next(b); if (next == NULL) return 0; ctx = BIO_get_data(b); switch (cmd) { case BIO_CTRL_RESET: ctx->compress.write_pos = 0; ctx->compress.bufsize = 0; ret = 1; break; case BIO_CTRL_FLUSH: ret = bio_zstd_flush(b); if (ret > 0) { ret = BIO_flush(next); BIO_copy_next_retry(b); } break; case BIO_C_SET_BUFF_SIZE: ibs = ctx->decompress.bufsize; obs = ctx->compress.bufsize; if (ptr != NULL) { ip = ptr; if (*ip == 0) ibs = (size_t)num; else obs = (size_t)num; } else { obs = ibs = (size_t)num; } if (ibs > 0 && ibs != ctx->decompress.bufsize) { if (ctx->decompress.buffer != NULL) { tmp = OPENSSL_realloc(ctx->decompress.buffer, ibs); if (tmp == NULL) return 0; if (ctx->decompress.inbuf.src == ctx->decompress.buffer) ctx->decompress.inbuf.src = tmp; ctx->decompress.buffer = tmp; } ctx->decompress.bufsize = ibs; } if (obs > 0 && obs != ctx->compress.bufsize) { if (ctx->compress.outbuf.dst != NULL) { tmp = OPENSSL_realloc(ctx->compress.outbuf.dst, obs); if (tmp == NULL) return 0; ctx->compress.outbuf.dst = tmp; } ctx->compress.bufsize = obs; } ret = 1; break; case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_WPENDING: if (ctx->compress.outbuf.pos < ctx->compress.outbuf.size) ret = 1; else ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_PENDING: if (ctx->decompress.inbuf.pos < ctx->decompress.inbuf.size) ret = 1; else ret = BIO_ctrl(next, cmd, num, ptr); break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static long bio_zstd_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } #endif
./openssl/crypto/comp/c_zlib.c
/* * Copyright 1998-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/objects.h> #include "internal/comp.h" #include <openssl/err.h> #include "crypto/cryptlib.h" #include "internal/bio.h" #include "internal/thread_once.h" #include "comp_local.h" COMP_METHOD *COMP_zlib(void); #ifdef OPENSSL_NO_ZLIB # undef ZLIB_SHARED #else # include <zlib.h> static int zlib_stateful_init(COMP_CTX *ctx); static void zlib_stateful_finish(COMP_CTX *ctx); static ossl_ssize_t zlib_stateful_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen); static ossl_ssize_t zlib_stateful_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen); /* memory allocations functions for zlib initialisation */ static void *zlib_zalloc(void *opaque, unsigned int no, unsigned int size) { void *p; p = OPENSSL_zalloc(no * size); return p; } static void zlib_zfree(void *opaque, void *address) { OPENSSL_free(address); } static COMP_METHOD zlib_stateful_method = { NID_zlib_compression, LN_zlib_compression, zlib_stateful_init, zlib_stateful_finish, zlib_stateful_compress_block, zlib_stateful_expand_block }; /* * When OpenSSL is built on Windows, we do not want to require that * the ZLIB.DLL be available in order for the OpenSSL DLLs to * work. Therefore, all ZLIB routines are loaded at run time * and we do not link to a .LIB file when ZLIB_SHARED is set. */ # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # include <windows.h> # endif /* !(OPENSSL_SYS_WINDOWS || * OPENSSL_SYS_WIN32) */ # ifdef ZLIB_SHARED # include "internal/dso.h" /* Function pointers */ typedef int (*compress_ft) (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen); typedef int (*uncompress_ft) (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen); typedef int (*inflateEnd_ft) (z_streamp strm); typedef int (*inflate_ft) (z_streamp strm, int flush); typedef int (*inflateInit__ft) (z_streamp strm, const char *version, int stream_size); typedef int (*deflateEnd_ft) (z_streamp strm); typedef int (*deflate_ft) (z_streamp strm, int flush); typedef int (*deflateInit__ft) (z_streamp strm, int level, const char *version, int stream_size); typedef const char *(*zError__ft) (int err); static compress_ft p_compress = NULL; static uncompress_ft p_uncompress = NULL; static inflateEnd_ft p_inflateEnd = NULL; static inflate_ft p_inflate = NULL; static inflateInit__ft p_inflateInit_ = NULL; static deflateEnd_ft p_deflateEnd = NULL; static deflate_ft p_deflate = NULL; static deflateInit__ft p_deflateInit_ = NULL; static zError__ft p_zError = NULL; static DSO *zlib_dso = NULL; # define compress p_compress # define uncompress p_uncompress # define inflateEnd p_inflateEnd # define inflate p_inflate # define inflateInit_ p_inflateInit_ # define deflateEnd p_deflateEnd # define deflate p_deflate # define deflateInit_ p_deflateInit_ # define zError p_zError # endif /* ZLIB_SHARED */ struct zlib_state { z_stream istream; z_stream ostream; }; static int zlib_stateful_init(COMP_CTX *ctx) { int err; struct zlib_state *state = OPENSSL_zalloc(sizeof(*state)); if (state == NULL) goto err; state->istream.zalloc = zlib_zalloc; state->istream.zfree = zlib_zfree; state->istream.opaque = Z_NULL; state->istream.next_in = Z_NULL; state->istream.next_out = Z_NULL; err = inflateInit_(&state->istream, ZLIB_VERSION, sizeof(z_stream)); if (err != Z_OK) goto err; state->ostream.zalloc = zlib_zalloc; state->ostream.zfree = zlib_zfree; state->ostream.opaque = Z_NULL; state->ostream.next_in = Z_NULL; state->ostream.next_out = Z_NULL; err = deflateInit_(&state->ostream, Z_DEFAULT_COMPRESSION, ZLIB_VERSION, sizeof(z_stream)); if (err != Z_OK) goto err; ctx->data = state; return 1; err: OPENSSL_free(state); return 0; } static void zlib_stateful_finish(COMP_CTX *ctx) { struct zlib_state *state = ctx->data; inflateEnd(&state->istream); deflateEnd(&state->ostream); OPENSSL_free(state); } static ossl_ssize_t zlib_stateful_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { int err = Z_OK; struct zlib_state *state = ctx->data; if (state == NULL) return -1; state->ostream.next_in = in; state->ostream.avail_in = ilen; state->ostream.next_out = out; state->ostream.avail_out = olen; if (ilen > 0) err = deflate(&state->ostream, Z_SYNC_FLUSH); if (err != Z_OK) return -1; if (state->ostream.avail_out > olen) return -1; return (ossl_ssize_t)(olen - state->ostream.avail_out); } static ossl_ssize_t zlib_stateful_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { int err = Z_OK; struct zlib_state *state = ctx->data; if (state == NULL) return 0; state->istream.next_in = in; state->istream.avail_in = ilen; state->istream.next_out = out; state->istream.avail_out = olen; if (ilen > 0) err = inflate(&state->istream, Z_SYNC_FLUSH); if (err != Z_OK) return -1; if (state->istream.avail_out > olen) return -1; return (ossl_ssize_t)(olen - state->istream.avail_out); } /* ONESHOT COMPRESSION/DECOMPRESSION */ static int zlib_oneshot_init(COMP_CTX *ctx) { return 1; } static void zlib_oneshot_finish(COMP_CTX *ctx) { } static ossl_ssize_t zlib_oneshot_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { uLongf out_size; if (ilen == 0) return 0; /* zlib's uLongf defined as unsigned long FAR */ if (olen > ULONG_MAX) return -1; out_size = (uLongf)olen; if (compress(out, &out_size, in, ilen) != Z_OK) return -1; if (out_size > OSSL_SSIZE_MAX) return -1; return (ossl_ssize_t)out_size; } static ossl_ssize_t zlib_oneshot_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { uLongf out_size; if (ilen == 0) return 0; /* zlib's uLongf defined as unsigned long FAR */ if (olen > ULONG_MAX) return -1; out_size = (uLongf)olen; if (uncompress(out, &out_size, in, ilen) != Z_OK) return -1; if (out_size > OSSL_SSIZE_MAX) return -1; return (ossl_ssize_t)out_size; } static COMP_METHOD zlib_oneshot_method = { NID_zlib_compression, LN_zlib_compression, zlib_oneshot_init, zlib_oneshot_finish, zlib_oneshot_compress_block, zlib_oneshot_expand_block }; static CRYPTO_ONCE zlib_once = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_comp_zlib_init) { # ifdef ZLIB_SHARED /* LIBZ may be externally defined, and we should respect that value */ # ifndef LIBZ # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # define LIBZ "ZLIB1" # elif defined(OPENSSL_SYS_VMS) # define LIBZ "LIBZ" # else # define LIBZ "z" # endif # endif zlib_dso = DSO_load(NULL, LIBZ, NULL, 0); if (zlib_dso != NULL) { p_compress = (compress_ft) DSO_bind_func(zlib_dso, "compress"); p_uncompress = (compress_ft) DSO_bind_func(zlib_dso, "uncompress"); p_inflateEnd = (inflateEnd_ft) DSO_bind_func(zlib_dso, "inflateEnd"); p_inflate = (inflate_ft) DSO_bind_func(zlib_dso, "inflate"); p_inflateInit_ = (inflateInit__ft) DSO_bind_func(zlib_dso, "inflateInit_"); p_deflateEnd = (deflateEnd_ft) DSO_bind_func(zlib_dso, "deflateEnd"); p_deflate = (deflate_ft) DSO_bind_func(zlib_dso, "deflate"); p_deflateInit_ = (deflateInit__ft) DSO_bind_func(zlib_dso, "deflateInit_"); p_zError = (zError__ft) DSO_bind_func(zlib_dso, "zError"); if (p_compress == NULL || p_uncompress == NULL || p_inflateEnd == NULL || p_inflate == NULL || p_inflateInit_ == NULL || p_deflateEnd == NULL || p_deflate == NULL || p_deflateInit_ == NULL || p_zError == NULL) { ossl_comp_zlib_cleanup(); return 0; } } # endif return 1; } #endif COMP_METHOD *COMP_zlib(void) { COMP_METHOD *meth = NULL; #ifndef OPENSSL_NO_ZLIB if (RUN_ONCE(&zlib_once, ossl_comp_zlib_init)) meth = &zlib_stateful_method; #endif return meth; } COMP_METHOD *COMP_zlib_oneshot(void) { COMP_METHOD *meth = NULL; #ifndef OPENSSL_NO_ZLIB if (RUN_ONCE(&zlib_once, ossl_comp_zlib_init)) meth = &zlib_oneshot_method; #endif return meth; } /* Also called from OPENSSL_cleanup() */ void ossl_comp_zlib_cleanup(void) { #ifdef ZLIB_SHARED DSO_free(zlib_dso); zlib_dso = NULL; #endif } #ifndef OPENSSL_NO_ZLIB /* Zlib based compression/decompression filter BIO */ typedef struct { unsigned char *ibuf; /* Input buffer */ int ibufsize; /* Buffer size */ z_stream zin; /* Input decompress context */ unsigned char *obuf; /* Output buffer */ int obufsize; /* Output buffer size */ unsigned char *optr; /* Position in output buffer */ int ocount; /* Amount of data in output buffer */ int odone; /* deflate EOF */ int comp_level; /* Compression level to use */ z_stream zout; /* Output compression context */ } BIO_ZLIB_CTX; # define ZLIB_DEFAULT_BUFSIZE 1024 static int bio_zlib_new(BIO *bi); static int bio_zlib_free(BIO *bi); static int bio_zlib_read(BIO *b, char *out, int outl); static int bio_zlib_write(BIO *b, const char *in, int inl); static long bio_zlib_ctrl(BIO *b, int cmd, long num, void *ptr); static long bio_zlib_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp); static const BIO_METHOD bio_meth_zlib = { BIO_TYPE_COMP, "zlib", bwrite_conv, bio_zlib_write, bread_conv, bio_zlib_read, NULL, /* bio_zlib_puts, */ NULL, /* bio_zlib_gets, */ bio_zlib_ctrl, bio_zlib_new, bio_zlib_free, bio_zlib_callback_ctrl }; #endif const BIO_METHOD *BIO_f_zlib(void) { #ifndef OPENSSL_NO_ZLIB if (RUN_ONCE(&zlib_once, ossl_comp_zlib_init)) return &bio_meth_zlib; #endif return NULL; } #ifndef OPENSSL_NO_ZLIB static int bio_zlib_new(BIO *bi) { BIO_ZLIB_CTX *ctx; # ifdef ZLIB_SHARED if (!RUN_ONCE(&zlib_once, ossl_comp_zlib_init)) { ERR_raise(ERR_LIB_COMP, COMP_R_ZLIB_NOT_SUPPORTED); return 0; } # endif ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) return 0; ctx->ibufsize = ZLIB_DEFAULT_BUFSIZE; ctx->obufsize = ZLIB_DEFAULT_BUFSIZE; ctx->zin.zalloc = Z_NULL; ctx->zin.zfree = Z_NULL; ctx->zout.zalloc = Z_NULL; ctx->zout.zfree = Z_NULL; ctx->comp_level = Z_DEFAULT_COMPRESSION; BIO_set_init(bi, 1); BIO_set_data(bi, ctx); return 1; } static int bio_zlib_free(BIO *bi) { BIO_ZLIB_CTX *ctx; if (!bi) return 0; ctx = BIO_get_data(bi); if (ctx->ibuf) { /* Destroy decompress context */ inflateEnd(&ctx->zin); OPENSSL_free(ctx->ibuf); } if (ctx->obuf) { /* Destroy compress context */ deflateEnd(&ctx->zout); OPENSSL_free(ctx->obuf); } OPENSSL_free(ctx); BIO_set_data(bi, NULL); BIO_set_init(bi, 0); return 1; } static int bio_zlib_read(BIO *b, char *out, int outl) { BIO_ZLIB_CTX *ctx; int ret; z_stream *zin; BIO *next = BIO_next(b); if (!out || !outl) return 0; ctx = BIO_get_data(b); zin = &ctx->zin; BIO_clear_retry_flags(b); if (!ctx->ibuf) { ctx->ibuf = OPENSSL_malloc(ctx->ibufsize); if (ctx->ibuf == NULL) return 0; if ((ret = inflateInit(zin)) != Z_OK) { ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_INFLATE_ERROR, "zlib error: %s", zError(ret)); return 0; } zin->next_in = ctx->ibuf; zin->avail_in = 0; } /* Copy output data directly to supplied buffer */ zin->next_out = (unsigned char *)out; zin->avail_out = (unsigned int)outl; for (;;) { /* Decompress while data available */ while (zin->avail_in) { ret = inflate(zin, 0); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_INFLATE_ERROR, "zlib error: %s", zError(ret)); return 0; } /* If EOF or we've read everything then return */ if ((ret == Z_STREAM_END) || !zin->avail_out) return outl - zin->avail_out; } /* * No data in input buffer try to read some in, if an error then * return the total data read. */ ret = BIO_read(next, ctx->ibuf, ctx->ibufsize); if (ret <= 0) { /* Total data read */ int tot = outl - zin->avail_out; BIO_copy_next_retry(b); if (ret < 0) return (tot > 0) ? tot : ret; return tot; } zin->avail_in = ret; zin->next_in = ctx->ibuf; } } static int bio_zlib_write(BIO *b, const char *in, int inl) { BIO_ZLIB_CTX *ctx; int ret; z_stream *zout; BIO *next = BIO_next(b); if (!in || !inl) return 0; ctx = BIO_get_data(b); if (ctx->odone) return 0; zout = &ctx->zout; BIO_clear_retry_flags(b); if (!ctx->obuf) { ctx->obuf = OPENSSL_malloc(ctx->obufsize); /* Need error here */ if (ctx->obuf == NULL) return 0; ctx->optr = ctx->obuf; ctx->ocount = 0; if ((ret = deflateInit(zout, ctx->comp_level)) != Z_OK) { ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_DEFLATE_ERROR, "zlib error: %s", zError(ret)); return 0; } zout->next_out = ctx->obuf; zout->avail_out = ctx->obufsize; } /* Obtain input data directly from supplied buffer */ zout->next_in = (void *)in; zout->avail_in = inl; for (;;) { /* If data in output buffer write it first */ while (ctx->ocount) { ret = BIO_write(next, ctx->optr, ctx->ocount); if (ret <= 0) { /* Total data written */ int tot = inl - zout->avail_in; BIO_copy_next_retry(b); if (ret < 0) return (tot > 0) ? tot : ret; return tot; } ctx->optr += ret; ctx->ocount -= ret; } /* Have we consumed all supplied data? */ if (!zout->avail_in) return inl; /* Compress some more */ /* Reset buffer */ ctx->optr = ctx->obuf; zout->next_out = ctx->obuf; zout->avail_out = ctx->obufsize; /* Compress some more */ ret = deflate(zout, 0); if (ret != Z_OK) { ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_DEFLATE_ERROR, "zlib error: %s", zError(ret)); return 0; } ctx->ocount = ctx->obufsize - zout->avail_out; } } static int bio_zlib_flush(BIO *b) { BIO_ZLIB_CTX *ctx; int ret; z_stream *zout; BIO *next = BIO_next(b); ctx = BIO_get_data(b); /* If no data written or already flush show success */ if (!ctx->obuf || (ctx->odone && !ctx->ocount)) return 1; zout = &ctx->zout; BIO_clear_retry_flags(b); /* No more input data */ zout->next_in = NULL; zout->avail_in = 0; for (;;) { /* If data in output buffer write it first */ while (ctx->ocount) { ret = BIO_write(next, ctx->optr, ctx->ocount); if (ret <= 0) { BIO_copy_next_retry(b); return ret; } ctx->optr += ret; ctx->ocount -= ret; } if (ctx->odone) return 1; /* Compress some more */ /* Reset buffer */ ctx->optr = ctx->obuf; zout->next_out = ctx->obuf; zout->avail_out = ctx->obufsize; /* Compress some more */ ret = deflate(zout, Z_FINISH); if (ret == Z_STREAM_END) ctx->odone = 1; else if (ret != Z_OK) { ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_DEFLATE_ERROR, "zlib error: %s", zError(ret)); return 0; } ctx->ocount = ctx->obufsize - zout->avail_out; } } static long bio_zlib_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO_ZLIB_CTX *ctx; int ret, *ip; int ibs, obs; BIO *next = BIO_next(b); if (next == NULL) return 0; ctx = BIO_get_data(b); switch (cmd) { case BIO_CTRL_RESET: ctx->ocount = 0; ctx->odone = 0; ret = 1; break; case BIO_CTRL_FLUSH: ret = bio_zlib_flush(b); if (ret > 0) { ret = BIO_flush(next); BIO_copy_next_retry(b); } break; case BIO_C_SET_BUFF_SIZE: ibs = -1; obs = -1; if (ptr != NULL) { ip = ptr; if (*ip == 0) ibs = (int)num; else obs = (int)num; } else { ibs = (int)num; obs = ibs; } if (ibs != -1) { OPENSSL_free(ctx->ibuf); ctx->ibuf = NULL; ctx->ibufsize = ibs; } if (obs != -1) { OPENSSL_free(ctx->obuf); ctx->obuf = NULL; ctx->obufsize = obs; } ret = 1; break; case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_WPENDING: if (ctx->obuf == NULL) return 0; if (ctx->odone) { ret = ctx->ocount; } else { ret = ctx->ocount; if (ret == 0) /* Unknown amount pending but we are not finished */ ret = 1; } if (ret == 0) ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_PENDING: ret = ctx->zin.avail_in; if (ret == 0) ret = BIO_ctrl(next, cmd, num, ptr); break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static long bio_zlib_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } #endif
./openssl/crypto/comp/comp_local.h
/* * Copyright 2015-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 */ struct comp_method_st { int type; /* NID for compression library */ const char *name; /* A text string to identify the library */ int (*init) (COMP_CTX *ctx); void (*finish) (COMP_CTX *ctx); ossl_ssize_t (*compress) (COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen); ossl_ssize_t (*expand) (COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen); }; struct comp_ctx_st { struct comp_method_st *meth; unsigned long compress_in; unsigned long compress_out; unsigned long expand_in; unsigned long expand_out; void* data; };
./openssl/crypto/asn1/a_utctm.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include "asn1_local.h" #include <openssl/asn1t.h> IMPLEMENT_ASN1_DUP_FUNCTION(ASN1_UTCTIME) /* This is the primary function used to parse ASN1_UTCTIME */ int ossl_asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d) { /* wrapper around ossl_asn1_time_to_tm */ if (d->type != V_ASN1_UTCTIME) return 0; return ossl_asn1_time_to_tm(tm, d); } int ASN1_UTCTIME_check(const ASN1_UTCTIME *d) { return ossl_asn1_utctime_to_tm(NULL, d); } /* Sets the string via simple copy without cleaning it up */ int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str) { ASN1_UTCTIME t; t.type = V_ASN1_UTCTIME; t.length = strlen(str); t.data = (unsigned char *)str; t.flags = 0; if (!ASN1_UTCTIME_check(&t)) return 0; if (s != NULL && !ASN1_STRING_copy(s, &t)) return 0; return 1; } ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t) { return ASN1_UTCTIME_adj(s, t, 0, 0); } ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t, int offset_day, long offset_sec) { struct tm *ts; struct tm data; ts = OPENSSL_gmtime(&t, &data); if (ts == NULL) return NULL; if (offset_day || offset_sec) { if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec)) return NULL; } return ossl_asn1_time_from_tm(s, ts, V_ASN1_UTCTIME); } int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t) { struct tm stm, ttm; int day, sec; if (!ossl_asn1_utctime_to_tm(&stm, s)) return -2; if (OPENSSL_gmtime(&t, &ttm) == NULL) return -2; if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm)) return -2; if (day > 0 || sec > 0) return 1; if (day < 0 || sec < 0) return -1; return 0; } int ASN1_UTCTIME_print(BIO *bp, const ASN1_UTCTIME *tm) { if (tm->type != V_ASN1_UTCTIME) return 0; return ASN1_TIME_print(bp, tm); }
./openssl/crypto/asn1/asn1_item_list.h
/* * 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 */ static ASN1_ITEM_EXP *asn1_item_list[] = { ASN1_ITEM_ref(ACCESS_DESCRIPTION), #ifndef OPENSSL_NO_RFC3779 ASN1_ITEM_ref(ASIdOrRange), ASN1_ITEM_ref(ASIdentifierChoice), ASN1_ITEM_ref(ASIdentifiers), #endif ASN1_ITEM_ref(ASN1_ANY), ASN1_ITEM_ref(ASN1_BIT_STRING), ASN1_ITEM_ref(ASN1_BMPSTRING), ASN1_ITEM_ref(ASN1_BOOLEAN), ASN1_ITEM_ref(ASN1_ENUMERATED), ASN1_ITEM_ref(ASN1_FBOOLEAN), ASN1_ITEM_ref(ASN1_GENERALIZEDTIME), ASN1_ITEM_ref(ASN1_GENERALSTRING), ASN1_ITEM_ref(ASN1_IA5STRING), ASN1_ITEM_ref(ASN1_INTEGER), ASN1_ITEM_ref(ASN1_NULL), ASN1_ITEM_ref(ASN1_OBJECT), ASN1_ITEM_ref(ASN1_OCTET_STRING_NDEF), ASN1_ITEM_ref(ASN1_OCTET_STRING), ASN1_ITEM_ref(ASN1_PRINTABLESTRING), ASN1_ITEM_ref(ASN1_PRINTABLE), ASN1_ITEM_ref(ASN1_SEQUENCE_ANY), ASN1_ITEM_ref(ASN1_SEQUENCE), ASN1_ITEM_ref(ASN1_SET_ANY), ASN1_ITEM_ref(ASN1_T61STRING), ASN1_ITEM_ref(ASN1_TBOOLEAN), ASN1_ITEM_ref(ASN1_TIME), ASN1_ITEM_ref(ASN1_UNIVERSALSTRING), ASN1_ITEM_ref(ASN1_UTCTIME), ASN1_ITEM_ref(ASN1_UTF8STRING), ASN1_ITEM_ref(ASN1_VISIBLESTRING), #ifndef OPENSSL_NO_RFC3779 ASN1_ITEM_ref(ASRange), #endif ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS), ASN1_ITEM_ref(AUTHORITY_KEYID), ASN1_ITEM_ref(BASIC_CONSTRAINTS), ASN1_ITEM_ref(BIGNUM), ASN1_ITEM_ref(CBIGNUM), ASN1_ITEM_ref(CERTIFICATEPOLICIES), #ifndef OPENSSL_NO_CMS ASN1_ITEM_ref(CMS_ContentInfo), ASN1_ITEM_ref(CMS_EnvelopedData), ASN1_ITEM_ref(CMS_ReceiptRequest), #endif ASN1_ITEM_ref(CRL_DIST_POINTS), #ifndef OPENSSL_NO_DH ASN1_ITEM_ref(DHparams), #endif ASN1_ITEM_ref(DIRECTORYSTRING), ASN1_ITEM_ref(DISPLAYTEXT), ASN1_ITEM_ref(DIST_POINT_NAME), ASN1_ITEM_ref(DIST_POINT), #ifndef OPENSSL_NO_EC # ifndef OPENSSL_NO_DEPRECATED_3_0 ASN1_ITEM_ref(ECPARAMETERS), ASN1_ITEM_ref(ECPKPARAMETERS), # endif #endif ASN1_ITEM_ref(EDIPARTYNAME), ASN1_ITEM_ref(EXTENDED_KEY_USAGE), ASN1_ITEM_ref(GENERAL_NAMES), ASN1_ITEM_ref(GENERAL_NAME), ASN1_ITEM_ref(GENERAL_SUBTREE), #ifndef OPENSSL_NO_RFC3779 ASN1_ITEM_ref(IPAddressChoice), ASN1_ITEM_ref(IPAddressFamily), ASN1_ITEM_ref(IPAddressOrRange), ASN1_ITEM_ref(IPAddressRange), #endif ASN1_ITEM_ref(ISSUING_DIST_POINT), #ifndef OPENSSL_NO_DEPRECATED_3_0 ASN1_ITEM_ref(LONG), #endif ASN1_ITEM_ref(NAME_CONSTRAINTS), ASN1_ITEM_ref(NETSCAPE_CERT_SEQUENCE), ASN1_ITEM_ref(NETSCAPE_SPKAC), ASN1_ITEM_ref(NETSCAPE_SPKI), ASN1_ITEM_ref(NOTICEREF), #ifndef OPENSSL_NO_OCSP ASN1_ITEM_ref(OCSP_BASICRESP), ASN1_ITEM_ref(OCSP_CERTID), ASN1_ITEM_ref(OCSP_CERTSTATUS), ASN1_ITEM_ref(OCSP_CRLID), ASN1_ITEM_ref(OCSP_ONEREQ), ASN1_ITEM_ref(OCSP_REQINFO), ASN1_ITEM_ref(OCSP_REQUEST), ASN1_ITEM_ref(OCSP_RESPBYTES), ASN1_ITEM_ref(OCSP_RESPDATA), ASN1_ITEM_ref(OCSP_RESPID), ASN1_ITEM_ref(OCSP_RESPONSE), ASN1_ITEM_ref(OCSP_REVOKEDINFO), ASN1_ITEM_ref(OCSP_SERVICELOC), ASN1_ITEM_ref(OCSP_SIGNATURE), ASN1_ITEM_ref(OCSP_SINGLERESP), #endif ASN1_ITEM_ref(OTHERNAME), ASN1_ITEM_ref(PBE2PARAM), ASN1_ITEM_ref(PBEPARAM), ASN1_ITEM_ref(PBKDF2PARAM), ASN1_ITEM_ref(PKCS12_AUTHSAFES), ASN1_ITEM_ref(PKCS12_BAGS), ASN1_ITEM_ref(PKCS12_MAC_DATA), ASN1_ITEM_ref(PKCS12_SAFEBAGS), ASN1_ITEM_ref(PKCS12_SAFEBAG), ASN1_ITEM_ref(PKCS12), ASN1_ITEM_ref(PKCS7_ATTR_SIGN), ASN1_ITEM_ref(PKCS7_ATTR_VERIFY), ASN1_ITEM_ref(PKCS7_DIGEST), ASN1_ITEM_ref(PKCS7_ENCRYPT), ASN1_ITEM_ref(PKCS7_ENC_CONTENT), ASN1_ITEM_ref(PKCS7_ENVELOPE), ASN1_ITEM_ref(PKCS7_ISSUER_AND_SERIAL), ASN1_ITEM_ref(PKCS7_RECIP_INFO), ASN1_ITEM_ref(PKCS7_SIGNED), ASN1_ITEM_ref(PKCS7_SIGNER_INFO), ASN1_ITEM_ref(PKCS7_SIGN_ENVELOPE), ASN1_ITEM_ref(PKCS7), ASN1_ITEM_ref(PKCS8_PRIV_KEY_INFO), ASN1_ITEM_ref(PKEY_USAGE_PERIOD), ASN1_ITEM_ref(POLICYINFO), ASN1_ITEM_ref(POLICYQUALINFO), ASN1_ITEM_ref(POLICY_CONSTRAINTS), ASN1_ITEM_ref(POLICY_MAPPINGS), ASN1_ITEM_ref(POLICY_MAPPING), ASN1_ITEM_ref(PROXY_CERT_INFO_EXTENSION), ASN1_ITEM_ref(PROXY_POLICY), #ifndef OPENSSL_NO_DEPRECATED_3_0 ASN1_ITEM_ref(RSAPrivateKey), ASN1_ITEM_ref(RSAPublicKey), ASN1_ITEM_ref(RSA_OAEP_PARAMS), ASN1_ITEM_ref(RSA_PSS_PARAMS), #endif #ifndef OPENSSL_NO_SCRYPT ASN1_ITEM_ref(SCRYPT_PARAMS), #endif ASN1_ITEM_ref(SXNETID), ASN1_ITEM_ref(SXNET), ASN1_ITEM_ref(ISSUER_SIGN_TOOL), ASN1_ITEM_ref(USERNOTICE), ASN1_ITEM_ref(X509_ALGORS), ASN1_ITEM_ref(X509_ALGOR), ASN1_ITEM_ref(X509_ATTRIBUTE), ASN1_ITEM_ref(X509_CERT_AUX), ASN1_ITEM_ref(X509_CINF), ASN1_ITEM_ref(X509_CRL_INFO), ASN1_ITEM_ref(X509_CRL), ASN1_ITEM_ref(X509_EXTENSIONS), ASN1_ITEM_ref(X509_EXTENSION), ASN1_ITEM_ref(X509_NAME_ENTRY), ASN1_ITEM_ref(X509_NAME), ASN1_ITEM_ref(X509_PUBKEY), ASN1_ITEM_ref(X509_REQ_INFO), ASN1_ITEM_ref(X509_REQ), ASN1_ITEM_ref(X509_REVOKED), ASN1_ITEM_ref(X509_SIG), ASN1_ITEM_ref(X509_VAL), ASN1_ITEM_ref(X509), #ifndef OPENSSL_NO_DEPRECATED_3_0 ASN1_ITEM_ref(ZLONG), #endif ASN1_ITEM_ref(INT32), ASN1_ITEM_ref(UINT32), ASN1_ITEM_ref(ZINT32), ASN1_ITEM_ref(ZUINT32), ASN1_ITEM_ref(INT64), ASN1_ITEM_ref(UINT64), ASN1_ITEM_ref(ZINT64), ASN1_ITEM_ref(ZUINT64), };
./openssl/crypto/asn1/a_i2d_fp.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/asn1.h> #ifndef NO_OLD_ASN1 # ifndef OPENSSL_NO_STDIO int ASN1_i2d_fp(i2d_of_void *i2d, FILE *out, const void *x) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, out, BIO_NOCLOSE); ret = ASN1_i2d_bio(i2d, b, x); BIO_free(b); return ret; } # endif int ASN1_i2d_bio(i2d_of_void *i2d, BIO *out, const void *x) { char *b; unsigned char *p; int i, j = 0, n, ret = 1; n = i2d(x, NULL); if (n <= 0) return 0; b = OPENSSL_malloc(n); if (b == NULL) return 0; p = (unsigned char *)b; i2d(x, &p); for (;;) { i = BIO_write(out, &(b[j]), n); if (i == n) break; if (i <= 0) { ret = 0; break; } j += i; n -= i; } OPENSSL_free(b); return ret; } #endif #ifndef OPENSSL_NO_STDIO int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, const void *x) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, out, BIO_NOCLOSE); ret = ASN1_item_i2d_bio(it, b, x); BIO_free(b); return ret; } #endif int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, const void *x) { unsigned char *b = NULL; int i, j = 0, n, ret = 1; n = ASN1_item_i2d(x, &b, it); if (b == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); return 0; } for (;;) { i = BIO_write(out, &(b[j]), n); if (i == n) break; if (i <= 0) { ret = 0; break; } j += i; n -= i; } OPENSSL_free(b); return ret; } BIO *ASN1_item_i2d_mem_bio(const ASN1_ITEM *it, const ASN1_VALUE *val) { BIO *res; if (it == NULL || val == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((res = BIO_new(BIO_s_mem())) == NULL) return NULL; if (ASN1_item_i2d_bio(it, res, val) <= 0) { BIO_free(res); res = NULL; } return res; }
./openssl/crypto/asn1/bio_ndef.c
/* * Copyright 2008-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/asn1t.h> #include <openssl/bio.h> #include <openssl/err.h> #include <stdio.h> /* Experimental NDEF ASN1 BIO support routines */ /* * The usage is quite simple, initialize an ASN1 structure, get a BIO from it * then any data written through the BIO will end up translated to * appropriate format on the fly. The data is streamed out and does *not* * need to be all held in memory at once. When the BIO is flushed the output * is finalized and any signatures etc written out. The BIO is a 'proper' * BIO and can handle non blocking I/O correctly. The usage is simple. The * implementation is *not*... */ /* BIO support data stored in the ASN1 BIO ex_arg */ typedef struct ndef_aux_st { /* ASN1 structure this BIO refers to */ ASN1_VALUE *val; const ASN1_ITEM *it; /* Top of the BIO chain */ BIO *ndef_bio; /* Output BIO */ BIO *out; /* Boundary where content is inserted */ unsigned char **boundary; /* DER buffer start */ unsigned char *derbuf; } NDEF_SUPPORT; static int ndef_prefix(BIO *b, unsigned char **pbuf, int *plen, void *parg); static int ndef_prefix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg); static int ndef_suffix(BIO *b, unsigned char **pbuf, int *plen, void *parg); static int ndef_suffix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg); /* * On success, the returned BIO owns the input BIO as part of its BIO chain. * On failure, NULL is returned and the input BIO is owned by the caller. * * Unfortunately cannot constify this due to CMS_stream() and PKCS7_stream() */ BIO *BIO_new_NDEF(BIO *out, ASN1_VALUE *val, const ASN1_ITEM *it) { NDEF_SUPPORT *ndef_aux = NULL; BIO *asn_bio = NULL; const ASN1_AUX *aux = it->funcs; ASN1_STREAM_ARG sarg; BIO *pop_bio = NULL; if (!aux || !aux->asn1_cb) { ERR_raise(ERR_LIB_ASN1, ASN1_R_STREAMING_NOT_SUPPORTED); return NULL; } ndef_aux = OPENSSL_zalloc(sizeof(*ndef_aux)); asn_bio = BIO_new(BIO_f_asn1()); if (ndef_aux == NULL || asn_bio == NULL) goto err; /* ASN1 bio needs to be next to output BIO */ out = BIO_push(asn_bio, out); if (out == NULL) goto err; pop_bio = asn_bio; if (BIO_asn1_set_prefix(asn_bio, ndef_prefix, ndef_prefix_free) <= 0 || BIO_asn1_set_suffix(asn_bio, ndef_suffix, ndef_suffix_free) <= 0 || BIO_ctrl(asn_bio, BIO_C_SET_EX_ARG, 0, ndef_aux) <= 0) goto err; /* * Now let the callback prepend any digest, cipher, etc., that the BIO's * ASN1 structure needs. */ sarg.out = out; sarg.ndef_bio = NULL; sarg.boundary = NULL; /* * The asn1_cb(), must not have mutated asn_bio on error, leaving it in the * middle of some partially built, but not returned BIO chain. */ if (aux->asn1_cb(ASN1_OP_STREAM_PRE, &val, it, &sarg) <= 0) { /* * ndef_aux is now owned by asn_bio so we must not free it in the err * clean up block */ ndef_aux = NULL; goto err; } /* * We must not fail now because the callback has prepended additional * BIOs to the chain */ ndef_aux->val = val; ndef_aux->it = it; ndef_aux->ndef_bio = sarg.ndef_bio; ndef_aux->boundary = sarg.boundary; ndef_aux->out = out; return sarg.ndef_bio; err: /* BIO_pop() is NULL safe */ (void)BIO_pop(pop_bio); BIO_free(asn_bio); OPENSSL_free(ndef_aux); return NULL; } static int ndef_prefix(BIO *b, unsigned char **pbuf, int *plen, void *parg) { NDEF_SUPPORT *ndef_aux; unsigned char *p; int derlen; if (parg == NULL) return 0; ndef_aux = *(NDEF_SUPPORT **)parg; derlen = ASN1_item_ndef_i2d(ndef_aux->val, NULL, ndef_aux->it); if (derlen < 0) return 0; if ((p = OPENSSL_malloc(derlen)) == NULL) return 0; ndef_aux->derbuf = p; *pbuf = p; ASN1_item_ndef_i2d(ndef_aux->val, &p, ndef_aux->it); if (*ndef_aux->boundary == NULL) return 0; *plen = *ndef_aux->boundary - *pbuf; return 1; } static int ndef_prefix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg) { NDEF_SUPPORT *ndef_aux; if (parg == NULL) return 0; ndef_aux = *(NDEF_SUPPORT **)parg; if (ndef_aux == NULL) return 0; OPENSSL_free(ndef_aux->derbuf); ndef_aux->derbuf = NULL; *pbuf = NULL; *plen = 0; return 1; } static int ndef_suffix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg) { NDEF_SUPPORT **pndef_aux = (NDEF_SUPPORT **)parg; if (!ndef_prefix_free(b, pbuf, plen, parg)) return 0; OPENSSL_free(*pndef_aux); *pndef_aux = NULL; return 1; } static int ndef_suffix(BIO *b, unsigned char **pbuf, int *plen, void *parg) { NDEF_SUPPORT *ndef_aux; unsigned char *p; int derlen; const ASN1_AUX *aux; ASN1_STREAM_ARG sarg; if (parg == NULL) return 0; ndef_aux = *(NDEF_SUPPORT **)parg; aux = ndef_aux->it->funcs; /* Finalize structures */ sarg.ndef_bio = ndef_aux->ndef_bio; sarg.out = ndef_aux->out; sarg.boundary = ndef_aux->boundary; if (aux->asn1_cb(ASN1_OP_STREAM_POST, &ndef_aux->val, ndef_aux->it, &sarg) <= 0) return 0; derlen = ASN1_item_ndef_i2d(ndef_aux->val, NULL, ndef_aux->it); if (derlen < 0) return 0; if ((p = OPENSSL_malloc(derlen)) == NULL) return 0; ndef_aux->derbuf = p; *pbuf = p; derlen = ASN1_item_ndef_i2d(ndef_aux->val, &p, ndef_aux->it); if (*ndef_aux->boundary == NULL) return 0; *pbuf = *ndef_aux->boundary; *plen = derlen - (*ndef_aux->boundary - ndef_aux->derbuf); return 1; }
./openssl/crypto/asn1/t_pkey.c
/* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/buffer.h> #include "crypto/bn.h" /* Number of octets per line */ #define ASN1_BUF_PRINT_WIDTH 15 /* Maximum indent */ #define ASN1_PRINT_MAX_INDENT 128 int ASN1_buf_print(BIO *bp, const unsigned char *buf, size_t buflen, int indent) { size_t i; for (i = 0; i < buflen; i++) { if ((i % ASN1_BUF_PRINT_WIDTH) == 0) { if (i > 0 && BIO_puts(bp, "\n") <= 0) return 0; if (!BIO_indent(bp, indent, ASN1_PRINT_MAX_INDENT)) return 0; } /* * Use colon separators for each octet for compatibility as * this function is used to print out key components. */ if (BIO_printf(bp, "%02x%s", buf[i], (i == buflen - 1) ? "" : ":") <= 0) return 0; } if (BIO_write(bp, "\n", 1) <= 0) return 0; return 1; } int ASN1_bn_print(BIO *bp, const char *number, const BIGNUM *num, unsigned char *ign, int indent) { int n, rv = 0; const char *neg; unsigned char *buf = NULL, *tmp = NULL; int buflen; if (num == NULL) return 1; neg = BN_is_negative(num) ? "-" : ""; if (!BIO_indent(bp, indent, ASN1_PRINT_MAX_INDENT)) return 0; if (BN_is_zero(num)) { if (BIO_printf(bp, "%s 0\n", number) <= 0) return 0; return 1; } if (BN_num_bytes(num) <= BN_BYTES) { if (BIO_printf(bp, "%s %s%lu (%s0x%lx)\n", number, neg, (unsigned long)bn_get_words(num)[0], neg, (unsigned long)bn_get_words(num)[0]) <= 0) return 0; return 1; } buflen = BN_num_bytes(num) + 1; buf = tmp = OPENSSL_malloc(buflen); if (buf == NULL) goto err; buf[0] = 0; if (BIO_printf(bp, "%s%s\n", number, (neg[0] == '-') ? " (Negative)" : "") <= 0) goto err; n = BN_bn2bin(num, buf + 1); if (buf[1] & 0x80) n++; else tmp++; if (ASN1_buf_print(bp, tmp, n, indent + 4) == 0) goto err; rv = 1; err: OPENSSL_clear_free(buf, buflen); return rv; }
./openssl/crypto/asn1/a_mbstr.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 "crypto/ctype.h" #include "internal/cryptlib.h" #include "internal/unicode.h" #include <openssl/asn1.h> static int traverse_string(const unsigned char *p, int len, int inform, int (*rfunc) (unsigned long value, void *in), void *arg); static int in_utf8(unsigned long value, void *arg); static int out_utf8(unsigned long value, void *arg); static int type_str(unsigned long value, void *arg); static int cpy_asc(unsigned long value, void *arg); static int cpy_bmp(unsigned long value, void *arg); static int cpy_univ(unsigned long value, void *arg); static int cpy_utf8(unsigned long value, void *arg); /* * These functions take a string in UTF8, ASCII or multibyte form and a mask * of permissible ASN1 string types. It then works out the minimal type * (using the order Numeric < Printable < IA5 < T61 < BMP < Universal < UTF8) * and creates a string of the correct type with the supplied data. Yes this is * horrible: it has to be :-( The 'ncopy' form checks minimum and maximum * size limits too. */ int ASN1_mbstring_copy(ASN1_STRING **out, const unsigned char *in, int len, int inform, unsigned long mask) { return ASN1_mbstring_ncopy(out, in, len, inform, mask, 0, 0); } int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len, int inform, unsigned long mask, long minsize, long maxsize) { int str_type; int ret; char free_out; int outform, outlen = 0; ASN1_STRING *dest; unsigned char *p; int nchar; int (*cpyfunc) (unsigned long, void *) = NULL; if (len == -1) len = strlen((const char *)in); if (!mask) mask = DIRSTRING_TYPE; if (len < 0) return -1; /* First do a string check and work out the number of characters */ switch (inform) { case MBSTRING_BMP: if (len & 1) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_BMPSTRING_LENGTH); return -1; } nchar = len >> 1; break; case MBSTRING_UNIV: if (len & 3) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_UNIVERSALSTRING_LENGTH); return -1; } nchar = len >> 2; break; case MBSTRING_UTF8: nchar = 0; /* This counts the characters and does utf8 syntax checking */ ret = traverse_string(in, len, MBSTRING_UTF8, in_utf8, &nchar); if (ret < 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_UTF8STRING); return -1; } break; case MBSTRING_ASC: nchar = len; break; default: ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_FORMAT); return -1; } if ((minsize > 0) && (nchar < minsize)) { ERR_raise_data(ERR_LIB_ASN1, ASN1_R_STRING_TOO_SHORT, "minsize=%ld", minsize); return -1; } if ((maxsize > 0) && (nchar > maxsize)) { ERR_raise_data(ERR_LIB_ASN1, ASN1_R_STRING_TOO_LONG, "maxsize=%ld", maxsize); return -1; } /* Now work out minimal type (if any) */ if (traverse_string(in, len, inform, type_str, &mask) < 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_CHARACTERS); return -1; } /* Now work out output format and string type */ outform = MBSTRING_ASC; if (mask & B_ASN1_NUMERICSTRING) str_type = V_ASN1_NUMERICSTRING; else if (mask & B_ASN1_PRINTABLESTRING) str_type = V_ASN1_PRINTABLESTRING; else if (mask & B_ASN1_IA5STRING) str_type = V_ASN1_IA5STRING; else if (mask & B_ASN1_T61STRING) str_type = V_ASN1_T61STRING; else if (mask & B_ASN1_BMPSTRING) { str_type = V_ASN1_BMPSTRING; outform = MBSTRING_BMP; } else if (mask & B_ASN1_UNIVERSALSTRING) { str_type = V_ASN1_UNIVERSALSTRING; outform = MBSTRING_UNIV; } else { str_type = V_ASN1_UTF8STRING; outform = MBSTRING_UTF8; } if (!out) return str_type; if (*out) { free_out = 0; dest = *out; ASN1_STRING_set0(dest, NULL, 0); dest->type = str_type; } else { free_out = 1; dest = ASN1_STRING_type_new(str_type); if (dest == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); return -1; } *out = dest; } /* If both the same type just copy across */ if (inform == outform) { if (!ASN1_STRING_set(dest, in, len)) { if (free_out) { ASN1_STRING_free(dest); *out = NULL; } ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); return -1; } return str_type; } /* Work out how much space the destination will need */ switch (outform) { case MBSTRING_ASC: outlen = nchar; cpyfunc = cpy_asc; break; case MBSTRING_BMP: outlen = nchar << 1; cpyfunc = cpy_bmp; break; case MBSTRING_UNIV: outlen = nchar << 2; cpyfunc = cpy_univ; break; case MBSTRING_UTF8: outlen = 0; traverse_string(in, len, inform, out_utf8, &outlen); cpyfunc = cpy_utf8; break; } if ((p = OPENSSL_malloc(outlen + 1)) == NULL) { if (free_out) { ASN1_STRING_free(dest); *out = NULL; } return -1; } dest->length = outlen; dest->data = p; p[outlen] = 0; traverse_string(in, len, inform, cpyfunc, &p); return str_type; } /* * This function traverses a string and passes the value of each character to * an optional function along with a void * argument. */ static int traverse_string(const unsigned char *p, int len, int inform, int (*rfunc) (unsigned long value, void *in), void *arg) { unsigned long value; int ret; while (len) { if (inform == MBSTRING_ASC) { value = *p++; len--; } else if (inform == MBSTRING_BMP) { value = *p++ << 8; value |= *p++; len -= 2; } else if (inform == MBSTRING_UNIV) { value = ((unsigned long)*p++) << 24; value |= ((unsigned long)*p++) << 16; value |= *p++ << 8; value |= *p++; len -= 4; } else { ret = UTF8_getc(p, len, &value); if (ret < 0) return -1; len -= ret; p += ret; } if (rfunc) { ret = rfunc(value, arg); if (ret <= 0) return ret; } } return 1; } /* Various utility functions for traverse_string */ /* Just count number of characters */ static int in_utf8(unsigned long value, void *arg) { int *nchar; if (!is_unicode_valid(value)) return -2; nchar = arg; (*nchar)++; return 1; } /* Determine size of output as a UTF8 String */ static int out_utf8(unsigned long value, void *arg) { int *outlen, len; len = UTF8_putc(NULL, -1, value); if (len <= 0) return len; outlen = arg; *outlen += len; return 1; } /* * Determine the "type" of a string: check each character against a supplied * "mask". */ static int type_str(unsigned long value, void *arg) { unsigned long types = *((unsigned long *)arg); const int native = value > INT_MAX ? INT_MAX : ossl_fromascii(value); if ((types & B_ASN1_NUMERICSTRING) && !(ossl_isdigit(native) || native == ' ')) types &= ~B_ASN1_NUMERICSTRING; if ((types & B_ASN1_PRINTABLESTRING) && !ossl_isasn1print(native)) types &= ~B_ASN1_PRINTABLESTRING; if ((types & B_ASN1_IA5STRING) && !ossl_isascii(native)) types &= ~B_ASN1_IA5STRING; if ((types & B_ASN1_T61STRING) && (value > 0xff)) types &= ~B_ASN1_T61STRING; if ((types & B_ASN1_BMPSTRING) && (value > 0xffff)) types &= ~B_ASN1_BMPSTRING; if ((types & B_ASN1_UTF8STRING) && !is_unicode_valid(value)) types &= ~B_ASN1_UTF8STRING; if (!types) return -1; *((unsigned long *)arg) = types; return 1; } /* Copy one byte per character ASCII like strings */ static int cpy_asc(unsigned long value, void *arg) { unsigned char **p, *q; p = arg; q = *p; *q = (unsigned char)value; (*p)++; return 1; } /* Copy two byte per character BMPStrings */ static int cpy_bmp(unsigned long value, void *arg) { unsigned char **p, *q; p = arg; q = *p; *q++ = (unsigned char)((value >> 8) & 0xff); *q = (unsigned char)(value & 0xff); *p += 2; return 1; } /* Copy four byte per character UniversalStrings */ static int cpy_univ(unsigned long value, void *arg) { unsigned char **p, *q; p = arg; q = *p; *q++ = (unsigned char)((value >> 24) & 0xff); *q++ = (unsigned char)((value >> 16) & 0xff); *q++ = (unsigned char)((value >> 8) & 0xff); *q = (unsigned char)(value & 0xff); *p += 4; return 1; } /* Copy to a UTF8String */ static int cpy_utf8(unsigned long value, void *arg) { unsigned char **p; int ret; p = arg; /* We already know there is enough room so pass 0xff as the length */ ret = UTF8_putc(*p, 0xff, value); *p += ret; return 1; }
./openssl/crypto/asn1/p5_scrypt.c
/* * Copyright 2015-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/core_names.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/rand.h> #include "crypto/evp.h" #ifndef OPENSSL_NO_SCRYPT /* PKCS#5 scrypt password based encryption structures */ ASN1_SEQUENCE(SCRYPT_PARAMS) = { ASN1_SIMPLE(SCRYPT_PARAMS, salt, ASN1_OCTET_STRING), ASN1_SIMPLE(SCRYPT_PARAMS, costParameter, ASN1_INTEGER), ASN1_SIMPLE(SCRYPT_PARAMS, blockSize, ASN1_INTEGER), ASN1_SIMPLE(SCRYPT_PARAMS, parallelizationParameter, ASN1_INTEGER), ASN1_OPT(SCRYPT_PARAMS, keyLength, ASN1_INTEGER), } ASN1_SEQUENCE_END(SCRYPT_PARAMS) IMPLEMENT_ASN1_FUNCTIONS(SCRYPT_PARAMS) static X509_ALGOR *pkcs5_scrypt_set(const unsigned char *salt, size_t saltlen, size_t keylen, uint64_t N, uint64_t r, uint64_t p); /* * Return an algorithm identifier for a PKCS#5 v2.0 PBE algorithm using scrypt */ X509_ALGOR *PKCS5_pbe2_set_scrypt(const EVP_CIPHER *cipher, const unsigned char *salt, int saltlen, unsigned char *aiv, uint64_t N, uint64_t r, uint64_t p) { X509_ALGOR *scheme = NULL, *ret = NULL; int alg_nid; size_t keylen = 0; EVP_CIPHER_CTX *ctx = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; PBE2PARAM *pbe2 = NULL; if (!cipher) { ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_NULL_PARAMETER); goto err; } if (EVP_PBE_scrypt(NULL, 0, NULL, 0, N, r, p, 0, NULL, 0) == 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_SCRYPT_PARAMETERS); goto err; } alg_nid = EVP_CIPHER_get_type(cipher); if (alg_nid == NID_undef) { ERR_raise(ERR_LIB_ASN1, ASN1_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER); goto err; } pbe2 = PBE2PARAM_new(); if (pbe2 == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* Setup the AlgorithmIdentifier for the encryption scheme */ scheme = pbe2->encryption; scheme->algorithm = OBJ_nid2obj(alg_nid); scheme->parameter = ASN1_TYPE_new(); if (scheme->parameter == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* Create random IV */ if (EVP_CIPHER_get_iv_length(cipher)) { if (aiv) memcpy(iv, aiv, EVP_CIPHER_get_iv_length(cipher)); else if (RAND_bytes(iv, EVP_CIPHER_get_iv_length(cipher)) <= 0) goto err; } ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB); goto err; } /* Dummy cipherinit to just setup the IV */ if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, iv, 0) == 0) goto err; if (EVP_CIPHER_param_to_asn1(ctx, scheme->parameter) <= 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ERROR_SETTING_CIPHER_PARAMS); goto err; } EVP_CIPHER_CTX_free(ctx); ctx = NULL; /* If its RC2 then we'd better setup the key length */ if (alg_nid == NID_rc2_cbc) keylen = EVP_CIPHER_get_key_length(cipher); /* Setup keyfunc */ X509_ALGOR_free(pbe2->keyfunc); pbe2->keyfunc = pkcs5_scrypt_set(salt, saltlen, keylen, N, r, p); if (pbe2->keyfunc == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* Now set up top level AlgorithmIdentifier */ ret = X509_ALGOR_new(); if (ret == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } ret->algorithm = OBJ_nid2obj(NID_pbes2); /* Encode PBE2PARAM into parameter */ if (ASN1_TYPE_pack_sequence(ASN1_ITEM_rptr(PBE2PARAM), pbe2, &ret->parameter) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } PBE2PARAM_free(pbe2); pbe2 = NULL; return ret; err: PBE2PARAM_free(pbe2); X509_ALGOR_free(ret); EVP_CIPHER_CTX_free(ctx); return NULL; } static X509_ALGOR *pkcs5_scrypt_set(const unsigned char *salt, size_t saltlen, size_t keylen, uint64_t N, uint64_t r, uint64_t p) { X509_ALGOR *keyfunc = NULL; SCRYPT_PARAMS *sparam = SCRYPT_PARAMS_new(); if (sparam == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (!saltlen) saltlen = PKCS5_DEFAULT_PBE2_SALT_LEN; /* This will either copy salt or grow the buffer */ if (ASN1_STRING_set(sparam->salt, salt, saltlen) == 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (salt == NULL && RAND_bytes(sparam->salt->data, saltlen) <= 0) goto err; if (ASN1_INTEGER_set_uint64(sparam->costParameter, N) == 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (ASN1_INTEGER_set_uint64(sparam->blockSize, r) == 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (ASN1_INTEGER_set_uint64(sparam->parallelizationParameter, p) == 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* If have a key len set it up */ if (keylen > 0) { sparam->keyLength = ASN1_INTEGER_new(); if (sparam->keyLength == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (ASN1_INTEGER_set_int64(sparam->keyLength, keylen) == 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } } /* Finally setup the keyfunc structure */ keyfunc = X509_ALGOR_new(); if (keyfunc == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } keyfunc->algorithm = OBJ_nid2obj(NID_id_scrypt); /* Encode SCRYPT_PARAMS into parameter of pbe2 */ if (ASN1_TYPE_pack_sequence(ASN1_ITEM_rptr(SCRYPT_PARAMS), sparam, &keyfunc->parameter) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } SCRYPT_PARAMS_free(sparam); return keyfunc; err: SCRYPT_PARAMS_free(sparam); X509_ALGOR_free(keyfunc); return NULL; } int PKCS5_v2_scrypt_keyivgen_ex(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *c, const EVP_MD *md, int en_de, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char *salt, key[EVP_MAX_KEY_LENGTH]; uint64_t p, r, N; size_t saltlen; size_t keylen = 0; int t, rv = 0; SCRYPT_PARAMS *sparam = NULL; if (EVP_CIPHER_CTX_get0_cipher(ctx) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET); goto err; } /* Decode parameter */ sparam = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(SCRYPT_PARAMS), param); if (sparam == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_DECODE_ERROR); goto err; } t = EVP_CIPHER_CTX_get_key_length(ctx); if (t < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); goto err; } keylen = t; /* Now check the parameters of sparam */ if (sparam->keyLength) { uint64_t spkeylen; if ((ASN1_INTEGER_get_uint64(&spkeylen, sparam->keyLength) == 0) || (spkeylen != keylen)) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEYLENGTH); goto err; } } /* Check all parameters fit in uint64_t and are acceptable to scrypt */ if (ASN1_INTEGER_get_uint64(&N, sparam->costParameter) == 0 || ASN1_INTEGER_get_uint64(&r, sparam->blockSize) == 0 || ASN1_INTEGER_get_uint64(&p, sparam->parallelizationParameter) == 0 || EVP_PBE_scrypt_ex(NULL, 0, NULL, 0, N, r, p, 0, NULL, 0, libctx, propq) == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_ILLEGAL_SCRYPT_PARAMETERS); goto err; } /* it seems that its all OK */ salt = sparam->salt->data; saltlen = sparam->salt->length; if (EVP_PBE_scrypt_ex(pass, passlen, salt, saltlen, N, r, p, 0, key, keylen, libctx, propq) == 0) goto err; rv = EVP_CipherInit_ex(ctx, NULL, NULL, key, NULL, en_de); err: if (keylen) OPENSSL_cleanse(key, keylen); SCRYPT_PARAMS_free(sparam); return rv; } int PKCS5_v2_scrypt_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *c, const EVP_MD *md, int en_de) { return PKCS5_v2_scrypt_keyivgen_ex(ctx, pass, passlen, param, c, md, en_de, NULL, NULL); } #endif /* OPENSSL_NO_SCRYPT */
./openssl/crypto/asn1/d2i_param.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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/asn1.h> #include "internal/asn1.h" #include "crypto/asn1.h" #include "crypto/evp.h" EVP_PKEY *d2i_KeyParams(int type, EVP_PKEY **a, const unsigned char **pp, long length) { EVP_PKEY *ret = NULL; if ((a == NULL) || (*a == NULL)) { if ((ret = EVP_PKEY_new()) == NULL) return NULL; } else ret = *a; if (type != EVP_PKEY_get_id(ret) && !EVP_PKEY_set_type(ret, type)) goto err; if (ret->ameth == NULL || ret->ameth->param_decode == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_TYPE); goto err; } if (!ret->ameth->param_decode(ret, pp, length)) goto err; if (a != NULL) (*a) = ret; return ret; err: if (a == NULL || *a != ret) EVP_PKEY_free(ret); return NULL; } EVP_PKEY *d2i_KeyParams_bio(int type, EVP_PKEY **a, BIO *in) { BUF_MEM *b = NULL; const unsigned char *p; void *ret = NULL; int len; len = asn1_d2i_read_bio(in, &b); if (len < 0) goto err; p = (unsigned char *)b->data; ret = d2i_KeyParams(type, a, &p, len); err: BUF_MEM_free(b); return ret; }
./openssl/crypto/asn1/x_pkey.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/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> X509_PKEY *X509_PKEY_new(void) { X509_PKEY *ret = NULL; ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->enc_algor = X509_ALGOR_new(); ret->enc_pkey = ASN1_OCTET_STRING_new(); if (ret->enc_algor == NULL || ret->enc_pkey == NULL) { X509_PKEY_free(ret); ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); return NULL; } return ret; } void X509_PKEY_free(X509_PKEY *x) { if (x == NULL) return; X509_ALGOR_free(x->enc_algor); ASN1_OCTET_STRING_free(x->enc_pkey); EVP_PKEY_free(x->dec_pkey); if (x->key_free) OPENSSL_free(x->key_data); OPENSSL_free(x); }
./openssl/crypto/asn1/d2i_pr.c
/* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/decoder.h> #include <openssl/engine.h> #include <openssl/x509.h> #include <openssl/asn1.h> #include "crypto/asn1.h" #include "crypto/evp.h" #include "internal/asn1.h" #include "internal/sizes.h" static EVP_PKEY * d2i_PrivateKey_decoder(int keytype, EVP_PKEY **a, const unsigned char **pp, long length, OSSL_LIB_CTX *libctx, const char *propq) { OSSL_DECODER_CTX *dctx = NULL; size_t len = length; EVP_PKEY *pkey = NULL, *bak_a = NULL; EVP_PKEY **ppkey = &pkey; const char *key_name = NULL; char keytypebuf[OSSL_MAX_NAME_SIZE]; int ret; const unsigned char *p = *pp; const char *structure; PKCS8_PRIV_KEY_INFO *p8info; const ASN1_OBJECT *algoid; if (keytype != EVP_PKEY_NONE) { key_name = evp_pkey_type2name(keytype); if (key_name == NULL) return NULL; } /* This is just a probe. It might fail, so we ignore errors */ ERR_set_mark(); p8info = d2i_PKCS8_PRIV_KEY_INFO(NULL, pp, len); ERR_pop_to_mark(); if (p8info != NULL) { if (key_name == NULL && PKCS8_pkey_get0(&algoid, NULL, NULL, NULL, p8info) && OBJ_obj2txt(keytypebuf, sizeof(keytypebuf), algoid, 0)) key_name = keytypebuf; structure = "PrivateKeyInfo"; PKCS8_PRIV_KEY_INFO_free(p8info); } else { structure = "type-specific"; } *pp = p; if (a != NULL && (bak_a = *a) != NULL) ppkey = a; dctx = OSSL_DECODER_CTX_new_for_pkey(ppkey, "DER", structure, key_name, EVP_PKEY_KEYPAIR, libctx, propq); if (a != NULL) *a = bak_a; if (dctx == NULL) goto err; ret = OSSL_DECODER_from_data(dctx, pp, &len); OSSL_DECODER_CTX_free(dctx); if (ret && *ppkey != NULL && evp_keymgmt_util_has(*ppkey, OSSL_KEYMGMT_SELECT_PRIVATE_KEY)) { if (a != NULL) *a = *ppkey; return *ppkey; } err: if (ppkey != a) EVP_PKEY_free(*ppkey); return NULL; } EVP_PKEY * ossl_d2i_PrivateKey_legacy(int keytype, EVP_PKEY **a, const unsigned char **pp, long length, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *ret; const unsigned char *p = *pp; if (a == NULL || *a == NULL) { if ((ret = EVP_PKEY_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB); return NULL; } } else { ret = *a; #ifndef OPENSSL_NO_ENGINE ENGINE_finish(ret->engine); ret->engine = NULL; #endif } if (!EVP_PKEY_set_type(ret, keytype)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE); goto err; } ERR_set_mark(); if (!ret->ameth->old_priv_decode || !ret->ameth->old_priv_decode(ret, &p, length)) { if (ret->ameth->priv_decode != NULL || ret->ameth->priv_decode_ex != NULL) { EVP_PKEY *tmp; PKCS8_PRIV_KEY_INFO *p8 = NULL; p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, length); if (p8 == NULL) { ERR_clear_last_mark(); goto err; } tmp = evp_pkcs82pkey_legacy(p8, libctx, propq); PKCS8_PRIV_KEY_INFO_free(p8); if (tmp == NULL) { ERR_clear_last_mark(); goto err; } EVP_PKEY_free(ret); ret = tmp; ERR_pop_to_mark(); if (EVP_PKEY_type(keytype) != EVP_PKEY_get_base_id(ret)) goto err; } else { ERR_clear_last_mark(); ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } } else { ERR_clear_last_mark(); } *pp = p; if (a != NULL) *a = ret; return ret; err: if (a == NULL || *a != ret) EVP_PKEY_free(ret); return NULL; } EVP_PKEY *d2i_PrivateKey_ex(int keytype, EVP_PKEY **a, const unsigned char **pp, long length, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *ret; ret = d2i_PrivateKey_decoder(keytype, a, pp, length, libctx, propq); /* try the legacy path if the decoder failed */ if (ret == NULL) ret = ossl_d2i_PrivateKey_legacy(keytype, a, pp, length, libctx, propq); return ret; } EVP_PKEY *d2i_PrivateKey(int type, EVP_PKEY **a, const unsigned char **pp, long length) { return d2i_PrivateKey_ex(type, a, pp, length, NULL, NULL); } static EVP_PKEY *d2i_AutoPrivateKey_legacy(EVP_PKEY **a, const unsigned char **pp, long length, OSSL_LIB_CTX *libctx, const char *propq) { STACK_OF(ASN1_TYPE) *inkey; const unsigned char *p; int keytype; p = *pp; /* * Dirty trick: read in the ASN1 data into a STACK_OF(ASN1_TYPE): by * analyzing it we can determine the passed structure: this assumes the * input is surrounded by an ASN1 SEQUENCE. */ inkey = d2i_ASN1_SEQUENCE_ANY(NULL, &p, length); p = *pp; /* * Since we only need to discern "traditional format" RSA and DSA keys we * can just count the elements. */ if (sk_ASN1_TYPE_num(inkey) == 6) { keytype = EVP_PKEY_DSA; } else if (sk_ASN1_TYPE_num(inkey) == 4) { keytype = EVP_PKEY_EC; } else if (sk_ASN1_TYPE_num(inkey) == 3) { /* This seems to be PKCS8, not * traditional format */ PKCS8_PRIV_KEY_INFO *p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, length); EVP_PKEY *ret; sk_ASN1_TYPE_pop_free(inkey, ASN1_TYPE_free); if (p8 == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE); return NULL; } ret = evp_pkcs82pkey_legacy(p8, libctx, propq); PKCS8_PRIV_KEY_INFO_free(p8); if (ret == NULL) return NULL; *pp = p; if (a != NULL) { *a = ret; } return ret; } else { keytype = EVP_PKEY_RSA; } sk_ASN1_TYPE_pop_free(inkey, ASN1_TYPE_free); return ossl_d2i_PrivateKey_legacy(keytype, a, pp, length, libctx, propq); } /* * This works like d2i_PrivateKey() except it passes the keytype as * EVP_PKEY_NONE, which then figures out the type during decoding. */ EVP_PKEY *d2i_AutoPrivateKey_ex(EVP_PKEY **a, const unsigned char **pp, long length, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *ret; ret = d2i_PrivateKey_decoder(EVP_PKEY_NONE, a, pp, length, libctx, propq); /* try the legacy path if the decoder failed */ if (ret == NULL) ret = d2i_AutoPrivateKey_legacy(a, pp, length, libctx, propq); return ret; } EVP_PKEY *d2i_AutoPrivateKey(EVP_PKEY **a, const unsigned char **pp, long length) { return d2i_AutoPrivateKey_ex(a, pp, length, NULL, NULL); }
./openssl/crypto/asn1/n_pkey.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 <openssl/opensslconf.h> #include "internal/cryptlib.h" #include <stdio.h> #include <openssl/rsa.h> #include <openssl/objects.h> #include <openssl/asn1t.h> #include <openssl/evp.h> #include <openssl/x509.h> #define ASN1_BROKEN_SEQUENCE(tname) \ static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_BROKEN, 0, 0, 0, 0}; \ ASN1_SEQUENCE(tname) #define static_ASN1_BROKEN_SEQUENCE_END(stname) \ static_ASN1_SEQUENCE_END_ref(stname, stname) typedef struct netscape_pkey_st { int32_t version; X509_ALGOR *algor; ASN1_OCTET_STRING *private_key; } NETSCAPE_PKEY; typedef struct netscape_encrypted_pkey_st { ASN1_OCTET_STRING *os; /* * This is the same structure as DigestInfo so use it: although this * isn't really anything to do with digests. */ X509_SIG *enckey; } NETSCAPE_ENCRYPTED_PKEY; ASN1_BROKEN_SEQUENCE(NETSCAPE_ENCRYPTED_PKEY) = { ASN1_SIMPLE(NETSCAPE_ENCRYPTED_PKEY, os, ASN1_OCTET_STRING), ASN1_SIMPLE(NETSCAPE_ENCRYPTED_PKEY, enckey, X509_SIG) } static_ASN1_BROKEN_SEQUENCE_END(NETSCAPE_ENCRYPTED_PKEY) DECLARE_ASN1_FUNCTIONS(NETSCAPE_ENCRYPTED_PKEY) DECLARE_ASN1_ENCODE_FUNCTIONS_name(NETSCAPE_ENCRYPTED_PKEY, NETSCAPE_ENCRYPTED_PKEY) IMPLEMENT_ASN1_FUNCTIONS(NETSCAPE_ENCRYPTED_PKEY) ASN1_SEQUENCE(NETSCAPE_PKEY) = { ASN1_EMBED(NETSCAPE_PKEY, version, INT32), ASN1_SIMPLE(NETSCAPE_PKEY, algor, X509_ALGOR), ASN1_SIMPLE(NETSCAPE_PKEY, private_key, ASN1_OCTET_STRING) } static_ASN1_SEQUENCE_END(NETSCAPE_PKEY) DECLARE_ASN1_FUNCTIONS(NETSCAPE_PKEY) DECLARE_ASN1_ENCODE_FUNCTIONS_name(NETSCAPE_PKEY, NETSCAPE_PKEY) IMPLEMENT_ASN1_FUNCTIONS(NETSCAPE_PKEY)
./openssl/crypto/asn1/a_object.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 <limits.h> #include "crypto/ctype.h" #include "internal/cryptlib.h" #include <openssl/buffer.h> #include <openssl/asn1.h> #include <openssl/objects.h> #include <openssl/bn.h> #include "crypto/asn1.h" #include "asn1_local.h" int i2d_ASN1_OBJECT(const ASN1_OBJECT *a, unsigned char **pp) { unsigned char *p, *allocated = NULL; int objsize; if ((a == NULL) || (a->data == NULL)) return 0; objsize = ASN1_object_size(0, a->length, V_ASN1_OBJECT); if (pp == NULL || objsize == -1) return objsize; if (*pp == NULL) { if ((p = allocated = OPENSSL_malloc(objsize)) == NULL) return 0; } else { p = *pp; } ASN1_put_object(&p, 0, a->length, V_ASN1_OBJECT, V_ASN1_UNIVERSAL); memcpy(p, a->data, a->length); /* * If a new buffer was allocated, just return it back. * If not, return the incremented buffer pointer. */ *pp = allocated != NULL ? allocated : p + a->length; return objsize; } int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num) { int i, first, len = 0, c, use_bn; char ftmp[24], *tmp = ftmp; int tmpsize = sizeof(ftmp); const char *p; unsigned long l; BIGNUM *bl = NULL; if (num == 0) return 0; else if (num == -1) num = strlen(buf); p = buf; c = *(p++); num--; if ((c >= '0') && (c <= '2')) { first = c - '0'; } else { ERR_raise(ERR_LIB_ASN1, ASN1_R_FIRST_NUM_TOO_LARGE); goto err; } if (num <= 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_MISSING_SECOND_NUMBER); goto err; } c = *(p++); num--; for (;;) { if (num <= 0) break; if ((c != '.') && (c != ' ')) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_SEPARATOR); goto err; } l = 0; use_bn = 0; for (;;) { if (num <= 0) break; num--; c = *(p++); if ((c == ' ') || (c == '.')) break; if (!ossl_isdigit(c)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_DIGIT); goto err; } if (!use_bn && l >= ((ULONG_MAX - 80) / 10L)) { use_bn = 1; if (bl == NULL) bl = BN_new(); if (bl == NULL || !BN_set_word(bl, l)) goto err; } if (use_bn) { if (!BN_mul_word(bl, 10L) || !BN_add_word(bl, c - '0')) goto err; } else l = l * 10L + (long)(c - '0'); } if (len == 0) { if ((first < 2) && (l >= 40)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_SECOND_NUMBER_TOO_LARGE); goto err; } if (use_bn) { if (!BN_add_word(bl, first * 40)) goto err; } else l += (long)first *40; } i = 0; if (use_bn) { int blsize; blsize = BN_num_bits(bl); blsize = (blsize + 6) / 7; if (blsize > tmpsize) { if (tmp != ftmp) OPENSSL_free(tmp); tmpsize = blsize + 32; tmp = OPENSSL_malloc(tmpsize); if (tmp == NULL) goto err; } while (blsize--) { BN_ULONG t = BN_div_word(bl, 0x80L); if (t == (BN_ULONG)-1) goto err; tmp[i++] = (unsigned char)t; } } else { for (;;) { tmp[i++] = (unsigned char)l & 0x7f; l >>= 7L; if (l == 0L) break; } } if (out != NULL) { if (len + i > olen) { ERR_raise(ERR_LIB_ASN1, ASN1_R_BUFFER_TOO_SMALL); goto err; } while (--i > 0) out[len++] = tmp[i] | 0x80; out[len++] = tmp[0]; } else len += i; } if (tmp != ftmp) OPENSSL_free(tmp); BN_free(bl); return len; err: if (tmp != ftmp) OPENSSL_free(tmp); BN_free(bl); return 0; } int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a) { return OBJ_obj2txt(buf, buf_len, a, 0); } int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a) { char buf[80], *p = buf; int i; if ((a == NULL) || (a->data == NULL)) return BIO_write(bp, "NULL", 4); i = i2t_ASN1_OBJECT(buf, sizeof(buf), a); if (i > (int)(sizeof(buf) - 1)) { if (i > INT_MAX - 1) { /* catch an integer overflow */ ERR_raise(ERR_LIB_ASN1, ASN1_R_LENGTH_TOO_LONG); return -1; } if ((p = OPENSSL_malloc(i + 1)) == NULL) return -1; i2t_ASN1_OBJECT(p, i + 1, a); } if (i <= 0) { i = BIO_write(bp, "<INVALID>", 9); i += BIO_dump(bp, (const char *)a->data, a->length); return i; } BIO_write(bp, p, i); if (p != buf) OPENSSL_free(p); return i; } ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp, long length) { const unsigned char *p; long len; int tag, xclass; int inf, i; ASN1_OBJECT *ret = NULL; p = *pp; inf = ASN1_get_object(&p, &len, &tag, &xclass, length); if (inf & 0x80) { i = ASN1_R_BAD_OBJECT_HEADER; goto err; } if (tag != V_ASN1_OBJECT) { i = ASN1_R_EXPECTING_AN_OBJECT; goto err; } ret = ossl_c2i_ASN1_OBJECT(a, &p, len); if (ret) *pp = p; return ret; err: ERR_raise(ERR_LIB_ASN1, i); return NULL; } ASN1_OBJECT *ossl_c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp, long len) { ASN1_OBJECT *ret = NULL, tobj; const unsigned char *p; unsigned char *data; int i, length; /* * Sanity check OID encoding. Need at least one content octet. MSB must * be clear in the last octet. can't have leading 0x80 in subidentifiers, * see: X.690 8.19.2 */ if (len <= 0 || len > INT_MAX || pp == NULL || (p = *pp) == NULL || p[len - 1] & 0x80) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_OBJECT_ENCODING); return NULL; } /* Now 0 < len <= INT_MAX, so the cast is safe. */ length = (int)len; /* * Try to lookup OID in table: these are all valid encodings so if we get * a match we know the OID is valid. */ tobj.nid = NID_undef; tobj.data = p; tobj.length = length; tobj.flags = 0; i = OBJ_obj2nid(&tobj); if (i != NID_undef) { /* * Return shared registered OID object: this improves efficiency * because we don't have to return a dynamically allocated OID * and NID lookups can use the cached value. */ ret = OBJ_nid2obj(i); if (a) { ASN1_OBJECT_free(*a); *a = ret; } *pp += len; return ret; } for (i = 0; i < length; i++, p++) { if (*p == 0x80 && (!i || !(p[-1] & 0x80))) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_OBJECT_ENCODING); return NULL; } } if ((a == NULL) || ((*a) == NULL) || !((*a)->flags & ASN1_OBJECT_FLAG_DYNAMIC)) { if ((ret = ASN1_OBJECT_new()) == NULL) return NULL; } else { ret = (*a); } p = *pp; /* detach data from object */ data = (unsigned char *)ret->data; ret->data = NULL; /* once detached we can change it */ if ((data == NULL) || (ret->length < length)) { ret->length = 0; OPENSSL_free(data); data = OPENSSL_malloc(length); if (data == NULL) goto err; ret->flags |= ASN1_OBJECT_FLAG_DYNAMIC_DATA; } memcpy(data, p, length); /* If there are dynamic strings, free them here, and clear the flag */ if ((ret->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) != 0) { OPENSSL_free((char *)ret->sn); OPENSSL_free((char *)ret->ln); ret->flags &= ~ASN1_OBJECT_FLAG_DYNAMIC_STRINGS; } /* reattach data to object, after which it remains const */ ret->data = data; ret->length = length; ret->sn = NULL; ret->ln = NULL; /* ret->flags=ASN1_OBJECT_FLAG_DYNAMIC; we know it is dynamic */ p += length; if (a != NULL) (*a) = ret; *pp = p; return ret; err: ERR_raise(ERR_LIB_ASN1, i); if ((a == NULL) || (*a != ret)) ASN1_OBJECT_free(ret); return NULL; } ASN1_OBJECT *ASN1_OBJECT_new(void) { ASN1_OBJECT *ret; ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->flags = ASN1_OBJECT_FLAG_DYNAMIC; return ret; } void ASN1_OBJECT_free(ASN1_OBJECT *a) { if (a == NULL) return; if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) { #ifndef CONST_STRICT /* * Disable purely for compile-time strict const checking. Doing this * on a "real" compile will cause memory leaks */ OPENSSL_free((void*)a->sn); OPENSSL_free((void*)a->ln); #endif a->sn = a->ln = NULL; } if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_DATA) { OPENSSL_free((void*)a->data); a->data = NULL; a->length = 0; } if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC) OPENSSL_free(a); } ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data, int len, const char *sn, const char *ln) { ASN1_OBJECT o; o.sn = sn; o.ln = ln; o.data = data; o.nid = nid; o.length = len; o.flags = ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS | ASN1_OBJECT_FLAG_DYNAMIC_DATA; return OBJ_dup(&o); }
./openssl/crypto/asn1/t_spki.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/x509.h> #include <openssl/asn1.h> #include <openssl/rsa.h> #include <openssl/dsa.h> #include <openssl/bn.h> /* Print out an SPKI */ int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki) { EVP_PKEY *pkey; ASN1_IA5STRING *chal; ASN1_OBJECT *spkioid; int i, n; char *s; BIO_printf(out, "Netscape SPKI:\n"); X509_PUBKEY_get0_param(&spkioid, NULL, NULL, NULL, spki->spkac->pubkey); i = OBJ_obj2nid(spkioid); BIO_printf(out, " Public Key Algorithm: %s\n", (i == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(i)); pkey = X509_PUBKEY_get(spki->spkac->pubkey); if (pkey == NULL) BIO_printf(out, " Unable to load public key\n"); else { EVP_PKEY_print_public(out, pkey, 4, NULL); EVP_PKEY_free(pkey); } chal = spki->spkac->challenge; if (chal->length) BIO_printf(out, " Challenge String: %.*s\n", chal->length, chal->data); i = OBJ_obj2nid(spki->sig_algor.algorithm); BIO_printf(out, " Signature Algorithm: %s", (i == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(i)); n = spki->signature->length; s = (char *)spki->signature->data; for (i = 0; i < n; i++) { if ((i % 18) == 0) BIO_write(out, "\n ", 7); BIO_printf(out, "%02x%s", (unsigned char)s[i], ((i + 1) == n) ? "" : ":"); } BIO_write(out, "\n", 1); return 1; }
./openssl/crypto/asn1/i2d_evp.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 */ /* * Low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/encoder.h> #include <openssl/buffer.h> #include <openssl/x509.h> #include <openssl/rsa.h> /* For i2d_RSAPublicKey */ #include <openssl/dsa.h> /* For i2d_DSAPublicKey */ #include <openssl/ec.h> /* For i2o_ECPublicKey */ #include "crypto/asn1.h" #include "crypto/evp.h" struct type_and_structure_st { const char *output_type; const char *output_structure; }; static int i2d_provided(const EVP_PKEY *a, int selection, const struct type_and_structure_st *output_info, unsigned char **pp) { int ret; for (ret = -1; ret == -1 && output_info->output_type != NULL; output_info++) { /* * The i2d_ calls don't take a boundary length for *pp. However, * OSSL_ENCODER_to_data() needs one, so we make one up. Because * OSSL_ENCODER_to_data() decrements this number by the amount of * bytes written, we need to calculate the length written further * down, when pp != NULL. */ size_t len = INT_MAX; int pp_was_NULL = (pp == NULL || *pp == NULL); OSSL_ENCODER_CTX *ctx; ctx = OSSL_ENCODER_CTX_new_for_pkey(a, selection, output_info->output_type, output_info->output_structure, NULL); if (ctx == NULL) return -1; if (OSSL_ENCODER_to_data(ctx, pp, &len)) { if (pp_was_NULL) ret = (int)len; else ret = INT_MAX - (int)len; } OSSL_ENCODER_CTX_free(ctx); } if (ret == -1) ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_TYPE); return ret; } int i2d_KeyParams(const EVP_PKEY *a, unsigned char **pp) { if (evp_pkey_is_provided(a)) { static const struct type_and_structure_st output_info[] = { { "DER", "type-specific" }, { NULL, } }; return i2d_provided(a, EVP_PKEY_KEY_PARAMETERS, output_info, pp); } if (a->ameth != NULL && a->ameth->param_encode != NULL) return a->ameth->param_encode(a, pp); ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_TYPE); return -1; } int i2d_KeyParams_bio(BIO *bp, const EVP_PKEY *pkey) { return ASN1_i2d_bio_of(EVP_PKEY, i2d_KeyParams, bp, pkey); } int i2d_PrivateKey(const EVP_PKEY *a, unsigned char **pp) { if (evp_pkey_is_provided(a)) { static const struct type_and_structure_st output_info[] = { { "DER", "type-specific" }, { "DER", "PrivateKeyInfo" }, { NULL, } }; return i2d_provided(a, EVP_PKEY_KEYPAIR, output_info, pp); } if (a->ameth != NULL && a->ameth->old_priv_encode != NULL) { return a->ameth->old_priv_encode(a, pp); } if (a->ameth != NULL && a->ameth->priv_encode != NULL) { PKCS8_PRIV_KEY_INFO *p8 = EVP_PKEY2PKCS8(a); int ret = 0; if (p8 != NULL) { ret = i2d_PKCS8_PRIV_KEY_INFO(p8, pp); PKCS8_PRIV_KEY_INFO_free(p8); } return ret; } ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE); return -1; } int i2d_PublicKey(const EVP_PKEY *a, unsigned char **pp) { if (evp_pkey_is_provided(a)) { static const struct type_and_structure_st output_info[] = { { "DER", "type-specific" }, { "blob", NULL }, /* for EC */ { NULL, } }; return i2d_provided(a, EVP_PKEY_PUBLIC_KEY, output_info, pp); } switch (EVP_PKEY_get_base_id(a)) { case EVP_PKEY_RSA: return i2d_RSAPublicKey(EVP_PKEY_get0_RSA(a), pp); #ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: return i2d_DSAPublicKey(EVP_PKEY_get0_DSA(a), pp); #endif #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: return i2o_ECPublicKey(EVP_PKEY_get0_EC_KEY(a), pp); #endif default: ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE); return -1; } }
./openssl/crypto/asn1/charmap.h
/* * WARNING: do not edit! * Generated by crypto/asn1/charmap.pl * * 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 */ #define CHARTYPE_HOST_ANY 4096 #define CHARTYPE_HOST_DOT 8192 #define CHARTYPE_HOST_HYPHEN 16384 #define CHARTYPE_HOST_WILD 32768 /* * Mask of various character properties */ static const unsigned short char_type[] = { 1026, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 120, 0, 1, 40, 0, 0, 0, 16, 1040, 1040, 33792, 25, 25, 16400, 8208, 16, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 16, 9, 9, 16, 9, 16, 0, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 0, 1025, 0, 0, 0, 0, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 0, 0, 0, 0, 2 };
./openssl/crypto/asn1/tasn_scn.c
/* * Copyright 2010-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 <stddef.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/objects.h> #include <openssl/buffer.h> #include <openssl/err.h> #include <openssl/x509v3.h> #include "asn1_local.h" /* * General ASN1 structure recursive scanner: iterate through all fields * passing details to a callback. */ ASN1_SCTX *ASN1_SCTX_new(int (*scan_cb) (ASN1_SCTX *ctx)) { ASN1_SCTX *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->scan_cb = scan_cb; return ret; } void ASN1_SCTX_free(ASN1_SCTX *p) { OPENSSL_free(p); } const ASN1_ITEM *ASN1_SCTX_get_item(ASN1_SCTX *p) { return p->it; } const ASN1_TEMPLATE *ASN1_SCTX_get_template(ASN1_SCTX *p) { return p->tt; } unsigned long ASN1_SCTX_get_flags(ASN1_SCTX *p) { return p->flags; } void ASN1_SCTX_set_app_data(ASN1_SCTX *p, void *data) { p->app_data = data; } void *ASN1_SCTX_get_app_data(ASN1_SCTX *p) { return p->app_data; }
./openssl/crypto/asn1/x_sig.c
/* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> #include "crypto/x509.h" ASN1_SEQUENCE(X509_SIG) = { ASN1_SIMPLE(X509_SIG, algor, X509_ALGOR), ASN1_SIMPLE(X509_SIG, digest, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(X509_SIG) IMPLEMENT_ASN1_FUNCTIONS(X509_SIG) void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg, const ASN1_OCTET_STRING **pdigest) { if (palg) *palg = sig->algor; if (pdigest) *pdigest = sig->digest; } void X509_SIG_getm(X509_SIG *sig, X509_ALGOR **palg, ASN1_OCTET_STRING **pdigest) { if (palg) *palg = sig->algor; if (pdigest) *pdigest = sig->digest; }
./openssl/crypto/asn1/asn_mstbl.c
/* * Copyright 2012-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 <openssl/crypto.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/x509v3.h> /* Multi string module: add table entries from a given section */ static int do_tcreate(const char *value, const char *name); static int stbl_module_init(CONF_IMODULE *md, const CONF *cnf) { int i; const char *stbl_section; STACK_OF(CONF_VALUE) *sktmp; CONF_VALUE *mval; stbl_section = CONF_imodule_get_value(md); if ((sktmp = NCONF_get_section(cnf, stbl_section)) == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ERROR_LOADING_SECTION); return 0; } for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) { mval = sk_CONF_VALUE_value(sktmp, i); if (!do_tcreate(mval->value, mval->name)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_VALUE); return 0; } } return 1; } static void stbl_module_finish(CONF_IMODULE *md) { ASN1_STRING_TABLE_cleanup(); } void ASN1_add_stable_module(void) { CONF_module_add("stbl_section", stbl_module_init, stbl_module_finish); } /* * Create an table entry based on a name value pair. format is oid_name = * n1:v1, n2:v2,... where name is "min", "max", "mask" or "flags". */ static int do_tcreate(const char *value, const char *name) { char *eptr; int nid, i, rv = 0; long tbl_min = -1, tbl_max = -1; unsigned long tbl_mask = 0, tbl_flags = 0; STACK_OF(CONF_VALUE) *lst = NULL; CONF_VALUE *cnf = NULL; nid = OBJ_sn2nid(name); if (nid == NID_undef) nid = OBJ_ln2nid(name); if (nid == NID_undef) goto err; lst = X509V3_parse_list(value); if (!lst) goto err; for (i = 0; i < sk_CONF_VALUE_num(lst); i++) { cnf = sk_CONF_VALUE_value(lst, i); if (cnf->value == NULL) goto err; if (strcmp(cnf->name, "min") == 0) { tbl_min = strtoul(cnf->value, &eptr, 0); if (*eptr) goto err; } else if (strcmp(cnf->name, "max") == 0) { tbl_max = strtoul(cnf->value, &eptr, 0); if (*eptr) goto err; } else if (strcmp(cnf->name, "mask") == 0) { if (!ASN1_str2mask(cnf->value, &tbl_mask) || !tbl_mask) goto err; } else if (strcmp(cnf->name, "flags") == 0) { if (strcmp(cnf->value, "nomask") == 0) tbl_flags = STABLE_NO_MASK; else if (strcmp(cnf->value, "none") == 0) tbl_flags = STABLE_FLAGS_CLEAR; else goto err; } else goto err; } rv = 1; err: if (rv == 0) { if (cnf) ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_STRING_TABLE_VALUE, "field=%s, value=%s", cnf->name, cnf->value != NULL ? cnf->value : value); else ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_STRING_TABLE_VALUE, "name=%s, value=%s", name, value); } else { rv = ASN1_STRING_TABLE_add(nid, tbl_min, tbl_max, tbl_mask, tbl_flags); if (!rv) ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); } sk_CONF_VALUE_pop_free(lst, X509V3_conf_free); return rv; }
./openssl/crypto/asn1/tasn_typ.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 <stdio.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> /* Declarations for string types */ #define IMPLEMENT_ASN1_STRING_FUNCTIONS(sname) \ IMPLEMENT_ASN1_TYPE(sname) \ IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(sname, sname, sname) \ sname *sname##_new(void) \ { \ return ASN1_STRING_type_new(V_##sname); \ } \ void sname##_free(sname *x) \ { \ ASN1_STRING_free(x); \ } IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_OCTET_STRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_INTEGER) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_ENUMERATED) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_BIT_STRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_UTF8STRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_PRINTABLESTRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_T61STRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_IA5STRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_GENERALSTRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_UTCTIME) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_GENERALIZEDTIME) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_VISIBLESTRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_UNIVERSALSTRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_BMPSTRING) IMPLEMENT_ASN1_TYPE(ASN1_NULL) IMPLEMENT_ASN1_FUNCTIONS(ASN1_NULL) IMPLEMENT_ASN1_TYPE(ASN1_OBJECT) IMPLEMENT_ASN1_TYPE(ASN1_ANY) /* Just swallow an ASN1_SEQUENCE in an ASN1_STRING */ IMPLEMENT_ASN1_TYPE(ASN1_SEQUENCE) IMPLEMENT_ASN1_FUNCTIONS_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE) /* Multistring types */ IMPLEMENT_ASN1_MSTRING(ASN1_PRINTABLE, B_ASN1_PRINTABLE) IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, ASN1_PRINTABLE) IMPLEMENT_ASN1_MSTRING(DISPLAYTEXT, B_ASN1_DISPLAYTEXT) IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, DISPLAYTEXT) IMPLEMENT_ASN1_MSTRING(DIRECTORYSTRING, B_ASN1_DIRECTORYSTRING) IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, DIRECTORYSTRING) /* Three separate BOOLEAN type: normal, DEFAULT TRUE and DEFAULT FALSE */ IMPLEMENT_ASN1_TYPE_ex(ASN1_BOOLEAN, ASN1_BOOLEAN, -1) IMPLEMENT_ASN1_TYPE_ex(ASN1_TBOOLEAN, ASN1_BOOLEAN, 1) IMPLEMENT_ASN1_TYPE_ex(ASN1_FBOOLEAN, ASN1_BOOLEAN, 0) /* Special, OCTET STRING with indefinite length constructed support */ IMPLEMENT_ASN1_TYPE_ex(ASN1_OCTET_STRING_NDEF, ASN1_OCTET_STRING, ASN1_TFLG_NDEF) ASN1_ITEM_TEMPLATE(ASN1_SEQUENCE_ANY) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, ASN1_SEQUENCE_ANY, ASN1_ANY) ASN1_ITEM_TEMPLATE_END(ASN1_SEQUENCE_ANY) ASN1_ITEM_TEMPLATE(ASN1_SET_ANY) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, ASN1_SET_ANY, ASN1_ANY) ASN1_ITEM_TEMPLATE_END(ASN1_SET_ANY) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(ASN1_SEQUENCE_ANY, ASN1_SET_ANY, ASN1_SET_ANY)
./openssl/crypto/asn1/p8_pkey.c
/* * Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> #include "crypto/x509.h" /* Minor tweak to operation: zero private key data */ static int pkey_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { /* Since the structure must still be valid use ASN1_OP_FREE_PRE */ if (operation == ASN1_OP_FREE_PRE) { PKCS8_PRIV_KEY_INFO *key = (PKCS8_PRIV_KEY_INFO *)*pval; if (key->pkey) OPENSSL_cleanse(key->pkey->data, key->pkey->length); } return 1; } ASN1_SEQUENCE_cb(PKCS8_PRIV_KEY_INFO, pkey_cb) = { ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, version, ASN1_INTEGER), ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkeyalg, X509_ALGOR), ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkey, ASN1_OCTET_STRING), ASN1_IMP_SET_OF_OPT(PKCS8_PRIV_KEY_INFO, attributes, X509_ATTRIBUTE, 0) } ASN1_SEQUENCE_END_cb(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO) IMPLEMENT_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO) int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj, int version, int ptype, void *pval, unsigned char *penc, int penclen) { if (version >= 0) { if (!ASN1_INTEGER_set(priv->version, version)) return 0; } if (!X509_ALGOR_set0(priv->pkeyalg, aobj, ptype, pval)) return 0; if (penc) ASN1_STRING_set0(priv->pkey, penc, penclen); return 1; } int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg, const unsigned char **pk, int *ppklen, const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8) { if (ppkalg) *ppkalg = p8->pkeyalg->algorithm; if (pk) { *pk = ASN1_STRING_get0_data(p8->pkey); *ppklen = ASN1_STRING_length(p8->pkey); } if (pa) *pa = p8->pkeyalg; return 1; } const STACK_OF(X509_ATTRIBUTE) * PKCS8_pkey_get0_attrs(const PKCS8_PRIV_KEY_INFO *p8) { return p8->attributes; } int PKCS8_pkey_add1_attr_by_NID(PKCS8_PRIV_KEY_INFO *p8, int nid, int type, const unsigned char *bytes, int len) { if (X509at_add1_attr_by_NID(&p8->attributes, nid, type, bytes, len) != NULL) return 1; return 0; } int PKCS8_pkey_add1_attr_by_OBJ(PKCS8_PRIV_KEY_INFO *p8, const ASN1_OBJECT *obj, int type, const unsigned char *bytes, int len) { return (X509at_add1_attr_by_OBJ(&p8->attributes, obj, type, bytes, len) != NULL); } int PKCS8_pkey_add1_attr(PKCS8_PRIV_KEY_INFO *p8, X509_ATTRIBUTE *attr) { return (X509at_add1_attr(&p8->attributes, attr) != NULL); }
./openssl/crypto/asn1/t_bitst.c
/* * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/x509v3.h> int ASN1_BIT_STRING_name_print(BIO *out, ASN1_BIT_STRING *bs, BIT_STRING_BITNAME *tbl, int indent) { BIT_STRING_BITNAME *bnam; char first = 1; BIO_printf(out, "%*s", indent, ""); for (bnam = tbl; bnam->lname; bnam++) { if (ASN1_BIT_STRING_get_bit(bs, bnam->bitnum)) { if (!first) BIO_puts(out, ", "); BIO_puts(out, bnam->lname); first = 0; } } BIO_puts(out, "\n"); return 1; } int ASN1_BIT_STRING_set_asc(ASN1_BIT_STRING *bs, const char *name, int value, BIT_STRING_BITNAME *tbl) { int bitnum; bitnum = ASN1_BIT_STRING_num_asc(name, tbl); if (bitnum < 0) return 0; if (bs) { if (!ASN1_BIT_STRING_set_bit(bs, bitnum, value)) return 0; } return 1; } int ASN1_BIT_STRING_num_asc(const char *name, BIT_STRING_BITNAME *tbl) { BIT_STRING_BITNAME *bnam; for (bnam = tbl; bnam->lname; bnam++) { if ((strcmp(bnam->sname, name) == 0) || (strcmp(bnam->lname, name) == 0)) return bnam->bitnum; } return -1; }
./openssl/crypto/asn1/x_val.c
/* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> ASN1_SEQUENCE(X509_VAL) = { ASN1_SIMPLE(X509_VAL, notBefore, ASN1_TIME), ASN1_SIMPLE(X509_VAL, notAfter, ASN1_TIME) } ASN1_SEQUENCE_END(X509_VAL) IMPLEMENT_ASN1_FUNCTIONS(X509_VAL)
./openssl/crypto/asn1/a_d2i_fp.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 <limits.h> #include "internal/cryptlib.h" #include "internal/numbers.h" #include <openssl/buffer.h> #include <openssl/asn1.h> #include "internal/asn1.h" #include "crypto/asn1.h" #ifndef NO_OLD_ASN1 # ifndef OPENSSL_NO_STDIO void *ASN1_d2i_fp(void *(*xnew) (void), d2i_of_void *d2i, FILE *in, void **x) { BIO *b; void *ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB); return NULL; } BIO_set_fp(b, in, BIO_NOCLOSE); ret = ASN1_d2i_bio(xnew, d2i, b, x); BIO_free(b); return ret; } # endif void *ASN1_d2i_bio(void *(*xnew) (void), d2i_of_void *d2i, BIO *in, void **x) { BUF_MEM *b = NULL; const unsigned char *p; void *ret = NULL; int len; len = asn1_d2i_read_bio(in, &b); if (len < 0) goto err; p = (unsigned char *)b->data; ret = d2i(x, &p, len); err: BUF_MEM_free(b); return ret; } #endif void *ASN1_item_d2i_bio_ex(const ASN1_ITEM *it, BIO *in, void *x, OSSL_LIB_CTX *libctx, const char *propq) { BUF_MEM *b = NULL; const unsigned char *p; void *ret = NULL; int len; if (in == NULL) return NULL; len = asn1_d2i_read_bio(in, &b); if (len < 0) goto err; p = (const unsigned char *)b->data; ret = ASN1_item_d2i_ex(x, &p, len, it, libctx, propq); err: BUF_MEM_free(b); return ret; } void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x) { return ASN1_item_d2i_bio_ex(it, in, x, NULL, NULL); } #ifndef OPENSSL_NO_STDIO void *ASN1_item_d2i_fp_ex(const ASN1_ITEM *it, FILE *in, void *x, OSSL_LIB_CTX *libctx, const char *propq) { BIO *b; char *ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB); return NULL; } BIO_set_fp(b, in, BIO_NOCLOSE); ret = ASN1_item_d2i_bio_ex(it, b, x, libctx, propq); BIO_free(b); return ret; } void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x) { return ASN1_item_d2i_fp_ex(it, in, x, NULL, NULL); } #endif #define HEADER_SIZE 8 #define ASN1_CHUNK_INITIAL_SIZE (16 * 1024) int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb) { BUF_MEM *b; unsigned char *p; int i; size_t want = HEADER_SIZE; uint32_t eos = 0; size_t off = 0; size_t len = 0; size_t diff; const unsigned char *q; long slen; int inf, tag, xclass; b = BUF_MEM_new(); if (b == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB); return -1; } ERR_set_mark(); for (;;) { diff = len - off; if (want >= diff) { want -= diff; if (len + want < len || !BUF_MEM_grow_clean(b, len + want)) { ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB); goto err; } i = BIO_read(in, &(b->data[len]), want); if (i < 0 && diff == 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_NOT_ENOUGH_DATA); goto err; } if (i > 0) { if (len + i < len) { ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG); goto err; } len += i; } } /* else data already loaded */ p = (unsigned char *)&(b->data[off]); q = p; diff = len - off; if (diff == 0) goto err; inf = ASN1_get_object(&q, &slen, &tag, &xclass, diff); if (inf & 0x80) { unsigned long e; e = ERR_GET_REASON(ERR_peek_last_error()); if (e != ASN1_R_TOO_LONG) goto err; ERR_pop_to_mark(); } i = q - p; /* header length */ off += i; /* end of data */ if (inf & 1) { /* no data body so go round again */ if (eos == UINT32_MAX) { ERR_raise(ERR_LIB_ASN1, ASN1_R_HEADER_TOO_LONG); goto err; } eos++; want = HEADER_SIZE; } else if (eos && (slen == 0) && (tag == V_ASN1_EOC)) { /* eos value, so go back and read another header */ eos--; if (eos == 0) break; else want = HEADER_SIZE; } else { /* suck in slen bytes of data */ want = slen; if (want > (len - off)) { size_t chunk_max = ASN1_CHUNK_INITIAL_SIZE; want -= (len - off); if (want > INT_MAX /* BIO_read takes an int length */ || len + want < len) { ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG); goto err; } while (want > 0) { /* * Read content in chunks of increasing size * so we can return an error for EOF without * having to allocate the entire content length * in one go. */ size_t chunk = want > chunk_max ? chunk_max : want; if (!BUF_MEM_grow_clean(b, len + chunk)) { ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB); goto err; } want -= chunk; while (chunk > 0) { i = BIO_read(in, &(b->data[len]), chunk); if (i <= 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_NOT_ENOUGH_DATA); goto err; } /* * This can't overflow because |len+want| didn't * overflow. */ len += i; chunk -= i; } if (chunk_max < INT_MAX/2) chunk_max *= 2; } } if (off + slen < off) { ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG); goto err; } off += slen; if (eos == 0) { break; } else want = HEADER_SIZE; } } if (off > INT_MAX) { ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG); goto err; } *pb = b; return off; err: ERR_clear_last_mark(); BUF_MEM_free(b); return -1; }
./openssl/crypto/asn1/p5_pbe.c
/* * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> #include <openssl/rand.h> #include "crypto/evp.h" /* PKCS#5 password based encryption structure */ ASN1_SEQUENCE(PBEPARAM) = { ASN1_SIMPLE(PBEPARAM, salt, ASN1_OCTET_STRING), ASN1_SIMPLE(PBEPARAM, iter, ASN1_INTEGER) } ASN1_SEQUENCE_END(PBEPARAM) IMPLEMENT_ASN1_FUNCTIONS(PBEPARAM) /* Set an algorithm identifier for a PKCS#5 PBE algorithm */ int PKCS5_pbe_set0_algor_ex(X509_ALGOR *algor, int alg, int iter, const unsigned char *salt, int saltlen, OSSL_LIB_CTX *ctx) { PBEPARAM *pbe = NULL; ASN1_STRING *pbe_str = NULL; unsigned char *sstr = NULL; pbe = PBEPARAM_new(); if (pbe == NULL) { /* ERR_R_ASN1_LIB, because PBEPARAM_new() is defined in crypto/asn1 */ ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (iter <= 0) iter = PKCS5_DEFAULT_ITER; if (!ASN1_INTEGER_set(pbe->iter, iter)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (!saltlen) saltlen = PKCS5_DEFAULT_PBE1_SALT_LEN; if (saltlen < 0) goto err; sstr = OPENSSL_malloc(saltlen); if (sstr == NULL) goto err; if (salt) memcpy(sstr, salt, saltlen); else if (RAND_bytes_ex(ctx, sstr, saltlen, 0) <= 0) goto err; ASN1_STRING_set0(pbe->salt, sstr, saltlen); sstr = NULL; if (!ASN1_item_pack(pbe, ASN1_ITEM_rptr(PBEPARAM), &pbe_str)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } PBEPARAM_free(pbe); pbe = NULL; if (X509_ALGOR_set0(algor, OBJ_nid2obj(alg), V_ASN1_SEQUENCE, pbe_str)) return 1; err: OPENSSL_free(sstr); PBEPARAM_free(pbe); ASN1_STRING_free(pbe_str); return 0; } int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter, const unsigned char *salt, int saltlen) { return PKCS5_pbe_set0_algor_ex(algor, alg, iter, salt, saltlen, NULL); } /* Return an algorithm identifier for a PKCS#5 PBE algorithm */ X509_ALGOR *PKCS5_pbe_set_ex(int alg, int iter, const unsigned char *salt, int saltlen, OSSL_LIB_CTX *ctx) { X509_ALGOR *ret; ret = X509_ALGOR_new(); if (ret == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_X509_LIB); return NULL; } if (PKCS5_pbe_set0_algor_ex(ret, alg, iter, salt, saltlen, ctx)) return ret; X509_ALGOR_free(ret); return NULL; } X509_ALGOR *PKCS5_pbe_set(int alg, int iter, const unsigned char *salt, int saltlen) { return PKCS5_pbe_set_ex(alg, iter, salt, saltlen, NULL); }
./openssl/crypto/asn1/tasn_prn.c
/* * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stddef.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/objects.h> #include <openssl/buffer.h> #include <openssl/err.h> #include <openssl/x509v3.h> #include "crypto/asn1.h" #include "asn1_local.h" /* * Print routines. */ /* ASN1_PCTX routines */ static ASN1_PCTX default_pctx = { ASN1_PCTX_FLAGS_SHOW_ABSENT, /* flags */ 0, /* nm_flags */ 0, /* cert_flags */ 0, /* oid_flags */ 0 /* str_flags */ }; ASN1_PCTX *ASN1_PCTX_new(void) { ASN1_PCTX *ret; ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; return ret; } void ASN1_PCTX_free(ASN1_PCTX *p) { OPENSSL_free(p); } unsigned long ASN1_PCTX_get_flags(const ASN1_PCTX *p) { return p->flags; } void ASN1_PCTX_set_flags(ASN1_PCTX *p, unsigned long flags) { p->flags = flags; } unsigned long ASN1_PCTX_get_nm_flags(const ASN1_PCTX *p) { return p->nm_flags; } void ASN1_PCTX_set_nm_flags(ASN1_PCTX *p, unsigned long flags) { p->nm_flags = flags; } unsigned long ASN1_PCTX_get_cert_flags(const ASN1_PCTX *p) { return p->cert_flags; } void ASN1_PCTX_set_cert_flags(ASN1_PCTX *p, unsigned long flags) { p->cert_flags = flags; } unsigned long ASN1_PCTX_get_oid_flags(const ASN1_PCTX *p) { return p->oid_flags; } void ASN1_PCTX_set_oid_flags(ASN1_PCTX *p, unsigned long flags) { p->oid_flags = flags; } unsigned long ASN1_PCTX_get_str_flags(const ASN1_PCTX *p) { return p->str_flags; } void ASN1_PCTX_set_str_flags(ASN1_PCTX *p, unsigned long flags) { p->str_flags = flags; } /* Main print routines */ static int asn1_item_print_ctx(BIO *out, const ASN1_VALUE **fld, int indent, const ASN1_ITEM *it, const char *fname, const char *sname, int nohdr, const ASN1_PCTX *pctx); static int asn1_template_print_ctx(BIO *out, const ASN1_VALUE **fld, int indent, const ASN1_TEMPLATE *tt, const ASN1_PCTX *pctx); static int asn1_primitive_print(BIO *out, const ASN1_VALUE **fld, const ASN1_ITEM *it, int indent, const char *fname, const char *sname, const ASN1_PCTX *pctx); static int asn1_print_fsname(BIO *out, int indent, const char *fname, const char *sname, const ASN1_PCTX *pctx); int ASN1_item_print(BIO *out, const ASN1_VALUE *ifld, int indent, const ASN1_ITEM *it, const ASN1_PCTX *pctx) { const char *sname; if (pctx == NULL) pctx = &default_pctx; if (pctx->flags & ASN1_PCTX_FLAGS_NO_STRUCT_NAME) sname = NULL; else sname = it->sname; return asn1_item_print_ctx(out, &ifld, indent, it, NULL, sname, 0, pctx); } static int asn1_item_print_ctx(BIO *out, const ASN1_VALUE **fld, int indent, const ASN1_ITEM *it, const char *fname, const char *sname, int nohdr, const ASN1_PCTX *pctx) { const ASN1_TEMPLATE *tt; const ASN1_EXTERN_FUNCS *ef; const ASN1_VALUE **tmpfld; const ASN1_AUX *aux = it->funcs; ASN1_aux_const_cb *asn1_cb = NULL; ASN1_PRINT_ARG parg; int i; if (aux != NULL) { parg.out = out; parg.indent = indent; parg.pctx = pctx; asn1_cb = ((aux->flags & ASN1_AFLG_CONST_CB) != 0) ? aux->asn1_const_cb : (ASN1_aux_const_cb *)aux->asn1_cb; /* backward compatibility */ } if (((it->itype != ASN1_ITYPE_PRIMITIVE) || (it->utype != V_ASN1_BOOLEAN)) && *fld == NULL) { if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_ABSENT) { if (!nohdr && !asn1_print_fsname(out, indent, fname, sname, pctx)) return 0; if (BIO_puts(out, "<ABSENT>\n") <= 0) return 0; } return 1; } switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) { if (!asn1_template_print_ctx(out, fld, indent, it->templates, pctx)) return 0; break; } /* fall through */ case ASN1_ITYPE_MSTRING: if (!asn1_primitive_print(out, fld, it, indent, fname, sname, pctx)) return 0; break; case ASN1_ITYPE_EXTERN: if (!nohdr && !asn1_print_fsname(out, indent, fname, sname, pctx)) return 0; /* Use new style print routine if possible */ ef = it->funcs; if (ef && ef->asn1_ex_print) { i = ef->asn1_ex_print(out, fld, indent, "", pctx); if (!i) return 0; if ((i == 2) && (BIO_puts(out, "\n") <= 0)) return 0; return 1; } else if (sname && BIO_printf(out, ":EXTERNAL TYPE %s\n", sname) <= 0) return 0; break; case ASN1_ITYPE_CHOICE: /* CHOICE type, get selector */ i = ossl_asn1_get_choice_selector_const(fld, it); /* This should never happen... */ if ((i < 0) || (i >= it->tcount)) { if (BIO_printf(out, "ERROR: selector [%d] invalid\n", i) <= 0) return 0; return 1; } tt = it->templates + i; tmpfld = ossl_asn1_get_const_field_ptr(fld, tt); if (!asn1_template_print_ctx(out, tmpfld, indent, tt, pctx)) return 0; break; case ASN1_ITYPE_SEQUENCE: case ASN1_ITYPE_NDEF_SEQUENCE: if (!nohdr && !asn1_print_fsname(out, indent, fname, sname, pctx)) return 0; if (fname || sname) { if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SEQUENCE) { if (BIO_puts(out, " {\n") <= 0) return 0; } else { if (BIO_puts(out, "\n") <= 0) return 0; } } if (asn1_cb) { i = asn1_cb(ASN1_OP_PRINT_PRE, fld, it, &parg); if (i == 0) return 0; if (i == 2) return 1; } /* Print each field entry */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { const ASN1_TEMPLATE *seqtt; seqtt = ossl_asn1_do_adb(*fld, tt, 1); if (!seqtt) return 0; tmpfld = ossl_asn1_get_const_field_ptr(fld, seqtt); if (!asn1_template_print_ctx(out, tmpfld, indent + 2, seqtt, pctx)) return 0; } if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SEQUENCE) { if (BIO_printf(out, "%*s}\n", indent, "") < 0) return 0; } if (asn1_cb) { i = asn1_cb(ASN1_OP_PRINT_POST, fld, it, &parg); if (i == 0) return 0; } break; default: BIO_printf(out, "Unprocessed type %d\n", it->itype); return 0; } return 1; } static int asn1_template_print_ctx(BIO *out, const ASN1_VALUE **fld, int indent, const ASN1_TEMPLATE *tt, const ASN1_PCTX *pctx) { int i, flags; const char *sname, *fname; const ASN1_VALUE *tfld; flags = tt->flags; if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME) sname = ASN1_ITEM_ptr(tt->item)->sname; else sname = NULL; if (pctx->flags & ASN1_PCTX_FLAGS_NO_FIELD_NAME) fname = NULL; else fname = tt->field_name; /* * If field is embedded then fld needs fixing so it is a pointer to * a pointer to a field. */ if (flags & ASN1_TFLG_EMBED) { tfld = (const ASN1_VALUE *)fld; fld = &tfld; } if (flags & ASN1_TFLG_SK_MASK) { char *tname; const ASN1_VALUE *skitem; STACK_OF(const_ASN1_VALUE) *stack; /* SET OF, SEQUENCE OF */ if (fname) { if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SSOF) { if (flags & ASN1_TFLG_SET_OF) tname = "SET"; else tname = "SEQUENCE"; if (BIO_printf(out, "%*s%s OF %s {\n", indent, "", tname, tt->field_name) <= 0) return 0; } else if (BIO_printf(out, "%*s%s:\n", indent, "", fname) <= 0) return 0; } stack = (STACK_OF(const_ASN1_VALUE) *)*fld; for (i = 0; i < sk_const_ASN1_VALUE_num(stack); i++) { if ((i > 0) && (BIO_puts(out, "\n") <= 0)) return 0; skitem = sk_const_ASN1_VALUE_value(stack, i); if (!asn1_item_print_ctx(out, &skitem, indent + 2, ASN1_ITEM_ptr(tt->item), NULL, NULL, 1, pctx)) return 0; } if (i == 0 && BIO_printf(out, "%*s<%s>\n", indent + 2, "", stack == NULL ? "ABSENT" : "EMPTY") <= 0) return 0; if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SEQUENCE) { if (BIO_printf(out, "%*s}\n", indent, "") <= 0) return 0; } return 1; } return asn1_item_print_ctx(out, fld, indent, ASN1_ITEM_ptr(tt->item), fname, sname, 0, pctx); } static int asn1_print_fsname(BIO *out, int indent, const char *fname, const char *sname, const ASN1_PCTX *pctx) { static const char spaces[] = " "; static const int nspaces = sizeof(spaces) - 1; while (indent > nspaces) { if (BIO_write(out, spaces, nspaces) != nspaces) return 0; indent -= nspaces; } if (BIO_write(out, spaces, indent) != indent) return 0; if (pctx->flags & ASN1_PCTX_FLAGS_NO_STRUCT_NAME) sname = NULL; if (pctx->flags & ASN1_PCTX_FLAGS_NO_FIELD_NAME) fname = NULL; if (!sname && !fname) return 1; if (fname) { if (BIO_puts(out, fname) <= 0) return 0; } if (sname) { if (fname) { if (BIO_printf(out, " (%s)", sname) <= 0) return 0; } else { if (BIO_puts(out, sname) <= 0) return 0; } } if (BIO_write(out, ": ", 2) != 2) return 0; return 1; } static int asn1_print_boolean(BIO *out, int boolval) { const char *str; switch (boolval) { case -1: str = "BOOL ABSENT"; break; case 0: str = "FALSE"; break; default: str = "TRUE"; break; } if (BIO_puts(out, str) <= 0) return 0; return 1; } static int asn1_print_integer(BIO *out, const ASN1_INTEGER *str) { char *s; int ret = 1; s = i2s_ASN1_INTEGER(NULL, str); if (s == NULL) return 0; if (BIO_puts(out, s) <= 0) ret = 0; OPENSSL_free(s); return ret; } static int asn1_print_oid(BIO *out, const ASN1_OBJECT *oid) { char objbuf[80]; const char *ln; ln = OBJ_nid2ln(OBJ_obj2nid(oid)); if (!ln) ln = ""; OBJ_obj2txt(objbuf, sizeof(objbuf), oid, 1); if (BIO_printf(out, "%s (%s)", ln, objbuf) <= 0) return 0; return 1; } static int asn1_print_obstring(BIO *out, const ASN1_STRING *str, int indent) { if (str->type == V_ASN1_BIT_STRING) { if (BIO_printf(out, " (%ld unused bits)\n", str->flags & 0x7) <= 0) return 0; } else if (BIO_puts(out, "\n") <= 0) return 0; if ((str->length > 0) && BIO_dump_indent(out, (const char *)str->data, str->length, indent + 2) <= 0) return 0; return 1; } static int asn1_primitive_print(BIO *out, const ASN1_VALUE **fld, const ASN1_ITEM *it, int indent, const char *fname, const char *sname, const ASN1_PCTX *pctx) { long utype; ASN1_STRING *str; int ret = 1, needlf = 1; const char *pname; const ASN1_PRIMITIVE_FUNCS *pf; pf = it->funcs; if (!asn1_print_fsname(out, indent, fname, sname, pctx)) return 0; if (pf && pf->prim_print) return pf->prim_print(out, fld, it, indent, pctx); if (it->itype == ASN1_ITYPE_MSTRING) { str = (ASN1_STRING *)*fld; utype = str->type & ~V_ASN1_NEG; } else { utype = it->utype; if (utype == V_ASN1_BOOLEAN) str = NULL; else str = (ASN1_STRING *)*fld; } if (utype == V_ASN1_ANY) { const ASN1_TYPE *atype = (const ASN1_TYPE *)*fld; utype = atype->type; fld = (const ASN1_VALUE **)&atype->value.asn1_value; /* actually is const */ str = (ASN1_STRING *)*fld; if (pctx->flags & ASN1_PCTX_FLAGS_NO_ANY_TYPE) pname = NULL; else pname = ASN1_tag2str(utype); } else { if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_TYPE) pname = ASN1_tag2str(utype); else pname = NULL; } if (utype == V_ASN1_NULL) { if (BIO_puts(out, "NULL\n") <= 0) return 0; return 1; } if (pname) { if (BIO_puts(out, pname) <= 0) return 0; if (BIO_puts(out, ":") <= 0) return 0; } switch (utype) { case V_ASN1_BOOLEAN: { int boolval = *(int *)fld; if (boolval == -1) boolval = it->size; ret = asn1_print_boolean(out, boolval); } break; case V_ASN1_INTEGER: case V_ASN1_ENUMERATED: ret = asn1_print_integer(out, str); break; case V_ASN1_UTCTIME: ret = ASN1_UTCTIME_print(out, str); break; case V_ASN1_GENERALIZEDTIME: ret = ASN1_GENERALIZEDTIME_print(out, str); break; case V_ASN1_OBJECT: ret = asn1_print_oid(out, (const ASN1_OBJECT *)*fld); break; case V_ASN1_OCTET_STRING: case V_ASN1_BIT_STRING: ret = asn1_print_obstring(out, str, indent); needlf = 0; break; case V_ASN1_SEQUENCE: case V_ASN1_SET: case V_ASN1_OTHER: if (BIO_puts(out, "\n") <= 0) return 0; if (ASN1_parse_dump(out, str->data, str->length, indent, 0) <= 0) ret = 0; needlf = 0; break; default: ret = ASN1_STRING_print_ex(out, str, pctx->str_flags); } if (!ret) return 0; if (needlf && BIO_puts(out, "\n") <= 0) return 0; return 1; }
./openssl/crypto/asn1/a_gentm.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 */ /* * GENERALIZEDTIME implementation. Based on UTCTIME */ #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include "asn1_local.h" #include <openssl/asn1t.h> IMPLEMENT_ASN1_DUP_FUNCTION(ASN1_GENERALIZEDTIME) /* This is the primary function used to parse ASN1_GENERALIZEDTIME */ static int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d) { /* wrapper around ossl_asn1_time_to_tm */ if (d->type != V_ASN1_GENERALIZEDTIME) return 0; return ossl_asn1_time_to_tm(tm, d); } int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *d) { return asn1_generalizedtime_to_tm(NULL, d); } int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str) { ASN1_GENERALIZEDTIME t; t.type = V_ASN1_GENERALIZEDTIME; t.length = strlen(str); t.data = (unsigned char *)str; t.flags = 0; if (!ASN1_GENERALIZEDTIME_check(&t)) return 0; if (s != NULL && !ASN1_STRING_copy(s, &t)) return 0; return 1; } ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s, time_t t) { return ASN1_GENERALIZEDTIME_adj(s, t, 0, 0); } ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s, time_t t, int offset_day, long offset_sec) { struct tm *ts; struct tm data; ts = OPENSSL_gmtime(&t, &data); if (ts == NULL) return NULL; if (offset_day || offset_sec) { if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec)) return NULL; } return ossl_asn1_time_from_tm(s, ts, V_ASN1_GENERALIZEDTIME); } int ASN1_GENERALIZEDTIME_print(BIO *bp, const ASN1_GENERALIZEDTIME *tm) { if (tm->type != V_ASN1_GENERALIZEDTIME) return 0; return ASN1_TIME_print(bp, tm); }
./openssl/crypto/asn1/a_print.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 "crypto/ctype.h" #include "internal/cryptlib.h" #include <openssl/asn1.h> int ASN1_PRINTABLE_type(const unsigned char *s, int len) { int c; int ia5 = 0; int t61 = 0; if (s == NULL) return V_ASN1_PRINTABLESTRING; if (len < 0) len = strlen((const char *)s); while (len-- > 0) { c = *(s++); if (!ossl_isasn1print(c)) ia5 = 1; if (!ossl_isascii(c)) t61 = 1; } if (t61) return V_ASN1_T61STRING; if (ia5) return V_ASN1_IA5STRING; return V_ASN1_PRINTABLESTRING; } int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s) { int i; unsigned char *p; if (s->type != V_ASN1_UNIVERSALSTRING) return 0; if ((s->length % 4) != 0) return 0; p = s->data; for (i = 0; i < s->length; i += 4) { if ((p[0] != '\0') || (p[1] != '\0') || (p[2] != '\0')) break; else p += 4; } if (i < s->length) return 0; p = s->data; for (i = 3; i < s->length; i += 4) { *(p++) = s->data[i]; } *(p) = '\0'; s->length /= 4; s->type = ASN1_PRINTABLE_type(s->data, s->length); return 1; } int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v) { int i, n; char buf[80]; const char *p; if (v == NULL) return 0; n = 0; p = (const char *)v->data; for (i = 0; i < v->length; i++) { if ((p[i] > '~') || ((p[i] < ' ') && (p[i] != '\n') && (p[i] != '\r'))) buf[n] = '.'; else buf[n] = p[i]; n++; if (n >= 80) { if (BIO_write(bp, buf, n) <= 0) return 0; n = 0; } } if (n > 0) if (BIO_write(bp, buf, n) <= 0) return 0; return 1; }
./openssl/crypto/asn1/bio_asn1.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 */ /* * Experimental ASN1 BIO. When written through the data is converted to an * ASN1 string type: default is OCTET STRING. Additional functions can be * provided to add prefix and suffix data. */ #include <string.h> #include "internal/bio.h" #include <openssl/asn1.h> #include "internal/cryptlib.h" /* Must be large enough for biggest tag+length */ #define DEFAULT_ASN1_BUF_SIZE 20 typedef enum { ASN1_STATE_START, ASN1_STATE_PRE_COPY, ASN1_STATE_HEADER, ASN1_STATE_HEADER_COPY, ASN1_STATE_DATA_COPY, ASN1_STATE_POST_COPY, ASN1_STATE_DONE } asn1_bio_state_t; typedef struct BIO_ASN1_EX_FUNCS_st { asn1_ps_func *ex_func; asn1_ps_func *ex_free_func; } BIO_ASN1_EX_FUNCS; typedef struct BIO_ASN1_BUF_CTX_t { /* Internal state */ asn1_bio_state_t state; /* Internal buffer */ unsigned char *buf; /* Size of buffer */ int bufsize; /* Current position in buffer */ int bufpos; /* Current buffer length */ int buflen; /* Amount of data to copy */ int copylen; /* Class and tag to use */ int asn1_class, asn1_tag; asn1_ps_func *prefix, *prefix_free, *suffix, *suffix_free; /* Extra buffer for prefix and suffix data */ unsigned char *ex_buf; int ex_len; int ex_pos; void *ex_arg; } BIO_ASN1_BUF_CTX; static int asn1_bio_write(BIO *h, const char *buf, int num); static int asn1_bio_read(BIO *h, char *buf, int size); static int asn1_bio_puts(BIO *h, const char *str); static int asn1_bio_gets(BIO *h, char *str, int size); static long asn1_bio_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int asn1_bio_new(BIO *h); static int asn1_bio_free(BIO *data); static long asn1_bio_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); static int asn1_bio_init(BIO_ASN1_BUF_CTX *ctx, int size); static int asn1_bio_flush_ex(BIO *b, BIO_ASN1_BUF_CTX *ctx, asn1_ps_func *cleanup, asn1_bio_state_t next); static int asn1_bio_setup_ex(BIO *b, BIO_ASN1_BUF_CTX *ctx, asn1_ps_func *setup, asn1_bio_state_t ex_state, asn1_bio_state_t other_state); static const BIO_METHOD methods_asn1 = { BIO_TYPE_ASN1, "asn1", bwrite_conv, asn1_bio_write, bread_conv, asn1_bio_read, asn1_bio_puts, asn1_bio_gets, asn1_bio_ctrl, asn1_bio_new, asn1_bio_free, asn1_bio_callback_ctrl, }; const BIO_METHOD *BIO_f_asn1(void) { return &methods_asn1; } static int asn1_bio_new(BIO *b) { BIO_ASN1_BUF_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) return 0; if (!asn1_bio_init(ctx, DEFAULT_ASN1_BUF_SIZE)) { OPENSSL_free(ctx); return 0; } BIO_set_data(b, ctx); BIO_set_init(b, 1); return 1; } static int asn1_bio_init(BIO_ASN1_BUF_CTX *ctx, int size) { if (size <= 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if ((ctx->buf = OPENSSL_malloc(size)) == NULL) return 0; ctx->bufsize = size; ctx->asn1_class = V_ASN1_UNIVERSAL; ctx->asn1_tag = V_ASN1_OCTET_STRING; ctx->state = ASN1_STATE_START; return 1; } static int asn1_bio_free(BIO *b) { BIO_ASN1_BUF_CTX *ctx; if (b == NULL) return 0; ctx = BIO_get_data(b); if (ctx == NULL) return 0; if (ctx->prefix_free != NULL) ctx->prefix_free(b, &ctx->ex_buf, &ctx->ex_len, &ctx->ex_arg); if (ctx->suffix_free != NULL) ctx->suffix_free(b, &ctx->ex_buf, &ctx->ex_len, &ctx->ex_arg); OPENSSL_free(ctx->buf); OPENSSL_free(ctx); BIO_set_data(b, NULL); BIO_set_init(b, 0); return 1; } static int asn1_bio_write(BIO *b, const char *in, int inl) { BIO_ASN1_BUF_CTX *ctx; int wrmax, wrlen, ret; unsigned char *p; BIO *next; ctx = BIO_get_data(b); next = BIO_next(b); if (in == NULL || inl < 0 || ctx == NULL || next == NULL) return 0; wrlen = 0; ret = -1; for (;;) { switch (ctx->state) { /* Setup prefix data, call it */ case ASN1_STATE_START: if (!asn1_bio_setup_ex(b, ctx, ctx->prefix, ASN1_STATE_PRE_COPY, ASN1_STATE_HEADER)) return -1; break; /* Copy any pre data first */ case ASN1_STATE_PRE_COPY: ret = asn1_bio_flush_ex(b, ctx, ctx->prefix_free, ASN1_STATE_HEADER); if (ret <= 0) goto done; break; case ASN1_STATE_HEADER: ctx->buflen = ASN1_object_size(0, inl, ctx->asn1_tag) - inl; if (!ossl_assert(ctx->buflen <= ctx->bufsize)) return -1; p = ctx->buf; ASN1_put_object(&p, 0, inl, ctx->asn1_tag, ctx->asn1_class); ctx->copylen = inl; ctx->state = ASN1_STATE_HEADER_COPY; break; case ASN1_STATE_HEADER_COPY: ret = BIO_write(next, ctx->buf + ctx->bufpos, ctx->buflen); if (ret <= 0) goto done; ctx->buflen -= ret; if (ctx->buflen) ctx->bufpos += ret; else { ctx->bufpos = 0; ctx->state = ASN1_STATE_DATA_COPY; } break; case ASN1_STATE_DATA_COPY: if (inl > ctx->copylen) wrmax = ctx->copylen; else wrmax = inl; ret = BIO_write(next, in, wrmax); if (ret <= 0) goto done; wrlen += ret; ctx->copylen -= ret; in += ret; inl -= ret; if (ctx->copylen == 0) ctx->state = ASN1_STATE_HEADER; if (inl == 0) goto done; break; case ASN1_STATE_POST_COPY: case ASN1_STATE_DONE: BIO_clear_retry_flags(b); return 0; } } done: BIO_clear_retry_flags(b); BIO_copy_next_retry(b); return (wrlen > 0) ? wrlen : ret; } static int asn1_bio_flush_ex(BIO *b, BIO_ASN1_BUF_CTX *ctx, asn1_ps_func *cleanup, asn1_bio_state_t next) { int ret; if (ctx->ex_len <= 0) return 1; for (;;) { ret = BIO_write(BIO_next(b), ctx->ex_buf + ctx->ex_pos, ctx->ex_len); if (ret <= 0) break; ctx->ex_len -= ret; if (ctx->ex_len > 0) ctx->ex_pos += ret; else { if (cleanup) cleanup(b, &ctx->ex_buf, &ctx->ex_len, &ctx->ex_arg); ctx->state = next; ctx->ex_pos = 0; break; } } return ret; } static int asn1_bio_setup_ex(BIO *b, BIO_ASN1_BUF_CTX *ctx, asn1_ps_func *setup, asn1_bio_state_t ex_state, asn1_bio_state_t other_state) { if (setup && !setup(b, &ctx->ex_buf, &ctx->ex_len, &ctx->ex_arg)) { BIO_clear_retry_flags(b); return 0; } if (ctx->ex_len > 0) ctx->state = ex_state; else ctx->state = other_state; return 1; } static int asn1_bio_read(BIO *b, char *in, int inl) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_read(next, in, inl); } static int asn1_bio_puts(BIO *b, const char *str) { return asn1_bio_write(b, str, strlen(str)); } static int asn1_bio_gets(BIO *b, char *str, int size) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_gets(next, str, size); } static long asn1_bio_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } static long asn1_bio_ctrl(BIO *b, int cmd, long arg1, void *arg2) { BIO_ASN1_BUF_CTX *ctx; BIO_ASN1_EX_FUNCS *ex_func; long ret = 1; BIO *next; ctx = BIO_get_data(b); if (ctx == NULL) return 0; next = BIO_next(b); switch (cmd) { case BIO_C_SET_PREFIX: ex_func = arg2; ctx->prefix = ex_func->ex_func; ctx->prefix_free = ex_func->ex_free_func; break; case BIO_C_GET_PREFIX: ex_func = arg2; ex_func->ex_func = ctx->prefix; ex_func->ex_free_func = ctx->prefix_free; break; case BIO_C_SET_SUFFIX: ex_func = arg2; ctx->suffix = ex_func->ex_func; ctx->suffix_free = ex_func->ex_free_func; break; case BIO_C_GET_SUFFIX: ex_func = arg2; ex_func->ex_func = ctx->suffix; ex_func->ex_free_func = ctx->suffix_free; break; case BIO_C_SET_EX_ARG: ctx->ex_arg = arg2; break; case BIO_C_GET_EX_ARG: *(void **)arg2 = ctx->ex_arg; break; case BIO_CTRL_FLUSH: if (next == NULL) return 0; /* Call post function if possible */ if (ctx->state == ASN1_STATE_HEADER) { if (!asn1_bio_setup_ex(b, ctx, ctx->suffix, ASN1_STATE_POST_COPY, ASN1_STATE_DONE)) return 0; } if (ctx->state == ASN1_STATE_POST_COPY) { ret = asn1_bio_flush_ex(b, ctx, ctx->suffix_free, ASN1_STATE_DONE); if (ret <= 0) return ret; } if (ctx->state == ASN1_STATE_DONE) return BIO_ctrl(next, cmd, arg1, arg2); else { BIO_clear_retry_flags(b); return 0; } default: if (next == NULL) return 0; return BIO_ctrl(next, cmd, arg1, arg2); } return ret; } static int asn1_bio_set_ex(BIO *b, int cmd, asn1_ps_func *ex_func, asn1_ps_func *ex_free_func) { BIO_ASN1_EX_FUNCS extmp; extmp.ex_func = ex_func; extmp.ex_free_func = ex_free_func; return BIO_ctrl(b, cmd, 0, &extmp); } static int asn1_bio_get_ex(BIO *b, int cmd, asn1_ps_func **ex_func, asn1_ps_func **ex_free_func) { BIO_ASN1_EX_FUNCS extmp; int ret; ret = BIO_ctrl(b, cmd, 0, &extmp); if (ret > 0) { *ex_func = extmp.ex_func; *ex_free_func = extmp.ex_free_func; } return ret; } int BIO_asn1_set_prefix(BIO *b, asn1_ps_func *prefix, asn1_ps_func *prefix_free) { return asn1_bio_set_ex(b, BIO_C_SET_PREFIX, prefix, prefix_free); } int BIO_asn1_get_prefix(BIO *b, asn1_ps_func **pprefix, asn1_ps_func **pprefix_free) { return asn1_bio_get_ex(b, BIO_C_GET_PREFIX, pprefix, pprefix_free); } int BIO_asn1_set_suffix(BIO *b, asn1_ps_func *suffix, asn1_ps_func *suffix_free) { return asn1_bio_set_ex(b, BIO_C_SET_SUFFIX, suffix, suffix_free); } int BIO_asn1_get_suffix(BIO *b, asn1_ps_func **psuffix, asn1_ps_func **psuffix_free) { return asn1_bio_get_ex(b, BIO_C_GET_SUFFIX, psuffix, psuffix_free); }
./openssl/crypto/asn1/asn1_gen.c
/* * Copyright 2002-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/asn1.h> #include <openssl/x509v3.h> #include "internal/cryptlib.h" #include "crypto/asn1.h" #define ASN1_GEN_FLAG 0x10000 #define ASN1_GEN_FLAG_IMP (ASN1_GEN_FLAG|1) #define ASN1_GEN_FLAG_EXP (ASN1_GEN_FLAG|2) #define ASN1_GEN_FLAG_TAG (ASN1_GEN_FLAG|3) #define ASN1_GEN_FLAG_BITWRAP (ASN1_GEN_FLAG|4) #define ASN1_GEN_FLAG_OCTWRAP (ASN1_GEN_FLAG|5) #define ASN1_GEN_FLAG_SEQWRAP (ASN1_GEN_FLAG|6) #define ASN1_GEN_FLAG_SETWRAP (ASN1_GEN_FLAG|7) #define ASN1_GEN_FLAG_FORMAT (ASN1_GEN_FLAG|8) #define ASN1_GEN_STR(str,val) {str, sizeof(str) - 1, val} #define ASN1_FLAG_EXP_MAX 20 /* Maximum number of nested sequences */ #define ASN1_GEN_SEQ_MAX_DEPTH 50 /* Input formats */ /* ASCII: default */ #define ASN1_GEN_FORMAT_ASCII 1 /* UTF8 */ #define ASN1_GEN_FORMAT_UTF8 2 /* Hex */ #define ASN1_GEN_FORMAT_HEX 3 /* List of bits */ #define ASN1_GEN_FORMAT_BITLIST 4 struct tag_name_st { const char *strnam; int len; int tag; }; typedef struct { int exp_tag; int exp_class; int exp_constructed; int exp_pad; long exp_len; } tag_exp_type; typedef struct { int imp_tag; int imp_class; int utype; int format; const char *str; tag_exp_type exp_list[ASN1_FLAG_EXP_MAX]; int exp_count; } tag_exp_arg; static ASN1_TYPE *generate_v3(const char *str, X509V3_CTX *cnf, int depth, int *perr); static int bitstr_cb(const char *elem, int len, void *bitstr); static int asn1_cb(const char *elem, int len, void *bitstr); static int append_exp(tag_exp_arg *arg, int exp_tag, int exp_class, int exp_constructed, int exp_pad, int imp_ok); static int parse_tagging(const char *vstart, int vlen, int *ptag, int *pclass); static ASN1_TYPE *asn1_multi(int utype, const char *section, X509V3_CTX *cnf, int depth, int *perr); static ASN1_TYPE *asn1_str2type(const char *str, int format, int utype); static int asn1_str2tag(const char *tagstr, int len); ASN1_TYPE *ASN1_generate_nconf(const char *str, CONF *nconf) { X509V3_CTX cnf; if (!nconf) return ASN1_generate_v3(str, NULL); X509V3_set_nconf(&cnf, nconf); return ASN1_generate_v3(str, &cnf); } ASN1_TYPE *ASN1_generate_v3(const char *str, X509V3_CTX *cnf) { int err = 0; ASN1_TYPE *ret = generate_v3(str, cnf, 0, &err); if (err) ERR_raise(ERR_LIB_ASN1, err); return ret; } static ASN1_TYPE *generate_v3(const char *str, X509V3_CTX *cnf, int depth, int *perr) { ASN1_TYPE *ret; tag_exp_arg asn1_tags; tag_exp_type *etmp; int i, len; unsigned char *orig_der = NULL, *new_der = NULL; const unsigned char *cpy_start; unsigned char *p; const unsigned char *cp; int cpy_len; long hdr_len = 0; int hdr_constructed = 0, hdr_tag, hdr_class; int r; asn1_tags.imp_tag = -1; asn1_tags.imp_class = -1; asn1_tags.format = ASN1_GEN_FORMAT_ASCII; asn1_tags.exp_count = 0; if (CONF_parse_list(str, ',', 1, asn1_cb, &asn1_tags) != 0) { *perr = ASN1_R_UNKNOWN_TAG; return NULL; } if ((asn1_tags.utype == V_ASN1_SEQUENCE) || (asn1_tags.utype == V_ASN1_SET)) { if (!cnf) { *perr = ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG; return NULL; } if (depth >= ASN1_GEN_SEQ_MAX_DEPTH) { *perr = ASN1_R_ILLEGAL_NESTED_TAGGING; return NULL; } ret = asn1_multi(asn1_tags.utype, asn1_tags.str, cnf, depth, perr); } else ret = asn1_str2type(asn1_tags.str, asn1_tags.format, asn1_tags.utype); if (!ret) return NULL; /* If no tagging return base type */ if ((asn1_tags.imp_tag == -1) && (asn1_tags.exp_count == 0)) return ret; /* Generate the encoding */ cpy_len = i2d_ASN1_TYPE(ret, &orig_der); ASN1_TYPE_free(ret); ret = NULL; /* Set point to start copying for modified encoding */ cpy_start = orig_der; /* Do we need IMPLICIT tagging? */ if (asn1_tags.imp_tag != -1) { /* If IMPLICIT we will replace the underlying tag */ /* Skip existing tag+len */ r = ASN1_get_object(&cpy_start, &hdr_len, &hdr_tag, &hdr_class, cpy_len); if (r & 0x80) goto err; /* Update copy length */ cpy_len -= cpy_start - orig_der; /* * For IMPLICIT tagging the length should match the original length * and constructed flag should be consistent. */ if (r & 0x1) { /* Indefinite length constructed */ hdr_constructed = 2; hdr_len = 0; } else /* Just retain constructed flag */ hdr_constructed = r & V_ASN1_CONSTRUCTED; /* * Work out new length with IMPLICIT tag: ignore constructed because * it will mess up if indefinite length */ len = ASN1_object_size(0, hdr_len, asn1_tags.imp_tag); } else len = cpy_len; /* Work out length in any EXPLICIT, starting from end */ for (i = 0, etmp = asn1_tags.exp_list + asn1_tags.exp_count - 1; i < asn1_tags.exp_count; i++, etmp--) { /* Content length: number of content octets + any padding */ len += etmp->exp_pad; etmp->exp_len = len; /* Total object length: length including new header */ len = ASN1_object_size(0, len, etmp->exp_tag); } /* Allocate buffer for new encoding */ new_der = OPENSSL_malloc(len); if (new_der == NULL) goto err; /* Generate tagged encoding */ p = new_der; /* Output explicit tags first */ for (i = 0, etmp = asn1_tags.exp_list; i < asn1_tags.exp_count; i++, etmp++) { ASN1_put_object(&p, etmp->exp_constructed, etmp->exp_len, etmp->exp_tag, etmp->exp_class); if (etmp->exp_pad) *p++ = 0; } /* If IMPLICIT, output tag */ if (asn1_tags.imp_tag != -1) { if (asn1_tags.imp_class == V_ASN1_UNIVERSAL && (asn1_tags.imp_tag == V_ASN1_SEQUENCE || asn1_tags.imp_tag == V_ASN1_SET)) hdr_constructed = V_ASN1_CONSTRUCTED; ASN1_put_object(&p, hdr_constructed, hdr_len, asn1_tags.imp_tag, asn1_tags.imp_class); } /* Copy across original encoding */ memcpy(p, cpy_start, cpy_len); cp = new_der; /* Obtain new ASN1_TYPE structure */ ret = d2i_ASN1_TYPE(NULL, &cp, len); err: OPENSSL_free(orig_der); OPENSSL_free(new_der); return ret; } static int asn1_cb(const char *elem, int len, void *bitstr) { tag_exp_arg *arg = bitstr; int i; int utype; int vlen = 0; const char *p, *vstart = NULL; int tmp_tag, tmp_class; if (elem == NULL) return -1; for (i = 0, p = elem; i < len; p++, i++) { /* Look for the ':' in name value pairs */ if (*p == ':') { vstart = p + 1; vlen = len - (vstart - elem); len = p - elem; break; } } utype = asn1_str2tag(elem, len); if (utype == -1) { ERR_raise_data(ERR_LIB_ASN1, ASN1_R_UNKNOWN_TAG, "tag=%s", elem); return -1; } /* If this is not a modifier mark end of string and exit */ if (!(utype & ASN1_GEN_FLAG)) { arg->utype = utype; arg->str = vstart; /* If no value and not end of string, error */ if (!vstart && elem[len]) { ERR_raise(ERR_LIB_ASN1, ASN1_R_MISSING_VALUE); return -1; } return 0; } switch (utype) { case ASN1_GEN_FLAG_IMP: /* Check for illegal multiple IMPLICIT tagging */ if (arg->imp_tag != -1) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_NESTED_TAGGING); return -1; } if (!parse_tagging(vstart, vlen, &arg->imp_tag, &arg->imp_class)) return -1; break; case ASN1_GEN_FLAG_EXP: if (!parse_tagging(vstart, vlen, &tmp_tag, &tmp_class)) return -1; if (!append_exp(arg, tmp_tag, tmp_class, 1, 0, 0)) return -1; break; case ASN1_GEN_FLAG_SEQWRAP: if (!append_exp(arg, V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL, 1, 0, 1)) return -1; break; case ASN1_GEN_FLAG_SETWRAP: if (!append_exp(arg, V_ASN1_SET, V_ASN1_UNIVERSAL, 1, 0, 1)) return -1; break; case ASN1_GEN_FLAG_BITWRAP: if (!append_exp(arg, V_ASN1_BIT_STRING, V_ASN1_UNIVERSAL, 0, 1, 1)) return -1; break; case ASN1_GEN_FLAG_OCTWRAP: if (!append_exp(arg, V_ASN1_OCTET_STRING, V_ASN1_UNIVERSAL, 0, 0, 1)) return -1; break; case ASN1_GEN_FLAG_FORMAT: if (!vstart) { ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_FORMAT); return -1; } if (HAS_PREFIX(vstart, "ASCII")) arg->format = ASN1_GEN_FORMAT_ASCII; else if (HAS_PREFIX(vstart, "UTF8")) arg->format = ASN1_GEN_FORMAT_UTF8; else if (HAS_PREFIX(vstart, "HEX")) arg->format = ASN1_GEN_FORMAT_HEX; else if (HAS_PREFIX(vstart, "BITLIST")) arg->format = ASN1_GEN_FORMAT_BITLIST; else { ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_FORMAT); return -1; } break; } return 1; } static int parse_tagging(const char *vstart, int vlen, int *ptag, int *pclass) { long tag_num; char *eptr; if (!vstart) return 0; tag_num = strtoul(vstart, &eptr, 10); /* Check we haven't gone past max length: should be impossible */ if (eptr && *eptr && (eptr > vstart + vlen)) return 0; if (tag_num < 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_NUMBER); return 0; } *ptag = tag_num; /* If we have non numeric characters, parse them */ if (eptr) vlen -= eptr - vstart; else vlen = 0; if (vlen) { switch (*eptr) { case 'U': *pclass = V_ASN1_UNIVERSAL; break; case 'A': *pclass = V_ASN1_APPLICATION; break; case 'P': *pclass = V_ASN1_PRIVATE; break; case 'C': *pclass = V_ASN1_CONTEXT_SPECIFIC; break; default: ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_MODIFIER, "Char=%c", *eptr); return 0; } } else *pclass = V_ASN1_CONTEXT_SPECIFIC; return 1; } /* Handle multiple types: SET and SEQUENCE */ static ASN1_TYPE *asn1_multi(int utype, const char *section, X509V3_CTX *cnf, int depth, int *perr) { ASN1_TYPE *ret = NULL; STACK_OF(ASN1_TYPE) *sk = NULL; STACK_OF(CONF_VALUE) *sect = NULL; unsigned char *der = NULL; int derlen; int i; sk = sk_ASN1_TYPE_new_null(); if (!sk) goto bad; if (section) { if (!cnf) goto bad; sect = X509V3_get_section(cnf, (char *)section); if (!sect) goto bad; for (i = 0; i < sk_CONF_VALUE_num(sect); i++) { ASN1_TYPE *typ = generate_v3(sk_CONF_VALUE_value(sect, i)->value, cnf, depth + 1, perr); if (!typ) goto bad; if (!sk_ASN1_TYPE_push(sk, typ)) goto bad; } } /* * Now we has a STACK of the components, convert to the correct form */ if (utype == V_ASN1_SET) derlen = i2d_ASN1_SET_ANY(sk, &der); else derlen = i2d_ASN1_SEQUENCE_ANY(sk, &der); if (derlen < 0) goto bad; if ((ret = ASN1_TYPE_new()) == NULL) goto bad; if ((ret->value.asn1_string = ASN1_STRING_type_new(utype)) == NULL) goto bad; ret->type = utype; ret->value.asn1_string->data = der; ret->value.asn1_string->length = derlen; der = NULL; bad: OPENSSL_free(der); sk_ASN1_TYPE_pop_free(sk, ASN1_TYPE_free); X509V3_section_free(cnf, sect); return ret; } static int append_exp(tag_exp_arg *arg, int exp_tag, int exp_class, int exp_constructed, int exp_pad, int imp_ok) { tag_exp_type *exp_tmp; /* Can only have IMPLICIT if permitted */ if ((arg->imp_tag != -1) && !imp_ok) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_IMPLICIT_TAG); return 0; } if (arg->exp_count == ASN1_FLAG_EXP_MAX) { ERR_raise(ERR_LIB_ASN1, ASN1_R_DEPTH_EXCEEDED); return 0; } exp_tmp = &arg->exp_list[arg->exp_count++]; /* * If IMPLICIT set tag to implicit value then reset implicit tag since it * has been used. */ if (arg->imp_tag != -1) { exp_tmp->exp_tag = arg->imp_tag; exp_tmp->exp_class = arg->imp_class; arg->imp_tag = -1; arg->imp_class = -1; } else { exp_tmp->exp_tag = exp_tag; exp_tmp->exp_class = exp_class; } exp_tmp->exp_constructed = exp_constructed; exp_tmp->exp_pad = exp_pad; return 1; } static int asn1_str2tag(const char *tagstr, int len) { unsigned int i; static const struct tag_name_st *tntmp, tnst[] = { ASN1_GEN_STR("BOOL", V_ASN1_BOOLEAN), ASN1_GEN_STR("BOOLEAN", V_ASN1_BOOLEAN), ASN1_GEN_STR("NULL", V_ASN1_NULL), ASN1_GEN_STR("INT", V_ASN1_INTEGER), ASN1_GEN_STR("INTEGER", V_ASN1_INTEGER), ASN1_GEN_STR("ENUM", V_ASN1_ENUMERATED), ASN1_GEN_STR("ENUMERATED", V_ASN1_ENUMERATED), ASN1_GEN_STR("OID", V_ASN1_OBJECT), ASN1_GEN_STR("OBJECT", V_ASN1_OBJECT), ASN1_GEN_STR("UTCTIME", V_ASN1_UTCTIME), ASN1_GEN_STR("UTC", V_ASN1_UTCTIME), ASN1_GEN_STR("GENERALIZEDTIME", V_ASN1_GENERALIZEDTIME), ASN1_GEN_STR("GENTIME", V_ASN1_GENERALIZEDTIME), ASN1_GEN_STR("OCT", V_ASN1_OCTET_STRING), ASN1_GEN_STR("OCTETSTRING", V_ASN1_OCTET_STRING), ASN1_GEN_STR("BITSTR", V_ASN1_BIT_STRING), ASN1_GEN_STR("BITSTRING", V_ASN1_BIT_STRING), ASN1_GEN_STR("UNIVERSALSTRING", V_ASN1_UNIVERSALSTRING), ASN1_GEN_STR("UNIV", V_ASN1_UNIVERSALSTRING), ASN1_GEN_STR("IA5", V_ASN1_IA5STRING), ASN1_GEN_STR("IA5STRING", V_ASN1_IA5STRING), ASN1_GEN_STR("UTF8", V_ASN1_UTF8STRING), ASN1_GEN_STR("UTF8String", V_ASN1_UTF8STRING), ASN1_GEN_STR("BMP", V_ASN1_BMPSTRING), ASN1_GEN_STR("BMPSTRING", V_ASN1_BMPSTRING), ASN1_GEN_STR("VISIBLESTRING", V_ASN1_VISIBLESTRING), ASN1_GEN_STR("VISIBLE", V_ASN1_VISIBLESTRING), ASN1_GEN_STR("PRINTABLESTRING", V_ASN1_PRINTABLESTRING), ASN1_GEN_STR("PRINTABLE", V_ASN1_PRINTABLESTRING), ASN1_GEN_STR("T61", V_ASN1_T61STRING), ASN1_GEN_STR("T61STRING", V_ASN1_T61STRING), ASN1_GEN_STR("TELETEXSTRING", V_ASN1_T61STRING), ASN1_GEN_STR("GeneralString", V_ASN1_GENERALSTRING), ASN1_GEN_STR("GENSTR", V_ASN1_GENERALSTRING), ASN1_GEN_STR("NUMERIC", V_ASN1_NUMERICSTRING), ASN1_GEN_STR("NUMERICSTRING", V_ASN1_NUMERICSTRING), /* Special cases */ ASN1_GEN_STR("SEQUENCE", V_ASN1_SEQUENCE), ASN1_GEN_STR("SEQ", V_ASN1_SEQUENCE), ASN1_GEN_STR("SET", V_ASN1_SET), /* type modifiers */ /* Explicit tag */ ASN1_GEN_STR("EXP", ASN1_GEN_FLAG_EXP), ASN1_GEN_STR("EXPLICIT", ASN1_GEN_FLAG_EXP), /* Implicit tag */ ASN1_GEN_STR("IMP", ASN1_GEN_FLAG_IMP), ASN1_GEN_STR("IMPLICIT", ASN1_GEN_FLAG_IMP), /* OCTET STRING wrapper */ ASN1_GEN_STR("OCTWRAP", ASN1_GEN_FLAG_OCTWRAP), /* SEQUENCE wrapper */ ASN1_GEN_STR("SEQWRAP", ASN1_GEN_FLAG_SEQWRAP), /* SET wrapper */ ASN1_GEN_STR("SETWRAP", ASN1_GEN_FLAG_SETWRAP), /* BIT STRING wrapper */ ASN1_GEN_STR("BITWRAP", ASN1_GEN_FLAG_BITWRAP), ASN1_GEN_STR("FORM", ASN1_GEN_FLAG_FORMAT), ASN1_GEN_STR("FORMAT", ASN1_GEN_FLAG_FORMAT), }; if (len == -1) len = strlen(tagstr); tntmp = tnst; for (i = 0; i < OSSL_NELEM(tnst); i++, tntmp++) { if ((len == tntmp->len) && (OPENSSL_strncasecmp(tntmp->strnam, tagstr, len) == 0)) return tntmp->tag; } return -1; } static ASN1_TYPE *asn1_str2type(const char *str, int format, int utype) { ASN1_TYPE *atmp = NULL; CONF_VALUE vtmp; unsigned char *rdata; long rdlen; int no_unused = 1; if ((atmp = ASN1_TYPE_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); return NULL; } if (!str) str = ""; switch (utype) { case V_ASN1_NULL: if (str && *str) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_NULL_VALUE); goto bad_form; } break; case V_ASN1_BOOLEAN: if (format != ASN1_GEN_FORMAT_ASCII) { ERR_raise(ERR_LIB_ASN1, ASN1_R_NOT_ASCII_FORMAT); goto bad_form; } vtmp.name = NULL; vtmp.section = NULL; vtmp.value = (char *)str; if (!X509V3_get_value_bool(&vtmp, &atmp->value.boolean)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_BOOLEAN); goto bad_str; } break; case V_ASN1_INTEGER: case V_ASN1_ENUMERATED: if (format != ASN1_GEN_FORMAT_ASCII) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INTEGER_NOT_ASCII_FORMAT); goto bad_form; } if ((atmp->value.integer = s2i_ASN1_INTEGER(NULL, str)) == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_INTEGER); goto bad_str; } break; case V_ASN1_OBJECT: if (format != ASN1_GEN_FORMAT_ASCII) { ERR_raise(ERR_LIB_ASN1, ASN1_R_OBJECT_NOT_ASCII_FORMAT); goto bad_form; } if ((atmp->value.object = OBJ_txt2obj(str, 0)) == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_OBJECT); goto bad_str; } break; case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: if (format != ASN1_GEN_FORMAT_ASCII) { ERR_raise(ERR_LIB_ASN1, ASN1_R_TIME_NOT_ASCII_FORMAT); goto bad_form; } if ((atmp->value.asn1_string = ASN1_STRING_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto bad_str; } if (!ASN1_STRING_set(atmp->value.asn1_string, str, -1)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto bad_str; } atmp->value.asn1_string->type = utype; if (!ASN1_TIME_check(atmp->value.asn1_string)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_TIME_VALUE); goto bad_str; } break; case V_ASN1_BMPSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_IA5STRING: case V_ASN1_T61STRING: case V_ASN1_UTF8STRING: case V_ASN1_VISIBLESTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_GENERALSTRING: case V_ASN1_NUMERICSTRING: if (format == ASN1_GEN_FORMAT_ASCII) format = MBSTRING_ASC; else if (format == ASN1_GEN_FORMAT_UTF8) format = MBSTRING_UTF8; else { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_FORMAT); goto bad_form; } if (ASN1_mbstring_copy(&atmp->value.asn1_string, (unsigned char *)str, -1, format, ASN1_tag2bit(utype)) <= 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto bad_str; } break; case V_ASN1_BIT_STRING: case V_ASN1_OCTET_STRING: if ((atmp->value.asn1_string = ASN1_STRING_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto bad_form; } if (format == ASN1_GEN_FORMAT_HEX) { if ((rdata = OPENSSL_hexstr2buf(str, &rdlen)) == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_HEX); goto bad_str; } atmp->value.asn1_string->data = rdata; atmp->value.asn1_string->length = rdlen; atmp->value.asn1_string->type = utype; } else if (format == ASN1_GEN_FORMAT_ASCII) { if (!ASN1_STRING_set(atmp->value.asn1_string, str, -1)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto bad_str; } } else if ((format == ASN1_GEN_FORMAT_BITLIST) && (utype == V_ASN1_BIT_STRING)) { if (!CONF_parse_list (str, ',', 1, bitstr_cb, atmp->value.bit_string)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_LIST_ERROR); goto bad_str; } no_unused = 0; } else { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_BITSTRING_FORMAT); goto bad_form; } if ((utype == V_ASN1_BIT_STRING) && no_unused) ossl_asn1_string_set_bits_left(atmp->value.asn1_string, 0); break; default: ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_TYPE); goto bad_str; } atmp->type = utype; return atmp; bad_str: ERR_add_error_data(2, "string=", str); bad_form: ASN1_TYPE_free(atmp); return NULL; } static int bitstr_cb(const char *elem, int len, void *bitstr) { long bitnum; char *eptr; if (!elem) return 0; bitnum = strtoul(elem, &eptr, 10); if (eptr && *eptr && (eptr != elem + len)) return 0; if (bitnum < 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_NUMBER); return 0; } if (!ASN1_BIT_STRING_set_bit(bitstr, bitnum, 1)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); return 0; } return 1; } static int mask_cb(const char *elem, int len, void *arg) { unsigned long *pmask = arg, tmpmask; int tag; if (elem == NULL) return 0; if (len == 3 && HAS_PREFIX(elem, "DIR")) { *pmask |= B_ASN1_DIRECTORYSTRING; return 1; } tag = asn1_str2tag(elem, len); if (!tag || (tag & ASN1_GEN_FLAG)) return 0; tmpmask = ASN1_tag2bit(tag); if (!tmpmask) return 0; *pmask |= tmpmask; return 1; } int ASN1_str2mask(const char *str, unsigned long *pmask) { *pmask = 0; return CONF_parse_list(str, '|', 1, mask_cb, pmask); }
./openssl/crypto/asn1/tbl_standard.h
/* * Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* size limits: this stuff is taken straight from RFC3280 */ #define ub_name 32768 #define ub_common_name 64 #define ub_locality_name 128 #define ub_state_name 128 #define ub_organization_name 64 #define ub_organization_unit_name 64 #define ub_title 64 #define ub_email_address 128 #define ub_serial_number 64 /* From RFC4524 */ #define ub_rfc822_mailbox 256 /* This table must be kept in NID order */ static const ASN1_STRING_TABLE tbl_standard[] = { {NID_commonName, 1, ub_common_name, DIRSTRING_TYPE, 0}, {NID_countryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, {NID_localityName, 1, ub_locality_name, DIRSTRING_TYPE, 0}, {NID_stateOrProvinceName, 1, ub_state_name, DIRSTRING_TYPE, 0}, {NID_organizationName, 1, ub_organization_name, DIRSTRING_TYPE, 0}, {NID_organizationalUnitName, 1, ub_organization_unit_name, DIRSTRING_TYPE, 0}, {NID_pkcs9_emailAddress, 1, ub_email_address, B_ASN1_IA5STRING, STABLE_NO_MASK}, {NID_pkcs9_unstructuredName, 1, -1, PKCS9STRING_TYPE, 0}, {NID_pkcs9_challengePassword, 1, -1, PKCS9STRING_TYPE, 0}, {NID_pkcs9_unstructuredAddress, 1, -1, DIRSTRING_TYPE, 0}, {NID_givenName, 1, ub_name, DIRSTRING_TYPE, 0}, {NID_surname, 1, ub_name, DIRSTRING_TYPE, 0}, {NID_initials, 1, ub_name, DIRSTRING_TYPE, 0}, {NID_serialNumber, 1, ub_serial_number, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, {NID_friendlyName, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}, {NID_name, 1, ub_name, DIRSTRING_TYPE, 0}, {NID_dnQualifier, -1, -1, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, {NID_domainComponent, 1, -1, B_ASN1_IA5STRING, STABLE_NO_MASK}, {NID_ms_csp_name, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}, {NID_rfc822Mailbox, 1, ub_rfc822_mailbox, B_ASN1_IA5STRING, STABLE_NO_MASK}, {NID_jurisdictionCountryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, {NID_INN, 1, 12, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, {NID_OGRN, 1, 13, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, {NID_SNILS, 1, 11, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, {NID_countryCode3c, 3, 3, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, {NID_countryCode3n, 3, 3, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, {NID_dnsName, 0, -1, B_ASN1_UTF8STRING, STABLE_NO_MASK}, {NID_id_on_SmtpUTF8Mailbox, 1, ub_email_address, B_ASN1_UTF8STRING, STABLE_NO_MASK} };