code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup crypt_types * @ingroup crypt * @brief types of crypto */ #ifndef CRYPT_TYPES_H #define CRYPT_TYPES_H #include <stdint.h> #include <stddef.h> #include "crypt_algid.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus /** * @ingroup crypt_types * * Data structure */ typedef struct { uint8_t *data; /**< Data content */ uint32_t len; /**< Data length */ } CRYPT_Data; /** * @ingroup crypt_types * * Constant data structure */ typedef struct { const uint8_t *data; uint32_t len; } CRYPT_ConstData; /** * @ingroup crypt_types * * Data range */ typedef struct { uint32_t min; /**< Minimum value */ uint32_t max; /**< Maximum value */ } CRYPT_Range; /** * @ingroup crypt_types * * @brief Pkcsv15 padding mode, when RSA is used for signature. */ typedef struct { CRYPT_MD_AlgId mdId; /**< ID of the hash algorithm during pkcsv15 padding */ } CRYPT_RSA_PkcsV15Para; /** * @ingroup crypt_types * * RSA salt length type, when rsa pss mode is used for signature and verify */ typedef enum { // When the padding type is PSS, the salt data is obtained by the DRBG and the length is hashlen. CRYPT_RSA_SALTLEN_TYPE_HASHLEN = -1, // When the padding type is PSS, the salt data is obtained by the DRBG. // and the length is padLen - mdMethod->GetDigestSize - 2 CRYPT_RSA_SALTLEN_TYPE_MAXLEN = -2, // get salt length from signature, only used verify. CRYPT_RSA_SALTLEN_TYPE_AUTOLEN = -3 } CRYPT_RSA_SaltLenType; /** * @ingroup crypt_types * * PSS padding mode, when RSA is used for signature. */ typedef struct { int32_t saltLen; /**< pss salt length. enum values defined by CRYPT_RSA_SaltLenType or actual value. */ CRYPT_MD_AlgId mdId; /**< mdid when pss padding. */ CRYPT_MD_AlgId mgfId; /**< mgfid when pss padding. */ } CRYPT_RSA_PssPara; typedef struct { CRYPT_MD_AlgId mdId; /**< mdid when oaep padding */ CRYPT_MD_AlgId mgfId; /**< mgfid when oaep padding */ } CRYPT_RSA_OaepPara; typedef enum { CRYPT_RSA_BLINDING = 0x00000001, /**< Enable the RSA blinding function for signature. */ CRYPT_RSA_BSSA = 0x00000002, /**< The signature process is rsa blind signature. */ CRYPT_RSA_MAXFLAG } CRYPT_RSA_Flag; typedef enum { CRYPT_DH_NO_PADZERO = 0x00000001, /**< Follow the standard RFC 5246, remove the prefix-0 when cal the shared key. It takes effect only after local settings are made. */ CRYPT_DH_MAXFLAG } CRYPT_DH_Flag; /** * @ingroup crypt_types * * RSA private key parameter structure */ typedef struct { uint8_t *d; /**< RSA private key parameter marked as d. */ uint8_t *n; /**< RSA private key parameter marked as n. */ uint8_t *p; /**< RSA private key parameter marked as p. */ uint8_t *q; /**< RSA private key parameter marked as q. */ uint8_t *dP; /**< RSA private key parameter marked as dP. */ uint8_t *dQ; /**< RSA private key parameter marked as dQ. */ uint8_t *qInv; /**< RSA private key parameter marked as qInv. */ uint8_t *e; /**< RSA public key parameter marked as e. */ uint32_t dLen; /**< Length of the RSA private key parameter marked as d. */ uint32_t nLen; /**< Length of the RSA private key parameter marked as n. */ uint32_t pLen; /**< Length of the RSA private key parameter marked as p. */ uint32_t qLen; /**< Length of the RSA private key parameter marked as q. */ uint32_t dPLen; /**< Length of the RSA private key parameter marked as dPLen. */ uint32_t dQLen; /**< Length of the RSA private key parameter marked as dQLen. */ uint32_t qInvLen; /**< Length of the RSA private key parameter marked as qInvLen. */ uint32_t eLen; /**< Length of the RSA public key parameter marked as eLen. */ } CRYPT_RsaPrv; /** * @ingroup crypt_types * * Elliptic curve parameter information */ typedef struct { uint8_t *p; uint8_t *a; uint8_t *b; uint8_t *n; uint8_t *h; uint8_t *x; uint8_t *y; uint32_t pLen; uint32_t aLen; uint32_t bLen; uint32_t nLen; uint32_t hLen; uint32_t xLen; uint32_t yLen; } CRYPT_EccPara; /** * @ingroup crypt_types * * Paillier private key parameter structure */ typedef struct { uint8_t *n; /**< Paillier private key parameter marked as n */ uint8_t *lambda; /**< Paillier private key parameter marked as lambda */ uint8_t *mu; /**< Paillier private key parameter marked as mu */ uint8_t *n2; /**< Paillier private key parameter marked as n2 */ uint32_t nLen; /**< Length of the Paillier private key parameter marked as n */ uint32_t lambdaLen; /**< Length of the Paillier private key parameter marked as lambda */ uint32_t muLen; /**< Length of the Paillier private key parameter marked as mu */ uint32_t n2Len; /**< Length of the Paillier private key parameter marked as n2 */ } CRYPT_PaillierPrv; typedef struct { /* Initialization parameters of the noise source */ void *para; /* Noise Source Initialization Interface */ void *(*init)(void *para); /* Noise source read interface,can't be NULL */ int32_t (*read)(void *ctx, uint32_t timeout, uint8_t *buf, uint32_t bufLen); /* Noise Source Deinitialization Interface */ void (*deinit)(void *ctx); } CRYPT_EAL_NsMethod; typedef struct { /* Repetition Count Test: the cutoff value C */ uint32_t rctCutoff; /* Adaptive Proportion Test: the cutoff value C */ uint32_t aptCutoff; /* Adaptive Proportion Test: the window size W * see nist.sp.800-90b section 4.4.2 * The window size W is selected based on the alphabet size, and shall be assigned to 1024 * if the noise source is binary (that is, the noise source produces only two distinct values) and 512 if * the noise source is not binary (that is, the noise source produces more than two distinct values). */ uint32_t aptWinSize; } CRYPT_EAL_NsTestPara; typedef struct { /* Noise source name, which must be unique. */ const char *name; /* Whether the noise source automatically performs the health test */ bool autoTest; /* Minimum entropy, that is, the number of bits of entropy for a byte */ uint32_t minEntropy; CRYPT_EAL_NsMethod nsMeth; CRYPT_EAL_NsTestPara nsPara; } CRYPT_EAL_NsPara; /** * @ingroup crypt_types * @brief Entropy source callback for obtaining entropy data. * * @param ctx [IN] the entropy source handle. * @param buf [OUT] buffer. * @param bufLen [IN] the length of buffer. * @return 0, success * Other error codes */ typedef uint32_t (*CRYPT_EAL_EntropyGet)(void *ctx, uint8_t *buf, uint32_t bufLen); typedef struct { /* Whether Physical Entropy Source. */ bool isPhysical; /* minimum entropy, (0, 8]. */ uint32_t minEntropy; /* entropy source handle */ void *entropyCtx; CRYPT_EAL_EntropyGet entropyGet; } CRYPT_EAL_EsPara; /** * @ingroup crypt_types * * ElGamal private key parameter structure */ typedef struct { uint8_t *p; /**< ElGamal private key parameter marked as p */ uint8_t *g; /**< ElGamal private key parameter marked as g */ uint8_t *x; /**< ElGamal private key parameter marked as x */ uint32_t pLen; /**< Length of the ElGamal private key parameter marked as p */ uint32_t gLen; /**< Length of the ElGamal private key parameter marked as g */ uint32_t xLen; /**< Length of the ElGamal private key parameter marked as x */ } CRYPT_ElGamalPrv; /** * @ingroup crypt_types * * DSA private key parameter structure */ typedef CRYPT_Data CRYPT_DsaPrv; /** * @ingroup crypt_types * * ECC private key parameter structure. */ typedef CRYPT_Data CRYPT_EccPrv; /** * @ingroup crypt_types * * ECDSA private key parameter structure. */ typedef CRYPT_Data CRYPT_EcdsaPrv; /** * @ingroup crypt_types * * SM2 private key parameter structure */ typedef CRYPT_Data CRYPT_Sm2Prv; /** * @ingroup crypt_types * * DH private key parameter structure */ typedef CRYPT_Data CRYPT_DhPrv; /** * @ingroup crypt_types * * ECDH private key parameter structure */ typedef CRYPT_Data CRYPT_EcdhPrv; /** * @ingroup crypt_types * * ed25519/x25519 private key parameter structure */ typedef CRYPT_Data CRYPT_Curve25519Prv; /** * @ingroup crypt_types * * kem decaps key parameter structure */ typedef CRYPT_Data CRYPT_KemDecapsKey; /** * @ingroup crypt_types * * MLDSA private key parameter structure */ typedef CRYPT_Data CRYPT_MlDsaPrv; /** * @ingroup crypt_types * * RSA public key parameter structure */ typedef struct { uint8_t *e; /**< RSA public key parameter marked as e */ uint8_t *n; /**< RSA public key parameter marked as n */ uint32_t eLen; /**< Length of the RSA public key parameter marked as e*/ uint32_t nLen; /**< Length of the RSA public key parameter marked as e*/ } CRYPT_RsaPub; /** * @ingroup crypt_types * * Paillier public key parameter structure */ typedef struct { uint8_t *n; /**< Paillier public key parameter marked as n */ uint8_t *g; /**< Paillier public key parameter marked as g */ uint8_t *n2; /**< Paillier public key parameter marked as n2 */ uint32_t nLen; /**< Length of the Paillier public key parameter marked as n */ uint32_t gLen; /**< Length of the Paillier public key parameter marked as g */ uint32_t n2Len; /**< Length of the Paillier public key parameter marked as n2 */ } CRYPT_PaillierPub; /** * @brief SLH-DSA public key structure */ typedef struct { uint8_t *seed; // Seed for generating keys uint8_t *root; // Root node of the top XMSS tree uint32_t len; // key length } CRYPT_SlhDsaPub; /** * @brief SLH-DSA private key structure */ typedef struct { uint8_t *seed; // Seed for generating keys uint8_t *prf; // To generate randomization value CRYPT_SlhDsaPub pub; // pubkey } CRYPT_SlhDsaPrv; /** * @brief XMSS public key structure */ typedef CRYPT_SlhDsaPub CRYPT_XmssPub; /** * @brief XMSS private key structure */ typedef struct { uint8_t *seed; // Seed for generating keys uint8_t *prf; // To generate randomization value uint64_t index; // ots key index CRYPT_XmssPub pub; // pubkey } CRYPT_XmssPrv; /** * @ingroup crypt_types * * ElGamal public key parameter structure */ typedef struct { uint8_t *p; /**< ElGamal public key parameter marked as p */ uint8_t *g; /**< ElGamal public key parameter marked as g */ uint8_t *y; /**< ElGamal public key parameter marked as y */ uint8_t *q; /**< ElGamal public key parameter marked as q */ uint32_t pLen; /**< Length of the ElGamal public key parameter marked as p */ uint32_t gLen; /**< Length of the ElGamal public key parameter marked as g */ uint32_t yLen; /**< Length of the ElGamal public key parameter marked as y */ uint32_t qLen; /**< Length of the ElGamal public key parameter marked as q */ } CRYPT_ElGamalPub; /** * @ingroup crypt_types * * DSA public key parameter structure */ typedef CRYPT_Data CRYPT_DsaPub; /** * @ingroup crypt_types * * ECC public key parameter structure */ typedef CRYPT_Data CRYPT_EccPub; /** * @ingroup crypt_types * * ECDSA public key parameter structure. */ typedef CRYPT_Data CRYPT_EcdsaPub; /** * @ingroup crypt_types * * SM2 public key parameter structure */ typedef CRYPT_Data CRYPT_Sm2Pub; /** * @ingroup crypt_types * * DH public key parameter structure */ typedef CRYPT_Data CRYPT_DhPub; /** * @ingroup crypt_types * * ECDH public key parameter structure */ typedef CRYPT_Data CRYPT_EcdhPub; /** * @ingroup crypt_types * * ed25519/x25519 public key parameter structure */ typedef CRYPT_Data CRYPT_Curve25519Pub; /** * @ingroup crypt_types * * kem encaps key parameter structure */ typedef CRYPT_Data CRYPT_KemEncapsKey; /** * @ingroup crypt_types * * MLDSA public key parameter structure */ typedef CRYPT_Data CRYPT_MlDsaPub; /** * @ingroup crypt_types * * Para structure of the RSA algorithm */ typedef struct { /**< This parameter cannot be NULL and is determined by the underlying structure. */ uint8_t *e; /**< Para Parameter e */ uint32_t eLen; /**< Length of para e*/ uint32_t bits; /**< Bits of para, FIPS 186-5 dose not support generation and use of keys with odd bits. */ } CRYPT_RsaPara; /** * @ingroup crypt_types * * Para structure of the DSA algorithm. This parameter cannot be null, and it is determined by the underlying structure. */ typedef struct { uint8_t *p; /**< Parameter p */ uint8_t *q; /**< Parameter q */ uint8_t *g; /**< Parameter g */ uint32_t pLen; /**< Length of parameter p*/ uint32_t qLen; /**< Length of parameter q*/ uint32_t gLen; /**< Length of parameter g*/ } CRYPT_DsaPara; /** * @ingroup crypt_types * * Para structure of the DH algorithm */ typedef struct { uint8_t *p; /**< Parameter p. */ uint8_t *q; /**< Parameter q, the parameter can be NULL. */ uint8_t *g; /**< Parameter g. */ uint32_t pLen; /**< Length of parameter p. */ uint32_t qLen; /**< Length of parameter q. */ uint32_t gLen; /**< Length of parameter g. */ } CRYPT_DhPara; /** * @ingroup crypt_types * * Para structure of the Paillier algorithm */ typedef struct { uint8_t *p; /**< Parameter p. */ uint8_t *q; /**< Parameter q. */ uint32_t pLen; /**< Length of parameter p. */ uint32_t qLen; /**< Length of parameter q. */ uint32_t bits; /**< Bits of para. */ } CRYPT_PaillierPara; /** * @ingroup crypt_types * * Para structure of the ElGamal algorithm */ typedef struct { uint8_t *q; /**< Parameter q. */ uint32_t qLen; /**< Length of parameter q. */ uint32_t bits; /**< Bits of para. */ uint32_t k_bits; /**< Bits of q. */ } CRYPT_ElGamalPara; /** * @ingroup crypt_types * * Obtain the entropy source. If the default entropy source provided by HiTLS is not used, * the API must be registered. the output data must meet requirements such as the length. * The HiTLS does not check the entropy source. The data must be provided by the entropy source. * * @param ctx [IN] Context used by the caller. * @param entropy [OUT] Indicates the obtained entropy source data. The length of the entropy source data * must meet the following requirements: lenRange->min <= len <= lenRange->max. * @param strength [IN] Entropy source strength. * @param lenRange [IN] Entropy source length range. * @retval 0 indicates success, and other values indicate failure. */ typedef int32_t (*CRYPT_EAL_GetEntropyCb)(void *ctx, CRYPT_Data *entropy, uint32_t strength, CRYPT_Range *lenRange); /** * @ingroup crypt_types * @brief The entropy source memory is cleared, this API is optional. * @param ctx [IN] Context used by the caller * @param entropy [OUT] Entropy source data * @retval void */ typedef void (*CRYPT_EAL_CleanEntropyCb)(void *ctx, CRYPT_Data *entropy); /** * @ingroup crypt_types * @brief Obtain the random number. This API is not need to registered. * For registration, the output data must meet requirements such as the length. * The HiTLS does not check the entropy source, but will implement if provide the function. * * @param ctx [IN] Context used by the caller * @param nonce [OUT] Obtained random number. * The length of the random number must be lenRange->min <= len <= lenRange->max. * @param strength [IN]: Random number strength * @param lenRange [IN] Random number length range. * @retval 0 indicates success, and other values indicate failure. */ typedef int32_t (*CRYPT_EAL_GetNonceCb)(void *ctx, CRYPT_Data *nonce, uint32_t strength, CRYPT_Range *lenRange); /** * @ingroup crypt_types * @brief Random number memory clearance. this API is optional. * @param ctx [IN] Context used by the caller * @param nonce [OUT] random number * @retval void */ typedef void (*CRYPT_EAL_CleanNonceCb)(void *ctx, CRYPT_Data *nonce); /** * @ingroup crypt_types * * Metohd structure of the RAND registration interface, including the entropy source obtaining and clearing * interface and random number obtaining and clearing interface. * For details about how to use the default entropy source of the HiTLS, see CRYPT_EAL_RandInit(). * If the default mode is not used, the entropy source obtaining interface cannot be null, interface for * obtaining random numbers can be null. */ typedef struct { CRYPT_EAL_GetEntropyCb getEntropy; CRYPT_EAL_CleanEntropyCb cleanEntropy; CRYPT_EAL_GetNonceCb getNonce; CRYPT_EAL_CleanNonceCb cleanNonce; } CRYPT_RandSeedMethod; /** * @ingroup crypt_ctrl_param * * Set and obtain internal mode parameters. */ typedef enum { CRYPT_CTRL_SET_IV = 0, /**< Set IV data, the data type is uint8_t type.. */ CRYPT_CTRL_GET_IV, /**< Obtains the IV data, the data type is uint8_t type. */ CRYPT_CTRL_GET_BLOCKSIZE, /**< Obtain the block size, the data type is uint8_t type. */ CRYPT_CTRL_SET_COUNT, /**< Set the counter information, the input is a four-byte little-endian byte stream, the algorithm required is chacha20. */ CRYPT_CTRL_SET_AAD, /**< Set the ADD information in AEAD encryption and decryption mode. */ CRYPT_CTRL_GET_TAG, /**< Obtain the tag at the end in AEAD encryption or decryption. */ CRYPT_CTRL_SET_TAGLEN, /**< Set the tag length before the encryption/decryption starts in AEAD encryption/decryption. the setting type is uint32_t. */ CRYPT_CTRL_SET_MSGLEN, /**< In CMM mode, the length of the encrypted message needs to be used as the input for calculation. the length must be set before SET_AAD. The input data type is int64_t. */ CRYPT_CTRL_SET_FEEDBACKSIZE, /**< Setting the ciphertext feedback length in CFB mode. */ CRYPT_CTRL_GET_FEEDBACKSIZE, /**< Obtaining the ciphertext feedback length in CFB mode. */ CRYPT_CTRL_DES_NOKEYCHECK, /**< DES does not verify the key. */ CRYPT_CTRL_SET_PADDING, /**< Set the padding mode of the algorithm. */ CRYPT_CTRL_GET_PADDING, /**< Obtain the padding mode of thealgorithm. */ CRYPT_CTRL_REINIT_STATUS, /**< Reinitialize the status of the algorithm. */ CRYPT_CTRL_MAX } CRYPT_CipherCtrl; /** * @ingroup crypt_ctrl_param * * Set and obtain internal parameters of pkey. */ typedef enum { // common CRYPT_CTRL_UP_REFERENCES = 0, /**< The reference count value increases automatically. It is applicable to asymmetric algorithms such as 25519, RSA, and ECC. */ CRYPT_CTRL_SET_PARA_BY_ID, /* Asymmetric cipher set para by id. */ CRYPT_CTRL_SET_NO_PADDING, /**< RSA Set the padding mode to NO_PADDING. */ CRYPT_CTRL_GET_PARA, /* Asymmetric cipher get para. */ CRYPT_CTRL_GET_PARAID, /* Asymmetric cipher get id of para. */ CRYPT_CTRL_GET_BITS, /* Asymmetric cipher get bits . */ CRYPT_CTRL_GET_SIGNLEN, /* Asymmetric cipher get signlen . */ CRYPT_CTRL_GET_SECBITS, /* Asymmetric cipher get secure bits . */ CRYPT_CTRL_GET_SHARED_KEY_LEN, /**< Get the shared key length */ CRYPT_CTRL_GET_PUBKEY_LEN, /**< Get the encapsulation key length */ CRYPT_CTRL_GET_PRVKEY_LEN, /**< Get the decapsulation key length */ CRYPT_CTRL_GET_CIPHERTEXT_LEN, /**< Get the ciphertext length */ CRYPT_CTRL_SET_DETERMINISTIC_FLAG, /**< Whether to use deterministic signatures */ CRYPT_CTRL_SET_CTX_INFO, /**< Set the context string. */ CRYPT_CTRL_SET_PREHASH_FLAG, /**< Change the SLH-DSA or ML-DSA mode to prehash version or pure version. */ CRYPT_CTRL_GEN_PARA, /**< Asymmetric cipher generate para. */ CRYPT_CTRL_SET_GEN_FLAG, /**< Set SP800-56Ar3 generate private key flag. */ CRYPT_CTRL_PCT_TEST, /**< Verify the consistency of the asymmetric key pair. */ CRYPT_CTRL_CLEAN_PUB_KEY, /**< Clean the pubkey. */ // dh CRYPT_CTRL_SET_DH_FLAG = 150, /**< Set the dh flag.*/ // rsa CRYPT_CTRL_SET_RSA_EMSA_PKCSV15 = 200, /**< RSA set the signature padding mode to EMSA_PKCSV15. */ CRYPT_CTRL_GET_RSA_SALT, /**< Obtain the salt length of the RSA algorithm. */ CRYPT_CTRL_SET_RSA_EMSA_PSS, /**< RSA set the signature padding mode to EMSA_PSS. */ CRYPT_CTRL_SET_RSA_SALT, /**< When the RSA algorithm is used for PSS signature, the salt data is specified. During signature, the user data address is directly saved to the key. And the user data is used for the next signature, the caller must ensure that the next signature is called within the life cycle of the salt data. This option is not recommended and is used only for KAT and self-verification. */ CRYPT_CTRL_SET_RSA_PADDING, /**< Set the padding mode of the RSA algorithm. */ CRYPT_CTRL_SET_RSA_RSAES_OAEP, /**< RSA set the padding mode to RSAES_OAEP. */ CRYPT_CTRL_SET_RSA_OAEP_LABEL, /**< RSA oaep padding and setting labels, used to generate hash values. */ CRYPT_CTRL_SET_RSA_FLAG, /**< RSA set the flag. */ CRYPT_CTRL_SET_RSA_RSAES_PKCSV15, /**< RSA Set the encryption/decryption padding mode to RSAES_PKCSV15. */ CRYPT_CTRL_SET_RSA_RSAES_PKCSV15_TLS, /**< RSA Set the encryption/decryption padding mode to RSAES_PKCSV15_TLS. */ CRYPT_CTRL_GET_RSA_SALTLEN, /**< Obtain the real salt len in pss mode. The salt len can be set to -1, -2, -3 in sign or verify, which needs additional conversion during encoding. If salt len = -3, the max salt len will be returned. */ CRYPT_CTRL_GET_RSA_PADDING, /**< Obtain the padding mode of the RSA algorithm. */ CRYPT_CTRL_GET_RSA_MD, /**< Obtain the MD algorithm of the RSA algorithm. */ CRYPT_CTRL_GET_RSA_MGF, /**< Obtain the mgf algorithm when the RSA algorithm padding mode is PSS. */ CRYPT_CTRL_CLR_RSA_FLAG, /**< RSA clear the flag. */ CRYPT_CTRL_SET_RSA_BSSA_FACTOR_R, /**< Set the random bytes for RSA-BSSA. */ // ecc CRYPT_CTRL_SET_SM2_USER_ID = 300, CRYPT_CTRL_SET_SM2_SERVER, /* SM2 set the user status. */ CRYPT_CTRL_SET_SM2_R, /* SM2 set the R value. */ CRYPT_CTRL_SET_SM2_RANDOM, /* SM2 set the r value. */ CRYPT_CTRL_SET_SM2_PKG, /* SM2 uses the PKG process. */ CRYPT_CTRL_SET_SM2_K, /* SM2 set the K value. */ CRYPT_CTRL_SET_ECC_POINT_FORMAT, /**< ECC PKEY set the point format. For the point format, see CRYPT_PKEY_PointFormat. */ CRYPT_CTRL_SET_ECC_USE_COFACTOR_MODE, /**< Indicates whether to use the cofactor mode to prevent man-in-the-middle from tampering with the public key. Set this parameter to 1 when used or 0 when not used. */ CRYPT_CTRL_GET_SM2_SEND_CHECK, /* SM2 obtain the check value sent from the local end to the peer end. */ CRYPT_CTRL_GENE_SM2_R, /* SM2 obtain the R value. */ CRYPT_CTRL_SM2_DO_CHECK, /* SM2 check the shared key. */ CRYPT_CTRL_GEN_ECC_PUBLICKEY, /**< Use prikey generate pubkey. */ CRYPT_CTRL_GET_ECC_PUB_X_BIN, /**< Get the bn of x of the ecc public key without padded bin. */ CRYPT_CTRL_GET_ECC_PUB_Y_BIN, /**< Get the bn of y of the ecc public key without padded bin. */ CRYPT_CTRL_GET_ECC_ORDER_BITS, /**< Get the number of bits in the group order. */ CRYPT_CTRL_GET_ECC_NAME, /**< Obtain the name of the ECC curve. */ CRYPT_CTRL_GEN_X25519_PUBLICKEY, /**< Use prikey genarate x25519 pubkey. */ // slh-dsa CRYPT_CTRL_GET_SLH_DSA_KEY_LEN = 600, /**< Get the SLH-DSA key length. */ CRYPT_CTRL_SET_SLH_DSA_ADDRAND, /**< Set the SLH-DSA additional random bytes. */ CRYPT_CTRL_SET_MLDSA_ENCODE_FLAG = 700, /**< Set the flag for encode messages. */ CRYPT_CTRL_SET_MLDSA_MUMSG_FLAG, /**< Whether to calculate message representative */ // xmss CRYPT_CTRL_GET_XMSS_KEY_LEN = 800, /**< Get the XMSS key length. */ } CRYPT_PkeyCtrl; typedef enum { CRYPT_CTRL_SET_GM_LEVEL, /**< Set the authentication level of gm drbg */ CRYPT_CTRL_SET_RESEED_INTERVAL, CRYPT_CTRL_SET_RESEED_TIME, CRYPT_CTRL_GET_RESEED_INTERVAL, CRYPT_CTRL_GET_RESEED_TIME, CRYPT_CTRL_SET_PREDICTION_RESISTANCE, CRYPT_CTRL_GET_WORKING_STATUS, CRYPT_CTRL_RAND_MAX = 0xff, } CRYPT_RandCtrl; /** * @ingroup crypt_ctrl_param * * Set and obtain internal parameters of mac. */ typedef enum { CRYPT_CTRL_SET_CBC_MAC_PADDING = 0, /**< set cbc-mac padding type */ CRYPT_CTRL_GET_MACLEN, /* Mac get maxlen . */ CRYPT_CTRL_MAC_MAX } CRYPT_MacCtrl; /** * @ingroup crypt_entropy_type * * Entropy setting type. */ typedef enum { CRYPT_ENTROPY_SET_POOL_SIZE = 0, /**< Sets the EntropyPool size. */ CRYPT_ENTROPY_SET_CF, /**< Sets the EntropyPool conditioning function. */ CRYPT_ENTROPY_ADD_NS, /**< Adding a Noise Source. */ CRYPT_ENTROPY_REMOVE_NS, /**< Deleting a Noise Source. */ CRYPT_ENTROPY_ENABLE_TEST, /**< Sets the Health Test. */ CRYPT_ENTROPY_GET_STATE, /**< Gets the entropy source state. */ CRYPT_ENTROPY_GET_POOL_SIZE, /**< Gets the entropy pool size. */ CRYPT_ENTROPY_POOL_GET_CURRSIZE, /**< Gets the entropy pool current size. */ CRYPT_ENTROPY_GET_CF_SIZE, /**< Gets the cf size. */ CRYPT_ENTROPY_GATHER_ENTROPY, /**< Entropy source collection option. This option collects the original entropy data from each noise source, obtains the full entropy output after adjustment by the conditioning function, and stores the full entropy output in the entropy pool. The length of the entropy output obtained each time is the output length of the adjustment function. The caller can use this interface to implement the automatic collection function of the entropy pool. */ CRYPT_ENTROPY_SET_LOG_CALLBACK, /**< Set the entropy log callback. This callback is used to log the noise source collection result. */ CRYPT_ENTROPY_MAX } CRYPT_ENTROPY_TYPE; /** * @ingroup crypt_padding_type * * Padding mode enumerated type */ typedef enum { CRYPT_PADDING_NONE = 0, /**< Never pad (full blocks only). */ CRYPT_PADDING_ZEROS, /**< Zero padding (not reversible). */ CRYPT_PADDING_ISO7816, /**< ISO/IEC 7816-4 padding. */ CRYPT_PADDING_X923, /**< ANSI X.923 padding. */ CRYPT_PADDING_PKCS5, /**< PKCS5 padding. */ CRYPT_PADDING_PKCS7, /**< PKCS7 padding. */ CRYPT_PADDING_MAX_COUNT } CRYPT_PaddingType; typedef enum { CRYPT_EMSA_PKCSV15 = 1, /**< PKCS1-v1_5 according to RFC8017. */ CRYPT_EMSA_PSS, /**< PSS according to RFC8017. */ CRYPT_RSAES_OAEP, /**< OAEP according to RFC8017. */ CRYPT_RSAES_PKCSV15, /**< RSAES_PKCSV15 according to RFC8017. */ CRYPT_RSA_NO_PAD, CRYPT_RSAES_PKCSV15_TLS, /* Specific RSA pkcs1.5 padding verification process to prevent possible Bleichenbacher attacks */ CRYPT_RSA_PADDINGMAX, } CRYPT_RsaPadType; /** * @ingroup crypt_types * * Operation type */ typedef enum { CRYPT_EVENT_ENC, /**< Encryption. */ CRYPT_EVENT_DEC, /**< Decryption. */ CRYPT_EVENT_GEN, /**< Generate the key. */ CRYPT_EVENT_SIGN, /**< Signature. */ CRYPT_EVENT_VERIFY, /**< Verify the signature. */ CRYPT_EVENT_MD, /**< Hash. */ CRYPT_EVENT_MAC, /**< MAC. */ CRYPT_EVENT_KDF, /**< KDF. */ CRYPT_EVENT_KEYAGGREMENT, /**< Key negotiation. */ CRYPT_EVENT_RANDGEN, /**< Generating a random number. */ CRYPT_EVENT_ZERO, /**< sensitive information to zero. */ CRYPT_EVENT_ERR, /**< An error occurred. */ CRYPT_EVENT_SETSSP, /**< Adding and Modifying Password Data and SSP. */ CRYPT_EVENT_GETSSP, /**< Access password data and SSP. */ CRYPT_EVENT_ENCAPS, /**< Key encapsulation. */ CRYPT_EVENT_DECAPS, /**< Key decapsulation. */ CRYPT_EVENT_BLIND, /**< Message blinding. */ CRYPT_EVENT_UNBLIND, /**< Signature unblinding. */ CRYPT_EVENT_PARAM_CHECK, /**< Parameter check. */ CRYPT_EVENT_PCT_TEST, /**< PCT test. */ CRYPT_EVENT_KAT_TEST, /**< KAT test. */ CRYPT_EVENT_ES_HEALTH_TEST, /**< Entropy source health test. */ CRYPT_EVENT_INTEGRITY_TEST, /**< Integrity test. */ CRYPT_EVENT_GET_VERSION, /**< Get the version of the provider. */ CRYPT_EVENT_MAX } CRYPT_EVENT_TYPE; /** * @ingroup crypt_types * * Algorithm type */ typedef enum { CRYPT_ALGO_CIPHER = 0, CRYPT_ALGO_PKEY, CRYPT_ALGO_MD, CRYPT_ALGO_MAC, CRYPT_ALGO_KDF, CRYPT_ALGO_RAND } CRYPT_ALGO_TYPE; /** * @ingroup crypt_types * @brief event report. * * @param oper [IN] Operation type. * @param type [IN] Algorithm type. * @param id [IN] Algorithm ID. * @param err [IN] CRYPT_SUCCESS, if successful. * For other error codes, see crypt_errno.h. * * @retval None */ typedef void (*EventReport)(CRYPT_EVENT_TYPE oper, CRYPT_ALGO_TYPE type, int32_t id, int32_t err); /** * @ingroup crypt_types * * Event reporting callback registration interface, the EAL reports an event when the service is executed * and an error is reported. * If the CMVP feature is enabled, the default implementation is provided and registration is not allowed. * Note that Multi-threading is not supported. * * @param func [IN] Event reporting and processing callback * * @retval NONE */ void CRYPT_EAL_RegEventReport(EventReport func); /** * @ingroup crypt_getInfo_type * * Obtain the algorithm attribute type. */ typedef enum { CRYPT_INFO_IS_AEAD = 0, /**< Whether the AEAD algorithm is used. */ CRYPT_INFO_IS_STREAM, /**< Stream encryption or not. */ CRYPT_INFO_IV_LEN, /**< Algorithm IV length. */ CRYPT_INFO_KEY_LEN, /**< Algorithm key length. */ CRYPT_INFO_BLOCK_LEN, /**< Algorithm block length. */ CRYPT_INFO_MAX } CRYPT_INFO_TYPE; typedef enum { CRYPT_KDF_HKDF_MODE_FULL = 0, CRYPT_KDF_HKDF_MODE_EXTRACT, CRYPT_KDF_HKDF_MODE_EXPAND, } CRYPT_HKDF_MODE; typedef enum { CRYPT_ENCDEC_UNKNOW, CRYPT_PRIKEY_PKCS8_UNENCRYPT, CRYPT_PRIKEY_PKCS8_ENCRYPT, CRYPT_PRIKEY_RSA, CRYPT_PRIKEY_ECC, CRYPT_PUBKEY_SUBKEY, CRYPT_PUBKEY_RSA, CRYPT_PUBKEY_SUBKEY_WITHOUT_SEQ } CRYPT_ENCDEC_TYPE; typedef enum { CRYPT_DERIVE_PBKDF2, } CRYPT_DERIVE_MODE; typedef struct { uint32_t deriveMode; void *param; } CRYPT_EncodeParam; typedef struct { uint32_t pbesId; uint32_t pbkdfId; uint32_t hmacId; uint32_t symId; uint32_t saltLen; uint8_t *pwd; uint32_t pwdLen; uint32_t itCnt; } CRYPT_Pbkdf2Param; typedef struct EAL_LibCtx CRYPT_EAL_LibCtx; /* The hitls framework generates context for each provider */ typedef struct EAL_ProviderMgrCtx CRYPT_EAL_ProvMgrCtx; typedef struct { int32_t id; void *func; } CRYPT_EAL_Func; typedef enum { CRYPT_CMVP_PROVIDER_SELFTEST = 0x01, /**< Self-test. */ } CRYPT_CMVP_SELFTEST_AlgId; #ifdef __cplusplus } #endif // __cplusplus #endif // CRYPT_TYPES_H
2301_79861745/bench_create
include/crypto/crypt_types.h
C
unknown
33,276
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_PKI_CERT_H #define HITLS_PKI_CERT_H #include "hitls_pki_types.h" #include "crypt_eal_pkey.h" #ifdef __cplusplus extern "C" { #endif typedef struct _HITLS_X509_Cert HITLS_X509_Cert; /** * @ingroup pki * @brief Allocate a certificate. * * @retval HITLS_X509_Cert * */ HITLS_X509_Cert *HITLS_X509_CertNew(void); /** * @brief Create a new X509 certificate object using the provider mechanism * * @param libCtx [IN] Library context from CRYPT_EAL_LibCtx * @param attrName [IN] Provider attribute name for capability matching * * @return HITLS_X509_Cert* Certificate object or NULL on failure */ HITLS_X509_Cert *HITLS_X509_ProviderCertNew(HITLS_PKI_LibCtx *libCtx, const char *attrName); /** * @ingroup pki * @brief Unallocate a certificate. * * @param cert [IN] The certificate. */ void HITLS_X509_CertFree(HITLS_X509_Cert *cert); /** * @ingroup pki * @brief Duplicate a certificate. * * @param src [IN] Source certificate. * @retval HITLS_X509_Cert *, success. * NULL, fail. */ HITLS_X509_Cert *HITLS_X509_CertDup(HITLS_X509_Cert *src); /** * @ingroup pki * @brief Sign a certificate. * * @attention 1. This function can only be used when generating a new certificate. * 2. You need to first call interfaces HITLS_X509_CertCtrl to set cert information. * * @param mdId [IN] The message digest algorithm ID. * @param prvKey [IN] The private key context used for signing. * @param algParam [IN] The signature algorithm parameters. * @param cert [IN] The certificate to be signed. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CertSign(int32_t mdId, const CRYPT_EAL_PkeyCtx *prvKey, const HITLS_X509_SignAlgParam *algParam, HITLS_X509_Cert *cert); /** * @ingroup pki * @brief Compute the digest of the certificate. * * @attention This function must be called after generating or parsing a certificate. * * @param cert [IN] The certificate. * @param mdId [IN] Digest algorithm. * @param data [IN/OUT] The digest result. * @param dataLen [IN/OUT] The length of the digest. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CertDigest(HITLS_X509_Cert *cert, CRYPT_MD_AlgId mdId, uint8_t *data, uint32_t *dataLen); /** * @ingroup pki * @brief Generic function to process certificate. * * @param cert [IN] The certificate. * @param cmd [IN] HITLS_X509_Cmd * @param val [IN/OUT] input and output value * @param valLen [In] value length * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CertCtrl(HITLS_X509_Cert *cert, int32_t cmd, void *val, uint32_t valLen); /** * @ingroup pki * @brief Parse the CERT in the buffer. * @par Description: Parse the CERT in the buffer. * If the parsing is successful, the memory for the cert is requested from within the function, * and the user needs to free it after use. When the parameter is BSL_FORMAT_PEM and * BSL_FORMAT_UNKNOWN, the buff of encode needs to end with '\0' * @attention None * @param format [IN] Encoding format: BSL_FORMAT_PEM/BSL_FORMAT_ASN1/BSL_FORMAT_UNKNOWN. * @param encode [IN] CERT data. * @param cert [OUT] CERT after parse. * @return #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CertParseBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_Cert **cert); /** * @ingroup pki * @brief Parse a certificate buffer using the provider mechanism * @par Description: Parse the certificate data using a specific provider implementation. * If parsing is successful, memory for the certificate is allocated internally, * and the user needs to free it after use. * * @param libCtx [IN] Library context from CRYPT_EAL_LibCtx * @param attrName [IN] Provider attribute name for capability matching * @param format [IN] Encoding format: BSL_FORMAT_PEM/BSL_FORMAT_ASN1/BSL_FORMAT_UNKNOWN * @param encode [IN] Certificate data buffer * @param cert [OUT] Parsed certificate object * @return #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_ProviderCertParseBuff(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const BSL_Buffer *encode, HITLS_X509_Cert **cert); /** * @ingroup pki * @brief Parse multiple certificates from a buffer. * @par Description: Parse multiple certificates from a buffer. * If parsing is successful, memory for the certificate list is allocated internally, * and the user needs to free it after use. * @attention None * @param format [IN] Encoding format: BSL_FORMAT_PEM/BSL_FORMAT_ASN1/BSL_FORMAT_UNKNOWN. * @param encode [IN] Certificate data buffer. * @param certlist [OUT] Certificate list after parsing. * @return #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CertParseBundleBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_List **certlist); /** * @ingroup pki * @brief Parse multiple certificates from a buffer using the provider mechanism * @par Description: Parse multiple certificates from a buffer using a specific provider implementation. * If parsing is successful, memory for the certificate list is allocated internally, * and the user needs to free it after use. * * @param libCtx [IN] Library context from CRYPT_EAL_LibCtx * @param attrName [IN] Provider attribute name for capability matching * @param format [IN] Encoding format: "PEM"/"ASN1"/NULL * @param encode [IN] Certificate data buffer * @param certlist [OUT] List of parsed certificate objects * @return #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_ProviderCertParseBundleBuff(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const BSL_Buffer *encode, HITLS_X509_List **certlist); /** * @ingroup pki * @brief Parse the CERT in the file. * @par Description: Parse the CERT in the file. * If the parsing is successful, the memory for the cert is requested from within the function, * and the user needs to free it after use. * @attention None * @param format [IN] Encoding format: BSL_FORMAT_PEM/BSL_FORMAT_ASN1/BSL_FORMAT_UNKNOWN. * @param path [IN] CERT file path. * @param cert [OUT] CERT after parse. * @return #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CertParseFile(int32_t format, const char *path, HITLS_X509_Cert **cert); /** * @ingroup pki * @brief Parse a certificate file using the provider mechanism * @par Description: Parse the certificate from a file using a specific provider implementation. * If parsing is successful, memory for the certificate is allocated internally, * and the user needs to free it after use. * * @param libCtx [IN] Library context from CRYPT_EAL_LibCtx * @param attrName [IN] Provider attribute name for capability matching * @param format [IN] Encoding format: "PEM"/"ASN1"/NULL * @param path [IN] Certificate file path * @param cert [OUT] Parsed certificate object * @return #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_ProviderCertParseFile(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const char *path, HITLS_X509_Cert **cert); /** * @ingroup pki * @brief Parse the CERTs in the file. * @par Description: Parse multiple CERTs in the file. * If the parsing is successful, the memory for the certlist is requested from within the function, * and the user needs to free it after use. * @attention None * @param format [IN] Encoding format: BSL_FORMAT_PEM/BSL_FORMAT_ASN1/BSL_FORMAT_UNKNOWN. * @param path [IN] Certificate file path. * @param certlist [OUT] Certificate list after parse. * @return #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CertParseBundleFile(int32_t format, const char *path, HITLS_X509_List **certlist); /** * @ingroup pki * @brief Parse multiple certificates from a bundle file using the provider mechanism * @par Description: Parse multiple certificates from a file using a specific provider implementation. * If parsing is successful, memory for the certificate list is allocated internally, * and the user needs to free it after use. * * @param libCtx [IN] Library context from CRYPT_EAL_LibCtx * @param attrName [IN] Provider attribute name for capability matching * @param format [IN] Encoding format: "PEM"/"ASN1"/NULL * @param path [IN] Certificate bundle file path * @param certlist [OUT] List of parsed certificate objects * @return #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_ProviderCertParseBundleFile(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const char *path, HITLS_X509_List **certlist); /** * @ingroup pki * @brief Generates an encoded certificate. * * @attention This function is used after parsing the certificate or after signing. * * @param format [IN] Encoding format: BSL_FORMAT_ASN1 or BSL_FORMAT_PEM * @param cert [IN] cert * @param buff [OUT] encode result * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CertGenBuff(int32_t format, HITLS_X509_Cert *cert, BSL_Buffer *buff); /** * @ingroup pki * @brief Generate a certificate file. * * @attention This function is used after parsing the certificate or after signing. * * @param format [IN] Encoding format: BSL_FORMAT_ASN1 or BSL_FORMAT_PEM * @param cert [IN] cert * @param path [IN] file path * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CertGenFile(int32_t format, HITLS_X509_Cert *cert, const char *path); #ifdef __cplusplus } #endif #endif // HITLS_PKI_CERT_H
2301_79861745/bench_create
include/pki/hitls_pki_cert.h
C
unknown
10,634
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_PKI_CRL_H #define HITLS_PKI_CRL_H #include "hitls_pki_types.h" #include "crypt_eal_pkey.h" #ifdef __cplusplus extern "C" { #endif typedef struct _HITLS_X509_Crl HITLS_X509_Crl; typedef struct _HITLS_X509_CrlEntry HITLS_X509_CrlEntry; /** * @ingroup pki * @brief Allocate a crl. * * @retval HITLS_X509_Crl * */ HITLS_X509_Crl *HITLS_X509_CrlNew(void); /** * @ingroup pki * @brief Release the CRL. * @par Description: Release the memory of the CRL. * * @attention None * @param crl [IN] CRL after parse. * @return Error code */ void HITLS_X509_CrlFree(HITLS_X509_Crl *crl); /** * @ingroup pki * @brief Crl setting interface. * @par Description: Set CRL information. * parameter data type Length(len):number of data bytes * HITLS_X509_REF_UP int The length is sizeof(int), which is used to increase the * number of CRL references. * @attention None * @param crl [IN] CRL data * @param cmd [IN] Set type. * @param val [OUT] Set data. * @param valLen [IN] The length of val. * @return Error code */ int32_t HITLS_X509_CrlCtrl(HITLS_X509_Crl *crl, int32_t cmd, void *val, uint32_t valLen); /** * @ingroup pki * @brief Parse the CRL in the buffer. * @par Description: Parse the CRL in the buffer. * If the parsing is successful, the memory for the crl is requested from within the function, * and the user needs to free it after use. When the parameter is BSL_FORMAT_PEM and * BSL_FORMAT_UNKNOWN, the buff of encode needs to end with '\0' * @attention None * @param format [IN] Encoding format: BSL_FORMAT_PEM/BSL_FORMAT_ASN1/BSL_FORMAT_UNKNOWN. * @param encode [IN] CRL data. * @param crl [OUT] CRL after parse. * @return Error code */ int32_t HITLS_X509_CrlParseBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_Crl **crl); /** * @ingroup pki * @brief Parse multiple CRLs from a buffer. * @par Description: Parse multiple CRLs from a buffer. * If parsing is successful, memory for the CRL list is allocated internally, * and the user needs to free it after use. * @attention None * @param format [IN] Encoding format: BSL_FORMAT_PEM/BSL_FORMAT_ASN1/BSL_FORMAT_UNKNOWN. * @param encode [IN] CRL data buffer. * @param crlList [OUT] List of parsed CRL objects. * @return #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CrlParseBundleBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_List **crlList); /** * @ingroup pki * @brief Parse the CRL in the file. * @par Description: Parse the CRL in the file. * If the parsing is successful, the memory for the crl is requested from within the function, * and the user needs to free it after use. * @attention None * @param format [IN] Encoding format: BSL_FORMAT_PEM/BSL_FORMAT_ASN1/BSL_FORMAT_UNKNOWN. * @param path [IN] CRL file path. * @param crl [OUT] CRL after parse. * @return Error code */ int32_t HITLS_X509_CrlParseFile(int32_t format, const char *path, HITLS_X509_Crl **crl); /** * @ingroup pki * @brief Parse the CRLs in the file. * @par Description: Parse multiple CRLs in the file. * If the parsing is successful, the memory for the crllist is requested from within the function, * and the user needs to free it after use. * @attention None * @param format [IN] Encoding format: BSL_FORMAT_PEM/BSL_FORMAT_ASN1/ * BSL_FORMAT_UNKNOWN. * @param path [IN] CRL file path. * @param crllist [OUT] CRL list after parse. * @return Error code */ int32_t HITLS_X509_CrlParseBundleFile(int32_t format, const char *path, HITLS_X509_List **crlList); /** * @ingroup pki * @brief Generate a CRL and encode it. * @par Description: This function encodes the CRL into the specified format. * If the encoding is successful, the memory for the encode data is requested from within the function, * and the user needs to free it after use. * * @attention This function is used after parsing the crl or after signing. * * @attention None * @param format [IN] Encoding format: BSL_FORMAT_PEM or BSL_FORMAT_ASN1. * @param crl [IN] CRL raw data. * @param buff [OUT] Encode data. * @return Error code */ int32_t HITLS_X509_CrlGenBuff(int32_t format, HITLS_X509_Crl *crl, BSL_Buffer *buff); /** * @ingroup pki * @brief Generate a CRL and encode it to specific file. * @par Description: This function encodes the CRL into the specified format. * If the encoding is successful, the memory for the encode data is requested from within the function, * and the user needs to free it after use. * * @attention This function is used after parsing the crl or after signing. * * @attention None * @param format [IN] Encoding format: BSL_FORMAT_PEM or BSL_FORMAT_ASN1. * @param crl [IN] CRL raw data. * @param path [OUT] Encoding data file path. * @return Error code */ int32_t HITLS_X509_CrlGenFile(int32_t format, HITLS_X509_Crl *crl, const char *path); /** * @ingroup pki * @brief Verify the integrity of the CRL. * @par Description: This function verifies the integrity of the CRL * * @attention For generated CRLs, must be called after signing. * * @attention None * @param pubkey [IN] pubkey. * @param crl [IN] CRL info. * @return Error code */ int32_t HITLS_X509_CrlVerify(void *pubkey, const HITLS_X509_Crl *crl); /** * @ingroup pki * @brief Signing a CRL. * @par Description: This function is used to sign the CRL. * * @attention 1. This function can only be used when generating a new crl. * 2. Before signing, you need to call the HITLS_X509_CrlCtrl interface to set the CRL information. * * @attention The interface can be called multiple times, and the signature is regenerated on each call. * @param mdId [IN] hash algorithm. * @param prvKey [IN] private key. * @param algParam [IN] signature parameter, for example, rsa-pss parameter. * @param crl [IN/OUT] CRL info. * @return Error code */ int32_t HITLS_X509_CrlSign(int32_t mdId, const CRYPT_EAL_PkeyCtx *prvKey, const HITLS_X509_SignAlgParam *algParam, HITLS_X509_Crl *crl); /** * @ingroup pki crl * @brief Allocate a revoked certificate. * * @attention None * @return HITLS_X509_CrlEntry * */ HITLS_X509_CrlEntry *HITLS_X509_CrlEntryNew(void); /** * @ingroup pki * @brief Release the CRL certificateRevoke struct . * @par Description: Release the memory of the CRL certificateRevoke struct. * * @attention None * @param entry [IN] entry info. * @return Error code */ void HITLS_X509_CrlEntryFree(HITLS_X509_CrlEntry *entry); /** * @ingroup pki * @brief Control interface for CRL entry. * @par Description: This function provides control interface for CRL entry operations. * @attention None * @param revoked [IN] CRL entry to control. * @param cmd [IN] Control command. * @param val [IN/OUT] Control value. * @param valLen [IN] Length of control value. * @return Error code */ int32_t HITLS_X509_CrlEntryCtrl(HITLS_X509_CrlEntry *revoked, int32_t cmd, void *val, uint32_t valLen); #ifdef __cplusplus } #endif #endif // HITLS_PKI_CRL_H
2301_79861745/bench_create
include/pki/hitls_pki_crl.h
C
unknown
7,934
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_PKI_CSR_H #define HITLS_PKI_CSR_H #include "hitls_pki_types.h" #include "crypt_eal_pkey.h" #ifdef __cplusplus extern "C" { #endif typedef struct _HITLS_X509_Csr HITLS_X509_Csr; /** * @ingroup pki * @brief Allocate a pkcs10 csr. * * @retval HITLS_X509_Csr * */ HITLS_X509_Csr *HITLS_X509_CsrNew(void); /** * @ingroup pki * @brief Release the pkcs10 csr. * * @param csr [IN] CSR context. * @retval void */ void HITLS_X509_CsrFree(HITLS_X509_Csr *csr); /** * @ingroup pki * @brief Sign a CSR (Certificate Signing Request). * * @attention 1. This function can only be used when generating a new csr. * 2. You need to first call interfaces HITLS_X509_CsrCtrl and HITLS_X509_AttrCtrl to set csr information. * * @param mdId [IN] The message digest algorithm ID. * @param prvKey [IN] The private key context used for signing. * @param algParam [IN] The signature algorithm parameters. * @param csr [IN] The CSR to be signed. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CsrSign(int32_t mdId, const CRYPT_EAL_PkeyCtx *prvKey, const HITLS_X509_SignAlgParam *algParam, HITLS_X509_Csr *csr); /** * @ingroup pki * @brief Generate csr to store in buffer * * @attention This function is used after parsing the csr or after signing. * * @param format [IN] The format of the generated csr: BSL_FORMAT_ASN1/BSL_FORMAT_PEM * @param csr [IN] The csr context * @param buff [OUT] The buffer of the generated csr. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CsrGenBuff(int32_t format, HITLS_X509_Csr *csr, BSL_Buffer *buff); /** * @ingroup pki * @brief Generate csr to store in file * * @attention This function is used after parsing the csr or after signing. * * @param format [IN] The format of the generated csr: BSL_FORMAT_ASN1/BSL_FORMAT_PEM * @param csr [IN] The csr context * @param path [IN] The path of the generated csr. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CsrGenFile(int32_t format, HITLS_X509_Csr *csr, const char *path); /** * @ingroup pki * @brief Generic function to process csr function * * @param csr [IN] The csr context * @param cmd [IN] HITLS_X509_Cmd * @param val [IN/OUT] input and output value. * @param valLen [IN] value length. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CsrCtrl(HITLS_X509_Csr *csr, int32_t cmd, void *val, uint32_t valLen); /** * @ingroup pki * @brief Parse the csr in the buffer.When the parameter is BSL_FORMAT_PEM and * BSL_FORMAT_UNKNOWN, the buff of encode needs to end with '\0' * * @param format [IN] Encoding format: BSL_FORMAT_PEM/BSL_FORMAT_ASN1 * @param encode [IN] The csr data * @param csr [OUT] The csr context after parsing * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CsrParseBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_Csr **csr); /** * @ingroup pki * @brief Parse the csr in the file * * @param format [IN] Encoding format: BSL_FORMAT_PEM/BSL_FORMAT_ASN1 * @param path [IN] The csr file path * @param csr [OUT] The csr context after parsing * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CsrParseFile(int32_t format, const char *path, HITLS_X509_Csr **csr); /** * @ingroup pki * @brief Csr verify function * * @param csr [IN] The csr context * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CsrVerify(HITLS_X509_Csr *csr); #ifdef __cplusplus } #endif #endif // HITLS_PKI_CSR_H
2301_79861745/bench_create
include/pki/hitls_pki_csr.h
C
unknown
4,434
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_PKI_ERRNO_H #define HITLS_PKI_ERRNO_H #ifdef __cplusplus extern "C" { #endif typedef enum { HITLS_PKI_SUCCESS, HITLS_X509_ERR_TIME_EXPIRED = 0x04000001, HITLS_X509_ERR_TIME_FUTURE, HITLS_X509_ERR_VFY_KU_NO_CERTSIGN, HITLS_X509_ERR_VFY_KU_NO_CRLSIGN, HITLS_X509_ERR_VFY_SIGNALG_NOT_MATCH, HITLS_X509_ERR_INVALID_PARAM, HITLS_X509_ERR_VFY_CHECK_SECBITS, HITLS_X509_ERR_VFY_CERT_REVOKED, HITLS_X509_ERR_VFY_GET_HASHID, HITLS_X509_ERR_VFY_GET_SIGNID, HITLS_X509_ERR_VFY_DUP_PUBKEY, HITLS_X509_ERR_CERT_CHAIN_COUNT_IS0, HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND, HITLS_X509_ERR_ROOT_CERT_NOT_FOUND, HITLS_X509_ERR_CHAIN_DEPTH_UP_LIMIT, HITLS_X509_ERR_VFY_AKI_SKI_NOT_MATCH, HITLS_X509_ERR_VFY_ERR_SM2_USER_ID, HITLS_X509_ERR_CERT_NOT_CA = 0x04010001, HITLS_X509_ERR_CERT_EXIST, HITLS_X509_ERR_CERT_START_TIME_LATER, HITLS_X509_ERR_PROCESS_CRITICALEXT, HITLS_X509_ERR_CERT_INVALID_DN, HITLS_X509_ERR_CERT_INVALID_SERIAL_NUM, HITLS_X509_ERR_CERT_INVALID_TIME, HITLS_X509_ERR_CERT_INVALID_PUBKEY, HITLS_X509_ERR_CERT_INACCURACY_VERSION, HITLS_X509_ERR_CERT_NOT_SIGNED, HITLS_X509_ERR_CERT_SIGN_ALG, HITLS_X509_ERR_CERT_DUP_FAIL, HITLS_X509_ERR_CRL_EXIST = 0x04020001, HITLS_X509_ERR_CRL_NOT_FOUND, HITLS_X509_ERR_CRL_INACCURACY_VERSION, HITLS_X509_ERR_CRL_ENTRY, HITLS_X509_ERR_CRL_THISUPDATE_UNEXIST, HITLS_X509_ERR_CRL_NEXTUPDATE_UNEXIST, HITLS_X509_ERR_CRL_REVOKELIST_UNEXIST, HITLS_X509_ERR_CRL_ISSUER_EMPTY, HITLS_X509_ERR_CRL_TIME_INVALID, HITLS_X509_ERR_CRL_NOT_SIGNED, HITLS_X509_ERR_FORMAT_UNSUPPORT = 0x04030001, HITLS_X509_ERR_ALG_OID, HITLS_X509_ERR_NAME_OID, HITLS_X509_ERR_PARSE_STR, HITLS_X509_ERR_CHECK_TAG, HITLS_X509_ERR_GET_ANY_TAG, HITLS_X509_ERR_PARSE_NO_ELEMENT, HITLS_X509_ERR_PARSE_NO_ENOUGH, HITLS_X509_ERR_HASHID, HITLS_X509_ERR_SET_DNNAME_UNKNOWN, HITLS_X509_ERR_SET_DNNAME_TOOMUCH, HITLS_X509_ERR_SET_DNNAME_INVALID_LEN, HITLS_X509_ERR_SET_KEY, HITLS_X509_ERR_SIGN_PARAM, HITLS_X509_ERR_MD_NOT_MATCH, HITLS_X509_ERR_MGF_NOT_MATCH, HITLS_X509_ERR_PSS_SALTLEN, HITLS_X509_ERR_ENCODE_SIGNID, HITLS_X509_ERR_PARSE_OBJ_ID, HITLS_X509_ERR_PARSE_ATTR_BUF, HITLS_X509_ERR_SET_ATTR_REPEAT, HITLS_X509_ERR_SET_AFTER_PARSE, HITLS_X509_ERR_SET_NAME_LIST, HITLS_X509_ERR_SORT_NAME_NODE, HITLS_X509_ERR_ATTR_NOT_FOUND, HITLS_X509_ERR_SIGN_AFTER_PARSE, HITLS_X509_ERR_FUNC_UNSUPPORT, HITLS_X509_ERR_ALG_UNSUPPORT, HITLS_X509_ERR_ATTR_UNSUPPORT, /* extensions */ HITLS_X509_ERR_EXT_NOT_FOUND = 0x04040001, HITLS_X509_ERR_EXT_UNSUPPORT, HITLS_X509_ERR_EXT_PARSE_AFTER_SET, HITLS_X509_ERR_EXT_SET_AFTER_PARSE, HITLS_X509_ERR_EXT_SET, HITLS_X509_ERR_EXT_KU, HITLS_X509_ERR_EXT_OID, HITLS_X509_ERR_EXT_KID, HITLS_X509_ERR_EXT_SAN, HITLS_X509_ERR_EXT_SAN_ELE, HITLS_X509_ERR_EXT_EXTENDED_KU, HITLS_X509_ERR_EXT_EXTENDED_KU_ELE, HITLS_X509_ERR_EXT_GN_UNSUPPORT, HITLS_X509_ERR_EXT_CRLNUMBER, HITLS_X509_ERR_PARSE_EXT_KU, HITLS_X509_ERR_PARSE_EXT_BUF, HITLS_X509_ERR_PARSE_EXT_REPEAT, HITLS_X509_ERR_PARSE_AKI, HITLS_X509_ERR_PARSE_SAN, HITLS_X509_ERR_PARSE_SAN_ITEM_UNKNOW, HITLS_X509_ERR_PARSE_EXKU, HITLS_X509_ERR_PARSE_EXKU_ITEM, HITLS_X509_ERR_EXT_ILLEGAL_AKI, HITLS_X509_ERR_CSR_INVALID_PUBKEY = 0x04050001, HITLS_X509_ERR_CSR_INVALID_SUBJECT_DN, HITLS_X509_ERR_CSR_NOT_SIGNED, HITLS_CMS_ERR_NULL_POINTER = 0x04060001, HITLS_CMS_ERR_INVALID_DATA, HITLS_CMS_ERR_INVALID_ALGO, HITLS_CMS_ERR_PARSE_TYPE, HITLS_PKCS12_ERR_NULL_POINTER = 0x04070001, HITLS_PKCS12_ERR_INVALID_PARAM, HITLS_PKCS12_ERR_INVALID_PFX, HITLS_PKCS12_ERR_INVALID_ALGO, HITLS_PKCS12_ERR_PARSE_TYPE, HITLS_PKCS12_ERR_VERIFY_FAIL, HITLS_PKCS12_ERR_INVALID_CONTENTINFO, HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE, HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES, HITLS_PKCS12_ERR_INVALID_CERTYPES, HITLS_PKCS12_ERR_INVALID_PASSWORD, HITLS_PKCS12_ERR_INVALID_SALTLEN, HITLS_PKCS12_ERR_INVALID_ITERATION, HITLS_PKCS12_ERR_NO_ENTITYKEY, HITLS_PKCS12_ERR_NO_ENTITYCERT, HITLS_PKCS12_ERR_FORMAT_UNSUPPORT, HITLS_PKCS12_ERR_NONE_DATA, HITLS_PKCS12_ERR_NO_PAIRED_CERT_AND_KEY, HITLS_PKCS12_ERR_KDF_TOO_LONG_INPUT, HITLS_PKCS12_ERR_REPEATED_SET_ENTITYCERT, HITLS_PKCS12_ERR_REPEATED_SET_KEY, HITLS_PKCS12_ERR_NO_ENCRYPT_PARAM, HITLS_PKCS12_ERR_NO_MAC_PARAM, HITLS_PKCS12_ERR_NO_SAFEBAG_ATTRIBUTES, HITLS_PKCS12_ERR_BAG_NO_KEY, HITLS_PKCS12_ERR_BAG_NO_CERT, HITLS_PKCS12_ERR_BAG_NO_SECRET, HITLS_PKCS12_ERR_BUFFLEN_NOT_ENOUGH, HITLS_PRINT_ERR_SIGN_ALG = 0x04080001, HITLS_PRINT_ERR_PUBKEY, HITLS_PRINT_ERR_CERT_TBS, HITLS_PRINT_ERR_CERT, HITLS_PRINT_ERR_DNNAME, HITLS_PRINT_ERR_DNNAME_VALUE, HITLS_PRINT_ERR_DNNAME_HASH, HITLS_PRINT_ERR_EXT_NAME, HITLS_PRINT_ERR_EXT, HITLS_PRINT_ERR_EXT_KU, HITLS_PRINT_ERR_EXT_EXTKU, HITLS_PRINT_ERR_EXT_SKI, HITLS_PRINT_ERR_EXT_AKI_KID, HITLS_PRINT_ERR_EXT_AKI_ISSUER, HITLS_PRINT_ERR_EXT_AKI_SERIAL, HITLS_PRINT_ERR_GNNAME, HITLS_PRINT_ERR_GNNAME_UNKNOWN, HITLS_PRINT_ERR_CSR_INFO, HITLS_PRINT_ERR_CSR, HITLS_PRINT_ERR_SIGN_ALG_UNSUPPORT, HITLS_PRINT_ERR_CRL, HITLS_PRINT_ERR_CRL_TBS } HITLS_X509_ERRNO; #ifdef __cplusplus } #endif #endif // HITLS_PKI_ERRNO_H
2301_79861745/bench_create
include/pki/hitls_pki_errno.h
C
unknown
6,103
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_PKI_PKCS12_H #define HITLS_PKI_PKCS12_H #include "hitls_pki_types.h" #ifdef __cplusplus extern "C" { #endif typedef struct _HITLS_PKCS12 HITLS_PKCS12; typedef struct _HITLS_PKCS12_Bag HITLS_PKCS12_Bag; /** * @ingroup pkcs12 * @brief Allocate a pkcs12 struct. * * @retval HITLS_PKCS12 * */ HITLS_PKCS12 *HITLS_PKCS12_New(void); /** * @ingroup pkcs12 * @brief Allocate a pkcs12 struct. * * @param libCtx [IN] lib context * @param attrName [IN] attribute name * @retval HITLS_PKCS12 * */ HITLS_PKCS12 *HITLS_PKCS12_ProviderNew(HITLS_PKI_LibCtx *libCtx, const char *attrName); /** * @ingroup pkcs12 * @brief Release the pkcs12 context. * * @param csr [IN] p12 context. * @retval void */ void HITLS_PKCS12_Free(HITLS_PKCS12 *p12); /** * @ingroup pkcs12 * @brief Allocate a bag struct, which could store a cert or key and its attributes. * * @param bagId [IN] BagId, BSL_CID_PKCS8SHROUDEDKEYBAG/BSL_CID_CERTBAG/BSL_CID_SECRETBAG * @param bagType [IN] BagType, for example, BSL_CID_X509CERTIFICATE is a bagType of BSL_CID_CERTBAG. * @param bagValue [IN] bagValue, the bagValue must match the bag-type. Each Bag only holds one piece of * information -- a key or a certificate... * @retval HITLS_PKCS12_Bag * */ HITLS_PKCS12_Bag *HITLS_PKCS12_BagNew(uint32_t bagId, uint32_t bagType, void *bagValue); /** * @ingroup pkcs12 * @brief Release the bag context. * * @param bag [IN] bag context. * @retval void */ void HITLS_PKCS12_BagFree(HITLS_PKCS12_Bag *bag); /** * @ingroup pkcs12 * @brief Generic function to set a p12 context. * * @param bag [IN] bag context. * @param cmd [IN] HITLS_PKCS12_XXX * @param val [IN/OUT] input and output value * @param valType [In] value type or length * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_PKCS12_BagCtrl(HITLS_PKCS12_Bag *bag, int32_t cmd, void *val, uint32_t valType); /** * @ingroup pkcs12 * @brief Generic function to set a p12 context. * * @param p12 [IN] p12 context. * @param cmd [IN] HITLS_PKCS12_XXX * cmd val type * HITLS_PKCS12_GEN_LOCALKEYID AlgId of MD * HITLS_PKCS12_SET_ENTITY_KEYBAG a pkey bag * HITLS_PKCS12_SET_ENTITY_CERTBAG a cert bag * HITLS_PKCS12_ADD_CERTBAG a cert bag * HITLS_PKCS12_GET_ENTITY_CERT HITLS_X509_Cert** * HITLS_PKCS12_GET_ENTITY_KEY CRYPT_EAL_PkeyCtx** * @param val [IN/OUT] input and output value * @param valLen [In] value length * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_PKCS12_Ctrl(HITLS_PKCS12 *p12, int32_t cmd, void *val, uint32_t valLen); /** * @ingroup pkcs12 * @brief pkcs12 parse * @par Description: parse p12 buffer, and set the p12 struct. When the parameter is * BSL_FORMAT_PEM and BSL_FORMAT_UNKNOWN, the buff of encode needs to end with '\0' * * @attention Only support to parse p12 buffer in key-integrity and key-privacy protection mode. * @param format [IN] Decoding format: BSL_FORMAT_ASN. * @param encode [IN] encode data * @param pwdParam [IN] include MAC-pwd, enc-pwd, they can be different. * @param p12 [OUT] the p12 struct. * @param needMacVerify [IN] true, need verify mac; false, skip mac check. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_PKCS12_ParseBuff(int32_t format, const BSL_Buffer *encode, const HITLS_PKCS12_PwdParam *pwdParam, HITLS_PKCS12 **p12, bool needMacVerify); /** * @ingroup pkcs12 * @brief pkcs12 parse * @par Description: parse p12 buffer, and set the p12 struct. * * @attention Only support to parse p12 buffer in key-integrity and key-privacy protection mode. * @param libCtx [IN] lib context * @param attrName [IN] attribute name * @param format [IN] Encoding format: "ASN1" * @param encode [IN] encode data * @param pwdParam [IN] include MAC-pwd, enc-pwd, they can be different. * @param p12 [OUT] the p12 struct. * @param needMacVerify [IN] true, need verify mac; false, skip mac check. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_PKCS12_ProviderParseBuff(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const BSL_Buffer *encode, const HITLS_PKCS12_PwdParam *pwdParam, HITLS_PKCS12 **p12, bool needMacVerify); /** * @ingroup pkcs12 * @par Description: parse p12 file, and set the p12 struct. * * @attention Only support to parse p12 files in key-integrity and key-privacy protection mode. * @param format [IN] Encoding format: BSL_FORMAT_ASN1 * @param path [IN] p12 file path. * @param pwdParam [IN] include MAC-pwd, enc-pwd, they can be different. * @param p12 [OUT] the p12 struct. * @param needMacVerify [IN] true, need verify mac; false, skip mac check. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_PKCS12_ParseFile(int32_t format, const char *path, const HITLS_PKCS12_PwdParam *pwdParam, HITLS_PKCS12 **p12, bool needMacVerify); /** * @ingroup pkcs12 * @brief pkcs12 parse file * @par Description: parse p12 file, and set the p12 struct. * * @attention Only support to parse p12 files in key-integrity and key-privacy protection mode. * @param libCtx [IN] lib context * @param attrName [IN] attribute name * @param format [IN] Encoding format: "ASN1" * @param path [IN] p12 file path. * @param pwdParam [IN] include MAC-pwd, enc-pwd, they can be different. * @param p12 [OUT] the p12 struct. * @param needMacVerify [IN] true, need verify mac; false, skip mac check. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_PKCS12_ProviderParseFile(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const char *path, const HITLS_PKCS12_PwdParam *pwdParam, HITLS_PKCS12 **p12, bool needMacVerify); /** * @ingroup pkcs12 * @brief pkcs12 gen * @par Description: gen p12 buffer. * * @attention Generate a p12 buffer based on the existing information. * @param format [IN] Encoding format: BSL_FORMAT_ASN1. * @param p12 [IN] p12 struct, including entityCert, CA-cert, prvkey, and so on. * @param encodeParam [IN] encode data * @param isNeedMac [IN] Identifies whether macData is required. * @param encode [OUT] result. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_PKCS12_GenBuff(int32_t format, HITLS_PKCS12 *p12, const HITLS_PKCS12_EncodeParam *encodeParam, bool isNeedMac, BSL_Buffer *encode); /** * @ingroup pkcs12 * @par Description: Generate p12 to store in file * * @attention Generate a .p12 file based on the existing information. * @param format [IN] Encoding format: BSL_FORMAT_ASN1. * @param p12 [IN] p12 struct, including entityCert, CA-cert, prvkey, and so on. * @param encodeParam [IN] encode data * @param isNeedMac [IN] Identifies whether macData is required. * @param path [IN] The path of the generated p12-file. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_PKCS12_GenFile(int32_t format, HITLS_PKCS12 *p12, const HITLS_PKCS12_EncodeParam *encodeParam, bool isNeedMac, const char *path); #ifdef __cplusplus } #endif #endif // HITLS_PKI_PKCS12_H
2301_79861745/bench_create
include/pki/hitls_pki_pkcs12.h
C
unknown
8,376
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_PKI_TYPES_H #define HITLS_PKI_TYPES_H #include <stdint.h> #include <stdbool.h> #include "bsl_obj.h" #include "bsl_types.h" #include "bsl_list.h" #include "crypt_types.h" #ifdef __cplusplus extern "C" { #endif typedef void HITLS_PKI_LibCtx; #define HITLS_X509_List BslList #define HITLS_X509_VERSION_1 0 #define HITLS_X509_VERSION_2 1 #define HITLS_X509_VERSION_3 2 /* Key usage */ #define HITLS_X509_EXT_KU_DIGITAL_SIGN 0x0080 #define HITLS_X509_EXT_KU_NON_REPUDIATION 0x0040 #define HITLS_X509_EXT_KU_KEY_ENCIPHERMENT 0x0020 #define HITLS_X509_EXT_KU_DATA_ENCIPHERMENT 0x0010 #define HITLS_X509_EXT_KU_KEY_AGREEMENT 0x0008 #define HITLS_X509_EXT_KU_KEY_CERT_SIGN 0x0004 #define HITLS_X509_EXT_KU_CRL_SIGN 0x0002 #define HITLS_X509_EXT_KU_ENCIPHER_ONLY 0x0001 #define HITLS_X509_EXT_KU_DECIPHER_ONLY 0x8000 #define HITLS_X509_EXT_KU_NONE 0xFFFF /* No Key Usage extension. */ typedef enum { HITLS_X509_REF_UP = 0, /** Increase the reference count of the object */ HITLS_X509_GET_ENCODELEN = 0x0100, /** Get the length in bytes of the ASN.1 DER encoded cert/csr */ HITLS_X509_GET_ENCODE, /** Get the ASN.1 DER encoded cert/csr data */ HITLS_X509_GET_PUBKEY, /** Get the public key contained in the cert/csr */ HITLS_X509_GET_SIGNALG, /** Get the signature algorithm used to sign the cert/csr */ HITLS_X509_GET_SUBJECT_DN_STR, /** Get the subject distinguished name as a formatted string */ HITLS_X509_GET_ISSUER_DN_STR, /** Get the issuer distinguished name as a formatted string */ HITLS_X509_GET_SERIALNUM_STR, /** Get the serial number as a string */ HITLS_X509_GET_BEFORE_TIME_STR, /** Get the validity start time as a string */ HITLS_X509_GET_AFTER_TIME_STR, /** Get the validity end time as a string */ HITLS_X509_GET_SUBJECT_DN, /** Get the list of subject distinguished name components. Note: The list is read-only and should not be modified. */ HITLS_X509_GET_ISSUER_DN, /** Get the list of issuer distinguished name components. Note: The list is read-only and should not be modified. */ HITLS_X509_GET_VERSION, /** Get the version from cert or crl. */ HITLS_X509_GET_REVOKELIST, /** Get the certificate revoke list from the crl. */ HITLS_X509_GET_SERIALNUM, /** Get the serial number of the cert. */ HITLS_X509_GET_BEFORE_TIME, /** Get the validity start time */ HITLS_X509_GET_AFTER_TIME, /** Get the validity end time */ HITLS_X509_GET_SIGN_MDALG, /** Get the hash algorithm of signature algorithm used to sign the cert/ */ HITLS_X509_GET_ENCODE_SUBJECT_DN, /** Get the ASN.1 DER encoded subject distinguished name */ HITLS_X509_IS_SELF_SIGNED, /** Determine whether the certificate is a self-signed certificate */ HITLS_X509_SET_VERSION = 0x0200, /** Set the version for the cert. */ HITLS_X509_SET_SERIALNUM, /** Set the serial number for the cert, the length range is 1 to 20. */ HITLS_X509_SET_BEFORE_TIME, /** Set the before time for the cert. */ HITLS_X509_SET_AFTER_TIME, /** Set the after time for the cert. */ HITLS_X509_SET_PUBKEY, /** Set the public key for the cert/csr. */ HITLS_X509_SET_SUBJECT_DN, /** Set the subject name list. */ HITLS_X509_SET_ISSUER_DN, /** Set the issuer name list. */ HITLS_X509_SET_CSR_EXT, /** Replace the cert's ext with csr's */ HITLS_X509_ADD_SUBJECT_NAME, /** Add the subject name for the cert/csr. */ HITLS_X509_CRL_ADD_REVOKED_CERT, /** Add the revoke cert to crl. */ HITLS_X509_EXT_SET_SKI = 0x0400, /** Set the subject key identifier extension. */ HITLS_X509_EXT_SET_AKI, /** Set the authority key identifier extension. */ HITLS_X509_EXT_SET_KUSAGE, /** Set the key usage extension. */ HITLS_X509_EXT_SET_SAN, /** Set the subject alternative name extension. */ HITLS_X509_EXT_SET_BCONS, /** Set the basic constraints extension. */ HITLS_X509_EXT_SET_EXKUSAGE, /** Set the extended key usage extension. */ HITLS_X509_EXT_SET_CRLNUMBER, /** Set the crlnumber extension. */ HITLS_X509_EXT_GET_SKI = 0x0500, /** Get Subject Key Identifier from extensions. Note: Kid is a shallow copy. */ HITLS_X509_EXT_GET_CRLNUMBER, /** get the crlnumber form the crl. */ HITLS_X509_EXT_GET_AKI, /** get the Authority Key Identifier form the crl/cert/csr. */ HITLS_X509_EXT_GET_KUSAGE, /** get the key usage form the crl/cert/csr. Note: If key usage is not set, return 0xffff. */ HITLS_X509_EXT_CHECK_SKI = 0x0600, /** Check if ski is exists. */ HITLS_X509_CSR_GET_ATTRIBUTES = 0x0700, /** Get the attributes from the csr. */ HITLS_X509_SET_VFY_SM2_USER_ID = 0x800, /** Set sm2 user Id when verify cert/csr/crl. */ } HITLS_X509_Cmd; typedef enum { HITLS_X509_ATTR_SET_REQUESTED_EXTENSIONS = 0x0100, HITLS_X509_ATTR_GET_REQUESTED_EXTENSIONS = 0x0200, } HITLS_X509_AttrCmd; /** * GeneralName types defined in RFC 5280 Section 4.2.1.6 * Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.6 * GeneralName ::= CHOICE { * otherName [0] OtherName, * rfc822Name [1] IA5String, * dNSName [2] IA5String, * x400Address [3] ORAddress, * directoryName [4] Name, * ediPartyName [5] EDIPartyName, * uniformResourceIdentifier [6] IA5String, * iPAddress [7] OCTET STRING, * registeredID [8] OBJECT IDENTIFIER } */ typedef enum { HITLS_X509_GN_EMAIL, // rfc822Name [1] IA5String HITLS_X509_GN_DNS, // dNSName [2] IA5String HITLS_X509_GN_DNNAME, // directoryName [4] Name HITLS_X509_GN_URI, // uniformResourceIdentifier [6] IA5String HITLS_X509_GN_IP, // iPAddress [7] Octet String // Other types are not supported yet HITLS_X509_GN_MAX } HITLS_X509_GeneralNameType; /* Distinguish name */ typedef struct { BslCid cid; uint8_t *data; uint32_t dataLen; } HITLS_X509_DN; /** * GenernalName */ typedef struct { HITLS_X509_GeneralNameType type; BSL_Buffer value; } HITLS_X509_GeneralName; /** * Authority Key identifier */ typedef struct { bool critical; BSL_Buffer kid; // keyIdentifier: optional BslList *issuerName; // Not supported. authorityCertIssuer: optional, List of HITLS_X509_GeneralName BSL_Buffer serialNum; // Not supported. authorityCertSerialNumber: optional } HITLS_X509_ExtAki; /** * Subject Key identifier */ typedef struct { bool critical; BSL_Buffer kid; } HITLS_X509_ExtSki; /** * Key Usage */ typedef struct { bool critical; uint32_t keyUsage; } HITLS_X509_ExtKeyUsage; /** * Extended Key Usage */ typedef struct { bool critical; BslList *oidList; // Object Identifier: list of BSL_Buffer } HITLS_X509_ExtExKeyUsage; /** * Subject Alternative Name */ typedef struct { bool critical; BslList *names; // List of HITLS_X509_GeneralName } HITLS_X509_ExtSan; /** * Basic Constraints */ typedef struct { bool critical; bool isCa; // Default to false. int32_t maxPathLen; // Greater than or equal to 0. -1: no check, 0: no intermediate certificate } HITLS_X509_ExtBCons; /** * @brief Signature algorithm parameters. */ typedef struct { int32_t algId; /**< Algorithm identifier */ union { CRYPT_RSA_PssPara rsaPss; /**< RSA PSS padding parameters */ BSL_Buffer sm2UserId; }; } HITLS_X509_SignAlgParam; /** * Crl number */ typedef struct { bool critical; // Default to false. BSL_Buffer crlNumber; // crlNumber } HITLS_X509_ExtCrlNumber; typedef struct { bool critical; BSL_TIME time; } HITLS_X509_RevokeExtTime; typedef enum { HITLS_X509_CRL_SET_REVOKED_SERIALNUM = 0, /** Set the revoked serial number. */ HITLS_X509_CRL_SET_REVOKED_REVOKE_TIME, /** Set the revoke time. */ HITLS_X509_CRL_SET_REVOKED_INVALID_TIME, /** Set the invalid time extension. */ HITLS_X509_CRL_SET_REVOKED_REASON, /** Set the revoke reason extension. */ HITLS_X509_CRL_SET_REVOKED_CERTISSUER, /** Set the revoke cert issuer extension. */ HITLS_X509_CRL_GET_REVOKED_SERIALNUM = 0x0100, /** Get the revoked serial number. */ HITLS_X509_CRL_GET_REVOKED_REVOKE_TIME, /** Get the revoke time. */ HITLS_X509_CRL_GET_REVOKED_INVALID_TIME, /** Get the invalid time extension. */ HITLS_X509_CRL_GET_REVOKED_REASON, /** Get the revoke reason extension. */ HITLS_X509_CRL_GET_REVOKED_CERTISSUER, /** Get the revoke cert issuer extension. */ } HITLS_X509_RevokeCmd; typedef enum { HITLS_X509_REVOKED_REASON_UNSPECIFIED = 0, /** CRLReason: Unspecified. */ HITLS_X509_REVOKED_REASON_KEY_COMPROMISE, /** CRLReason: Key compromise. */ HITLS_X509_REVOKED_REASON_CA_COMPROMISE, /** CRLReason: CA compromise. */ HITLS_X509_REVOKED_REASON_AFFILIATION_CHANGED, /** CRLReason: Affiliation changed. */ HITLS_X509_REVOKED_REASON_SUPERSEDED, /** CRLReason: Superseded. */ HITLS_X509_REVOKED_REASON_CESSATION_OF_OPERATION, /** CRLReason: Cessation of operation. */ HITLS_X509_REVOKED_REASON_CERTIFICATE_HOLD, /** CRLReason: Certificate hold. */ HITLS_X509_REVOKED_REASON_REMOVE_FROM_CRL, /** CRLReason: Remove from CRL. */ HITLS_X509_REVOKED_REASON_PRIVILEGE_WITHDRAWN, /** CRLReason: Privilege withdrawn. */ HITLS_X509_REVOKED_REASON_AA_COMPROMISE, /** CRLReason: aA compromise. */ } HITLS_X509_RevokeReason; typedef struct { bool critical; int32_t reason; } HITLS_X509_RevokeExtReason; typedef struct { bool critical; BslList *issuerName; // List of HITLS_X509_GeneralName } HITLS_X509_RevokeExtCertIssuer; typedef enum { HITLS_X509_EXT_TYPE_CSR, } HITLS_X509_ExtType; typedef enum { HITLS_X509_VFY_FLAG_CRL_ALL = 1, HITLS_X509_VFY_FLAG_CRL_DEV = 2 } HITLS_X509_VFY_FLAGS; typedef enum { HITLS_X509_STORECTX_SET_PARAM_DEPTH, HITLS_X509_STORECTX_SET_PARAM_FLAGS, HITLS_X509_STORECTX_SET_TIME, HITLS_X509_STORECTX_SET_SECBITS, /* clear flag */ HITLS_X509_STORECTX_CLR_PARAM_FLAGS, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, HITLS_X509_STORECTX_SHALLOW_COPY_SET_CA, HITLS_X509_STORECTX_SET_CRL, HITLS_X509_STORECTX_CLEAR_CRL, HITLS_X509_STORECTX_REF_UP, HITLS_X509_STORECTX_SET_VFY_SM2_USERID, HITLS_X509_STORECTX_GET_PARAM_DEPTH, HITLS_X509_STORECTX_GET_PARAM_FLAGS, HITLS_X509_STORECTX_ADD_CA_PATH, /**< Add additional CA path for on-demand loading */ HITLS_X509_STORECTX_MAX } HITLS_X509_StoreCtxCmd; typedef struct { BSL_Buffer *macPwd; BSL_Buffer *encPwd; } HITLS_PKCS12_PwdParam; /** * @ingroup hitls_pki_types * @brief Flags for printing Distinguished Names (DNs) in X509 certificates */ #define HITLS_PKI_PRINT_DN_ONELINE 0 #define HITLS_PKI_PRINT_DN_MULTILINE 1 #define HITLS_PKI_PRINT_DN_RFC2253 2 // default flag /** * @ingroup hitls_pki_types * @brief Commands for printing X509 certificate and DN information */ typedef enum { HITLS_PKI_SET_PRINT_FLAG, // The default flag is rfc2253. Multi-threading is not supported. HITLS_PKI_PRINT_DNNAME, HITLS_PKI_PRINT_DNNAME_HASH, HITLS_PKI_PRINT_CERT, HITLS_PKI_PRINT_NEXTUPDATE, HITLS_PKI_PRINT_CSR, HITLS_PKI_PRINT_CRL } HITLS_PKI_PrintCmd; /** * While the standard imposes no constraints on password length, (pwdLen + saltLen) should be kept below 2^31 * to avoid integer overflow in internal calculations. */ typedef struct { uint32_t saltLen; uint32_t itCnt; uint32_t macId; uint8_t *pwd; uint32_t pwdLen; } HITLS_PKCS12_KdfParam; typedef struct { void *para; int32_t algId; } HITLS_PKCS12_MacParam; /** * Parameters for p12 file generation. * Only PBES2 is supported, but different symmetric encryption algorithms can be used within certificates and keys. */ typedef struct { CRYPT_EncodeParam encParam; HITLS_PKCS12_MacParam macParam; } HITLS_PKCS12_EncodeParam; typedef enum { HITLS_PKCS12_GEN_LOCALKEYID = 0x01, /** Gen and set localKeyId of entity-key and entity-cert in p12-ctx. */ HITLS_PKCS12_SET_ENTITY_KEYBAG, /** Set entity key-Bag to p12-ctx. */ HITLS_PKCS12_SET_ENTITY_CERTBAG, /** Set entity cert-Bag to p12-ctx. */ HITLS_PKCS12_ADD_CERTBAG, /** Set other cert-Bag to p12-ctx. */ HITLS_PKCS12_GET_ENTITY_CERT, /** Obtain entity cert from p12-ctx. */ HITLS_PKCS12_GET_ENTITY_KEY, /** Obtain entity pkey from p12-ctx. */ HITLS_PKCS12_GET_SECRETBAGS, /** Get secret-Bags from p12-ctx. The list is read-only and should not be modified. */ HITLS_PKCS12_ADD_SECRETBAG, /** Add secret-Bag to p12-ctx. */ HITLS_PKCS12_GET_ENTITY_CERTBAG, /** Obtain entity cert-Bag from p12-ctx. */ HITLS_PKCS12_GET_ENTITY_KEYBAG, /** Obtain entity key-Bag from p12-ctx. */ HITLS_PKCS12_ADD_KEYBAG, /** Add key-Bag to p12-ctx. */ HITLS_PKCS12_GET_KEYBAGS, /** Get key-Bags from p12-ctx. The list is read-only and should not be modified. */ HITLS_PKCS12_GET_CERTBAGS, /** Get cert-Bags from p12-ctx. The list is read-only and should not be modified. */ } HITLS_PKCS12_Cmd; typedef enum { HITLS_PKCS12_BAG_ADD_ATTR, /** Add attribute to safeBag. */ HITLS_PKCS12_BAG_GET_ATTR, /** Get attribute from safeBag. */ HITLS_PKCS12_BAG_GET_VALUE, /** Get value from safeBag. */ HITLS_PKCS12_BAG_GET_ID, /** Get id from safeBag. */ HITLS_PKCS12_BAG_GET_TYPE, /** Get type from safeBag. */ } HITLS_PKCS12_BagCmd; #ifdef __cplusplus } #endif #endif // HITLS_PKI_TYPES_H
2301_79861745/bench_create
include/pki/hitls_pki_types.h
C
unknown
15,426
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_PKI_UTILS_H #define HITLS_PKI_UTILS_H #include "bsl_uio.h" #include "hitls_pki_types.h" #ifdef __cplusplus extern "C" { #endif typedef struct _HITLS_X509_Ext HITLS_X509_Ext; typedef struct _HITLS_X509_Attrs HITLS_X509_Attrs; /** * @ingroup hitls_pki_utils * @brief Generic function to print data. * @attention * Thread safe : Not thread-safe function. * Blocking risk : No blocking. * Time consuming : Not time-consuming. * * @param cmd [IN] HITLS_PKI_PrintCmd * @param val [IN] The data to be printed. * @param valLen [In] The length of the data to be printed. * @param uio [In] Pointer to the BSL_UIO structure. * @retval #HITLS_PKI_SUCCESS, success. * error codes see the hitls_pki_errno.h */ int32_t HITLS_PKI_PrintCtrl(int32_t cmd, void *val, uint32_t valLen, BSL_UIO *uio); /** * @ingroup pki * @brief Generic function to set/get an extension. * * @param ext [IN] extensions * @param cmd [IN] HITLS_X509_EXT_SET_XXX * cmd data type * HITLS_X509_EXT_GET|SET_KUSAGE HITLS_X509_ExtKeyUsage * HITLS_X509_EXT_GET|SET_BCONS HITLS_X509_ExtBCons * HITLS_X509_EXT_GET|SET_AKI HITLS_X509_ExtAki * HITLS_X509_EXT_GET|SET_SKI HITLS_X509_ExtSki * HITLS_X509_EXT_GET|SET_SAN HITLS_X509_ExtSan * HITLS_X509_EXT_GET|SET_EXKUSAGE HITLS_X509_ExtExKeyUsage * HITLS_X509_EXT_CHECK_SKI bool * @param val [IN/OUT] input and output value * @param valLen [In] value length * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_ExtCtrl(HITLS_X509_Ext *ext, int32_t cmd, void *val, uint32_t valLen); /** * @ingroup pki * @brief Allocate a extension. * * @retval HITLS_X509_Ext * */ HITLS_X509_Ext *HITLS_X509_ExtNew(int32_t type); /** * @ingroup pki * @brief Unallocate a extension. * * @param ext [IN] The extension. */ void HITLS_X509_ExtFree(HITLS_X509_Ext *ext); /** * @ingroup pki * @brief clear the HITLS_X509_ExtAki structure. * @par Description: This interface needs to be called to clean up memory when obtaining AKI extensions from * certificates, CRLs, or CSRs using the macro HITLS_X509_EXT_GET_AKI. * * @param aki [IN] The HITLS_X509_ExtAki aki */ void HITLS_X509_ClearAuthorityKeyId(HITLS_X509_ExtAki *aki); /** * @ingroup pki * @brief Free a general name. * * @param data [IN] The general name. */ void HITLS_X509_FreeGeneralName(HITLS_X509_GeneralName *data); /** * @ingroup pki * @brief New a list of distinguish name, the item is HITLS_X509_NameNode. * @attention You need to HITLS_X509_DnListFree to free list, after the end of use * * @retval #BslList *, success. * error return NULL. */ BslList *HITLS_X509_DnListNew(void); /** * @ingroup pki * @brief New a list of distinguish name, the list . * * @param list [IN] The name list * @retval void */ void HITLS_X509_DnListFree(BslList *dnList); /** * @ingroup pki * @brief Add a distinguish name array to list. * * @param list [IN] The name list * @param dnNames [IN] dnName array * @param size [IN] The count of dnName array * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_AddDnName(BslList *list, HITLS_X509_DN *dnNames, uint32_t size); /** * @ingroup pki * @brief Generic function to process attribute function * * @param attributes [IN] The attribute list * @param cmd [IN] HITLS_X509_AttrCmd * @param val data type * HITLS_X509_ATTR_XX_REQUESTED_EXTENSIONS HITLS_X509_Ext * @param valLen The length of value. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_AttrCtrl(HITLS_X509_Attrs *attributes, HITLS_X509_AttrCmd cmd, void *val, uint32_t valLen); #ifdef __cplusplus } #endif #endif // HITLS_PKI_UTILS_H
2301_79861745/bench_create
include/pki/hitls_pki_utils.h
C
unknown
4,589
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_PKI_X509_H #define HITLS_PKI_X509_H #include "hitls_pki_cert.h" #include "hitls_pki_crl.h" #ifdef __cplusplus extern "C" { #endif typedef struct _HITLS_X509_StoreCtx HITLS_X509_StoreCtx; /** * @ingroup pki * @brief Allocate a StoreCtx. * * @retval HITLS_X509_StoreCtx * */ HITLS_X509_StoreCtx *HITLS_X509_StoreCtxNew(void); /** * @brief Create a new X509 store object using the provider mechanism * * @param libCtx [IN] Library context from CRYPT_EAL * @param attrName [IN] Provider attribute name for capability matching * * @return HITLS_X509_StoreCtx* Store object or NULL on failure */ HITLS_X509_StoreCtx *HITLS_X509_ProviderStoreCtxNew(HITLS_PKI_LibCtx *libCtx, const char *attrName); /** * @ingroup pki * @brief Release the StoreCtx. * * @param storeCtx [IN] StoreCtx. * @retval void */ void HITLS_X509_StoreCtxFree(HITLS_X509_StoreCtx *storeCtx); /** * @ingroup pki * @brief Generic function to process StoreCtx. * * @param storeCtx [IN] StoreCtx. * @param cmd [IN] HITLS_X509_Cmd data type data length * HITLS_X509_STORECTX_SET_PARAM_DEPTH int32_t sizeof(int32_t) * HITLS_X509_STORECTX_SET_PARAM_FLAGS uint64_t sizeof(uint64_t) * HITLS_X509_STORECTX_SET_TIME int64_t sizeof(int64_t) * HITLS_X509_STORECTX_SET_SECBITS uint32_t sizeof(uint32_t) * HITLS_X509_STORECTX_CLR_PARAM_FLAGS uint64_t sizeof(uint64_t) * HITLS_X509_STORECTX_DEEP_COPY_SET_CA HITLS_X509_Cert - * HITLS_X509_STORECTX_SHALLOW_COPY_SET_CA HITLS_X509_Cert - * HITLS_X509_STORECTX_SET_CRL HITLS_X509_Crl - * HITLS_X509_STORECTX_CLEAR_CRL NULL 0 * HITLS_X509_STORECTX_REF_UP int sizeof(int) * HITLS_X509_STORECTX_SET_VFY_SM2_USERID buffer > 0 * HITLS_X509_STORECTX_GET_PARAM_DEPTH int32_t * sizeof(int32_t) * HITLS_X509_STORECTX_GET_PARAM_FLAGS uint64_t * sizeof(uint64_t) * HITLS_X509_STORECTX_ADD_CA_PATH char * string length * @param val [IN/OUT] input and output value. * @param valLen [IN] value length. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_StoreCtxCtrl(HITLS_X509_StoreCtx *storeCtx, int32_t cmd, void *val, uint32_t valLen); /** * @ingroup pki * @brief Certificate chain verify function. * * @param storeCtx [IN] StoreCtx. * @param chain [IN] certificate chain. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CertVerify(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain); /** * @ingroup pki * @brief Certificate chain build function. * * @param storeCtx [IN] StoreCtx. * @param isWithRoot [IN] whether the root cert is included. * @param cert [IN] certificate. * @param chain [OUT] certificate chain. * @retval #HITLS_PKI_SUCCESS, success. * Error codes can be found in hitls_pki_errno.h */ int32_t HITLS_X509_CertChainBuild(HITLS_X509_StoreCtx *storeCtx, bool isWithRoot, HITLS_X509_Cert *cert, HITLS_X509_List **chain); #ifdef __cplusplus } #endif #endif // HITLS_PKI_X509_H
2301_79861745/bench_create
include/pki/hitls_pki_x509.h
C
unknown
4,004
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls * @ingroup hitls * @brief TLS parameter configuration */ #ifndef HITLS_H #define HITLS_H #include <stdint.h> #include <stddef.h> #include "hitls_type.h" #include "hitls_config.h" #include "hitls_cert_type.h" #include "bsl_uio.h" #ifdef __cplusplus extern "C" { #endif /** * @ingroup hitls * @brief Create a TLS object and deep copy the HITLS_Config to the HITLS_Ctx. * * This is the main TLS structure, which starts to establish a secure link through the client or server * on the basis that the link has been established at the network layer. * * @attention The HITLS_Config can be released after the creation is successful. * @param config [IN] Config context * @retval HITLS_Ctx pointer. If the operation fails, a null value is returned. */ HITLS_Ctx *HITLS_New(HITLS_Config *config); /** * @ingroup hitls * @brief Release the TLS connection. * * @param ctx [IN] TLS connection handle. * @retval void */ void HITLS_Free(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Set the UIO object for the HiTLS context. * * Bind the HiTLS context to the UIO object, through which the TLS object sends data, reads data, * and controls the connection status at the network layer. * After successfully setting, the number of times the UIO object is referenced increases by 1. * BSL_UIO_Free is called to release the association between the HiTLS and UIO when HITLS_Free is called. * * @attention After a HiTLS context is bound to a UIO object, the UIO object cannot be bound to other HiTLS contexts. * This function must be called before HITLS_Connect and HITLS_Accept. * @param ctx [OUT] TLS connection handle. * @param uio [IN] UIO object. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetUio(HITLS_Ctx *ctx, BSL_UIO *uio); /** * @ingroup hitls * @brief Read UIO for the HiTLS context. * * @attention Must be called before HITLS_Connect and HITLS_Accept and released after HITLS_Free. * If this function has been called, you must call BSL_UIO_Free to release the UIO. * @param ctx [OUT] TLS connection handle. * @param uio [IN] UIO object. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetReadUio(HITLS_Ctx *ctx, BSL_UIO *uio); /** * @ingroup hitls * @brief Obtain the UIO object from the HiTLS context. * * @param ctx [IN] TLS object. * @retval UIO object. */ BSL_UIO *HITLS_GetUio(const HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Obtain the UIO object of the read data. * * @param ctx [IN] TLS object * @retval UIO object */ BSL_UIO *HITLS_GetReadUio(const HITLS_Ctx *ctx); /** * @ingroup hitls * @brief The client starts the handshake with the TLS server. * * Starting the handshake with the TLS server using HITLS_Connect. * The UIO object must be created and bound to the HiTLS context. * HITLS_Connect is designed as a non-blocking interface. If the handshake cannot be continued, * the returned value will not be HITLS_SUCCESS. * If the return value is HITLS_REC_NORMAL_RECV_BUF_EMPTY or HITLS_REC_NORMAL_IO_BUSY, * no fatal error occurs. Problems such as network congestion or network delay may occur. * You can continue to call HITLS_Connect. Note that if UIO is blocked, HITLS_Connect will also block, * but the return value is processed in the same way. * * @attention Only clients can call this interface. * @param ctx [IN] TLS connection handle. * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY, record The receiving buffer is NULL and the handshake can be continued. * @retval HITLS_REC_NORMAL_IO_BUSY, the network I/O is busy and needs to wait for the next sending. * You can continue the handshake. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_Connect(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Set the initial status of the connection. * * @param ctx [IN] TLS connection handle. * @param isClient [IN] Set the current client or server. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetEndPoint(HITLS_Ctx *ctx, bool isClient); /** * @ingroup hitls * @brief The server waits for the client to start handshake. * * The server waits for the client to initiate the handshake. * The UIO object must be created and bound to the HiTLS context.\n * HITLS_Accept is designed for non-blocking interfaces. * If the handshake cannot be continued, the system returns. The return value is not success. * If the return value is HITLS_REC_NORMAL_RECV_BUF_EMPTY or HITLS_REC_NORMAL_IO_BUSY, no fatal error occurs. * Problems such as network congestion or network delay may occur. You can continue to call HITLS_Accept. * Note that if the UIO is blocked, the HITLS_Accept will also be blocked, but the processing * of the returned value is the same. * * @attention Only the server calls this API. * @param ctx [IN] TLS connection handle. * @retval HITLS_SUCCESS, the handshake is successful. * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY, record The receiving buffer is NULL and the handshake can continue. * @retval HITLS_REC_NORMAL_IO_BUSY, the network I/O is busy and needs to wait for the next sending. * You can continue the handshake. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_Accept(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Read application data * * @attention Only the application data decrypted by one record can be read by HiTLS at a time * HiTLS copies the application data to the input cache. * If the cache size is less than 16 KB, the maximum size of the application message decrypted * by a single record is 16 KB. This will result in a partial copy of the application data * You can call HITLS_GetReadPendingBytes to obtain the size of the remaining readable application data * in the current record. This is useful in DTLS scenarios. * @param ctx [IN] TLS context * @param data [OUT] Read data * @param bufSize [IN] Size of the buffer * @param readLen [OUT] Read length * @retval HITLS_SUCCESS, if successful * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY, record The receiving buffer is NULL and can be read again. * @retval HITLS_REC_NORMAL_IO_BUSY, the network I/O is busy and needs to wait for the next sending * You can continue to read the I/O. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_Read(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen); /** * @ingroup hitls * @brief read application data from a TLS/SSL connection * @attention HITLS_Peek() is identical to HITLS_Read() except no bytes are actually removed from the underlying BIO during the read * @param ctx [IN] TLS context * @param data [OUT] data buffer * @param bufSize [IN] data buffer size * @param readLen [OUT] store the number of bytes actually read in *readLen * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY, read buffer is empty, more bytes can be read. * @retval HITLS_REC_NORMAL_IO_BUSY, IO budy, waiting for next calling to read more. * @retval Refer to hitls_error.h for more */ int32_t HITLS_Peek(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen); /** * @ingroup hitls * @brief Write data. * * Encrypts and packs data with the specified length dataLen into a single record and sends the record. * * @attention The length of the data to be sent cannot exceed the maximum writable length, * which can be obtained by calling HITLS_GetMaxWriteSize. * @param ctx [IN] TLS context * @param data [IN] Data to be written * @param dataLen [IN] Length to be written * @param writeLen [OUT] Length of Successful Writes * @retval HITLS_SUCCESS is sent successfully. * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY, record If the receiving buffer is NULL, the message can be sent again. * @retval HITLS_REC_NORMAL_IO_BUSY, The network I/O is busy and needs to wait for the next sending. * You can continue sending the I/O. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_Write(HITLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen); /** * @ingroup hitls * @brief Obtain the maximum writable (plaintext) length. * * @param ctx [OUT] TLS connection handle. * @param len [OUT] Maximum writable plaintext length (within 16 KB) * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_GetMaxWriteSize(const HITLS_Ctx *ctx, uint32_t *len); /** * @ingroup hitls * @brief Obtain user data from the HiTLS context. This interface is called in the callback registered with the HiTLS. * * @attention must be called before HITLS_Connect and HITLS_Accept. * The life cycle of the user data pointer must be longer than the life cycle of the TLS object. * @param ctx [OUT] TLS connection handle. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, the TLS object pointer of the input parameter is null. */ void *HITLS_GetUserData(const HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Save the user data in the HiTLS context, which can be obtained from the callback registered with the HiTLS. * * @attention must be called before HITLS_Connect and HITLS_Accept. * The life cycle of the user data pointer must be greater than the life cycle of the TLS object.\n * If the user data needs to be cleared, the HITLS_SetUserData(ctx, NULL) interface can be called directly. * The Clean interface is not provided separately. * @param ctx [OUT] TLS connection handle. * @param userData [IN] Pointer to the user data. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, the TLS object pointer of the input parameter is null. */ int32_t HITLS_SetUserData(HITLS_Ctx *ctx, void *userData); /** * @ingroup hitls * @brief Close the TLS connection. * * If the peer end is not closed, the system sends a closed notify message to the peer end. * HITLS_Close must not be called if a fatal error has occurred on the link. * * @param ctx [IN] TLS connection handle. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_Close(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Set the shutdown status of the TLS link. * * In HITLS_Close, if the peer end is not closed, a closed notification message is sent to the peer end. * When the local end sends a closed notify message, the HiTLS sets the HITLS_SENT_SHUTDOWN flag bit. * When the local end receives the closed notify message, the HiTLS sets the HITLS_RECEIVED_SHUTDOWN flag bit. * By default, the HiTLS needs to send and receive closed notifications. * The actual condition for properly closing a session is HITLS_SENT_SHUTDOWN. (According to the TLS RFC, * it is acceptable to send only close_notify alerts without waiting for a reply from the peer.) * If HITLS_RECEIVED_SHUTDOWN is set, it indicates that the peer end does not need to wait for the closed notification. * * @param ctx [IN] TLS connection handle. * @param mode [IN] TLS shutdown status: HITLS_SENT_SHUTDOWN / HITLS_RECEIVED_SHUTDOWN. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetShutdownState(HITLS_Ctx *ctx, uint32_t mode); /** * @ingroup hitls * @brief Obtain the shutdown status of the TLS link. * * @param ctx [IN] TLS connection handle. * @param mode [OUT] TLS shutdown status: HITLS_SENT_SHUTDOWN / HITLS_RECEIVED_SHUTDOWN. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_GetShutdownState(const HITLS_Ctx *ctx, uint32_t *mode); /** * @ingroup hitls * @brief Obtain the HiTLS negotiation version. * * @param ctx [IN] TLS object * @param version [OUT] Negotiated version * @retval HITLS_SUCCESS, obtained successfully. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetNegotiatedVersion(const HITLS_Ctx *ctx, uint16_t *version); /** * @ingroup hitls * @brief Obtain the latest protocol version. * * @param ctx [IN] TLS object * @param maxVersion [OUT] Latest protocol version supported * @retval HITLS_SUCCESS, obtained successfully. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetMaxProtoVersion(const HITLS_Ctx *ctx, uint16_t *maxVersion); /** * @ingroup hitls * @brief Obtain the latest protocol version. * * @param ctx [IN] TLS object * @param maxVersion [OUT] Latest protocol version supported * @retval HITLS_SUCCESS, obtained successfully. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetMinProtoVersion(const HITLS_Ctx *ctx, uint16_t *minVersion); /** * @ingroup hitls * @brief Set the minimum protocol version based on the specified version. * * @param ctx [OUT] TLS object * @param versiion [IN] The given version * @attention The maximum version number and minimum version number must be both TLS and DTLS. Currently, * only DTLS 1.2 is supported. This interface is used together with the full configuration interfaces, * such as HITLS_CFG_NewDTLSConfig and HITLS_CFG_NewTLSConfig. * If the TLS full configuration is configured, only the TLS version can be set. * If full DTLS configuration is configured, only the DTLS version can be set. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetMinProtoVersion(HITLS_Ctx *ctx, uint16_t version); /** * @ingroup hitls * @brief Set the maximum protocol version that is supported based on the specified version. * * @param ctx [OUT] TLS object * @param versiion [IN] The given version * @attention The maximum version number and minimum version number must be both TLS and DTLS. Currently, * only DTLS 1.2 is supported. This function is used together with the full configuration interfaces, * such as HITLS_CFG_NewDTLSConfig and HITLS_CFG_NewTLSConfig. * If the TLS full configuration is configured, only the TLS version can be set. * If full DTLS configuration is configured, only the DTLS version can be set. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetMaxProtoVersion(HITLS_Ctx *ctx, uint16_t version); /** * @ingroup hitls * @brief Obtain whether to use the AEAD algorithm. * * @param ctx [IN] TLS object * @param isAead [OUT] Indicates whether to use the AEAD algorithm. * @retval HITLS_SUCCESS, obtained successfully. * HITLS_NULL_INPUT, The input parameter pointer is null. */ int32_t HITLS_IsAead(const HITLS_Ctx *ctx, uint8_t *isAead); /** * @ingroup hitls * @brief Check whether DTLS is used. * * @param ctx [IN] TLS object * @param isDtls [OUT] Indicates whether to use DTLS. * @retval HITLS_SUCCESS, is obtained successfully. * HITLS_NULL_INPUT, The input parameter pointer is null. */ int32_t HITLS_IsDtls(const HITLS_Ctx *ctx, uint8_t *isDtls); /** * @ingroup hitls * @brief Record the error value of the HiTLS link. * * @param ctx [OUT] TLS connection handle * @param errorCode [IN] Error value * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetErrorCode(HITLS_Ctx *ctx, int32_t errorCode); /** * @ingroup hitls * @brief Obtain the error value of the HiTLS link. * * @param ctx [OUT] TLS connection handle * @retval Link error value */ int32_t HITLS_GetErrorCode(const HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Obtain the information about whether the handshake is complete. * * @param ctx [OUT] TLS connection handle * @param isDone [IN] Indicates whether the handshake is complete. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_IsHandShakeDone(const HITLS_Ctx *ctx, uint8_t *isDone); /** * @ingroup hitls * @brief Indicates whether the HiTLS object functions as the server. * * @param ctx [OUT] TLS connection handle * @param isServer [IN] Indicates whether to function as the server. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_IsServer(const HITLS_Ctx *ctx, uint8_t *isServer); /** * @ingroup hitls * @brief Check the HiTLS object in the read cache. * * (including processed and unprocessed data, excluding the network layer) Whether there is data * * @param ctx [IN] TLS connection handle * @param isPending [OUT] Whether there is data. The options are as follows: 1: yes; 0: no. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_ReadHasPending(const HITLS_Ctx *ctx, uint8_t *isPending); /** * @ingroup hitls * @brief Obtain the number of bytes of application data to be read from the current record from the HiTLS object. * * @attention When the HiTLS works in data packet transmission (DTLS), the HITLS_Read may * copy part of the application packet because the input buffer is not large enough. * This function is used to obtain the remaining size of the application packet. * This is useful for transport over DTLS. * @param ctx [IN] TLS connection handle * @retval Number of bytes of application data that can be read. */ uint32_t HITLS_GetReadPendingBytes(const HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Obtain the signature hash algorithm used by the peer end. * * @param ctx [IN] TLS connection handle * @param peerSignScheme [OUT] Peer signature hash algorithm * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_GetPeerSignScheme(const HITLS_Ctx *ctx, HITLS_SignHashAlgo *peerSignScheme); /** * @ingroup hitls * @brief Obtain the signature hash algorithm used by the local end. * * @param ctx [IN] TLS connection handle * @param localSignScheme [OUT] Local signature hash algorithm * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_GetLocalSignScheme(const HITLS_Ctx *ctx, HITLS_SignHashAlgo *localSignScheme); /** * @ingroup hitls * @brief Set the group supported by the hitls object. * * @param ctx [OUT] hitls context * @param lst [IN] group list * @param groupSize [IN] List length * @retval HITLS_SUCCESS is set successfully. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetEcGroups(HITLS_Ctx *ctx, uint16_t *lst, uint32_t groupSize); /** * @ingroup hitls * @brief Set the signature algorithm supported by the hitls object. * * @param ctx [OUT] hitls context. * @param signAlgs [IN] List of supported signature algorithms. * @param signAlgsSize [IN] Length of the signature algorithm list. * @retval HITLS_SUCCESS, set successfully. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetSigalgsList(HITLS_Ctx *ctx, const uint16_t *signAlgs, uint16_t signAlgsSize); /** * @ingroup hitls * @brief Set the EC point format of the hitls. * * @attention Currently, the value can only be HITLS_ECPOINTFORMAT_UNCOMPRESSED. * @param ctx [OUT] hitls context. * @param pointFormats [IN] ec point format, corresponding to the HITLS_ECPointFormat enumerated value. * @param pointFormatsSize [IN] Length of the ec point format * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetEcPointFormats(HITLS_Ctx *ctx, const uint8_t *pointFormats, uint32_t pointFormatsSize); /** * @ingroup hitls * @brief Set whether to verify the client certificate. * * @param ctx [OUT] TLS connection handle * @param support [IN] Indicates whether to verify the client certificate, the options are * as follows: true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_SetClientVerifySupport(HITLS_Ctx *ctx, bool support); /** * @ingroup hitls * @brief Set whether to support the function without the client certificate, Takes effect only when the client * certificate is verified. * * Client: This setting has no impact. * Server: When an NULL certificate is received from the client, indicates whether the certificate passes * the verification, the verification fails by default. * * @param ctx [OUT] TLS connection handle * @param support [IN] Indicates whether the authentication is successful when there is no client certificate. true: If the certificate sent by the client is NULL, the server still passes the verification. false: If the certificate sent by the client is NULL, the server fails the verification. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_SetNoClientCertSupport(HITLS_Ctx *ctx, bool support); /** * @ingroup hitls * @brief Set whether to support post-handshake AUTH. * * @param ctx [OUT] TLS connection handle * @param support [IN] true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_SetPostHandshakeAuthSupport(HITLS_Ctx *ctx, bool support); /** * @ingroup hitls * @brief Set whether to support do not proceed dual-ended verification. * * @param ctx [OUT] TLS connection handle * @param support [IN] true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_SetVerifyNoneSupport(HITLS_Ctx *ctx, bool support); /** * @ingroup hitls * @brief Set whether the client certificate can be requested only once. * * @param ctx [OUT] TLS connection handle * @param support [IN] true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_SetClientOnceVerifySupport(HITLS_Ctx *ctx, bool support); /** * @ingroup hitls * @brief Obtain the value of hitlsConfig. * * @param ctx [IN] TLS connection handle * @retval NULL, The input parameter pointer is null. * @retval hitlsConfig in ctx. */ const HITLS_Config *HITLS_GetConfig(const HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Obtain the point of GlobalConfig * @param ctx [IN] TLS connection handle * @retval NULL The input parameter pointer is null * @retval GlobalConfig in ctx */ HITLS_Config *HITLS_GetGlobalConfig(const HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Clears the configured TLS1.3 cipher suite. * * @param ctx [IN] TLS connection handle. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_ClearTLS13CipherSuites(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Set the supported cipher suites. * * The sequence of the cipher suites affects the priority of the selected cipher suites. * The cipher suites with the highest priority are selected first. * * @attention Do not check the cipher suite to meet the changes in the supported version. * @param ctx [OUT] TLS connection handle. * @param cipherSuites [IN] Key suite array, corresponding to the HITLS_CipherSuite enumerated value. * @param cipherSuitesSize [IN] Key suite array length. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetCipherSuites(HITLS_Ctx *ctx, const uint16_t *cipherSuites, uint32_t cipherSuitesSize); /** * @ingroup hitls * @brief Obtain the negotiated cipher suite pointer. * * @param ctx [IN] TLS connection handle * @retval Pointer to the negotiated cipher suite. * NULL, the input parameter pointer is null. */ const HITLS_Cipher *HITLS_GetCurrentCipher(const HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Obtain the random number of the client and server during the handshake. * * @param ctx [IN] TLS connection handle * @param out [OUT] Random number obtained * @param outlen [OUT] Length of the input parameter out. * If the length is greater than the maximum random number length, the value will be changed. * @param isClient [IN] True, obtain the random number of the client. * False, obtain the random number of the server. * @retval HITLS_SUCCESS, obtaining the status succeeded. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetHsRandom(const HITLS_Ctx *ctx, uint8_t *out, uint32_t *outlen, bool isClient); /** * @ingroup hitls * @brief Obtain the current handshake status. * * @param ctx [IN] TLS connection handle * @param state [OUT] Current handshake status * @retval HITLS_SUCCESS, Obtaining the status succeeded. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetHandShakeState(const HITLS_Ctx *ctx, uint32_t *state); /** * @brief Obtain the handshake status character string. * * @param state [IN] Handshake status * @retval Character string corresponding to the handshake status */ const char *HITLS_GetStateString(uint32_t state); /** * @ingroup hitls * @brief Check whether a handshake is being performed. * * @param ctx [IN] TLS connection handle * @param isHandShaking [OUT] Indicates whether the handshake is in progress. * @retval HITLS_SUCCESS, Obtaining the status succeeded. * For other error codes, see hitls_error.h. */ int32_t HITLS_IsHandShaking(const HITLS_Ctx *ctx, uint8_t *isHandShaking); /** * @ingroup hitls * @brief Obtain whether renegotiation is supported. * * @param ctx [IN] hitls Context * @param isSupportRenegotiation [OUT] Whether to support renegotiation * @retval HITLS_SUCCESS, obtain successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetRenegotiationSupport(const HITLS_Ctx *ctx, uint8_t *isSupportRenegotiation); /** * @ingroup hitls * @brief Check whether the handshake has not been performed. * * @param ctx [IN] TLS connection handle * @param isBefore [OUT] Indicates whether the handshake has not been performed. * @retval HITLS_SUCCESS, obtaining the status succeeded. * For other error codes, see hitls_error.h. */ int32_t HITLS_IsBeforeHandShake(const HITLS_Ctx *ctx, uint8_t *isBefore); /** * @ingroup hitls * @brief Set the MTU of Data Link layer. * * @param ctx [IN] TLS connection handle * @param linkMtu [IN] MTU of Data Link layer. * @retval HITLS_SUCCESS, set the mtu succeeded. * @retval HITLS_CONFIG_INVALID_LENGTH, the mtu is invalid * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetLinkMtu(HITLS_Ctx *ctx, uint16_t linkMtu); /** * @ingroup hitls * @brief Set the MTU of a path. * * @param ctx [IN] TLS connection handle * @param mtu [IN] Set the MTU. * @retval HITLS_SUCCESS, set the mtu succeeded. * @retval HITLS_CONFIG_INVALID_LENGTH, the mtu is invalid * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetMtu(HITLS_Ctx *ctx, uint16_t mtu); /** * @ingroup hitls * @brief Set the option that don't query mtu from the bio. * * @param ctx [IN] TLS connection handle * @param noQueryMtu [IN] whether not to query the mtu from the bio. * @retval HITLS_SUCCESS, set the option succeeded. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetNoQueryMtu(HITLS_Ctx *ctx, bool noQueryMtu); /** * @ingroup hitls * @brief Querying whether the EMSGSIZE error occur and mtu need be modified * * @param ctx [IN] TLS connection handle. * @param needQueryMtu [IN] Indicates whether the EMSGSIZE error occur and mtu need be modified * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetNeedQueryMtu(HITLS_Ctx *ctx, bool *needQueryMtu); /** * @ingroup hitls * @brief Obtain the version number set by the client in ClientHello. * * @param ctx [IN] TLS connection handle * @param clientVersion [OUT] Obtained version number * @retval HITLS_SUCCESS, obtaining the status succeeded. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetClientVersion(const HITLS_Ctx *ctx, uint16_t *clientVersion); /** * @ingroup hitls * @brief The client/server starts handshake. * * @attention In the IDLE state, the HITLS_SetEndPoint must be called first. * @param ctx [IN] TLS connection handle * @retval HITLS_SUCCESS, obtaining the status succeeded. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_DoHandShake(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Check whether the current end is client. * * @param ctx [IN] TLS connection handle * @param isClient [OUT] Client or not. * @retval HITLS_SUCCESS, obtaining the status succeeded. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_IsClient(const HITLS_Ctx *ctx, bool *isClient); /** * @ingroup hitls * @brief Set the keyupdate type of the current context and send the keyupdate message. * * @param ctx [IN] TLS connection handle * @param updateType [IN] keyupdate type * @retval HITLS_SUCCESS, if successful. * For other error codes, see hitls_error.h. */ int32_t HITLS_KeyUpdate(HITLS_Ctx *ctx, uint32_t updateType); /** * @ingroup hitls * @brief Return the keyupdate type of the current context. * * @param ctx [IN] TLS connection handle * @retval KeyUpdateType in ctx * @retval NULL, the input parameter pointer is null. */ int32_t HITLS_GetKeyUpdateType(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Obtain the supported peer group or the number of supported peer groups of the nth match. * * nmatch Value range: - 1 or a positive integer * This function can be called only after negotiation and can be called only by the server. * If nmatch is a positive integer, check the intersection of groups on the client and server, * and return the nmatch group in the intersection by groupId. * If the value of nmatch is - 1, the number of intersection groups on the client and server is * returned based on groupId. * * @param ctx [IN] TLS connection handle. * @param nmatch [IN] Sequence number of the group to be obtained, -1 Return the number of supported peer groups. * @param groupId [OUT] Returned result. * @retval HITLS_SUCCESS, Obtaining the status succeeded. * For details about other error codes, see hitls_error.h. * */ int32_t HITLS_GetSharedGroup(const HITLS_Ctx *ctx, int32_t nmatch, uint16_t *groupId); /** * @ingroup hitls * @brief Set the DTLS timeout interval callback. * @param ctx [IN] TLS connection handle. * @param cb [IN] DTLS obtaining timeout interval callback. * @return HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetDtlsTimerCb(HITLS_Ctx *ctx, HITLS_DtlsTimerCb cb); /** * @ingroup hitls * @brief Obtain the supported version number. * * @param ctx [IN] TLS connection handle. * @param version [OUT] Supported version number. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_GetVersionSupport(const HITLS_Ctx *ctx, uint32_t *version); /** * @ingroup hitls * @brief Set the supported version number. * * @param ctx [OUT] TLS connection handle * @param version [IN] Supported version number. * @attention The maximum version number and minimum version number must be both TLS and DTLS. Currently, * only DTLS 1.2 is supported. This function is used together with the full configuration interfaces, * such as HITLS_CFG_NewDTLSConfig and HITLS_CFG_NewTLSConfig. * If the TLS full configuration is configured, only the TLS version can be set. If full DTLS configuration * is configured, only the DTLS version can be set. * The versions must be consecutive. By default, the minimum and maximum versions are supported. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_SetVersionSupport(HITLS_Ctx *ctx, uint32_t version); /** * @ingroup hitls * @brief Set the supported version number range. * * @param ctx [OUT] TLS connection handle * @param minVersion [IN] Minimum version number supported. * @param maxVersion [IN] Maximum version number supported. * @attention The maximum version number and minimum version number must be both TLS and DTLS. * Currently, only DTLS 1.2 is supported. This function is used together with the full configuration interfaces, * such as HITLS_CFG_NewDTLSConfig and HITLS_CFG_NewTLSConfig. * If the TLS full configuration is configured, only the TLS version can be set. If full DTLS configuration is * configured, only the DTLS version can be set. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_SetVersion(HITLS_Ctx *ctx, uint32_t minVersion, uint32_t maxVersion); /** * @ingroup hitls * @brief Set the version number to be disabled. * * @param ctx [OUT] TLS connection handle * @param noVersion [IN] Disabled version number. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_SetVersionForbid(HITLS_Ctx *ctx, uint32_t noVersion); /** * @ingroup hitls * @brief Sets whether to verify the version in the premaster secret. * * @param ctx [OUT] TLS Connection Handle. * @param needCheck [IN] Indicates whether to perform check. * @attention This parameter is valid for versions earlier than TLS1.1. * true indicates that verification is supported, and false indicates that verification is not supported. In * this case, rollback attacks may occur. For versions later than TLS1.1, forcible verification is supported. * This interface takes effect on the server. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_SetNeedCheckPmsVersion(HITLS_Ctx *ctx, bool needCheck); /** * @ingroup hitls * @brief Set the silent disconnection mode. * * @param ctx [IN] TLS connection handle. * @param mode [IN] Mode type. The value 0 indicates that the quiet disconnection mode is disabled, and the value 1 * indicates that the quiet disconnection mode is enabled. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetQuietShutdown(HITLS_Ctx *ctx, int32_t mode); /** * @ingroup hitls * @brief Obtain the current silent disconnection mode. * * @param ctx [IN] TLS connection handle * @param mode [OUT] Mode type. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetQuietShutdown(const HITLS_Ctx *ctx, int32_t *mode); /** * @ingroup hitls * @brief Sets whether to support the function of automatically selecting DH parameters. * * If the value is true, the DH parameter is automatically selected based on the length of the certificate private key. * If the value is false, the DH parameter needs to be set. * * @param ctx [IN/OUT] hitls context. * @param support [IN] Whether to support. The options are as follows: true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, ctx is null. */ int32_t HITLS_SetDhAutoSupport(HITLS_Ctx *ctx, bool support); /** * @ingroup hitls * @brief Set the DH parameter specified by the user. * * @param ctx [IN/OUT] hitls context. * @param dhPkey [IN] User-specified DH key. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT ctx or dhPkey field is NULL */ int32_t HITLS_SetTmpDh(HITLS_Ctx *ctx, HITLS_CRYPT_Key *dhPkey); /** * @ingroup hitls * @brief Set the TmpDh callback function. * @param ctx [IN/OUT] TLS connection handle. * @param callback [IN] Set the TmpDh callback. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetTmpDhCb(HITLS_Ctx *ctx, HITLS_DhTmpCb callback); /** * @ingroup hitls * @brief Sets the RecordPadding callback. * * @param ctx [IN/OUT] TLS Connection Handle * @param callback [IN] Sets the RecordPadding callback. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetRecordPaddingCb(HITLS_Ctx *ctx, HITLS_RecordPaddingCb callback); /** * @ingroup hitls * @brief Obtains the RecordPadding callback function. * * @param ctx [IN/OUT] TLS Connection Handle * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ HITLS_RecordPaddingCb HITLS_GetRecordPaddingCb(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Sets the parameters arg required by the RecordPadding callback function. * * @param ctx [IN/OUT] TLS Connection Handle * @param arg [IN] Related Parameter arg * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetRecordPaddingCbArg(HITLS_Ctx *ctx, void *arg); /** * @ingroup hitls * @brief Obtains the parameter arg required by the RecordPadding callback function. * * @param ctx [IN/OUT] TLS Connection Handle * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ void *HITLS_GetRecordPaddingCbArg(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Obtain the verification data and length of the peer end based on the received finished message. * * @param ctx [IN] TLS context * @param buf [OUT] verify data * @param bufLen [IN] Length of the buffer to be obtained * @param dataLen [OUT] Actual length of the buf * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetPeerFinishVerifyData(const HITLS_Ctx *ctx, void *buf, uint32_t bufLen, uint32_t *dataLen); /** * @ingroup hitls * @brief Disables the verification of keyusage in the certificate. This function is enabled by default. * * @param ctx [OUT] config context * @param isCheck [IN] Sets whether to check key usage. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetCheckKeyUsage(HITLS_Ctx *ctx, bool isCheck); /** * @ingroup hitls * @brief Obtain the verification data and length of the local end based on the sent finished message. * * @param ctx [IN] TLS context * @param buf [OUT] verify data * @param bufLen [IN] Length of the buffer to be obtained * @param dataLen [OUT] Indicates the actual length of the buffer * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetFinishVerifyData(const HITLS_Ctx *ctx, void *buf, uint32_t bufLen, uint32_t *dataLen); /** * @ingroup hitls * @brief Obtains whether security renegotiation is supported. * * @param ctx [IN] hitls context. * @param isSecureRenegotiation [OUT] Whether to support security renegotiation * @retval HITLS_SUCCESS, obtained successfully. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetSecureRenegotiationSupport(const HITLS_Ctx *ctx, uint8_t *isSecureRenegotiation); /** * @ingroup hitls * @brief Perform renegotiation. * * @attention 1. After this interface is called, the user needs to call one of the * HITLS_Connect / HITLS_Accept / HITLS_Read / HITLS_Write interfaces again, * The HITLS_Renegotiate interface is used only for setting and initialization of renegotiation, * The renegotiation process is performed when the user calls the * HITLS_Connect / HITLS_Accept / HITLS_Read / HITLS_Write. * 2. You are advised to use the HITLS_Connect / HITLS_Accept interface for renegotiation. * After the negotiation is complete, call the HITLS_Read / HITLS_Write interface. * 3. If the user uses HITLS_Read to perform renegotiation, * the user may receive the app message from the peer end during the renegotiation. * (1) If the renegotiation has not started, the HiTLS will return the message to the user. * (2) If the renegotiation is in progress, no app message is received in this scenario, * and the HiTLS sends an alert message to disconnect the link. * 4. If the user uses the HITLS_Connect / HITLS_Accept / HITLS_Write for renegotiation, * the user may receive the app message from the peer end during the renegotiation, * HiTLS caches the message, the message is returned when a user calls HITLS_Read. * Maximum of 50 app messages can be cached, if the cache is full, subsequent app messages will be * ignored. * 5. In the DTLS over UDP scenario, if the user functions as the server, * packet loss occurs in the renegotiation request(hello request). * (1) If the user calls the HITLS_Write for renegotiation, the app message to be sent is * sent to the peer end after packet loss occurs in the renegotiation request. * (2) The HiTLS does not retransmit the renegotiation request. The user needs to call the * HITLS_Renegotiate and HITLS_Accept interfaces again to continue the renegotiation. * You can call the HITLS_GetRenegotiationState interface to determine * whether the current renegotiation is in the renegotiation state, * If the renegotiation is not in the renegotiation state, * call the HITLS_Renegotiate and HITLS_Accept interfaces again to continue the renegotiation. * 6. In the DTLS over UDP scenario, if the user as the client, * packet loss occurs in the renegotiation request (client hello). * (1) If the user calls the HITLS_Write to perform renegotiation, the app message is not * sent to the peer end after packet loss occurs in the renegotiation request. * Instead, the user waits for the response from the peer end. * (2) The client hello message is retransmitted inside the HiTLS, * and the user does not need to initiate renegotiation again. * @param ctx [IN] TLS Connection Handle * * @retval HITLS_SUCCESS, if successful. * @retval For details about other error codes, see hitls_error.h. */ int32_t HITLS_Renegotiate(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Obtain the current is whether in the renegotiation state. * * @attention For the server, the server does not enter the renegotiation state by sending only the hello request * message, The server enters the renegotiation state only after receiving the client hello message. * * @param ctx [IN] TLS Connection Handle. * @param isRenegotiationState [OUT] Indicates whether the renegotiation is in the renegotiation state. * true: in the renegotiation state; false: not in the renegotiation state. * * @retval HITLS_SUCCESS, if successful. * @retval For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetRenegotiationState(const HITLS_Ctx *ctx, uint8_t *isRenegotiationState); /** * @ingroup hitls * @brief Obtain the current internal status. * * @param ctx [IN] TLS connection Handle. * @param rwState [OUT] Current internal status information. * @retval HITLS_SUCCESS, if successful. * @retval For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetRwstate(const HITLS_Ctx *ctx, uint8_t *rwstate); /** * @ingroup hitls * @brief Check whether the client certificate can be verified. * * @param ctx [IN] TLS connection Handle. * @param isSupport [OUT] Indicates whether to verify the client certificate. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, ctx is null. */ int32_t HITLS_GetClientVerifySupport(HITLS_Ctx *ctx, uint8_t *isSupport); /** * @ingroup hitls * @brief Check whether no client certificate is supported, This command is valid only when client certificate * verification is enabled. * * @param ctx [IN] TLS Connection Handle. * @param isSupport [OUT] Whether no client certificate is supported. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, ctx is null. */ int32_t HITLS_GetNoClientCertSupport(HITLS_Ctx *ctx, uint8_t *isSupport); /** * @ingroup hitls * @brief Query whether post-handshake AUTH is supported * * @param ctx [IN] TLS connection Handle. * @param isSupport [OUT] indicates whether to support post-handshake AUTH. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, ctx is null. */ int32_t HITLS_GetPostHandshakeAuthSupport(HITLS_Ctx *ctx, uint8_t *isSupport); /** * @ingroup hitls * @brief Query if support is available for not performing dual-end verification. * * @param ctx [IN] TLS Connection Handle. * @param isSupport [OUT] if support is available for not performing dual-end verification. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, ctx is null. */ int32_t HITLS_GetVerifyNoneSupport(HITLS_Ctx *ctx, uint8_t *isSupport); /** * @ingroup hitls * @brief Query whether the client certificate can be requested only once. * * @param ctx [IN] TLS Connection Handle. * @param isSupport [OUT] Indicates whether the client certificate can be requested only once. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, ctx is null. */ int32_t HITLS_GetClientOnceVerifySupport(HITLS_Ctx *ctx, uint8_t *isSupport); /** * @ingroup hitls * @brief Clears the renegotiation count. * * @param ctx [IN] hitls context. * @param renegotiationNum [OUT] Number of incoming renegotiations. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_ClearRenegotiationNum(HITLS_Ctx *ctx, uint32_t *renegotiationNum); /** * @ingroup hitls * @brief Obtain the negotiated group information. * * @param ctx [IN] TLS Connection Handle. * @param group [OUT] Negotiated group information. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, ctx is null. */ int32_t HITLS_GetNegotiateGroup(const HITLS_Ctx *ctx, uint16_t *group); /** * @ingroup hitls * @brief Set the function to support the specified feature. * * @param ctx [OUT] TLS Connection Handle * @param mode [IN] Mode features to enabled. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetModeSupport(HITLS_Ctx *ctx, uint32_t mode); /** * @ingroup hitls * @brief Function to clear the specified feature. * * @param ctx [OUT] TLS Connection Handle * @param mode [IN] Mode features to clear. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_ClearModeSupport(HITLS_Ctx *ctx, uint32_t mode); /** * @ingroup hitls * @brief Obtain the mode of the function feature in the config file. * * @param ctx [OUT] TLS Connection Handle * @param mode [OUT] Mode obtain the output parameters of the mode. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetModeSupport(const HITLS_Ctx *ctx, uint32_t *mode); /** * @ingroup hitls * @brief Setting the Encrypt-Then-Mac mode. * * @param ctx [IN] TLS connection handle. * @param encryptThenMacType [IN] Current Encrypt-Then-Mac mode. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetEncryptThenMac(HITLS_Ctx *ctx, uint32_t encryptThenMacType); /** * @ingroup hitls * @brief Obtains the Encrypt-Then-Mac type * * @param ctx [IN] TLS connection Handle. * @param encryptThenMacType [OUT] Current Encrypt-Then-Mac mode. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetEncryptThenMac(const HITLS_Ctx *ctx, uint32_t *encryptThenMacType); /** * @ingroup hitls * @brief Setting the value of server_name. * * @param ctx [IN] TLS connection handle. * @param serverName [IN] serverName. * @param serverNameStrlen [IN] serverName length. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetServerName(HITLS_Ctx *ctx, uint8_t *serverName, uint32_t serverNameStrlen); /** * @ingroup hitls * @brief The algorithm suite can be preferentially selected from the algorithm list supported by the server. * * @param ctx [IN] TLS Connection Handle. * @param isSupport [IN] Support or Not. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetCipherServerPreference(HITLS_Ctx *ctx, bool isSupport); /** * @ingroup hitls * @brief Obtains whether the current cipher suite supports preferential selection * from the list of algorithms supported by the server. * * @param ctx [IN] TLS connection handle. * @param isSupport [OUT] Support or Not. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetCipherServerPreference(const HITLS_Ctx *ctx, bool *isSupport); /** * @ingroup hitls * @brief Sets whether to support renegotiation. * * @param ctx [IN/OUT] TLS connection handle. * @param isSupport [IN] Support or Not, true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. */ int32_t HITLS_SetRenegotiationSupport(HITLS_Ctx *ctx, bool isSupport); /** * @ingroup hitls * @brief Set whether to allow a renegotiate request from the client * @param ctx [IN/OUT] TLS connection handle. * @param isSupport [IN] Support or Not, true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. */ int32_t HITLS_SetClientRenegotiateSupport(HITLS_Ctx *ctx, bool isSupport); /** * @ingroup hitls * @brief Set whether to abort handshake when server doesn't support SecRenegotiation * @param ctx [IN/OUT] TLS connection handle. * @param isSupport [IN] Support or Not, true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. */ int32_t HITLS_SetLegacyRenegotiateSupport(HITLS_Ctx *ctx, bool isSupport); /** * @ingroup hitls * @brief Sets whether to support session tickets. * * @param ctx [IN/OUT] TLS connection handle. * @param isSupport [IN] whether to support session tickets, true: yes; false: no * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. */ int32_t HITLS_SetSessionTicketSupport(HITLS_Ctx *ctx, bool isSupport); /** * @ingroup hitls * @brief Check whether the session ticket is supported. * * @param ctx [IN] TLS connection handle. * @param isSupport [OUT] whether to support session tickets, true: yes; false: no * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. */ int32_t HITLS_GetSessionTicketSupport(const HITLS_Ctx *ctx, uint8_t *isSupport); /** * @ingroup hitls * @brief Sets whether to perform cookie exchange in the dtls. * * @param ctx [IN] TLS connection handle. * @param isSupport [IN] Indicates whether to perform cookie exchange * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetDtlsCookieExangeSupport(HITLS_Ctx *ctx, bool isSupport); /** * @ingroup hitls * @brief Querying whether the DTLS performs cookie exchange. * * @param ctx [IN] TLS connection handle. * @param isSupport [IN] Indicates whether to perform cookie exchange. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetDtlsCookieExangeSupport(const HITLS_Ctx *ctx, bool *isSupport); /** * @ingroup hitls * @brief Sets whether to send handshake messages by flight distance. * * @param ctx [IN/OUT] TLS connection handle. * @param isEnable [IN] Indicates whether to enable handshake information sending by flight distance. * The value 0 indicates disable, other values indicate enable. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetFlightTransmitSwitch(HITLS_Ctx *ctx, uint8_t isEnable); /** * @ingroup hitls * @brief Obtains the status of whether to send handshake information according to the flight distance. * * @param ctx [IN] TLS connection handle. * @param isEnable [OUT] Indicates whether to send handshake information by flight distance * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetFlightTransmitSwitch(const HITLS_Ctx *ctx, uint8_t *isEnable); /** * @ingroup hitls * @brief set the max empty records number can be received * * @param ctx [IN/OUT] TLS connection handle. * @param emptyNum [IN] Indicates the max number of empty records can be received * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetEmptyRecordsNum(HITLS_Ctx *ctx, uint32_t emptyNum); /** * @ingroup hitls * @brief Obtain the max empty records number can be received * * @param ctx [IN] TLS connection handle. * @param emptyNum [OUT] Indicates the max number of empty records can be received * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetEmptyRecordsNum(const HITLS_Ctx *ctx, uint32_t *emptyNum); /** * @ingroup hitls * @brief set the max send fragment to restrict the amount of plaintext bytes in any record * * @param ctx [IN/OUT] TLS connection handle. * @param maxSendFragment [IN] Indicates the max send fragment * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_CONFIG_INVALID_LENGTH, the maxSendFragment is less than 64 or greater than 16384. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetMaxSendFragment(HITLS_Ctx *ctx, uint16_t maxSendFragment); /** * @ingroup hitls * @brief Obtain the max send fragment to restrict the amount of plaintext bytes in any record * * @param ctx [IN] TLS connection handle. * @param maxSendFragment [OUT] Indicates the max send fragment * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetMaxSendFragment(const HITLS_Ctx *ctx, uint16_t *maxSendFragment); /** * @ingroup hitls * @brief Set the rec inbuffer inital size * * @param ctx [IN/OUT] TLS connection handle. * @param recInbufferSize [IN] Indicates the rec inbuffer inital size * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_CONFIG_INVALID_LENGTH, the recInbufferSize is less than 512 or greater than 18432. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetRecInbufferSize(HITLS_Ctx *ctx, uint32_t recInbufferSize); /** * @ingroup hitls * @brief Obtain the rec inbuffer inital size * * @param ctx [IN] TLS connection handle. * @param recInbufferSize [OUT] Indicates the rec inbuffer inital size * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetRecInbufferSize(const HITLS_Ctx *ctx, uint32_t *recInbufferSize); /** * @ingroup hitls * @brief Sets the maximum size of the certificate chain that can be sent from the peer end. * * @param ctx [IN/OUT] TLS connection handle. * @param maxSize [IN] Sets the maximum size of the certificate chain that can be sent from the peer end. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetMaxCertList(HITLS_Ctx *ctx, uint32_t maxSize); /** * @ingroup hitls * @brief Obtains the maximum size of the certificate chain that can be sent by the peer end. * * @param ctx [IN] TLS connection handle. * @param maxSize [OUT] Maximum size of the certificate chain that can be sent from the peer end. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetMaxCertList(const HITLS_Ctx *ctx, uint32_t *maxSize); /** * @ingroup hitls * @brief This interface is valid only on the server. When the post-handshake command is configured, * the client identity is verified through this interface. * * @param ctx [IN] TLS Connection Handle * @retval HITLS_INVALID_INPUT, invalid input parameter. * @retval HITLS_SUCCESS, if successful. * @retval For details about other error codes, see hitls_error.h. */ int32_t HITLS_VerifyClientPostHandshake(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Obtain the legacy version from client hello. * @attention This interface is valid only in client hello callback. * @param ctx [IN] TLS connection handle. * @param out [OUT] Pointer to the output buffer for legacy version. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_ClientHelloGetLegacyVersion(HITLS_Ctx *ctx, uint16_t *version); /** * @ingroup hitls * @brief Obtain the random value from client hello. * * @attention This interface is valid only in client hello callback. * @param ctx [IN] TLS connection handle. * @param out [OUT] Pointer to the output buffer for random value. * @param outlen [IN] Length of the output buffer. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_ClientHelloGetRandom(HITLS_Ctx *ctx, uint8_t **out, uint8_t *outlen); /** * @ingroup hitls * @brief Obtain the session ID from client hello. * * @attention This interface is valid only in client hello callback. * @param ctx [IN] TLS connection handle. * @param out [OUT] Pointer to the output buffer for session ID. * @param outlen [OUT] Length of the output buffer. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_ClientHelloGetSessionID(HITLS_Ctx *ctx, uint8_t **out, uint8_t *outlen); /** * @ingroup hitls * @brief Obtain the cipher suites from client hello. * * @attention This interface is valid only in client hello callback. * @param ctx [IN] TLS connection handle. * @param out [OUT] Pointer to the output buffer for cipher suites. * @param outlen [OUT] Length of the output buffer. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_ClientHelloGetCiphers(HITLS_Ctx *ctx, uint16_t **out, uint16_t *outlen); /** * @ingroup hitls * @brief Obtain the all extension types from client hello. * * @attention This interface is valid only in client hello callback. * @attention the caller must release the storage allocated for *out using BSL_SAL_FREE(). * @param ctx [IN] TLS connection handle. * @param out [OUT] Pointer to the output buffer for all extensions. * @param outlen [OUT] Length of the output buffer. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_ClientHelloGetExtensionsPresent(HITLS_Ctx *ctx, uint16_t **out, uint8_t *outlen); /** * @ingroup hitls * @brief Obtain a specific extension from client hello. * * @attention This interface is valid only in client hello callback. * @param ctx [IN] TLS connection handle. * @param type [IN] Type of the extension to be obtained. * @param out [OUT] Pointer to the output buffer for the extension. * @param outlen [OUT] Length of the output buffer. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_ClientHelloGetExtension(HITLS_Ctx *ctx, uint16_t type, uint8_t **out, uint32_t *outlen); /** * @ingroup hitls * @brief Handle the timeout of sending and receiving DTLS messages. * * @param ctx [IN] TLS Connection Handle * @retval HITLS_SUCCESS, if retransmit the message successful. * @retval HITLS_MSG_HANDLE_DTLS_RETRANSMIT_NOT_TIMEOUT, It hasn't timed out yet. * @retval For details about other error codes, see hitls_error.h. */ int32_t HITLS_DtlsProcessTimeout(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Get the remaining timeout time for timeout retransmission. * * @param ctx [IN] TLS Connection Handle * @param remainTimeOut [OUT] remaining timeout time for timeout retransmission, unit: us * @retval HITLS_SUCCESS, if successful. * @retval HITLS_MSG_HANDLE_ERR_WITHOUT_TIMEOUT_ACTION, Indicates non UDP links or absence of timeout behavior. * @retval For details about other error codes, see hitls_error.h. */ int32_t HITLS_DtlsGetTimeout(HITLS_Ctx *ctx, uint64_t *remainTimeOut); /** * @ingroup hitls * @brief Sets whether to support middle box compat mode. * * @param ctx [IN] TLS Connection Handle. * @param isMiddleBox [IN] Support or Not. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_SetMiddleBoxCompat(HITLS_Ctx *ctx, bool isMiddleBox); /** * @ingroup hitls * @brief Obtain whether middle box compat mode is supported. * * @param ctx [IN] TLS connection handle. * @param isMiddleBox [OUT] Support or Not. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetMiddleBoxCompat(HITLS_Ctx *ctx, bool *isMiddleBox); /** * @brief Obtain the record out buffer remaining size * * @param ctx [IN] TLS connection handle * @param size [OUT] record out buffer remaining size * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_GetOutPendingSize(const HITLS_Ctx *ctx, uint32_t *size); /** * @brief Flush the record out buffer * * @param ctx [IN] TLS connection handle * * @retval HITLS_SUCCESS Out buffer is empty or flush success * @retval HITLS_REC_NORMAL_IO_BUSY Out buffer is not empty, but the IO operation is busy */ int32_t HITLS_Flush(HITLS_Ctx *ctx); #ifdef __cplusplus } #endif #endif /* HITLS_H */
2301_79861745/bench_create
include/tls/hitls.h
C
unknown
64,081
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_alpn * @ingroup hitls * @brief TLS ALPN related type */ #ifndef HITLS_ALPN_H #define HITLS_ALPN_H #include <stdint.h> #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define HITLS_ALPN_ERR_OK 0 /* Correct execution. */ #define HITLS_ALPN_ERR_ALERT_WARNING 1 /* Execution error, sent warning alert. */ #define HITLS_ALPN_ERR_ALERT_FATAL 2 /* Execution error, sent fatal alert. */ #define HITLS_ALPN_ERR_NOACK 3 /* Execution exception, ignore processing. */ /** * @ingroup hitls_alpn * @brief Callback prototype for selecting the ALPN protocol on the server, which is used to select * the application layer protocol during ALPN negotiation. * * @param ctx [IN] Ctx context. * @param selectedProto [OUT] Indicates the initial IP address of the protocol that is being matched. * @param selectedProtoLen [OUT] Matching protocol length. * @param clientAlpnList [IN] Client ALPN List. * @param clientAlpnListSize [IN] Client ALPN List length. * @param userData [IN] Context transferred by the user. * @retval HITLS_ALPN_ERR_OK 0, indicates success. HITLS_ALPN_ERR_ALERT_WARNING 1, indicates send warning alert. HITLS_ALPN_ERR_ALERT_FATAL 2, indicates send fatal alert. HITLS_ALPN_ERR_NOACK 3, indicates no processing. */ typedef int32_t (*HITLS_AlpnSelectCb)(HITLS_Ctx *ctx, uint8_t **selectedProto, uint8_t *selectedProtoSize, uint8_t *clientAlpnList, uint32_t clientAlpnListSize, void *userData); /** * @ingroup hitls_alpn * @brief Sets the ALPN list on the client, which is used to negotiate the application layer protocol * with the server in the handshake phase. * * @param config [OUT] Config context. * @param alpnProtos [IN] Application layer protocol list. * @param alpnProtosLen [IN] Length of the application layer protocol list. * @retval If success, return HITLS_SUCCESS. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetAlpnProtos(HITLS_Config *config, const uint8_t *alpnProtos, uint32_t alpnProtosLen); /** * @ingroup hitls_alpn * @brief Sets the ALPN selection callback on the server. * * The callback is used to select the application layer protocol in the handshake phase, cb can be NULL. * * @param config [OUT] Config context. * @param callback [IN] Server callback implemented by the user. * @param userData [IN] Product context. * @retval If success, return HITLS_SUCCESS. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetAlpnProtosSelectCb(HITLS_Config *config, HITLS_AlpnSelectCb callback, void *userData); /** * @ingroup hitls_alpn * @brief Sets the client ALPN list, which is used to negotiate the application layer protocol * with the server in the handshake phase. * * @param ctx [OUT] TLS connection Handle. * @param protos [IN] Application layer protocol list. * @param protosLen [IN] Length of the application layer protocol list. * @retval If success, return HITLS_SUCCESS. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetAlpnProtos(HITLS_Ctx *ctx, const uint8_t *protos, uint32_t protosLen); /** * @ingroup hitls_alpn * @brief Obtaining the ALPN Negotiation Result * * @param ctx [IN] Ctx context. * @param proto [OUT] Header address of the outgoing selected protocol. * @param protoLen [OUT] Length of the outgoing selected protocol. * @retval If success, return HITLS_SUCCESS. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetSelectedAlpnProto(HITLS_Ctx *ctx, uint8_t **proto, uint32_t *protoLen); #ifdef __cplusplus } #endif #endif // HITLS_ALPN_H
2301_79861745/bench_create
include/tls/hitls_alpn.h
C
unknown
4,359
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_cert * @ingroup hitls * @brief TLS Certificate Operation Interface */ #ifndef HITLS_CERT_H #define HITLS_CERT_H #include <stdbool.h> #include <stdint.h> #include <stddef.h> #include "hitls_type.h" #include "hitls_cert_type.h" #include "hitls_error.h" #ifdef __cplusplus extern "C" { #endif /** * @ingroup hitls_cert * @brief Set the verify store used by the TLS configuration, which is used for certificate verification. * * @param config [OUT] TLS link configuration. * @param store [IN] CA certificate store. * @param isClone [IN] Indicates whether deep copy is required. true indicates need, false indicates not need. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetVerifyStore(HITLS_Config *config, HITLS_CERT_Store *store, bool isClone); /** * @ingroup hitls_cert * @brief Obtain the verify store used by the TLS configuration. * * @attention The user cannot release the memory. * * @param config [IN] TLS link configuration * @retval Verify store */ HITLS_CERT_Store *HITLS_CFG_GetVerifyStore(const HITLS_Config *config); /** * @ingroup hitls_cert * @brief Set the verify store used by the TLS link for certificate verification. * * @param ctx [OUT] TLS link object * @param store [IN] CA certificate store * @param isClone [IN] Indicates whether deep copy is required. The options are true and false. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetVerifyStore(HITLS_Ctx *ctx, HITLS_CERT_Store *store, bool isClone); /** * @ingroup hitls_cert * @brief Obtain the verify store used by the TLS link. * * @param ctx [IN] TLS link object * @retval Verify store */ HITLS_CERT_Store *HITLS_GetVerifyStore(const HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Set the chain store used by the TLS configuration, which is used to construct the certificate chain. * * @param config [OUT] TLS link configuration * @param store [IN] Certificate chain store * @param isClone [IN] Indicates whether deep copy is required. The options are as follows: true: yes; false: no. * @retval HITLS_SUCCESS. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetChainStore(HITLS_Config *config, HITLS_CERT_Store *store, bool isClone); /** * @ingroup hitls_cert * @brief Obtain the chain store used by the TLS configuration. * * @attention The user cannot release the memory. * @param config [IN] TLS link configuration * @retval Chain store */ HITLS_CERT_Store *HITLS_CFG_GetChainStore(const HITLS_Config *config); /** * @ingroup hitls_cert * @brief Set the chain store used by the TLS link to construct the certificate chain. * * @param ctx [OUT] TLS link object * @param store [IN] Certificate chain * @param isClone [IN] Indicates whether deep copy is required. The options are true and false. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetChainStore(HITLS_Ctx *ctx, HITLS_CERT_Store *store, bool isClone); /** * @ingroup hitls_cert * @brief Obtain the chain store used by the TLS link. * * @param ctx [IN] TLS object * @retval Chain Store */ HITLS_CERT_Store *HITLS_GetChainStore(const HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Set the cert store used by the TLS configuration. * * @attention If verify store is not set, use cert store to verify the certificate. * If chain store is not set, use cert store to construct a certificate chain. * @param config [OUT] TLS link configuration * @param store [IN] Trust certificate store * @param isClone [IN] Indicates whether deep copy is required. The options are true and false. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetCertStore(HITLS_Config *config, HITLS_CERT_Store *store, bool isClone); /** * @ingroup hitls_cert * @brief Obtain the cert store used by the TLS configuration. * * @attention The user cannot release the memory. * @param config [IN] TLS link configuration * @retval Cert store */ HITLS_CERT_Store *HITLS_CFG_GetCertStore(const HITLS_Config *config); /** * @ingroup hitls_cert * @brief Set the cert store used by the TLS link. * * @attention If verify store is not set, use cert store to verify the certificate. * If chain store is not set, use cert store to construct a certificate chain. * @param ctx [OUT] TLS link object * @param store [IN] Trust certificate store * @param isClone [IN] Indicates whether deep copy is required. The options are true and false. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetCertStore(HITLS_Ctx *ctx, HITLS_CERT_Store *store, bool isClone); /** * @ingroup hitls_cert * @brief Obtain the cert store used by the TLS link. * * @param ctx [IN] TLS link object * @retval Cert store */ HITLS_CERT_Store *HITLS_GetCertStore(const HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Set the certificate verification depth. * * @param config [OUT] TLS link configuration * @param depth [IN] Verification depth, type: uint32_t * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ #define HITLS_CFG_SetVerifyDepth(config, depth) \ HITLS_CFG_CtrlSetVerifyParams(config, NULL, CERT_STORE_CTRL_SET_VERIFY_DEPTH, depth, NULL) /** * @ingroup hitls_cert * @brief Obtain the certificate verification depth. * * @param config [IN] TLS link configuration * @param depth [OUT] Certificate verification depth, type: int32_t * * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ #define HITLS_CFG_GetVerifyDepth(config, depth) \ HITLS_CFG_CtrlGetVerifyParams((HITLS_Config *)(uintptr_t)(config), NULL, CERT_STORE_CTRL_GET_VERIFY_DEPTH, depth) /** * @ingroup hitls_cert * @brief Set the certificate verification depth. * * @param ctx [OUT] TLS link object * @param depth [IN] Verification depth, type: uint32_t * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ #define HITLS_SetVerifyDepth(ctx, depth) \ HITLS_CtrlSetVerifyParams(ctx, NULL, CERT_STORE_CTRL_SET_VERIFY_DEPTH, depth, NULL) /** * @ingroup hitls_cert * @brief Obtain the certificate verification depth. * * @param ctx [IN] TLS link object * @param depth [OUT] Certificate verification depth, type: int32_t * * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ #define HITLS_GetVerifyDepth(ctx, depth) \ HITLS_CtrlGetVerifyParams(ctx, NULL, CERT_STORE_CTRL_GET_VERIFY_DEPTH, depth) /** * @ingroup hitls_cert * @brief Password Callback * * @attention This callback function must be compatible with OpenSSL and logically the same as OpenSSL. * @param buf [OUT] Passwd data. * @param bufLen [IN] Maximum buffer length. * @param flag [IN] r/w flag. The value 0 indicates read, and the value 1 indicates write. * @param userdata [IN] User data. * * @retval Passwd Data length */ typedef int32_t (*HITLS_PasswordCb)(char *buf, int32_t bufLen, int32_t flag, void *userdata); /** * @ingroup hitls_cert * @brief Set the default password callback, cb can be NULL. * * @param config [OUT] TLS link configuration * @param cb [IN] Password Callback * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetDefaultPasswordCb(HITLS_Config *config, HITLS_PasswordCb cb); /** * @ingroup hitls_cert * @brief Callback for obtaining the default password. * * @param config [IN] TLS link configuration. * @retval Password Callback. */ HITLS_PasswordCb HITLS_CFG_GetDefaultPasswordCb(HITLS_Config *config); /** * @ingroup hitls_cert * @brief Set the user data used by the password callback. * * @param config [OUT] TLS link configuration * @param userdata [IN] User data * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetDefaultPasswordCbUserdata(HITLS_Config *config, void *userdata); /** * @ingroup hitls_cert * @brief Obtain the user data used by the password callback. * * @param config [IN] TLS link configuration * @retval User Data */ void *HITLS_CFG_GetDefaultPasswordCbUserdata(HITLS_Config *config); /** * @ingroup hitls_cert * @brief Set the default password callback, cb can be NULL * * @param ctx [OUT] TLS link object * @param cb [IN] password Callback * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetDefaultPasswordCb(HITLS_Ctx *ctx, HITLS_PasswordCb cb); /** * @ingroup hitls_cert * @brief Callback for obtaining the default password * * @param ctx [IN] TLS link object * @retval Password Callback */ HITLS_PasswordCb HITLS_GetDefaultPasswordCb(HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Set the user data used by the default password callback. * * @param ctx [OUT] TLS link object * @param userdata [IN] user data * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetDefaultPasswordCbUserdata(HITLS_Ctx *ctx, void *userdata); /** * @ingroup hitls_cert * @brief Obtain the user data used by the default password callback. * * @param ctx [IN] TLS link object * @retval User data */ void *HITLS_GetDefaultPasswordCbUserdata(HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Add the device certificate by the ShangMi(SM) cipher suites. * Only one certificate can be added for each type. * * @param config [OUT] TLS link configuration * @param cert [IN] Device certificate * @param isClone [IN] Indicates whether deep copy is required. The options are as follows: true: yes; false: no. * @param isTlcpEncCert [IN] Indicates whether the certificate is encrypted by China. * The options are as follows: true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetTlcpCertificate(HITLS_Config *config, HITLS_CERT_X509 *cert, bool isClone, bool isTlcpEncCert); /** * @ingroup hitls_cert * @brief Add the private key of the device certificate by the ShangMi(SM) cipher suites. * Only one private key can be added for each type of certificate. * * @param config [OUT] TLS link configuration * @param privateKey [IN] Certificate private key * @param isClone [IN] Indicates whether deep copy is required. The options are as follows: true: yes; false: no. * @param isTlcpEncCertPriKey [IN] Indicates whether the private key of the encryption certificate is * the private key of the encryption certificate. true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetTlcpPrivateKey(HITLS_Config *config, HITLS_CERT_Key *privateKey, bool isClone, bool isTlcpEncCertPriKey); /** * @ingroup hitls_cert * @brief Add a device certificate. Only one certificate of each type can be added * * @param config [OUT] TLS link configuration * @param cert [IN] Device certificate * @param isClone [IN] Indicates whether deep copy is required. The options are as follows: true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetCertificate(HITLS_Config *config, HITLS_CERT_X509 *cert, bool isClone); /** * @ingroup hitls_cert * @brief Load the device certificate from the file. * * @param config [OUT] TLS link configuration * @param file [IN] File name * @param type [IN] File format * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_LoadCertFile(HITLS_Config *config, const char *file, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Read the device certificate from the buffer. * * @param config [OUT] TLS link configuration * @param buf [IN] Certificate data * @param bufLen [IN] Data length * @param format [IN] Data format * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_LoadCertBuffer(HITLS_Config *config, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Obtain the device certificate in use. * * @attention The user cannot release the memory. * @param config [IN] TLS link configuration * @retval Device certificate */ HITLS_CERT_X509 *HITLS_CFG_GetCertificate(const HITLS_Config *config); /** * @ingroup hitls_cert * @brief Add a device certificate. Only one certificate can be added for each type. * * @param ctx [OUT] TLS link object * @param cert [IN] Device certificate * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetCertificate(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, bool isClone); /** * @ingroup hitls_cert * @brief Use a file to set the device certificate. * * @param ctx [IN/OUT] TLS connection handle * @param file [IN] File name * @param format [IN] Data format * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_LoadCertFile(HITLS_Ctx *ctx, const char *file, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Read the device certificate from the buffer. * * @param ctx [OUT] TLS link object * @param buf [IN] Certificate data * @param bufLen [IN] Data length * @param format [IN] Data format * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_LoadCertBuffer(HITLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Obtain the local certificate. * * Returns the most recently added certificate if it is called before the certificate is selected. * If no certificate is added, NULL is returned. * It returns the certificate selected during the handshake if a certificate selection occurs, or NULL * if no certificate is selected (e.g. on a client that does not use a client certificate). * * @attention: Shallow copy, can be used only during the ctx life cycle, and the caller * must not release the returned pointer. * @param ctx [IN] TLS link object * @retval Device certificate */ HITLS_CERT_X509 *HITLS_GetCertificate(const HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Obtain the peer certificate. * * @attention: Certificate reference increments by one. * @param ctx [IN] hitls Context * @retval Peer certificate */ HITLS_CERT_X509 *HITLS_GetPeerCertificate(const HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Add the private key of the device certificate. * Only one private key can be added for each type of certificate. * * @param config [OUT] TLS link configuration * @param privateKey [IN] Certificate private key * @param isClone [IN] Indicates whether deep copy is required. The options are as follows: true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetPrivateKey(HITLS_Config *config, HITLS_CERT_Key *privateKey, bool isClone); /** * @ingroup hitls_cert * @brief Load the private key of the device certificate from the file. * * @param config [OUT] TLS link configuration * @param file [IN] File name * @param format [IN] Data format * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_LoadKeyFile(HITLS_Config *config, const char *file, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Load the private key of the device certificate from the file, when the provider is used. * * @param config [OUT] TLS link configuration * @param file [IN] File name * @param format [IN] Data format. e.g. "PEM", "ASN1", etc. * @param type [IN] Data type. e.g. "PRIKEY_RSA", "PRIKEY_ECC", "PRIKEY_PKCS8_UNENCRYPT", * "PRIKEY_PKCS8_ENCRYPT", etc. */ int32_t HITLS_CFG_ProviderLoadKeyFile(HITLS_Config *config, const char *file, const char *format, const char *type); /** * @ingroup hitls_cert * @brief Read the private key of the device certificate from the buffer. * * @param config [OUT] TLS link configuration * @param buf [IN] Private key data * @param bufLen [IN] Data length * @param format [IN] Data format * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_LoadKeyBuffer(HITLS_Config *config, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Load the private key of the device certificate from the buffer, when the provider is used. * * @param config [OUT] TLS link configuration * @param buf [IN] Private key data * @param bufLen [IN] Data length * @param format [IN] Data format * @param type [IN] Data type */ int32_t HITLS_CFG_ProviderLoadKeyBuffer(HITLS_Config *config, const uint8_t *buf, uint32_t bufLen, const char *format, const char *type); /** * @ingroup hitls_cert * @brief Obtain the private key of the certificate in use. * * @attention The user cannot release the memory. * * @param config [IN] TLS link configuration * @retval Certificate private key */ HITLS_CERT_Key *HITLS_CFG_GetPrivateKey(HITLS_Config *config); /** * @ingroup hitls_cert * @brief Check whether the configured certificate matches the private key. * * @param config [IN] TLS link configuration * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_CheckPrivateKey(HITLS_Config *config); /** * @ingroup hitls_cert * @brief Add the private key of the device certificate. * * Only one private key can be added for each type of certificate. * * @param ctx [OUT] TLS link object. * @param pkey [IN] Device private key. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetPrivateKey(HITLS_Ctx *ctx, HITLS_CERT_Key *key, bool isClone); /** * @ingroup hitls_cert * @brief Use the file to set the device private key. * * @param ctx [IN/OUT] TLS connection handle * @param file [IN] File name. * @param format [IN] Data format. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_LoadKeyFile(HITLS_Ctx *ctx, const char *file, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Load the private key of the device certificate from the file, when the provider is used. * * @param ctx [IN/OUT] TLS connection handle * @param file [IN] File name. * @param format [IN] Data format. * @param type [IN] Data type. */ int32_t HITLS_ProviderLoadKeyFile(HITLS_Ctx *ctx, const char *file, const char *format, const char *type); /** * @ingroup hitls_cert * @brief Read the private key of the device certificate from the buffer. * * @param ctx [OUT] TLS link object. * @param buf [IN] Private key data. * @param bufLen [IN] Data length. * @param format [IN] Data format. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_LoadKeyBuffer(HITLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Load the private key of the device certificate from the buffer, when the provider is used. * * @param ctx [IN/OUT] TLS connection handle * @param buf [IN] Private key data. * @param bufLen [IN] Data length. * @param format [IN] Data format. * @param type [IN] Data type. */ int32_t HITLS_ProviderLoadKeyBuffer(HITLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, const char *format, const char *type); /** * @ingroup hitls_cert * @brief Obtain the private key of the certificate in use. * * @attention The user cannot release the memory. * * @param ctx [IN] TLS link object * @retval Certificate private key */ HITLS_CERT_Key *HITLS_GetPrivateKey(HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Check whether the configured certificate matches the private key. * * @param ctx [IN] TLS link object * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CheckPrivateKey(HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Add the certificate to the certificate chain that is being used by the current config. * * @param config [IN] TLS link configuration * @param cert [IN] Certificate to be added * @param isClone [IN] Indicates whether deep copy is required. The options are true and false. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_AddChainCert(HITLS_Config *config, HITLS_CERT_X509 *cert, bool isClone); /** * @ingroup hitls_cert * @brief Add the certificate to the certificate store that is being used by the current config. * * @param config [IN] TLS link configuration * @param cert [IN] Certificate to be added * @param storeType [IN] Indicates which store to add cert. * @param isClone [IN] Indicates whether deep copy is required. The options are true and false. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_AddCertToStore(HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_StoreType storeType, bool isClone); /** * @ingroup hitls_cert * @brief Parse Certificate file or buffer to X509. * * @param config [IN] TLS link configuration * @param buf [IN] Certificate file or buffer * @param len [IN] bufLen * @param type [IN] buf type: file or buffer * @param format [IN] cert type * * @retval HITLS_CERT_X509 */ HITLS_CERT_X509 *HITLS_CFG_ParseCert(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Parse Certificate file or buffer to X509. * * @param config [IN] TLS link configuration * @param buf [IN] Certificate file or buffer * @param len [IN] bufLen * @param type [IN] buf type: file or buffer * @param format [IN] cert type * * @retval HITLS_CERT_X509 */ HITLS_CERT_Key *HITLS_CFG_ParseKey(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Parse Certificate file or buffer to X509. * * @param config [IN] TLS link configuration * @param buf [IN] Certificate file or buffer * @param len [IN] bufLen * @param type [IN] buf type: file or buffer * @param format [IN] cert type * @param encodeType [IN] cert encode type * * @retval HITLS_CERT_X509 */ HITLS_CERT_Key *HITLS_CFG_ProviderParseKey(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, const char *format, const char *encodeType); /** * @ingroup hitls_cert * @brief Obtain the certificate chain that is being used by the current config. * @param config [IN] TLS link configuration * @retval The certificate chain that is currently in use */ HITLS_CERT_Chain *HITLS_CFG_GetChainCerts(HITLS_Config *config); /** * @ingroup hitls_cert * @brief Clear the certificate chain associated with the current certificate. * * @param config [IN] TLS link configuration * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_ClearChainCerts(HITLS_Config *config); /** * @ingroup hitls_cert * @brief Clear the certificate in the current certificate. * * @param ctx [IN] hitls context * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_ClearChainCerts(HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Release all loaded certificates and private keys. * * @param config [IN] TLS link configuration * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_RemoveCertAndKey(HITLS_Config *config); /** * @ingroup hitls_cert * @brief Release all loaded certificates and private keys. * * @param ctx [IN] TLS link object * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_RemoveCertAndKey(HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Certificate verification callback * * @attention This callback function must be compatible with OpenSSL and has the same logic as OpenSSL. * @param isPreverifyOk [IN] Indicates whether the relevant certificate has passed the verification * (isPreverifyOk=1) or failed (isPreverifyOk=0) * @param storeCtx [IN] Cert store context * @retval 1 indicates success. Other values indicate failure. */ typedef int (*HITLS_VerifyCb)(int32_t isPreverifyOk, HITLS_CERT_StoreCtx *storeCtx); /** * @ingroup hitls_cert * @brief Set the certificate verification callback function, cb can be NULL. * * @param config [OUT] TLS link configuration * @param callback [IN] Certificate verification callback function * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetVerifyCb(HITLS_Config *config, HITLS_VerifyCb callback); /** * @ingroup hitls_cert * @brief Obtain the certificate verification callback function. * * @param config [OUT] TLS link configuration * @return Certificate verification callback function */ HITLS_VerifyCb HITLS_CFG_GetVerifyCb(HITLS_Config *config); /** * @ingroup hitls_cert * @brief Set the certificate verification callback function, cb can be NULL. * * @param ctx [OUT] TLS link object * @param callback [IN] Certificate verification callback function * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetVerifyCb(HITLS_Ctx *ctx, HITLS_VerifyCb callback); /** * @ingroup hitls_cert * @brief Obtain the certificate verification callback function. * * @param ctx [IN] TLS link object * @retval Certificate verification callback function */ HITLS_VerifyCb HITLS_GetVerifyCb(HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Set the peer certificate verification result of the current context. * * @param ctx [IN] TLS connection handle * @param verifyResult [IN] Peer certificate verification result * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetVerifyResult(HITLS_Ctx *ctx, HITLS_ERROR verifyResult); /** * @ingroup hitls_cert * @brief Return the peer certificate verification result of the current context. * * @param ctx [IN] TLS connection handle * @param verifyResult [OUT] Peer certificate verification result * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_GetVerifyResult(const HITLS_Ctx *ctx, HITLS_ERROR *verifyResult); /** * @ingroup hitls_cert * @brief Obtain the peer certificate chain. * * @param ctx [OUT] TLS connection handle * @retval Peer certificate chain */ HITLS_CERT_Chain *HITLS_GetPeerCertChain(const HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Obtain the trusted CA list of the peer end. * * @param ctx [OUT] TLS connection handle * @retval Peer CA list */ HITLS_TrustedCAList *HITLS_GetPeerCAList(const HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Obtain the trusted CA list of the current context. * * @param ctx [OUT] TLS connection handle * @retval Trusted CA list */ HITLS_TrustedCAList *HITLS_GetCAList(const HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Set the trusted CA list of the current context. * * @param ctx [OUT] TLS connection handle * @retval Trusted CA list */ int32_t HITLS_SetCAList(HITLS_Ctx *ctx, HITLS_TrustedCAList *list); /** * @ingroup hitls_cert * @brief Add a certificate to the attached certificate chain. * * @param config [OUT] Config handle * @param cert [IN] X509 certificate * @retval 0 indicates success. Other values indicate failure. */ int32_t HITLS_CFG_AddExtraChainCert(HITLS_Config *config, HITLS_CERT_X509 *cert); /** * @ingroup hitls_cert * @brief Obtain the attached certificate chain. * * @param config [IN] Config handle * @retval Attach the certificate chain. */ HITLS_CERT_Chain *HITLS_CFG_GetExtraChainCerts(HITLS_Config *config); /** * @ingroup hitls_cert * @brief Release the attached certificate chain. * * @param config [IN] TLS link configuration * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_ClearExtraChainCerts(HITLS_Config *config); /* If the ClientHello callback is successfully executed, the handshake continues */ #define HITLS_CERT_CALLBACK_SUCCESS 1 /* The ClientHello callback fails. Send an alert message and terminate the handshake */ #define HITLS_CERT_CALLBACK_FAILED 0 /* The ClientHello callback is suspended. The handshake process is suspended and the callback is called again */ #define HITLS_CERT_CALLBACK_RETRY (-1) /** * @ingroup hitls_cert * @brief Process the certificate callback. * @attention This callback function is compatible with OpenSSL and has the same logic as OpenSSL. * * @param ctx [IN] TLS link object * @param arg [IN] Related parameters arg * @return HITLS_CERT_CALLBACK_SUCCESS if the callback is successfully executed. * HITLS_CERT_CALLBACK_FAILED if the callback fails. * HITLS_CERT_CALLBACK_RETRY if the callback is suspended. */ typedef int32_t (*HITLS_CertCb)(HITLS_Ctx *ctx, void *arg); /** * @ingroup hitls_cert * @brief set the processing certificate callback function, which checks the passed ctx structure and * sets or clear any appropriate certificate, cb can be NULL. * @param config [OUT] TLS link configuration * @param certCb [IN] Certificate callback function * @param arg [IN] Parameters required in the callback function. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetCertCb(HITLS_Config *config, HITLS_CertCb certCb, void *arg); /** * @ingroup hitls_cert * @brief set the processing certificate callback function, which checks the passed ctx structure and * sets or clear any appropriate certificate, cb can be NULL. * @param ctx [OUT] TLS link configuration * @param certCb [IN] Certificate callback function * @param arg [IN] Parameters required in the callback function. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetCertCb(HITLS_Ctx *ctx, HITLS_CertCb certCb, void *arg); /** * @ingroup hitls_cert * @brief Key logging callback * @attention This callback function must be compatible with OpenSSL and is logically the same as OpenSSL. * * @param ctx [OUT] TLS Link object * @param line [IN] Content to be recorded */ typedef void (*HITLS_KeyLogCb)(HITLS_Ctx *ctx, const char *line); /** * @ingroup hitls_cert * @brief Sets the callback for recording TLS keys. * @param config [OUT] TLS Link Configuration * @param callback [IN] Callback function for recording keys * * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetKeyLogCb(HITLS_Config *config, HITLS_KeyLogCb callback); /** * @ingroup hitls_cert * @brief Callback for obtaining TLS key logs * @param config [OUT] TLS Link Configuration * * @retval Callback function for recording key logs */ HITLS_KeyLogCb HITLS_CFG_GetKeyLogCb(HITLS_Config *config); /** * @ingroup hitls_cert * @brief If logging is enabled, the master key is logged * * @param ctx [OUT] TLS Link object. * @param label [IN] Label * @param secret [IN] Key * @param secretLen [IN] Key length. * * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_LogSecret(HITLS_Ctx *ctx, const char *label, const uint8_t *secret, size_t secretLen); /** * @ingroup hitls_cert * @brief Load the CA file and parse it into a trusted CA list. * * @attention The user cannot release the memory. * @param config [OUT] TLS link configuration * @param input [IN] Input data * @param inputLen [IN] Length of the input data * @param inputType [IN] Type of the input data * @param format [IN] File format * @param caList [OUT] Trusted CA list * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_ParseCAList(HITLS_Config *config, const char *input, uint32_t inputLen, HITLS_ParseType inputType, HITLS_ParseFormat format, HITLS_TrustedCAList **caList); /** * @ingroup hitls_cert * @brief Before establishing a TLS connection, try to form a certificate chain as much as possible according to * the flag. * @param config [OUT] TLS link configuration * @param flag [IN] Control how to group certificate chains based on flags, see HITLS_BUILD_CHAIN_FLAG. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_BuildCertChain(HITLS_Config *config, HITLS_BUILD_CHAIN_FLAG flag); /** * @ingroup hitls_cert * @brief Before establishing a TLS connection, try to form a certificate chain as much as possible according to * the flag. * @param ctx [OUT] TLS link configuration * @param flag [IN] Control how to group certificate chains based on flags, see HITLS_BUILD_CHAIN_FLAG. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_BuildCertChain(HITLS_Ctx *ctx, HITLS_BUILD_CHAIN_FLAG flag); /** * @ingroup hitls_cert * @brief Set certificate verification parameters. * @param config [OUT] TLS link configuration * @param store [IN] Certificate store * @param cmd [IN] Operation command, HITLS_CERT_CtrlCmd enum * @param in [IN] Input parameter, integer type * @param inArg [IN] Input parameter, pointer type * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_CtrlSetVerifyParams( HITLS_Config *config, HITLS_CERT_Store *store, uint32_t cmd, int64_t in, void *inArg); /** * @ingroup hitls_cert * @brief Get certificate verification parameters. * @param config [IN] TLS link configuration * @param store [IN] Certificate store * @param cmd [IN] Operation command, HITLS_CERT_CtrlCmd enum * @param out [OUT] Output parameter * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_CtrlGetVerifyParams(HITLS_Config *config, HITLS_CERT_Store *store, uint32_t cmd, void *out); /** * @ingroup hitls_cert * @brief Set certificate verification parameters. * @param ctx [OUT] TLS link configuration * @param store [IN] Certificate store * @param cmd [IN] Operation command, HITLS_CERT_CtrlCmd enum * @param in [IN] Input parameter, integer type * @param inArg [IN] Input parameter, pointer type * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CtrlSetVerifyParams(HITLS_Ctx *ctx, HITLS_CERT_Store *store, uint32_t cmd, int64_t in, void *inArg); /** * @ingroup hitls_cert * @brief Get certificate verification parameters. * @param ctx [IN] TLS link configuration * @param store [IN] Certificate store * @param cmd [IN] Operation command, HITLS_CERT_CtrlCmd enum * @param out [OUT] Output parameter * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CtrlGetVerifyParams(HITLS_Ctx *ctx, HITLS_CERT_Store *store, uint32_t cmd, void *out); /** * @ingroup hitls_cert * @brief Load CRL from file and add it into the verify store of the TLS configuration. * * @param config [OUT] TLS link configuration * @param file [IN] CRL file path * @param format [IN] Data format, see HITLS_ParseFormat * @retval HITLS_SUCCESS if successful * @retval For other error codes, see hitls_error.h */ int32_t HITLS_CFG_LoadCrlFile(HITLS_Config *config, const char *file, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Load CRL from buffer and add it into the verify store of the TLS configuration. * * @param config [OUT] TLS link configuration * @param buf [IN] CRL data * @param bufLen [IN] Data length * @param format [IN] Data format, see HITLS_ParseFormat * @retval HITLS_SUCCESS if successful * @retval For other error codes, see hitls_error.h */ int32_t HITLS_CFG_LoadCrlBuffer(HITLS_Config *config, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Clear all CRLs in the verify store of the configuration. * * @param config [IN] TLS link configuration * @retval HITLS_SUCCESS if successful * @retval For other error codes, see hitls_error.h */ int32_t HITLS_CFG_ClearVerifyCrls(HITLS_Config *config); /** * @ingroup hitls_cert * @brief Load CRL from file and add it into the verify store of the TLS context. */ int32_t HITLS_LoadCrlFile(HITLS_Ctx *ctx, const char *file, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Load CRL from buffer and add it into the verify store of the TLS context. */ int32_t HITLS_LoadCrlBuffer(HITLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format); /** * @ingroup hitls_cert * @brief Clear all CRLs in the verify store of the context. */ int32_t HITLS_ClearVerifyCrls(HITLS_Ctx *ctx); /** * @ingroup hitls_cert * @brief Set the certificate verification flags. * * @param config [OUT] TLS link configuration * @param verifyFlags [IN] Verification flags, type: uint32_t * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ #define HITLS_CFG_SetVerifyFlags(config, verifyFlags) \ HITLS_CFG_CtrlSetVerifyParams(config, NULL, CERT_STORE_CTRL_SET_VERIFY_FLAGS, verifyFlags, NULL) /** * @ingroup hitls_cert * @brief Set the certificate verification flags. * * @param ctx [OUT] TLS link object * @param verifyFlags [IN] Verification flags, type: uint32_t * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ #define HITLS_SetVerifyFlags(ctx, verifyFlags) \ HITLS_CtrlSetVerifyParams(ctx, NULL, CERT_STORE_CTRL_SET_VERIFY_FLAGS, verifyFlags, NULL) /** * @ingroup hitls_cert * @brief Set the certificate verification flags. * * @param config [IN] TLS link configuration * @param verifyFlags [OUT] Verification flags, type: uint32_t * * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ #define HITLS_CFG_GetVerifyFlags(config, verifyFlags) \ HITLS_CFG_CtrlGetVerifyParams(config, NULL, CERT_STORE_CTRL_GET_VERIFY_FLAGS, verifyFlags) /** * @ingroup hitls_cert * @brief Set the certificate verification flags. * * @param ctx [IN] TLS link object * @param verifyFlags [OUT] Verification flags, type: uint32_t * * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ #define HITLS_GetVerifyFlags(ctx, verifyFlags) \ HITLS_CtrlGetVerifyParams(ctx, NULL, CERT_STORE_CTRL_GET_VERIFY_FLAGS, verifyFlags) /** * @ingroup hitls_cert * @brief Use the certificate chain file to set the certificate chain. * * @param ctx [OUT] TLS link configuration * @param file [IN] Certificate chain file name * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_UseCertificateChainFile(HITLS_Ctx *ctx, const char *file); /** * @ingroup hitls_cert * @brief Use the certificate chain file to set the certificate chain. * * @param config [OUT] TLS link configuration * @param file [IN] Certificate chain file name * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_UseCertificateChainFile(HITLS_Config *config, const char *file); /** * @ingroup hitls_cert * @brief Load the verification file from the file. * * @param config [OUT] TLS link configuration * @param file [IN] File name * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_LoadVerifyFile(HITLS_Config *config, const char *file); /** * @ingroup hitls_cert * @brief Load the verification file from the directory. * * @param config [OUT] TLS link configuration * @param path [IN] Directory path * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_LoadVerifyDir(HITLS_Config *config, const char *path); /** * @ingroup hitls_cert * @brief Release the certificate. * * @param config [IN] Config handle * @param cert [IN] X509 certificate * * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_FreeCert(HITLS_Config *config, HITLS_CERT_X509 *cert); /** * @ingroup hitls_cert * @brief Release the key. * * @param config [IN] Config handle * @param key [IN] private key * * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_FreeKey(HITLS_Config *config, HITLS_CERT_Key *key); #ifdef __cplusplus } #endif #endif /* HITLS_CERT_H */
2301_79861745/bench_create
include/tls/hitls_cert.h
C
unknown
43,223
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_cert_init * @ingroup hitls * @brief TLS certificate abstraction layer initialization */ #ifndef HITLS_CERT_INIT_H #define HITLS_CERT_INIT_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /** * @ingroup hitls_cert_init * @brief Certificate initialization interface, default use the HITLS X509 interface. * * @attention If HITLS X509 not be used, do not need to call this interface. * @param NA * @retval void */ int32_t HITLS_CertMethodInit(void); /** * @ingroup hitls_cert_init * @brief Deinitialize the certificate, set the certificate registration interface to NULL. * * @param NA * @retval void */ void HITLS_CertMethodDeinit(void); #ifdef __cplusplus } #endif #endif /* HITLS_CRYPT_CERT_H */
2301_79861745/bench_create
include/tls/hitls_cert_init.h
C
unknown
1,312
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_cert_type * @ingroup hitls * @brief Structures related to a certificate */ #ifndef HITLS_CERT_TYPE_H #define HITLS_CERT_TYPE_H #include <stdint.h> #include "bsl_obj.h" #include "bsl_types.h" #ifdef __cplusplus extern "C" { #endif /** * @ingroup hitls_cert_type * @brief Describes the x509 certificate */ typedef void HITLS_CERT_X509; /** * @ingroup hitls_cert_type * @brief Describes the CRL */ typedef void HITLS_CERT_CRL; /** * @ingroup hitls_cert_type * @brief Describes the certificate key */ typedef void HITLS_CERT_Key; /** * @ingroup hitls_cert_type * @brief Describes the certificate */ typedef void HITLS_CERT_Store; /** * @ingroup hitls_cert_type * @brief Describes the certificate */ typedef void HITLS_CERT_StoreCtx; /** * @ingroup hitls_cert_type * @brief Describes the list of trusted CAs */ typedef struct BslList HITLS_TrustedCAList; /** * @ingroup hitls_cert_type * @brief Describes the certificate chain */ typedef struct BslList HITLS_CERT_Chain; /** * @ingroup hitls_cert_type * @brief Describes the CRL list */ typedef struct BslList HITLS_CERT_CRLList; /** * @ingroup hitls_cert_type * @brief ctrl option */ typedef enum { CERT_STORE_CTRL_SET_VERIFY_DEPTH = 0, /**< Set the certificate verification depth. */ CERT_STORE_CTRL_ADD_CERT_LIST, /**< Add ca and chain certificate to store */ CERT_STORE_CTRL_GET_VERIFY_DEPTH, /**< Get the certificate verification depth. */ CERT_STORE_CTRL_ADD_CRL_LIST, /**< Add CRL list to verify store */ CERT_STORE_CTRL_CLEAR_CRL_LIST, /**< Clear all CRLs from verify store */ CERT_STORE_CTRL_ADD_CA_PATH, /**< Set the CA path. */ CERT_CTRL_GET_ENCODE_LEN = 200, /**< Obtain the length of the certificate code. */ CERT_CTRL_GET_PUB_KEY, /**< Obtaining the Certificate Public Key (Release Required). */ CERT_CTRL_GET_SIGN_ALGO, /**< Obtain the certificate signature algorithm. */ CERT_CTRL_GET_ENCODE_SUBJECT_DN, /**< Get the subject distinguished name as a buffer. */ CERT_CTRL_IS_SELF_SIGNED, /** Determine whether the certificate is a self-signed certificate */ CERT_KEY_CTRL_GET_SIGN_LEN = 400, /**< Obtain the signature length. */ CERT_KEY_CTRL_GET_TYPE, /**< Obtaining the Key Type. */ CERT_KEY_CTRL_GET_CURVE_NAME, /**< Obtain the elliptic curve ID. */ CERT_KEY_CTRL_GET_POINT_FORMAT, /**< Obtains the format of the EC point. */ CERT_KEY_CTRL_GET_SECBITS, /**< Obtain the security bits. */ CERT_KEY_CTRL_IS_KEYENC_USAGE, /**< Is the encryption certificate permission. */ CERT_KEY_CTRL_IS_DIGITAL_SIGN_USAGE, /**< Is it digital signature permission. */ CERT_KEY_CTRL_IS_KEY_CERT_SIGN_USAGE, /**< Is the certificate issuing permission. */ CERT_KEY_CTRL_IS_KEY_AGREEMENT_USAGE, /**< Is it the certificate verification permission. */ CERT_KEY_CTRL_GET_PARAM_ID, /**< Obtain the parameter ID. */ CERT_KEY_CTRL_IS_DATA_ENC_USAGE, /**< Is it the data encryption permission. */ CERT_KEY_CTRL_IS_NON_REPUDIATION_USAGE, /**< Is it the non-repudiation permission. */ CERT_STORE_CTRL_GET_VERIFY_FLAGS, /**< Get the certificate verification flags. */ CERT_STORE_CTRL_SET_VERIFY_FLAGS, /**< Set the certificate verification flags. */ CERT_CTRL_BUTT, } HITLS_CERT_CtrlCmd; /** * @ingroup hitls_cert_type * @brief Read data format */ typedef enum { TLS_PARSE_TYPE_FILE, /**< Parse file */ TLS_PARSE_TYPE_BUFF, /**< Parse buffer */ TLS_PARSE_TYPE_BUTT, } HITLS_ParseType; /** * @ingroup hitls_cert_type * @brief Read data format */ typedef enum { TLS_PARSE_FORMAT_PEM = BSL_FORMAT_PEM, /**< PEM format */ TLS_PARSE_FORMAT_ASN1 = BSL_FORMAT_ASN1, /**< ASN1 format */ TLS_PARSE_FORMAT_PFX_COM = BSL_FORMAT_PFX_COM, /**< PFX COM format */ TLS_PARSE_FORMAT_PKCS12 = BSL_FORMAT_PKCS12, /**< PKCS12 format */ TLS_PARSE_FORMAT_BUTT = BSL_FORMAT_UNKNOWN, } HITLS_ParseFormat; /** * @ingroup hitls_cert_type * @brief cert store type */ typedef enum { TLS_CERT_STORE_TYPE_DEFAULT, /**< Default CA store */ TLS_CERT_STORE_TYPE_VERIFY, /**< Verifies the store, which is used to verify the certificate chain */ TLS_CERT_STORE_TYPE_CHAIN, /**< Certificate chain store, used to assemble the certificate chain */ TLS_CERT_STORE_TYPE_BUTT, } HITLS_CERT_StoreType; /** * @ingroup hitls_cert_type * @brief Certificate Public Key Type */ typedef enum { TLS_CERT_KEY_TYPE_UNKNOWN = BSL_CID_UNKNOWN, TLS_CERT_KEY_TYPE_RSA = BSL_CID_RSA, TLS_CERT_KEY_TYPE_RSA_PSS = BSL_CID_RSASSAPSS, TLS_CERT_KEY_TYPE_DSA = BSL_CID_DSA, TLS_CERT_KEY_TYPE_ECDSA = BSL_CID_ECDSA, TLS_CERT_KEY_TYPE_ED25519 = BSL_CID_ED25519, TLS_CERT_KEY_TYPE_SM2 = BSL_CID_SM2DSA } HITLS_CERT_KeyType; typedef enum { HITLS_BUILD_CHAIN_FLAG_NO_ROOT = 0x2, HITLS_BUILD_CHAIN_FLAG_CHECK = 0x4, HITLS_BUILD_CHAIN_FLAG_IGNORE_ERROR = 0x8, } HITLS_BUILD_CHAIN_FLAG; /** * @ingroup hitls_cert_type * @brief Certificate Signature Algorithm Enumeration */ typedef enum { /* Reservation algorithm. */ CERT_SIG_SCHEME_RSA_PKCS1_SHA1 = 0x0201, CERT_SIG_SCHEME_DSA_SHA1 = 0X0202, CERT_SIG_SCHEME_ECDSA_SHA1 = 0x0203, CERT_SIG_SCHEME_ECDSA_SHA224 = 0x0303, /* RSASSA-PKCS1-v1_5 algorithms */ CERT_SIG_SCHEME_RSA_PKCS1_SHA224 = 0x0301, CERT_SIG_SCHEME_RSA_PKCS1_SHA256 = 0x0401, CERT_SIG_SCHEME_RSA_PKCS1_SHA384 = 0x0501, CERT_SIG_SCHEME_RSA_PKCS1_SHA512 = 0x0601, /* DSA algorithms */ CERT_SIG_SCHEME_DSA_SHA224 = 0x0302, CERT_SIG_SCHEME_DSA_SHA256 = 0X0402, /**< signature algorithm: DSA_SHA256 */ CERT_SIG_SCHEME_DSA_SHA384 = 0X0502, /**< signature algorithm: DSA_SHA384 */ CERT_SIG_SCHEME_DSA_SHA512 = 0X0602, /**< signature algorithm: DSA_SHA512 */ /* ECDSA algorithms */ CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256 = 0x0403, CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384 = 0x0503, CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512 = 0x0603, /* GM sig algorithms */ CERT_SIG_SCHEME_SM2_SM3 = 0x0708, /* RSASSA-PSS algorithms with public key OID rsaEncryption */ CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256 = 0x0804, CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384 = 0x0805, CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512 = 0x0806, /* EdDSA algorithms */ CERT_SIG_SCHEME_ED25519 = 0x0807, CERT_SIG_SCHEME_ED448 = 0x0808, /* RSASSA-PSS algorithms with public key OID RSASSA-PSS */ CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256 = 0x0809, CERT_SIG_SCHEME_RSA_PSS_PSS_SHA384 = 0x080a, CERT_SIG_SCHEME_RSA_PSS_PSS_SHA512 = 0x080b, CERT_SIG_SCHEME_UNKNOWN = 0xffff } HITLS_SignHashAlgo; /** * @ingroup hitls_cert_type * @brief Trusted CA ID Type */ typedef enum { HITLS_TRUSTED_CA_PRE_AGREED = 0, /**< preset CA */ HITLS_TRUSTED_CA_KEY_SHA1 = 1, /**< Trusted CA key Hash */ HITLS_TRUSTED_CA_X509_NAME = 2, /**< Trusted CA x509 Certificate Name */ HITLS_TRUSTED_CA_CERT_SHA1 = 3, /**< Trusted CA Certificate Hash */ HITLS_TRUSTED_CA_UNKNOWN = 255 } HITLS_TrustedCAType; /** * @ingroup hitls_cert_type * @brief Node structure used to describe the trusted CA certificate list */ typedef struct HitlsTrustedCANode { HITLS_TrustedCAType caType; /**< Trusted CA type */ uint8_t *data; /**< Trusted CA data */ uint32_t dataSize; /**< Trusted CA data length */ } HITLS_TrustedCANode; #ifdef __cplusplus } #endif #endif /* HITLS_CERT_TYPE_H */
2301_79861745/bench_create
include/tls/hitls_cert_type.h
C
unknown
8,203
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_config * @ingroup hitls * @brief TLS parameter configuration */ #ifndef HITLS_CONFIG_H #define HITLS_CONFIG_H #include <stdbool.h> #include <stdint.h> #include "hitls_type.h" #include "hitls_crypt_type.h" #include "hitls_cert_type.h" #ifdef __cplusplus extern "C" { #endif /** * @ingroup hitls_config * @brief (D)TLCP 1.1 version */ #define HITLS_VERSION_TLCP_DTLCP11 0x0101u /** * @ingroup hitls_config * @brief TLS any version */ #define HITLS_TLS_ANY_VERSION 0x03ffu /** * @ingroup hitls_config * @brief SSL3.0 version number */ #define HITLS_VERSION_SSL30 0x0300u /** * @ingroup hitls_config * @brief TLS1.0 version number */ #define HITLS_VERSION_TLS10 0x0301u /** * @ingroup hitls_config * @brief TLS1.1 version number */ #define HITLS_VERSION_TLS11 0x0302u /** * @ingroup hitls_config * @brief TLS1.2 version */ #define HITLS_VERSION_TLS12 0x0303u /** * @ingroup config * @brief TLS 1.3 version */ #define HITLS_VERSION_TLS13 0x0304u /** * @ingroup config * @brief Prefix of SSL 3.0 or later */ #define HITLS_VERSION_TLS_MAJOR 0x03u /** * @ingroup hitls_config * @brief DTLS any version */ #define HITLS_DTLS_ANY_VERSION 0xfe00u /** * @ingroup hitls_config * @brief DTLS 1.2 version */ #define HITLS_VERSION_DTLS12 0xfefdu /** * @ingroup hitls_config * @brief Maximum size of the configuration data */ #define HITLS_CFG_MAX_SIZE 1024 /** * @ingroup hitls_config * @brief Configure the maximum size of the TLS1_3 cipher suite */ #define TLS13_CIPHERSUITES_MAX_LEN 80 /** * @ingroup hitls_config * @brief enumerate ciphersuites supported by HITLS with IANA coding * */ typedef enum { HITLS_RSA_WITH_AES_128_CBC_SHA = 0x002F, HITLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0x0032, HITLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033, HITLS_DH_ANON_WITH_AES_128_CBC_SHA = 0x0034, HITLS_RSA_WITH_AES_256_CBC_SHA = 0x0035, HITLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0x0038, HITLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039, HITLS_DH_ANON_WITH_AES_256_CBC_SHA = 0x003A, HITLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C, HITLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D, HITLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = 0x0040, HITLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067, HITLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = 0x006A, HITLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B, HITLS_DH_ANON_WITH_AES_128_CBC_SHA256 = 0x006C, HITLS_DH_ANON_WITH_AES_256_CBC_SHA256 = 0x006D, HITLS_PSK_WITH_AES_128_CBC_SHA = 0x008C, HITLS_PSK_WITH_AES_256_CBC_SHA = 0x008D, HITLS_DHE_PSK_WITH_AES_128_CBC_SHA = 0x0090, HITLS_DHE_PSK_WITH_AES_256_CBC_SHA = 0x0091, HITLS_RSA_PSK_WITH_AES_128_CBC_SHA = 0x0094, HITLS_RSA_PSK_WITH_AES_256_CBC_SHA = 0x0095, HITLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C, HITLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D, HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F, HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256 = 0x00A2, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384 = 0x00A3, HITLS_DH_ANON_WITH_AES_128_GCM_SHA256 = 0x00A6, HITLS_DH_ANON_WITH_AES_256_GCM_SHA384 = 0x00A7, HITLS_PSK_WITH_AES_128_GCM_SHA256 = 0x00A8, HITLS_PSK_WITH_AES_256_GCM_SHA384 = 0x00A9, HITLS_DHE_PSK_WITH_AES_128_GCM_SHA256 = 0x00AA, HITLS_DHE_PSK_WITH_AES_256_GCM_SHA384 = 0x00AB, HITLS_RSA_PSK_WITH_AES_128_GCM_SHA256 = 0x00AC, HITLS_RSA_PSK_WITH_AES_256_GCM_SHA384 = 0x00AD, HITLS_PSK_WITH_AES_128_CBC_SHA256 = 0x00AE, HITLS_PSK_WITH_AES_256_CBC_SHA384 = 0x00AF, HITLS_DHE_PSK_WITH_AES_128_CBC_SHA256 = 0x00B2, HITLS_DHE_PSK_WITH_AES_256_CBC_SHA384 = 0x00B3, HITLS_RSA_PSK_WITH_AES_128_CBC_SHA256 = 0x00B6, HITLS_RSA_PSK_WITH_AES_256_CBC_SHA384 = 0x00B7, HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009, HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A, HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013, HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014, HITLS_ECDH_ANON_WITH_AES_128_CBC_SHA = 0xC018, HITLS_ECDH_ANON_WITH_AES_256_CBC_SHA = 0xC019, HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023, HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024, HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027, HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B, HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C, HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030, HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA = 0xC035, HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA = 0xC036, HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 = 0xC037, HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 = 0xC038, HITLS_RSA_WITH_AES_128_CCM = 0xC09C, HITLS_RSA_WITH_AES_256_CCM = 0xC09D, HITLS_DHE_RSA_WITH_AES_128_CCM = 0xC09E, HITLS_DHE_RSA_WITH_AES_256_CCM = 0xC09F, HITLS_RSA_WITH_AES_128_CCM_8 = 0xC0A0, HITLS_RSA_WITH_AES_256_CCM_8 = 0xC0A1, HITLS_PSK_WITH_AES_256_CCM = 0xC0A5, HITLS_DHE_PSK_WITH_AES_128_CCM = 0xC0A6, HITLS_DHE_PSK_WITH_AES_256_CCM = 0xC0A7, HITLS_ECDHE_ECDSA_WITH_AES_128_CCM = 0xC0AC, HITLS_ECDHE_ECDSA_WITH_AES_256_CCM = 0xC0AD, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA8, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA9, HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCAA, HITLS_PSK_WITH_CHACHA20_POLY1305_SHA256 = 0xCCAB, HITLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 = 0xCCAC, HITLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 = 0xCCAD, HITLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 = 0xCCAE, HITLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256 = 0xD001, HITLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384 = 0xD002, HITLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256 = 0xD005, /* TLS1.3 cipher suite */ HITLS_AES_128_GCM_SHA256 = 0x1301, HITLS_AES_256_GCM_SHA384 = 0x1302, HITLS_CHACHA20_POLY1305_SHA256 = 0x1303, HITLS_AES_128_CCM_SHA256 = 0x1304, HITLS_AES_128_CCM_8_SHA256 = 0x1305, /* TLCP 1.1 cipher suite */ HITLS_ECDHE_SM4_CBC_SM3 = 0xE011, HITLS_ECC_SM4_CBC_SM3 = 0xE013, HITLS_ECDHE_SM4_GCM_SM3 = 0xE051, HITLS_ECC_SM4_GCM_SM3 = 0xE053, } HITLS_CipherSuite; /** * @ingroup hitls_config * @brief Create DTLS12 configuration items, including the default settings. The user can call the * HITLS_CFG_SetXXX interface to modify the settings. * * @attention The default configuration is as follows: Version number: HITLS_VERSION_DTLS12 Algorithm suite: HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256, HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256 EC point format: HITLS_POINT_FORMAT_UNCOMPRESSED groups:secp256r1, secp384r1, secp521r1, x25519, x448 Extended Master Key: Not Enabled Signature algorithm: All signature algorithms in the HITLS_SignHashAlgo table Dual-ended check: Disabled Allow Client No Certificate: Not Allowed Renegotiation: Not supported This API is a version-specific API. After the configuration context is created, the HITLS_SetVersion, HITLS_CFG_SetVersion, HITLS_SetVersionSupport, HITLS_CFG_SetVersionSupport, HITLS_SetMinProtoVersion, or HITLS_SetMaxProtoVersion interface cannot be used to set other supported versions. * @retval HITLS_Config, object pointer succeeded. * @retval NULL, failed to apply for the object. * @see HITLS_CFG_FreeConfig */ HITLS_Config *HITLS_CFG_NewDTLS12Config(void); /** * @ingroup hitls_config * @brief Create DTLS12 configuration items with provider, including the default settings. Same as HITLS_CFG_NewDTLS12Config * except that it requires libCtx and attribute parameters. * * @param[in] libCtx: The library context. * @param[in] attrName: The attribute name. * * @retval HITLS_Config, object pointer succeeded. * @retval NULL, failed to apply for the object. * @see HITLS_CFG_FreeConfig */ HITLS_Config *HITLS_CFG_ProviderNewDTLS12Config(HITLS_Lib_Ctx *libCtx, const char *attrName); /** * @ingroup hitls_config * @brief Create TLCP configuration items, including default settings. * * The user can call the HITLS_CFG_SetXXX interface to modify the settings. * * @attention The default configuration is as follows: Version number: HITLS_VERSION_TLCP_DTLCP11 Algorithm suite: HITLS_ECDHE_SM4_CBC_SM3, HITLS_ECC_SM4_CBC_SM3, HITLS_ECDHE_SM4_GCM_SM3, HITLS_ECC_SM4_GCM_SM3 EC point format: HITLS_POINT_FORMAT_UNCOMPRESSED groups:sm2 Extended Master Key: Enabled Signature algorithm: All signature algorithms in the HITLS_SignHashAlgo table Dual-ended check: Disabled Allow Client No Certificate: Not Allowed Renegotiation: Not supported This API is a version-specific API. After the configuration context is created, the HITLS_SetVersion, HITLS_CFG_SetVersion, HITLS_SetVersionSupport, HITLS_CFG_SetVersionSupport, HITLS_SetMinProtoVersion, or HITLS_SetMaxProtoVersion interface cannot be used to set other supported versions. * @retval HITLS_Config, object pointer succeeded. * @retval NULL, object application failed. */ HITLS_Config *HITLS_CFG_NewTLCPConfig(void); /** * @ingroup hitls_config * @brief Create TLCP configuration items with provider, including the default settings. Same as HITLS_CFG_NewTLCPConfig * except that it requires libCtx and attribute parameters. * * @param[in] libCtx: The library context. * @param[in] attrName: The attribute name. * * @retval HITLS_Config, object pointer succeeded. * @retval NULL, failed to apply for the object. * @see HITLS_CFG_FreeConfig */ HITLS_Config *HITLS_CFG_ProviderNewTLCPConfig(HITLS_Lib_Ctx *libCtx, const char *attrName); /** * @ingroup hitls_config * @brief Create DTLCP configuration items, including the default settings. The user can call the * HITLS_CFG_SetXXX interface to modify the settings. * * @attention The default configuration is as follows: Version number: HITLS_VERSION_TLCP_DTLCP11 Algorithm suite: HITLS_ECDHE_SM4_CBC_SM3, HITLS_ECC_SM4_CBC_SM3, HITLS_ECDHE_SM4_GCM_SM3, HITLS_ECC_SM4_GCM_SM3 EC point format: HITLS_POINT_FORMAT_UNCOMPRESSED groups:sm2 Extended Master Key: Enabled Signature algorithm: All signature algorithms in the HITLS_SignHashAlgo table Dual-ended check: Disabled Allow Client No Certificate: Not Allowed Renegotiation: Not supported This API is a version-specific API. After the configuration context is created, the HITLS_SetVersion, HITLS_CFG_SetVersion, HITLS_SetVersionSupport, HITLS_CFG_SetVersionSupport, HITLS_SetMinProtoVersion, or HITLS_SetMaxProtoVersion interface cannot be used to set other supported versions. * @retval HITLS_Config, object pointer succeeded. * @retval NULL, object application failed. */ HITLS_Config *HITLS_CFG_NewDTLCPConfig(void); /** * @ingroup hitls_config * @brief Create DTLCP configuration items with provider, including the default settings. Same as HITLS_CFG_NewDTLCPConfig * except that it requires libCtx and attribute parameters. * * @param[in] libCtx: The library context. * @param[in] attrName: The attribute name. * * @retval HITLS_Config, object pointer succeeded. * @retval NULL, failed to apply for the object. * @see HITLS_CFG_FreeConfig */ HITLS_Config *HITLS_CFG_ProviderNewDTLCPConfig(HITLS_Lib_Ctx *libCtx, const char *attrName); /** * @ingroup hitls_config * @brief Create a TLS12 configuration item, including the default configuration. * * The user can call the HITLS_CFG_SetXXX interface to modify the configuration. * * @attention The default configuration is as follows: Version number: HITLS_VERSION_TLS12 Algorithm suite: HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256, HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256 EC point format: HITLS_POINT_FORMAT_UNCOMPRESSED groups:secp256r1, secp384r1, secp521r1, x25519, x448 Extended Master Key: Enabled Signature algorithm: All signature algorithms in the HITLS_SignHashAlgo table Dual-ended check: Disabled Allow Client No Certificate: Not Allowed Renegotiation: Not supported This API is a version-specific API. After the configuration context is created, the HITLS_SetVersion, HITLS_CFG_SetVersion, HITLS_SetVersionSupport, HITLS_CFG_SetVersionSupport, HITLS_SetMinProtoVersion, or HITLS_SetMaxProtoVersion interface cannot be used to set other supported versions. * @retval HITLS_Config, object pointer succeeded. * @retval NULL, object application failed. */ HITLS_Config *HITLS_CFG_NewTLS12Config(void); /** * @ingroup hitls_config * @brief Create TLS12 configuration items with provider, including the default settings. Same as HITLS_CFG_NewTLS12Config * except that it requires libCtx and attribute parameters. * * @param[in] libCtx: The library context. * @param[in] attrName: The attribute name. * * @retval HITLS_Config, object pointer succeeded. * @retval NULL, failed to apply for the object. * @see HITLS_CFG_FreeConfig */ HITLS_Config *HITLS_CFG_ProviderNewTLS12Config(HITLS_Lib_Ctx *libCtx, const char *attrName); /** * @ingroup hitls_config * @brief Creates the default TLS13 configuration. * * The HITLS_CFG_SetXXX interface can be used to modify the default TLS13 configuration. * * @attention The default configuration is as follows: Version number: HITLS_VERSION_TLS13 Algorithm suite: HITLS_AES_128_GCM_SHA256, HITLS_CHACHA20_POLY1305_SHA256, HITLS_AES_128_GCM_SHA256 EC point format: HITLS_POINT_FORMAT_UNCOMPRESSED groups:secp256r1, secp384r1, secp521r1, x25519, x448 Extended Master Key: Enabled Signature algorithm: rsa, ecdsa, eddsa Dual-ended check: Disabled Allow Client No Certificate: Not Allowed This API is a version-specific API. After the configuration context is created, the HITLS_SetVersion, HITLS_CFG_SetVersion, HITLS_SetVersionSupport, HITLS_CFG_SetVersionSupport, HITLS_SetMinProtoVersion, and HITLS_SetMaxProtoVersion interface cannot be used to set other supported versions. * @retval HITLS_Config, object pointer succeeded. * @retval NULL, failed to apply for the object */ HITLS_Config *HITLS_CFG_NewTLS13Config(void); /** * @ingroup hitls_config * @brief Create TLS13 configuration items with provider, including the default settings. Same as HITLS_CFG_NewTLS13Config * except that it requires libCtx and attribute parameters. * * @param[in] libCtx: The library context. * @param[in] attrName: The attribute name. * * @retval HITLS_Config, object pointer succeeded. * @retval NULL, failed to apply for the object. * @see HITLS_CFG_FreeConfig */ HITLS_Config *HITLS_CFG_ProviderNewTLS13Config(HITLS_Lib_Ctx *libCtx, const char *attrName); /** * @ingroup hitls_config * @brief Create full TLS configurations. The HITLS_CFG_SetXXX interface can be used to modify the configurations. * * @attention The default configuration is as follows: Version number: HITLS_VERSION_TLS12, HITLS_VERSION_TLS13 Algorithm suite: HITLS_AES_128_GCM_SHA256, HITLS_CHACHA20_POLY1305_SHA256, HITLS_AES_128_GCM_SHA256 HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256, HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, HITLS_DHE_RSA_WITH_AES_256_CBC_SHA, HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, HITLS_DHE_RSA_WITH_AES_128_CBC_SHA, HITLS_RSA_WITH_AES_256_CBC_SHA, HITLS_RSA_WITH_AES_128_CBC_SHA, EC point format: HITLS_POINT_FORMAT_UNCOMPRESSED groups:secp256r1, secp384r1, secp521r1, x25519, x448, brainpool256r1, brainpool384r1, brainpool521r1 Extended Master Key: Enabled Signature algorithm: All signature algorithms in the HITLS_SignHashAlgo table Dual-ended check: Disabled Allow Client No Certificate: Not Allowed This interface is a unified configuration interface. After a configuration context is created, it can be used with the HITLS_SetVersion, HITLS_CFG_SetVersion, HITLS_SetVersionSupport, HITLS_CFG_SetVersionSupport, HITLS_SetMinProtoVersion, and HITLS_SetMaxProtoVersion are used together, Set the supported version. However, only the TLS configuration item is configured in this interface. Therefore, the DTLS version cannot be set. * @retval HITLS_Config, object pointer succeeded. * @retval NULL, object application failed. */ HITLS_Config *HITLS_CFG_NewTLSConfig(void); /** * @ingroup hitls_config * @brief Create TLS configuration items with provider, including the default settings. Same as HITLS_CFG_NewTLSConfig * except that it requires libCtx and attribute parameters. * * @param[in] libCtx: The library context. * @param[in] attrName: The attribute name. * * @retval HITLS_Config, object pointer succeeded. * @retval NULL, failed to apply for the object. * @see HITLS_CFG_FreeConfig */ HITLS_Config *HITLS_CFG_ProviderNewTLSConfig(HITLS_Lib_Ctx *libCtx, const char *attrName); /** * @ingroup hitls_config * @brief Create full DTLS configurations. The HITLS_CFG_SetXXX interface can be called * to modify the DTLS configuration. * * @attention The default configuration is as follows: Version number: HITLS_VERSION_DTLS10, HITLS_VERSION_DTLS12 Algorithm suite: HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256, HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256, EC point format: HITLS_POINT_FORMAT_UNCOMPRESSED groups:secp256r1, secp384r1, secp521r1, x25519, x448, brainpool256r1, brainpool384r1, brainpool521r1 Extended Master Key: Enabled Signature algorithm: All signature algorithms in the HITLS_SignHashAlgo table Dual-ended check: Disabled Allow Client No Certificate: Not Allowed This interface is a unified configuration interface. After a configuration context is created, it can be used with the HITLS_SetVersion, HITLS_CFG_SetVersion, HITLS_SetVersionSupport, HITLS_CFG_SetVersionSupport, HITLS_SetMinProtoVersion, and HITLS_SetMaxProtoVersion are used together, Set the supported version. However, only the DTLS configuration item is configured in this interface. Therefore, the TLS version cannot be set. * @retval HITLS_Config, object pointer succeeded. * @retval NULL, Object application failed. */ HITLS_Config *HITLS_CFG_NewDTLSConfig(void); /** * @ingroup hitls_config * @brief Create DTLS configuration items with provider, including the default settings. Same as HITLS_CFG_NewDTLSConfig * except that it requires libCtx and attribute parameters. * * @param[in] libCtx: The library context. * @param[in] attrName: The attribute name. * * @retval HITLS_Config, object pointer succeeded. * @retval NULL, failed to apply for the object. * @see HITLS_CFG_FreeConfig */ HITLS_Config *HITLS_CFG_ProviderNewDTLSConfig(HITLS_Lib_Ctx *libCtx, const char *attrName); /** * @ingroup hitls_config * @brief Release the config file. * * @param config [OUT] Config handle. * @retval void */ void HITLS_CFG_FreeConfig(HITLS_Config *config); /** * @ingroup hitls_config * @brief The reference counter of config increases by 1. * * @param config [OUT] Config handle. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_UpRef(HITLS_Config *config); /** * @ingroup hitls_config * @brief Set the supported version number range. * * @param config [OUT] Config handle * @param minVersion [IN] Minimum version number * @param maxVersion [IN] Maximum version number * @attention The maximum version number and minimum version number must be both TLS and DTLS. * Currently, only DTLS 1.2. * HITLS_CFG_NewDTLSConfig, HITLS_CFG_NewTLSConfig can be used with full configuration interfaces. * If TLS full configuration is configured, only the TLS version can be set. * If DTLS full configuration is configured, only the DTLS version can be set. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetVersion(HITLS_Config *config, uint16_t minVersion, uint16_t maxVersion); /** * @ingroup hitls_config * @brief Setting the disabled version number. * * @param config [OUT] Config handle * @param noversion [IN] Disabled version number. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetVersionForbid(HITLS_Config *config, uint32_t noVersion); /** * @ingroup hitls_config * @brief Set whether to support renegotiation. * * @param config [OUT] Config handle * @param support [IN] Whether to support the function. The options are as follows: True: yes; False: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetRenegotiationSupport(HITLS_Config *config, bool support); /** * @ingroup hitls_config * @brief Set whether to allow a renegotiate request from the client * @param config [OUT] Config handle * @param support [IN] Whether to support the function. The options are as follows: True: yes; False: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetClientRenegotiateSupport(HITLS_Config *config, bool support); /** * @ingroup hitls_config * @brief Set whether to abort handshake when server doesn't support SecRenegotiation * @param config [OUT] Config handle * @param support [IN] Whether to support the function. The options are as follows: True: yes; False: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetLegacyRenegotiateSupport(HITLS_Config *config, bool support); /** * @ingroup hitls_config * @brief Set whether to support session restoration during renegotiation. * By default, session restoration is not supported. * @param config [OUT] Config handle * @param support [IN] Whether to support the function. The options are as follows: True: yes; False: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetResumptionOnRenegoSupport(HITLS_Config *config, bool support); /** * @ingroup hitls_config * @brief Sets whether to verify the client certificate. * Client: This setting has no impact * Server: The certificate request will be sent. * * @param config [OUT] Config handle * @param support [IN] Indicates whether the client certificate can be verified.True: yes; False: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, The config parameter is empty. * @attention The settings on the client are invalid. Only the settings on the server take effect. * If this parameter is not set, single-ended verification is used by default. */ int32_t HITLS_CFG_SetClientVerifySupport(HITLS_Config *config, bool support); /** * @ingroup hitls_config * @brief Sets whether to allow the client certificate to be empty. * This parameter takes effect only when client certificate verification is enabled. * Client: This setting has no impact * Server: Check whether the certificate passes the verification when receiving an empty * certificate from the client. The verification fails by default. * * @param config [OUT] Config handle * @param support [IN] Indicates whether the authentication is successful when no client certificate is available. true: The server still passes the verification when the certificate sent by the client is empty. false: The server fails to pass the verification when the certificate sent by the client is empty. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, The config parameter is empty. */ int32_t HITLS_CFG_SetNoClientCertSupport(HITLS_Config *config, bool support); /** * @ingroup hitls_config * @brief Sets whether to forcibly support extended master keys. * * @param config [OUT] Config handle * @param support [IN] Indicates whether to forcibly support extended master keys. The options are as follows: True: yes; False: no. The default value is true. * @retval HITLS_SUCCESS. * @retval HITLS_NULL_INPUT, config is NULL */ int32_t HITLS_CFG_SetExtenedMasterSecretSupport(HITLS_Config *config, bool support); /** * @ingroup hitls_config * @brief Set whether the DH parameter can be automatically selected by users. * * If the value is true, the DH parameter is automatically selected based on the length of the * certificate private key. If the value is false, the DH parameter needs to be set. * * @param config [OUT] Config handle * @param support [IN] Whether to support the function. The options are as follows: True: yes; False: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetDhAutoSupport(HITLS_Config *config, bool support); /** * @ingroup hitls_config * @brief Set the DH parameter specified by the user. * * @param config [OUT] Config handle * @param dhPkey [IN] User-specified DH key. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is empty, or dhPkey is empty. */ int32_t HITLS_CFG_SetTmpDh(HITLS_Config *config, HITLS_CRYPT_Key *dhPkey); /** * @ingroup hitls_config * @brief Query whether renegotiation is supported. * * @param config [IN] Config handle * @param isSupport [OUT] Whether to support renegotiation * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_GetRenegotiationSupport(const HITLS_Config *config, uint8_t *isSupport); /** * @ingroup hitls_config * @brief Query whether the client certificate can be verified. * * @param config [IN] Config handle * @param isSupport [OUT] Indicates whether to verify the client certificate. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_GetClientVerifySupport(HITLS_Config *config, uint8_t *isSupport); /** * @ingroup hitls_config * @brief Query whether support there is no client certificate. This parameter takes effect * only when the client certificate is verified. * * @param config [IN] Config handle * @param isSupport [OUT] Indicates whether to support the function of not having a client certificate. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_GetNoClientCertSupport(HITLS_Config *config, uint8_t *isSupport); /** * @ingroup hitls_config * @brief Query whether extended master keys are supported. * * @param config [IN] Config handle * @param isSupport [OUT] Indicates whether to support the extended master key. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_GetExtenedMasterSecretSupport(HITLS_Config *config, uint8_t *isSupport); /** * @ingroup hitls_config * @brief Query whether the DH parameter can be automatically selected by the user. If yes, * the DH parameter will be automatically selected based on the length of the certificate private key. * * @param config [IN] Config handle * @param isSupport [OUT] Indicates whether to support the function of automatically selecting the DH parameter. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_GetDhAutoSupport(HITLS_Config *config, uint8_t *isSupport); /** * @ingroup hitls_config * @brief Setting whether to support post-handshake auth takes effect only for TLS1.3. client: If the client supports pha, the client sends pha extensions. Server: supports pha. After the handshake, the upper-layer interface HITLS_VerifyClientPostHandshake initiates certificate verification. * * @param config [OUT] Config handle * @param support [IN] Whether to support pha True: pha is supported. False: pha is not supported. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, The config parameter is empty. * @attention Before enabling this function on the server, enable HITLS_CFG_SetClientVerifySupport. * Otherwise, the configuration does not take effect. */ int32_t HITLS_CFG_SetPostHandshakeAuthSupport(HITLS_Config *config, bool support); /** * @ingroup hitls_config * @brief Query whether the post-handshake AUTH function is supported. * * @param config [IN] Config handle * @param isSupport [OUT] Indicates whether to support post-handshake AUTH. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_GetPostHandshakeAuthSupport(HITLS_Config *config, uint8_t *isSupport); /** * @ingroup hitls_config * @brief Sets whether to support not perform dual-ended verification * * @param support [IN] True: yes; False: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetVerifyNoneSupport(HITLS_Config *config, bool support); /** * @ingroup hitls_config * @brief Query whether not perform dual-ended verification is supported * * @param config [IN] Config handle * @param isSupport [OUT] Indicates whether not perform dual-ended verification is supported * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_GetVerifyNoneSupport(HITLS_Config *config, uint8_t *isSupport); /** * @ingroup hitls_config * @brief Set whether request client certificate only once is supported * * @param config [OUT] TLS link configuration * @param support [IN] True: yes; False: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetClientOnceVerifySupport(HITLS_Config *config, bool support); /** * @ingroup hitls_config * @brief Query whether request client certificate only once is supported * * @param config [IN] Config handle * @param isSupport [OUT] Indicates whether the client certificate can be requested only once. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_GetClientOnceVerifySupport(HITLS_Config *config, uint8_t *isSupport); /** * @ingroup hitls_config * @brief Set the supported cipher suites. The sequence of the cipher suites affects the priority of the selected * cipher suites. The cipher suite with the highest priority is the first. * @attention This setting will automatically filter out unsupported cipher suites. * @param config [OUT] Config handle. * @param cipherSuites [IN] cipher suite array, corresponding to the HITLS_CipherSuite enumerated value. * @param cipherSuitesSize [IN] cipher suite array length. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetCipherSuites(HITLS_Config *config, const uint16_t *cipherSuites, uint32_t cipherSuitesSize); /** * @ingroup hitls_config * @brief Clear the TLS1.3 cipher suite. * * @param config [IN] Config handle. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_ClearTLS13CipherSuites(HITLS_Config *config); /** * @ingroup hitls_config * @brief Set the format of the ec point. * * @attention Currently, this parameter can only be set to HITLS_ECPOINTFORMAT_UNCOMPRESSED. * * @param config [OUT] Config context. * @param pointFormats [IN] EC point format, corresponding to the HITLS_ECPointFormat enumerated value. * @param pointFormatsSize [IN] EC point format length * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetEcPointFormats(HITLS_Config *config, const uint8_t *pointFormats, uint32_t pointFormatsSize); /** * @ingroup hitls_config * @brief Set the group supported during key exchange. The group supported * by HiTLS can be queried in HITLS_NamedGroup. * * @attention If a group is not supported, an error will be reported during configuration check. * @param config [OUT] Config context. * @param groups [IN] Key exchange group. Corresponds to the HITLS_NamedGroup enumerated value. * @param groupsSize [IN] Group length * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetGroups(HITLS_Config *config, const uint16_t *groups, uint32_t groupsSize); /** * @ingroup hitls_config * @brief Set the signature algorithms supported during negotiation. The signature algorithms supported * by the HiTLS can be queried in the HITLS_SignHashAlgo file. * * @attention If an unsupported signature algorithm is set, an error will be reported during configuration check. * @param config [OUT] Config context * @param signAlgs [IN] Signature algorithm array, that is, the enumerated value of HITLS_SignHashAlgo. * @param signAlgsSize [IN] Signature algorithm array length * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetSignature(HITLS_Config *config, const uint16_t *signAlgs, uint16_t signAlgsSize); /** * @ingroup hitls_config * @brief Add the CA indicator, which is used when the peer certificate is requested. * * @param config [OUT] TLS link configuration * @param caType [IN] CA indication type * @param data [IN] CA indication data * @param len [IN] Data length * @retval HITLS_SUCCESS, if successful. * For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_AddCAIndication(HITLS_Config *config, HITLS_TrustedCAType caType, const uint8_t *data, uint32_t len); /** * @ingroup hitls_config * @brief Obtain the CA list. * * @param config [OUT] TLS link configuration * @retval CA list */ HITLS_TrustedCAList *HITLS_CFG_GetCAList(const HITLS_Config *config); /** * @ingroup hitls_config * @brief Set the CA list. * * @param config [in] TLS link configuration * @param list [in] CA list * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetCAList(HITLS_Config *config, HITLS_TrustedCAList *list); /** * @ingroup hitls_config * @brief Clear the CA list. * @param config [OUT] TLS link configuration * @retval CA list */ void HITLS_CFG_ClearCAList(HITLS_Config *config); /** * @ingroup hitls_config * @brief Set the key exchange mode, which is used by TLS1.3. * * @param config [OUT] TLS link configuration * @param mode [IN] PSK key exchange mode. Currently, only TLS13_KE_MODE_PSK_ONLY and TLS13_KE_MODE_PSK_WITH_DHE * are supported. The corresponding bit is set to 1. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetKeyExchMode(HITLS_Config *config, uint32_t mode); /** * @ingroup hitls_config * @brief Obtain the key exchange mode, which is used by TLS1.3. * * @param config [OUT] TLS link configuration * @retval Key exchange mode */ uint32_t HITLS_CFG_GetKeyExchMode(HITLS_Config *config); /* If the ClientHello callback is successfully executed, the handshake continues */ #define HITLS_CLIENT_HELLO_SUCCESS 1 /* The ClientHello callback fails. Send an alert message and terminate the handshake */ #define HITLS_CLIENT_HELLO_FAILED 0 /* The ClientHello callback is suspended. The handshake process is suspended and the callback is called again */ #define HITLS_CLIENT_HELLO_RETRY (-1) /** * @ingroup hitls_config * @brief ClientHello callback prototype for the server to process the callback. * * @param ctx [IN] Ctx context * @param alert [OUT] The callback that returns a failure should indicate the alert value to be sent in al. * @param arg [IN] Product input context * @retval HITLS_CLIENT_HELLO_SUCCESS: successful. * @retval HITLS_CLIENT_HELLO_RETRY: suspend the handshake process * @retval HITLS_CLIENT_HELLO_FAILED: failed, send an alert message and terminate the handshake */ typedef int32_t (*HITLS_ClientHelloCb)(HITLS_Ctx *ctx, int32_t *alert, void *arg); /** * @ingroup hitls_config * @brief Set the ClientHello callback on the server. * * @param config [OUT] Config context * @param callback [IN] ClientHello callback * @param arg [IN] Product input context * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetClientHelloCb(HITLS_Config *config, HITLS_ClientHelloCb callback, void *arg); /** * @ingroup hitls_config * @brief DTLS callback prototype for obtaining the timeout interval * @param ctx [IN] Ctx context * @param us [IN] Current timeout interval, Unit: microsecond * @return Obtained timeout interval */ typedef uint32_t (*HITLS_DtlsTimerCb)(HITLS_Ctx *ctx, uint32_t us); /** * @ingroup hitls_config * @brief Set the DTLS obtaining timeout interval callback. * @param config [OUT] Config context * @param callback [IN] DTLS callback for obtaining the timeout interval * @return HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetDtlsTimerCb(HITLS_Config *config, HITLS_DtlsTimerCb callback); /** * @ingroup hitls_config * @brief Obtaining the Minimum Supported Version Number * * @param config [IN] Config context * @param minVersion [OUT] Minimum version supported * @retval HITLS_SUCCESS is obtained successfully. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetMinVersion(const HITLS_Config *config, uint16_t *minVersion); /** * @ingroup hitls_config * @brief Obtaining the Maximum supported version number * * @param config [IN] Config context * @param maxVersion [OUT] Maximum supported version * @retval HITLS_SUCCESS is obtained successfully. * For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetMaxVersion(const HITLS_Config *config, uint16_t *maxVersion); /** * @ingroup hitls_config * @brief Obtain the symmetric encryption algorithm type based on the cipher suite. * * @param cipher[IN] Cipher suite * @param cipherAlg [OUT] Obtained symmetric encryption algorithm type. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetCipherId(const HITLS_Cipher *cipher, HITLS_CipherAlgo *cipherAlg); /** * @ingroup hitls_config * @brief Obtain the hash algorithm type based on the cipher suite. * * @param cipher [IN] Cipher suite * @param hashAlg [OUT] Obtained hash algorithm type. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetHashId(const HITLS_Cipher *cipher, HITLS_HashAlgo *hashAlg); /** * @ingroup hitls_config * @brief Obtain the MAC algorithm type based on the cipher suite. * * @param cipher [IN] Cipher suite * @param macAlg [OUT] Obtained MAC algorithm type. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetMacId(const HITLS_Cipher *cipher, HITLS_MacAlgo *macAlg); /** * @ingroup hitls_config * @brief Obtain the server authorization algorithm type based on the cipher suite. * * @param cipher [IN] Cipher suite * @param authAlg [OUT] Obtained server authorization type. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetAuthId(const HITLS_Cipher *cipher, HITLS_AuthAlgo *authAlg); /** * @ingroup hitls_config * @brief Obtain the key exchange algorithm type based on the cipher suite. * * @param cipher [IN] Cipher suite * @param kxAlg [OUT] Obtained key exchange algorithm type. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetKeyExchId(const HITLS_Cipher *cipher, HITLS_KeyExchAlgo *kxAlg); /** * @ingroup hitls_config * @brief Obtain the cipher suite name based on the cipher suite. * * @param cipher [IN] Cipher suite * @retval "(NONE)" Invalid cipher suite. * @retval Name of the given cipher suite */ const uint8_t* HITLS_CFG_GetCipherSuiteName(const HITLS_Cipher *cipher); /** * @ingroup hitls_config * @brief Obtain the RFC standard name of the cipher suite based on the cipher suite. * * @param cipherSuite [IN] cipher suite * * @retval "(NONE)" Invalid cipher suite. * @retval RFC standard name for the given cipher suite */ const uint8_t* HITLS_CFG_GetCipherSuiteStdName(const HITLS_Cipher *cipher); /** * @ingroup hitls_config * @brief Obtain the corresponding cipher suite pointer based on the RFC Standard Name. * * @param stdName [IN] RFC Standard Name * * @retval NULL. Failed to obtain the cipher suite. * @retval Pointer to the obtained cipher suite information. */ const HITLS_Cipher* HITLS_CFG_GetCipherSuiteByStdName(const uint8_t* stdName); /** * @ingroup hitls_config * @brief Outputs the description of the cipher suite as a string. * * @param cipherSuite [IN] Cipher suite * @param buf [OUT] Output the description. * @param len [IN] Description length * @retval NULL, Failed to obtain the description. * @retval Description of the cipher suite */ int32_t HITLS_CFG_GetDescription(const HITLS_Cipher *cipher, uint8_t *buf, int32_t len); /** * @ingroup hitls_config * @brief Determine whether to use the AEAD algorithm based on the cipher suite information. * * @param cipher [IN] Cipher suite information * @param isAead [OUT] Indicates whether to use the AEAD algorithm. * @retval HITLS_SUCCESS, obtained successfully. * HITLS_NULL_INPUT, the input parameter pointer is null. */ int32_t HITLS_CIPHER_IsAead(const HITLS_Cipher *cipher, uint8_t *isAead); /** * @ingroup hitls_config * @brief Obtain the earliest TLS version supported by the cipher suite based on the cipher suite. * * @param cipher [IN] Cipher suite * @param version [OUT] Obtain the earliest TLS version supported by the cipher suite. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetCipherVersion(const HITLS_Cipher *cipher, int32_t *version); /** * @ingroup hitls_config * @brief Obtain the cipher suite pointer based on the cipher suite ID. * * @param cipherSuite [IN] Cipher suite ID * * @retval HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE, Unsupported cipher suites * @retval Pointer to the obtained cipher suite information. */ const HITLS_Cipher *HITLS_CFG_GetCipherByID(uint16_t cipherSuite); /** * @ingroup hitls_config * @brief Obtain the encryption ID in the cipher suite. * * @param cipher [IN] Cipher suite. * @param cipherSuite [OUT] Cipher suite ID. * * @retval HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE, Unsupported cipher suites. * @retval Minimum TLS version supported by the given cipher suite. */ int32_t HITLS_CFG_GetCipherSuite(const HITLS_Cipher *cipher, uint16_t *cipherSuite); /** * @ingroup hitls_config * @brief Obtain the supported version number. * * @param config [IN] Config handle * @param version [OUT] Supported version number. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_GetVersionSupport(const HITLS_Config *config, uint32_t *version); /** * @ingroup hitls_config * @brief Set the supported version number. * * @param config [OUT] Config handle * @param version [IN] Supported version number. * @attention The maximum version number and minimum version number must be both TLS and DTLS. * Currently, only DTLS 1.2 is supported. This function is used together with the full configuration interfaces, * such as HITLS_CFG_NewDTLSConfig and HITLS_CFG_NewTLSConfig. * If the TLS full configuration is configured, only the TLS version can be set. * If full DTLS configuration is configured, only the DTLS version can be set. * The versions must be consecutive. By default, the minimum and maximum versions are supported. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetVersionSupport(HITLS_Config *config, uint32_t version); /** * @ingroup hitls_config * @brief This interface is used to verify the version in the premaster secret. * This interface takes effect on the server. The version must be earlier than 1.0, including 1.0. * * @param config [OUT] Config handle. * @param needCheck [IN] Indicates whether to perform verification. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetNeedCheckPmsVersion(HITLS_Config *config, bool needCheck); /** * @ingroup hitls_config * @brief Set the quiet disconnection mode. * * @param config [IN] TLS link configuration * @param mode [IN] Mode type. The value 0 indicates that the quiet disconnection mode is disabled, * and the value 1 indicates that the quiet disconnection mode is enabled. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetQuietShutdown(HITLS_Config *config, int32_t mode); /** * @ingroup hitls_config * @brief Obtain the current quiet disconnection mode. * * @param config [IN] TLS link configuration * @param mode [OUT] Current quiet disconnection mode * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_GetQuietShutdown(const HITLS_Config *config, int32_t *mode); /** * @ingroup hitls_config * @brief Set the timeout period after the DTLS over UDP connection is complete. * If the timer expires, the system does not receive the finished message resent by the peer end. * If this parameter is set to 0, the default value 240 seconds is used. * * @param config [IN] TLS link configuration * @param timeoutVal [IN] Timeout time * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetDtlsPostHsTimeoutVal(HITLS_Config *config, uint32_t timeoutVal); /** * @ingroup hitls_config * @brief Set the Encrypt-Then-Mac mode. * * @param config [IN] TLS link configuration * @param encryptThenMacType [IN] Current Encrypt-Then-Mac mode. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetEncryptThenMac(HITLS_Config *config, uint32_t encryptThenMacType); /** * @ingroup hitls_config * @brief Obtain the Encrypt-Then-Mac type. * * @param config [IN] TLS link configuration * @param encryptThenMacType [OUT] Current Encrypt-Then-Mac mode * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_GetEncryptThenMac(const HITLS_Config *config, uint32_t *encryptThenMacType); /** * @ingroup hitls_config * @brief Obtain the user data from the HiTLS Config object. * Generally, this function is called during the callback registered with the HiTLS. * * @attention must be called before HITLS_Connect and HITLS_Accept. * The life cycle of the user identifier must be longer than that of the TLS object. * @param config [OUT] TLS connection handle. * @param userData [IN] User identifier. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, The TLS object pointer of the input parameter is null. */ void *HITLS_CFG_GetConfigUserData(const HITLS_Config *config); /** * @ingroup hitls_config * @brief User data is stored in the HiTLS Config. The user data can be obtained * from the callback registered with the HiTLS. * * @attention must be called before HITLS_Connect and HITLS_Accept. * The life cycle of the user identifier must be longer than that of the TLS object. * If the user data needs to be cleared, the HITLS_SetUserData(ctx, NULL) interface can be called directly. * The Clean interface is not provided separately. * @param config [OUT] TLS connection handle. * @param userData [IN] User identifier. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, The TLS object pointer of the input parameter is null. */ int32_t HITLS_CFG_SetConfigUserData(HITLS_Config *config, void *userData); /** * @ingroup hitls_config * @brief UserData free callback */ typedef void (*HITLS_ConfigUserDataFreeCb)(void *); /** * @ingroup hitls_config * @brief Sets the UserData free callback * * @param config [OUT] TLS connection handle * @param userData [IN] User Data * @retval HITLS_SUCCESS * @retval HITLS_NULL_INPUT The input pointer is null */ int32_t HITLS_CFG_SetConfigUserDataFreeCb(HITLS_Config *config, HITLS_ConfigUserDataFreeCb callback); /** * @ingroup hitls_config * @brief Determine whether to use DTLS. * * @param config [IN] TLS link configuration. * @param isDtls [OUT] Indicates whether to use DTLS. * @retval HITLS_SUCCESS, obtained successfully. * HITLS_NULL_INPUT, the input parameter pointer is null. */ int32_t HITLS_CFG_IsDtls(const HITLS_Config *config, uint8_t *isDtls); /** * @ingroup hitls_config * @brief cipher suites are preferentially selected from the list of algorithms supported by the server. * * @param config [IN] TLS link configuration. * @param isSupport [IN] Support or not. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetCipherServerPreference(HITLS_Config *config, bool isSupport); /** * @ingroup hitls_config * @brief Obtains whether the current cipher suite supports preferential selection from the list of * algorithms supported by the server. * * @param config [IN] TLS link configuration * @param isSupport [OUT] Support or not * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_GetCipherServerPreference(const HITLS_Config *config, bool *isSupport); /** * @ingroup hitls_config * @brief Set whether to send handshake messages by route. * * @param config [IN/OUT] TLS link configuration * @param isEnable [IN] Indicates whether to enable the function of sending handshake information by range. * 0 indicates that the function is disabled. Other values indicate that the function is enabled. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetFlightTransmitSwitch(HITLS_Config *config, uint8_t isEnable); /** * @ingroup hitls_config * @brief Obtains the status of whether to send handshake information according to the route. * * @param config [IN] TLS link configuration. * @param isEnable [OUT] Indicates whether to send handshake information by route. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_GetFlightTransmitSwitch(const HITLS_Config *config, uint8_t *isEnable); /** * @ingroup hitls_config * @brief Set whether to send hello verify request message. * * @param config [IN] TLS link configuration. * @param isSupport [IN] Indicates whether to send hello verify request message. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetDtlsCookieExchangeSupport(HITLS_Config *config, bool isSupport); /** * @ingroup hitls_config * @brief Obtains the status of whether to send hello verify request message. * * @param config [IN] TLS link configuration. * @param isSupport [OUT] Indicates whether to send hello verify request message. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_GetDtlsCookieExchangeSupport(const HITLS_Config *config, bool *isSupport); /** * @ingroup hitls_config * @brief Set the max empty records number can be received * * @param config [IN/OUT] TLS link configuration * @param emptyNum [IN] Indicates the max number of empty records can be received * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetEmptyRecordsNum(HITLS_Config *config, uint32_t emptyNum); /** * @ingroup hitls_config * @brief Obtain the max empty records number can be received * * @param config [IN] TLS link configuration. * @param emptyNum [OUT] Indicates the max number of empty records can be received * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_GetEmptyRecordsNum(const HITLS_Config *config, uint32_t *emptyNum); /** * @ingroup hitls_config * @brief Set the max send fragment to restrict the amount of plaintext bytes in any record * * @param config [IN/OUT] TLS link configuration * @param maxSendFragment [IN] Indicates the max send fragment to restrict the amount of plaintext bytes in any record * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_CONFIG_INVALID_LENGTH, the maxSendFragment is less than 64 or greater than 16384. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetMaxSendFragment(HITLS_Config *config, uint16_t maxSendFragment); /** * @ingroup hitls_config * @brief Obtain the max send fragment to restrict the amount of plaintext bytes in any record * * @param config [IN] TLS link configuration. * @param maxSendFragment [OUT] Indicates the max send fragment * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_GetMaxSendFragment(const HITLS_Config *config, uint16_t *maxSendFragment); /** * @ingroup hitls_config * @brief Set the rec inbuffer inital size * * @param config [IN/OUT] TLS link configuration * @param recInbufferSize [IN] Indicates the rec inbuffer inital size * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_CONFIG_INVALID_LENGTH, the recInbufferSize is less than 512 or greater than 18432. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetRecInbufferSize(HITLS_Config *config, uint32_t recInbufferSize); /** * @ingroup hitls_config * @brief Obtain the rec inbuffer inital size * * @param config [IN] TLS link configuration. * @param recInbufferSize [OUT] Indicates the rec inbuffer inital size * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_GetRecInbufferSize(const HITLS_Config *config, uint32_t *recInbufferSize); /** * @ingroup hitls_config * @brief Set the maximum size of the certificate chain that can be sent by the peer end. * * @param config [IN/OUT] TLS link configuration. * @param maxSize [IN] Set the maximum size of the certificate chain that can be sent by the peer end. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetMaxCertList(HITLS_Config *config, uint32_t maxSize); /** * @ingroup hitls_config * @brief Obtain the maximum size of the certificate chain that can be sent by the peer end. * * @param config [IN] TLS link configuration * @param maxSize [OUT] Maximum size of the certificate chain that can be sent by the peer end. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_GetMaxCertList(const HITLS_Config *config, uint32_t *maxSize); typedef HITLS_CRYPT_Key *(*HITLS_DhTmpCb)(HITLS_Ctx *ctx, int32_t isExport, uint32_t keyLen); /** * @ingroup hitls_config * @brief Set the TmpDh callback, cb can be NULL. * @param config [OUT] Config Context. * @param callback [IN] TmpDh Callback. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetTmpDhCb(HITLS_Config *config, HITLS_DhTmpCb callback); typedef uint64_t (*HITLS_RecordPaddingCb)(HITLS_Ctx *ctx, int32_t type, uint64_t length, void *arg); /** * @ingroup hitls_config * @brief Set the RecordPadding callback. * * @param config [OUT] Config context * @param callback [IN] RecordPadding Callback * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetRecordPaddingCb(HITLS_Config *config, HITLS_RecordPaddingCb callback); /** * @ingroup hitls_config * @brief Obtains the RecordPadding callback function. * * @param config [OUT] Config context * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ HITLS_RecordPaddingCb HITLS_CFG_GetRecordPaddingCb(HITLS_Config *config); /** * @ingroup hitls_config * @brief Sets the parameters arg required by the RecordPadding callback function. * * @param config [OUT] Config context * @param arg [IN] Related parameters arg * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetRecordPaddingCbArg(HITLS_Config *config, void *arg); /** * @ingroup hitls_config * @brief Obtains the parameter arg required by the RecordPadding callback function. * * @param config [OUT] Config context * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ void *HITLS_CFG_GetRecordPaddingCbArg(HITLS_Config *config); /** * @ingroup hitls_config * @brief Disables the verification of keyusage in the certificate. This function is enabled by default. * * @param config [OUT] Config context * @param isCheck [IN] Sets whether to check key usage. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetCheckKeyUsage(HITLS_Config *config, bool isCheck); /** * @ingroup hitls_config * @brief Set read ahead flag to indicate whether read more data than user required to buffer in advance * @param config [OUT] Hitls config * @param onOff [IN] Read ahead flag, nonzero value indicates open, zero indicates close * @retval HITLS_NULL_INPUT * @retval HITLS_SUCCESS */ int32_t HITLS_CFG_SetReadAhead(HITLS_Config *config, int32_t onOff); /** * @ingroup hitls_config * @brief Get whether reading ahead has been set or not * * @param config [IN] Hitls config * @param onOff [OUT] Read ahead flag * @retval HITLS_NULL_INPUT * @retval HITLS_SUCCESS */ int32_t HITLS_CFG_GetReadAhead(HITLS_Config *config, int32_t *onOff); /** * @ingroup hitls_config * @brief Set the function to support the specified feature. * * @param config [OUT] Config context * @param mode [IN] Mode features to enabled. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetModeSupport(HITLS_Config *config, uint32_t mode); /** * @ingroup hitls_config * @brief Disable the specified feature. * * @param config [OUT] Config context * @param mode [IN] Mode features to disabled. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_ClearModeSupport(HITLS_Config *config, uint32_t mode); /** * @ingroup hitls_config * @brief Obtain the mode of the function feature in the config file. * * @param config [OUT] Config context * @param mode [OUT] Mode obtain the output parameters of the mode. * @retval HITLS_NULL_INPUT, the input parameter pointer is null. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_GetModeSupport(const HITLS_Config *config, uint32_t *mode); /** * @ingroup hitls * @brief Sets whether to support middle box compat mode. * * @param ctx [IN] TLS Connection Handle. * @param isMiddleBox [IN] Support or Not. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_SetMiddleBoxCompat(HITLS_Config *config, bool isMiddleBox); /** * @ingroup hitls * @brief Obtain whether middle box compat mode is supported. * * @param ctx [IN] TLS connection handle. * @param isMiddleBox [OUT] Support or Not. * @retval HITLS_NULL_INPUT, the input parameter pointer is NULL. * @retval HITLS_SUCCESS, if successful. */ int32_t HITLS_CFG_GetMiddleBoxCompat(HITLS_Config *config, bool *isMiddleBox); /** * @ingroup hitls_config * @brief Set whether the current configuration is a client configuration. * * @param config [OUT] Config context. * @param isClient [IN] Indicates whether it is a client configuration. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetEndPoint(HITLS_Config *config, bool isClient); #ifdef __cplusplus } #endif #endif /* HITLS_CONFIG_H */
2301_79861745/bench_create
include/tls/hitls_config.h
C
unknown
63,873
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_COOKIE_H #define HITLS_COOKIE_H #include <stdint.h> #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define HITLS_COOKIE_GENERATE_SUCCESS 1 /* Cookie Generated successfully */ #define HITLS_COOKIE_GENERATE_ERROR 0 /* Cookie Generation failed */ #define HITLS_COOKIE_VERIFY_SUCCESS 1 /* Cookie verification succeeded */ #define HITLS_COOKIE_VERIFY_ERROR 0 /* Cookie verification failed */ /** * @ingroup hitls_config * @brief Cookie Generation callback prototype for the server to process the callback. * * @param ctx [IN] Ctx context * @param cookie [OUT] Generated cookie * @param cookie_len [OUT] Length of Generated cookie * @retval HITLS_COOKIE_GENERATE_SUCCESS: successful. Other values are considered as failure. */ typedef int32_t (*HITLS_AppGenCookieCb)(HITLS_Ctx *ctx, uint8_t *cookie, uint32_t *cookieLen); /** * @ingroup hitls_config * @brief Cookie Verification callback prototype for the server to process the callback. * * @param ctx [IN] Ctx context * @param cookie [IN] Cookie to be verified * @param cookie_len [IN] Length of Cookie to be verified * @retval HITLS_COOKIE_VERIFY_SUCCESS: successful. Other values are considered as failure. */ typedef int32_t (*HITLS_AppVerifyCookieCb)(HITLS_Ctx *ctx, const uint8_t *cookie, uint32_t cookieLen); /** * @ingroup hitls_config * @brief Set the cookie generation callback on the server. * * @param config [OUT] Config context * @param callback [IN] CookieGenerate callback * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetCookieGenCb(HITLS_Config *config, HITLS_AppGenCookieCb callback); /** * @ingroup hitls_config * @brief Set the cookie verification callback on the server. * * @param config [OUT] Config context * @param callback [IN] CookieVerify callback * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetCookieVerifyCb(HITLS_Config *config, HITLS_AppVerifyCookieCb callback); #ifdef __cplusplus } #endif #endif // HITLS_COOKIE_H
2301_79861745/bench_create
include/tls/hitls_cookie.h
C
unknown
2,748
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_crypt_init * @ingroup hitls * @brief algorithm abstraction layer initialization */ #ifndef HITLS_CRYPT_INIT_H #define HITLS_CRYPT_INIT_H #ifdef __cplusplus extern "C" { #endif /** * @ingroup hitls_crypt_init * @brief Initialize the algorithm interface. By default, the hicrypto interface is used. * * @attention If hicrypto is not used, you do not need to call this API. */ void HITLS_CryptMethodInit(void); #ifdef __cplusplus } #endif #endif /* HITLS_CRYPT_INIT_H */
2301_79861745/bench_create
include/tls/hitls_crypt_init.h
C
unknown
1,051
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_crypt_reg * @ingroup hitls * @brief Algorithm related interfaces to be registered */ #ifndef HITLS_CRYPT_TYPE_H #define HITLS_CRYPT_TYPE_H #include <stdint.h> #include <stdbool.h> #include "bsl_obj.h" #ifdef __cplusplus extern "C" { #endif typedef void HITLS_Lib_Ctx; /** * @ingroup hitls_crypt_type * @brief Key handle, which is converted into the corresponding structure based on the algorithm library * used by the user. */ typedef void HITLS_CRYPT_Key; /** * @ingroup hitls_crypt_type * @brief Hash context. The user converts the structure based on the algorithm library. */ typedef void HITLS_HASH_Ctx; /** * @ingroup hitls_crypt_type * @brief HMAC context. The user converts the HMAC context into the corresponding structure * based on the algorithm library. */ typedef void HITLS_HMAC_Ctx; /** * @ingroup hitls_crypt_type * @brief cipher context. The user converts the cipher context into the corresponding structure * based on the algorithm library. */ typedef void HITLS_Cipher_Ctx; typedef struct BslList HITLS_CIPHER_List; /** * @ingroup hitls_crypt_type * @brief Enumerated value of the symmetric encryption algorithm type. */ typedef enum { HITLS_AEAD_CIPHER, HITLS_CBC_CIPHER, HITLS_CIPHER_TYPE_BUTT = 255 } HITLS_CipherType; /** * @ingroup hitls_crypt_type * @brief Enumerated value of the symmetric encryption algorithm. */ typedef enum { HITLS_CIPHER_NULL = BSL_CID_NULL, // Represents a null value, no encryption or decryption HITLS_CIPHER_AES_128_CBC = BSL_CID_AES128_CBC, HITLS_CIPHER_AES_256_CBC = BSL_CID_AES256_CBC, HITLS_CIPHER_AES_128_GCM = BSL_CID_AES128_GCM, HITLS_CIPHER_AES_256_GCM = BSL_CID_AES256_GCM, HITLS_CIPHER_AES_128_CCM = BSL_CID_AES128_CCM, HITLS_CIPHER_AES_256_CCM = BSL_CID_AES256_CCM, HITLS_CIPHER_AES_128_CCM8 = BSL_CID_AES128_CCM8, HITLS_CIPHER_AES_256_CCM8 = BSL_CID_AES256_CCM8, HITLS_CIPHER_CHACHA20_POLY1305 = BSL_CID_CHACHA20_POLY1305, HITLS_CIPHER_SM4_CBC = BSL_CID_SM4_CBC, HITLS_CIPHER_SM4_GCM = BSL_CID_SM4_GCM, HITLS_CIPHER_BUTT = BSL_CID_UNKNOWN // Represents an unrecognized algorithm type } HITLS_CipherAlgo; /** * @ingroup hitls_crypt_type * @brief Hash algorithm enumeration */ typedef enum { HITLS_HASH_NULL = BSL_CID_NULL, // Represents a null value, no hash operation HITLS_HASH_MD5 = BSL_CID_MD5, HITLS_HASH_SHA1 = BSL_CID_SHA1, HITLS_HASH_SHA_224 = BSL_CID_SHA224, HITLS_HASH_SHA_256 = BSL_CID_SHA256, HITLS_HASH_SHA_384 = BSL_CID_SHA384, HITLS_HASH_SHA_512 = BSL_CID_SHA512, HITLS_HASH_SM3 = BSL_CID_SM3, HITLS_HASH_BUTT = BSL_CID_UNKNOWN // Represents an unrecognized algorithm type } HITLS_HashAlgo; // CRYPT_MD_AlgId /** * @ingroup hitls_crypt_type * @brief MAC algorithm enumerated value */ typedef enum { HITLS_MAC_NULL = BSL_CID_NULL, // Represents a null value, no MAC operation HITLS_MAC_MD5 = BSL_CID_HMAC_MD5, HITLS_MAC_1 = BSL_CID_HMAC_SHA1, HITLS_MAC_224 = BSL_CID_HMAC_SHA224, HITLS_MAC_256 = BSL_CID_HMAC_SHA256, HITLS_MAC_384 = BSL_CID_HMAC_SHA384, HITLS_MAC_512 = BSL_CID_HMAC_SHA512, HITLS_MAC_SM3 = BSL_CID_HMAC_SM3, HITLS_MAC_AEAD = BSL_CID_MAC_AEAD, HITLS_MAC_BUTT = BSL_CID_UNKNOWN // Represents an unrecognized algorithm type } HITLS_MacAlgo; /** * @ingroup hitls_crypt_type * @brief Enumerated value of the authentication algorithm */ typedef enum { HITLS_AUTH_NULL, HITLS_AUTH_RSA, HITLS_AUTH_ECDSA, HITLS_AUTH_DSS, HITLS_AUTH_PSK, HITLS_AUTH_SM2, HITLS_AUTH_ANY, HITLS_AUTH_BUTT = 255 } HITLS_AuthAlgo; /** * @ingroup hitls_crypt_type * @brief Key exchange algorithm enumerated value */ typedef enum { HITLS_KEY_EXCH_NULL, HITLS_KEY_EXCH_ECDHE, HITLS_KEY_EXCH_DHE, HITLS_KEY_EXCH_ECDH, HITLS_KEY_EXCH_DH, HITLS_KEY_EXCH_RSA, HITLS_KEY_EXCH_PSK, HITLS_KEY_EXCH_DHE_PSK, HITLS_KEY_EXCH_ECDHE_PSK, HITLS_KEY_EXCH_RSA_PSK, HITLS_KEY_EXCH_ECC, /* sm2 encrypt */ HITLS_KEY_EXCH_BUTT = 255 } HITLS_KeyExchAlgo; /** * @ingroup hitls_crypt_type * @brief Signature algorithm enumeration */ typedef enum { HITLS_SIGN_RSA_PKCS1_V15 = BSL_CID_RSA, HITLS_SIGN_DSA = BSL_CID_DSA, HITLS_SIGN_ECDSA = BSL_CID_ECDSA, HITLS_SIGN_RSA_PSS = BSL_CID_RSASSAPSS, HITLS_SIGN_ED25519 = BSL_CID_ED25519, HITLS_SIGN_SM2 = BSL_CID_SM2DSA, HITLS_SIGN_BUTT = 255 } HITLS_SignAlgo; /** * @ingroup hitls_crypt_type * @brief Elliptic curve type enumerated value */ typedef enum { HITLS_EC_CURVE_TYPE_NAMED_CURVE = 3, HITLS_EC_CURVE_TYPE_BUTT = 255 } HITLS_ECCurveType; /** * @ingroup hitls_crypt_type * @brief Named Group enumerated value */ typedef enum { HITLS_EC_GROUP_SECP256R1 = 23, HITLS_EC_GROUP_SECP384R1 = 24, HITLS_EC_GROUP_SECP521R1 = 25, HITLS_EC_GROUP_BRAINPOOLP256R1 = 26, HITLS_EC_GROUP_BRAINPOOLP384R1 = 27, HITLS_EC_GROUP_BRAINPOOLP512R1 = 28, HITLS_EC_GROUP_CURVE25519 = 29, HITLS_EC_GROUP_SM2 = 41, HITLS_FF_DHE_2048 = 256, HITLS_FF_DHE_3072 = 257, HITLS_FF_DHE_4096 = 258, HITLS_FF_DHE_6144 = 259, HITLS_FF_DHE_8192 = 260, HITLS_HYBRID_X25519_MLKEM768 = 4588, HITLS_HYBRID_ECDH_NISTP256_MLKEM768 = 4587, HITLS_HYBRID_ECDH_NISTP384_MLKEM1024 = 4589, HITLS_NAMED_GROUP_BUTT = 0xFFFFu } HITLS_NamedGroup; /** * @ingroup hitls_crypt_type * @brief Elliptic curve point format enumerated value */ typedef enum { HITLS_POINT_FORMAT_UNCOMPRESSED = 0, HITLS_POINT_FORMAT_BUTT = 255 } HITLS_ECPointFormat; /** * @ingroup hitls_crypt_type * @brief Elliptic curve parameter */ typedef struct { HITLS_ECCurveType type; /**< Elliptic curve type. */ union { void *prime; /**< Display prime number: corresponding to the protocol explicit_prime. */ void *char2; /**< Display char2: corresponding to the protocol explicit_char2. */ HITLS_NamedGroup namedcurve; /**< Elliptic curve ID. */ } param; } HITLS_ECParameters; /** * @ingroup hitls_crypt_type * @brief Key parameters */ typedef struct { HITLS_CipherType type; /**< Encryption algorithm type. Currently, only aead is supported. */ HITLS_CipherAlgo algo; /**< Symmetric encryption algorithm. */ const uint8_t *key; /**< Symmetry key. */ uint32_t keyLen; /**< Symmetry key length. */ const uint8_t *iv; /**< IV. */ uint32_t ivLen; /**< IV length. */ uint8_t *aad; /**< Aad: AEAD: one of the input parameters for encryption and decryption. additional data. */ uint32_t aadLen; /**< Aad length. */ const uint8_t *hmacKey; /**< Hmac key. */ uint32_t hmacKeyLen; /**< Hmac key length. */ HITLS_Cipher_Ctx **ctx; /**< HITLS_Cipher_Ctx handle */ } HITLS_CipherParameters; /** * @ingroup hitls_crypt_type * @brief sm2 ecdhe negotiation key parameters */ typedef struct { HITLS_CRYPT_Key *tmpPriKey; /* Local temporary private key. */ uint8_t *tmpPeerPubkey; /* Peer temporary public key. */ uint32_t tmpPeerPubKeyLen; /* Length of the peer temporary public key. */ HITLS_CRYPT_Key *priKey; /* Local private key, which is used for SM2 algorithm negotiation. It is the private key of the encryption certificate. */ HITLS_CRYPT_Key *peerPubKey; /* Peer public key, which is used for SM2 algorithm negotiation. It is the public key in the encryption certificate. */ bool isClient; /* Client ID, which is used by the SM2 algorithm negotiation key. */ } HITLS_Sm2GenShareKeyParameters; /** * @ingroup hitls_crypt_type * @brief HKDF-Extract Input */ typedef struct { HITLS_HashAlgo hashAlgo; /* Hash algorithm. */ const uint8_t *salt; /* Salt value. */ uint32_t saltLen; /* Salt value length. */ const uint8_t *inputKeyMaterial; /* Input Keying Material. */ uint32_t inputKeyMaterialLen; /* Ikm length. */ } HITLS_CRYPT_HkdfExtractInput; /** * @ingroup hitls_crypt_type * @brief HKDF-Expand Input */ typedef struct { HITLS_HashAlgo hashAlgo; /* Hash algorithm. */ const uint8_t *prk; /* A pseudorandom key of at least HashLen octets. */ uint32_t prkLen; /* Prk length. */ const uint8_t *info; /* Extended data. */ uint32_t infoLen; /* Extend the data length. */ } HITLS_CRYPT_HkdfExpandInput; #ifdef __cplusplus } #endif #endif
2301_79861745/bench_create
include/tls/hitls_crypt_type.h
C
unknown
9,412
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_custom_extensions * @ingroup hitls * @brief TLS Custom Extensions */ #ifndef HITLS_CUSTOM_EXTENSIONS_H #define HITLS_CUSTOM_EXTENSIONS_H #include <stdint.h> #include "hitls_type.h" #include "hitls_cert_type.h" #ifdef __cplusplus extern "C" { #endif /* Extension context */ /** * @ingroup hitls_custom_extensions * @brief Extension is used in ClientHello messages. */ #define HITLS_EX_TYPE_CLIENT_HELLO 0x00001 /** * @ingroup hitls_custom_extensions * @brief Extension is used in Tls1.2 ServerHello messages. */ #define HITLS_EX_TYPE_TLS1_2_SERVER_HELLO 0x00002 /** * @ingroup hitls_custom_extensions * @brief Extension is used in Tls1.3 ServerHello messages. */ #define HITLS_EX_TYPE_TLS1_3_SERVER_HELLO 0x00004 /** * @ingroup hitls_custom_extensions * @brief Extension is used in HelloRetryRequest messages (TLS 1.3). */ #define HITLS_EX_TYPE_HELLO_RETRY_REQUEST 0x00008 /** * @ingroup hitls_custom_extensions * @brief Extension is used in EncryptedExtensions messages (TLS 1.3). */ #define HITLS_EX_TYPE_ENCRYPTED_EXTENSIONS 0x00010 /** * @ingroup hitls_custom_extensions * @brief Extension is used in Certificate messages. */ #define HITLS_EX_TYPE_TLS1_3_CERTIFICATE 0x00020 /** * @ingroup hitls_custom_extensions * @brief Extension is used in CertificateRequest messages. */ #define HITLS_EX_TYPE_TLS1_3_CERTIFICATE_REQUEST 0x00040 /** * @ingroup hitls_custom_extensions * @brief Extension is used in NewSessionTicket messages (TLS 1.3). */ #define HITLS_EX_TYPE_TLS1_3_NEW_SESSION_TICKET 0x00080 #define HITLS_ADD_CUSTOM_EXTENSION_RET_PACK 1 #define HITLS_ADD_CUSTOM_EXTENSION_RET_PASS HITLS_SUCCESS /** * @ingroup hitls_custom_extensions * @brief Callback function to add a custom extension. * * This function is invoked when adding a custom extension to a TLS message. * It prepares the extension data to be sent, utilizing certificate information if necessary. * * @param ctx [IN] TLS context * @param extType [IN] Extension type * @param context [IN] Context where the extension applies * @param out [OUT] Pointer to the extension data to be sent * @param outLen [OUT] Length of the extension data * @param cert [IN] Pointer to the HITLS_CERT_X509 structure representing certificate information * @param certIndex [IN] Certificate index indicating its position in the certificate chain * @param alert [OUT] Alert value provided by the user when requesting to add the custom extension * @param addArg [IN] Additional argument provided when registering the callback * @retval HITLS_ADD_CUSTOM_EXTENSION_RET_PACK if the extension needs to be packed, * HITLS_ADD_CUSTOM_EXTENSION_RET_PASS if it does not need to be packed, * otherwise, any other return value is considered a failure and will trigger a fatal alert based on the alert value. */ typedef int (*HITLS_AddCustomExtCallback) (const HITLS_Ctx *ctx, uint16_t extType, uint32_t context, uint8_t **out, uint32_t *outLen, HITLS_CERT_X509 *cert, uint32_t certIndex, uint32_t *alert, void *addArg); /** * @ingroup hitls_custom_extensions * @brief Callback function to free a custom extension. * * This function is invoked to release resources allocated for a custom extension. * * @param ctx [IN] TLS context * @param ext_type [IN] Extension type * @param context [IN] Context where the extension applies * @param out [IN] Extension data to be freed * @param add_arg [IN] Additional argument provided when registering the callback */ typedef void (*HITLS_FreeCustomExtCallback) (const HITLS_Ctx *ctx, uint16_t extType, uint32_t context, uint8_t *out, void *addArg); /** * @ingroup hitls_custom_extensions * @brief Callback function to parse a custom extension. * * This function is invoked when parsing a received custom extension. It interprets the * extension data and updates the TLS context based on certificate information if necessary. * * @param ctx [IN] TLS context * @param extType [IN] Extension type * @param context [IN] Context where the extension applies * @param in [IN] Pointer to the received extension data * @param inlen [IN] Length of the extension data * @param cert [IN] Pointer to the HITLS_CERT_X509 structure representing certificate information * @param certIndex [IN] Certificate index indicating its position in the certificate chain * @param alert [OUT] Alert value provided by the user when requesting to add the custom extension * @param parseArg [IN] Additional argument provided when registering the callback * @retval HITLS_SUCCESS if successful, otherwise an error code */ typedef int (*HITLS_ParseCustomExtCallback) (const HITLS_Ctx *ctx, uint16_t extType, uint32_t context, const uint8_t **in, uint32_t *inLen, HITLS_CERT_X509 *cert, uint32_t certIndex, uint32_t *alert, void *parseArg); /** * @ingroup hitls_custom_extensions * @brief Structure to hold parameters for adding a custom extension. */ typedef struct { uint16_t extType; /**< Extension type */ uint32_t context; /**< Context where the extension applies */ HITLS_AddCustomExtCallback addCb; /**< Callback function to add the extension */ HITLS_FreeCustomExtCallback freeCb; /**< Callback function to free the extension */ void *addArg; /**< Additional argument for add and free callbacks */ HITLS_ParseCustomExtCallback parseCb; /**< Callback function to parse the extension */ void *parseArg; /**< Additional argument for parse callback */ } HITLS_CustomExtParams; /** * @ingroup hitls_custom_extensions * @brief Add a custom extension to the TLS context using a parameter structure. * * This function adds a custom extension to the specified TLS context using the provided * parameters encapsulated in the HITLS_CustomExtParams structure. * * @param ctx [IN] TLS context * @param params [IN] Pointer to the structure containing custom extension parameters * @retval HITLS_SUCCESS if successful * For other error codes, see hitls_error.h */ uint32_t HITLS_AddCustomExtension(HITLS_Ctx *ctx, const HITLS_CustomExtParams *params); /** * @ingroup hitls_custom_extensions * @brief Add a custom extension to the HITLS configuration using a parameter structure. * * This function adds a custom extension to the specified HITLS configuration using the provided * parameters encapsulated in the HITLS_CustomExtParams structure. * * @param config [IN] Pointer to the HITLS configuration * @param params [IN] Pointer to the structure containing custom extension parameters * @retval HITLS_SUCCESS if successful * For other error codes, see hitls_error.h */ uint32_t HITLS_CFG_AddCustomExtension(HITLS_Config *config, const HITLS_CustomExtParams *params); #ifdef __cplusplus } #endif #endif /* HITLS_CUSTOM_EXTENSIONS_H */
2301_79861745/bench_create
include/tls/hitls_custom_extensions.h
C
unknown
7,751
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_crypt_reg * @ingroup hitls * @brief hitls maintenance and debugging */ #ifndef HITLS_DEBUG_H #define HITLS_DEBUG_H #include <stdint.h> #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define INDICATE_VALUE_SUCCESS 1u #define INDICATE_EVENT_LOOP 0x01 // 0000 0000 0000 0001, Handshake state transition #define INDICATE_EVENT_EXIT 0x02 // 0000 0000 0000 0010, Handshake status exit #define INDICATE_EVENT_READ 0x04 // 0000 0000 0000 0100, Read event #define INDICATE_EVENT_WRITE 0x08 // 0000 0000 0000 1000, Write event #define INDICATE_EVENT_HANDSHAKE_START 0x10 // 0000 0000 0001 0000, Handshake Start #define INDICATE_EVENT_HANDSHAKE_DONE 0x20 // 0000 0000 0010 0000, Handshake completed #define INDICATE_EVENT_STATE_CONNECT 0x1000 // 0001 0000 0000 0000, Local client #define INDICATE_EVENT_STATE_ACCEPT 0x2000 // 0010 0000 0000 0000, Local server #define INDICATE_EVENT_ALERT 0x4000 // 0100 0000 0000 0000, Warning Time #define INDICATE_EVENT_READ_ALERT (INDICATE_EVENT_ALERT | INDICATE_EVENT_READ) #define INDICATE_EVENT_WRITE_ALERT (INDICATE_EVENT_ALERT | INDICATE_EVENT_WRITE) #define INDICATE_EVENT_STATE_ACCEPT_LOOP (INDICATE_EVENT_STATE_ACCEPT | INDICATE_EVENT_LOOP) #define INDICATE_EVENT_STATE_ACCEPT_EXIT (INDICATE_EVENT_STATE_ACCEPT | INDICATE_EVENT_EXIT) #define INDICATE_EVENT_STATE_CONNECT_LOOP (INDICATE_EVENT_STATE_CONNECT | INDICATE_EVENT_LOOP) #define INDICATE_EVENT_STATE_CONNECT_EXIT (INDICATE_EVENT_STATE_CONNECT | INDICATE_EVENT_EXIT) /** * @ingroup hitls_debug * @brief Information prompt callback prototype * * @attention The message prompt callback function does not return a value * @param ctx [IN] Ctx context * @param eventType [IN] EventType Event type * @param value [IN] Value Function return value or Alert type that matches the event type * @retval No value is returned. */ typedef void (*HITLS_InfoCb)(const HITLS_Ctx *ctx, int32_t eventType, int32_t value); /** * @ingroup hitls_debug * @brief Set the callback for prompt information. * * @param ctx [OUT] Ctx context * @param callback [IN] Callback function for prompting information * @retval HITLS_SUCCESS, if successful. * For other error codes, see hitls_error.h. */ int32_t HITLS_SetInfoCb(HITLS_Ctx *ctx, HITLS_InfoCb callback); /** * @ingroup hitls_debug * @brief Callback for obtaining information * * @param ctx [IN] Ctx context * @retval Callback function of the current information prompt. * If this parameter is not set, NULL is returned. */ HITLS_InfoCb HITLS_GetInfoCb(const HITLS_Ctx *ctx); /** * @ingroup hitls_debug * @brief Set the callback function for prompting information. * * @param config [OUT] Config Context * @param callback [IN] Client callback * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetInfoCb(HITLS_Config *config, HITLS_InfoCb callback); /** * @ingroup hitls_debug * @brief Callback function for obtaining information prompts * * @param config [IN] config Context * @retval Callback function of the current information prompt. * If this parameter is not set, NULL is returned. */ HITLS_InfoCb HITLS_CFG_GetInfoCb(const HITLS_Config *config); /** * @ingroup hitls_debug * @brief Callback prototype of a protocol message * * @attention: The callback function for messages in the retention protocol does not return any value. * @param writePoint [IN] writePoint Message direction in the callback ">>>" or "<<<" * @param tlsVersion [IN] tlsVersion TLS version, for example, HITLS_VERSION_TLS12. * @param contentType[IN] contentType Type of the processed message body. * @param msg [IN] msg callback internal message processing instruction data * @param msgLen [IN] msgLen Processing instruction data length * @param ctx [IN] ctx HITLS context * @param arg [IN] arg User data, for example, BIO * @retval No value is returned. */ typedef void (*HITLS_MsgCb) (int32_t writePoint, int32_t tlsVersion, int32_t contentType, const void *msg, uint32_t msgLen, HITLS_Ctx *ctx, void *arg); /** * @ingroup hitls_debug * @brief Set the protocol message callback function, cb can be NULL. * * @param ctx [OUT] Ctx context * @param callback [IN] Protocol message callback function * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetMsgCb(HITLS_Ctx *ctx, HITLS_MsgCb callback); /** * @ingroup hitls_debug * @brief Set the protocol message callback function, cb can be NULL. * * @param config [OUT] Config Context * @param callback [IN] Protocol message callback * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetMsgCb(HITLS_Config *config, HITLS_MsgCb callback); /** * @ingroup hitls_debug * @brief Set the related parameters arg required by the protocol message callback function. * * @param config [OUT] Config Context. * @param arg [IN] Related parameters arg. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetMsgCbArg(HITLS_Config *config, void *arg); #ifdef __cplusplus } #endif #endif // HITLS_DEBUG_H
2301_79861745/bench_create
include/tls/hitls_debug.h
C
unknown
6,172
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_errno * @ingroup hitls * @brief error module */ #ifndef HITLS_ERROR_H #define HITLS_ERROR_H #include <stdint.h> #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define HITLS_SUCCESS 0 #define HITLS_X509_V_OK 0 /** * @ingroup hitls_errno * @brief Indicates that the connection is blocked. You can call HITLS_Connect to continue the connection. * This problem is usually caused by read and write operations. */ #define HITLS_WANT_CONNECT 1 /** * @ingroup hitls_errno * @brief Indicates that the connection is blocked and the HITLS_Accept can be called to continue the connection. * This problem is usually caused by read and write operations. */ #define HITLS_WANT_ACCEPT 2 /** * @ingroup hitls_errno * @brief indicates that the receiving buffer is empty and the interface can be * called to continue receiving data. */ #define HITLS_WANT_READ 3 /** * @ingroup hitls_errno * @brief The sending buffer is full and the interface can be called to continue sending data. */ #define HITLS_WANT_WRITE 4 /** * @ingroup hitls_errno * @brief An unrecoverable fatal error occurs in the TLS protocol, usually a protocol error. */ #define HITLS_ERR_TLS 5 /** * @ingroup hitls_errno * @brief An unrecoverable I/O error occurs, * which is usually a low level receiving and receiving exception or an unknown error occurs. */ #define HITLS_ERR_SYSCALL 6 #define HITLS_WANT_BACKUP 7 /** * @ingroup hitls_errno * @brief The operation did not complete because an application callback set by * HITLS_CFG_SetClientHelloCb() has asked to be called again. */ #define HITLS_WANT_CLIENT_HELLO_CB 8 /** * @ingroup hitls_errno * @brief The operation did not complete because an application callback set by * HITLS_CFG_SetCertCb() has asked to be called again. */ #define HITLS_WANT_X509_LOOKUP 9 /** * @ingroup hitls_errno * * Error code returned by the TLS module */ typedef enum { HITLS_NULL_INPUT = 0x02010001, /**< Incorrect null pointer input. */ HITLS_INVALID_INPUT, /**< Invalid input, the parameter value is out of the valid range.*/ HITLS_INTERNAL_EXCEPTION, /**< Unexpected internal error, which is unlikely. */ HITLS_MEMALLOC_FAIL, /**< Failed to apply for memory. */ HITLS_MEMCPY_FAIL, /**< Memory Copy Failure. */ HITLS_UNREGISTERED_CALLBACK, /**< Use unregistered callback. */ HITLS_CONFIG_FAIL_START = 0x02020001, /**< config module error code start bit. */ HITLS_CONFIG_NO_SUITABLE_CIPHER_SUITE, /**< No suitable cipher suite is found. */ HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE, /**< Unsupported cipher suites. */ HITLS_CONFIG_INVALID_SET, /**< Invalid setting. */ HITLS_CONFIG_NO_SUITABLE_SIGNATURE_ALGORITHM, /**< The signature algorithm and the cipher suite are nonmatching. */ HITLS_CONFIG_NO_GROUPS, /**< The group is not set. */ HITLS_CONFIG_UNSUPPORT_SIGNATURE_ALGORITHM, /**< Unsupported signature algorithm. */ HITLS_CONFIG_UNSUPPORT_POINT_FORMATS, /**< Unsupported the dot format. */ HITLS_CONFIG_INVALID_VERSION, /**< Unsupported the protocol version. */ HITLS_CONFIG_INVALID_LENGTH, /**< Invalid length. */ HITLS_CONFIG_NO_CERT, /**< Unset the certificate. */ HITLS_CONFIG_NO_PRIVATE_KEY, /**< Unset the certificate private key. */ HITLS_CONFIG_DUP_DH_KEY_FAIL, /**< Duplicate DH key failure. */ HITLS_CFG_ERR_LOAD_CERT_FILE, /**< Failed to load the certificate file. */ HITLS_CFG_ERR_LOAD_CERT_BUFFER, /**< Failed to load the certificate buffer. */ HITLS_CFG_ERR_LOAD_KEY_FILE, /**< Failed to load the key file. */ HITLS_CFG_ERR_LOAD_KEY_BUFFER, /**< Failed to load the key buffer. */ HITLS_CFG_ERR_LOAD_CRL_FILE, /**< Failed to load the CRL file. */ HITLS_CFG_ERR_LOAD_CRL_BUFFER, /**< Failed to load the CRL buffer. */ HITLS_CONFIG_ERR_LOAD_GROUP_INFO, /**< Failed to load the group info. */ HITLS_CONFIG_ERR_LOAD_SIGN_SCHEME_INFO, /**< Failed to load the signature scheme info. */ HITLS_CONFIG_DUP_CUSTOM_EXT, /**< Duplicate custom extension type detected. */ HITLS_CONFIG_ERR_MAX_LIMIT_CUSTOM_EXT, /**< Exceed the max limit of custom extensions. */ HITLS_CM_FAIL_START = 0x02030001, /**< Error start bit of the conn module. */ HITLS_CM_LINK_FATAL_ALERTED, /**< link sent fatal alert. */ HITLS_CM_LINK_CLOSED, /**< Link has been closed. */ HITLS_CM_LINK_UNESTABLISHED, /**< The current link is not established. Do not perform other operations, such as read and write. */ HITLS_CM_LINK_UNSUPPORT_SECURE_RENEGOTIATION, /**< The current link Unsupported security renegotiation. */ HITLS_MSG_HANDLE_FAIL_START = 0x02040001, /**< Start bit of the error code processed by the state machine. */ HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE, /**< receives unexpected handshake messages. */ HITLS_MSG_HANDLE_RANDOM_SIZE_ERR, /**< Incorrect random number length. */ HITLS_MSG_HANDLE_UNSUPPORT_POINT_FORMAT, /**< Unsupported the point format. */ HITLS_MSG_HANDLE_CIPHER_SUITE_ERR, /**< cannot find the supported cipher suite. */ HITLS_MSG_HANDLE_UNSUPPORT_VERSION, /**< Unsupported version. */ HITLS_MSG_HANDLE_STATE_ILLEGAL, /**< Handshake status error. */ HITLS_MSG_HANDLE_UNSUPPORT_KX_ALG, /**< Unsupported key exchange algorithm. */ HITLS_MSG_HANDLE_UNSUPPORT_CERT, /**< Unsupported certificate. */ HITLS_MSG_HANDLE_UNKNOWN_CURVE_TYPE, /**< Unsupported elliptic curve type. */ HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL, /**< Failed to verify the finished message. */ HITLS_MSG_HANDLE_VERIFY_SIGN_FAIL, /**< Failed to verify the finished message. */ HITLS_MSG_HANDLE_INCORRECT_DIGEST_LEN, /**< Incorrect length of the digest. */ HITLS_MSG_HANDLE_UNSUPPORT_NAMED_CURVE, /**< Unsupported ECDH elliptic curves. */ HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE, /**< Unsupported the extended type. */ HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE, /**< Unsupported cipher suites. */ HITLS_MSG_HANDLE_COOKIE_ERR, /**< Incorrect cookie. */ HITLS_MSG_VERIFY_COOKIE_ERR, /**< Failed to verify the cookie. */ HITLS_MSG_HANDLE_ERR_ENCODE_ECDH_KEY, /**< Failed to obtain the ECDH public key. */ HITLS_MSG_HANDLE_ERR_ENCODE_DH_KEY, /**< Failed to obtain the DH public key. */ HITLS_MSG_HANDLE_ERR_GET_DH_PARAMETERS, /**< Failed to obtain the DH parameter. */ HITLS_MSG_HANDLE_ERR_GET_DH_KEY, /**< Failed to generate the DH key. */ HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE, /**< Not receive the peer certificate. */ HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE, /**< Server has no certificate to send. */ HITLS_MSG_HANDLE_UNMATCHED_SEQUENCE, /**< Handshake sequence number nonmatch */ HITLS_MSG_HANDLE_ILLEGAL_VERSION, /**< Incorrect version. */ HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE, /**< Incorrect cipher suite. */ HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP, /**< Incorrect selectedGroup. */ HITLS_MSG_HANDLE_ILLEGAL_EXTRENED_MASTER_SECRET, /**< Incorrect extended master key. */ HITLS_MSG_HANDLE_MISSING_EXTENSION, /**< Message missing the extended field that must be sent */ HITLS_MSG_HANDLE_DUPLICATE_HELLO_RETYR_REQUEST, /**< Duplicate Hello Retry Request messages */ HITLS_MSG_HANDLE_ALPN_PROTOCOL_NO_MATCH, /**< No matching alpn */ HITLS_MSG_HANDLE_ILLEGAL_PSK_LEN, /**< Invalid PSK length */ HITLS_MSG_HANDLE_ILLEGAL_IDENTITY_LEN, /**< Invalid identity length */ HITLS_MSG_HANDLE_GET_UNSIGN_DATA_FAIL, /**< Failed to obtain the unsigned data during signature calculation */ HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID, /**< Receives an incorrect session ID */ HITLS_MSG_HANDLE_SNI_UNRECOGNIZED_NAME, /**< Not accept the extended value of server_name */ HITLS_MSG_HANDLE_ALPN_UNRECOGNIZED, /**< Not accept the extended ALPN value */ HITLS_MSG_HANDLE_ILLEGAL_KEY_UPDATE_TYPE, /**< Receives an incorrect key update type */ HITLS_MSG_HANDLE_SYS_TIME_FAIL, /**< System time function returns a failure */ HITLS_MSG_HANDLE_DTLS_CONNECT_TIMEOUT, /**< DTLS connection timeout */ HITLS_MSG_HANDLE_UNSECURE_VERSION, /**< Insecure version. */ HITLS_MSG_HANDLE_UNSECURE_CIPHER_SUITE, /**< Insecure cipher suites. */ HITLS_MSG_HANDLE_RENEGOTIATION_FAIL, /**< Renegotiation failure */ HITLS_MSG_HANDLE_SESSION_ID_CTX_ILLEGAL, /**< Session ID ctx mismatch */ HITLS_MSG_HANDLE_ENCRYPT_THEN_MAC_ERR, /**< Failed to change the EncryptThenMac status */ HITLS_MSG_HANDLE_ILLEGAL_PSK_IDENTITY, /**< psk identity error */ HITLS_MSG_HANDLE_PSK_USE_SESSION_FAIL, /**< The TLS1.3 client fails to process the PSK callback. */ HITLS_MSG_HANDLE_PSK_FIND_SESSION_FAIL, /**< The TLS1.3 server fails to process the PSK callback. */ HITLS_MSG_HANDLE_PSK_SESSION_INVALID_CIPHER_SUITE, /**< TLS1.3 psk session algorithm suite is incorrect. */ HITLS_MSG_HANDLE_PSK_INVALID, /**< TLS1.3 psk check failed. */ HITLS_MSG_HANDLE_INVALID_CERT_REQ_CTX, /**< TLS1.3 invalid certificateReqCtx. */ HITLS_MSG_HANDLE_HANDSHAKE_FAILURE, /**< TLS1.3 handshake parameters cannot be negotiated. */ HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD, /**< Receives an incorrect compression algorithm. */ HITLS_MSG_HANDLE_INVALID_EXTENDED_MASTER_SECRET, /**< The peer Unsupported the extended master key. */ HITLS_MSG_HANDLE_ERR_CLIENT_HELLO_FRAGMENT, HITLS_MSG_HANDLE_ERR_INAPPROPRIATE_FALLBACK, /**< The downgrade negotiation failed, and the client supports a higher version. */ HITLS_MSG_HANDLE_DTLS_RETRANSMIT_NOT_TIMEOUT, HITLS_MSG_HANDLE_ERR_WITHOUT_TIMEOUT_ACTION, HITLS_MSG_HANDLE_ERR_TIMEOUT_REWIND, HITLS_PACK_FAIL_START = 0x02050001, /**< Start bit of the pack error code. */ HITLS_PACK_UNSUPPORT_VERSION, /**< Unsupported version. */ HITLS_PACK_UNSECURE_VERSION, /**< Insecure version. */ HITLS_PACK_UNSUPPORT_HANDSHAKE_MSG, /**< Unsupported handshake messages. */ HITLS_PACK_NOT_ENOUGH_BUF_LENGTH, /**< Insufficient buffer length. */ HITLS_PACK_SESSIONID_ERR, /**< Failed to assemble the sessionId. */ HITLS_PACK_COOKIE_ERR, /**< Failed to assemble the cookie. */ HITLS_PACK_CLIENT_CIPHER_SUITE_ERR, /**< Failed to assemble client_cipher_suite. */ HITLS_PACK_UNSUPPORT_KX_ALG, /**< Unsupported the key negotiation algorithm. */ HITLS_PACK_UNSUPPORT_KX_CURVE_TYPE, /**< Unsupported ECDH key negotiation algorithm curve. */ HITLS_PACK_INVALID_KX_PUBKEY_LENGTH, /**< Invalid length of the public key for key negotiation */ HITLS_PACK_SIGNATURE_ERR, /**< Failed to assemble the server_kx message signature data. */ HITLS_PACK_PRE_SHARED_KEY_ERR, /**< Failed to assemble the PSK. */ HITLS_PARSE_FAIL_START = 0x02060001, /**< Start bit of the parse error code. */ HITLS_PARSE_UNSUPPORT_VERSION, /**< Unsupported Version. */ HITLS_PARSE_UNSUPPORT_HANDSHAKE_MSG, /**< Unsupported handshake messages. */ HITLS_PARSE_INVALID_MSG_LEN, /**< Message length error. */ HITLS_PARSE_DUPLICATE_EXTENDED_MSG, /**< Duplicate extended messages. */ HITLS_PARSE_COMPRESSION_METHOD_ERR, /**< Incorrect compression type. */ HITLS_PARSE_SERVER_NAME_ERR, /**< Failed to parse server_name. */ HITLS_PARSE_CERT_ERR, /**< Failed to parse the certificate. */ HITLS_PARSE_ECDH_PUBKEY_ERR, /**< Failed to parse the ecdh public key. */ HITLS_PARSE_ECDH_SIGN_ERR, /**< Failed to parse the ecdh signature. */ HITLS_PARSE_UNSUPPORT_KX_ALG, /**< Unsupported the key exchange algorithm. */ HITLS_PARSE_UNSUPPORT_KX_CURVE_TYPE, /**< Unsupported ECC curve type. */ HITLS_PARSE_GET_SIGN_PARA_ERR, /**< Failed to obtain the signature algorithm and hash algorithm */ HITLS_PARSE_UNSUPPORT_SIGN_ALG, /**< Unsupported the signature algorithm. */ HITLS_PARSE_VERIFY_SIGN_FAIL, /**< Failed to verify the signature. */ HITLS_PARSE_DH_P_ERR, /**< Failed to parse the dh_p. */ HITLS_PARSE_DH_G_ERR, /**< Failed to parse the dh_g. */ HITLS_PARSE_DH_PUBKEY_ERR, /**< Failed to parse the DHE public key. */ HITLS_PARSE_DH_SIGN_ERR, /**< Failed to parse the DHE signature. */ HITLS_PARSE_UNSUPPORTED_EXTENSION, /**< Unsupported extended fields. */ HITLS_PARSE_CA_LIST_ERR, /**< Failed to parse the CA name list. */ HITLS_PARSE_EXCESSIVE_MESSAGE_SIZE, /**< The length of the parsing exceeds the maximum. */ HITLS_PARSE_PRE_SHARED_KEY_FAILED, /**< Failed to parse the PSK extension. */ HITLS_PARSE_DUPLICATED_KEY_SHARE, /**< duplicated key share entry. */ HITLS_REASS_FAIL_START = 0x02070001, /**< Reassembly module error code start bit. */ HITLS_REASS_INVALID_FRAGMENT, /**< Receives invalid fragmented messages. */ HITLS_CCS_FAIL_START = 0x02080001, /**< ccs module error code start bit. */ HITLS_CCS_INVALID_CMD, /**< Invalid command. */ HITLS_ALERT_FAIL_START = 0x02090001, /**< alert module error code start bit. */ HITLS_ALERT_NO_WANT_SEND, /**< No alert messages to be sent. */ HITLS_REC_FAIL_START = 0x020A0001, /**< record module error start bit. */ HITLS_REC_PMTU_TOO_SMALL, /**< pmtu is too small to meet the record packet length. */ HITLS_REC_ERR_BUFFER_NOT_ENOUGH, /**< Insufficient buffer. */ HITLS_REC_ERR_TOO_BIG_LENGTH, /**< The length of the plaintext data to be written exceeds the maximum length of a single record. */ HITLS_REC_ERR_NOT_SUPPORT_CIPHER, /**< Unsupported the cipher suites. */ HITLS_REC_ERR_ENCRYPT, /**< Encryption failed. */ HITLS_REC_ERR_AEAD_NONCE_PARAM, /**< AEAD nonce input parameter is incorrect. */ HITLS_REC_ERR_SN_WRAPPING, /**< Sequence number Rewind. */ HITLS_REC_ERR_IO_EXCEPTION, /**< The low level I/O is abnormal. */ HITLS_REC_NORMAL_IO_BUSY, /**< Low level I/O is busy, need wait for the next sending. */ HITLS_REC_NORMAL_RECV_BUF_EMPTY, /**< The receiving buffer is empty. */ HITLS_REC_NORMAL_RECV_UNEXPECT_MSG, /**< If REC receives unexpected messages and the receiver is user, needs to recall the previous function. */ HITLS_REC_NORMAL_RECV_DISORDER_MSG, /**< The REC receives disordered records, to receive disordered finished records. */ HITLS_REC_INVLAID_RECORD, /**< record: invalid record message. */ HITLS_REC_INVALID_PROTOCOL_VERSION, /**< record: Incorrect version. */ HITLS_REC_BAD_RECORD_MAC, /**< record: Invalid MAC. */ HITLS_REC_DECODE_ERROR, /**< Decoding failed. */ HITLS_REC_RECORD_OVERFLOW, /**< Record is too long. */ HITLS_REC_ERR_RECV_UNEXPECTED_MSG, /**< Record: unexpected message */ HITLS_REC_ERR_GENERATE_MAC, /**< Failed to generate the MAC address. */ HITLS_REC_NORMAL_IO_EOF, /**< IO object has reached EOF. */ HITLS_REC_ENCRYPTED_NUMBER_OVERFLOW, /**< The number of AES-GCM encryption times cannot exceed 2^24.5. */ HITLS_REC_ERR_DATA_BETWEEN_CCS_AND_FINISHED, /**< When version is below TLS13, must not have data between ccs and finished. */ HITLS_UIO_FAIL_START = 0x020B0001, /**< uio module error code start bit. */ HITLS_UIO_FAIL, /**< UIO internal failure. */ HITLS_UIO_IO_EXCEPTION, /**< Low level I/O exception. */ HITLS_UIO_SCTP_IS_SND_BUF_EMPTY_FAIL, /**< Failed to obtain whether the sending buffer of the UIO object is empty. */ HITLS_UIO_SCTP_ADD_AUTH_KEY_FAIL, /**< Failed to add the auth key for the sctp UIO object. */ HITLS_UIO_SCTP_ACTIVE_AUTH_KEY_FAIL, /**< Failed to activate the auth key for the sctp UIO object. */ HITLS_UIO_SCTP_DEL_AUTH_KEY_FAIL, /**< Failed to delete the auth key for the sctp UIO object. */ HITLS_UIO_IO_TYPE_ERROR, /**< The type of UIO is wrong. */ HITLS_CERT_FAIL_START = 0x020C0001, /**< Certificate module error code start bit. */ HITLS_CERT_STORE_CTRL_ERR_SET_VERIFY_DEPTH, HITLS_CERT_STORE_CTRL_ERR_ADD_CERT_LIST, HITLS_CERT_STORE_CTRL_ERR_ADD_CRL_LIST, /**< Failed to add CRL list to verify store. */ HITLS_CERT_STORE_CTRL_ERR_CLEAR_CRL_LIST, /**< Failed to clear CRL list from verify store. */ HITLS_CERT_ERR_X509_DUP, /**< Failed to duplicate the certificate. */ HITLS_CERT_ERR_KEY_DUP, /**< Failed to duplicate the key. */ HITLS_CERT_ERR_STORE_DUP, /**< Failed to duplicate the store. */ HITLS_CERT_ERR_CHAIN_DUP, /**< Failed to duplicate the certificate chain. */ HITLS_CERT_CTRL_ERR_GET_ENCODE_LEN, /**< Failed to obtain the certificate encoding length. */ HITLS_CERT_CTRL_ERR_GET_PUB_KEY, /**< Failed to obtain the certificate public key. */ HITLS_CERT_CTRL_ERR_GET_SIGN_ALGO, /**< Failed to obtain the signature algorithm. */ HITLS_CERT_KEY_CTRL_ERR_GET_SIGN_LEN, /**< Failed to obtain the signature length. */ HITLS_CERT_KEY_CTRL_ERR_GET_TYPE, /**< Failed to obtain the key type. */ HITLS_CERT_KEY_CTRL_ERR_GET_CURVE_NAME, /**< Failed to obtain the elliptic curve ID. */ HITLS_CERT_KEY_CTRL_ERR_GET_POINT_FORMAT, /**< Failed to obtain the point format. */ HITLS_CERT_KEY_CTRL_ERR_GET_SECBITS, /**< Failed to obtain security bits. */ HITLS_CERT_KEY_CTRL_ERR_IS_ENC_USAGE, /**< Determine whether the certificate fails to be encrypted, Applicable to TLCP scenarios. */ HITLS_CERT_KEY_CTRL_ERR_IS_DIGITAL_SIGN_USAGE, /**< Determine whether the certificate fails to be digital sign. */ HITLS_CERT_KEY_CTRL_ERR_IS_KEY_CERT_SIGN_USAGE, /**< Determine whether the certificate fails to be cert sign. */ HITLS_CERT_KEY_CTRL_ERR_IS_KEY_AGREEMENT_USAGE, /**< Determine whether the certificate fails to be agreement. */ HITLS_CERT_KEY_CTRL_ERR_GET_PARAM_ID, /**< Failed to obtain the parameter ID. */ HITLS_CERT_ERR_INVALID_KEY_TYPE, /**< Invalid key type */ HITLS_CERT_ERR_CHECK_CERT_AND_KEY, /**< Certificate and private key nonmatch. */ HITLS_CERT_ERR_NO_CURVE_MATCH, /**< Certificate and elliptic curve ID nonmatch. */ HITLS_CERT_ERR_NO_POINT_FORMAT_MATCH, /**< Certificate and dot format nonmatch. */ HITLS_CERT_ERR_NO_SIGN_SCHEME_MATCH, /**< Certificate and signature algorithm nonmatch. */ HITLS_CERT_ERR_SELECT_CERTIFICATE, /**< Failed to select the certificate. */ HITLS_CERT_ERR_BUILD_CHAIN, /**< Failed to construct the certificate chain. */ HITLS_CERT_ERR_ENCODE_CERT, /**< Certificate encoding failure. */ HITLS_CERT_ERR_PARSE_MSG, /**< Certificate decoding failure. */ HITLS_CERT_ERR_VERIFY_CERT_CHAIN, /**< Certificate chain verification failure. */ HITLS_CERT_ERR_CREATE_SIGN, /**< Failed to sign using the certificate private key. */ HITLS_CERT_ERR_VERIFY_SIGN, /**< Failed to use the certificate public key to verify the signature. */ HITLS_CERT_ERR_ENCRYPT, /**< Failed to encrypt the RSA certificate public key. */ HITLS_CERT_ERR_DECRYPT, /**< Failed to decrypt using the RSA Certificate Private Key */ HITLS_CERT_ERR_ADD_CHAIN_CERT, /**< Failed to add the certificate chain. */ HITLS_CERT_ERR_MGR_DUP, /**< Failed to duplicate the certificate management structure. */ HITLS_CERT_ERR_INSECURE_SIG_ALG, /**< Insecure signature algorithm strength. */ HITLS_CERT_ERR_CA_KEY_WITH_INSECURE_SECBITS, /**< Insecure CA certificate key security bits. */ HITLS_CERT_ERR_EE_KEY_WITH_INSECURE_SECBITS, /**< Insecure EE certificate key security bits. */ HITLS_CERT_ERR_EXP_CERT, /**< No expected certificate included. */ HITLS_CERT_ERR_ENCODE, /**< Failed to encode the certificate. */ HITLS_CERT_ERR_KEYUSAGE, /**< Failed to verify the certificate keyusage. */ HITLS_CERT_ERR_INVALID_STORE_TYPE, /**< Invalid store type */ HITLS_CERT_ERR_X509_REF, /**< Certificate reference counting error. */ HITLS_CERT_ERR_INSERT_CERTPAIR, /**< Certificate insert certPair error. */ HITLS_CERT_ERR_NO_KEYUSAGE, /**< No keyusage. */ HITLS_CERT_KEY_CTRL_ERR_IS_DATA_ENC_USAGE, /**< Determine whether the certificate fails to be data enc. */ HITLS_CERT_KEY_CTRL_ERR_IS_NON_REPUDIATION_USAGE, /**< Determine whether the certificate fails to be non-repudiation. */ HITLS_CERT_CTRL_ERR_GET_SUBJECT_DN, /**< Failed to obtain the subject DN of the certificate. */ HITLS_CERT_STORE_CTRL_ERR_GET_VERIFY_DEPTH, /**< Get the certificate verification depth error. */ HITLS_CERT_CTRL_ERR_IS_SELF_SIGNED, /** Determine whether the certificate is a self-signed certificate */ HITLS_CERT_CTRL_ERR_INVALID_CMD, /**< certificate ctrl invalid command */ HITLS_CERT_STORE_CTRL_ERR_GET_VERIFY_FLAGS, /**< Failed to obtain the certificate verification flags. */ HITLS_CERT_STORE_CTRL_ERR_SET_VERIFY_FLAGS, /**< Failed to set the certificate verification flags. */ HITLS_CRYPT_FAIL_START = 0x020D0001, /**< Crypt adaptation module error code start bit. */ HITLS_CRYPT_ERR_GENERATE_RANDOM, /**< Failed to generate a random number. */ HITLS_CRYPT_ERR_HMAC, /**< HMAC operation failure. */ HITLS_CRYPT_ERR_DIGEST, /**< Hash operation failure. */ HITLS_CRYPT_ERR_ENCRYPT, /**< Encryption failure. */ HITLS_CRYPT_ERR_DECRYPT, /**< Decryption failure. */ HITLS_CRYPT_ERR_ENCODE_ECDH_KEY, /**< Failed to obtain the ECDH public key. */ HITLS_CRYPT_ERR_CALC_SHARED_KEY, /**< Failed to calculate the ECDH shared key. */ HITLS_CRYPT_ERR_ENCODE_DH_KEY, /**< Failed to obtain the DH public key. */ HITLS_CRYPT_ERR_HKDF_EXTRACT, /**< HKDF-Extract calculation error. */ HITLS_CRYPT_ERR_HKDF_EXPAND, /**< HKDF-Expand calculation error. */ HITLS_CRYPT_ERR_KEM_ENCAPSULATE, /**< KEM-Encapsulate calculation error. */ HITLS_CRYPT_ERR_KEM_DECAPSULATE, /**< KEM-Decapsulate calculation error. */ HITLS_CRYPT_ERR_DH, /**< DH failure. */ HITLS_CRYPT_ERR_KDF, /**< KDF failure. */ HITLS_APP_FAIL_START = 0x020E0001, /**< APP module error code start bit. */ HITLS_APP_ERR_TOO_LONG_TO_WRITE, /**< APP Data written is too long. */ HITLS_APP_ERR_ZERO_READ_BUF_LEN, /**< The buffer size read by the APP cannot be 0. */ HITLS_APP_ERR_WRITE_BAD_RETRY, /**< The addresses of the buffers sent twice are inconsistent. */ HITLS_SESS_FAIL_START = 0x02100001, /**< Session feature error code start bit. */ HITLS_SESS_ERR_SESSION_ID_GENRATE, /**< Session id output error. */ HITLS_SESS_ERR_DECODE_TICKET, /**< Error decoding session ticket object. */ HITLS_SESS_ERR_SESSION_TICKET_SIZE_INCORRECT, /**< Session ticket length is incorrect. */ HITLS_SESS_ERR_SESSION_TICKET_HMAC_FAIL, /**< Failed to calculate the session ticket hmac. */ HITLS_SESS_ERR_SESSION_TICKET_KEY_FAIL, /**< Failed to obtain the ticket key, and then link establishment failed, so needs to sent alert. */ HITLS_SESS_ERR_ENC_VERIFY_RESULT_FAIL, /**< Failed to verify the encoding result. */ HITLS_SESS_ERR_ENC_MASTER_SECRET_FAIL, /**< Failed to encode the master secret. */ HITLS_SESS_ERR_ENC_EXT_MASTER_SECRET_FAIL, /**< Failed to encode the extend master secret. */ HITLS_SESS_ERR_ENC_SESSION_ID_FAIL, /**< Failed to encode the session ID. */ HITLS_SESS_ERR_ENC_SESSION_ID_CTX_FAIL, /**< Failed to encode the session ID context. */ HITLS_SESS_ERR_ENC_HOST_NAME_FAIL, /**< Failed to encode the host name. */ HITLS_SESS_ERR_ENC_TIME_OUT_FAIL, /**< Failed to encode the time out. */ HITLS_SESS_ERR_ENC_VERSION_FAIL, /**< Failed to encode the version. */ HITLS_SESS_ERR_ENC_CIPHER_SUITE_FAIL, /**< Failed to encode the ciphersuite. */ HITLS_SESS_ERR_ENC_START_TIME_FAIL, /**< Failed to encode the start time. */ HITLS_SESS_ERR_ENC_PSK_IDENTITY_FAIL, /**< Failed to encode the PSK identity. */ HITLS_SESS_ERR_DEC_VERIFY_RESULT_FAIL, /**< Failed to decode the verify result. */ HITLS_SESS_ERR_DEC_VERSION_FAIL, /**< Failed to decode the version. */ HITLS_SESS_ERR_DEC_CIPHER_SUITE_FAIL, /**< Fails to decode the cipher suite. */ HITLS_SESS_ERR_DEC_MASTER_SECRET_FAIL, /**< Failed to decode the master secret. */ HITLS_SESS_ERR_DEC_PSK_IDENTITY_FAIL, /**< Failed to decode the PSK identity. */ HITLS_SESS_ERR_DEC_START_TIME_FAIL, /**< Failed to decode the start time. */ HITLS_SESS_ERR_DEC_TIME_OUT_FAIL, /**< Failed to decode the time out. */ HITLS_SESS_ERR_DEC_HOST_NAME_FAIL, /**< Failed to decode the host name. */ HITLS_SESS_ERR_DEC_SESSION_ID_CTX_FAIL, /**< Failed to decode the session ID context. */ HITLS_SESS_ERR_DEC_SESSION_ID_FAIL, /**< Failed to decode the session ID. */ HITLS_SESS_ERR_DEC_EXT_MASTER_SECRET_FAIL, /**< Failed to decode the extended master secret. */ HITLS_SESS_ERR_ENC_PEER_CERT_FAIL, /**< Failed to encode the peercert. */ HITLS_SESS_ERR_DEC_PEER_CERT_FAIL, /**< Failed to decode the peercert. */ HITLS_X509_FAIL_START = 0x02120001, /**< The X509 feature error code start bit of. */ HITLS_X509_V_ERR_UNSPECIFIED, HITLS_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, HITLS_X509_V_ERR_UNABLE_TO_GET_CRL, HITLS_X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, HITLS_X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, HITLS_X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, HITLS_X509_V_ERR_CERT_SIGNATURE_FAILURE, HITLS_X509_V_ERR_CRL_SIGNATURE_FAILURE, HITLS_X509_V_ERR_CERT_NOT_YET_VALID, HITLS_X509_V_ERR_CERT_HAS_EXPIRED, HITLS_X509_V_ERR_CRL_NOT_YET_VALID, HITLS_X509_V_ERR_CRL_HAS_EXPIRED, HITLS_X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, HITLS_X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, HITLS_X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, HITLS_X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, HITLS_X509_V_ERR_OUT_OF_MEM, HITLS_X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, HITLS_X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, HITLS_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, HITLS_X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, HITLS_X509_V_ERR_CERT_CHAIN_TOO_LONG, HITLS_X509_V_ERR_CERT_REVOKED, HITLS_X509_V_ERR_INVALID_CA, HITLS_X509_V_ERR_PATH_LENGTH_EXCEEDED, HITLS_X509_V_ERR_INVALID_PURPOSE, HITLS_X509_V_ERR_CERT_UNTRUSTED, HITLS_X509_V_ERR_CERT_REJECTED, HITLS_X509_V_ERR_SUBJECT_ISSUER_MISMATCH, HITLS_X509_V_ERR_AKID_SKID_MISMATCH, HITLS_X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH, HITLS_X509_V_ERR_KEYUSAGE_NO_CERTSIGN, HITLS_X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, HITLS_X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION, HITLS_X509_V_ERR_KEYUSAGE_NO_CRL_SIGN, HITLS_X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION, HITLS_X509_V_ERR_INVALID_NON_CA, HITLS_X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED, HITLS_X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE, HITLS_X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED, HITLS_X509_V_ERR_INVALID_EXTENSION, HITLS_X509_V_ERR_INVALID_POLICY_EXTENSION, HITLS_X509_V_ERR_NO_EXPLICIT_POLICY, HITLS_X509_V_ERR_DIFFERENT_CRL_SCOPE, HITLS_X509_V_ERR_ERROR_IN_CMP_CERT_NOT_AFTER_FIELD, HITLS_X509_V_ERR_ERROR_IN_CMP_CRL_THIS_UPDATE_FIELD, HITLS_X509_V_ERR_ERROR_IN_CMP_CRL_NEXT_UPDATE_FIELD, HITLS_X509_V_ERR_ERROR_IN_CMP_CERT_NOT_BEFORE_FIELD, HITLS_X509_V_ERR_CRL_PATH_VALIDATION_ERROR, HITLS_CERT_SELF_ADAPT_ERR = 0x02130001, HITLS_CERT_SELF_ADAPT_INVALID_TIME, HITLS_CERT_SELF_ADAPT_UNSUPPORT_FORMAT, HITLS_CERT_SELF_ADAPT_BUILD_CERT_CHAIN_ERR, HITLS_CALLBACK_CERT_RETRY = 0x02140001, /**< Certificate callback retry. */ HITLS_CALLBACK_CERT_ERROR, /**< Certificate callback failure. */ HITLS_CALLBACK_CLIENT_HELLO_ERROR, /**< ClientHello callback failure. */ HITLS_CALLBACK_CLIENT_HELLO_RETRY, /**< ClientHello callback retry. */ HITLS_CALLBACK_CLIENT_HELLO_INVALID_CALL, /**< Invalid use of HITLS_ClientHelloGet* function. */ HITLS_CALLBACK_CLIENT_HELLO_EXTENSION_NOT_FOUND, /**< Extension not found. */ } HITLS_ERROR; /** * @ingroup hitls_error * @brief Obtain the TLS operation error code. * * @param ctx [IN] TLS context * @param ret [IN] Return value of the TLS interface called * @retval HITLS_SUCCESS, No error. * @retval HITLS_WANT_CONNECT, indicates that the connection is blocked. * You can call HITLS_Connect to continue the connection, This problem is usually caused * by the read and write operation failure. * @retval HITLS_WANT_ACCEPT, indicates that the connection is blocked and the HITLS_Accept * can be called to continue the connection. This problem is usually caused by the read and write operation failure. * @retval HITLS_WANT_READ, indicates that the receiving buffer is empty and the interface * can be called to continue receiving data. * @retval HITLS_WANT_WRITE, indicates that the sending buffer is full and the interface * can be called to continue sending data. * @retval HITLS_ERR_TLS, An unrecoverable fatal error occurs in the TLS protocol, usually a protocol error. * @retval HITLS_ERR_SYSCALL, An unrecoverable I/O error occurs. Generally, the I/O error is caused * by the Low level receiving and receiving exception and an unknown error occurs. */ int32_t HITLS_GetError(const HITLS_Ctx *ctx, int32_t ret); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* end HITLS_ERROR_H */
2301_79861745/bench_create
include/tls/hitls_error.h
C
unknown
33,768
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_psk * @ingroup hitls * @brief Basic functions for link establishment based on PSK */ #ifndef HITLS_PSK_H #define HITLS_PSK_H #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif /** * @ingroup hitls_psk * @brief PSK Maximum size of the identity message */ #define HITLS_IDENTITY_HINT_MAX_SIZE 128 #define HITLS_PSK_FIND_SESSION_CB_SUCCESS 1 #define HITLS_PSK_FIND_SESSION_CB_FAIL 0 #define HITLS_PSK_USE_SESSION_CB_SUCCESS 1 #define HITLS_PSK_USE_SESSION_CB_FAIL 0 /** * @ingroup hitls_psk * @brief Obtain the PSK prototype on the client. * * @param ctx [IN] Context. * @param hint [IN] Message. * @param identity [OUT] Identity information written back by the user. * @param maxIdentityLen [IN] Maximum length of the identity buffer. * @param psk [OUT] PSK information written back by the user. * @param maxPskLen [IN] Maximum length of the psk buffer. * @retval Return the PSK length. */ typedef uint32_t (*HITLS_PskClientCb)(HITLS_Ctx *ctx, const uint8_t *hint, uint8_t *identity, uint32_t maxIdentityLen, uint8_t *psk, uint32_t maxPskLen); /** * @ingroup hitls_psk * @brief Obtain the PSK prototype on the server. * * @param ctx [IN] Context. * @param identity [IN] Identity information. * @param psk [OUT] PSK information written back by the user. * @param maxPskLen [IN] Maximum length of the psk buffer. * @retval Return the PSK length. */ typedef uint32_t (*HITLS_PskServerCb)(HITLS_Ctx *ctx, const uint8_t *identity, uint8_t *psk, uint32_t maxPskLen); /** * @ingroup hitls_psk * @brief TLS1.3 server PSK negotiation callback * * @param ctx [IN] ctx context * @param identity [OUT] Identity information * @param identityLen [OUT] Identity information length * @param session [OUT] session * @retval HITLS_PSK_FIND_SESSION_CB_SUCCESS, if successful. * HITLS_PSK_FIND_SESSION_CB_FAIL, if failed */ typedef int32_t (*HITLS_PskFindSessionCb)(HITLS_Ctx *ctx, const uint8_t *identity, uint32_t identityLen, HITLS_Session **session); /** * @ingroup hitls_psk * @brief TLS1.3 client PSK negotiation callback * * @param ctx [IN] ctx context * @param hashAlgo [IN] Hash algorithm * @param id [IN] Identity information * @param idLen [IN] Identity information length * @param session [OUT] session * @retval HITLS_PSK_USE_SESSION_CB_SUCCESS, if successful. * HITLS_PSK_USE_SESSION_CB_FAIL, if failed */ typedef int32_t (*HITLS_PskUseSessionCb)(HITLS_Ctx *ctx, uint32_t hashAlgo, const uint8_t **id, uint32_t *idLen, HITLS_Session **session); /** * @ingroup hitls_psk * @brief Set the PSK prompt information for PSK negotiation. * * @param config [OUT] config Context * @param hint [IN] Hint * @param hintSize [IN] Hint length * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetPskIdentityHint(HITLS_Config *config, const uint8_t *hint, uint32_t hintSize); /** * @ingroup hitls_psk * @brief Set the PSK callback function on the client, which is used to obtain the identity * * and PSK during PSK negotiation. * @param config [OUT] config Context * @param callback [IN] Client callback * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetPskClientCallback(HITLS_Config *config, HITLS_PskClientCb callback); /** * @ingroup hitls_psk * @brief Set the PSK callback on the server, which is used to obtain the PSK during PSK negotiation. * * @param config [OUT] config Context * @param callback [IN] Client callback * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetPskServerCallback(HITLS_Config *config, HITLS_PskServerCb callback); /** * @ingroup hitls_psk * @brief Set the PSK callback function on the client, which is used to obtain the identity and PSK * * during PSK negotiation. * @param ctx [OUT] TLS connection handle * @param cb [IN] Client callback * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetPskClientCallback(HITLS_Ctx *ctx, HITLS_PskClientCb cb); /** * @ingroup hitls_psk * @brief Set the PSK callback on the server, which is used to obtain the PSK during PSK negotiation. * * @param ctx [OUT] TLS connection handle * @param cb [IN] Server callback * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetPskServerCallback(HITLS_Ctx *ctx, HITLS_PskServerCb cb); /** * @ingroup hitls_psk * @brief Set the PSK identity hint on the server, which is used to provide identity hints for the * * client during PSK negotiation. * @param ctx [OUT] TLS connection handle * @param identityHint [IN] psk identity prompt * @param identityHineLen [IN] psk Length of the identity message * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetPskIdentityHint(HITLS_Ctx *ctx, const uint8_t *identityHint, uint32_t identityHintLen); /** * @ingroup hitls_psk * @brief Set the server callback, which is used to restore the PSK session of TLS1.3, cb can be NULL. * * @param ctx [OUT] TLS connection handle * @param callback [IN] Callback function * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetPskFindSessionCallback(HITLS_Config *config, HITLS_PskFindSessionCb callback); /** * @ingroup hitls_psk * @brief Set the server callback, which is used to restore the PSK session of TLS1.3, cb can be NULL. * * @param ctx [OUT] TLS connection handle * @param callback [IN] Callback function * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetPskUseSessionCallback(HITLS_Config *config, HITLS_PskUseSessionCb callback); /** * @ingroup hitls_psk * @brief Set the server callback, which is used to restore the PSK session of TLS1.3, cb can be NULL. * * @param ctx [OUT] TLS connection handle * @param cb [IN] Callback function * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetPskFindSessionCallback(HITLS_Ctx *ctx, HITLS_PskFindSessionCb cb); /** * @ingroup hitls_psk * @brief Set the client callback, which is used to restore the PSK session of TLS1.3, cb can be NULL. * * @param ctx [OUT] TLS connection handle * @param cb [IN] Callback function * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetPskUseSessionCallback(HITLS_Ctx *ctx, HITLS_PskUseSessionCb cb); #ifdef __cplusplus } #endif #endif
2301_79861745/bench_create
include/tls/hitls_psk.h
C
unknown
7,714
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_security * @ingroup hitls * @brief TLS security features */ #ifndef HITLS_SECURITY_H #define HITLS_SECURITY_H #include <stdint.h> #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif /** * @ingroup hitls_security * * HiTLS default level of security. You can configure the default level by using the compilation macro. * If the compilation macro is not defined, the default level 1 is used. */ #ifndef HITLS_DEFAULT_SECURITY_LEVEL #define HITLS_DEFAULT_SECURITY_LEVEL 1 #endif /* security level */ #define HITLS_SECURITY_LEVEL_ZERO 0 #define HITLS_SECURITY_LEVEL_ONE 1 #define HITLS_SECURITY_LEVEL_TWO 2 #define HITLS_SECURITY_LEVEL_THREE 3 #define HITLS_SECURITY_LEVEL_FOUR 4 #define HITLS_SECURITY_LEVEL_FIVE 5 #define HITLS_SECURITY_LEVEL_MIN HITLS_SECURITY_LEVEL_ZERO #define HITLS_SECURITY_LEVEL_MAX HITLS_SECURITY_LEVEL_FIVE /* security strength */ #define HITLS_SECURITY_LEVEL_ONE_SECBITS 80 #define HITLS_SECURITY_LEVEL_TWO_SECBITS 112 #define HITLS_SECURITY_LEVEL_THREE_SECBITS 128 #define HITLS_SECURITY_LEVEL_FOUR_SECBITS 192 #define HITLS_SECURITY_LEVEL_FIVE_SECBITS 256 /* What the "other" parameter contains in security callback */ /* Mask for type */ # define HITLS_SECURITY_SECOP_OTHER_TYPE 0xffff0000 # define HITLS_SECURITY_SECOP_OTHER_NONE 0 # define HITLS_SECURITY_SECOP_OTHER_CIPHER (1 << 16) # define HITLS_SECURITY_SECOP_OTHER_CURVE (2 << 16) # define HITLS_SECURITY_SECOP_OTHER_DH (3 << 16) # define HITLS_SECURITY_SECOP_OTHER_PKEY (4 << 16) # define HITLS_SECURITY_SECOP_OTHER_SIGALG (5 << 16) # define HITLS_SECURITY_SECOP_OTHER_CERT (6 << 16) /* Indicated operation refers to peer key or certificate */ # define HITLS_SECURITY_SECOP_PEER 0x1000 /* Called to filter ciphers */ /* Ciphers client supports */ # define HITLS_SECURITY_SECOP_CIPHER_SUPPORTED (1 | HITLS_SECURITY_SECOP_OTHER_CIPHER) /* Cipher shared by client/server */ # define HITLS_SECURITY_SECOP_CIPHER_SHARED (2 | HITLS_SECURITY_SECOP_OTHER_CIPHER) /* Sanity check of cipher server selects */ # define HITLS_SECURITY_SECOP_CIPHER_CHECK (3 | HITLS_SECURITY_SECOP_OTHER_CIPHER) /* Curves supported by client */ # define HITLS_SECURITY_SECOP_CURVE_SUPPORTED (4 | HITLS_SECURITY_SECOP_OTHER_CURVE) /* Curves shared by client/server */ # define HITLS_SECURITY_SECOP_CURVE_SHARED (5 | HITLS_SECURITY_SECOP_OTHER_CURVE) /* Sanity check of curve server selects */ # define HITLS_SECURITY_SECOP_CURVE_CHECK (6 | HITLS_SECURITY_SECOP_OTHER_CURVE) /* Temporary DH key */ # define HITLS_SECURITY_SECOP_TMP_DH (7 | HITLS_SECURITY_SECOP_OTHER_PKEY) /* SSL/TLS version */ # define HITLS_SECURITY_SECOP_VERSION (9 | HITLS_SECURITY_SECOP_OTHER_NONE) /* Session tickets */ # define HITLS_SECURITY_SECOP_TICKET (10 | HITLS_SECURITY_SECOP_OTHER_NONE) /* Supported signature algorithms sent to peer */ # define HITLS_SECURITY_SECOP_SIGALG_SUPPORTED (11 | HITLS_SECURITY_SECOP_OTHER_SIGALG) /* Shared signature algorithm */ # define HITLS_SECURITY_SECOP_SIGALG_SHARED (12 | HITLS_SECURITY_SECOP_OTHER_SIGALG) /* Sanity check signature algorithm allowed */ # define HITLS_SECURITY_SECOP_SIGALG_CHECK (13 | HITLS_SECURITY_SECOP_OTHER_SIGALG) /* Used to get mask of supported public key signature algorithms */ # define HITLS_SECURITY_SECOP_SIGALG_MASK (14 | HITLS_SECURITY_SECOP_OTHER_SIGALG) /* Use to see if compression is allowed */ # define HITLS_SECURITY_SECOP_COMPRESSION (15 | HITLS_SECURITY_SECOP_OTHER_NONE) /* EE key in certificate */ # define HITLS_SECURITY_SECOP_EE_KEY (16 | HITLS_SECURITY_SECOP_OTHER_CERT) /* CA key in certificate */ # define HITLS_SECURITY_SECOP_CA_KEY (17 | HITLS_SECURITY_SECOP_OTHER_CERT) /* CA digest algorithm in certificate */ # define HITLS_SECURITY_SECOP_CA_MD (18 | HITLS_SECURITY_SECOP_OTHER_CERT) /* Peer EE key in certificate */ # define HITLS_SECURITY_SECOP_PEER_EE_KEY (HITLS_SECURITY_SECOP_EE_KEY | HITLS_SECURITY_SECOP_PEER) /* Peer CA key in certificate */ # define HITLS_SECURITY_SECOP_PEER_CA_KEY (HITLS_SECURITY_SECOP_CA_KEY | HITLS_SECURITY_SECOP_PEER) /* Peer CA digest algorithm in certificate */ # define HITLS_SECURITY_SECOP_PEER_CA_MD (HITLS_SECURITY_SECOP_CA_MD | HITLS_SECURITY_SECOP_PEER) /** * @ingroup hitls_security * @brief Secure Callback Function Prototype * * @param ctx [IN] context * @param config [IN] context * @param option [IN] indicates the options to be checked, such as the version, certificate, temporary key, * signature algorithm, support group, and session ticket... * @param bits [IN] Number of security bits, which is used to check the level of security of the key. * @param id [IN] Indicates the ID to be checked, such as the version ID, signature algorithm ID, * and support group ID. Input based on the options that need to be checked. * @param other [IN] Parameters to be checked, such as cipher suites, certificates, and signature algorithms. * @param exData [IN] Input the data as required. * @retval HITLS_SUCCESS, if successful. * For details about other error codes,see hitls_error.h */ typedef int32_t (*HITLS_SecurityCb)(const HITLS_Ctx *ctx, const HITLS_Config *config, int32_t option, int32_t bits, int32_t id, void *other, void *exData); /** * @ingroup hitls_security * @brief Configure the security level * * @param config [IN/OUT] Config context * @param securityLevel [IN] Security level * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h */ int32_t HITLS_CFG_SetSecurityLevel(HITLS_Config *config, int32_t securityLevel); /** * @ingroup hitls_security * @brief Obtain the configured security level. * * @param config [IN] Config context * @param securityLevel [OUT] Security Context * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h */ int32_t HITLS_CFG_GetSecurityLevel(const HITLS_Config *config, int32_t *securityLevel); /** * @ingroup hitls_security * @brief Configure the security callback function. * * @param config [IN/OUT] Config context * @param securityCb [IN] Security callback function * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetSecurityCb(HITLS_Config *config, HITLS_SecurityCb securityCb); /** * @ingroup hitls_security * @brief Obtain the configured security callback function * * @param config [IN] Config context * @retval Security callback function HITLS_SecurityCb. */ HITLS_SecurityCb HITLS_CFG_GetSecurityCb(const HITLS_Config *config); /** * @ingroup hitls_security * @brief Configuring the Security ExData * * @param config [IN/OUT] Config context * @param securityExData [IN] Security ExData * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h */ int32_t HITLS_CFG_SetSecurityExData(HITLS_Config *config, void *securityExData); /** * @ingroup hitls_security * @brief Obtain the configured Security ExData * * @param config [IN] Config context * @retval Security ExData */ void *HITLS_CFG_GetSecurityExData(const HITLS_Config *config); /** * @ingroup hitls_security * @brief Set the link security level * * @param ctx [IN/OUT] Ctx context * @param securityLevel [IN] Security level * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h */ int32_t HITLS_SetSecurityLevel(HITLS_Ctx *ctx, int32_t securityLevel); /** * @ingroup hitls_security * @brief Obtain the link security level * * @param ctx [IN] Ctx context * @param securityLevel [OUT] Security level * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h */ int32_t HITLS_GetSecurityLevel(const HITLS_Ctx *ctx, int32_t *securityLevel); /** * @ingroup hitls_security * @brief Callback function for setting link security * * @param ctx [IN/OUT] Ctx context * @param securityCb [IN] Security callback function * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h */ int32_t HITLS_SetSecurityCb(HITLS_Ctx *ctx, HITLS_SecurityCb securityCb); /** * @ingroup hitls_security * @brief Obtain the Security callback function of the link * * @param ctx [IN] Ctx context * @retval Security callback HITLS_SecurityCb. */ HITLS_SecurityCb HITLS_GetSecurityCb(const HITLS_Ctx *ctx); /** * @ingroup hitls_security * @brief Setting Security ExData for the Link * * @param ctx [IN/OUT] Ctx context * @param securityExData [IN] Security ExData * @retval HITLS_SUCCESS, if successful. * For details about other error codes, hitls_error.h */ int32_t HITLS_SetSecurityExData(HITLS_Ctx *ctx, void *securityExData); /** * @ingroup hitls_security * @brief Obtains the configured Security ExData. * * @param ctx [IN] Ctx context * @retval Security ExData */ void *HITLS_GetSecurityExData(const HITLS_Ctx *ctx); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end HITLS_SECURITY_H */
2301_79861745/bench_create
include/tls/hitls_security.h
C
unknown
9,960
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_session * @ingroup hitls * @brief TLS session */ #ifndef HITLS_SESSION_H #define HITLS_SESSION_H #include <stdint.h> #include <stddef.h> #include <stdbool.h> #include "hitls_type.h" #include "hitls_crypt_type.h" #include "bsl_uio.h" #ifdef __cplusplus extern "C" { #endif /** * @ingroup hitls_session * @brief Session id Maximum size of the CTX. */ #define HITLS_SESSION_ID_CTX_MAX_SIZE 32u /** * @ingroup hitls_session * @brief Maximum size of a session ID */ #define HITLS_SESSION_ID_MAX_SIZE 32u /** * @ingroup hitls_session * @brief Set whether to support the session ticket function. * * @param config [OUT] Config handle * @param support [IN] Whether to support the session ticket. The options are as follows: true: yes; false: no. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetSessionTicketSupport(HITLS_Config *config, bool support); /** * @ingroup hitls_session * @brief Query whether the session ticket function is supported. * * @param config [IN] Config handle * @param isSupport [OUT] Whether to support the session ticket. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_GetSessionTicketSupport(const HITLS_Config *config, uint8_t *isSupport); /** * @ingroup hitls_session * @brief Setting TLS1.3, number of new session tickets sent after a complete link is established. * * This interface should be called before handshake. The default number is 2. * If the number is greater than or equal to 1, only one ticket is sent after the session is resumed. * When this parameter is set to 0, the ticket is not sent for the complete handshake and session resumption. * * @param config [OUT] Config handle * @param ticketNums [IN] Number of new session tickets sent. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is empty. */ int32_t HITLS_CFG_SetTicketNums(HITLS_Config *config, uint32_t ticketNums); /** * @ingroup hitls_session * @brief Obtain TLS1.3, number of new session tickets sent after complete link establishment. * * @param config [IN] config handle * @retval Number of tickets. */ uint32_t HITLS_CFG_GetTicketNums(HITLS_Config *config); /** * @ingroup hitls_session * @brief Setting TLS1.3, number of new session tickets sent after complete link establishment. * * This interface should be called before handshake. The default number is 2. * If the number is greater than or equal to 1, only one ticket is sent after the session is resumed. * When this parameter is set to 0, tickets will not be sent for the complete handshake and session recovery. * * @param ctx [OUT] ctx context * @param ticketNums [IN] Number of sent new session tickets. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, ctx is null. */ int32_t HITLS_SetTicketNums(HITLS_Ctx *ctx, uint32_t ticketNums); /** * @ingroup hitls_session * @brief Obtain TLS1.3, Number of new session tickets sent after complete link establishment. * * @param ctx [IN] ctx context * @retval Number of tickets. */ uint32_t HITLS_GetTicketNums(HITLS_Ctx *ctx); /** * @ingroup hitls_session * @brief This callback is called when a new session is negotiated. Users can use sessions. * * @param ctx [IN] ctx context * @param session [IN] Session handle * @retval 1 Success. If a user removes a session, the user needs to release the session handle. * @retval 0 failed. The user does not use the session. */ typedef int32_t (*HITLS_NewSessionCb) (HITLS_Ctx *ctx, HITLS_Session *session); /** * @ingroup hitls_session * @brief Set a callback for negotiating a new session call. * * @param config [OUT] config handle * @param newSessionCb [IN] Callback. * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, config is null. */ int32_t HITLS_CFG_SetNewSessionCb(HITLS_Config *config, const HITLS_NewSessionCb newSessionCb); #define HITLS_TICKET_KEY_RET_NEED_ALERT (-1) // callback fails. A fatal error occurs. // You need to send an alert #define HITLS_TICKET_KEY_RET_FAIL 0 // callback returns a failure, but the error is not a fatal error, // for example, key_name matching fails. #define HITLS_TICKET_KEY_RET_SUCCESS 1 // If the callback is successful, // the key can be used for encryption and decryption #define HITLS_TICKET_KEY_RET_SUCCESS_RENEW 2 // If the callback is successful, the key can be used for encryption // and decryption. In the decryption scenario, // the ticket needs to be renewed /** * @ingroup hitls_session * @brief Obtain and verify ticket_key on the server. * * @attention keyName is fixed at 16 bytes, and iv is fixed at 16 bytes. * During encryption, the keyName and cipher need to be returned. * The encryption type, encryption algorithm, key, iv, and hmacKey need to be filled in. * During decryption, the HiTLS transfers the keyName. * The user needs to find the corresponding key based on the keyName and return the corresponding encryption type, * encryption algorithm, and key. (HiTLS uses the iv value sent by the client, * so the iv value does not need to be returned.) * * @param keyName [IN/OUT] name values corresponding to aes_key and hmac_key * @param keyNameSize [IN] length of keyName * @param cipher [IN/OUT] Encryption information * @param isEncrypt [IN] Indicates whether to encrypt data. true: encrypt data. false: decrypt data. * * @retval TICKET_KEY_RET_NEED_ALERT : indicates that the function fails to be called. A fatal error occurs. * An alert message needs to be sent. * TICKET_KEY_RET_FAIL : During encryption, the failure to obtain the key_name is not a fatal error. * In this case, the HiTLS sends an empty new session ticket message * to the client.During decryption, the key_name matching fails, * but it is not a fatal error. If the return value is the same, * the HiTLS performs a complete handshake process or uses the * session ID to restore the session. * TICKET_KEY_RET_SUCCESS : indicates that the encryption is successful. Decryption succeeds. * TICKET_KEY_RET_SUCCESS_RENEW : indicates that the encryption is successful. * The value is the same as the returned value TICKET_KEY_RET_SUCCESS. * If the decryption succeeds and the ticket needs to be renewed or changed, * the HiTLS calls the callback again to encrypt the ticket * when sending a new session ticket. */ typedef int32_t (*HITLS_TicketKeyCb)(uint8_t *keyName, uint32_t keyNameSize, HITLS_CipherParameters *cipher, uint8_t isEncrypt); /** * @ingroup hitls_session * @brief Set the ticket key callback, which is used only by the server, cb can be NULL. * * @param config [OUT] Config Context * @param callback [IN] Ticket key callback * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetTicketKeyCallback(HITLS_Config *config, HITLS_TicketKeyCb callback); /** * @ingroup hitls_session * @brief Obtain the default ticket key of the HiTLS. * * The key is used to encrypt and decrypt the ticket in the new session ticket when the HITLS_TicketKeyCb callback * function is not set. * * @attention The returned key value is as follows: 16-byte key name + 32-byte AES key + 32-byte HMAC key * * @param config [IN] Config Context. * @param key [OUT] Obtained ticket key. * @param keySize [IN] Size of the key array. * @param outSize [OUT] Size of the obtained ticket key. * * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetSessionTicketKey(const HITLS_Config *config, uint8_t *key, uint32_t keySize, uint32_t *outSize); /** * @ingroup hitls_session * @brief Set the default ticket key of the HiTLS. The key is used to encrypt and decrypt tickets in the new * session ticket when the HITLS_TicketKeyCb callback function is not set. * * @attention The returned key value is as follows: 16-byte key name + 32-byte AES key + 32-byte HMAC key * * @param config [OUT] Config Context. * @param key [IN] Ticket key to be set. * @param keySize [IN] Size of the ticket key. * * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetSessionTicketKey(HITLS_Config *config, const uint8_t *key, uint32_t keySize); /** * @ingroup hitls_session * @brief Set the user-specific session ID ctx, only on the server. * * @attention session id ctx is different from session id, session recovery can be performed only after * session id ctx matching. * @param config [OUT] Config context. * @param sessionIdCtx [IN] Session ID Context. * @param len [IN] Session id context length, a maximum of 32 bytes. * @retval HITLS_SUCCESS, if successful. * For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetSessionIdCtx(HITLS_Config *config, const uint8_t *sessionIdCtx, uint32_t len); /** * @ingroup hitls_session * @brief Set the session cache mode. * * @param config [OUT] Config context. * @param mode [IN] Cache mode, corresponding to the HITLS_SESS_CACHE_MODE enumerated value. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetSessionCacheMode(HITLS_Config *config, HITLS_SESS_CACHE_MODE mode); /** * @ingroup hitls_session * @brief Obtain the session cache mode. * * @param config [IN] config Context. * @param mode [OUT] Cache mode, corresponding to the HITLS_SESS_CACHE_MODE enumerated value. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetSessionCacheMode(HITLS_Config *config, HITLS_SESS_CACHE_MODE *mode); /** * @ingroup hitls_session * @brief Set the maximum number of sessions in the session cache. * * @param config [OUT] Config context. * @param size [IN] Maximum number of sessions in the cache. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetSessionCacheSize(HITLS_Config *config, uint32_t size); /** * @ingroup hitls_session * @brief Obtain the maximum number of sessions in the session cache. * * @param config [IN] Config context. * @param size [OUT] Maximum number of sessions in the cache. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetSessionCacheSize(HITLS_Config *config, uint32_t *size); /** * @ingroup hitls_session * @brief Set the session timeout interval. * * @param config [OUT] Config context. * @param timeout [IN] Session timeout interval, in seconds. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetSessionTimeout(HITLS_Config *config, uint64_t timeout); /** * @ingroup hitls_session * @brief Obtain the timeout interval of a session. * * @param config [IN] Config context. * @param timeout [OUT] Session timeout interval, in seconds. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetSessionTimeout(const HITLS_Config *config, uint64_t *timeout); /** * @ingroup hitls_session * @brief Whether the link is multiplexed with a session. * * @param ctx [IN] config Context. * @param isReused [OUT] Indicates whether to reuse a session. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_IsSessionReused(HITLS_Ctx *ctx, uint8_t *isReused); /** * @ingroup hitls_session * @brief Set the user-specific session ID ctx of the HiTLS link, only on the server. * * @attention session id ctx is different from sessio id, session recovery can be performed only after * session id ctx matching. * @param ctx [OUT] Config context. * @param sessionIdCtx [IN] Session ID Context. * @param len [IN] Session ID context length, which cannot exceed 32 bytes. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_SetSessionIdCtx(HITLS_Ctx *ctx, const uint8_t *sessionIdCtx, uint32_t len); /** * @ingroup hitls_session * @brief Obtain the default ticket key of the HiTLS. * * The key is used to encrypt and decrypt the ticket in the new session ticket * when the HITLS_TicketKeyCb callback function is not set. * * @attention The returned key value is as follows: 16-byte key name + 32-byte AES key + 32-byte HMAC key * * @param ctx [OUT] TLS connection handle * @param key [OUT] Obtained ticket key * @param keySize [IN] Size of the key array * @param outSize [OUT] Size of the obtained ticket key. * * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_GetSessionTicketKey(const HITLS_Ctx *ctx, uint8_t *key, uint32_t keySize, uint32_t *outSize); /** * @ingroup hitls_session * @brief Set the default ticket key of the HiTLS. The key is used to encrypt and decrypt the ticket * in the new session ticket when the HITLS_TicketKeyCb callback function is not set. * * @attention The returned key value is as follows: 16-byte key name + 32-byte AES key + 32-byte HMAC key * * @param ctx [OUT] TLS connection handle. * @param key [IN] Ticket key to be set. * @param keySize [IN] Size of the ticket key. * * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetSessionTicketKey(HITLS_Ctx *ctx, const uint8_t *key, uint32_t keySize); /** * @ingroup hitls_session * @brief Set the handle for the session information about the HiTLS link. * * @attention Used only by the client. * @param ctx [OUT] TLS connection handle * @param session [IN] Session information handle. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SetSession(HITLS_Ctx *ctx, HITLS_Session *session); /** * @ingroup hitls_session * @brief Obtain the handle of the session information and directly obtain the pointer. * * @attention Directly obtain the pointer. * Ensure that the invoking is correct and avoid the pointer being a wild pointer. * @param ctx [IN] TLS connection handle * @retval Session information handle */ HITLS_Session *HITLS_GetSession(const HITLS_Ctx *ctx); /** * @ingroup hitls_session * @brief Obtain the handle of the copied session information. * * @attention The number of times that the call is called increases by 1. * The call is released by calling HITLS_SESS_Free. * @param ctx [IN] TLS connection handle * @retval Session information handle */ HITLS_Session *HITLS_GetDupSession(HITLS_Ctx *ctx); /** * @ingroup hitls_session * @brief Obtain the sign type of the peer * * @param ctx [IN] TLS connection handle * @param sigType [OUT] sign type. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_GetPeerSignatureType(const HITLS_Ctx *ctx, HITLS_SignAlgo *sigType); /** * @ingroup hitls_session * @brief Apply for a new session. * * @param void * @retval Session handle. */ HITLS_Session *HITLS_SESS_New(void); /** * @ingroup hitls_session * @brief Duplicate a session, the number of reference times increases by 1. * * @param sess * @retval Session handle. */ HITLS_Session *HITLS_SESS_Dup(HITLS_Session *sess); /** * @ingroup hitls_session * @brief Release the session information handle. * * @param sess [IN] Session information handle * @retval void */ void HITLS_SESS_Free(HITLS_Session *sess); /** * @ingroup hitls_session * @brief Set the master key of a session. * * @param sess [OUT] Session information handle. * @param masterKey [IN] Master key. * @param masterKeySize [IN] Size of the master key. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_SetMasterKey(HITLS_Session *sess, const uint8_t *masterKey, uint32_t masterKeySize); /** * @ingroup hitls_session * @brief Obtain the master key length of a session. * * @param sess [IN] Session information handle * @retval Size of the master key */ uint32_t HITLS_SESS_GetMasterKeyLen(const HITLS_Session *sess); /** * @ingroup hitls_session * @brief Obtain the master key of a session. * * @param sess [IN] Session information handle. * @param masterKey [OUT] Master key. * @param masterKeySize [OUT] Size of the master key. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_GetMasterKey(const HITLS_Session *sess, uint8_t *masterKey, uint32_t *masterKeySize); /** * @ingroup hitls_session * @brief Obtain the session protocol version. * * @param sess [IN] Session information handle. * @param version [OUT] Protocol version. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_GetProtocolVersion(const HITLS_Session *sess, uint16_t *version); /** * @ingroup hitls_session * @brief Set the session protocol version. * * @param sess [OUT] Session information handle * @param version [IN] Protocol version * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_SetProtocolVersion(HITLS_Session *sess, uint16_t version); /** * @ingroup hitls_session * @brief Set the session password suite. * * @param sess [OUT] Session information handle. * @param cipherSuite [IN] Password suite. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_SetCipherSuite(HITLS_Session *sess, uint16_t cipherSuite); /** * @ingroup hitls_session * @brief Obtain the session password suite. * * @param sess [IN] Session information handle. * @param cipherSuite [OUT] Cipher suite. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_GetCipherSuite(const HITLS_Session *sess, uint16_t *cipherSuite); /** * @ingroup hitls_session * @brief Set the session ID ctx. * * @param sess [OUT] Session information handle. * @param sessionIdCtx [IN] Session ID Context. * @param sessionIdCtxSize [IN] Session ID Context length. The maximum length is 32 bytes. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_SetSessionIdCtx(HITLS_Session *sess, uint8_t *sessionIdCtx, uint32_t sessionIdCtxSize); /** * @ingroup hitls_session * @brief Obtain the session ID ctx. * * @param sess [IN] Session information handle. * @param sessionIdCtx [OUT] Session ID Context. * @param sessionIdCtxSize [OUT] Session id Context length. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_GetSessionIdCtx(const HITLS_Session *sess, uint8_t *sessionIdCtx, uint32_t *sessionIdCtxSize); /** * @ingroup hitls_session * @brief Set the session ID. * * @param sess [OUT] Session information handle. * @param sessionId [IN] Session id. * @param sessionIdSize [IN] The session ID contains a maximum of 32 bytes. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_SetSessionId(HITLS_Session *sess, uint8_t *sessionId, uint32_t sessionIdSize); /** * @ingroup hitls_session * @brief Obtain the session ID. * * @param sess [IN] Session information handle * @param sessionId [OUT] Session id * @param sessionIdSize [OUT] Session ID length * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_GetSessionId(const HITLS_Session *sess, uint8_t *sessionId, uint32_t *sessionIdSize); /** * @ingroup hitls_session * @brief Set whether to contain the master key extension. * * @param sess [OUT] Session information handle. * @param haveExtMasterSecret [IN] Whether the master key extension is include. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_SetHaveExtMasterSecret(HITLS_Session *sess, uint8_t haveExtMasterSecret); /** * @ingroup hitls_session * @brief Obtain the master key extension. * * @param sess [IN] Session information handle. * @param haveExtMasterSecret [OUT] Whether the master key extension is contained. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_GetHaveExtMasterSecret(HITLS_Session *sess, uint8_t *haveExtMasterSecret); /** * @ingroup hitls_session * @brief Set the timeout interval, in seconds. * * @param sess [OUT] Session information handle * @param timeout [IN] Timeout interval, in seconds. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_SetTimeout(HITLS_Session *sess, uint64_t timeout); /** * @ingroup hitls_session * @brief Check whether the session can be recovered. Only simple check is performed, but the validity period * is not checked. * * @param sess [IN] Session information handle. * @retval Indicates whether the recovery can be performed. */ bool HITLS_SESS_IsResumable(const HITLS_Session *sess); /** * @ingroup hitls_session * @brief Check whether the session has a ticket. * * @param sess [IN] Session information handle * @retval Indicates whether a ticket exists. */ bool HITLS_SESS_HasTicket(const HITLS_Session *sess); /** * @ingroup hitls_session * @brief Set the user data of the session. * * @param sess [OUT] Session information handle. * @param userData [IN] User data. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ void *HITLS_SESS_GetUserData(const HITLS_Session *sess); /** * @ingroup hitls_session * @brief Set the user data of the session. * * @param sess [OUT] Session information handle. * @param userData [IN] User data. * @retval HITLS_SUCCESS, if successful. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_SESS_SetUserData(HITLS_Session *sess, void *userData); #ifdef __cplusplus } #endif #endif /* HITLS_SESSION_H */
2301_79861745/bench_create
include/tls/hitls_session.h
C
unknown
24,060
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_sni * @ingroup hitls * @brief TLS SNI correlation type */ #ifndef HITLS_SNI_H #define HITLS_SNI_H #include <stdint.h> #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif /* Currently, the SNI supports only the host name type. */ /** * @ingroup hitls_sni * @brief Currently, the SNI supports only the host name type. */ typedef enum { HITLS_SNI_HOSTNAME_TYPE, HITLS_SNI_BUTT = 255 /* Maximum enumerated value */ } SNI_Type; #define HITLS_ACCEPT_SNI_ERR_OK 0 /* Accepts the request and continues handshake. */ #define HITLS_ACCEPT_SNI_ERR_ALERT_FATAL 2 /* Do not accept the request and aborts the handshake. */ #define HITLS_ACCEPT_SNI_ERR_NOACK 3 /* Do not accept the request but continues the handshake. */ /** * @ingroup hitls_sni * @brief Obtain the value of server_name before, during, or after the handshake on the client or server. * * @param ctx [IN] TLS connection handle * @param type [IN] serverName type * @retval The value of server_name, if successful. * NULL, if failure. */ const char *HITLS_GetServerName(const HITLS_Ctx *ctx, const int type); /** * @ingroup hitls_sni * @brief Obtain the server_name type before, during, or after the handshake on the client or server. * * @param ctx [IN] TLS connection handle * @retval HITLS_SNI_HOSTNAME_TYPE, if successful. * -1: if failure. */ int32_t HITLS_GetServernameType(const HITLS_Ctx *ctx); /** * @ingroup hitls_sni * @brief Set server_name. * * @param config [OUT] config Context * @param serverName [IN] serverName * @param serverNameStrlen [IN] serverName length * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetServerName(HITLS_Config *config, uint8_t *serverName, uint32_t serverNameStrlen); /** * @ingroup hitls_sni * @brief Obtain the value of server_name configured on the client. * * @param config [IN] config Context * @param serverName [OUT] serverName * @param serverNameStrlen [OUT] serverName length * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetServerName(HITLS_Config *config, uint8_t **serverName, uint32_t *serverNameStrlen); /** * @ingroup hitls_sni * @brief Set the extension prototype for the server to process Client Hello server_name. * * @param ctx [IN] ctx context. * @param alert [IN] Warning information. * @param arg [IN] The server supports the input parameters related to server_name. * @retval The user return value contains: * HITLS_ACCEPT_SNI_ERR_OK 0 (received, server_name null extension) * HITLS_ACCEPT_SNI_ERR_ALERT_FATAL 2 (Do not accept, abort handshake) * HITLS_ACCEPT_SNI_ERR_NOACK 3 (not accepted, but continue handshake, not sending server_name null extension) */ typedef int32_t (*HITLS_SniDealCb)(HITLS_Ctx *ctx, int *alert, void *arg); /** * @ingroup hitls_sni * @brief Set the server_name callback function on the server, which is used for SNI negotiation, cb can be NULL. * * @param config [OUT] Config Context * @param callback [IN] Server callback implemented by the user * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetServerNameCb(HITLS_Config *config, HITLS_SniDealCb callback); /** * @ingroup hitls_sni * @brief Set the server_name parameters required during SNI negotiation on the server. * * @param config [OUT] Config context * @param arg [IN] Set parameters related to server_name. * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetServerNameArg(HITLS_Config *config, void *arg); /** * @ingroup hitls_sni * @brief Obtain the server_name callback settings on the server. * * @param config [IN] config Context * @param callback [IN] [OUT] Server callback implemented by the user * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetServerNameCb(HITLS_Config *config, HITLS_SniDealCb *callback); /** * @ingroup hitls_sni * @brief Obtain the server_name required during SNI negotiation on the server, related Parameter arg. * * @param config [IN] Config context * @param arg [IN] [OUT] Set parameters related to server_name.arg * @retval HITLS_SUCCESS, if successful. * For details about other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetServerNameArg(HITLS_Config *config, void **arg); #ifdef __cplusplus } #endif #endif
2301_79861745/bench_create
include/tls/hitls_sni.h
C
unknown
5,326
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_type * @ingroup hitls * @brief TLS type definition, provides the TLS type required by the user */ #ifndef HITLS_TYPE_H #define HITLS_TYPE_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /** * @ingroup hitls_type * @brief HITLS context */ typedef struct TlsCtx HITLS_Ctx; /** * @ingroup hitls_type * @brief config context */ typedef struct TlsConfig HITLS_Config; /** * @ingroup hitls_type * @brief cipherSuite information */ typedef struct TlsCipherSuiteInfo HITLS_Cipher; typedef struct TlsSessCtx HITLS_Session; /** * @ingroup hitls_type * @brief DTLS SCTP authkey length, which is specified in the protocol and can be used to determine the length * when the auth key is set. */ #define DTLS_SCTP_SHARED_AUTHKEY_LEN 64 /** * @ingroup hitls_type * @brief TLS1.3 key exchange mode: Only PSKs are used for key negotiation. */ #define TLS13_KE_MODE_PSK_ONLY 1u /** * @ingroup hitls_type * @brief TLS1.3 key exchange mode: Both PSK and (EC)DHE are used for key negotiation. */ #define TLS13_KE_MODE_PSK_WITH_DHE 2u /** * @ingroup hitls_type * @brief TLS1.3 certificate authentication: The certificate authentication is used and * the (EC)DHE negotiation key is required. */ #define TLS13_CERT_AUTH_WITH_DHE 4u /* Sets the number of digits in the version number. */ #define SSLV2_VERSION_BIT 0x00000001U #define SSLV3_VERSION_BIT 0x00000002U #define TLS10_VERSION_BIT 0x00000004U #define TLS11_VERSION_BIT 0x00000008U #define TLS12_VERSION_BIT 0x00000010U #define TLS13_VERSION_BIT 0x00000020U #define TLCP11_VERSION_BIT 0x00000080U #define DTLS10_VERSION_BIT 0x80000000U #define DTLS12_VERSION_BIT 0x40000000U #define DTLCP11_VERSION_BIT 0x00000100U #define TLS_VERSION_MASK (TLS12_VERSION_BIT | TLS13_VERSION_BIT) /* Currently, only DTLS12 is supported. DTLS10 is not supported */ #define DTLS_VERSION_MASK DTLS12_VERSION_BIT #define STREAM_VERSION_BITS \ (SSLV2_VERSION_BIT | SSLV3_VERSION_BIT | TLS10_VERSION_BIT | TLS11_VERSION_BIT | TLS12_VERSION_BIT | \ TLS13_VERSION_BIT | TLCP11_VERSION_BIT) #define DATAGRAM_VERSION_BITS (DTLS10_VERSION_BIT | DTLS12_VERSION_BIT | DTLCP11_VERSION_BIT) #define TLCP_VERSION_BITS (TLCP11_VERSION_BIT | DTLCP11_VERSION_BIT) #define ALL_VERSION (STREAM_VERSION_BITS | DATAGRAM_VERSION_BITS) /** * @ingroup hitls_type * @brief HITLS_SESS_CACHE_MODE: mode for storing hitls sessions. */ typedef enum { HITLS_SESS_CACHE_NO, HITLS_SESS_CACHE_CLIENT, HITLS_SESS_CACHE_SERVER, HITLS_SESS_CACHE_BOTH, } HITLS_SESS_CACHE_MODE; /** * @ingroup hitls_type * @brief key update message type */ typedef enum { HITLS_UPDATE_NOT_REQUESTED = 0, HITLS_UPDATE_REQUESTED = 1, HITLS_KEY_UPDATE_REQ_END = 255 } HITLS_KeyUpdateRequest; #define HITLS_MODE_ENABLE_PARTIAL_WRITE 0x00000001U #define HITLS_MODE_ACCEPT_MOVING_WRITE_BUFFER 0x00000002U #define HITLS_MODE_AUTO_RETRY 0x00000004U #define HITLS_MODE_NO_AUTO_CHAIN 0x00000008U #define HITLS_MODE_RELEASE_BUFFERS 0x00000010U #define HITLS_MODE_SEND_CLIENTHELLO_TIME 0x00000020U #define HITLS_MODE_SEND_SERVERHELLO_TIME 0x00000040U #define HITLS_MODE_SEND_FALLBACK_SCSV 0x00000080U #define HITLS_MODE_ASYNC 0x00000100U #define HITLS_MODE_DTLS_SCTP_LABEL_LENGTH_BUG 0x00000400U /* close_notify message has been sent to the peer end, turn off the alarm, and the connection is considered closed. */ # define HITLS_SENT_SHUTDOWN 1u # define HITLS_RECEIVED_SHUTDOWN 2u /* Received peer shutdown alert, normal close_notify or fatal error */ // Used to mark the current internal status #define HITLS_NOTHING 1u #define HITLS_WRITING 2u #define HITLS_READING 3u #define HITLS_ASYNC_PAUSED 4u #define HITLS_ASYNC_NO_JOBS 5u #define HITLS_CLIENT_HELLO_CB 6u #define HITLS_X509_LOOKUP 7u #define HITLS_CC_READ 0x001u /* Read state */ #define HITLS_CC_WRITE 0x002u /* Write status */ #ifdef __cplusplus } #endif #endif
2301_79861745/bench_create
include/tls/hitls_type.h
C
unknown
4,714
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_CMS_LOCAL_H #define HITLS_CMS_LOCAL_H #include "hitls_build.h" #ifdef HITLS_PKI_PKCS12 #include "bsl_types.h" #include "bsl_obj.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef HITLS_PKI_PKCS12_PARSE // parse PKCS7-Data int32_t HITLS_CMS_ParseAsn1Data(BSL_Buffer *encode, BSL_Buffer *dataValue); #endif // parse PKCS7-DigestInfo:only support hash. int32_t HITLS_CMS_ParseDigestInfo(BSL_Buffer *encode, BslCid *cid, BSL_Buffer *digest); #ifdef HITLS_PKI_PKCS12_GEN // encode PKCS7-DigestInfo:only support hash. int32_t HITLS_CMS_EncodeDigestInfoBuff(BslCid cid, BSL_Buffer *in, BSL_Buffer *encode); #endif #ifdef __cplusplus } #endif #endif // HITLS_PKI_PKCS12 #endif // HITLS_CMS_LOCAL_H
2301_79861745/bench_create
pki/cms/include/hitls_cms_local.h
C
unknown
1,276
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_PKCS12 #include "securec.h" #include "bsl_err_internal.h" #include "bsl_asn1_internal.h" #include "bsl_obj_internal.h" #include "crypt_eal_codecs.h" #include "crypt_eal_md.h" #include "crypt_encode_decode_key.h" #include "hitls_pki_errno.h" #ifdef HITLS_PKI_PKCS12_PARSE /** * Data Content Type * Data ::= OCTET STRING * * https://datatracker.ietf.org/doc/html/rfc5652#section-4 */ int32_t HITLS_CMS_ParseAsn1Data(BSL_Buffer *encode, BSL_Buffer *dataValue) { if (encode == NULL || dataValue == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CMS_ERR_NULL_POINTER); return HITLS_CMS_ERR_NULL_POINTER; } uint8_t *temp = encode->data; uint32_t tempLen = encode->dataLen; uint32_t decodeLen = 0; uint8_t *data = NULL; int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_OCTETSTRING, &temp, &tempLen, &decodeLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (decodeLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_CMS_ERR_INVALID_DATA); return HITLS_CMS_ERR_INVALID_DATA; } data = BSL_SAL_Dump(temp, decodeLen); if (data == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } dataValue->data = data; dataValue->dataLen = decodeLen; return HITLS_PKI_SUCCESS; } #endif /** * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithmIdentifier, * digest Digest * } * * https://datatracker.ietf.org/doc/html/rfc2315#section-9.4 */ static BSL_ASN1_TemplateItem g_digestInfoTempl[] = { /* digestAlgorithm */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_OBJECT_ID, 0, 1}, {BSL_ASN1_TAG_NULL, 0, 1}, /* digest */ {BSL_ASN1_TAG_OCTETSTRING, 0, 0}, }; typedef enum { HITLS_P7_DIGESTINFO_OID_IDX, HITLS_P7_DIGESTINFO_ALGPARAM_IDX, HITLS_P7_DIGESTINFO_OCTSTRING_IDX, HITLS_P7_DIGESTINFO_MAX_IDX, } HITLS_P7_DIGESTINFO_IDX; int32_t HITLS_CMS_ParseDigestInfo(BSL_Buffer *encode, BslCid *cid, BSL_Buffer *digest) { if (encode == NULL || encode->data == NULL || digest == NULL || cid == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CMS_ERR_NULL_POINTER); return HITLS_CMS_ERR_NULL_POINTER; } if (encode->dataLen == 0 || digest->data != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } uint8_t *temp = encode->data; uint32_t tempLen = encode->dataLen; BSL_ASN1_Buffer asn1[HITLS_P7_DIGESTINFO_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_digestInfoTempl, sizeof(g_digestInfoTempl) / sizeof(g_digestInfoTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asn1, HITLS_P7_DIGESTINFO_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString oidStr = {asn1[HITLS_P7_DIGESTINFO_OID_IDX].len, (char *)asn1[HITLS_P7_DIGESTINFO_OID_IDX].buff, 0}; BslCid parseCid = BSL_OBJ_GetCID(&oidStr); if (parseCid == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_CMS_ERR_PARSE_TYPE); return HITLS_CMS_ERR_PARSE_TYPE; } if (asn1[HITLS_P7_DIGESTINFO_OCTSTRING_IDX].len == 0) { BSL_ERR_PUSH_ERROR(HITLS_CMS_ERR_INVALID_DATA); return HITLS_CMS_ERR_INVALID_DATA; } uint8_t *output = BSL_SAL_Dump(asn1[HITLS_P7_DIGESTINFO_OCTSTRING_IDX].buff, asn1[HITLS_P7_DIGESTINFO_OCTSTRING_IDX].len); if (output == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } digest->data = output; digest->dataLen = asn1[HITLS_P7_DIGESTINFO_OCTSTRING_IDX].len; *cid = parseCid; return HITLS_PKI_SUCCESS; } #ifdef HITLS_PKI_PKCS12_GEN int32_t HITLS_CMS_EncodeDigestInfoBuff(BslCid cid, BSL_Buffer *in, BSL_Buffer *encode) { if (in == NULL || encode == NULL || encode->data != NULL || (in->data == NULL && in->dataLen != 0)) { BSL_ERR_PUSH_ERROR(HITLS_CMS_ERR_NULL_POINTER); return HITLS_CMS_ERR_NULL_POINTER; } BslOidString *oidstr = BSL_OBJ_GetOID(cid); if (oidstr == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CMS_ERR_INVALID_ALGO); return HITLS_CMS_ERR_INVALID_ALGO; } BSL_ASN1_Buffer asn1[HITLS_P7_DIGESTINFO_MAX_IDX] = { {BSL_ASN1_TAG_OBJECT_ID, oidstr->octetLen, (uint8_t *)oidstr->octs}, {BSL_ASN1_TAG_NULL, 0, NULL}, {BSL_ASN1_TAG_OCTETSTRING, in->dataLen, in->data}, }; BSL_Buffer tmp = {0}; BSL_ASN1_Template templ = {g_digestInfoTempl, sizeof(g_digestInfoTempl) / sizeof(g_digestInfoTempl[0])}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, asn1, HITLS_P7_DIGESTINFO_MAX_IDX, &tmp.data, &tmp.dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } encode->data = tmp.data; encode->dataLen = tmp.dataLen; return HITLS_PKI_SUCCESS; } #endif #endif // HITLS_PKI_PKCS12
2301_79861745/bench_create
pki/cms/src/hitls_cms_common.c
C
unknown
5,492
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_PKCS12_LOCAL_H #define HITLS_PKCS12_LOCAL_H #include "hitls_build.h" #ifdef HITLS_PKI_PKCS12 #include <stdint.h> #include "bsl_asn1_internal.h" #include "bsl_obj.h" #include "sal_atomic.h" #include "hitls_x509_local.h" #include "hitls_pki_cert.h" #include "crypt_eal_codecs.h" #ifdef __cplusplus extern "C" { #endif typedef struct { BslCid contentType; BSL_Buffer *contentValue; } HITLS_PKCS12_ContentInfo; typedef struct { BslCid alg; BSL_Buffer *mac; BSL_Buffer *macSalt; uint32_t iteration; } HITLS_PKCS12_MacData; /* This struct is provided for users to create related bags and add them to the p12-ctx. */ typedef struct _HITLS_PKCS12_Bag { uint32_t type; uint32_t id; union { CRYPT_EAL_PkeyCtx *key; HITLS_X509_Cert *cert; BSL_Buffer secret; } value; HITLS_X509_Attrs *attributes; // localKeyId, friendlyName, ect. Item is HITLS_PKCS12_SafeBagAttr. BSL_SAL_RefCount references; } HITLS_PKCS12_Bag; /* * The Top-Level p12-ctx, which can store certificates and pkey required by a .p12 file. * Note that the entity-cert and entity-pkey are unique. */ typedef struct _HITLS_PKCS12 { uint32_t version; HITLS_PKCS12_Bag *key; /* for store p8ShroudedKeyBag, only one p8ShroudedKeyBag is supported. */ HITLS_PKCS12_Bag *entityCert; /* for store entity-cert bag. If we find a cert that matches the p8ShroudedKeyBag, it will be placed here. */ BSL_ASN1_List *secretBags; /* for store secret-bags, we support multiple secret-bags. */ BSL_ASN1_List *certList; /* for store cert-bags, we support multiple cert-bags. */ BSL_ASN1_List *keyList; /* for store key-bags, we support multiple key-bags. */ HITLS_PKCS12_MacData *macData; HITLS_PKI_LibCtx *libCtx; const char *attrName; } HITLS_PKCS12; /* A common bag, could store a crl-bag, or a cert-bag, or a secret-bag... */ typedef struct { BslCid bagType; BSL_Buffer bagValue; // encode data } HITLS_PKCS12_CommonSafeBag; /* SafeBag Attributes. */ typedef struct { BslCid attrId; BSL_Buffer attrValue; } HITLS_PKCS12_SafeBagAttr; /* A safeBag defined in RFC 7292, which storing intermediate data in our decoding process. */ typedef struct { BslCid bagId; BSL_Buffer *bag; // encode data HITLS_X509_Attrs *attributes; // Currently, only support localKeyId, friendlyName. Item is HITLS_PKCS12_SafeBagAttr. } HITLS_PKCS12_SafeBag; void HITLS_PKCS12_SafeBagFree(HITLS_PKCS12_SafeBag *safeBag); HITLS_PKCS12_MacData *HITLS_PKCS12_MacDataNew(void); void HITLS_PKCS12_MacDataFree(HITLS_PKCS12_MacData *macData); void HITLS_PKCS12_AttributesFree(void *attribute); typedef enum { HITLS_PKCS12_KDF_ENCKEY_ID = 1, HITLS_PKCS12_KDF_ENCIV_ID = 2, HITLS_PKCS12_KDF_MACKEY_ID = 3, } HITLS_PKCS12_KDF_IDX; /* * A method of obtaining the mac key in key-integrity protection mode. * The method implementation follows standards RFC 7292 */ int32_t HITLS_PKCS12_KDF(HITLS_PKCS12 *p12, const uint8_t *pwd, uint32_t pwdLen, HITLS_PKCS12_KDF_IDX type, BSL_Buffer *output); /* * To cal mac data in key-integrity protection mode, we use the way of Hmac + PKCS12_KDF. */ int32_t HITLS_PKCS12_CalMac(HITLS_PKCS12 *p12, BSL_Buffer *pwd, BSL_Buffer *initData, BSL_Buffer *output); #ifdef HITLS_PKI_PKCS12_PARSE /* * Parse the outermost layer of contentInfo, provide two functions * 1. AuthSafe -> pkcs7 package format * 2. contentInfo_i -> safeContents */ int32_t HITLS_PKCS12_ParseContentInfo(HITLS_PKI_LibCtx *libCtx, const char *attrName, BSL_Buffer *encode, const uint8_t *password, uint32_t passLen, BSL_Buffer *data); /* * Parse the 'sequences of' of p12, provide two functions * 1. contentInfo -> contentInfo_i * 2. safeContent -> safeBag_i * Both of the above parsing only resolves to BER encoding format, and requiring further conversion. */ int32_t HITLS_PKCS12_ParseAsn1AddList(BSL_Buffer *encode, BSL_ASN1_List *list, uint32_t parseType); /* * Parse each safeBag of list, and convert decode data to the cert or key. */ int32_t HITLS_PKCS12_ParseSafeBagList(BSL_ASN1_List *bagList, const uint8_t *password, uint32_t passLen, HITLS_PKCS12 *p12); /* * Parse attributes of a safeBag, and convert decode data to the real data. */ int32_t HITLS_PKCS12_ParseSafeBagAttr(BSL_ASN1_Buffer *attrBuff, HITLS_X509_Attrs *attrList); /* * Parse AuthSafeData of a p12, and convert decode data to the real data. */ int32_t HITLS_PKCS12_ParseAuthSafeData(BSL_Buffer *encode, const uint8_t *password, uint32_t passLen, HITLS_PKCS12 *p12); /* * Parse MacData of a p12, and convert decode data to the real data. */ int32_t HITLS_PKCS12_ParseMacData(BSL_Buffer *encode, HITLS_PKCS12_MacData *macData); #endif #ifdef HITLS_PKI_PKCS12_GEN /* * Encode MacData of a p12. */ int32_t HITLS_PKCS12_EncodeMacData(HITLS_PKCS12 *p12, BSL_Buffer *initData, const HITLS_PKCS12_MacParam *macParam, BSL_Buffer *encode); /* * Encode contentInfo. */ int32_t HITLS_PKCS12_EncodeContentInfo(HITLS_PKI_LibCtx *libCtx, const char *attrName, BSL_Buffer *input, uint32_t encodeType, const CRYPT_EncodeParam *encryptParam, BSL_Buffer *encode); /* * Encode list, including contentInfo-list, safeContent-list. */ int32_t HITLS_PKCS12_EncodeAsn1List(HITLS_PKCS12 *p12, BSL_ASN1_List *list, uint32_t encodeType, const CRYPT_EncodeParam *encryptParam, BSL_Buffer *encode); #endif /** * @ingroup pkcs12 * @brief Add attributes to a bag. */ int32_t HITLS_PKCS12_BagAddAttr(HITLS_PKCS12_Bag *bag, uint32_t type, const BSL_Buffer *attrValue); /** * @ingroup pkcs12 * @brief Increase the reference count of a bag. */ int32_t HITLS_PKCS12_BagRefUp(HITLS_PKCS12_Bag *bag); #ifdef __cplusplus } #endif #endif // HITLS_PKI_PKCS12 #endif // HITLS_CRL_LOCAL_H
2301_79861745/bench_create
pki/pkcs12/include/hitls_pkcs12_local.h
C
unknown
6,386
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_PKCS12 #include "bsl_sal.h" #include "securec.h" #include "hitls_pki_errno.h" #include "hitls_x509_local.h" #include "hitls_cms_local.h" #include "bsl_obj_internal.h" #include "bsl_err_internal.h" #include "hitls_pki_pkcs12.h" #include "hitls_pkcs12_local.h" int32_t BagGetAttr(HITLS_PKCS12_Bag *bag, uint32_t valType, BSL_Buffer *attrValue) { if (bag == NULL || attrValue == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (valType != BSL_CID_LOCALKEYID && valType != BSL_CID_FRIENDLYNAME) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES); return HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES; } if (bag->attributes == NULL || bag->attributes->list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NO_SAFEBAG_ATTRIBUTES); return HITLS_PKCS12_ERR_NO_SAFEBAG_ATTRIBUTES; } BSL_ASN1_List *list = bag->attributes->list; HITLS_PKCS12_SafeBagAttr *node = BSL_LIST_GET_FIRST(list); while (node != NULL) { if (node->attrId == valType) { if (attrValue->data == NULL || attrValue->dataLen < node->attrValue.dataLen) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_BUFFLEN_NOT_ENOUGH); return HITLS_PKCS12_ERR_BUFFLEN_NOT_ENOUGH; } (void)memcpy_s(attrValue->data, attrValue->dataLen, node->attrValue.data, node->attrValue.dataLen); attrValue->dataLen = node->attrValue.dataLen; return HITLS_PKI_SUCCESS; } node = BSL_LIST_GET_NEXT(list); } BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NO_SAFEBAG_ATTRIBUTES); return HITLS_PKCS12_ERR_NO_SAFEBAG_ATTRIBUTES; } static int32_t GetKeyBagValue(HITLS_PKCS12_Bag *bag, void **value) { if (value == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (*value != NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } if (bag->value.key == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_BAG_NO_KEY); return HITLS_PKCS12_ERR_BAG_NO_KEY; } int32_t ret = CRYPT_EAL_PkeyUpRef(bag->value.key); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *((CRYPT_EAL_PkeyCtx **)value) = bag->value.key; return HITLS_PKI_SUCCESS; } static int32_t GetCertBagValue(HITLS_PKCS12_Bag *bag, void **value) { if (value == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (*value != NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } if (bag->value.cert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_BAG_NO_CERT); return HITLS_PKCS12_ERR_BAG_NO_CERT; } int32_t ref; if (bag->type != BSL_CID_X509CERTIFICATE) { // now only support x509 certificate. BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } int32_t ret = HITLS_X509_CertCtrl(bag->value.cert, HITLS_X509_REF_UP, &ref, sizeof(int32_t)); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *((HITLS_X509_Cert **)value) = bag->value.cert; return HITLS_PKI_SUCCESS; } static int32_t GetSecretBagValue(HITLS_PKCS12_Bag *bag, void *value) { if (value == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } BSL_Buffer *tmp = (BSL_Buffer *)value; if (bag->value.secret.data == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_BAG_NO_SECRET); return HITLS_PKCS12_ERR_BAG_NO_SECRET; } if (tmp->data == NULL || tmp->dataLen < bag->value.secret.dataLen) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_BUFFLEN_NOT_ENOUGH); return HITLS_PKCS12_ERR_BUFFLEN_NOT_ENOUGH; } (void)memcpy_s(tmp->data, tmp->dataLen, bag->value.secret.data, bag->value.secret.dataLen); tmp->dataLen = bag->value.secret.dataLen; return HITLS_PKI_SUCCESS; } int32_t BagGetValue(HITLS_PKCS12_Bag *bag, void *val) { if (bag == NULL || val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } switch (bag->id) { case BSL_CID_KEYBAG: case BSL_CID_PKCS8SHROUDEDKEYBAG: return GetKeyBagValue(bag, val); case BSL_CID_CERTBAG: return GetCertBagValue(bag, val); case BSL_CID_SECRETBAG: return GetSecretBagValue(bag, val); default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } } int32_t HITLS_PKCS12_BagRefUp(HITLS_PKCS12_Bag *bag) { if (bag == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } int val = 0; return BSL_SAL_AtomicUpReferences(&(bag->references), &val); } int32_t HITLS_PKCS12_BagCtrl(HITLS_PKCS12_Bag *bag, int32_t cmd, void *val, uint32_t valType) { if (bag == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } switch (cmd) { case HITLS_PKCS12_BAG_ADD_ATTR: return HITLS_PKCS12_BagAddAttr(bag, valType, val); case HITLS_PKCS12_BAG_GET_ATTR: return BagGetAttr(bag, valType, val); case HITLS_PKCS12_BAG_GET_ID: if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (valType != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } *((uint32_t *)val) = bag->id; return HITLS_PKI_SUCCESS; case HITLS_PKCS12_BAG_GET_TYPE: if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (valType != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } *((uint32_t *)val) = bag->type; return HITLS_PKI_SUCCESS; case HITLS_PKCS12_BAG_GET_VALUE: return BagGetValue(bag, val); default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_PKCS12
2301_79861745/bench_create
pki/pkcs12/src/hitls_pkcs12_bags.c
C
unknown
7,324
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_PKCS12 #include "bsl_sal.h" #ifdef HITLS_BSL_SAL_FILE #include "sal_file.h" #endif #include "securec.h" #include "hitls_pki_errno.h" #include "hitls_x509_local.h" #include "hitls_cms_local.h" #include "bsl_obj_internal.h" #include "bsl_err_internal.h" #include "crypt_encode_decode_key.h" #include "crypt_eal_codecs.h" #include "bsl_bytes.h" #include "crypt_eal_md.h" #include "hitls_pki_pkcs12.h" #include "hitls_pkcs12_local.h" #define HITLS_P12_CTX_SPECIFIC_TAG_EXTENSION 0 /* common Bag, including crl, cert, secret ... */ static BSL_ASN1_TemplateItem g_pk12CommonBagTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* bagId */ {BSL_ASN1_TAG_OBJECT_ID, 0, 1}, /* bagValue */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_P12_CTX_SPECIFIC_TAG_EXTENSION, 0, 1}, {BSL_ASN1_TAG_OCTETSTRING, 0, 2}, }; typedef enum { HITLS_PKCS12_COMMON_SAFEBAG_OID_IDX, HITLS_PKCS12_COMMON_SAFEBAG_BAGVALUES_IDX, HITLS_PKCS12_COMMON_SAFEBAG_MAX_IDX, } HITLS_PKCS12_COMMON_SAFEBAG_IDX; /* SafeBag ::= SEQUENCE { bagId BAG-TYPE.&id ({PKCS12BagSet}) bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}), bagAttributes SET OF PKCS12Attribute OPTIONAL } */ static BSL_ASN1_TemplateItem g_pk12SafeBagTempl[] = { /* bagId */ {BSL_ASN1_TAG_OBJECT_ID, BSL_ASN1_FLAG_DEFAULT, 0}, /* bagValue */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_P12_CTX_SPECIFIC_TAG_EXTENSION, BSL_ASN1_FLAG_HEADERONLY, 0}, /* bagAttributes */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_OPTIONAL, 0}, }; typedef enum { HITLS_PKCS12_SAFEBAG_OID_IDX, HITLS_PKCS12_SAFEBAG_BAGVALUES_IDX, HITLS_PKCS12_SAFEBAG_BAGATTRIBUTES_IDX, HITLS_PKCS12_SAFEBAG_MAX_IDX, } HITLS_PKCS12_SAFEBAG_IDX; /* * Defined in RFC 2531 * ContentInfo ::= SEQUENCE { * contentType ContentType, * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL * } */ static BSL_ASN1_TemplateItem g_pk12ContentInfoTempl[] = { /* content type */ {BSL_ASN1_TAG_OBJECT_ID, BSL_ASN1_FLAG_DEFAULT, 0}, /* content */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_P12_CTX_SPECIFIC_TAG_EXTENSION, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_OPTIONAL, 0}, }; typedef enum { HITLS_PKCS12_CONTENT_OID_IDX, HITLS_PKCS12_CONTENT_VALUE_IDX, HITLS_PKCS12_CONTENT_MAX_IDX, } HITLS_PKCS12_CONTENT_IDX; /* * MacData ::= SEQUENCE { * mac DigestInfo, * macSalt OCTET STRING, * iterations INTEGER DEFAULT 1 * -- Note: The default is for historical reasons and its * -- use is deprecated. * } */ static BSL_ASN1_TemplateItem g_p12MacDataTempl[] = { /* DigestInfo */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 0}, /* macSalt */ {BSL_ASN1_TAG_OCTETSTRING, 0, 0}, /* iterations */ {BSL_ASN1_TAG_INTEGER, 0, 0}, }; typedef enum { HITLS_PKCS12_MACDATA_DIGESTINFO_IDX, HITLS_PKCS12_MACDATA_SALT_IDX, HITLS_PKCS12_MACDATA_ITER_IDX, HITLS_PKCS12_MACDATA_MAX_IDX, } HITLS_PKCS12_MACDATA_IDX; /* * PFX ::= SEQUENCE { * version INTEGER {v3(3)}(v3,...), * authSafe ContentInfo, * macData MacData OPTIONAL * } */ static BSL_ASN1_TemplateItem g_p12TopLevelTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* pkcs12 */ /* version */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* tbs */ /* authSafe */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 1}, /* macData */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_OPTIONAL, 1}, }; typedef enum { HITLS_PKCS12_TOPLEVEL_VERSION_IDX, HITLS_PKCS12_TOPLEVEL_AUTHSAFE_IDX, HITLS_PKCS12_TOPLEVEL_MACDATA_IDX, HITLS_PKCS12_TOPLEVEL_MAX_IDX, } HITLS_PKCS12_TOPLEVEL_IDX; #ifdef HITLS_PKI_PKCS12_PARSE /* parse bags, and revoker already knows they are one of CommonBags */ static int32_t ParseCommonSafeBag(BSL_Buffer *buffer, HITLS_PKCS12_CommonSafeBag *bag) { uint8_t *temp = buffer->data; uint32_t tempLen = buffer->dataLen; BSL_ASN1_Buffer asnArr[HITLS_PKCS12_COMMON_SAFEBAG_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_pk12CommonBagTempl, sizeof(g_pk12CommonBagTempl) / sizeof(g_pk12CommonBagTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asnArr, HITLS_PKCS12_COMMON_SAFEBAG_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString oidStr = {asnArr[HITLS_PKCS12_COMMON_SAFEBAG_OID_IDX].len, (char *)asnArr[HITLS_PKCS12_COMMON_SAFEBAG_OID_IDX].buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_PARSE_TYPE); return HITLS_PKCS12_ERR_PARSE_TYPE; } bag->bagType = cid; bag->bagValue.data = asnArr[HITLS_PKCS12_COMMON_SAFEBAG_BAGVALUES_IDX].buff; bag->bagValue.dataLen = asnArr[HITLS_PKCS12_COMMON_SAFEBAG_BAGVALUES_IDX].len; return HITLS_PKI_SUCCESS; } /* Convert commonBags to the cert */ static int32_t ConvertCertBag(HITLS_PKCS12 *p12, HITLS_PKCS12_CommonSafeBag *bag, HITLS_X509_Cert **cert) { if (bag == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (bag->bagType != BSL_CID_X509CERTIFICATE) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_CERTYPES); return HITLS_PKCS12_ERR_INVALID_CERTYPES; } return HITLS_X509_ProviderCertParseBuff(p12->libCtx, p12->attrName, "ASN1", &bag->bagValue, cert); } static int32_t DecodeFriendlyName(BSL_ASN1_Buffer *buffer, BSL_Buffer *output) { uint8_t *temp = buffer->buff; uint32_t tempLen = buffer->len; uint32_t valueLen = buffer->len; int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_BMPSTRING, &temp, &tempLen, &valueLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Buffer input = { .buff = temp, .len = valueLen, .tag = BSL_ASN1_TAG_BMPSTRING, }; BSL_ASN1_Buffer decode = {0}; ret = BSL_ASN1_DecodePrimitiveItem(&input, &decode); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } output->data = decode.buff; output->dataLen = decode.len; return ret; } static int32_t ConvertAttributes(BslCid cid, BSL_ASN1_Buffer *buffer, BSL_Buffer *output) { int32_t ret; uint8_t *temp = buffer->buff; uint32_t tempLen = buffer->len; uint32_t valueLen = buffer->len; switch (cid) { case BSL_CID_FRIENDLYNAME: return DecodeFriendlyName(buffer, output); case BSL_CID_LOCALKEYID: ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_OCTETSTRING, &temp, &tempLen, &valueLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } output->data = BSL_SAL_Dump(temp, valueLen); if (output->data == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } output->dataLen = valueLen; return HITLS_PKI_SUCCESS; default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES); return HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES; } } static int32_t X509_ParseP12AttrItem(BslList *attrList, HITLS_X509_AttrEntry *attrEntry) { HITLS_PKCS12_SafeBagAttr attr = {0}; attr.attrId = attrEntry->cid; int32_t ret = ConvertAttributes(attrEntry->cid, &attrEntry->attrValue, &attr.attrValue); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_AddListItemDefault(&attr, sizeof(HITLS_PKCS12_SafeBagAttr), attrList); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BSL_SAL_Free(attr.attrValue.data); } return ret; } int32_t HITLS_PKCS12_ParseSafeBagAttr(BSL_ASN1_Buffer *attrBuff, HITLS_X509_Attrs *attrList) { return HITLS_X509_ParseAttrList(attrBuff, attrList, X509_ParseP12AttrItem, HITLS_PKCS12_AttributesFree); } /* * Parse the 'safeBag' of p12. This interface only parses the outermost layer and attributes of safeBag, * others are handed over to the next layer for parsing */ static int32_t ParseSafeBag(BSL_Buffer *buffer, HITLS_PKCS12_SafeBag *safeBag) { uint8_t *temp = buffer->data; uint32_t tempLen = buffer->dataLen; BSL_ASN1_Template templ = {g_pk12SafeBagTempl, sizeof(g_pk12SafeBagTempl) / sizeof(g_pk12SafeBagTempl[0])}; BSL_ASN1_Buffer asnArr[HITLS_PKCS12_SAFEBAG_MAX_IDX] = {0}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asnArr, HITLS_PKCS12_SAFEBAG_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString oid = {asnArr[HITLS_PKCS12_SAFEBAG_OID_IDX].len, (char *)asnArr[HITLS_PKCS12_SAFEBAG_OID_IDX].buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oid); if (cid == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE); return HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE; } HITLS_X509_Attrs *attributes = NULL; BSL_Buffer *bag = BSL_SAL_Calloc(1u, sizeof(BSL_Buffer)); if (bag == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } bag->data = BSL_SAL_Dump(asnArr[HITLS_PKCS12_SAFEBAG_BAGVALUES_IDX].buff, asnArr[HITLS_PKCS12_SAFEBAG_BAGVALUES_IDX].len); if (bag->data == NULL) { ret = BSL_DUMP_FAIL; BSL_ERR_PUSH_ERROR(ret); goto ERR; } bag->dataLen = asnArr[HITLS_PKCS12_SAFEBAG_BAGVALUES_IDX].len; attributes = HITLS_X509_AttrsNew(); if (attributes == NULL) { ret = BSL_MALLOC_FAIL; BSL_ERR_PUSH_ERROR(ret); goto ERR; } ret = HITLS_PKCS12_ParseSafeBagAttr(asnArr + HITLS_PKCS12_SAFEBAG_BAGATTRIBUTES_IDX, attributes); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } safeBag->attributes = attributes; safeBag->bagId = cid; safeBag->bag = bag; return ret; ERR: BSL_SAL_FREE(bag->data); BSL_SAL_FREE(bag); HITLS_X509_AttrsFree(attributes, HITLS_PKCS12_AttributesFree); return ret; } static int32_t ParsePKCS8ShroudedKeyBags(HITLS_PKCS12 *p12, const uint8_t *pwd, uint32_t pwdlen, HITLS_PKCS12_SafeBag *safeBag) { CRYPT_EAL_PkeyCtx *prikey = NULL; const BSL_Buffer pwdBuff = {(uint8_t *)(uintptr_t)pwd, pwdlen}; int32_t ret = CRYPT_EAL_ProviderDecodeBuffKey(p12->libCtx, p12->attrName, BSL_CID_UNKNOWN, "ASN1", "PRIKEY_PKCS8_ENCRYPT", safeBag->bag, &pwdBuff, &prikey); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } HITLS_PKCS12_Bag *keyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, prikey); CRYPT_EAL_PkeyFreeCtx(prikey); if (keyBag == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } keyBag->attributes = safeBag->attributes; safeBag->attributes = NULL; p12->key = keyBag; return HITLS_PKI_SUCCESS; } static int32_t ParseKeyBagAndAddList(HITLS_PKCS12 *p12, HITLS_PKCS12_SafeBag *safeBag) { CRYPT_EAL_PkeyCtx *prikey = NULL; int32_t ret = CRYPT_EAL_ProviderDecodeBuffKey(p12->libCtx, p12->attrName, BSL_CID_UNKNOWN, "ASN1", "PRIKEY_PKCS8_UNENCRYPT", safeBag->bag, NULL, &prikey); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } HITLS_PKCS12_Bag *keyBag = HITLS_PKCS12_BagNew(BSL_CID_KEYBAG, 0, prikey); CRYPT_EAL_PkeyFreeCtx(prikey); if (keyBag == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } keyBag->attributes = safeBag->attributes; ret = BSL_LIST_AddElement(p12->keyList, keyBag, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { keyBag->attributes = NULL; HITLS_PKCS12_BagFree(keyBag); BSL_ERR_PUSH_ERROR(ret); return ret; } safeBag->attributes = NULL; return HITLS_PKI_SUCCESS; } static int32_t ParseCertBagAndAddList(HITLS_PKCS12 *p12, HITLS_PKCS12_SafeBag *safeBag) { HITLS_PKCS12_CommonSafeBag bag = {0}; int32_t ret = ParseCommonSafeBag(safeBag->bag, &bag); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } HITLS_X509_Cert *cert = NULL; ret = ConvertCertBag(p12, &bag, &cert); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } HITLS_PKCS12_Bag *bagData = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, cert); HITLS_X509_CertFree(cert); if (bagData == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } bagData->attributes = safeBag->attributes; ret = BSL_LIST_AddElement(p12->certList, bagData, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { bagData->attributes = NULL; HITLS_PKCS12_BagFree(bagData); BSL_ERR_PUSH_ERROR(ret); return ret; } safeBag->attributes = NULL; return ret; } static int32_t ParseSecretBagAndAddList(HITLS_PKCS12 *p12, HITLS_PKCS12_SafeBag *safeBag) { HITLS_PKCS12_CommonSafeBag bag = {0}; int32_t ret = ParseCommonSafeBag(safeBag->bag, &bag); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } HITLS_PKCS12_Bag *bagData = HITLS_PKCS12_BagNew(BSL_CID_SECRETBAG, bag.bagType, &bag.bagValue); if (bagData == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } bagData->attributes = safeBag->attributes; ret = BSL_LIST_AddElement(p12->secretBags, bagData, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { bagData->attributes = NULL; HITLS_PKCS12_BagFree(bagData); BSL_ERR_PUSH_ERROR(ret); return ret; } safeBag->attributes = NULL; return ret; } /* Parse a SafeBag to the data we need, such as a private key, etc */ int32_t HITLS_PKCS12_ConvertSafeBag(HITLS_PKCS12_SafeBag *safeBag, const uint8_t *pwd, uint32_t pwdlen, HITLS_PKCS12 *p12) { if (safeBag == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } switch (safeBag->bagId) { case BSL_CID_PKCS8SHROUDEDKEYBAG: if (p12->key != NULL) { return HITLS_PKI_SUCCESS; } return ParsePKCS8ShroudedKeyBags(p12, pwd, pwdlen, safeBag); case BSL_CID_CERTBAG: return ParseCertBagAndAddList(p12, safeBag); case BSL_CID_SECRETBAG: return ParseSecretBagAndAddList(p12, safeBag); case BSL_CID_KEYBAG: return ParseKeyBagAndAddList(p12, safeBag); default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE); return HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE; } } int32_t HITLS_PKCS12_ParseContentInfo(HITLS_PKI_LibCtx *libCtx, const char *attrName, BSL_Buffer *encode, const uint8_t *password, uint32_t passLen, BSL_Buffer *data) { uint8_t *temp = encode->data; uint32_t tempLen = encode->dataLen; BSL_ASN1_Template templ = {g_pk12ContentInfoTempl, sizeof(g_pk12ContentInfoTempl) / sizeof(g_pk12ContentInfoTempl[0])}; BSL_ASN1_Buffer asnArr[HITLS_PKCS12_CONTENT_MAX_IDX] = {0}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asnArr, HITLS_PKCS12_CONTENT_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString oid = {asnArr[HITLS_PKCS12_CONTENT_OID_IDX].len, (char *)asnArr[HITLS_PKCS12_CONTENT_OID_IDX].buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oid); if (cid == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE); return HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE; } BSL_Buffer asnArrData = {asnArr[HITLS_PKCS12_CONTENT_VALUE_IDX].buff, asnArr[HITLS_PKCS12_CONTENT_VALUE_IDX].len}; switch (cid) { case BSL_CID_PKCS7_SIMPLEDATA: return HITLS_CMS_ParseAsn1Data(&asnArrData, data); case BSL_CID_PKCS7_ENCRYPTEDDATA: return CRYPT_EAL_ParseAsn1PKCS7EncryptedData(libCtx, attrName, &asnArrData, password, passLen, data); default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE); return HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE; } } /* Parse each safeBag from list, and extract the data we need, such as a private key, etc */ int32_t HITLS_PKCS12_ParseSafeBagList(BSL_ASN1_List *bagList, const uint8_t *password, uint32_t passLen, HITLS_PKCS12 *p12) { if (BSL_LIST_COUNT(bagList) == 0) { return HITLS_PKI_SUCCESS; } int32_t ret; HITLS_PKCS12_SafeBag *node = BSL_LIST_GET_FIRST(bagList); while (node != NULL) { ret = HITLS_PKCS12_ConvertSafeBag(node, password, passLen, p12); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } node = BSL_LIST_GET_NEXT(bagList); } return HITLS_PKI_SUCCESS; } static BSL_Buffer *FindLocatedId(HITLS_X509_Attrs *attributes) { if (attributes == NULL) { return NULL; } HITLS_PKCS12_SafeBagAttr *node = BSL_LIST_GET_FIRST(attributes->list); while (node != NULL) { if (node->attrId == BSL_CID_LOCALKEYID) { return &node->attrValue; } node = BSL_LIST_GET_NEXT(attributes->list); } return NULL; } static int32_t SetEntityCert(HITLS_PKCS12 *p12) { if (p12->key == NULL) { return HITLS_PKI_SUCCESS; } BSL_Buffer *keyId = FindLocatedId(p12->key->attributes); if (keyId == NULL) { return HITLS_PKI_SUCCESS; } BSL_ASN1_List *bags = p12->certList; HITLS_PKCS12_Bag *node = BSL_LIST_GET_FIRST(bags); while (node != NULL) { BSL_Buffer *certId = FindLocatedId(node->attributes); if (certId != NULL && certId->dataLen == keyId->dataLen && memcmp(certId->data, keyId->data, keyId->dataLen) == 0) { p12->entityCert = node; BSL_LIST_DetachCurrent(bags); return HITLS_PKI_SUCCESS; } node = BSL_LIST_GET_NEXT(bags); } BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NO_ENTITYCERT); return HITLS_PKCS12_ERR_NO_ENTITYCERT; } static int32_t ParseSafeBagList(HITLS_PKI_LibCtx *libCtx, const char *attrName, BSL_Buffer *node, const uint8_t *password, uint32_t passLen, BSL_ASN1_List *bagLists) { BSL_Buffer safeContent = {0}; int32_t ret = HITLS_PKCS12_ParseContentInfo(libCtx, attrName, node, password, passLen, &safeContent); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_PKCS12_ParseAsn1AddList(&safeContent, bagLists, BSL_CID_SAFECONTENTSBAG); BSL_SAL_Free(safeContent.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } // The caller guarantees that the input is not empty. int32_t HITLS_PKCS12_ParseAuthSafeData(BSL_Buffer *encode, const uint8_t *password, uint32_t passLen, HITLS_PKCS12 *p12) { BSL_ASN1_List *bagLists = NULL; BSL_Buffer *node = NULL; BSL_ASN1_List *contentList = BSL_LIST_New(sizeof(BSL_Buffer)); if (contentList == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = HITLS_PKCS12_ParseAsn1AddList(encode, contentList, BSL_CID_PKCS7_CONTENTINFO); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } bagLists = BSL_LIST_New(sizeof(HITLS_PKCS12_SafeBag)); if (bagLists == NULL) { ret = BSL_MALLOC_FAIL; BSL_ERR_PUSH_ERROR(ret); goto ERR; } node = BSL_LIST_GET_FIRST(contentList); while (node != NULL) { ret = ParseSafeBagList(p12->libCtx, p12->attrName, node, password, passLen, bagLists); if (ret != HITLS_PKI_SUCCESS) { goto ERR; } node = BSL_LIST_GET_NEXT(contentList); } ret = HITLS_PKCS12_ParseSafeBagList(bagLists, password, passLen, p12); if (ret != HITLS_PKI_SUCCESS) { goto ERR; } ret = SetEntityCert(p12); ERR: BSL_LIST_FREE(bagLists, (BSL_LIST_PFUNC_FREE)HITLS_PKCS12_SafeBagFree); BSL_LIST_FREE(contentList, NULL); return ret; } static int32_t ParseContentInfoAsnItem(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { (void) param; if (layer == 1) { return HITLS_PKI_SUCCESS; } BSL_Buffer buffer = {asn->buff, asn->len}; return HITLS_X509_AddListItemDefault(&buffer, sizeof(BSL_Buffer), list); } static int32_t ParseSafeContentAsnItem(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { (void) param; if (layer == 1) { return HITLS_PKI_SUCCESS; } BSL_Buffer buffer = {asn->buff, asn->len}; HITLS_PKCS12_SafeBag *safeBag = BSL_SAL_Calloc(sizeof(HITLS_PKCS12_SafeBag), 1); if (safeBag == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = ParseSafeBag(&buffer, safeBag); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(safeBag); BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_AddListItemDefault(safeBag, sizeof(HITLS_PKCS12_SafeBag), list); if (ret != HITLS_PKI_SUCCESS) { HITLS_PKCS12_SafeBagFree(safeBag); BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_SAL_Free(safeBag); return ret; } int32_t HITLS_PKCS12_ParseAsn1AddList(BSL_Buffer *encode, BSL_ASN1_List *list, uint32_t parseType) { if (encode == NULL || encode->data == NULL || list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } uint8_t expTag[] = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE}; BSL_ASN1_DecodeListParam listParam = {2, expTag}; BSL_ASN1_Buffer asn = { BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, encode->dataLen, encode->data, }; int32_t ret; switch (parseType) { case BSL_CID_PKCS7_CONTENTINFO: ret = BSL_ASN1_DecodeListItem(&listParam, &asn, &ParseContentInfoAsnItem, NULL, list); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); // Resources are released by the caller. } return ret; case BSL_CID_SAFECONTENTSBAG: ret = BSL_ASN1_DecodeListItem(&listParam, &asn, &ParseSafeContentAsnItem, NULL, list); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); // Resources are released by the caller. } return ret; default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE); return HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE; } } int32_t HITLS_PKCS12_ParseMacData(BSL_Buffer *encode, HITLS_PKCS12_MacData *macData) { if (encode == NULL || encode->data == NULL || encode->dataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } uint8_t *temp = encode->data; uint32_t tempLen = encode->dataLen; BSL_ASN1_Buffer asn1[HITLS_PKCS12_MACDATA_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_p12MacDataTempl, sizeof(g_p12MacDataTempl) / sizeof(g_p12MacDataTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asn1, HITLS_PKCS12_MACDATA_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer mac = {0}; BSL_Buffer digestInfo = {asn1[HITLS_PKCS12_MACDATA_DIGESTINFO_IDX].buff, asn1[HITLS_PKCS12_MACDATA_DIGESTINFO_IDX].len}; BslCid cid = BSL_CID_UNKNOWN; ret = HITLS_CMS_ParseDigestInfo(&digestInfo, &cid, &mac); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint8_t *salt = BSL_SAL_Dump(asn1[HITLS_PKCS12_MACDATA_SALT_IDX].buff, asn1[HITLS_PKCS12_MACDATA_SALT_IDX].len); if (salt == NULL) { BSL_SAL_Free(mac.data); BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } uint32_t iter = 0; ret = BSL_ASN1_DecodePrimitiveItem(&asn1[HITLS_PKCS12_MACDATA_ITER_IDX], &iter); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(mac.data); BSL_SAL_Free(salt); BSL_ERR_PUSH_ERROR(ret); return ret; } macData->mac->data = mac.data; macData->mac->dataLen = mac.dataLen; macData->alg = cid; macData->macSalt->data = salt; macData->macSalt->dataLen = asn1[HITLS_PKCS12_MACDATA_SALT_IDX].len; macData->iteration = iter; return HITLS_PKI_SUCCESS; } static void ClearMacData(HITLS_PKCS12_MacData *p12Mac) { if (p12Mac == NULL) { return; } BSL_SAL_FREE(p12Mac->mac->data); BSL_SAL_FREE(p12Mac->macSalt->data); p12Mac->macSalt->dataLen = 0; p12Mac->mac->dataLen = 0; p12Mac->iteration = 0; p12Mac->alg = BSL_CID_UNKNOWN; } static int32_t ParseMacDataAndVerify(HITLS_PKCS12 *p12, BSL_Buffer *initData, BSL_Buffer *macData, const HITLS_PKCS12_PwdParam *pwdParam) { int32_t ret = HITLS_PKCS12_ParseMacData(macData, p12->macData); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer verify = {0}; ret = HITLS_PKCS12_CalMac(p12, pwdParam->macPwd, initData, &verify); if (ret != HITLS_PKI_SUCCESS) { ClearMacData(p12->macData); BSL_ERR_PUSH_ERROR(ret); return ret; } if (p12->macData->mac->dataLen != verify.dataLen || memcmp(verify.data, p12->macData->mac->data, verify.dataLen) != 0) { ClearMacData(p12->macData); BSL_SAL_Free(verify.data); BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_VERIFY_FAIL); return HITLS_PKCS12_ERR_VERIFY_FAIL; } BSL_SAL_Free(verify.data); return HITLS_PKI_SUCCESS; } static int32_t ParseAsn1PKCS12(const BSL_Buffer *encode, const HITLS_PKCS12_PwdParam *pwdParam, HITLS_PKCS12 *p12, bool needMacVerify) { uint32_t version = 0; uint8_t *temp = encode->data; uint32_t tempLen = encode->dataLen; BSL_ASN1_Buffer asn1[HITLS_PKCS12_TOPLEVEL_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_p12TopLevelTempl, sizeof(g_p12TopLevelTempl) / sizeof(g_p12TopLevelTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asn1, HITLS_PKCS12_TOPLEVEL_MAX_IDX); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_ASN1_DecodePrimitiveItem(&asn1[HITLS_PKCS12_TOPLEVEL_VERSION_IDX], &version); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (version != 3) { // RFC 7292 requires that version = 3. BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PFX); return HITLS_PKCS12_ERR_INVALID_PFX; } BSL_Buffer macData = {asn1[HITLS_PKCS12_TOPLEVEL_MACDATA_IDX].buff, asn1[HITLS_PKCS12_TOPLEVEL_MACDATA_IDX].len}; BSL_Buffer contentInfo = {asn1[HITLS_PKCS12_TOPLEVEL_AUTHSAFE_IDX].buff, asn1[HITLS_PKCS12_TOPLEVEL_AUTHSAFE_IDX].len}; BSL_Buffer initData = {0}; ret = HITLS_PKCS12_ParseContentInfo(p12->libCtx, p12->attrName, &contentInfo, NULL, 0, &initData); if (ret != HITLS_PKI_SUCCESS) { return ret; // has pushed error code. } if (needMacVerify) { ret = ParseMacDataAndVerify(p12, &initData, &macData, pwdParam); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(initData.data); return ret; // has pushed error code. } } ret = HITLS_PKCS12_ParseAuthSafeData(&initData, pwdParam->encPwd->data, pwdParam->encPwd->dataLen, p12); BSL_SAL_Free(initData.data); if (ret != HITLS_PKI_SUCCESS) { ClearMacData(p12->macData); return ret; // has pushed error code. } p12->version = version; return HITLS_PKI_SUCCESS; } static int32_t ProviderParseBuffInternal(HITLS_PKI_LibCtx *libCtx, const char *attrName, int32_t format, const BSL_Buffer *encode, const HITLS_PKCS12_PwdParam *pwdParam, HITLS_PKCS12 **p12, bool needMacVerify) { if (encode == NULL || encode->data == NULL || encode->dataLen == 0 || pwdParam == NULL || pwdParam->encPwd == NULL || pwdParam->encPwd->data == NULL || p12 == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (*p12 != NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } int32_t ret; HITLS_PKCS12 *temP12 = HITLS_PKCS12_ProviderNew(libCtx, attrName); if (temP12 == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } switch (format) { case BSL_FORMAT_ASN1: ret = ParseAsn1PKCS12(encode, pwdParam, temP12, needMacVerify); break; default: ret = HITLS_PKCS12_ERR_FORMAT_UNSUPPORT; break; } if (ret != HITLS_PKI_SUCCESS) { HITLS_PKCS12_Free(temP12); BSL_ERR_PUSH_ERROR(ret); return ret; } *p12 = temP12; return HITLS_PKI_SUCCESS; } int32_t HITLS_PKCS12_ProviderParseBuff(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const BSL_Buffer *encode, const HITLS_PKCS12_PwdParam *pwdParam, HITLS_PKCS12 **p12, bool needMacVerify) { int32_t encodeFormat = CRYPT_EAL_GetEncodeFormat(format); return ProviderParseBuffInternal(libCtx, attrName, encodeFormat, encode, pwdParam, p12, needMacVerify); } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_PKCS12_ProviderParseFile(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const char *path, const HITLS_PKCS12_PwdParam *pwdParam, HITLS_PKCS12 **p12, bool needMacVerify) { if (path == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer encode = {data, dataLen}; ret = HITLS_PKCS12_ProviderParseBuff(libCtx, attrName, format, &encode, pwdParam, p12, needMacVerify); BSL_SAL_Free(data); return ret; } int32_t HITLS_PKCS12_ParseFile(int32_t format, const char *path, const HITLS_PKCS12_PwdParam *pwdParam, HITLS_PKCS12 **p12, bool needMacVerify) { if (path == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer encode = {data, dataLen}; ret = HITLS_PKCS12_ParseBuff(format, &encode, pwdParam, p12, needMacVerify); BSL_SAL_Free(data); return ret; } #endif // HITLS_BSL_SAL_FILE int32_t HITLS_PKCS12_ParseBuff(int32_t format, const BSL_Buffer *encode, const HITLS_PKCS12_PwdParam *pwdParam, HITLS_PKCS12 **p12, bool needMacVerify) { return ProviderParseBuffInternal(NULL, NULL, format, encode, pwdParam, p12, needMacVerify); } #endif // HITLS_PKI_PKCS12_PARSE #ifdef HITLS_PKI_PKCS12_GEN static void FreeListBuff(BSL_ASN1_Buffer *asnBuf, uint32_t count) { for (uint32_t i = 0; i < count; i++) { BSL_SAL_FREE(asnBuf[i].buff); } BSL_SAL_FREE(asnBuf); } static int32_t EncodeAttrValue(HITLS_PKCS12_SafeBagAttr *attribute, BSL_Buffer *encode) { BSL_ASN1_Buffer asnArr = {0}; int32_t ret; asnArr.buff = attribute->attrValue.data; asnArr.len = attribute->attrValue.dataLen; switch (attribute->attrId) { case BSL_CID_FRIENDLYNAME: asnArr.tag = BSL_ASN1_TAG_BMPSTRING; BSL_ASN1_TemplateItem nameTemplItem = {BSL_ASN1_TAG_BMPSTRING, 0, 0}; BSL_ASN1_Template nameTempl = {&nameTemplItem, 1}; ret = BSL_ASN1_EncodeTemplate(&nameTempl, &asnArr, 1, &encode->data, &encode->dataLen); break; case BSL_CID_LOCALKEYID: asnArr.tag = BSL_ASN1_TAG_OCTETSTRING; BSL_ASN1_TemplateItem locatedIdTemplItem = {BSL_ASN1_TAG_OCTETSTRING, 0, 0}; BSL_ASN1_Template locatedIdTempl = {&locatedIdTemplItem, 1}; ret = BSL_ASN1_EncodeTemplate(&locatedIdTempl, &asnArr, 1, &encode->data, &encode->dataLen); break; default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES); return HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES; } if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t X509_EncodeP12AttrItem(void *attrNode, HITLS_X509_AttrEntry *attrEntry) { if (attrNode == NULL || attrEntry == NULL) { return HITLS_X509_ERR_INVALID_PARAM; } HITLS_PKCS12_SafeBagAttr *p12Attr = attrNode; BslOidString *oidStr = BSL_OBJ_GetOID(p12Attr->attrId); if (oidStr == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES); return HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES; } attrEntry->attrId.tag = BSL_ASN1_TAG_OBJECT_ID; attrEntry->attrId.buff = (uint8_t *)oidStr->octs; attrEntry->attrId.len = oidStr->octetLen; BSL_Buffer buffer = {0}; int32_t ret = EncodeAttrValue(p12Attr, &buffer); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } attrEntry->attrValue.tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET; attrEntry->attrValue.buff = buffer.data; attrEntry->attrValue.len = buffer.dataLen; attrEntry->cid = p12Attr->attrId; return HITLS_PKI_SUCCESS; } int32_t HITLS_PKCS12_EncodeAttrList(HITLS_X509_Attrs *attrs, BSL_ASN1_Buffer *attrBuff) { return HITLS_X509_EncodeAttrList(BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET, attrs, X509_EncodeP12AttrItem, attrBuff); } static int32_t EncodeCertBag(HITLS_X509_Cert *cert, uint32_t certType, uint8_t **encode, uint32_t *encodeLen) { int32_t ret; BslOidString *oidStr = BSL_OBJ_GetOID(certType); if (oidStr == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_ALGO); return HITLS_PKCS12_ERR_INVALID_ALGO; } BSL_Buffer certBuff = {0}; ret = HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, cert, &certBuff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Buffer asnArr[HITLS_PKCS12_COMMON_SAFEBAG_MAX_IDX] = { { .buff = (uint8_t *)oidStr->octs, .len = oidStr->octetLen, .tag = BSL_ASN1_TAG_OBJECT_ID, }, { .buff = certBuff.data, .len = certBuff.dataLen, .tag = BSL_ASN1_TAG_OCTETSTRING, }}; BSL_ASN1_Template templ = {g_pk12CommonBagTempl, sizeof(g_pk12CommonBagTempl) / sizeof(g_pk12CommonBagTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, HITLS_PKCS12_COMMON_SAFEBAG_MAX_IDX, encode, encodeLen); BSL_SAL_Free(certBuff.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t EncodeSecretBag(BSL_Buffer *secret, uint32_t secretType, uint8_t **encode, uint32_t *encodeLen) { int32_t ret; BslOidString *oidStr = BSL_OBJ_GetOID(secretType); if (oidStr == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_ALGO); return HITLS_PKCS12_ERR_INVALID_ALGO; } BSL_ASN1_Buffer asnArr[HITLS_PKCS12_COMMON_SAFEBAG_MAX_IDX] = { { .buff = (uint8_t *)oidStr->octs, .len = oidStr->octetLen, .tag = BSL_ASN1_TAG_OBJECT_ID, }, { .buff = secret->data, .len = secret->dataLen, .tag = BSL_ASN1_TAG_OCTETSTRING, }}; BSL_ASN1_Template templ = {g_pk12CommonBagTempl, sizeof(g_pk12CommonBagTempl) / sizeof(g_pk12CommonBagTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, HITLS_PKCS12_COMMON_SAFEBAG_MAX_IDX, encode, encodeLen); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t EncodeSafeBag(HITLS_PKCS12 *p12, HITLS_PKCS12_Bag *bag, uint32_t encodeType, const CRYPT_EncodeParam *encryptParam, uint8_t **output, uint32_t *outputLen) { int32_t ret; BslOidString *oidStr = BSL_OBJ_GetOID(encodeType); if (oidStr == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_ALGO); return HITLS_PKCS12_ERR_INVALID_ALGO; } BSL_Buffer encode = {0}; switch (encodeType) { case BSL_CID_PKCS8SHROUDEDKEYBAG: if (encryptParam == NULL || encryptParam->param == NULL) { ret = HITLS_PKCS12_ERR_NO_ENCRYPT_PARAM; break; } ret = CRYPT_EAL_ProviderEncodeBuffKey(p12->libCtx, p12->attrName, bag->value.key, encryptParam, "ASN1", "PRIKEY_PKCS8_ENCRYPT", &encode); break; case BSL_CID_KEYBAG: ret = CRYPT_EAL_ProviderEncodeBuffKey(p12->libCtx, p12->attrName, bag->value.key, NULL, "ASN1", "PRIKEY_PKCS8_UNENCRYPT", &encode); break; case BSL_CID_CERTBAG: ret = EncodeCertBag(bag->value.cert, BSL_CID_X509CERTIFICATE, &encode.data, &encode.dataLen); break; case BSL_CID_SECRETBAG: ret = EncodeSecretBag(&bag->value.secret, bag->type, &encode.data, &encode.dataLen); break; default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE); return HITLS_PKCS12_ERR_INVALID_SAFEBAG_TYPE; } if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Buffer asnArr[HITLS_PKCS12_SAFEBAG_MAX_IDX] = { { .buff = (uint8_t *)oidStr->octs, .len = oidStr->octetLen, .tag = BSL_ASN1_TAG_OBJECT_ID, }, { .buff = encode.data, .len = encode.dataLen, .tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_P12_CTX_SPECIFIC_TAG_EXTENSION, }}; ret = HITLS_PKCS12_EncodeAttrList(bag->attributes, &asnArr[HITLS_PKCS12_SAFEBAG_BAGATTRIBUTES_IDX]); if (ret != BSL_SUCCESS) { BSL_SAL_Free(encode.data); BSL_ERR_PUSH_ERROR(ret); return ret; } asnArr[HITLS_PKCS12_SAFEBAG_BAGATTRIBUTES_IDX].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET; BSL_ASN1_Template templ = {g_pk12SafeBagTempl, sizeof(g_pk12SafeBagTempl) / sizeof(g_pk12SafeBagTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, HITLS_PKCS12_SAFEBAG_MAX_IDX, output, outputLen); BSL_SAL_Free(encode.data); BSL_SAL_FREE(asnArr[HITLS_PKCS12_SAFEBAG_BAGATTRIBUTES_IDX].buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t EncodeP7Data(BSL_Buffer *input, BSL_Buffer *encode) { BSL_ASN1_Buffer asnArr = {0}; asnArr.buff = input->data; asnArr.tag = BSL_ASN1_TAG_OCTETSTRING; asnArr.len = input->dataLen; BSL_ASN1_TemplateItem dataTemplItem = {BSL_ASN1_TAG_OCTETSTRING, 0, 0}; BSL_ASN1_Template dataTempl = {&dataTemplItem, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&dataTempl, &asnArr, 1, &encode->data, &encode->dataLen); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t HITLS_PKCS12_EncodeContentInfo(HITLS_PKI_LibCtx *libCtx, const char *attrName, BSL_Buffer *input, uint32_t encodeType, const CRYPT_EncodeParam *encryptParam, BSL_Buffer *encode) { int32_t ret; BslOidString *oidStr = BSL_OBJ_GetOID(encodeType); if (oidStr == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_ALGO); return HITLS_PKCS12_ERR_INVALID_ALGO; } BSL_Buffer initData = {0}; switch (encodeType) { case BSL_CID_PKCS7_SIMPLEDATA: ret = EncodeP7Data(input, &initData); break; case BSL_CID_PKCS7_ENCRYPTEDDATA: if (encryptParam == NULL || encryptParam->param == NULL) { ret = HITLS_PKCS12_ERR_NO_ENCRYPT_PARAM; break; } ret = CRYPT_EAL_EncodePKCS7EncryptDataBuff(libCtx, attrName, input, encryptParam, &initData); break; default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_CONTENTINFO); return HITLS_PKCS12_ERR_INVALID_CONTENTINFO; } if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Buffer asnArr[HITLS_PKCS12_CONTENT_MAX_IDX] = { { .buff = (uint8_t *)oidStr->octs, .len = oidStr->octetLen, .tag = BSL_ASN1_TAG_OBJECT_ID, }, { .buff = initData.data, .len = initData.dataLen, .tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_P12_CTX_SPECIFIC_TAG_EXTENSION, }}; BSL_ASN1_Template templ = {g_pk12ContentInfoTempl, sizeof(g_pk12ContentInfoTempl) / sizeof(g_pk12ContentInfoTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, HITLS_PKCS12_CONTENT_MAX_IDX, &encode->data, &encode->dataLen); BSL_SAL_Free(initData.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t EncodeSafeContent(HITLS_PKCS12 *p12, BSL_ASN1_Buffer **output, BSL_ASN1_List *list, uint32_t encodeType, const CRYPT_EncodeParam *encryptParam) { BSL_ASN1_Buffer *asnBuf = BSL_SAL_Calloc((uint32_t)list->count, sizeof(BSL_ASN1_Buffer)); if (asnBuf == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } uint32_t iter = 0; int32_t ret = HITLS_PKI_SUCCESS; HITLS_PKCS12_Bag *node = NULL; for (node = BSL_LIST_GET_FIRST(list); node != NULL; node = BSL_LIST_GET_NEXT(list), iter++) { ret = EncodeSafeBag(p12, node, encodeType, encryptParam, &asnBuf[iter].buff, &asnBuf[iter].len); if (ret != BSL_SUCCESS) { FreeListBuff(asnBuf, iter); BSL_ERR_PUSH_ERROR(ret); return ret; } asnBuf[iter].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; } *output = asnBuf; return ret; } static int32_t EncodeContentInfoList(BSL_ASN1_Buffer **output, BSL_ASN1_List *list) { BSL_ASN1_Buffer *asnBuf = BSL_SAL_Calloc((uint32_t)list->count, sizeof(BSL_ASN1_Buffer)); if (asnBuf == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } uint32_t iter = 0; int32_t ret = HITLS_PKI_SUCCESS; BSL_Buffer *node = NULL; for (node = BSL_LIST_GET_FIRST(list); node != NULL; node = BSL_LIST_GET_NEXT(list), iter++) { asnBuf[iter].buff = BSL_SAL_Dump(node->data, node->dataLen); if (asnBuf[iter].buff == NULL) { FreeListBuff(asnBuf, iter); BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } asnBuf[iter].len = node->dataLen; asnBuf[iter].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; } *output = asnBuf; return ret; } int32_t HITLS_PKCS12_EncodeAsn1List(HITLS_PKCS12 *p12, BSL_ASN1_List *list, uint32_t encodeType, const CRYPT_EncodeParam *encryptParam, BSL_Buffer *encode) { uint32_t count = (uint32_t)BSL_LIST_COUNT(list); BSL_ASN1_Buffer *asnBuffers = NULL; int32_t ret; switch (encodeType) { case BSL_CID_PKCS7_CONTENTINFO: ret = EncodeContentInfoList(&asnBuffers, list); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } break; case BSL_CID_SECRETBAG: case BSL_CID_PKCS8SHROUDEDKEYBAG: case BSL_CID_KEYBAG: case BSL_CID_CERTBAG: ret = EncodeSafeContent(p12, &asnBuffers, list, encodeType, encryptParam); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } break; default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_CONTENTINFO); return HITLS_PKCS12_ERR_INVALID_CONTENTINFO; } BSL_ASN1_TemplateItem listTempl = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0 }; BSL_ASN1_Template templ = {&listTempl, 1}; BSL_ASN1_Buffer out = {0}; ret = BSL_ASN1_EncodeListItem(BSL_ASN1_TAG_SEQUENCE, count, &templ, asnBuffers, count, &out); FreeListBuff(asnBuffers, count); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_ASN1_EncodeTemplate(&templ, &out, 1, &encode->data, &encode->dataLen); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } BSL_SAL_FREE(out.buff); return ret; } int32_t HITLS_PKCS12_EncodeMacData(HITLS_PKCS12 *p12, BSL_Buffer *initData, const HITLS_PKCS12_MacParam *macParam, BSL_Buffer *encode) { HITLS_PKCS12_MacData *p12Mac = p12->macData; if (macParam->algId != BSL_CID_PKCS12KDF) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_ALGO); return HITLS_PKCS12_ERR_INVALID_ALGO; } if (macParam->para == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NO_MAC_PARAM); return HITLS_PKCS12_ERR_NO_MAC_PARAM; } BSL_Buffer mac = {0}; BSL_Buffer digestInfo = {0}; HITLS_PKCS12_KdfParam *param = (HITLS_PKCS12_KdfParam *)macParam->para; p12Mac->alg = param->macId; p12Mac->iteration = param->itCnt; p12Mac->macSalt->dataLen = param->saltLen; BSL_Buffer macPwd = {param->pwd, param->pwdLen}; int32_t ret = HITLS_PKCS12_CalMac(p12, &macPwd, initData, &mac); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_CMS_EncodeDigestInfoBuff(p12Mac->alg, &mac, &digestInfo); BSL_SAL_FREE(mac.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Buffer asnArr[HITLS_PKCS12_MACDATA_MAX_IDX] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, digestInfo.dataLen, digestInfo.data}, {BSL_ASN1_TAG_OCTETSTRING, p12Mac->macSalt->dataLen, p12Mac->macSalt->data}}; ret = BSL_ASN1_EncodeLimb(BSL_ASN1_TAG_INTEGER, p12Mac->iteration, &asnArr[HITLS_PKCS12_MACDATA_ITER_IDX]); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(digestInfo.data); BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Template templ = {g_p12MacDataTempl, sizeof(g_p12MacDataTempl) / sizeof(g_p12MacDataTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, HITLS_PKCS12_MACDATA_MAX_IDX, &encode->data, &encode->dataLen); BSL_SAL_Free(digestInfo.data); BSL_SAL_Free(asnArr[HITLS_PKCS12_MACDATA_ITER_IDX].buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t EncodeCertListAddList(HITLS_PKCS12 *p12, const CRYPT_EncodeParam *encParam, BSL_ASN1_List *list, bool isNeedMac) { int32_t ret; BSL_Buffer certEncode = {0}; if (p12->entityCert != NULL && p12->entityCert->value.cert != NULL) { HITLS_PKCS12_Bag *bag = BSL_SAL_Malloc(sizeof(HITLS_PKCS12_Bag)); if (bag == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } bag->attributes = p12->entityCert->attributes; bag->value.cert = p12->entityCert->value.cert; ret = BSL_LIST_AddElement(p12->certList, bag, BSL_LIST_POS_BEGIN); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(bag); BSL_ERR_PUSH_ERROR(ret); return ret; } } if (BSL_LIST_COUNT(p12->certList) <= 0) { return HITLS_PKI_SUCCESS; } ret = HITLS_PKCS12_EncodeAsn1List(p12, p12->certList, BSL_CID_CERTBAG, NULL, &certEncode); if (p12->entityCert != NULL && p12->entityCert->value.cert != NULL) { BSL_LIST_First(p12->certList); BSL_LIST_DeleteCurrent(p12->certList, NULL); } if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer contentInfoEncode = {0}; if (isNeedMac) { ret = HITLS_PKCS12_EncodeContentInfo(p12->libCtx, p12->attrName, &certEncode, BSL_CID_PKCS7_ENCRYPTEDDATA, encParam, &contentInfoEncode); } else { ret = HITLS_PKCS12_EncodeContentInfo(p12->libCtx, p12->attrName, &certEncode, BSL_CID_PKCS7_SIMPLEDATA, encParam, &contentInfoEncode); } BSL_SAL_FREE(certEncode.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_AddListItemDefault(&contentInfoEncode, sizeof(BSL_Buffer), list); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(contentInfoEncode.data); BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t EncodeUnitListAddList(HITLS_PKCS12 *p12, const CRYPT_EncodeParam *encParam, BSL_ASN1_List *list, bool isNeedMac, BSL_ASN1_List *uintBags) { if (BSL_LIST_COUNT(uintBags) <= 0) { return HITLS_PKI_SUCCESS; } BSL_Buffer uintEncode = {0}; HITLS_PKCS12_Bag *bag = BSL_LIST_GET_FIRST(uintBags); int32_t ret = HITLS_PKCS12_EncodeAsn1List(p12, uintBags, bag->id, NULL, &uintEncode); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer contentInfoEncode = {0}; if (isNeedMac) { ret = HITLS_PKCS12_EncodeContentInfo(p12->libCtx, p12->attrName, &uintEncode, BSL_CID_PKCS7_ENCRYPTEDDATA, encParam, &contentInfoEncode); } else { ret = HITLS_PKCS12_EncodeContentInfo(p12->libCtx, p12->attrName, &uintEncode, BSL_CID_PKCS7_SIMPLEDATA, encParam, &contentInfoEncode); } BSL_SAL_FREE(uintEncode.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_AddListItemDefault(&contentInfoEncode, sizeof(BSL_Buffer), list); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(contentInfoEncode.data); BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t EncodeShroudedKeyAddList(HITLS_PKCS12 *p12, const CRYPT_EncodeParam *encParam, BSL_ASN1_List *list) { if (p12->key == NULL || p12->key->value.key == NULL) { return HITLS_PKI_SUCCESS; } BSL_ASN1_List *keyList = BSL_LIST_New(sizeof(HITLS_PKCS12_Bag)); if (keyList == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } HITLS_PKCS12_Bag bag = {0}; BSL_Buffer keyEncode = {0}; BSL_Buffer contentInfoEncode = {0}; bag.attributes = p12->key->attributes; bag.value.key = p12->key->value.key; int32_t ret = HITLS_X509_AddListItemDefault(&bag, sizeof(HITLS_PKCS12_Bag), keyList); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(keyList); BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_PKCS12_EncodeAsn1List(p12, keyList, BSL_CID_PKCS8SHROUDEDKEYBAG, encParam, &keyEncode); BSL_LIST_FREE(keyList, NULL); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_PKCS12_EncodeContentInfo(p12->libCtx, p12->attrName, &keyEncode, BSL_CID_PKCS7_SIMPLEDATA, NULL, &contentInfoEncode); BSL_SAL_FREE(keyEncode.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_AddListItemDefault(&contentInfoEncode, sizeof(BSL_Buffer), list); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(contentInfoEncode.data); BSL_ERR_PUSH_ERROR(ret); } return ret; } static void FreeBuffer(void *buffer) { if (buffer == NULL) { return; } BSL_Buffer *tmp = (BSL_Buffer *)buffer; BSL_SAL_FREE(tmp->data); BSL_SAL_Free(tmp); } static int32_t EncodePkcs12(uint32_t version, BSL_Buffer *authSafe, BSL_Buffer *macData, BSL_Buffer *encode) { BSL_ASN1_Buffer asnArr[HITLS_PKCS12_TOPLEVEL_MAX_IDX] = { { .buff = NULL, .len = 0, .tag = BSL_ASN1_TAG_INTEGER, }, { .buff = authSafe->data, .len = authSafe->dataLen, .tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, }, { .buff = macData->data, .len = macData->dataLen, .tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, }}; int32_t ret = BSL_ASN1_EncodeLimb(BSL_ASN1_TAG_INTEGER, version, asnArr); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Template templ = {g_p12TopLevelTempl, sizeof(g_p12TopLevelTempl) / sizeof(g_p12TopLevelTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, HITLS_PKCS12_TOPLEVEL_MAX_IDX, &encode->data, &encode->dataLen); BSL_SAL_Free(asnArr[HITLS_PKCS12_TOPLEVEL_VERSION_IDX].buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t EncodeP12Info(HITLS_PKCS12 *p12, const HITLS_PKCS12_EncodeParam *encodeParam, bool isNeedMac, BSL_Buffer *encode) { BSL_ASN1_List *list = BSL_LIST_New(sizeof(BSL_Buffer)); if (list == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } // encode certBags. int32_t ret = EncodeCertListAddList(p12, &encodeParam->encParam, list, isNeedMac); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(list, FreeBuffer); return ret; } // encode shrouded key bags. ret = EncodeShroudedKeyAddList(p12, &encodeParam->encParam, list); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(list, FreeBuffer); return ret; } // encode keyBags. ret = EncodeUnitListAddList(p12, &encodeParam->encParam, list, isNeedMac, p12->keyList); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(list, FreeBuffer); return ret; } // encode secretBags. ret = EncodeUnitListAddList(p12, &encodeParam->encParam, list, isNeedMac, p12->secretBags); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(list, FreeBuffer); return ret; } if (BSL_LIST_COUNT(list) <= 0) { BSL_SAL_Free(list); BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NONE_DATA); return HITLS_PKCS12_ERR_NONE_DATA; } BSL_Buffer initData = {0}; ret = HITLS_PKCS12_EncodeAsn1List(p12, list, BSL_CID_PKCS7_CONTENTINFO, NULL, &initData); BSL_LIST_FREE(list, FreeBuffer); if (ret != HITLS_PKI_SUCCESS) { return ret; } BSL_Buffer macData = {0}; if (isNeedMac) { ret = HITLS_PKCS12_EncodeMacData(p12, &initData, &encodeParam->macParam, &macData); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(initData.data); return ret; } } BSL_Buffer authSafe = {0}; ret = HITLS_PKCS12_EncodeContentInfo(p12->libCtx, p12->attrName, &initData, BSL_CID_PKCS7_SIMPLEDATA, NULL, &authSafe); BSL_SAL_FREE(initData.data); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(macData.data); return ret; } ret = EncodePkcs12(p12->version, &authSafe, &macData, encode); BSL_SAL_FREE(authSafe.data); BSL_SAL_FREE(macData.data); return ret; } int32_t HITLS_PKCS12_GenBuff(int32_t format, HITLS_PKCS12 *p12, const HITLS_PKCS12_EncodeParam *encodeParam, bool isNeedMac, BSL_Buffer *encode) { if (p12 == NULL || encodeParam == NULL || encode == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (encode->data != NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } switch (format) { case BSL_FORMAT_ASN1: return EncodeP12Info(p12, encodeParam, isNeedMac, encode); default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_FORMAT_UNSUPPORT); return HITLS_PKCS12_ERR_FORMAT_UNSUPPORT; } } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_PKCS12_GenFile(int32_t format, HITLS_PKCS12 *p12, const HITLS_PKCS12_EncodeParam *encodeParam, bool isNeedMac, const char *path) { if (path == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } BSL_Buffer encode = {0}; int32_t ret = HITLS_PKCS12_GenBuff(format, p12, encodeParam, isNeedMac, &encode); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_SAL_WriteFile(path, encode.data, encode.dataLen); BSL_SAL_Free(encode.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif static void DeleteAttribute(HITLS_PKCS12_Bag *bag, uint32_t type) { if (bag->attributes == NULL) { return; } BSL_ASN1_List *list = bag->attributes->list; HITLS_PKCS12_SafeBagAttr *node = BSL_LIST_GET_FIRST(list); while (node != NULL) { if (node->attrId == type) { return BSL_LIST_DeleteCurrent(list, HITLS_PKCS12_AttributesFree); } node = BSL_LIST_GET_NEXT(list); } return; } static bool IsAttrExist(HITLS_PKCS12_Bag *bag, uint32_t type) { if (bag->attributes == NULL || bag->attributes->list == NULL) { return false; } BSL_ASN1_List *list = bag->attributes->list; HITLS_PKCS12_SafeBagAttr *node = BSL_LIST_GET_FIRST(list); while (node != NULL) { if (node->attrId == type) { return true; } node = BSL_LIST_GET_NEXT(list); } return false; } int32_t HITLS_PKCS12_BagAddAttr(HITLS_PKCS12_Bag *bag, uint32_t type, const BSL_Buffer *attrValue) { if (bag == NULL || attrValue == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (attrValue->data == NULL || attrValue->dataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } if (type != BSL_CID_LOCALKEYID && type != BSL_CID_FRIENDLYNAME) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES); return HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES; } if (IsAttrExist(bag, type)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_ATTR_REPEAT); return HITLS_X509_ERR_SET_ATTR_REPEAT; } HITLS_PKCS12_SafeBagAttr attr = {0}; attr.attrId = type; attr.attrValue.data = BSL_SAL_Dump(attrValue->data, attrValue->dataLen); if (attr.attrValue.data == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } attr.attrValue.dataLen = attrValue->dataLen; if (bag->attributes == NULL) { bag->attributes = HITLS_X509_AttrsNew(); if (bag->attributes == NULL) { BSL_SAL_FREE(attr.attrValue.data); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } } int32_t ret = HITLS_X509_AddListItemDefault(&attr, sizeof(HITLS_PKCS12_SafeBagAttr), bag->attributes->list); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(attr.attrValue.data); BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t PKCS12_SetEntityKey(HITLS_PKCS12 *p12, void *val) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (p12->key != NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_REPEATED_SET_KEY); return HITLS_PKCS12_ERR_REPEATED_SET_KEY; } HITLS_PKCS12_Bag *input = (HITLS_PKCS12_Bag *)val; if (input->id != BSL_CID_PKCS8SHROUDEDKEYBAG) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } if (input->value.key == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } int32_t ret = HITLS_PKCS12_BagRefUp(input); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } p12->key = input; return HITLS_PKI_SUCCESS; } static int32_t PKCS12_SetEntityCert(HITLS_PKCS12 *p12, void *val) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (p12->entityCert != NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_REPEATED_SET_ENTITYCERT); return HITLS_PKCS12_ERR_REPEATED_SET_ENTITYCERT; } HITLS_PKCS12_Bag *input = (HITLS_PKCS12_Bag *)val; if (input->id != BSL_CID_CERTBAG) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } if (input->value.cert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } int32_t ret = HITLS_PKCS12_BagRefUp(input); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } p12->entityCert = input; return HITLS_PKI_SUCCESS; } static int32_t PKCS12_AddUnitBag(HITLS_PKCS12 *p12, void *val) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } int32_t ret; HITLS_PKCS12_Bag *input = (HITLS_PKCS12_Bag *)val; BSL_ASN1_List *bagList = NULL; switch (input->id) { case BSL_CID_SECRETBAG: bagList = p12->secretBags; break; case BSL_CID_KEYBAG: bagList = p12->keyList; if (input->value.key == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } break; case BSL_CID_CERTBAG: if (input->value.cert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } bagList = p12->certList; break; default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } ret = HITLS_PKCS12_BagRefUp(input); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_LIST_AddElement(bagList, input, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { HITLS_PKCS12_BagFree(input); BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t PKCS12_SetLocalKeyId(HITLS_PKCS12 *p12, CRYPT_MD_AlgId *algId, uint32_t algIdLen) { if (algId == NULL || p12->entityCert == NULL || p12->key == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (algIdLen != sizeof(CRYPT_MD_AlgId)) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } if (p12->entityCert->value.cert == NULL || p12->key->value.key == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NO_PAIRED_CERT_AND_KEY); return HITLS_PKCS12_ERR_NO_PAIRED_CERT_AND_KEY; } uint32_t mdSize = CRYPT_EAL_MdGetDigestSize(*algId); if (mdSize == 0) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } uint8_t *md = BSL_SAL_Malloc(mdSize); if (md == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = HITLS_X509_CertDigest(p12->entityCert->value.cert, *algId, md, &mdSize); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(md); BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer buffer = {.data = md, .dataLen = mdSize}; ret = HITLS_PKCS12_BagAddAttr(p12->key, BSL_CID_LOCALKEYID, &buffer); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(md); BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_PKCS12_BagAddAttr(p12->entityCert, BSL_CID_LOCALKEYID, &buffer); BSL_SAL_Free(md); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); DeleteAttribute(p12->key, BSL_CID_LOCALKEYID); } return ret; } #endif // HITLS_PKI_PKCS12_GEN static int32_t PKCS12_GetEntityCert(HITLS_PKCS12 *p12, int32_t cmd, void **val) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (*val != NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } if (p12->entityCert == NULL || p12->entityCert->value.cert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NO_ENTITYCERT); return HITLS_PKCS12_ERR_NO_ENTITYCERT; } if (cmd == HITLS_PKCS12_GET_ENTITY_CERT) { int ref; int32_t ret = HITLS_X509_CertCtrl(p12->entityCert->value.cert, HITLS_X509_REF_UP, &ref, sizeof(int)); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *val = p12->entityCert->value.cert; } else if (cmd == HITLS_PKCS12_GET_ENTITY_CERTBAG) { int32_t ret = HITLS_PKCS12_BagRefUp(p12->entityCert); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *val = p12->entityCert; } return HITLS_PKI_SUCCESS; } static int32_t PKCS12_GetEntityKey(HITLS_PKCS12 *p12, int32_t cmd, void **val) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (*val != NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } if (p12->key == NULL || p12->key->value.key == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NO_ENTITYKEY); return HITLS_PKCS12_ERR_NO_ENTITYKEY; } if (cmd == HITLS_PKCS12_GET_ENTITY_KEY) { int32_t ret = CRYPT_EAL_PkeyUpRef(p12->key->value.key); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *val = p12->key->value.key; } else if (cmd == HITLS_PKCS12_GET_ENTITY_KEYBAG) { int32_t ret = HITLS_PKCS12_BagRefUp(p12->key); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *val = p12->key; } return HITLS_PKI_SUCCESS; } static int32_t PKCS12_GetKeyBags(HITLS_PKCS12 *p12, void **val) { if (p12->keyList == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (val == NULL || *val != NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } *val = p12->keyList; return HITLS_PKI_SUCCESS; } static int32_t PKCS12_GetSecretBags(HITLS_PKCS12 *p12, void **val) { if (p12->secretBags == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (val == NULL || *val != NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } *val = p12->secretBags; return HITLS_PKI_SUCCESS; } static int32_t PKCS12_GetCertBags(HITLS_PKCS12 *p12, void **val) { if (p12->certList == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (val == NULL || *val != NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } *val = p12->certList; return HITLS_PKI_SUCCESS; } int32_t HITLS_PKCS12_Ctrl(HITLS_PKCS12 *p12, int32_t cmd, void *val, uint32_t valType) { #ifndef HITLS_PKI_PKCS12_GEN (void)valType; #endif if (p12 == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } switch (cmd) { #ifdef HITLS_PKI_PKCS12_GEN case HITLS_PKCS12_GEN_LOCALKEYID: return PKCS12_SetLocalKeyId(p12, val, valType); case HITLS_PKCS12_SET_ENTITY_KEYBAG: return PKCS12_SetEntityKey(p12, val); case HITLS_PKCS12_SET_ENTITY_CERTBAG: return PKCS12_SetEntityCert(p12, val); case HITLS_PKCS12_ADD_CERTBAG: case HITLS_PKCS12_ADD_SECRETBAG: case HITLS_PKCS12_ADD_KEYBAG: return PKCS12_AddUnitBag(p12, val); #endif case HITLS_PKCS12_GET_ENTITY_CERT: case HITLS_PKCS12_GET_ENTITY_CERTBAG: return PKCS12_GetEntityCert(p12, cmd, val); case HITLS_PKCS12_GET_ENTITY_KEY: case HITLS_PKCS12_GET_ENTITY_KEYBAG: return PKCS12_GetEntityKey(p12, cmd, val); case HITLS_PKCS12_GET_CERTBAGS: return PKCS12_GetCertBags(p12, val); case HITLS_PKCS12_GET_SECRETBAGS: return PKCS12_GetSecretBags(p12, val); case HITLS_PKCS12_GET_KEYBAGS: return PKCS12_GetKeyBags(p12, val); default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_PKCS12
2301_79861745/bench_create
pki/pkcs12/src/hitls_pkcs12_common.c
C
unknown
70,387
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_PKCS12 #include "bsl_sal.h" #ifdef HITLS_BSL_SAL_FILE #include "sal_file.h" #endif #include "securec.h" #include "hitls_pkcs12_local.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "hitls_pki_errno.h" #include "crypt_eal_mac.h" #include "crypt_eal_md.h" #include "hitls_cert_local.h" #include "crypt_eal_rand.h" #include "crypt_errno.h" #include "hitls_pki_pkcs12.h" #include "hitls_pki_cert.h" void HITLS_PKCS12_AttributesFree(void *attribute) { if (attribute == NULL) { return; } HITLS_PKCS12_SafeBagAttr *attr = attribute; BSL_SAL_FREE(attr->attrValue.data); BSL_SAL_FREE(attr); } void HITLS_PKCS12_SafeBagFree(HITLS_PKCS12_SafeBag *safeBag) { if (safeBag == NULL) { return; } HITLS_X509_AttrsFree(safeBag->attributes, HITLS_PKCS12_AttributesFree); safeBag->attributes = NULL; BSL_SAL_CleanseData(safeBag->bag->data, safeBag->bag->dataLen); BSL_SAL_FREE(safeBag->bag->data); BSL_SAL_FREE(safeBag->bag); BSL_SAL_Free(safeBag); return; } HITLS_PKCS12_MacData *HITLS_PKCS12_MacDataNew(void) { HITLS_PKCS12_MacData *macData = BSL_SAL_Calloc(1u, sizeof(HITLS_PKCS12_MacData)); if (macData == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } BSL_Buffer *macSalt = BSL_SAL_Calloc(1u, sizeof(BSL_Buffer)); if (macSalt == NULL) { BSL_SAL_Free(macData); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } BSL_Buffer *mac = BSL_SAL_Calloc(1u, sizeof(BSL_Buffer)); if (mac == NULL) { BSL_SAL_Free(macSalt); BSL_SAL_Free(macData); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } macData->mac = mac; macData->macSalt = macSalt; return macData; } void HITLS_PKCS12_MacDataFree(HITLS_PKCS12_MacData *macData) { if (macData == NULL) { return; } if (macData->mac != NULL) { BSL_SAL_FREE(macData->mac->data); BSL_SAL_Free(macData->mac); } if (macData->macSalt != NULL) { BSL_SAL_CleanseData(macData->macSalt->data, macData->macSalt->dataLen); BSL_SAL_FREE(macData->macSalt->data); BSL_SAL_Free(macData->macSalt); } BSL_SAL_Free(macData); } HITLS_PKCS12 *HITLS_PKCS12_New(void) { HITLS_PKCS12 *p12 = BSL_SAL_Calloc(1u, sizeof(HITLS_PKCS12)); if (p12 == NULL) { return NULL; } p12->macData = HITLS_PKCS12_MacDataNew(); if (p12->macData == NULL) { BSL_SAL_Free(p12); return NULL; } p12->certList = BSL_LIST_New(sizeof(HITLS_PKCS12_Bag)); if (p12->certList == NULL) { HITLS_PKCS12_Free(p12); return NULL; } p12->secretBags = BSL_LIST_New(sizeof(HITLS_PKCS12_Bag)); if (p12->secretBags == NULL) { HITLS_PKCS12_Free(p12); return NULL; } p12->keyList = BSL_LIST_New(sizeof(HITLS_PKCS12_Bag)); if (p12->keyList == NULL) { HITLS_PKCS12_Free(p12); return NULL; } p12->version = 3; // RFC7292 required the version = 3; return p12; } HITLS_PKCS12 *HITLS_PKCS12_ProviderNew(HITLS_PKI_LibCtx *libCtx, const char *attrName) { HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); if (p12 == NULL) { return NULL; } p12->libCtx = libCtx; p12->attrName = attrName; return p12; } void HITLS_PKCS12_Free(HITLS_PKCS12 *p12) { if (p12 == NULL) { return; } HITLS_PKCS12_BagFree(p12->entityCert); HITLS_PKCS12_BagFree(p12->key); BSL_LIST_FREE(p12->certList, (BSL_LIST_PFUNC_FREE)HITLS_PKCS12_BagFree); BSL_LIST_FREE(p12->secretBags, (BSL_LIST_PFUNC_FREE)HITLS_PKCS12_BagFree); BSL_LIST_FREE(p12->keyList, (BSL_LIST_PFUNC_FREE)HITLS_PKCS12_BagFree); HITLS_PKCS12_MacDataFree(p12->macData); BSL_SAL_Free(p12); } /* PKCS8ShroudedKeyBag and KeyBag didn't needs to set bagType. */ static int32_t SetKeyBag(HITLS_PKCS12_Bag *bag, void *value) { int32_t ret = CRYPT_EAL_PkeyUpRef((CRYPT_EAL_PkeyCtx *)value); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } bag->value.key = (CRYPT_EAL_PkeyCtx *)value; return HITLS_PKI_SUCCESS; } static int32_t SetCertBag(HITLS_PKCS12_Bag *bag, void *value, uint32_t bagType) { int32_t ref; if (bagType != BSL_CID_X509CERTIFICATE) { // now only support x509 certificate. BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } int32_t ret = HITLS_X509_CertCtrl((HITLS_X509_Cert *)value, HITLS_X509_REF_UP, &ref, sizeof(int32_t)); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } bag->value.cert = (HITLS_X509_Cert *)value; bag->type = bagType; return HITLS_PKI_SUCCESS; } static int32_t SetSecretBag(HITLS_PKCS12_Bag *bag, void *value, uint32_t bagType) { BSL_Buffer *tmp = (BSL_Buffer *)value; if (tmp->data == NULL || tmp->dataLen == 0) { bag->value.secret.dataLen = 0; bag->type = bagType; return HITLS_PKI_SUCCESS; } bag->value.secret.data = BSL_SAL_Dump(tmp->data, tmp->dataLen); if (bag->value.secret.data == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } bag->value.secret.dataLen = tmp->dataLen; bag->type = bagType; return HITLS_PKI_SUCCESS; } static int32_t BagSetValue(HITLS_PKCS12_Bag *bag, void *value, uint32_t bagId, uint32_t bagType) { switch (bagId) { case BSL_CID_KEYBAG: case BSL_CID_PKCS8SHROUDEDKEYBAG: return SetKeyBag(bag, value); case BSL_CID_CERTBAG: return SetCertBag(bag, value, bagType); case BSL_CID_SECRETBAG: return SetSecretBag(bag, value, bagType); default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } } HITLS_PKCS12_Bag *HITLS_PKCS12_BagNew(uint32_t bagId, uint32_t bagType, void *bagValue) { if (bagValue == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return NULL; } HITLS_PKCS12_Bag *bag = BSL_SAL_Calloc(1u, sizeof(HITLS_PKCS12_Bag)); if (bag == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } if (BagSetValue(bag, bagValue, bagId, bagType) != HITLS_PKI_SUCCESS) { BSL_SAL_Free(bag); return NULL; } bag->id = bagId; BSL_SAL_ReferencesInit(&(bag->references)); return bag; } void HITLS_PKCS12_BagFree(HITLS_PKCS12_Bag *bag) { if (bag == NULL) { return; } int ret = 0; BSL_SAL_AtomicDownReferences(&(bag->references), &ret); if (ret > 0) { return; } switch (bag->id) { case BSL_CID_KEYBAG: case BSL_CID_PKCS8SHROUDEDKEYBAG: CRYPT_EAL_PkeyFreeCtx(bag->value.key); break; case BSL_CID_CERTBAG: if (bag->type == BSL_CID_X509CERTIFICATE) { HITLS_X509_CertFree(bag->value.cert); } break; case BSL_CID_SECRETBAG: BSL_SAL_CleanseData(bag->value.secret.data, bag->value.secret.dataLen); BSL_SAL_FREE(bag->value.secret.data); break; default: break; } HITLS_X509_AttrsFree(bag->attributes, HITLS_PKCS12_AttributesFree); BSL_SAL_ReferencesFree(&(bag->references)); BSL_SAL_Free(bag); return; } typedef struct { CRYPT_MD_AlgId alg; uint32_t u; uint32_t v; } Pkcs12KdfParam; /* * The data comes from RFC7292. * https://datatracker.ietf.org/doc/html/rfc7292#appendix-B.2 */ const Pkcs12KdfParam PKCS12KDF_PARAM[] = { {.alg = CRYPT_MD_SHA224, .u = 28, .v = 64}, {.alg = CRYPT_MD_SHA256, .u = 32, .v = 64}, {.alg = CRYPT_MD_SHA384, .u = 48, .v = 128}, {.alg = CRYPT_MD_SHA512, .u = 64, .v = 128}, {.alg = CRYPT_MD_SM3, .u = 32, .v = 64}, }; const Pkcs12KdfParam *FindKdfParam(CRYPT_MD_AlgId id) { const Pkcs12KdfParam *param = NULL; uint32_t num = sizeof(PKCS12KDF_PARAM) / sizeof(PKCS12KDF_PARAM[0]); for (uint32_t i = 0; i < num; i++) { if (PKCS12KDF_PARAM[i].alg == id) { param = &PKCS12KDF_PARAM[i]; return param; } } return NULL; } static int32_t InitKdfParam(const Pkcs12KdfParam *param, uint8_t **D, uint8_t **A, uint8_t **B) { *D = BSL_SAL_Malloc(param->v); *A = BSL_SAL_Malloc(param->u); *B = BSL_SAL_Malloc(param->v); if (*D == NULL || *A == NULL || *B == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); BSL_SAL_FREE(*D); BSL_SAL_FREE(*B); BSL_SAL_FREE(*A); return BSL_MALLOC_FAIL; } return HITLS_PKI_SUCCESS; } static int32_t MacLoop(uint32_t LoopTimes, CRYPT_EAL_MdCTX *ctx, const Pkcs12KdfParam *param, uint8_t *D, uint8_t *I, uint8_t *A, uint32_t k, uint32_t dataLen) { int32_t ret; uint32_t tempLen = param->u; /* A = H(H(H(... H(D || I)))) */ ret = CRYPT_EAL_MdInit(ctx); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_MdUpdate(ctx, D, param->v); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_MdUpdate(ctx, I, k); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_MdFinal(ctx, A, &tempLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } CRYPT_EAL_MdDeinit(ctx); if (LoopTimes != 0) { for (uint32_t j = 0; j < LoopTimes - 1; j++) { ret = CRYPT_EAL_MdInit(ctx); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_MdUpdate(ctx, A, dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_MdFinal(ctx, A, &dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } CRYPT_EAL_MdDeinit(ctx); } } return ret; } static void KdfUpdate(uint8_t *I, uint8_t *A, uint8_t *B, uint32_t k, const Pkcs12KdfParam *param) { /* Concatenate copies of Ai to create a string B */ for (uint32_t l = 0; l < param->v; l++) { B[l] = A[l % param->u]; } /* I_j = (I_j + B + 1) mod 2^v */ for (uint32_t m = 0; m < k; m++) { /* K = ceiling(s/v) + ceiling(p/v) */ uint8_t *tempI = I + m * param->v; uint8_t carry = 1; for (int32_t r = (int32_t)param->v - 1; r >= 0; r--) { uint8_t temp = tempI[r] + carry; carry = temp < tempI[r] ? 1 : 0; temp += B[r]; carry += temp < B[r] ? 1 : 0; tempI[r] = temp; } } } int32_t HITLS_PKCS12_KDF(HITLS_PKCS12 *p12, const uint8_t *pwd, uint32_t pwdLen, HITLS_PKCS12_KDF_IDX type, BSL_Buffer *output) { if (p12 == NULL || output == NULL || output->data == NULL || p12->macData == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (pwd == NULL && pwdLen != 0) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } HITLS_PKCS12_MacData *macData = p12->macData; uint32_t n = output->dataLen; uint32_t iter = macData->iteration; uint8_t *key = output->data; const Pkcs12KdfParam *param = FindKdfParam((CRYPT_MD_AlgId)macData->alg); if (param == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_ALGO); return HITLS_PKCS12_ERR_INVALID_ALGO; } CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_ProviderMdNewCtx(p12->libCtx, (CRYPT_MD_AlgId)macData->alg, p12->attrName); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } uint8_t *D = NULL; uint8_t *A = NULL; uint8_t *B = NULL; uint8_t *I = NULL; int32_t ret = InitKdfParam(param, &D, &A, &B); if (ret != HITLS_PKI_SUCCESS) { CRYPT_EAL_MdFreeCtx(ctx); return ret; } (void)memset_s(D, param->v, type, param->v); uint32_t SLen = param->v * ((macData->macSalt->dataLen + param->v - 1) / param->v); uint32_t PLen = param->v * ((pwdLen + param->v - 1) / param->v); uint32_t k = 0; if (SLen + PLen < SLen) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_KDF_TOO_LONG_INPUT); ret = HITLS_PKCS12_ERR_KDF_TOO_LONG_INPUT; goto EXIT; } k = SLen + PLen; I = BSL_SAL_Calloc(1u, k); if (I == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); ret = BSL_MALLOC_FAIL; goto EXIT; } /* I = S||P */ if (macData->macSalt->data != NULL) { for (uint32_t i = 0; i < SLen; i++) { I[i] = macData->macSalt->data[i % macData->macSalt->dataLen]; } } if (pwd != NULL) { for (uint32_t i = 0; i < PLen; i++) { I[i + SLen] = pwd[i % pwdLen]; } } /* C = ceiling(n/u) */ uint32_t c = (n + param->u - 1) / param->u; for (uint32_t i = 0; i < c; i++) { ret = MacLoop(iter, ctx, param, D, I, A, k, param->u); if (ret != HITLS_PKI_SUCCESS) { goto EXIT; // has pushed err code. } uint32_t copyLen = n > param->u ? param->u : n; if (memcpy_s(key, n, A, copyLen) != EOK) { ret = BSL_MEMCPY_FAIL; BSL_ERR_PUSH_ERROR(BSL_MEMCPY_FAIL); goto EXIT; } n -= copyLen; if (n == 0) { goto EXIT; } key = key + copyLen; KdfUpdate(I, A, B, k / param->v, param); } EXIT: CRYPT_EAL_MdFreeCtx(ctx); BSL_SAL_Free(D); BSL_SAL_CleanseData(I, k); BSL_SAL_Free(I); BSL_SAL_Free(B); BSL_SAL_Free(A); return ret; } static uint32_t GetMacId(BslCid id) { switch ((CRYPT_MD_AlgId)id) { case CRYPT_MD_SHA224: return CRYPT_MAC_HMAC_SHA224; case CRYPT_MD_SHA256: return CRYPT_MAC_HMAC_SHA256; case CRYPT_MD_SHA384: return CRYPT_MAC_HMAC_SHA384; case CRYPT_MD_SHA512: return CRYPT_MAC_HMAC_SHA512; case CRYPT_MD_SM3: return CRYPT_MAC_HMAC_SM3; default: BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_ALGO); return BSL_CID_UNKNOWN; } } static int32_t Utf8ToUtf16(const uint8_t *src, uint8_t *target, uint32_t len) { for (uint32_t i = 0; i < len; i++) { if (src[i] > 127) { // the ascii <= 127. BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PASSWORD); return HITLS_PKCS12_ERR_INVALID_PASSWORD; } target[2 * i + 1] = src[i]; // we need 2 space, [0,0] -> after encode = [0, data]; } return HITLS_PKI_SUCCESS; } static int32_t TransCodePwd(BSL_Buffer *pwd, uint8_t **transcoded, uint32_t *transcodedLen) { if (pwd == NULL || pwd->data == NULL) { *transcodedLen = 0; return HITLS_PKI_SUCCESS; } uint32_t outputLen = 2 * pwd->dataLen + 2; // encodeLen = 2 * len, and two zeros at the end. uint8_t *output = BSL_SAL_Calloc(1u, outputLen); if (output == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = Utf8ToUtf16(pwd->data, output, pwd->dataLen); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_CleanseData(output, outputLen); BSL_SAL_FREE(output); return ret; // has pushed err code. } *transcodedLen = outputLen; *transcoded = output; return HITLS_PKI_SUCCESS; } static int32_t GetHmacKey(HITLS_PKCS12 *p12, BSL_Buffer *pwd, uint32_t macSize, uint8_t **keyData) { uint32_t temPwdLen = 0; uint8_t *temPwd = NULL; int32_t ret = TransCodePwd(pwd, &temPwd, &temPwdLen); if (ret != HITLS_PKI_SUCCESS) { return ret; // has pushed err code. } uint8_t *key = BSL_SAL_Malloc(macSize); if (key == NULL) { BSL_SAL_CleanseData(temPwd, temPwdLen); BSL_SAL_FREE(temPwd); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } BSL_Buffer keyBuffer = {key, macSize}; ret = HITLS_PKCS12_KDF(p12, temPwd, temPwdLen, HITLS_PKCS12_KDF_MACKEY_ID, &keyBuffer); BSL_SAL_CleanseData(temPwd, temPwdLen); BSL_SAL_FREE(temPwd); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_CleanseData(key, macSize); BSL_SAL_FREE(key); return ret; } *keyData = key; return ret; } static int32_t ParamCheckAndInit(HITLS_PKCS12 *p12, BSL_Buffer *pwd, uint32_t *macId, uint32_t *macSize) { if (p12 == NULL || p12->macData == NULL || p12->macData->macSalt == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_NULL_POINTER); return HITLS_PKCS12_ERR_NULL_POINTER; } if (pwd != NULL && pwd->data == NULL && pwd->dataLen != 0) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_PARAM); return HITLS_PKCS12_ERR_INVALID_PARAM; } HITLS_PKCS12_MacData *macData = p12->macData; if (macData->iteration < 1000) { // The nist sp800-132 required the minimum iteration count = 1000. BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_ITERATION); return HITLS_PKCS12_ERR_INVALID_ITERATION; } *macId = GetMacId(macData->alg); *macSize = CRYPT_EAL_MdGetDigestSize((CRYPT_MD_AlgId)macData->alg); if (*macId == BSL_CID_UNKNOWN || *macSize == 0) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_ALGO); return HITLS_PKCS12_ERR_INVALID_ALGO; } if (macData->macSalt->data == NULL) { if (macData->macSalt->dataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_PKCS12_ERR_INVALID_SALTLEN); return HITLS_PKCS12_ERR_INVALID_SALTLEN; } uint8_t *salt = BSL_SAL_Malloc(macData->macSalt->dataLen); if (salt == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = CRYPT_EAL_RandbytesEx(p12->libCtx, salt, macData->macSalt->dataLen); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(salt); BSL_ERR_PUSH_ERROR(ret); return ret; } macData->macSalt->data = salt; } return HITLS_PKI_SUCCESS; } int32_t HITLS_PKCS12_CalMac(HITLS_PKCS12 *p12, BSL_Buffer *pwd, BSL_Buffer *initData, BSL_Buffer *output) { uint32_t macId; uint32_t macSize; int32_t ret = ParamCheckAndInit(p12, pwd, &macId, &macSize); if (ret != HITLS_PKI_SUCCESS) { return ret; } uint8_t *keyData = NULL; ret = GetHmacKey(p12, pwd, macSize, &keyData); if (ret != HITLS_PKI_SUCCESS) { return ret; // has pushed err code. } CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_ProviderMacNewCtx(p12->libCtx, macId, p12->attrName); if (ctx == NULL) { BSL_SAL_CleanseData(keyData, macSize); BSL_SAL_FREE(keyData); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } ret = CRYPT_EAL_MacInit(ctx, keyData, macSize); BSL_SAL_CleanseData(keyData, macSize); BSL_SAL_FREE(keyData); if (ret != HITLS_PKI_SUCCESS) { CRYPT_EAL_MacFreeCtx(ctx); BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_MacUpdate(ctx, initData->data, initData->dataLen); if (ret != HITLS_PKI_SUCCESS) { CRYPT_EAL_MacFreeCtx(ctx); BSL_ERR_PUSH_ERROR(ret); return ret; } uint8_t *temp = BSL_SAL_Malloc(macSize); if (temp == NULL) { CRYPT_EAL_MacFreeCtx(ctx); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } ret = CRYPT_EAL_MacFinal(ctx, temp, &macSize); CRYPT_EAL_MacFreeCtx(ctx); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(temp); BSL_ERR_PUSH_ERROR(ret); return ret; } output->data = temp; output->dataLen = macSize; return ret; } #endif // HITLS_PKI_PKCS12
2301_79861745/bench_create
pki/pkcs12/src/hitls_pkcs12_util.c
C
unknown
20,588
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_PRINT_LOCAL_H #define HITLS_PRINT_LOCAL_H #include "hitls_build.h" #ifdef HITLS_PKI_INFO #include <stdint.h> #include "bsl_uio.h" #ifdef __cplusplus extern "C" { #endif int32_t HITLS_PKI_SetPrintFlag(int32_t val); int32_t HITLS_PKI_GetPrintFlag(void); int32_t HITLS_PKI_PrintDnName(uint32_t layer, BslList *list, bool newLine, BSL_UIO *uio); #ifdef __cplusplus } #endif #endif // HITLS_PKI_INFO #endif // HITLS_PRINT_LOCAL_H
2301_79861745/bench_create
pki/print/include/hitls_print_local.h
C
unknown
992
/** * @copyright Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved. * @file hitls_pki_print.c * @brief x509 print functions. * @create: 2024-09-14 */ #include "hitls_build.h" #ifdef HITLS_PKI_INFO #include <string.h> #include <inttypes.h> #include "bsl_sal.h" #include "bsl_list.h" #include "bsl_asn1_internal.h" #include "bsl_obj_internal.h" #include "bsl_err_internal.h" #include "bsl_print.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "crypt_errno.h" #include "crypt_encode_decode_key.h" #include "crypt_utils.h" #include "hitls_pki_errno.h" #include "hitls_x509_local.h" #ifdef HITLS_PKI_X509_CRT #include "hitls_cert_local.h" #endif #ifdef HITLS_PKI_X509_CSR #include "hitls_csr_local.h" #endif #ifdef HITLS_PKI_X509_CRL #include "hitls_crl_local.h" #include "hitls_pki_crl.h" #endif #include "hitls_pki_utils.h" #include "hitls_print_local.h" #define HITLS_X509_IPV4_LEN 4 #define HITLS_X509_IPV6_LEN 16 #define HITLS_X509_UNKOWN "Unknown\n" #define HITLS_X509_UNSUPPORT "<unsupported>" #define HITLS_X509_UNSUPPORT_N "<unsupported>\n" #define HITLS_X509_V3_EXT "X509V3 extensions:\n" #define HITLS_X509_UNSUPPORT_EXT "<Unsupported extension>\n" #define HITLS_X509_PRINT_NEW_LINE "\n" #if defined(HITLS_PKI_X509_CRT) || defined(HITLS_PKI_X509_CSR) typedef struct { uint32_t type; const char *name; } HITLS_X509_TypeNameMap; static HITLS_X509_TypeNameMap g_keyUsageNameMap[] = { {HITLS_X509_EXT_KU_DIGITAL_SIGN, "Digital Signature"}, {HITLS_X509_EXT_KU_NON_REPUDIATION, "Non Repudiation"}, {HITLS_X509_EXT_KU_KEY_ENCIPHERMENT, "Key Encipherment"}, {HITLS_X509_EXT_KU_DATA_ENCIPHERMENT, "Data Encipherment"}, {HITLS_X509_EXT_KU_KEY_AGREEMENT, "Key Agreement"}, {HITLS_X509_EXT_KU_KEY_CERT_SIGN, "Certificate Sign"}, {HITLS_X509_EXT_KU_CRL_SIGN, "CRL Sign"}, {HITLS_X509_EXT_KU_ENCIPHER_ONLY, "Encipher Only"}, {HITLS_X509_EXT_KU_DECIPHER_ONLY, "Decipher Only"}, }; static HITLS_X509_TypeNameMap g_gnNameMap[] = { {HITLS_X509_GN_OTHER, "OtherName"}, {HITLS_X509_GN_EMAIL, "Email"}, {HITLS_X509_GN_DNS, "DNS"}, {HITLS_X509_GN_X400, "X400Name"}, {HITLS_X509_GN_DNNAME, "DirName"}, {HITLS_X509_GN_EDI, "EdiPartyName"}, {HITLS_X509_GN_URI, "URI"}, {HITLS_X509_GN_IP, "IP Address"}, {HITLS_X509_GN_RID, "Registered ID"}, }; #define HITLS_X509_KU_CNT (sizeof(g_keyUsageNameMap) / sizeof(g_keyUsageNameMap[0])) #define HITLS_X509_GN_NAME_CNT (sizeof(g_gnNameMap) / sizeof(g_gnNameMap[0])) #endif // HITLS_PKI_X509_CRT || HITLS_PKI_X509_CSR static int32_t g_nameFlag = HITLS_PKI_PRINT_DN_RFC2253; static char g_rfc2253Ecsape[] = {',', '+', '"', '\\', '<', '>', ';'}; #define RFC2253_ESCAPE_CHAR_CNT (sizeof(g_rfc2253Ecsape) / sizeof(char)) int32_t HITLS_PKI_SetPrintFlag(int32_t val) { g_nameFlag = val; return HITLS_PKI_SUCCESS; } int32_t HITLS_PKI_GetPrintFlag(void) { return g_nameFlag; } static const char *GetNameByOid(BslOidString *oid) { const char *res = NULL; if (g_nameFlag == HITLS_PKI_PRINT_DN_RFC2253) { BslCid cid = BSL_OBJ_GetCID(oid); const BslAsn1DnInfo *dnInfo = BSL_OBJ_GetDnInfoFromCid(cid); if (dnInfo != NULL) { res = dnInfo->shortName; } if (res == NULL) { res = BSL_OBJ_GetOidNameFromOid(oid); } } else if (g_nameFlag == HITLS_PKI_PRINT_DN_MULTILINE) { res = BSL_OBJ_GetOidNameFromOid(oid); } else { res = BSL_OBJ_GetOidNameFromOid(oid); } return res == NULL ? "Unknown" : res; } static bool NeedQuote(BSL_ASN1_Buffer *value) { if (g_nameFlag != HITLS_PKI_PRINT_DN_ONELINE) { return false; } for (uint32_t i = 0; i < value->len; i++) { if (i == 0 && (value->buff[i] == '#' || value->buff[i] == ' ')) { return true; } if (value->buff[i] == ',' || value->buff[i] == '<' || value->buff[i] == '>') { return true; } } return false; } static bool CharInList(char c, char *list, uint32_t listSize) { for (uint32_t i = 0; i < listSize; i++) { if (c == list[i]) { return true; } } return false; } /* * RFC2253: section 2.4 * The following characters need to be escaped" * (1) a space or "#" character occurring at the beginning of the string * (2) a space character occurring at the end of the string * (3) one of the characters ",", "+", """, "\", "<", ">" or ";" */ static bool Rfc2253Escape(uint8_t *cur, uint64_t c, uint8_t *begin, uint8_t *end) { return g_nameFlag == HITLS_PKI_PRINT_DN_RFC2253 && // RFC 2253 ((cur == begin && (c == ' ' || c == '#')) || // (1) (cur + 1 == end && c == ' ') || // (2) CharInList((char)c, g_rfc2253Ecsape, RFC2253_ESCAPE_CHAR_CNT)); // (3) } static int32_t PrintDnNameValue(BSL_ASN1_Buffer *value, BSL_UIO *uio) { uint8_t *cur = value->buff; uint8_t *end = value->buff + value->len; uint64_t c; char quote = '"'; bool needQuote = NeedQuote(value); if (needQuote && BSL_PRINT_Buff(0, uio, &quote, 1) != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_DNNAME_VALUE); return HITLS_PRINT_ERR_DNNAME_VALUE; } char *fmt; int32_t ret; char tmpC; while (cur != end) { c = *cur; fmt = NULL; tmpC = 0; if (c < ' ' || c > '~') { // control character fmt = "\\%02"PRIX64""; } else if (Rfc2253Escape(cur, c, value->buff, end) == true) { fmt = "\\%c"; tmpC = (char)c; } else if (needQuote && c == '"') { fmt = "\\\""; } if (tmpC != 0) { ret = fmt == NULL ? BSL_PRINT_Buff(0, uio, &tmpC, 1) : BSL_PRINT_Fmt(0, uio, fmt, tmpC); } else { tmpC = (char)c; ret = fmt == NULL ? BSL_PRINT_Buff(0, uio, &tmpC, 1) : BSL_PRINT_Fmt(0, uio, fmt, c); } if (ret != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_DNNAME_VALUE); return HITLS_PRINT_ERR_DNNAME_VALUE; } cur++; } if (needQuote && BSL_PRINT_Buff(0, uio, &quote, 1) != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_DNNAME_VALUE); return HITLS_PRINT_ERR_DNNAME_VALUE; } return HITLS_PKI_SUCCESS; } static char *GetPrefixFmt(bool preLayerIs2, bool isFirst) { if (preLayerIs2) { if (g_nameFlag == HITLS_PKI_PRINT_DN_RFC2253) { return "+%s="; } return " + %s = "; // multiline or oneline } if (g_nameFlag == HITLS_PKI_PRINT_DN_RFC2253) { return isFirst ? "%s=" : ",%s="; } if (g_nameFlag == HITLS_PKI_PRINT_DN_ONELINE) { return isFirst ? "%s = " : ", %s = "; } return "%s = "; // multiline } int32_t HITLS_PKI_PrintDnName(uint32_t layer, BslList *list, bool newLine, BSL_UIO *uio) { BslOidString oid = {0}; const char *oidName = NULL; HITLS_X509_NameNode *name = NULL; bool preLayerIs2 = false; int8_t namePosFlag = -1; // -1: not start; 0: first; 1: others int32_t ret = HITLS_PKI_SUCCESS; for (name = g_nameFlag == HITLS_PKI_PRINT_DN_RFC2253 ? BSL_LIST_GET_LAST(list) : BSL_LIST_GET_FIRST(list); name != NULL; name = g_nameFlag == HITLS_PKI_PRINT_DN_RFC2253 ? BSL_LIST_GET_PREV(list) : BSL_LIST_GET_NEXT(list)) { if (name->layer == 1) { preLayerIs2 = false; continue; } namePosFlag = namePosFlag == -1 ? 0 : 1; oid.octs = (char *)name->nameType.buff; oid.octetLen = name->nameType.len; oidName = GetNameByOid(&oid); /* prefix: name */ if (g_nameFlag == HITLS_PKI_PRINT_DN_MULTILINE) { if (namePosFlag == 0) { // first: Only indent ret = BSL_PRINT_Buff(layer, uio, NULL, 0); } else if (!preLayerIs2) { // not first or multi: Line wrap and indent ret = BSL_PRINT_Fmt(0, uio, "\n") != 0 || BSL_PRINT_Buff(layer, uio, NULL, 0) != 0; } if (ret != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_DNNAME); return HITLS_PRINT_ERR_DNNAME; } } if (BSL_PRINT_Fmt(0, uio, GetPrefixFmt(preLayerIs2, namePosFlag == 0), oidName) != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_DNNAME); return HITLS_PRINT_ERR_DNNAME; } /* value */ if (name->nameValue.buff != NULL && name->nameValue.len != 0) { if (PrintDnNameValue(&name->nameValue, uio) != 0) { return HITLS_PRINT_ERR_DNNAME_VALUE; } } preLayerIs2 = name->layer != 1; } if (newLine) { return BSL_PRINT_Buff(0, uio, HITLS_X509_PRINT_NEW_LINE, strlen(HITLS_X509_PRINT_NEW_LINE)) == 0 ? HITLS_PKI_SUCCESS : HITLS_PRINT_ERR_DNNAME; } return HITLS_PKI_SUCCESS; } #if defined(HITLS_PKI_X509_CRT) || defined(HITLS_PKI_X509_CSR) || defined(HITLS_PKI_X509_CRL) static int32_t PrintBCons(HITLS_X509_Ext *ext, uint32_t layer, BSL_UIO *uio) { HITLS_X509_CertExt *certExt = ext->extData; if (certExt == NULL) { return HITLS_PKI_SUCCESS; } if (certExt->maxPathLen >= 0) { return BSL_PRINT_Fmt(layer, uio, "CA:%s, pathlen:%d\n", certExt->isCa ? "TRUE" : "FALSE", certExt->maxPathLen); } else { return BSL_PRINT_Fmt(layer, uio, "CA:%s\n", certExt->isCa ? "TRUE" : "FALSE"); } } static int32_t PrintKeyUsage(HITLS_X509_Ext *ext, uint32_t layer, BSL_UIO *uio) { HITLS_X509_CertExt *certExt = ext->extData; if (certExt == NULL) { return HITLS_PKI_SUCCESS; } uint32_t cnt = 0; char *fmt = NULL; for (uint32_t i = 0; i < HITLS_X509_KU_CNT; i++) { if ((certExt->keyUsage & g_keyUsageNameMap[i].type) == 0) { continue; } fmt = cnt == 0 ? "%s" : ", %s"; if (BSL_PRINT_Fmt(cnt == 0 ? layer : 0, uio, fmt, g_keyUsageNameMap[i].name) != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_EXT_KU); return HITLS_PRINT_ERR_EXT_KU; } cnt++; } if (cnt == 0) { return HITLS_PKI_SUCCESS; } return BSL_PRINT_Buff(0, uio, HITLS_X509_PRINT_NEW_LINE, strlen(HITLS_X509_PRINT_NEW_LINE)) == 0 ? HITLS_PKI_SUCCESS : HITLS_PRINT_ERR_EXT_KU; } static int32_t PrintIpAddress(BSL_Buffer *ip, uint32_t layer, BSL_UIO *uio) { if (ip->dataLen == HITLS_X509_IPV4_LEN) { return BSL_PRINT_Fmt(layer, uio, "%d.%d.%d.%d", ip->data[0], ip->data[1], ip->data[2], ip->data[3]); // 0,1,2,3: Displays the decimal number of each byte of the IP address. } else if (ip->dataLen == HITLS_X509_IPV6_LEN) { int32_t ret; for (uint32_t i = 0; i < HITLS_X509_IPV6_LEN; i += 2) { // Print 2 bytes at a time. ret = BSL_PRINT_Fmt( layer, uio, (i + 2) == HITLS_X509_IPV6_LEN ? "%X" : "%X:", // Print 2 bytes at a time. ip->data[i] << 8 | ip->data[i + 1]); // left shift 8 bits if (ret != 0) { BSL_ERR_PUSH_ERROR(ret); return ret; } } return HITLS_PKI_SUCCESS; } else { return BSL_PRINT_Fmt(layer, uio, "<invalid lenth=%d>", ip->dataLen); } } static int32_t PrintGeneralName(HITLS_X509_GeneralName *gn, bool first, uint32_t layer, BSL_UIO *uio) { const char *name = NULL; for (uint32_t i = 0; i < HITLS_X509_GN_NAME_CNT; i++) { if (g_gnNameMap[i].type == gn->type) { name = g_gnNameMap[i].name; break; } } if (name == NULL) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_GNNAME_UNKNOWN); return HITLS_PRINT_ERR_GNNAME_UNKNOWN; } int32_t ret = BSL_PRINT_Fmt(layer, uio, first ? "%s:" : ", %s:", name); if (ret != 0) { BSL_ERR_PUSH_ERROR(ret); return ret; } switch (gn->type) { case HITLS_X509_GN_EMAIL: case HITLS_X509_GN_DNS: case HITLS_X509_GN_URI: return BSL_PRINT_Buff(0, uio, gn->value.data, gn->value.dataLen); case HITLS_X509_GN_IP: return PrintIpAddress(&gn->value, 0, uio); case HITLS_X509_GN_DNNAME: return HITLS_PKI_PrintDnName(0, (BslList *)gn->value.data, false, uio); default: return BSL_PRINT_Buff(0, uio, HITLS_X509_UNSUPPORT, strlen(HITLS_X509_UNSUPPORT)); } } static int32_t PrintGeneralNames(BslList *list, uint32_t layer, BSL_UIO *uio) { uint32_t cnt = 0; int32_t ret; for (HITLS_X509_GeneralName *gn = BSL_LIST_GET_FIRST(list); gn != NULL; gn = BSL_LIST_GET_NEXT(list)) { ret = PrintGeneralName(gn, cnt == 0, cnt == 0 ? layer : 0, uio); if (ret != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_GNNAME); return HITLS_PRINT_ERR_GNNAME; } cnt++; } if (cnt == 0) { return HITLS_PKI_SUCCESS; } return BSL_PRINT_Buff(0, uio, HITLS_X509_PRINT_NEW_LINE, strlen(HITLS_X509_PRINT_NEW_LINE)) == 0 ? HITLS_PKI_SUCCESS : HITLS_PRINT_ERR_GNNAME; } static int32_t PrintAki(HITLS_X509_ExtEntry *entry, uint32_t layer, BSL_UIO *uio) { HITLS_X509_ExtAki aki = {0}; int32_t ret = HITLS_X509_ParseAuthorityKeyId(entry, &aki); if (ret != HITLS_PKI_SUCCESS) { return ret; } if (aki.kid.data != NULL) { if (BSL_PRINT_Fmt(layer, uio, "Keyid: ") != 0 || BSL_PRINT_Hex(0, true, aki.kid.data, aki.kid.dataLen, uio) != 0) { HITLS_X509_ClearAuthorityKeyId(&aki); BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_EXT_AKI_KID); return HITLS_PRINT_ERR_EXT_AKI_KID; } } if (aki.issuerName != NULL) { if (PrintGeneralNames(aki.issuerName, layer, uio) != 0) { HITLS_X509_ClearAuthorityKeyId(&aki); BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_EXT_AKI_ISSUER); return HITLS_PRINT_ERR_EXT_AKI_ISSUER; } } if (aki.serialNum.data != NULL) { if (BSL_PRINT_Fmt(layer, uio, "Serial: ") != 0 || BSL_PRINT_Hex(0, true, aki.serialNum.data, aki.serialNum.dataLen, uio) != 0) { HITLS_X509_ClearAuthorityKeyId(&aki); BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_EXT_AKI_SERIAL); return HITLS_PRINT_ERR_EXT_AKI_SERIAL; } } HITLS_X509_ClearAuthorityKeyId(&aki); return HITLS_PKI_SUCCESS; } static int32_t PrintSki(HITLS_X509_ExtEntry *entry, uint32_t layer, BSL_UIO *uio) { HITLS_X509_ExtSki ski = {0}; int32_t ret = HITLS_X509_ParseSubjectKeyId(entry, &ski); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (ski.kid.data != NULL) { if (BSL_PRINT_Hex(layer, true, ski.kid.data, ski.kid.dataLen, uio) != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_EXT_SKI); return HITLS_PRINT_ERR_EXT_SKI; } } return HITLS_PKI_SUCCESS; } static int32_t PrintSan(HITLS_X509_ExtEntry *entry, uint32_t layer, BSL_UIO *uio) { HITLS_X509_ExtSan san = {0}; int32_t ret = HITLS_X509_ParseSubjectAltName(entry, &san); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (BSL_LIST_COUNT(san.names) == 0) { HITLS_X509_ClearSubjectAltName(&san); return HITLS_PKI_SUCCESS; } ret = PrintGeneralNames(san.names, layer, uio); HITLS_X509_ClearSubjectAltName(&san); return ret; } static int32_t PrintExtendedKeyUsage(HITLS_X509_ExtEntry *entry, uint32_t layer, BSL_UIO *uio) { HITLS_X509_ExtExKeyUsage exKu = {0}; int32_t ret = HITLS_X509_ParseExtendedKeyUsage(entry, &exKu); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t cnt = 0; char *fmt = NULL; BslOidString oidStr = {0}; for (BSL_Buffer *oid = BSL_LIST_GET_FIRST(exKu.oidList); oid != NULL; oid = BSL_LIST_GET_NEXT(exKu.oidList)) { fmt = cnt == 0 ? "%s" : ", %s"; oidStr.octs = (char *)oid->data; oidStr.octetLen = oid->dataLen; const char *name = BSL_OBJ_GetOidNameFromOid(&oidStr); if (name == NULL) { if (BSL_PRINT_Fmt(cnt == 0 ? layer : 0, uio, fmt, HITLS_X509_UNKOWN) != 0) { HITLS_X509_ClearExtendedKeyUsage(&exKu); BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_EXT_EXTKU); return HITLS_PRINT_ERR_EXT_EXTKU; } } else { if (BSL_PRINT_Fmt(cnt == 0 ? layer : 0, uio, fmt, name) != 0) { HITLS_X509_ClearExtendedKeyUsage(&exKu); BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_EXT_EXTKU); return HITLS_PRINT_ERR_EXT_EXTKU; } } cnt++; } HITLS_X509_ClearExtendedKeyUsage(&exKu); if (cnt == 0) { return HITLS_PKI_SUCCESS; } return BSL_PRINT_Buff(0, uio, HITLS_X509_PRINT_NEW_LINE, strlen(HITLS_X509_PRINT_NEW_LINE)) == 0 ? HITLS_PKI_SUCCESS : HITLS_PRINT_ERR_EXT_EXTKU; } static int32_t PrintCrlNumber(HITLS_X509_Ext *ext, uint32_t layer, BSL_UIO *uio) { HITLS_X509_ExtCrlNumber number = {0}; int32_t ret = X509_ExtCtrl(ext, HITLS_X509_EXT_GET_CRLNUMBER, &number, sizeof(HITLS_X509_ExtCrlNumber)); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return BSL_PRINT_Number(layer, NULL, number.crlNumber.data, number.crlNumber.dataLen, uio); } static int32_t PrintExt(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, uint32_t layer, BSL_UIO *uio) { switch (entry->cid) { case BSL_CID_CE_BASICCONSTRAINTS: return PrintBCons(ext, layer, uio); case BSL_CID_CE_KEYUSAGE: return PrintKeyUsage(ext, layer, uio); case BSL_CID_CE_AUTHORITYKEYIDENTIFIER: return PrintAki(entry, layer, uio); case BSL_CID_CE_SUBJECTKEYIDENTIFIER: return PrintSki(entry, layer, uio); case BSL_CID_CE_SUBJECTALTNAME: return PrintSan(entry, layer, uio); case BSL_CID_CE_EXTKEYUSAGE: return PrintExtendedKeyUsage(entry, layer, uio); case BSL_CID_CE_CRLNUMBER: return PrintCrlNumber(ext, layer, uio); default: return BSL_PRINT_Buff(layer, uio, HITLS_X509_UNSUPPORT_N, strlen(HITLS_X509_UNSUPPORT_N)) == 0 ? HITLS_PKI_SUCCESS : HITLS_PRINT_ERR_EXT; } } static int32_t PrintX509Ext(HITLS_X509_Ext *ext, bool isCertExt, uint32_t layer, BSL_UIO *uio) { int32_t count = BSL_LIST_COUNT(ext->extList); if (count == 0) { return HITLS_PKI_SUCCESS; } if (isCertExt) { if (BSL_PRINT_Buff(layer, uio, HITLS_X509_V3_EXT, strlen(HITLS_X509_V3_EXT)) != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_EXT_NAME); return HITLS_PRINT_ERR_EXT_NAME; } } HITLS_X509_ExtEntry *entry = BSL_LIST_GET_FIRST(ext->extList); const char *extName = NULL; int32_t ret; int32_t tmpNameFlag = g_nameFlag; g_nameFlag = HITLS_PKI_PRINT_DN_RFC2253; /* The ext content must be printed in one line. Therefore, the format of dirname is RFC2253. */ for (entry = BSL_LIST_GET_FIRST(ext->extList); entry != NULL; entry = BSL_LIST_GET_NEXT(ext->extList)) { extName = BSL_OBJ_GetOidNameFromCID(entry->cid); if (extName == NULL) { if (BSL_PRINT_Buff(layer + 1, uio, HITLS_X509_UNSUPPORT_EXT, strlen(HITLS_X509_UNSUPPORT_EXT)) != 0) { g_nameFlag = tmpNameFlag; BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_EXT_NAME); return HITLS_PRINT_ERR_EXT_NAME; } continue; } if (BSL_PRINT_Fmt(layer + 1, uio, "%s:%s\n", extName, entry->critical ? " critical" : "") != 0) { g_nameFlag = tmpNameFlag; BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_EXT_NAME); return HITLS_PRINT_ERR_EXT_NAME; } ret = PrintExt(ext, entry, layer + 1 + 1, uio); if (ret != HITLS_PKI_SUCCESS) { g_nameFlag = tmpNameFlag; BSL_ERR_PUSH_ERROR(ret); return ret; } } g_nameFlag = tmpNameFlag; return HITLS_PKI_SUCCESS; } static const char *GetPkeyAlgName(CRYPT_EAL_PkeyCtx *pkey) { CRYPT_RsaPadType padType = 0; int32_t ret; switch (CRYPT_EAL_PkeyGetId(pkey)) { case CRYPT_PKEY_RSA: { ret = CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(CRYPT_RsaPadType)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return HITLS_X509_UNSUPPORT; } const char *name = BSL_OBJ_GetOidNameFromCID(padType == CRYPT_EMSA_PSS ? BSL_CID_RSASSAPSS : BSL_CID_RSA); return name == NULL ? HITLS_X509_UNSUPPORT : name; } case CRYPT_PKEY_ECDSA: case CRYPT_PKEY_SM2: { const char *name = BSL_OBJ_GetOidNameFromCID(BSL_CID_EC_PUBLICKEY); return name == NULL ? HITLS_X509_UNSUPPORT : name; } default: return HITLS_X509_UNSUPPORT; } } static int32_t PrintPubKey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio) { const char *name = GetPkeyAlgName(pkey); if (BSL_PRINT_Fmt(layer, uio, "Subject Public Key Info:\n") != 0 || BSL_PRINT_Fmt(layer + 1, uio, "Public Key Algorithm: %s\n", name) != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_PUBKEY); return HITLS_PRINT_ERR_PUBKEY; } return CRYPT_EAL_PrintPubkey(layer + 1 + 1, pkey, uio); } static int32_t PrintSignAlgInfo(uint32_t layer, HITLS_X509_Asn1AlgId *algId, BSL_UIO *uio) { const char *name = BSL_OBJ_GetOidNameFromCID(algId->algId); if (name == NULL) { name = HITLS_X509_UNKOWN; } if (BSL_PRINT_Fmt(layer, uio, "Signature Algorithm: %s\n", name) != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_SIGN_ALG); return HITLS_PRINT_ERR_SIGN_ALG; } if (algId->algId == BSL_CID_RSASSAPSS) { #ifdef HITLS_CRYPTO_RSA return CRYPT_EAL_PrintRsaPssPara(layer + 1, &algId->rsaPssParam, uio); #else return HITLS_PRINT_ERR_SIGN_ALG_UNSUPPORT; #endif } return HITLS_PKI_SUCCESS; } #endif #ifdef HITLS_PKI_X509_CRT static int32_t PrintCertTbs(uint32_t layer, HITLS_X509_CertTbs *tbs, BSL_UIO *uio) { /* version */ RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Version: %d (0x%02x)\n", tbs->version + 1, tbs->version) != 0, HITLS_PRINT_ERR_CERT_TBS); /* serial number */ RETURN_RET_IF( BSL_PRINT_Number(layer, "Serial Number", tbs->serialNum.buff, tbs->serialNum.len, uio) != 0, HITLS_PRINT_ERR_CERT_TBS); /* signature algorithm */ int32_t ret = PrintSignAlgInfo(layer, &tbs->signAlgId, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* issuer */ RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, g_nameFlag == HITLS_PKI_PRINT_DN_MULTILINE ? "Issuer: \n" : "Issuer: ") != 0, HITLS_PRINT_ERR_DNNAME); ret = HITLS_PKI_PrintDnName(layer + 1, tbs->issuerName, true, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* validity */ RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Validity:\n") != 0, HITLS_PRINT_ERR_CERT_TBS); RETURN_RET_IF(BSL_PRINT_Fmt(layer + 1, uio, "Not Before: ") != 0 || BSL_PRINT_Time(0, &tbs->validTime.start, uio) != 0, HITLS_PRINT_ERR_CERT_TBS); RETURN_RET_IF(BSL_PRINT_Fmt(layer + 1, uio, "Not After : ") != 0 || BSL_PRINT_Time(0, &tbs->validTime.end, uio) != 0, HITLS_PRINT_ERR_CERT_TBS); /* subject */ RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, g_nameFlag == HITLS_PKI_PRINT_DN_MULTILINE ? "Subject: \n" : "Subject: ") != 0, HITLS_PRINT_ERR_DNNAME); ret = HITLS_PKI_PrintDnName(layer + 1, tbs->subjectName, true, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* pubkey info */ ret = PrintPubKey(layer, tbs->ealPubKey, uio); if (ret != HITLS_PKI_SUCCESS) { return ret; } /* extensions */ return PrintX509Ext(&tbs->ext, true, layer, uio); } static int32_t PrintCert(void *val, BSL_UIO *uio) { uint32_t layer = 0; HITLS_X509_Cert *cert = (HITLS_X509_Cert *)val; if (BSL_PRINT_Fmt(layer++, uio, "Certificate:\n") != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_CERT); return HITLS_PRINT_ERR_CERT; } if (BSL_PRINT_Fmt(layer, uio, "Data:\n") != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_CERT); return HITLS_PRINT_ERR_CERT; } int32_t ret = PrintCertTbs(layer + 1, &cert->tbs, uio); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = PrintSignAlgInfo(layer, &cert->signAlgId, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return BSL_PRINT_Number(layer, "Signature Value", cert->signature.buff, cert->signature.len, uio); } #endif #ifdef HITLS_PKI_X509_CSR static int32_t PrintReqExtension(BSL_ASN1_Buffer *reqExtension, uint32_t layer, BSL_UIO *uio) { HITLS_X509_Ext *ext = HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CSR); if (ext == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = HITLS_X509_ParseExt(reqExtension, ext); if (ret != BSL_SUCCESS) { HITLS_X509_ExtFree(ext); BSL_ERR_PUSH_ERROR(ret); return ret; } ret = PrintX509Ext(ext, false, layer, uio); HITLS_X509_ExtFree(ext); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t PrintAttr(HITLS_X509_AttrEntry *entry, uint32_t layer, BSL_UIO *uio) { switch (entry->cid) { case BSL_CID_EXTENSIONREQUEST: return PrintReqExtension(&entry->attrValue, layer, uio); default: return HITLS_X509_ERR_ATTR_UNSUPPORT; } } static int32_t PrintAttrs(BslList *attrs, uint32_t layer, BSL_UIO *uio) { if (BSL_PRINT_Fmt(layer, uio, "Attributes:\n") != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_CSR_INFO); return HITLS_PRINT_ERR_CSR_INFO; } int32_t count = BSL_LIST_COUNT(attrs); if (count == 0) { if (BSL_PRINT_Fmt(layer + 1, uio, "(none)\n") != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_CSR_INFO); return HITLS_PRINT_ERR_CSR_INFO; } } if (BSL_PRINT_Fmt(layer + 1, uio, "Requested Extensions:\n") != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_CSR_INFO); return HITLS_PRINT_ERR_CSR_INFO; } if (count == 0) { return HITLS_PKI_SUCCESS; } int32_t ret; for (HITLS_X509_AttrEntry *entry = BSL_LIST_GET_FIRST(attrs); entry != NULL; entry = BSL_LIST_GET_NEXT(attrs)) { ret = PrintAttr(entry, layer + 1, uio); if (ret != HITLS_PKI_SUCCESS) { return ret; } } return HITLS_PKI_SUCCESS; } static int32_t PrintCsrReqInfo(uint32_t layer, HITLS_X509_ReqInfo *reqInfo, BSL_UIO *uio) { /* version */ RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Version: %d (0x%02x)\n", reqInfo->version + 1, reqInfo->version) != 0, HITLS_PRINT_ERR_CSR_INFO); /* subject name */ RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, g_nameFlag == HITLS_PKI_PRINT_DN_MULTILINE ? "Subject: \n" : "Subject: ") != 0, HITLS_PRINT_ERR_DNNAME); int32_t ret = HITLS_PKI_PrintDnName(layer + 1, reqInfo->subjectName, true, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* pubkey info */ ret = PrintPubKey(layer, reqInfo->ealPubKey, uio); if (ret != HITLS_PKI_SUCCESS) { return ret; } return PrintAttrs(reqInfo->attributes->list, layer, uio); } static int32_t PrintCsr(void *val, BSL_UIO *uio) { uint32_t layer = 0; HITLS_X509_Csr *csr = (HITLS_X509_Csr *)val; if (BSL_PRINT_Fmt(layer++, uio, "Certificate Request:\n") != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_CERT); return HITLS_PRINT_ERR_CERT; } if (BSL_PRINT_Fmt(layer, uio, "Data:\n") != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_CERT); return HITLS_PRINT_ERR_CERT; } int32_t ret = PrintCsrReqInfo(layer + 1, &csr->reqInfo, uio); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = PrintSignAlgInfo(layer, &csr->signAlgId, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return BSL_PRINT_Number(layer, "Signature Value", csr->signature.buff, csr->signature.len, uio); } #endif #ifdef HITLS_PKI_X509_CRL static int32_t CmpExtByCid(const void *pExt, const void *pCid) { const HITLS_X509_ExtEntry *ext = pExt; BslCid cid = *(const BslCid *)pCid; return cid == ext->cid ? 0 : 1; } static int32_t PrintCrlReason(HITLS_X509_ExtEntry *extEntry, uint32_t layer, BSL_UIO *uio) { int32_t reason = -1; int32_t ret = HITLS_ParseCrlExtReason(extEntry, &reason); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "X509v3 CRL Reason Code: %s\n", extEntry->critical ? "critical" : "") != 0, HITLS_PRINT_ERR_CRL_TBS); RETURN_RET_IF(BSL_PRINT_Fmt(layer + 1, uio, "%d\n", reason) != 0, HITLS_PRINT_ERR_CRL_TBS); return HITLS_PKI_SUCCESS; } static int32_t PrintInvalidTime(HITLS_X509_ExtEntry *extEntry, uint32_t layer, BSL_UIO *uio) { BSL_TIME time = {0}; int32_t ret = HITLS_ParseCrlExtInvalidTime(extEntry, &time); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Invalidity Date: %s\n", extEntry->critical ? "critical" : "") != 0, HITLS_PRINT_ERR_CRL_TBS); RETURN_RET_IF(BSL_PRINT_Time(layer + 1, &time, uio) != 0, HITLS_PRINT_ERR_CRL_TBS); return HITLS_PKI_SUCCESS; } static int32_t PrintCertificateIssuer(HITLS_X509_ExtEntry *extEntry, uint32_t layer, BSL_UIO *uio) { HITLS_X509_RevokeExtCertIssuer issuer = {0}; int32_t ret = HITLS_X509_ParseSubjectAltName(extEntry, (HITLS_X509_ExtSan *)&issuer); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (BSL_LIST_COUNT(issuer.issuerName) == 0) { HITLS_X509_ClearSubjectAltName((HITLS_X509_ExtSan *)&issuer); return HITLS_PKI_SUCCESS; } RETURN_RET_IF( BSL_PRINT_Fmt(layer, uio, "X509v3 Certificate Issuer: %s\n", extEntry->critical ? "critical" : "") != 0, HITLS_PRINT_ERR_CRL_TBS); ret = PrintGeneralNames(issuer.issuerName, layer + 1, uio); HITLS_X509_ClearSubjectAltName((HITLS_X509_ExtSan *)&issuer); return ret; } static int32_t PrintCrlEntry(uint32_t layer, HITLS_X509_CrlEntry *crlEntry, BSL_UIO *uio) { int32_t ret; BslCid cid = BSL_CID_CE_CRLREASONS; HITLS_X509_ExtEntry *extEntry = BSL_LIST_Search(crlEntry->extList, &cid, CmpExtByCid, NULL); if (extEntry != NULL) { ret = PrintCrlReason(extEntry, layer, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } cid = BSL_CID_CE_INVALIDITYDATE; extEntry = BSL_LIST_Search(crlEntry->extList, &cid, CmpExtByCid, NULL); if (extEntry != NULL) { ret = PrintInvalidTime(extEntry, layer, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } cid = BSL_CID_CE_CERTIFICATEISSUER; extEntry = BSL_LIST_Search(crlEntry->extList, &cid, CmpExtByCid, NULL); if (extEntry != NULL) { ret = PrintCertificateIssuer(extEntry, layer, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } return HITLS_PKI_SUCCESS; } static int32_t PrintRevokedCertificates(uint32_t layer, BSL_ASN1_List *revokedCerts, BSL_UIO *uio) { int32_t ret; HITLS_X509_CrlEntry *crlEntry = BSL_LIST_GET_FIRST(revokedCerts); while (crlEntry != NULL) { /* serial number */ RETURN_RET_IF(BSL_PRINT_Number( layer, "Serial Number", crlEntry->serialNumber.buff, crlEntry->serialNumber.len, uio) != 0, HITLS_PRINT_ERR_CRL_TBS); RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Revocation Date: ") != 0 || BSL_PRINT_Time(0, &crlEntry->time, uio) != 0, HITLS_PRINT_ERR_CRL_TBS); if (crlEntry->extList != NULL) { RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "CRL entry extensions:\n") != 0, HITLS_PRINT_ERR_CRL_TBS); ret = PrintCrlEntry(layer + 1, crlEntry, uio); if (ret != HITLS_PKI_SUCCESS) { return ret; } } crlEntry = BSL_LIST_GET_NEXT(revokedCerts); } return HITLS_PKI_SUCCESS; } static int32_t PrintCrlTbs(uint32_t layer, HITLS_X509_CrlTbs *tbs, BSL_UIO *uio) { /* version */ RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Version: %d (0x%02x)\n", tbs->version + 1, tbs->version) != 0, HITLS_PRINT_ERR_CRL_TBS); /* signature algorithm */ int32_t ret = PrintSignAlgInfo(layer, &tbs->signAlgId, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* issuer */ RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, g_nameFlag == HITLS_PKI_PRINT_DN_MULTILINE ? "Issuer: \n" : "Issuer: ") != 0, HITLS_PRINT_ERR_DNNAME); ret = HITLS_PKI_PrintDnName(layer + 1, tbs->issuerName, true, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Last Update: ") != 0 || BSL_PRINT_Time(0, &tbs->validTime.start, uio) != 0, HITLS_PRINT_ERR_CRL_TBS); RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Next Update: ") != 0 || BSL_PRINT_Time(0, &tbs->validTime.end, uio) != 0, HITLS_PRINT_ERR_CRL_TBS); if (tbs->revokedCerts != NULL) { RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Revoked Certificates:\n") != 0, HITLS_PRINT_ERR_CRL_TBS); ret = PrintRevokedCertificates(layer + 1, tbs->revokedCerts, uio); if (ret != HITLS_PKI_SUCCESS) { return ret; } } /* CRL extensions */ ret = PrintX509Ext(&tbs->crlExt, true, layer, uio); if (ret != HITLS_PKI_SUCCESS) { return ret; } /* signature algorithm */ ret = PrintSignAlgInfo(layer, &tbs->signAlgId, uio); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return HITLS_PKI_SUCCESS; } static int32_t PrintCrl(void *val, BSL_UIO *uio) { uint32_t layer = 0; HITLS_X509_Crl *crl = (HITLS_X509_Crl *)val; if (BSL_PRINT_Fmt(layer, uio, "Certificate Revocation List (CRL):\n") != 0) { BSL_ERR_PUSH_ERROR(HITLS_PRINT_ERR_CRL); return HITLS_PRINT_ERR_CRL; } int32_t ret = PrintCrlTbs(layer + 1, &crl->tbs, uio); if (ret != HITLS_PKI_SUCCESS) { return ret; } return BSL_PRINT_Number(layer + 1, "Signature Value", crl->signature.buff, crl->signature.len, uio); } #endif static int32_t PrintDnNameHash(uint32_t layer, BslList *list, BSL_UIO *uio) { BSL_ASN1_Buffer name = {0}; uint32_t nameHash = 0; uint8_t md[20] = {0}; // 20: CRYPT_SHA1_DIGESTSIZE uint32_t mdLen = 20; // 20: CRYPT_SHA1_DIGESTSIZE int32_t ret = HITLS_X509_EncodeCanonNameList(list, &name); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = CRYPT_EAL_Md(CRYPT_MD_SHA1, name.buff, name.len, md, &mdLen); BSL_SAL_Free(name.buff); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } nameHash = (((uint32_t)md[0]) | // 1st byte ((uint32_t)md[1] << 8) | // 2(1+1)nd byte, shift left by 8 bits. ((uint32_t)md[2] << 16) | // 3(2+1)rd byte, shift left by 16 bits. ((uint32_t)md[3] << 24)); // 4(3+1)th byte, shift left by 24 bits. return BSL_PRINT_Fmt(layer, uio, "%08x\n", nameHash) == 0 ? HITLS_PKI_SUCCESS : HITLS_PRINT_ERR_DNNAME_HASH; } int32_t HITLS_PKI_PrintCtrl(int32_t cmd, void *val, uint32_t valLen, BSL_UIO *uio) { if (cmd == HITLS_PKI_SET_PRINT_FLAG) { return (val != NULL && valLen == sizeof(int32_t)) ? HITLS_PKI_SetPrintFlag(*(int32_t *)val) : HITLS_X509_ERR_INVALID_PARAM; } if (val == NULL || uio == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (cmd) { case HITLS_PKI_PRINT_DNNAME: if (valLen != sizeof(BslList)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } return HITLS_PKI_PrintDnName(g_nameFlag == HITLS_PKI_PRINT_DN_MULTILINE ? 1 : 0, val, true, uio); case HITLS_PKI_PRINT_DNNAME_HASH: if (valLen != sizeof(BslList)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } return PrintDnNameHash(0, val, uio); #ifdef HITLS_PKI_X509_CRT case HITLS_PKI_PRINT_CERT: if (valLen != sizeof(HITLS_X509_Cert *)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } return PrintCert(val, uio); #endif case HITLS_PKI_PRINT_NEXTUPDATE: if (valLen != sizeof(BSL_TIME)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } return BSL_PRINT_Time(0, val, uio); #ifdef HITLS_PKI_X509_CSR case HITLS_PKI_PRINT_CSR: if (valLen != sizeof(HITLS_X509_Csr *)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } return PrintCsr(val, uio); #endif #ifdef HITLS_PKI_X509_CRL case HITLS_PKI_PRINT_CRL: if (valLen != sizeof(HITLS_X509_Crl *)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } return PrintCrl(val, uio); #endif default: return HITLS_X509_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_INFO
2301_79861745/bench_create
pki/print/src/hitls_pki_print.c
C
unknown
38,712
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_CERT_LOCAL_H #define HITLS_CERT_LOCAL_H #include "hitls_build.h" #ifdef HITLS_PKI_X509_CRT #include <stdint.h> #include "bsl_asn1_internal.h" #include "bsl_obj.h" #include "sal_atomic.h" #include "hitls_x509_local.h" #ifdef __cplusplus extern "C" { #endif typedef struct { uint8_t *tbsRawData; uint32_t tbsRawDataLen; int32_t version; BSL_ASN1_Buffer serialNum; HITLS_X509_Asn1AlgId signAlgId; BSL_ASN1_List *issuerName; HITLS_X509_ValidTime validTime; BSL_ASN1_List *subjectName; void *ealPubKey; HITLS_X509_Ext ext; } HITLS_X509_CertTbs; typedef enum { HITLS_X509_CERT_STATE_NEW = 0, HITLS_X509_CERT_STATE_SET, HITLS_X509_CERT_STATE_SIGN, HITLS_X509_CERT_STATE_GEN, } HITLS_X509_CERT_STATE; typedef struct _HITLS_X509_Cert { uint8_t flag; // Used to mark certificate parsing or generation, indicating resource release behavior. uint8_t state; uint8_t *rawData; uint32_t rawDataLen; HITLS_X509_CertTbs tbs; HITLS_X509_Asn1AlgId signAlgId; BSL_ASN1_BitString signature; BSL_SAL_RefCount references; CRYPT_EAL_LibCtx *libCtx; // Provider context const char *attrName; // Provider attribute name } HITLS_X509_Cert; #ifdef HITLS_PKI_X509_VFY int32_t HITLS_X509_CheckIssued(HITLS_X509_Cert *issue, HITLS_X509_Cert *subject, bool *res); bool HITLS_X509_CertIsCA(HITLS_X509_Cert *cert); #endif #ifdef __cplusplus } #endif #endif // HITLS_PKI_X509_CRT #endif // HITLS_CERT_LOCAL_H
2301_79861745/bench_create
pki/x509_cert/include/hitls_cert_local.h
C
unknown
2,061
/** * @copyright Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved. * @file hitls_x509_cert.c * @brief x509 certificate resolution. * @create: 2024-07-08 */ #include "hitls_build.h" #ifdef HITLS_PKI_X509_CRT #include <stdio.h> #include "securec.h" #include "bsl_sal.h" #ifdef HITLS_BSL_SAL_FILE #include "sal_file.h" #endif #include "sal_time.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_obj_internal.h" #include "hitls_pki_errno.h" #include "hitls_x509_local.h" #include "crypt_eal_codecs.h" #include "crypt_encode_decode_key.h" #include "crypt_errno.h" #include "crypt_eal_md.h" #ifdef HITLS_BSL_PEM #include "bsl_pem_internal.h" #endif // HITLS_BSL_PEM #include "bsl_err_internal.h" #include "hitls_csr_local.h" #include "hitls_cert_local.h" #ifdef HITLS_PKI_INFO #include "hitls_print_local.h" #endif // HITLS_PKI_INFO #include "hitls_pki_utils.h" #include "hitls_pki_csr.h" #include "hitls_pki_cert.h" #define HITLS_CERT_CTX_SPECIFIC_TAG_VER 0 #define HITLS_CERT_CTX_SPECIFIC_TAG_ISSUERID 1 #define HITLS_CERT_CTX_SPECIFIC_TAG_SUBJECTID 2 #define HITLS_CERT_CTX_SPECIFIC_TAG_EXTENSION 3 #define MAX_DN_STR_LEN 256 #define PRINT_TIME_MAX_SIZE 32 #define HITLS_X509_CERT_PARSE_FLAG 0x01 #define HITLS_X509_CERT_GEN_FLAG 0x02 typedef enum { HITLS_X509_ISSUER_DN_NAME, HITLS_X509_SUBJECT_DN_NAME, } DISTINCT_NAME_TYPE; typedef enum { HITLS_X509_BEFORE_TIME, HITLS_X509_AFTER_TIME, } X509_TIME_TYPE; BSL_ASN1_TemplateItem g_certTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* x509 */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* tbs */ /* 2: version */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CERT_CTX_SPECIFIC_TAG_VER, BSL_ASN1_FLAG_DEFAULT, 2}, {BSL_ASN1_TAG_INTEGER, 0, 3}, /* 2: serial number */ {BSL_ASN1_TAG_INTEGER, 0, 2}, /* 2: signature info */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, {BSL_ASN1_TAG_OBJECT_ID, 0, 3}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 3}, // 8 /* 2: issuer */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 2}, /* 2: validity */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, {BSL_ASN1_TAG_CHOICE, 0, 3}, {BSL_ASN1_TAG_CHOICE, 0, 3}, // 12 /* 2: subject ref: issuer */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 2}, /* 2: subject public key info ref signature info */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 2}, /* 2: issuer id, subject id */ {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_CERT_CTX_SPECIFIC_TAG_ISSUERID, BSL_ASN1_FLAG_OPTIONAL, 2}, {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_CERT_CTX_SPECIFIC_TAG_SUBJECTID, BSL_ASN1_FLAG_OPTIONAL, 2}, /* 2: extension */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CERT_CTX_SPECIFIC_TAG_EXTENSION, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 2}, // 17 {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* signAlg */ {BSL_ASN1_TAG_OBJECT_ID, 0, 2}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 2}, // 20 {BSL_ASN1_TAG_BITSTRING, 0, 1} /* sig */ }; typedef enum { HITLS_X509_CERT_VERSION_IDX = 0, HITLS_X509_CERT_SERIAL_IDX = 1, HITLS_X509_CERT_TBS_SIGNALG_OID_IDX = 2, HITLS_X509_CERT_TBS_SIGNALG_ANY_IDX = 3, HITLS_X509_CERT_ISSUER_IDX = 4, HITLS_X509_CERT_BEFORE_VALID_IDX = 5, HITLS_X509_CERT_AFTER_VALID_IDX = 6, HITLS_X509_CERT_SUBJECT_IDX = 7, HITLS_X509_CERT_SUBKEYINFO_IDX = 8, HITLS_X509_CERT_ISSUERID_IDX = 9, HITLS_X509_CERT_SUBJECTID_IDX = 10, HITLS_X509_CERT_EXT_IDX = 11, HITLS_X509_CERT_SIGNALG_IDX = 12, HITLS_X509_CERT_SIGNALG_ANY_IDX = 13, HITLS_X509_CERT_SIGN_IDX = 14, HITLS_X509_CERT_MAX_IDX = 15, } HITLS_X509_CERT_IDX; #define X509_ASN1_START_TIME_IDX 10 #define X509_ASN1_END_TIME_IDX 11 #define X509_ASN1_TBS_SIGNALG_ANY 7 #define X509_ASN1_SIGNALG_ANY 19 #ifdef HITLS_PKI_X509_CRT_PARSE int32_t HITLS_X509_CertTagGetOrCheck(int32_t type, uint32_t idx, void *data, void *expVal) { switch (type) { case BSL_ASN1_TYPE_CHECK_CHOICE_TAG: { if (idx == X509_ASN1_START_TIME_IDX || idx == X509_ASN1_END_TIME_IDX) { uint8_t tag = *(uint8_t *) data; if ((tag == BSL_ASN1_TAG_UTCTIME) || (tag == BSL_ASN1_TAG_GENERALIZEDTIME)) { *(uint8_t *) expVal = tag; return BSL_SUCCESS; } } return HITLS_X509_ERR_CHECK_TAG; } case BSL_ASN1_TYPE_GET_ANY_TAG: { if (idx == X509_ASN1_TBS_SIGNALG_ANY || idx == X509_ASN1_SIGNALG_ANY) { BSL_ASN1_Buffer *param = (BSL_ASN1_Buffer *)data; BslOidString oidStr = {param->len, (char *)param->buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_UNKNOWN) { return HITLS_X509_ERR_GET_ANY_TAG; } if (cid == BSL_CID_RSASSAPSS) { // note: any can be encoded empty or null *(uint8_t *)expVal = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; return BSL_SUCCESS; } else { *(uint8_t *)expVal = BSL_ASN1_TAG_NULL; // is null return BSL_SUCCESS; } } return HITLS_X509_ERR_GET_ANY_TAG; } default: return HITLS_X509_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_X509_CRT_PARSE void HITLS_X509_CertFree(HITLS_X509_Cert *cert) { if (cert == NULL) { return; } int ret = 0; BSL_SAL_AtomicDownReferences(&(cert->references), &ret); if (ret > 0) { return; } if (cert->flag == HITLS_X509_CERT_GEN_FLAG) { BSL_SAL_FREE(cert->tbs.serialNum.buff); BSL_SAL_FREE(cert->tbs.tbsRawData); BSL_SAL_FREE(cert->signature.buff); BSL_LIST_FREE(cert->tbs.issuerName, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); BSL_LIST_FREE(cert->tbs.subjectName, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); } else { BSL_LIST_FREE(cert->tbs.issuerName, NULL); BSL_LIST_FREE(cert->tbs.subjectName, NULL); } #ifdef HITLS_CRYPTO_SM2 if (cert->signAlgId.algId == BSL_CID_SM2DSAWITHSM3) { BSL_SAL_FREE(cert->signAlgId.sm2UserId.data); } #endif X509_ExtFree(&cert->tbs.ext, false); BSL_SAL_FREE(cert->rawData); CRYPT_EAL_PkeyFreeCtx(cert->tbs.ealPubKey); BSL_SAL_ReferencesFree(&(cert->references)); BSL_SAL_Free(cert); } HITLS_X509_Cert *HITLS_X509_CertNew(void) { BSL_ASN1_List *issuerName = NULL; BSL_ASN1_List *subjectName = NULL; HITLS_X509_Ext *ext = NULL; HITLS_X509_Cert *cert = (HITLS_X509_Cert *)BSL_SAL_Calloc(1, sizeof(HITLS_X509_Cert)); if (cert == NULL) { return NULL; } issuerName = BSL_LIST_New(sizeof(HITLS_X509_NameNode)); if (issuerName == NULL) { goto ERR; } subjectName = BSL_LIST_New(sizeof(HITLS_X509_NameNode)); if (subjectName == NULL) { goto ERR; } ext = X509_ExtNew(&cert->tbs.ext, HITLS_X509_EXT_TYPE_CERT); if (ext == NULL) { goto ERR; } BSL_SAL_ReferencesInit(&(cert->references)); cert->tbs.issuerName = issuerName; cert->tbs.subjectName = subjectName; cert->state = HITLS_X509_CERT_STATE_NEW; return cert; ERR: BSL_SAL_Free(cert); BSL_SAL_Free(issuerName); BSL_SAL_Free(subjectName); return NULL; } #ifdef HITLS_PKI_X509_CRT_PARSE int32_t HITLS_X509_ParseCertTbs(BSL_ASN1_Buffer *asnArr, HITLS_X509_Cert *cert) { int32_t ret; // version: default is 0 if (asnArr[HITLS_X509_CERT_VERSION_IDX].tag != 0) { ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CERT_VERSION_IDX], &cert->tbs.version); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } // serialNum cert->tbs.serialNum = asnArr[HITLS_X509_CERT_SERIAL_IDX]; // sign alg ret = HITLS_X509_ParseSignAlgInfo(&asnArr[HITLS_X509_CERT_TBS_SIGNALG_OID_IDX], &asnArr[HITLS_X509_CERT_TBS_SIGNALG_ANY_IDX], &cert->tbs.signAlgId); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // issuer name ret = HITLS_X509_ParseNameList(&asnArr[HITLS_X509_CERT_ISSUER_IDX], cert->tbs.issuerName); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // validity ret = HITLS_X509_ParseTime(&asnArr[HITLS_X509_CERT_BEFORE_VALID_IDX], &asnArr[HITLS_X509_CERT_AFTER_VALID_IDX], &cert->tbs.validTime); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // subject name ret = HITLS_X509_ParseNameList(&asnArr[HITLS_X509_CERT_SUBJECT_IDX], cert->tbs.subjectName); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // subject public key info BSL_Buffer subPubKeyBuff = {asnArr[HITLS_X509_CERT_SUBKEYINFO_IDX].buff, asnArr[HITLS_X509_CERT_SUBKEYINFO_IDX].len}; ret = CRYPT_EAL_ProviderDecodeBuffKey(cert->libCtx, cert->attrName, BSL_CID_UNKNOWN, "ASN1", "PUBKEY_SUBKEY_WITHOUT_SEQ", &subPubKeyBuff, NULL, (CRYPT_EAL_PkeyCtx **)&cert->tbs.ealPubKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // ext ret = HITLS_X509_ParseExt(&asnArr[HITLS_X509_CERT_EXT_IDX], &cert->tbs.ext); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } return ret; ERR: if (cert->tbs.ealPubKey != NULL) { CRYPT_EAL_PkeyFreeCtx(cert->tbs.ealPubKey); cert->tbs.ealPubKey = NULL; } BSL_LIST_DeleteAll(cert->tbs.issuerName, NULL); BSL_LIST_DeleteAll(cert->tbs.subjectName, NULL); return ret; } int32_t HITLS_X509_ParseAsn1Cert(uint8_t *encode, uint32_t encodeLen, HITLS_X509_Cert *cert) { uint8_t *temp = encode; uint32_t tempLen = encodeLen; cert->rawData = encode; // cert takes over the encode immediately. if ((cert->flag & HITLS_X509_CERT_GEN_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } // template parse BSL_ASN1_Buffer asnArr[HITLS_X509_CERT_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_certTempl, sizeof(g_certTempl) / sizeof(g_certTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, HITLS_X509_CertTagGetOrCheck, &temp, &tempLen, asnArr, HITLS_X509_CERT_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // parse tbs raw data ret = HITLS_X509_ParseTbsRawData(encode, encodeLen, &cert->tbs.tbsRawData, &cert->tbs.tbsRawDataLen); if (ret != HITLS_PKI_SUCCESS) { return ret; } // parse tbs ret = HITLS_X509_ParseCertTbs(asnArr, cert); if (ret != HITLS_PKI_SUCCESS) { return ret; } // parse sign alg ret = HITLS_X509_ParseSignAlgInfo(&asnArr[HITLS_X509_CERT_SIGNALG_IDX], &asnArr[HITLS_X509_CERT_SIGNALG_ANY_IDX], &cert->signAlgId); if (ret != HITLS_PKI_SUCCESS) { goto ERR; } // parse signature ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CERT_SIGN_IDX], &cert->signature); if (ret != BSL_SUCCESS) { goto ERR; } cert->rawDataLen = encodeLen - tempLen; cert->flag |= HITLS_X509_CERT_PARSE_FLAG; return HITLS_PKI_SUCCESS; ERR: CRYPT_EAL_PkeyFreeCtx(cert->tbs.ealPubKey); cert->tbs.ealPubKey = NULL; BSL_LIST_DeleteAll(cert->tbs.issuerName, NULL); BSL_LIST_DeleteAll(cert->tbs.subjectName, NULL); BSL_LIST_DeleteAll(cert->tbs.ext.extList, NULL); return ret; } int32_t HITLS_X509_CertMulParseBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, int32_t format, const BSL_Buffer *encode, HITLS_X509_List **certlist) { int32_t ret; if (encode == NULL || encode->data == NULL || encode->dataLen == 0 || certlist == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } X509_ParseFuncCbk certCbk = { .asn1Parse = (HITLS_X509_Asn1Parse)HITLS_X509_ParseAsn1Cert, .x509ProviderNew = (HITLS_X509_ProviderNew)HITLS_X509_ProviderCertNew, .x509Free = (HITLS_X509_Free)HITLS_X509_CertFree }; HITLS_X509_List *list = BSL_LIST_New(sizeof(HITLS_X509_Cert)); if (list == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } ret = HITLS_X509_ParseX509(libCtx, attrName, format, encode, true, &certCbk, list); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } *certlist = list; return ret; } static int32_t ProviderCertParseBuffInternal(HITLS_PKI_LibCtx *libCtx, const char *attrName, int32_t format, const BSL_Buffer *encode, HITLS_X509_Cert **cert) { HITLS_X509_List *list = NULL; if (cert == NULL || *cert != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t ret = HITLS_X509_CertMulParseBuff(libCtx, attrName, format, encode, &list); if (ret != HITLS_PKI_SUCCESS) { return ret; } HITLS_X509_Cert *tmp = BSL_LIST_GET_FIRST(list); int ref; ret = HITLS_X509_CertCtrl(tmp, HITLS_X509_REF_UP, &ref, sizeof(int)); BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); if (ret != HITLS_PKI_SUCCESS) { return ret; } *cert = tmp; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CertParseBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_Cert **cert) { return ProviderCertParseBuffInternal(NULL, NULL, format, encode, cert); } int32_t HITLS_X509_CertParseBundleBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_List **certlist) { return HITLS_X509_CertMulParseBuff(NULL, NULL, format, encode, certlist); } int32_t HITLS_X509_ProviderCertParseBundleBuff(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const BSL_Buffer *encode, HITLS_X509_List **certlist) { int32_t encodeFormat = CRYPT_EAL_GetEncodeFormat(format); return HITLS_X509_CertMulParseBuff(libCtx, attrName, encodeFormat, encode, certlist); } #ifdef HITLS_BSL_SAL_FILE static int32_t ProviderCertParseBundleFileInternal(HITLS_PKI_LibCtx *libCtx, const char *attrName, int32_t format, const char *path, HITLS_X509_List **certlist) { uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { return ret; } BSL_Buffer encode = {data, dataLen}; ret = HITLS_X509_CertMulParseBuff(libCtx, attrName, format, &encode, certlist); BSL_SAL_Free(data); return ret; } int32_t HITLS_X509_CertParseFile(int32_t format, const char *path, HITLS_X509_Cert **cert) { uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer encode = {data, dataLen}; ret = ProviderCertParseBuffInternal(NULL, NULL, format, &encode, cert); BSL_SAL_Free(data); return ret; } int32_t HITLS_X509_CertParseBundleFile(int32_t format, const char *path, HITLS_X509_List **certlist) { return ProviderCertParseBundleFileInternal(NULL, NULL, format, path, certlist); } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_PKI_X509_CRT_PARSE #ifdef HITLS_PKI_INFO /* RFC2253 https://www.rfc-editor.org/rfc/rfc2253 */ static int32_t X509GetPrintSNStr(const BSL_ASN1_Buffer *nameType, char *buff, uint32_t buffLen, uint32_t *usedLen) { if (nameType == NULL || nameType->buff == NULL || nameType->len == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } BslOidString oid = { .octs = (char *)nameType->buff, .octetLen = nameType->len, }; const char *oidName = BSL_OBJ_GetOidNameFromOid(&oid); if (oidName == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_INVALID_DN); return HITLS_X509_ERR_CERT_INVALID_DN; } if (strcpy_s(buff, buffLen, oidName) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_INVALID_DN); return HITLS_X509_ERR_CERT_INVALID_DN; } *usedLen = (uint32_t)strlen(oidName); return HITLS_PKI_SUCCESS; } static int32_t X509PrintNameNode(const HITLS_X509_NameNode *nameNode, char *buff, uint32_t buffLen, uint32_t *usedLen) { if (nameNode->layer == 1) { return HITLS_PKI_SUCCESS; } uint32_t offset = 0; *usedLen = 0; /* Get the printable type */ int32_t ret = X509GetPrintSNStr(&nameNode->nameType, buff, buffLen, &offset); if (ret != HITLS_PKI_SUCCESS) { return ret; } /* print '=' between type and value */ if (buffLen - offset < 2) { // 2 denote buffer is enough to place two character, i.e '=' and '\0' BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } buff[offset] = '='; offset++; /* print 'value' */ if (nameNode->nameValue.buff == NULL || nameNode->nameValue.len == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (memcpy_s(buff + offset, buffLen - offset, nameNode->nameValue.buff, nameNode->nameValue.len) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_INVALID_DN); return HITLS_X509_ERR_CERT_INVALID_DN; } offset += nameNode->nameValue.len; *usedLen = offset; return HITLS_PKI_SUCCESS; } static int32_t GetDistinguishNameStrFromList(BSL_ASN1_List *nameList, BSL_Buffer *buff) { if (nameList == NULL || BSL_LIST_COUNT(nameList) == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } uint32_t offset = 0; char tmpBuffStr[MAX_DN_STR_LEN] = {0}; char *tmpBuff = tmpBuffStr; uint32_t tmpBuffLen = MAX_DN_STR_LEN; (void)BSL_LIST_GET_FIRST(nameList); HITLS_X509_NameNode *firstNameNode = BSL_LIST_GET_NEXT(nameList); HITLS_X509_NameNode *nameNode = firstNameNode; while (nameNode != NULL) { if (tmpBuffLen - offset < 2) { // 2 denote buffer is enough to place two character, i.e ',' and '\0' BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (nameNode != firstNameNode && nameNode->layer == 2) { // Is 2 nodes. *tmpBuff = ','; tmpBuff++; offset++; } uint32_t eachUsedLen = 0; int32_t ret = X509PrintNameNode(nameNode, tmpBuff, tmpBuffLen - offset, &eachUsedLen); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } tmpBuff += eachUsedLen; offset += eachUsedLen; nameNode = BSL_LIST_GET_NEXT(nameList); } buff->data = BSL_SAL_Calloc(offset + 1, sizeof(char)); if (buff->data == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } (void)memcpy_s(buff->data, offset + 1, tmpBuffStr, offset); buff->dataLen = offset; return HITLS_PKI_SUCCESS; } static int32_t X509_GetDistinguishNameStr(HITLS_X509_Cert *cert, BSL_Buffer *val, int32_t opt) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (opt) { case HITLS_X509_ISSUER_DN_NAME: return GetDistinguishNameStrFromList(cert->tbs.issuerName, val); case HITLS_X509_SUBJECT_DN_NAME: return GetDistinguishNameStrFromList(cert->tbs.subjectName, val); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } static int32_t GetAsn1SerialNumStr(const BSL_ASN1_Buffer *number, BSL_Buffer *val) { if (number == NULL || number->buff == NULL || number->len == 0 || number->tag != BSL_ASN1_TAG_INTEGER || val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } for (size_t i = 0; i < number->len - 1; i++) { if (sprintf_s((char *)&val->data[3 * i], val->dataLen - 3 * i, "%02x:", number->buff[i]) == -1) { // 3: "xx:" BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_INVALID_SERIAL_NUM); return HITLS_X509_ERR_CERT_INVALID_SERIAL_NUM; } } size_t index = 3 * (number->len - 1); // 3: "xx:" if (sprintf_s((char *)&val->data[index], val->dataLen - index, "%02x", number->buff[number->len - 1]) == -1) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_INVALID_SERIAL_NUM); return HITLS_X509_ERR_CERT_INVALID_SERIAL_NUM; } val->dataLen = 3 * number->len - 1; // 3: "xx:" return HITLS_PKI_SUCCESS; } static int32_t X509_GetSerialNumStr(HITLS_X509_Cert *cert, BSL_Buffer *val) { if (val == NULL || cert->tbs.serialNum.buff == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } BSL_ASN1_Buffer serialNum = cert->tbs.serialNum; val->data = BSL_SAL_Calloc(serialNum.len * 3, sizeof(uint8_t)); // "%02x:" Use 3 bytes. if (val->data == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } val->dataLen = serialNum.len * 3; // "%02x:" Use 3 bytes. int32_t ret = GetAsn1SerialNumStr(&serialNum, val); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(val->data); val->dataLen = 0; } return ret; } // rfc822: https://www.w3.org/Protocols/rfc822/ static const char g_monAsn1Str[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static int32_t GetAsn1BslTimeStr(const BSL_TIME *time, BSL_Buffer *val) { if (time == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } val->data = BSL_SAL_Calloc(PRINT_TIME_MAX_SIZE, sizeof(uint8_t)); if (val->data == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } if (sprintf_s((char *)val->data, PRINT_TIME_MAX_SIZE, "%s %u %02u:%02u:%02u %u%s", g_monAsn1Str[time->month - 1], time->day, time->hour, time->minute, time->second, time->year, " GMT") == -1) { BSL_SAL_FREE(val->data); val->dataLen = 0; BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_INVALID_TIME); return HITLS_X509_ERR_CERT_INVALID_TIME; } val->dataLen = (uint32_t)strlen((char *)val->data); return HITLS_PKI_SUCCESS; } static int32_t X509_GetAsn1BslTimeStr(HITLS_X509_Cert *cert, BSL_Buffer *val, int32_t opt) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (opt) { case HITLS_X509_BEFORE_TIME: return GetAsn1BslTimeStr(&cert->tbs.validTime.start, val); case HITLS_X509_AFTER_TIME: return GetAsn1BslTimeStr(&cert->tbs.validTime.end, val); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_INFO static int32_t X509_CertGetCtrl(HITLS_X509_Cert *cert, int32_t cmd, void *val, uint32_t valLen) { switch (cmd) { case HITLS_X509_GET_ENCODELEN: return HITLS_X509_GetEncodeLen(cert->rawDataLen, val, valLen); case HITLS_X509_GET_ENCODE: return HITLS_X509_GetEncodeData(cert->rawData, val); case HITLS_X509_GET_PUBKEY: return HITLS_X509_GetPubKey(cert->tbs.ealPubKey, val); case HITLS_X509_GET_SIGNALG: return HITLS_X509_GetSignAlg(cert->signAlgId.algId, val, valLen); case HITLS_X509_GET_SIGN_MDALG: return HITLS_X509_GetSignMdAlg(&cert->signAlgId, val, (int32_t)valLen); case HITLS_X509_GET_SUBJECT_DN: return HITLS_X509_GetList(cert->tbs.subjectName, val, valLen); case HITLS_X509_GET_ISSUER_DN: return HITLS_X509_GetList(cert->tbs.issuerName, val, valLen); case HITLS_X509_GET_SERIALNUM: return HITLS_X509_GetSerial(&cert->tbs.serialNum, val, valLen); #ifdef HITLS_PKI_INFO case HITLS_X509_GET_SUBJECT_DN_STR: return X509_GetDistinguishNameStr(cert, val, HITLS_X509_SUBJECT_DN_NAME); case HITLS_X509_GET_ISSUER_DN_STR: return X509_GetDistinguishNameStr(cert, val, HITLS_X509_ISSUER_DN_NAME); case HITLS_X509_GET_SERIALNUM_STR: return X509_GetSerialNumStr(cert, val); case HITLS_X509_GET_BEFORE_TIME_STR: return X509_GetAsn1BslTimeStr(cert, val, HITLS_X509_BEFORE_TIME); case HITLS_X509_GET_AFTER_TIME_STR: return X509_GetAsn1BslTimeStr(cert, val, HITLS_X509_AFTER_TIME); #endif // HITLS_PKI_INFO case HITLS_X509_GET_ENCODE_SUBJECT_DN: return HITLS_X509_GetListBuff(cert->tbs.subjectName, val, valLen); case HITLS_X509_IS_SELF_SIGNED: return HITLS_X509_CheckIssued(cert, cert, val); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #ifdef HITLS_PKI_X509_CRT_GEN typedef bool (*SetParamCheck)(const void *val, uint32_t valLen); static bool VersionCheck(const void *val, uint32_t valLen) { return valLen == sizeof(int32_t) && *(const int32_t *)val >= HITLS_X509_VERSION_1 && *(const int32_t *)val <= HITLS_X509_VERSION_3; } static bool TimeCheck(const void *val, uint32_t valLen) { (void)val; return valLen == sizeof(BSL_TIME) && BSL_DateTimeCheck((const BSL_TIME *)val); } static int32_t CertSet(void *dest, uint32_t size, void *val, uint32_t valLen, SetParamCheck check) { if (check(val, valLen) != true) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } (void)memcpy_s(dest, size, val, size); return HITLS_PKI_SUCCESS; } #ifdef HITLS_PKI_X509_CSR static int32_t HITLS_X509_SetCsrExt(HITLS_X509_Ext *ext, HITLS_X509_Csr *csr) { HITLS_X509_Ext *csrExt = NULL; int32_t ret = HITLS_X509_AttrCtrl( csr->reqInfo.attributes, HITLS_X509_ATTR_GET_REQUESTED_EXTENSIONS, &csrExt, sizeof(HITLS_X509_Ext *)); if (ret == HITLS_X509_ERR_ATTR_NOT_FOUND) { return ret; } if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_ExtReplace(ext, csrExt); X509_ExtFree(csrExt, true); return ret; } #endif static int32_t X509_CertSetCtrl(HITLS_X509_Cert *cert, int32_t cmd, void *val, uint32_t valLen) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((cert->flag & HITLS_X509_CERT_PARSE_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_AFTER_PARSE); return HITLS_X509_ERR_SET_AFTER_PARSE; } cert->flag |= HITLS_X509_CERT_GEN_FLAG; cert->state = HITLS_X509_CERT_STATE_SET; int32_t ret; switch (cmd) { case HITLS_X509_SET_VERSION: return CertSet(&cert->tbs.version, sizeof(int32_t), val, valLen, VersionCheck); case HITLS_X509_SET_SERIALNUM: return HITLS_X509_SetSerial(&cert->tbs.serialNum, val, valLen); case HITLS_X509_SET_BEFORE_TIME: ret = CertSet(&cert->tbs.validTime.start, sizeof(BSL_TIME), val, valLen, TimeCheck); if (ret == HITLS_PKI_SUCCESS) { cert->tbs.validTime.flag |= BSL_TIME_BEFORE_SET; cert->tbs.validTime.flag |= cert->tbs.validTime.start.year <= BSL_TIME_UTC_MAX_YEAR ? BSL_TIME_BEFORE_IS_UTC : 0; } return ret; case HITLS_X509_SET_AFTER_TIME: ret = CertSet(&cert->tbs.validTime.end, sizeof(BSL_TIME), val, valLen, TimeCheck); if (ret == HITLS_PKI_SUCCESS) { cert->tbs.validTime.flag |= BSL_TIME_AFTER_SET; cert->tbs.validTime.flag |= cert->tbs.validTime.end.year <= BSL_TIME_UTC_MAX_YEAR ? BSL_TIME_AFTER_IS_UTC : 0; } return ret; case HITLS_X509_SET_PUBKEY: return HITLS_X509_SetPkey(&cert->tbs.ealPubKey, val); case HITLS_X509_SET_ISSUER_DN: return HITLS_X509_SetNameList(&cert->tbs.issuerName, val, valLen); case HITLS_X509_SET_SUBJECT_DN: return HITLS_X509_SetNameList(&cert->tbs.subjectName, val, valLen); #ifdef HITLS_PKI_X509_CSR case HITLS_X509_SET_CSR_EXT: return HITLS_X509_SetCsrExt(&cert->tbs.ext, val); #endif default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_X509_CRT_GEN int32_t HITLS_X509_CertCtrl(HITLS_X509_Cert *cert, int32_t cmd, void *val, uint32_t valLen) { if (cert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (cmd == HITLS_X509_REF_UP) { return HITLS_X509_RefUp(&cert->references, val, valLen); } else if (cmd >= HITLS_X509_GET_ENCODELEN && cmd < HITLS_X509_SET_VERSION) { return X509_CertGetCtrl(cert, cmd, val, valLen); #ifdef HITLS_PKI_X509_CRT_GEN } else if (cmd >= HITLS_X509_SET_VERSION && cmd < HITLS_X509_EXT_SET_SKI) { return X509_CertSetCtrl(cert, cmd, val, valLen); #endif } else if (cmd <= HITLS_X509_EXT_CHECK_SKI) { static int32_t cmdSet[] = {HITLS_X509_EXT_SET_SKI, HITLS_X509_EXT_SET_AKI, HITLS_X509_EXT_SET_KUSAGE, HITLS_X509_EXT_SET_SAN, HITLS_X509_EXT_SET_BCONS, HITLS_X509_EXT_SET_EXKUSAGE, HITLS_X509_EXT_GET_SKI, HITLS_X509_EXT_GET_AKI, HITLS_X509_EXT_CHECK_SKI, HITLS_X509_EXT_GET_KUSAGE}; if (!X509_CheckCmdValid(cmdSet, sizeof(cmdSet) / sizeof(int32_t), cmd)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_UNSUPPORT); return HITLS_X509_ERR_EXT_UNSUPPORT; } return X509_ExtCtrl(&cert->tbs.ext, cmd, val, valLen); } else { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #ifdef HITLS_PKI_X509_CRT_PARSE HITLS_X509_Cert *HITLS_X509_CertDup(HITLS_X509_Cert *src) { if (src == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return NULL; } HITLS_X509_Cert *tempCert = NULL; BSL_Buffer encode = {src->rawData, src->rawDataLen}; int32_t ret = HITLS_X509_ProviderCertParseBuff(src->libCtx, src->attrName, "ASN1", &encode, &tempCert); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return NULL; } return tempCert; } #endif // HITLS_PKI_X509_CRT_PARSE #ifdef HITLS_PKI_X509_VFY /** * Confirm whether the certificate is the issuer of the current certificate * 1. Check if the issueName matches the subjectName * 2. Is the issuer certificate a CA * 3. Check if the algorithm of the issuer certificate matches that of the sub certificate * 4. Check if the certificate keyusage has a certificate sign */ int32_t HITLS_X509_CheckIssued(HITLS_X509_Cert *issue, HITLS_X509_Cert *subject, bool *res) { int32_t ret = HITLS_X509_CmpNameNode(issue->tbs.subjectName, subject->tbs.issuerName); if (ret != HITLS_PKI_SUCCESS) { *res = false; return HITLS_PKI_SUCCESS; } if (issue->tbs.version == HITLS_X509_VERSION_3 && subject->tbs.version == HITLS_X509_VERSION_3) { ret = HITLS_X509_CheckAki(&issue->tbs.ext, &subject->tbs.ext, issue->tbs.issuerName, &issue->tbs.serialNum); if (ret != HITLS_PKI_SUCCESS && ret != HITLS_X509_ERR_VFY_AKI_SKI_NOT_MATCH) { return ret; } if (ret == HITLS_X509_ERR_VFY_AKI_SKI_NOT_MATCH) { *res = false; return HITLS_PKI_SUCCESS; } } /** * If the basic constraints extension is not present in a version 3 certificate, * or the extension is present but the cA boolean is not asserted, * then the certified public key MUST NOT be used to verify certificate signatures. */ HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)issue->tbs.ext.extData; if (issue->tbs.version == HITLS_X509_VERSION_3 && (certExt->extFlags & HITLS_X509_EXT_FLAG_BCONS) == 0 && !certExt->isCa) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_NOT_CA); return HITLS_X509_ERR_CERT_NOT_CA; } ret = HITLS_X509_CheckAlg(issue->tbs.ealPubKey, &subject->tbs.signAlgId); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /** * Conforming CAs MUST include this extension * in certificates that contain public keys that are used to validate digital signatures on * other public key certificates or CRLs. */ if ((certExt->extFlags & HITLS_X509_EXT_FLAG_KUSAGE) != 0) { if (((certExt->keyUsage & HITLS_X509_EXT_KU_KEY_CERT_SIGN)) == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_KU_NO_CERTSIGN); return HITLS_X509_ERR_VFY_KU_NO_CERTSIGN; } } *res = true; return HITLS_PKI_SUCCESS; } bool HITLS_X509_CertIsCA(HITLS_X509_Cert *cert) { HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)cert->tbs.ext.extData; if (cert->tbs.version == HITLS_X509_VERSION_3) { if ((certExt->extFlags & HITLS_X509_EXT_FLAG_BCONS) == 0) { return false; } else { return certExt->isCa; } } return true; } #endif // HITLS_PKI_X509_VFY #ifdef HITLS_PKI_X509_CRT_GEN static int32_t EncodeTbsItems(HITLS_X509_CertTbs *tbs, BSL_ASN1_Buffer *signAlg, BSL_ASN1_Buffer *issuer, BSL_ASN1_Buffer *subject, BSL_ASN1_Buffer *pubkey, BSL_ASN1_Buffer *ext) { BSL_Buffer pub = {0}; int32_t ret = HITLS_X509_EncodeSignAlgInfo(&tbs->signAlgId, signAlg); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_EncodeNameList(tbs->issuerName, issuer); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ret = HITLS_X509_EncodeNameList(tbs->subjectName, subject); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ret = CRYPT_EAL_EncodePubKeyBuffInternal(tbs->ealPubKey, BSL_FORMAT_ASN1, CRYPT_PUBKEY_SUBKEY, false, &pub); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } if (tbs->version == HITLS_X509_VERSION_3) { ret = HITLS_X509_EncodeExt(BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CERT_CTX_SPECIFIC_TAG_EXTENSION, tbs->ext.extList, ext); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } } pubkey->buff = pub.data; pubkey->len = pub.dataLen; return ret; ERR: BSL_SAL_Free(signAlg->buff); BSL_SAL_Free(issuer->buff); BSL_SAL_Free(subject->buff); BSL_SAL_Free(pub.data); return ret; } BSL_ASN1_TemplateItem g_tbsTempl[] = { /* version */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CERT_CTX_SPECIFIC_TAG_VER, BSL_ASN1_FLAG_DEFAULT, 0}, {BSL_ASN1_TAG_INTEGER, BSL_ASN1_FLAG_DEFAULT, 1}, /* serial number */ {BSL_ASN1_TAG_INTEGER, 0, 0}, /* signature info */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* issuer */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 0}, /* validity */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_CHOICE, 0, 1}, {BSL_ASN1_TAG_CHOICE, 0, 1}, /* subject ref: issuer */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 0}, /* subject public key info ref signature info */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 0}, /* Note!!: issuer id, subject id are not supported */ /* extension */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CERT_CTX_SPECIFIC_TAG_EXTENSION, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 0}, }; #define HITLS_X509_CERT_TBS_SIZE 9 static int32_t EncodeTbsCertificate(HITLS_X509_CertTbs *tbs, BSL_ASN1_Buffer *tbsBuff) { BSL_ASN1_Buffer signAlg = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}; BSL_ASN1_Buffer issuer = {0}; BSL_ASN1_Buffer subject = {0}; BSL_ASN1_Buffer pubkey = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}; BSL_ASN1_Buffer ext = {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CERT_CTX_SPECIFIC_TAG_EXTENSION, 0, NULL}; int32_t ret = EncodeTbsItems(tbs, &signAlg, &issuer, &subject, &pubkey, &ext); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint8_t ver = (uint8_t)tbs->version; BSL_ASN1_Template templ = {g_tbsTempl, sizeof(g_tbsTempl) / sizeof(g_tbsTempl[0])}; BSL_ASN1_Buffer asns[HITLS_X509_CERT_TBS_SIZE] = { {BSL_ASN1_TAG_INTEGER, ver == HITLS_X509_VERSION_1 ? 0 : 1, ver == HITLS_X509_VERSION_1 ? NULL : &ver}, // 0 tbs->serialNum, // 1 serial number signAlg, // 2 sigAlg issuer, // 3 issuer {(tbs->validTime.flag & BSL_TIME_BEFORE_IS_UTC) != 0 ? BSL_ASN1_TAG_UTCTIME : BSL_ASN1_TAG_GENERALIZEDTIME, sizeof(BSL_TIME), (uint8_t *)&tbs->validTime.start}, // 4 start {(tbs->validTime.flag & BSL_TIME_AFTER_IS_UTC) != 0 ? BSL_ASN1_TAG_UTCTIME : BSL_ASN1_TAG_GENERALIZEDTIME, sizeof(BSL_TIME), (uint8_t *)&tbs->validTime.end}, // 5 end subject, // 6 subject pubkey, // 7 pubkey info ext, // 8 extensions, only for v3 }; ret = BSL_ASN1_EncodeTemplate(&templ, asns, HITLS_X509_CERT_TBS_SIZE, &tbsBuff->buff, &tbsBuff->len); BSL_SAL_Free(signAlg.buff); BSL_SAL_Free(issuer.buff); BSL_SAL_Free(subject.buff); BSL_SAL_Free(pubkey.buff); if (ver == HITLS_X509_VERSION_3 && ext.buff != NULL) { BSL_SAL_Free(ext.buff); } return ret; } BSL_ASN1_TemplateItem g_briefCertTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* x509 */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* tbs */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* signAlg */ {BSL_ASN1_TAG_BITSTRING, 0, 1} /* sig */ }; #define HITLS_X509_CERT_BRIEF_SIZE 3 static int32_t EncodeAsn1Cert(HITLS_X509_Cert *cert) { if (cert->signature.buff == NULL || cert->signature.len == 0 || cert->tbs.tbsRawData == NULL || cert->tbs.tbsRawDataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_NOT_SIGNED); return HITLS_X509_ERR_CERT_NOT_SIGNED; } BSL_ASN1_Buffer asns[HITLS_X509_CERT_BRIEF_SIZE] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, cert->tbs.tbsRawDataLen, cert->tbs.tbsRawData}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}, {BSL_ASN1_TAG_BITSTRING, sizeof(BSL_ASN1_BitString), (uint8_t *)&cert->signature}, }; uint32_t valLen = 0; int32_t ret = BSL_ASN1_DecodeTagLen(asns[0].tag, &asns[0].buff, &asns[0].len, &valLen); // 0 is tbs if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_EncodeSignAlgInfo(&cert->signAlgId, &asns[1]); // 1 is signAlg if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Template templ = {g_briefCertTempl, sizeof(g_briefCertTempl) / sizeof(g_briefCertTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asns, HITLS_X509_CERT_BRIEF_SIZE, &cert->rawData, &cert->rawDataLen); BSL_SAL_Free(asns[1].buff); return ret; } static int32_t CheckCertTbs(HITLS_X509_Cert *cert) { if (cert == NULL) { return HITLS_X509_ERR_INVALID_PARAM; } if (BSL_LIST_COUNT(cert->tbs.ext.extList) > 0 && cert->tbs.version != HITLS_X509_VERSION_3) { return HITLS_X509_ERR_CERT_INACCURACY_VERSION; } if (cert->tbs.serialNum.buff == NULL || cert->tbs.serialNum.len == 0) { return HITLS_X509_ERR_CERT_INVALID_SERIAL_NUM; } if (BSL_LIST_COUNT(cert->tbs.issuerName) <= 0 || BSL_LIST_COUNT(cert->tbs.subjectName) <= 0) { return HITLS_X509_ERR_CERT_INVALID_DN; } if ((cert->tbs.validTime.flag & BSL_TIME_BEFORE_SET) == 0 || (cert->tbs.validTime.flag & BSL_TIME_AFTER_SET) == 0) { return HITLS_X509_ERR_CERT_INVALID_TIME; } int32_t ret = BSL_SAL_DateTimeCompare(&cert->tbs.validTime.start, &cert->tbs.validTime.end, NULL); if (ret != BSL_TIME_DATE_BEFORE && ret != BSL_TIME_CMP_EQUAL) { return HITLS_X509_ERR_CERT_START_TIME_LATER; } if (cert->tbs.ealPubKey == NULL) { return HITLS_X509_ERR_CERT_INVALID_PUBKEY; } return HITLS_PKI_SUCCESS; } /** * @brief Encode ASN.1 certificate * * @param cert [IN] Pointer to the certificate structure * @param buff [OUT] Pointer to the buffer. * If NULL, only the ASN.1 certificate is encoded. * If non-NULL, the DER encoding content of the certificate is stored in buff * @return int32_t Return value, 0 means success, other values mean failure */ static int32_t HITLS_X509_EncodeAsn1Cert(HITLS_X509_Cert *cert, BSL_Buffer *buff) { int32_t ret; if ((cert->flag & HITLS_X509_CERT_GEN_FLAG) != 0) { if (cert->state != HITLS_X509_CERT_STATE_SIGN && cert->state != HITLS_X509_CERT_STATE_GEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_NOT_SIGNED); return HITLS_X509_ERR_CERT_NOT_SIGNED; } if (cert->state == HITLS_X509_CERT_STATE_SIGN) { ret = EncodeAsn1Cert(cert); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } cert->state = HITLS_X509_CERT_STATE_GEN; } } if (cert->rawData == NULL || cert->rawDataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_NOT_SIGNED); return HITLS_X509_ERR_CERT_NOT_SIGNED; } if (buff == NULL) { return HITLS_PKI_SUCCESS; } buff->data = BSL_SAL_Dump(cert->rawData, cert->rawDataLen); if (buff->data == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } buff->dataLen = cert->rawDataLen; return HITLS_PKI_SUCCESS; } #ifdef HITLS_BSL_PEM int32_t HITLS_X509_EncodePemCert(HITLS_X509_Cert *cert, BSL_Buffer *buff) { int32_t ret = HITLS_X509_EncodeAsn1Cert(cert, NULL); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_PEM_Symbol symbol = {BSL_PEM_CERT_BEGIN_STR, BSL_PEM_CERT_END_STR}; return BSL_PEM_EncodeAsn1ToPem(cert->rawData, cert->rawDataLen, &symbol, (char **)&buff->data, &buff->dataLen); } #endif // HITLS_BSL_PEM int32_t HITLS_X509_CertGenBuff(int32_t format, HITLS_X509_Cert *cert, BSL_Buffer *buff) { if (cert == NULL || buff == NULL || buff->data != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (format) { case BSL_FORMAT_ASN1: return HITLS_X509_EncodeAsn1Cert(cert, buff); #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: return HITLS_X509_EncodePemCert(cert, buff); #endif // HITLS_BSL_PEM default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_X509_CertGenFile(int32_t format, HITLS_X509_Cert *cert, const char *path) { if (path == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } BSL_Buffer encode = {0}; int32_t ret = HITLS_X509_CertGenBuff(format, cert, &encode); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_SAL_WriteFile(path, encode.data, encode.dataLen); BSL_SAL_Free(encode.data); return ret; } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_PKI_X509_CRT_GEN int32_t HITLS_X509_CertDigest(HITLS_X509_Cert *cert, CRYPT_MD_AlgId mdId, uint8_t *data, uint32_t *dataLen) { if (cert == NULL || data == NULL || dataLen == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((cert->flag & HITLS_X509_CERT_PARSE_FLAG) != 0 || (cert->state == HITLS_X509_CERT_STATE_GEN)) { return CRYPT_EAL_Md(mdId, cert->rawData, cert->rawDataLen, data, dataLen); } #ifdef HITLS_PKI_X509_CRT_GEN int32_t ret = HITLS_X509_EncodeAsn1Cert(cert, NULL); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return CRYPT_EAL_Md(mdId, cert->rawData, cert->rawDataLen, data, dataLen); #else BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_FUNC_UNSUPPORT); return HITLS_X509_ERR_FUNC_UNSUPPORT; #endif } #ifdef HITLS_PKI_X509_CRT_GEN static int32_t CertSignCb(int32_t mdId, CRYPT_EAL_PkeyCtx *pivKey, HITLS_X509_Asn1AlgId *signAlgId, HITLS_X509_Cert *cert) { BSL_ASN1_Buffer tbsAsn1 = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}; BSL_Buffer signBuff = {0}; cert->signAlgId = *signAlgId; cert->tbs.signAlgId = *signAlgId; int32_t ret = EncodeTbsCertificate(&cert->tbs, &tbsAsn1); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_SignAsn1Data(pivKey, mdId, &tbsAsn1, &signBuff, &cert->signature); BSL_SAL_Free(tbsAsn1.buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } cert->tbs.tbsRawData = signBuff.data; cert->tbs.tbsRawDataLen = signBuff.dataLen; cert->state = HITLS_X509_CERT_STATE_SIGN; return ret; } int32_t HITLS_X509_CertSign(int32_t mdId, const CRYPT_EAL_PkeyCtx *prvKey, const HITLS_X509_SignAlgParam *algParam, HITLS_X509_Cert *cert) { if (cert == NULL || prvKey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((cert->flag & HITLS_X509_CERT_PARSE_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SIGN_AFTER_PARSE); return HITLS_X509_ERR_SIGN_AFTER_PARSE; } if (cert->state == HITLS_X509_CERT_STATE_SIGN || cert->state == HITLS_X509_CERT_STATE_GEN) { return HITLS_PKI_SUCCESS; } int32_t ret = CheckCertTbs(cert); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_SAL_FREE(cert->signature.buff); cert->signature.len = 0; BSL_SAL_FREE(cert->tbs.tbsRawData); cert->tbs.tbsRawDataLen = 0; BSL_SAL_FREE(cert->rawData); cert->rawDataLen = 0; #ifdef HITLS_CRYPTO_SM2 if (cert->signAlgId.algId == BSL_CID_SM2DSAWITHSM3) { BSL_SAL_FREE(cert->signAlgId.sm2UserId.data); cert->signAlgId.sm2UserId.dataLen = 0; } #endif return HITLS_X509_Sign(mdId, prvKey, algParam, cert, (HITLS_X509_SignCb)CertSignCb); } #endif // HITLS_PKI_X509_CRT_GEN HITLS_X509_Cert *HITLS_X509_ProviderCertNew(HITLS_PKI_LibCtx *libCtx, const char *attrName) { HITLS_X509_Cert *cert = HITLS_X509_CertNew(); if (cert == NULL) { return NULL; } cert->libCtx = libCtx; cert->attrName = attrName; return cert; } #ifdef HITLS_PKI_X509_CRT_PARSE int32_t HITLS_X509_ProviderCertParseBuff(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const BSL_Buffer *encode, HITLS_X509_Cert **cert) { int32_t encodeFormat = CRYPT_EAL_GetEncodeFormat(format); return ProviderCertParseBuffInternal(libCtx, attrName, encodeFormat, encode, cert); } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_X509_ProviderCertParseFile(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const char *path, HITLS_X509_Cert **cert) { uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer encode = {data, dataLen}; ret = HITLS_X509_ProviderCertParseBuff(libCtx, attrName, format, &encode, cert); BSL_SAL_Free(data); return ret; } int32_t HITLS_X509_ProviderCertParseBundleFile(HITLS_PKI_LibCtx *libCtx, const char *attrName, const char *format, const char *path, HITLS_X509_List **certlist) { int32_t encodeFormat = CRYPT_EAL_GetEncodeFormat(format); return ProviderCertParseBundleFileInternal(libCtx, attrName, encodeFormat, path, certlist); } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_PKI_X509_CRT_PARSE #endif // HITLS_PKI_X509_CRT
2301_79861745/bench_create
pki/x509_cert/src/hitls_x509_cert.c
C
unknown
49,898
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_X509_LOCAL_H #define HITLS_X509_LOCAL_H #include "hitls_build.h" #ifdef HITLS_PKI_X509 #include <stdint.h> #include "bsl_asn1_internal.h" #include "bsl_obj.h" #include "crypt_eal_pkey.h" #include "sal_atomic.h" #include "hitls_pki_types.h" #ifdef __cplusplus extern "C" { #endif /** * RFC 5280: section 4.1.2.5.1 */ #define BSL_TIME_UTC_MAX_YEAR 2049 #define BSL_TIME_BEFORE_SET 0x01 #define BSL_TIME_AFTER_SET 0x02 #define BSL_TIME_BEFORE_IS_UTC 0x04 #define BSL_TIME_AFTER_IS_UTC 0x08 /* Identifies the current ext as a parsed state */ #define HITLS_X509_EXT_FLAG_PARSE (1 << 0) /* Identifies the current ext as a generated state */ #define HITLS_X509_EXT_FLAG_GEN (1 << 1) /* Identifies the keyusage extension in the current structure */ #define HITLS_X509_EXT_FLAG_KUSAGE (1 << 0) /* Identifies the basic constraints extension in the current structure */ #define HITLS_X509_EXT_FLAG_BCONS (1 << 1) #define HITLS_X509_GN_OTHER (HITLS_X509_GN_IP + 1) #define HITLS_X509_GN_X400 (HITLS_X509_GN_OTHER + 1) #define HITLS_X509_GN_EDI (HITLS_X509_GN_X400 + 1) #define HITLS_X509_GN_RID (HITLS_X509_GN_EDI + 1) typedef struct _HITLS_X509_NameNode { BSL_ASN1_Buffer nameType; BSL_ASN1_Buffer nameValue; uint8_t layer; } HITLS_X509_NameNode; typedef struct _HITLS_X509_ExtEntry { BslCid cid; BSL_ASN1_Buffer extnId; bool critical; BSL_ASN1_Buffer extnValue; } HITLS_X509_ExtEntry; typedef struct _HITLS_X509_CertExt { uint32_t extFlags; // Indicates which extensions exist // basic usage ext bool isCa; // -1 no check, 0 no intermediate certificate int32_t maxPathLen; // key usage ext uint32_t keyUsage; } HITLS_X509_CertExt; typedef enum { HITLS_X509_EXT_TYPE_CERT = 1, HITLS_X509_EXT_TYPE_CRL, } HITLS_X509_ExtInnerType; typedef struct _HITLS_X509_Ext { uint32_t flag; // Identifies the status of the current ext, generate or parse BslList *extList; int32_t type; void *extData; } HITLS_X509_Ext; typedef struct _HITLS_X509_AttrEntry { BslCid cid; BSL_ASN1_Buffer attrId; BSL_ASN1_Buffer attrValue; } HITLS_X509_AttrEntry; typedef int32_t (*HITLS_X509_ParseAttrItemCb)(BslList *attrList, HITLS_X509_AttrEntry *attrEntry); typedef int32_t (*HITLS_X509_EncodeAttrItemCb)(void *attrNode, HITLS_X509_AttrEntry *attrEntry); typedef void *(*HITLS_X509_DupAttrItemCb)(const void *item); typedef void (*HITLS_X509_FreeAttrItemCb)(void *item); typedef struct _HITLS_X509_Attrs { uint8_t flag; BslList *list; // The list of HITLS_X509_AttrEntry } HITLS_X509_Attrs; typedef struct _HITLS_X509_ValidTime { uint8_t flag; BSL_TIME start; BSL_TIME end; } HITLS_X509_ValidTime; typedef struct _HITLS_X509_Asn1AlgId { BslCid algId; union { CRYPT_RSA_PssPara rsaPssParam; #ifdef HITLS_CRYPTO_SM2 BSL_Buffer sm2UserId; #endif }; } HITLS_X509_Asn1AlgId; typedef int32_t (*HITLS_X509_Asn1Parse)(uint8_t *encode, uint32_t encodeLen, void *out); typedef void *(*HITLS_X509_ProviderNew)(CRYPT_EAL_LibCtx *libCtx, const char *attrName); typedef void *(*HITLS_X509_New)(void); typedef void (*HITLS_X509_Free)(void *elem); typedef struct { HITLS_X509_Asn1Parse asn1Parse; HITLS_X509_ProviderNew x509ProviderNew; HITLS_X509_New x509New; HITLS_X509_Free x509Free; } X509_ParseFuncCbk; int32_t HITLS_X509_ParseTbsRawData(uint8_t *encode, uint32_t encodeLen, uint8_t **tbsRawData, uint32_t *tbsRawDataLen); #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CRL_PARSE) || defined(HITLS_PKI_X509_CSR_PARSE) // The public key parsing is more complex, and the crypto module completes it int32_t HITLS_X509_ParseSignAlgInfo(BSL_ASN1_Buffer *algId, BSL_ASN1_Buffer *param, HITLS_X509_Asn1AlgId *x509Alg); int32_t HITLS_X509_ParseExtendedKeyUsage(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtExKeyUsage *exku); int32_t HITLS_X509_ParseSubjectAltName(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtSan *san); void HITLS_X509_ClearSubjectAltName(HITLS_X509_ExtSan *san); int32_t HITLS_X509_ParseExtItem(BSL_ASN1_Buffer *extItem, HITLS_X509_ExtEntry *extEntry); int32_t HITLS_X509_ParseTime(BSL_ASN1_Buffer *before, BSL_ASN1_Buffer *after, HITLS_X509_ValidTime *time); #endif #if defined(HITLS_PKI_X509_CSR_GEN) || defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) int32_t HITLS_X509_EncodeSignAlgInfo(HITLS_X509_Asn1AlgId *x509Alg, BSL_ASN1_Buffer *asn); int32_t HITLS_X509_EncodeNameList(BSL_ASN1_List *list, BSL_ASN1_Buffer *name); int32_t HITLS_X509_SetNameList(BslList **dest, void *val, uint32_t valLen); int32_t HITLS_X509_EncodeExt(uint8_t tag, BSL_ASN1_List *list, BSL_ASN1_Buffer *ext); int32_t HITLS_X509_SignAsn1Data(CRYPT_EAL_PkeyCtx *priv, CRYPT_MD_AlgId mdId, BSL_ASN1_Buffer *asn1Buff, BSL_Buffer *rawSignBuff, BSL_ASN1_BitString *sign); typedef int32_t (*EncodeExtCb)(void *, HITLS_X509_ExtEntry *, const void *); int32_t HITLS_X509_SetExtList(void *param, BslList *extList, BslCid cid, BSL_Buffer *val, EncodeExtCb encodeExt); int32_t HITLS_X509_SetGeneralNames(HITLS_X509_ExtEntry *extEntry, void *val); int32_t HITLS_X509_EncodeExtEntry(BSL_ASN1_List *list, BSL_ASN1_Buffer *ext); typedef int32_t (*HITLS_X509_SignCb)(int32_t mdId, CRYPT_EAL_PkeyCtx *prvKey, HITLS_X509_Asn1AlgId *signAlgId, void *obj); int32_t HITLS_X509_Sign(int32_t mdId, const CRYPT_EAL_PkeyCtx *prvKey, const HITLS_X509_SignAlgParam *algParam, void *obj, HITLS_X509_SignCb signCb); #endif void HITLS_X509_FreeNameNode(HITLS_X509_NameNode *node); int32_t HITLS_X509_ParseNameList(BSL_ASN1_Buffer *name, BSL_ASN1_List *list); int32_t HITLS_X509_ParseGeneralNames(uint8_t *encode, uint32_t encLen, BslList *list); void HITLS_X509_ClearGeneralNames(BslList *names); int32_t HITLS_X509_ParseAuthorityKeyId(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtAki *aki); int32_t HITLS_X509_ParseSubjectKeyId(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtSki *ski); void HITLS_X509_ClearExtendedKeyUsage(HITLS_X509_ExtExKeyUsage *exku); HITLS_X509_Ext *X509_ExtNew(HITLS_X509_Ext *ext, int32_t type); void X509_ExtFree(HITLS_X509_Ext *ext, bool isFreeOut); #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CRL_PARSE) || defined(HITLS_PKI_X509_CSR) int32_t HITLS_X509_ParseExt(BSL_ASN1_Buffer *ext, HITLS_X509_Ext *certExt); #endif void HITLS_X509_ExtEntryFree(HITLS_X509_ExtEntry *entry); int32_t HITLS_X509_AddListItemDefault(void *item, uint32_t len, BSL_ASN1_List *list); int32_t HITLS_X509_ParseX509(CRYPT_EAL_LibCtx *libCtx, const char *attrName, int32_t format, const BSL_Buffer *encode, bool isCert, X509_ParseFuncCbk *parseFun, HITLS_X509_List *list); int32_t HITLS_X509_CheckAlg(CRYPT_EAL_PkeyCtx *pubkey, const HITLS_X509_Asn1AlgId *subAlg); #if defined(HITLS_PKI_X509_CSR_PARSE) || defined(HITLS_PKI_PKCS12_PARSE) int32_t HITLS_X509_ParseAttrList(BSL_ASN1_Buffer *attrBuff, HITLS_X509_Attrs *attrs, HITLS_X509_ParseAttrItemCb parseCb, HITLS_X509_FreeAttrItemCb freeItem); #endif #ifdef HITLS_PKI_PKCS12_GEN HITLS_X509_Attrs *HITLS_X509_AttrsDup(const HITLS_X509_Attrs *src, HITLS_X509_DupAttrItemCb dupCb, HITLS_X509_FreeAttrItemCb freeCb); #endif void HITLS_X509_AttrEntryFree(HITLS_X509_AttrEntry *attr); HITLS_X509_Attrs *HITLS_X509_AttrsNew(void); void HITLS_X509_AttrsFree(HITLS_X509_Attrs *attrs, HITLS_X509_FreeAttrItemCb freeItem); #if defined(HITLS_PKI_X509_CSR_GEN) || defined(HITLS_PKI_PKCS12_GEN) int32_t HITLS_X509_EncodeAttrList(uint8_t tag, HITLS_X509_Attrs *attrs, HITLS_X509_EncodeAttrItemCb encodeCb, BSL_ASN1_Buffer *attrAsn1); #endif int32_t HITLS_X509_CheckSignature(const CRYPT_EAL_PkeyCtx *pubKey, uint8_t *rawData, uint32_t rawDataLen, const HITLS_X509_Asn1AlgId *alg, const BSL_ASN1_BitString *signature); #ifdef HITLS_CRYPTO_SM2 int32_t HITLS_X509_SetSm2UserId(BSL_Buffer *sm2UserId, void *val, uint32_t valLen); #endif int32_t HITLS_X509_RefUp(BSL_SAL_RefCount *references, int32_t *val, uint32_t valLen); int32_t HITLS_X509_GetList(BslList *list, void *val, uint32_t valLen); int32_t HITLS_X509_GetListBuff(BslList *list, void *val, uint32_t valLen); int32_t HITLS_X509_GetPubKey(void *ealPubKey, void **val); int32_t HITLS_X509_GetSignAlg(BslCid signAlgId, int32_t *val, uint32_t valLen); int32_t HITLS_X509_GetSignMdAlg(const HITLS_X509_Asn1AlgId *signAlgId, int32_t *val, int32_t valLen); int32_t HITLS_X509_GetEncodeLen(uint32_t encodeLen, uint32_t *val, uint32_t valLen); int32_t HITLS_X509_GetEncodeData(uint8_t *rawData, uint8_t **val); int32_t HITLS_X509_SetPkey(void **pkey, void *val); #ifdef HITLS_PKI_X509_CRT_GEN int32_t HITLS_X509_ExtReplace(HITLS_X509_Ext *dest, HITLS_X509_Ext *src); #endif #if defined(HITLS_PKI_X509_CRT) || defined(HITLS_PKI_X509_CRL) #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) int32_t HITLS_X509_SetSerial(BSL_ASN1_Buffer *serial, const void *val, uint32_t valLen); HITLS_X509_ExtEntry *X509_DupExtEntry(const HITLS_X509_ExtEntry *src); #endif int32_t HITLS_X509_GetSerial(BSL_ASN1_Buffer *serial, void *val, uint32_t valLen); #endif typedef int32_t (*DecodeExtCb)(HITLS_X509_ExtEntry *, void *); int32_t HITLS_X509_GetExt(BslList *ext, BslCid cid, BSL_Buffer *val, uint32_t expectLen, DecodeExtCb decodeExt); bool X509_IsValidHashAlg(CRYPT_MD_AlgId id); #ifdef HITLS_PKI_X509_VFY int32_t HITLS_X509_CheckAki(HITLS_X509_Ext *issueExt, HITLS_X509_Ext *subjectExt, BSL_ASN1_List *issueName, BSL_ASN1_Buffer *serialNum); int32_t HITLS_X509_CmpNameNode(BSL_ASN1_List *nameOri, BSL_ASN1_List *name); #endif bool X509_CheckCmdValid(int32_t *cmdSet, uint32_t cmdSize, int32_t cmd); int32_t X509_ExtCtrl(HITLS_X509_Ext *ext, int32_t cmd, void *val, uint32_t valLen); #ifdef HITLS_PKI_INFO int32_t HITLS_X509_EncodeCanonNameList(BSL_ASN1_List *list, BSL_ASN1_Buffer *name); #endif #ifdef __cplusplus } #endif #endif // HITLS_PKI_X509 #endif // HITLS_X509_LOCAL_H
2301_79861745/bench_create
pki/x509_common/include/hitls_x509_local.h
C
unknown
10,506
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_PKI_X509_CSR) || defined(HITLS_PKI_PKCS12) #include <stdint.h> #include "securec.h" #include "hitls_x509_local.h" #include "bsl_obj.h" #include "bsl_sal.h" #include "bsl_obj_internal.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "hitls_pki_errno.h" #include "hitls_pki_utils.h" #if defined(HITLS_PKI_X509_CSR_PARSE) || defined(HITLS_PKI_PKCS12_PARSE) /** * RFC 2985: section-5.4.2 * extensionRequest ATTRIBUTE ::= { * WITH SYNTAX ExtensionRequest * SINGLE VALUE TRUE * ID pkcs-9-at-extensionRequest * } * ExtensionRequest ::= Extensions */ static BSL_ASN1_TemplateItem g_x509AttrTempl[] = { {BSL_ASN1_TAG_OBJECT_ID, 0, 0}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET, BSL_ASN1_FLAG_HEADERONLY, 0}, }; typedef enum { HITLS_X509_ATTR_OID_IDX, HITLS_X509_ATTR_SET_IDX, HITLS_X509_ATTR_INDEX_MAX } HITLS_X509_ATTR_IDX; #endif #define HITLS_X509_ATTR_MAX_NUM 20 #define HITLS_X509_ATTRS_PARSE_FLAG 0x01 #define HITLS_X509_ATTRS_GEN_FLAG 0x02 HITLS_X509_Attrs *HITLS_X509_AttrsNew(void) { HITLS_X509_Attrs *attrs = (HITLS_X509_Attrs *)BSL_SAL_Calloc(1, sizeof(HITLS_X509_Attrs)); if (attrs == NULL) { return NULL; } attrs->list = BSL_LIST_New(sizeof(HITLS_X509_AttrEntry *)); if (attrs->list == NULL) { BSL_SAL_Free(attrs); return NULL; } attrs->flag = HITLS_X509_ATTRS_GEN_FLAG; return attrs; } /* * For pkcs12, parsing and encoding operation uses deep copy, and it use callback function to free * For csr, parsing operation uses shallow copy, and encoding operation uses deep copy */ void HITLS_X509_AttrsFree(HITLS_X509_Attrs *attrs, HITLS_X509_FreeAttrItemCb freeItem) { if (attrs == NULL) { return; } if (freeItem != NULL) { BSL_LIST_FREE(attrs->list, (BSL_LIST_PFUNC_FREE)freeItem); BSL_SAL_Free(attrs); return; } if ((attrs->flag & HITLS_X509_ATTRS_PARSE_FLAG) != 0) { BSL_LIST_FREE(attrs->list, NULL); } else { BSL_LIST_FREE(attrs->list, (BSL_LIST_PFUNC_FREE)HITLS_X509_AttrEntryFree); } BSL_SAL_Free(attrs); } #if defined(HITLS_PKI_X509_CSR_GEN) || defined(HITLS_PKI_PKCS12_GEN) int32_t HITLS_X509_EncodeObjIdentity(BslCid cid, BSL_ASN1_Buffer *asnBuff) { BslOidString *oidStr = BSL_OBJ_GetOID(cid); if (oidStr == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); return CRYPT_ERR_ALGID; } asnBuff->tag = BSL_ASN1_TAG_OBJECT_ID; asnBuff->buff = (uint8_t *)oidStr->octs; asnBuff->len = oidStr->octetLen; return HITLS_PKI_SUCCESS; } #endif #ifdef HITLS_PKI_PKCS12_GEN HITLS_X509_Attrs *HITLS_X509_AttrsDup(const HITLS_X509_Attrs *src, HITLS_X509_DupAttrItemCb dupCb, HITLS_X509_FreeAttrItemCb freeCb) { if (src == NULL || BSL_LIST_COUNT(src->list) <= 0 || dupCb == NULL || freeCb == NULL) { return NULL; } HITLS_X509_Attrs *dst = HITLS_X509_AttrsNew(); if (dst == NULL) { return NULL; } void *node = NULL; for (node = BSL_LIST_GET_FIRST(src->list); node != NULL; node = BSL_LIST_GET_NEXT(src->list)) { void *dstEntry = dupCb(node); if (dstEntry == NULL) { HITLS_X509_AttrsFree(dst, freeCb); return NULL; } int32_t ret = BSL_LIST_AddElement(dst->list, dstEntry, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { freeCb(dstEntry); HITLS_X509_AttrsFree(dst, freeCb); return NULL; } } dst->flag = src->flag; return dst; } #endif void HITLS_X509_AttrEntryFree(HITLS_X509_AttrEntry *attr) { if (attr == NULL) { return; } BSL_SAL_Free(attr->attrValue.buff); BSL_SAL_Free(attr); } #if defined(HITLS_PKI_X509_CSR_PARSE) || defined(HITLS_PKI_PKCS12_PARSE) int32_t HITLS_X509_ParseAttr(BSL_ASN1_Buffer *attrItem, HITLS_X509_AttrEntry *attrEntry) { uint8_t *temp = attrItem->buff; uint32_t tempLen = attrItem->len; BSL_ASN1_Buffer asnArr[HITLS_X509_ATTR_INDEX_MAX] = {0}; BSL_ASN1_Template templ = {g_x509AttrTempl, sizeof(g_x509AttrTempl) / sizeof(g_x509AttrTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asnArr, HITLS_X509_ATTR_INDEX_MAX); if (tempLen != 0) { ret = HITLS_X509_ERR_PARSE_ATTR_BUF; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* parse attribute id */ BslOidString oid = {asnArr[HITLS_X509_ATTR_OID_IDX].len, (char *)asnArr[HITLS_X509_ATTR_OID_IDX].buff, 0}; attrEntry->cid = BSL_OBJ_GetCID(&oid); if (attrEntry->cid == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_OBJ_ID); return HITLS_X509_ERR_PARSE_OBJ_ID; } /* set id and value asn1 buffer */ attrEntry->attrId = asnArr[HITLS_X509_ATTR_OID_IDX]; attrEntry->attrValue = asnArr[HITLS_X509_ATTR_SET_IDX]; return ret; } int32_t HITLS_X509_ParseAttrsListAsnItem(uint32_t layer, BSL_ASN1_Buffer *asn, void *cbParam, BSL_ASN1_List *list) { (void)layer; HITLS_X509_ParseAttrItemCb parseCb = cbParam; HITLS_X509_AttrEntry *node = BSL_SAL_Calloc(1, sizeof(HITLS_X509_AttrEntry)); if (node == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } /* parse attribute entry */ int32_t ret = HITLS_X509_ParseAttr(asn, node); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } if (parseCb != NULL) { ret = parseCb(list, node); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } goto ERR; } ret = BSL_LIST_AddElement(list, node, BSL_LIST_POS_AFTER); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } return ret; ERR: BSL_SAL_FREE(node); return ret; } int32_t HITLS_X509_ParseAttrList(BSL_ASN1_Buffer *attrBuff, HITLS_X509_Attrs *attrs, HITLS_X509_ParseAttrItemCb parseCb, HITLS_X509_FreeAttrItemCb freeItem) { if (attrBuff->tag == 0 || attrBuff->buff == NULL || attrBuff->len == 0) { return HITLS_PKI_SUCCESS; } uint8_t expTag[] = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE}; BSL_ASN1_DecodeListParam listParam = {1, expTag}; int32_t ret = BSL_ASN1_DecodeListItem(&listParam, attrBuff, &HITLS_X509_ParseAttrsListAsnItem, parseCb, attrs->list); if (ret != BSL_SUCCESS) { BSL_LIST_DeleteAll(attrs->list, freeItem); return ret; } attrs->flag = HITLS_X509_ATTRS_PARSE_FLAG; return ret; } #endif static int32_t CmpAttrEntryByCid(const void *attrEntry, const void *cid) { const HITLS_X509_AttrEntry *node = attrEntry; return node->cid == *(const BslCid *)cid ? 0 : 1; } typedef int32_t (*DecodeAttrCb)(HITLS_X509_Attrs *attributes, HITLS_X509_AttrEntry *attrEntry, void *val, uint32_t valLen); #if defined(HITLS_PKI_X509_CSR_GEN) || defined(HITLS_PKI_PKCS12_GEN) typedef int32_t (*EncodeAttrCb)(HITLS_X509_Attrs *attributes, void *val, uint32_t valLen, BSL_ASN1_Buffer *attrValue); static int32_t EncodeReqExtAttr(HITLS_X509_Attrs *attributes, void *val, uint32_t valLen, BSL_ASN1_Buffer *attrValue) { (void)valLen; (void)attributes; HITLS_X509_Ext *ext = (HITLS_X509_Ext *)val; return HITLS_X509_EncodeExt(BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET, ext->extList, attrValue); } static int32_t SetAttr(HITLS_X509_Attrs *attributes, BslCid cid, void *val, uint32_t valLen, EncodeAttrCb encodeAttrCb) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } /* Check if the attribute already exists. */ if (BSL_LIST_Search(attributes->list, &cid, CmpAttrEntryByCid, NULL) != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_ATTR_REPEAT); return HITLS_X509_ERR_SET_ATTR_REPEAT; } HITLS_X509_AttrEntry *attrEntry = BSL_SAL_Calloc(1, sizeof(HITLS_X509_AttrEntry)); if (attrEntry == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = HITLS_X509_EncodeObjIdentity(cid, &attrEntry->attrId); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ret = encodeAttrCb(attributes, val, valLen, &attrEntry->attrValue); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } attrEntry->cid = cid; ret = BSL_LIST_AddElement(attributes->list, attrEntry, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } return ret; ERR: HITLS_X509_AttrEntryFree(attrEntry); return ret; } #endif // HITLS_PKI_X509_CSR_GEN || HITLS_PKI_PKCS12_GEN static int32_t DecodeReqExtAttr(HITLS_X509_Attrs *attributes, HITLS_X509_AttrEntry *attrEntry, void *val, uint32_t valLen) { (void)attributes; if (valLen != sizeof(HITLS_X509_Ext *)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } HITLS_X509_Ext *ext = HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CSR); if (ext == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = HITLS_X509_ParseExt(&attrEntry->attrValue, ext); if (ret != BSL_SUCCESS) { HITLS_X509_ExtFree(ext); BSL_ERR_PUSH_ERROR(ret); return ret; } *(HITLS_X509_Ext **)val = ext; return HITLS_PKI_SUCCESS; } static int32_t GetAttr(HITLS_X509_Attrs *attributes, BslCid cid, void *val, uint32_t valLen, DecodeAttrCb decodeAttrCb) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } HITLS_X509_AttrEntry *attrEntry = BSL_LIST_Search(attributes->list, &cid, CmpAttrEntryByCid, NULL); if (attrEntry == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ATTR_NOT_FOUND); return HITLS_X509_ERR_ATTR_NOT_FOUND; } return decodeAttrCb(attributes, attrEntry, val, valLen); } int32_t HITLS_X509_AttrCtrl(HITLS_X509_Attrs *attributes, HITLS_X509_AttrCmd cmd, void *val, uint32_t valLen) { if (attributes == NULL || val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (cmd) { #if defined(HITLS_PKI_X509_CSR_GEN) || defined(HITLS_PKI_PKCS12_GEN) case HITLS_X509_ATTR_SET_REQUESTED_EXTENSIONS: return SetAttr(attributes, BSL_CID_EXTENSIONREQUEST, val, valLen, EncodeReqExtAttr); #endif case HITLS_X509_ATTR_GET_REQUESTED_EXTENSIONS: return GetAttr(attributes, BSL_CID_EXTENSIONREQUEST, val, valLen, DecodeReqExtAttr); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #if defined(HITLS_PKI_X509_CSR_GEN) || defined(HITLS_PKI_PKCS12_GEN) #define X509_CSR_ATTR_ELEM_NUMBER 2 static BSL_ASN1_TemplateItem g_x509AttrEntryTempl[] = { {BSL_ASN1_TAG_OBJECT_ID, 0, 0}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET, 0, 0}, }; int32_t HITLS_X509_EncodeAttrEntry(HITLS_X509_AttrEntry *node, BSL_ASN1_Buffer *attrBuff) { BSL_ASN1_Buffer asnBuf[X509_CSR_ATTR_ELEM_NUMBER] = {0}; asnBuf[0] = node->attrId; asnBuf[1] = node->attrValue; BSL_ASN1_Template templ = {g_x509AttrEntryTempl, sizeof(g_x509AttrEntryTempl) / sizeof(g_x509AttrEntryTempl[0])}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, asnBuf, X509_CSR_ATTR_ELEM_NUMBER, &attrBuff->buff, &attrBuff->len); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } attrBuff->tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; return ret; } void FreeAsnAttrsBuff(BSL_ASN1_Buffer *asnBuf, uint32_t count) { for (uint32_t i = 0; i < count; i++) { BSL_SAL_FREE(asnBuf[i].buff); } BSL_SAL_FREE(asnBuf); } int32_t HITLS_X509_EncodeAttrList(uint8_t tag, HITLS_X509_Attrs *attrs, HITLS_X509_EncodeAttrItemCb encodeCb, BSL_ASN1_Buffer *attrAsn1) { if (attrs == NULL || attrs->list == NULL || BSL_LIST_COUNT(attrs->list) <= 0) { attrAsn1->tag = tag; attrAsn1->buff = NULL; attrAsn1->len = 0; return HITLS_PKI_SUCCESS; } uint32_t count = (uint32_t)BSL_LIST_COUNT(attrs->list); /* no attribute */ BSL_ASN1_Buffer *asnBuf = BSL_SAL_Calloc(count, sizeof(BSL_ASN1_Buffer)); if (asnBuf == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } uint32_t iter = 0; int32_t ret; void *node = NULL; for (node = BSL_LIST_GET_FIRST(attrs->list); node != NULL; node = BSL_LIST_GET_NEXT(attrs->list), iter++) { HITLS_X509_AttrEntry attrEntry = {}; if (encodeCb != NULL) { ret = encodeCb(node, &attrEntry); if (ret != HITLS_PKI_SUCCESS) { FreeAsnAttrsBuff(asnBuf, count); return ret; } } else { attrEntry = *(HITLS_X509_AttrEntry *)node; } ret = HITLS_X509_EncodeAttrEntry(&attrEntry, &asnBuf[iter]); if (encodeCb != NULL) { BSL_SAL_FREE(attrEntry.attrValue.buff); } if (ret != HITLS_PKI_SUCCESS) { FreeAsnAttrsBuff(asnBuf, count); return ret; } } static BSL_ASN1_TemplateItem attrSeqTempl = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0 }; BSL_ASN1_Template templ = {&attrSeqTempl, 1}; ret = BSL_ASN1_EncodeListItem(BSL_ASN1_TAG_SEQUENCE, count, &templ, asnBuf, iter, attrAsn1); FreeAsnAttrsBuff(asnBuf, count); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } attrAsn1->tag = tag; return ret; } #endif // HITLS_PKI_X509_CSR_GEN || HITLS_PKI_PKCS12_GEN #endif // HITLS_PKI_X509_CSR || HITLS_PKI_PKCS12
2301_79861745/bench_create
pki/x509_common/src/hitls_x509_attrs.c
C
unknown
14,514
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_X509 #include "hitls_x509_local.h" #include "securec.h" #include "bsl_sal.h" #include "bsl_log_internal.h" #include "hitls_pki_errno.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "bsl_obj_internal.h" #include "bsl_err_internal.h" #ifdef HITLS_BSL_PEM #include "bsl_pem_internal.h" #endif // HITLS_BSL_PEM #include "crypt_encode_decode_key.h" #include "bsl_params.h" #include "crypt_params_key.h" #include "hitls_pki_utils.h" int32_t HITLS_X509_AddListItemDefault(void *item, uint32_t len, BSL_ASN1_List *list) { void *node = BSL_SAL_Malloc(len); if (node == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } (void)memcpy_s(node, len, item, len); int32_t ret = BSL_LIST_AddElement(list, node, BSL_LIST_POS_AFTER); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BSL_SAL_Free(node); } return ret; } #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CRL_PARSE) || defined(HITLS_PKI_X509_CSR_PARSE) int32_t HITLS_X509_ParseTbsRawData(uint8_t *encode, uint32_t encodeLen, uint8_t **tbsRawData, uint32_t *tbsRawDataLen) { uint8_t *temp = encode; uint32_t tempLen = encodeLen; uint32_t valLen; // x509 int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, &temp, &tempLen, &valLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t len = tempLen; *tbsRawData = temp; // tbs ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, &temp, &tempLen, &valLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *tbsRawDataLen = len - tempLen + valLen; return ret; } int32_t HITLS_X509_ParseSignAlgInfo(BSL_ASN1_Buffer *algId, BSL_ASN1_Buffer *param, HITLS_X509_Asn1AlgId *x509Alg) { int32_t ret = HITLS_PKI_SUCCESS; BslOidString oidStr = {algId->len, (char *)algId->buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ALG_OID); return HITLS_X509_ERR_ALG_OID; } if (cid == BSL_CID_RSASSAPSS) { #ifdef HITLS_CRYPTO_RSA ret = CRYPT_EAL_ParseRsaPssAlgParam(param, &x509Alg->rsaPssParam); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } #else (void)param; BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ALG_UNSUPPORT); return HITLS_X509_ERR_ALG_UNSUPPORT; #endif } x509Alg->algId = cid; return ret; } #endif static int32_t HITLS_X509_ParseNameNode(BSL_ASN1_Buffer *asn, HITLS_X509_NameNode *node) { uint8_t *temp = asn->buff; uint32_t tempLen = asn->len; // parse oid if (*temp != BSL_ASN1_TAG_OBJECT_ID) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_NAME_OID); return HITLS_X509_ERR_NAME_OID; } int32_t ret = BSL_ASN1_DecodeItem(&temp, &tempLen, &node->nameType); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // parse string if (*temp != BSL_ASN1_TAG_UTF8STRING && *temp != BSL_ASN1_TAG_PRINTABLESTRING && *temp != BSL_ASN1_TAG_IA5STRING) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_STR); return HITLS_X509_ERR_PARSE_STR; } ret = BSL_ASN1_DecodeItem(&temp, &tempLen, &node->nameValue); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t HITLS_X509_ParseListAsnItem(uint32_t layer, BSL_ASN1_Buffer *asn, void *cbParam, BSL_ASN1_List *list) { (void) cbParam; int32_t ret = HITLS_PKI_SUCCESS; HITLS_X509_NameNode *node = BSL_SAL_Calloc(1, sizeof(HITLS_X509_NameNode)); if (node == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } if (layer == 1) { node->layer = 1; } else { // layer == 2 node->layer = 2; ret = HITLS_X509_ParseNameNode(asn, node); if (ret != HITLS_PKI_SUCCESS) { goto ERR; } } ret = BSL_LIST_AddElement(list, node, BSL_LIST_POS_AFTER); if (ret != BSL_SUCCESS) { goto ERR; } return ret; ERR: BSL_SAL_Free(node); return ret; } int32_t HITLS_X509_ParseNameList(BSL_ASN1_Buffer *name, BSL_ASN1_List *list) { uint8_t expTag[] = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET, BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE}; BSL_ASN1_DecodeListParam listParam = {2, expTag}; int32_t ret = BSL_ASN1_DecodeListItem(&listParam, name, HITLS_X509_ParseListAsnItem, NULL, list); if (ret != BSL_SUCCESS) { BSL_LIST_DeleteAll(list, NULL); } return ret; } #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CSR_PARSE) || defined(HITLS_PKI_X509_CRL) int32_t HITLS_X509_ParseTime(BSL_ASN1_Buffer *before, BSL_ASN1_Buffer *after, HITLS_X509_ValidTime *time) { int32_t ret = BSL_ASN1_DecodePrimitiveItem(before, &time->start); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } time->flag |= BSL_TIME_BEFORE_SET; if (before->tag == BSL_ASN1_TAG_UTCTIME) { time->flag |= BSL_TIME_BEFORE_IS_UTC; } // crl after time is optional if (after->tag != 0) { ret = BSL_ASN1_DecodePrimitiveItem(after, &time->end); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } time->flag |= BSL_TIME_AFTER_SET; if (after->tag == BSL_ASN1_TAG_UTCTIME) { time->flag |= BSL_TIME_AFTER_IS_UTC; } } return ret; } #endif #if defined(HITLS_PKI_X509_CSR_GEN) || defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) static bool X509_CheckIsRsa(uint32_t algId) { switch (algId) { case BSL_CID_RSA: case BSL_CID_MD5WITHRSA: case BSL_CID_SHA1WITHRSA: case BSL_CID_SHA224WITHRSAENCRYPTION: case BSL_CID_SHA256WITHRSAENCRYPTION: case BSL_CID_SHA384WITHRSAENCRYPTION: case BSL_CID_SHA512WITHRSAENCRYPTION: case BSL_CID_SM3WITHRSAENCRYPTION: return true; default: return false; } } int32_t HITLS_X509_EncodeSignAlgInfo(HITLS_X509_Asn1AlgId *x509Alg, BSL_ASN1_Buffer *asn) { int32_t ret; BslOidString *oidStr = BSL_OBJ_GetOID(x509Alg->algId); if (oidStr == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ALG_OID); return HITLS_X509_ERR_ALG_OID; } BSL_ASN1_Buffer asnArr[2] = {0}; asnArr[0].buff = (uint8_t *)oidStr->octs; asnArr[0].len = oidStr->octetLen; asnArr[0].tag = BSL_ASN1_TAG_OBJECT_ID; if (x509Alg->algId == BSL_CID_RSASSAPSS) { #ifdef HITLS_CRYPTO_RSA ret = CRYPT_EAL_EncodeRsaPssAlgParam(&(x509Alg->rsaPssParam), &asnArr[1].buff, &asnArr[1].len); #else ret = HITLS_X509_ERR_ALG_UNSUPPORT; #endif if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } asnArr[1].tag = BSL_ASN1_TAG_SEQUENCE | BSL_ASN1_TAG_CONSTRUCTED; } else if (X509_CheckIsRsa(x509Alg->algId)) { asnArr[1].buff = NULL; asnArr[1].len = 0; asnArr[1].tag = BSL_ASN1_TAG_NULL; } else { /** * RFC5758 sec 3.2 * When the ecdsa-with-SHA224, ecdsa-with-SHA256, ecdsa-with-SHA384, or * ecdsa-with-SHA512 algorithm identifier appears in the algorithm field * as an AlgorithmIdentifier, the encoding MUST omit the parameters * field. */ asnArr[1].buff = NULL; asnArr[1].len = 0; asnArr[1].tag = BSL_ASN1_TAG_ANY; } BSL_ASN1_TemplateItem algTempl[] = { {BSL_ASN1_TAG_OBJECT_ID, 0, 0}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY, 0}, }; BSL_ASN1_Template templ = {algTempl, sizeof(algTempl) / sizeof(algTempl[0])}; // 2: alg + param ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, 2, &(asn->buff), &(asn->len)); BSL_SAL_FREE(asnArr[1].buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } asn->tag = BSL_ASN1_TAG_SEQUENCE | BSL_ASN1_TAG_CONSTRUCTED; return HITLS_PKI_SUCCESS; } static int32_t X509_EncodeRdName(BSL_ASN1_List *list, BSL_ASN1_Buffer *asnBuf) { uint32_t maxCount = (BSL_LIST_COUNT(list) - 1) * 2; // 2: layer 1 and layer 2 BSL_ASN1_Buffer *tmpBuf = BSL_SAL_Calloc(maxCount, sizeof(BSL_ASN1_Buffer)); if (tmpBuf == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } uint32_t iter = 0; HITLS_X509_NameNode *node = BSL_LIST_GET_NEXT(list); while (node != NULL && node->layer != 1) { tmpBuf[iter++] = node->nameType; tmpBuf[iter++] = node->nameValue; node = BSL_LIST_GET_NEXT(list); } BSL_ASN1_TemplateItem x509RdName[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_OBJECT_ID, 0, 1}, {BSL_ASN1_TAG_ANY, 0, 1} }; BSL_ASN1_Template templ = {x509RdName, sizeof(x509RdName) / sizeof(x509RdName[0])}; int32_t ret = BSL_ASN1_EncodeListItem(BSL_ASN1_TAG_SET, iter / 2, &templ, tmpBuf, iter, asnBuf); BSL_SAL_Free(tmpBuf); return ret; } int32_t HITLS_X509_EncodeNameList(BSL_ASN1_List *list, BSL_ASN1_Buffer *name) { int32_t ret; // (count + 1) / 2 : round up, the maximum number of set uint32_t maxCount = ((uint32_t)BSL_LIST_COUNT(list) + 1) / 2; BSL_ASN1_Buffer *asnBuf = BSL_SAL_Calloc(maxCount, sizeof(BSL_ASN1_Buffer)); if (asnBuf == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } HITLS_X509_NameNode *node = BSL_LIST_GET_FIRST(list); uint32_t iter = 0; while (node != NULL) { ret = X509_EncodeRdName(list, &asnBuf[iter]); if (ret != HITLS_PKI_SUCCESS) { goto EXIT; } iter++; node = BSL_LIST_Curr(list); } BSL_ASN1_TemplateItem x509Name[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET, 0, 0} }; BSL_ASN1_Template templ = {x509Name, 1}; ret = BSL_ASN1_EncodeListItem(BSL_ASN1_TAG_SEQUENCE, iter, &templ, asnBuf, iter, name); EXIT: for (uint32_t index = 0; index < iter; index++) { BSL_SAL_Free(asnBuf[index].buff); } BSL_SAL_Free(asnBuf); return ret; } #endif #if defined(HITLS_PKI_INFO) || defined(HITLS_PKI_X509_VFY_LOCATION) static HITLS_X509_NameNode *NameNodeDup(HITLS_X509_NameNode *node) { uint32_t size = sizeof(HITLS_X509_NameNode) + node->nameType.len + node->nameValue.len; uint8_t *tmp = BSL_SAL_Calloc(1, size); if (tmp == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } HITLS_X509_NameNode *res = (HITLS_X509_NameNode *)tmp; res->layer = node->layer; if (node->nameType.len != 0) { res->nameType.tag = node->nameType.tag; res->nameType.len = node->nameType.len; res->nameType.buff = tmp + sizeof(HITLS_X509_NameNode); (void)memcpy_s(res->nameType.buff, res->nameType.len, node->nameType.buff, node->nameType.len); } if (node->nameValue.len != 0) { res->nameValue.tag = node->nameValue.tag; res->nameValue.len = node->nameValue.len; res->nameValue.buff = tmp + sizeof(HITLS_X509_NameNode) + node->nameType.len; (void)memcpy_s(res->nameValue.buff, res->nameValue.len, node->nameValue.buff, node->nameValue.len); } return res; } static char ToLower(char c) { if (c >= 'A' && c <= 'Z') { return c + 32; // 32 is ('a' - 'A') } return c; } static bool IsSpace(char c) { return c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r' || c == ' '; } static void StringCanon(BSL_ASN1_Buffer *str) { if (str->tag != BSL_ASN1_TAG_UTF8STRING) { str->tag = BSL_ASN1_TAG_UTF8STRING; } bool preSpace = true; uint32_t idx = 0; for (uint32_t i = 0; i < str->len; i++) { if (IsSpace((char)str->buff[i])) { if (!preSpace) { str->buff[idx++] = ' '; } preSpace = true; continue; } str->buff[idx++] = (uint8_t)ToLower((char)str->buff[i]); preSpace = false; } str->len = str->buff[idx - 1] == ' ' ? idx - 1 : idx; } int32_t HITLS_X509_EncodeCanonNameList(BSL_ASN1_List *list, BSL_ASN1_Buffer *name) { if (BSL_LIST_COUNT(list) == 0) { return HITLS_PKI_SUCCESS; } BslList *tmpList = BSL_LIST_Copy(list, (BSL_LIST_PFUNC_DUP)NameNodeDup, NULL); if (tmpList == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret; for (HITLS_X509_NameNode *node = BSL_LIST_GET_FIRST(tmpList); node != NULL; node = BSL_LIST_GET_NEXT(tmpList)) { if (node->nameValue.buff == NULL || node->nameValue.len == 0) { continue; } StringCanon(&node->nameValue); } ret = HITLS_X509_EncodeNameList(tmpList, name); BSL_LIST_FREE(tmpList, NULL); return ret; } #endif #ifdef HITLS_BSL_PEM static void X509_GetPemSymbol(bool isCert, BSL_PEM_Symbol *symbol) { if (isCert) { symbol->head = BSL_PEM_CERT_BEGIN_STR; symbol->tail = BSL_PEM_CERT_END_STR; } else { symbol->head = BSL_PEM_CRL_BEGIN_STR; symbol->tail = BSL_PEM_CRL_END_STR; } } #endif // HITLS_BSL_PEM static int32_t X509_ParseAndAddRes(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *asn1Buf, X509_ParseFuncCbk *parseFun, HITLS_X509_List *list) { void *res = NULL; if (parseFun->x509ProviderNew != NULL) { res = parseFun->x509ProviderNew(libCtx, attrName); } else if (parseFun->x509New != NULL) { res = parseFun->x509New(); } if (res == NULL) { BSL_SAL_FREE(asn1Buf->data); // must free asn1Buf.data. BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = parseFun->asn1Parse(asn1Buf->data, asn1Buf->dataLen, res); if (ret != HITLS_PKI_SUCCESS) { parseFun->x509Free(res); // The asn1Buf.data is taken over by res->rawData. BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_LIST_AddElement(list, res, BSL_LIST_POS_AFTER); if (ret != BSL_SUCCESS) { parseFun->x509Free(res); BSL_ERR_PUSH_ERROR(ret); return ret; } return HITLS_PKI_SUCCESS; } static int32_t HITLS_X509_ParseAsn1(CRYPT_EAL_LibCtx *libCtx, const char *attrName, const BSL_Buffer *encode, X509_ParseFuncCbk *parseFun, HITLS_X509_List *list) { uint8_t *data = encode->data; uint32_t dataLen = encode->dataLen; while (dataLen > 0) { uint32_t elemLen = dataLen; int32_t ret = BSL_ASN1_GetCompleteLen(data, &elemLen); if (ret != HITLS_PKI_SUCCESS) { return ret; } BSL_Buffer asn1Buf = {data, elemLen}; asn1Buf.data = BSL_SAL_Dump(data, elemLen); if (asn1Buf.data == NULL) { return BSL_DUMP_FAIL; } ret = X509_ParseAndAddRes(libCtx, attrName, &asn1Buf, parseFun, list); if (ret != HITLS_PKI_SUCCESS) { return ret; // asn1Buf.data has beed freed in X509_ParseAndAddRes. } data += elemLen; dataLen -= elemLen; } return HITLS_PKI_SUCCESS; } #ifdef HITLS_BSL_PEM static int32_t HITLS_X509_ParsePem(CRYPT_EAL_LibCtx *libCtx, const char *attrName, const BSL_Buffer *encode, bool isCert, X509_ParseFuncCbk *parseFun, HITLS_X509_List *list) { char *nextEncode = (char *)(encode->data); uint32_t nextEncodeLen = encode->dataLen; BSL_PEM_Symbol symbol = {0}; X509_GetPemSymbol(isCert, &symbol); while (nextEncodeLen > 0) { BSL_Buffer asn1Buf = {0}; int32_t ret = BSL_PEM_DecodePemToAsn1(&nextEncode, &nextEncodeLen, &symbol, &(asn1Buf.data), &(asn1Buf.dataLen)); if (ret != HITLS_PKI_SUCCESS) { break; } ret = X509_ParseAndAddRes(libCtx, attrName, &asn1Buf, parseFun, list); if (ret != HITLS_PKI_SUCCESS) { // asn1Buf.data has beed freed in X509_ParseAndAddRes. return ret; } } if (BSL_LIST_COUNT(list) == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_NO_ELEMENT); return HITLS_X509_ERR_PARSE_NO_ELEMENT; } return HITLS_PKI_SUCCESS; } #endif // HITLS_BSL_PEM static int32_t HITLS_X509_ParseUnknown(CRYPT_EAL_LibCtx *libCtx, const char *attrName, const BSL_Buffer *encode, bool isCert, X509_ParseFuncCbk *parseFun, HITLS_X509_List *list) { #ifdef HITLS_BSL_PEM bool isPem = BSL_PEM_IsPemFormat((char *)(encode->data), encode->dataLen); if (isPem) { return HITLS_X509_ParsePem(libCtx, attrName, encode, isCert, parseFun, list); } #else (void)isCert; #endif // HITLS_BSL_PEM return HITLS_X509_ParseAsn1(libCtx, attrName, encode, parseFun, list); } int32_t HITLS_X509_ParseX509(CRYPT_EAL_LibCtx *libCtx, const char *attrName, int32_t format, const BSL_Buffer *encode, bool isCert, X509_ParseFuncCbk *parseFun, HITLS_X509_List *list) { switch (format) { case BSL_FORMAT_ASN1: return HITLS_X509_ParseAsn1(libCtx, attrName, encode, parseFun, list); #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: return HITLS_X509_ParsePem(libCtx, attrName, encode, isCert, parseFun, list); #endif // HITLS_BSL_PEM case BSL_FORMAT_UNKNOWN: return HITLS_X509_ParseUnknown(libCtx, attrName, encode, isCert, parseFun, list); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_FORMAT_UNSUPPORT); return HITLS_X509_ERR_FORMAT_UNSUPPORT; } } #ifdef HITLS_PKI_X509_VFY static int32_t X509_NodeNameCompare(BSL_ASN1_Buffer *src, BSL_ASN1_Buffer *dest) { if (src->tag != dest->tag) { return 1; } if (src->len != dest->len) { return 1; } return memcmp(src->buff, dest->buff, dest->len); } static int32_t X509_NodeNameCaseCompare(BSL_ASN1_Buffer *src, BSL_ASN1_Buffer *dest) { if ((src->tag == BSL_ASN1_TAG_UTF8STRING || src->tag == BSL_ASN1_TAG_PRINTABLESTRING) && (dest->tag == BSL_ASN1_TAG_UTF8STRING || dest->tag == BSL_ASN1_TAG_PRINTABLESTRING)) { if (src->len != dest->len) { return 1; } for (uint32_t i = 0; i < src->len; i++) { if (src->buff[i] == dest->buff[i]) { continue; } if ('a' <= src->buff[i] && src->buff[i] <= 'z' && src->buff[i] - dest->buff[i] == 32) { continue; } if ('a' <= dest->buff[i] && dest->buff[i] <= 'z' && dest->buff[i] - src->buff[i] == 32) { continue; } return 1; } return 0; } return 1; } static int32_t X509_NodeNameValueCompare(BSL_ASN1_Buffer *src, BSL_ASN1_Buffer *dest) { // quick comparison if (X509_NodeNameCompare(src, dest) == 0) { return 0; } return X509_NodeNameCaseCompare(src, dest); } static int32_t X509_NodeCompare(BSL_ASN1_Buffer *buffOri, BSL_ASN1_Buffer *buff) { if (buffOri->tag != buff->tag) { return 1; } if (buffOri->len != buff->len) { return 1; } return memcmp(buffOri->buff, buff->buff, buff->len); } int32_t HITLS_X509_CmpNameNode(BSL_ASN1_List *nameOri, BSL_ASN1_List *name) { HITLS_X509_NameNode *nodeOri = BSL_LIST_GET_FIRST(nameOri); HITLS_X509_NameNode *node = BSL_LIST_GET_FIRST(name); while (nodeOri != NULL || node != NULL) { if (nodeOri == NULL || node == NULL) { return 1; } if (X509_NodeCompare(&nodeOri->nameType, &node->nameType) != 0) { return 1; } if (nodeOri->layer != node->layer) { return 1; } if (X509_NodeNameValueCompare(&nodeOri->nameValue, &node->nameValue) != 0) { return 1; } nodeOri = (HITLS_X509_NameNode *)BSL_LIST_GET_NEXT(nameOri); node = (HITLS_X509_NameNode *)BSL_LIST_GET_NEXT(name); } return 0; } #endif // HITLS_PKI_X509_VFY #ifdef HITLS_CRYPTO_RSA /** * RFC 4055 section 3.3 * * The key is identified by the id-RSASSA-PSS signature algorithm identifier, but the parameters field is * absent. In this case no parameter validation is needed. * The key is identified by the id-RSASSA-PSS signature algorithm identifier and the parameters are present. * In this case all parameters in the signature structure algorithm identifier MUST match the parameters * in the key structure algorithm identifier except the saltLength field. The saltLength field in the * signature parameters MUST be greater or equal to that in the key parameters field. */ static int32_t X509_CheckPssParam(CRYPT_EAL_PkeyCtx *key, int32_t algId, const CRYPT_RSA_PssPara *rsaPssParam) { if (algId != BSL_CID_RSASSAPSS) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_MD_NOT_MATCH); return HITLS_X509_ERR_MD_NOT_MATCH; } CRYPT_MD_AlgId mdId; int32_t ret = CRYPT_EAL_PkeyCtrl(key, CRYPT_CTRL_GET_RSA_MD, &mdId, sizeof(int32_t)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (mdId == CRYPT_MD_MAX) { /* If the hash algorithm is unknown, no pss parameter is specified in key. */ return HITLS_PKI_SUCCESS; } if (mdId != rsaPssParam->mdId) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_MD_NOT_MATCH); return HITLS_X509_ERR_MD_NOT_MATCH; } CRYPT_MD_AlgId mgfId; ret = CRYPT_EAL_PkeyCtrl(key, CRYPT_CTRL_GET_RSA_MGF, &mgfId, sizeof(uint32_t)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (mgfId != rsaPssParam->mgfId) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_MGF_NOT_MATCH); return HITLS_X509_ERR_MGF_NOT_MATCH; } int32_t saltLen; ret = CRYPT_EAL_PkeyCtrl(key, CRYPT_CTRL_GET_RSA_SALTLEN, &saltLen, sizeof(int32_t)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (rsaPssParam->saltLen < saltLen) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PSS_SALTLEN); return HITLS_X509_ERR_PSS_SALTLEN; } return HITLS_PKI_SUCCESS; } #endif // HITLS_CRYPTO_RSA int32_t HITLS_X509_CheckAlg(CRYPT_EAL_PkeyCtx *pubkey, const HITLS_X509_Asn1AlgId *subAlg) { uint32_t pubKeyId = CRYPT_EAL_PkeyGetId(pubkey); if (pubKeyId == CRYPT_PKEY_MAX) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_GET_SIGNID); return HITLS_X509_ERR_VFY_GET_SIGNID; } if (pubKeyId == CRYPT_PKEY_RSA) { #ifdef HITLS_CRYPTO_RSA CRYPT_RsaPadType pad; int32_t ret = CRYPT_EAL_PkeyCtrl(pubkey, CRYPT_CTRL_GET_RSA_PADDING, &pad, sizeof(pad)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (pad == CRYPT_EMSA_PSS) { return X509_CheckPssParam(pubkey, subAlg->algId, &subAlg->rsaPssParam); } #else BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ALG_UNSUPPORT); return HITLS_X509_ERR_ALG_UNSUPPORT; #endif } BslCid subSignAlg = BSL_OBJ_GetAsymAlgIdFromSignId(subAlg->algId); if (subSignAlg == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_GET_SIGNID); return HITLS_X509_ERR_VFY_GET_SIGNID; } if (pubKeyId != subSignAlg) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_SIGNALG_NOT_MATCH); return HITLS_X509_ERR_VFY_SIGNALG_NOT_MATCH; } return HITLS_PKI_SUCCESS; } #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CSR_GEN) int32_t HITLS_X509_SignAsn1Data(CRYPT_EAL_PkeyCtx *priv, CRYPT_MD_AlgId mdId, BSL_ASN1_Buffer *asn1Buff, BSL_Buffer *rawSignBuff, BSL_ASN1_BitString *sign) { BSL_ASN1_TemplateItem templItem = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}; BSL_ASN1_Template templ = {&templItem, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, asn1Buff, 1, &rawSignBuff->data, &rawSignBuff->dataLen); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } sign->len = CRYPT_EAL_PkeyGetSignLen(priv); sign->buff = (uint8_t *)BSL_SAL_Malloc(sign->len); if (sign->buff == NULL) { BSL_SAL_FREE(rawSignBuff->data); rawSignBuff->dataLen = 0; BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } ret = CRYPT_EAL_PkeySign(priv, mdId, rawSignBuff->data, rawSignBuff->dataLen, sign->buff, &sign->len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BSL_SAL_FREE(sign->buff); sign->len = 0; BSL_SAL_FREE(rawSignBuff->data); rawSignBuff->dataLen = 0; } return ret; } #endif static uint32_t X509_GetHashId(const HITLS_X509_Asn1AlgId *alg) { uint32_t hashId = BSL_OBJ_GetHashIdFromSignId(alg->algId); if (hashId != BSL_CID_UNKNOWN) { return hashId; } if (alg->algId == BSL_CID_RSASSAPSS) { return alg->rsaPssParam.mdId; } return BSL_CID_UNKNOWN; } #if defined(HITLS_CRYPTO_RSA) || defined(HITLS_CRYPTO_SM2) static int32_t X509_CtrlAlgInfo(const CRYPT_EAL_PkeyCtx *pubKey, uint32_t hashId, const HITLS_X509_Asn1AlgId *alg) { #ifndef HITLS_CRYPTO_RSA (void)hashId; #endif switch (alg->algId) { #ifdef HITLS_CRYPTO_RSA case BSL_CID_MD5WITHRSA: case BSL_CID_SHA1WITHRSA: case BSL_CID_SHA224WITHRSAENCRYPTION: case BSL_CID_SHA256WITHRSAENCRYPTION: case BSL_CID_SHA384WITHRSAENCRYPTION: case BSL_CID_SHA512WITHRSAENCRYPTION: case BSL_CID_SM3WITHRSAENCRYPTION: return CRYPT_EAL_PkeyCtrl((CRYPT_EAL_PkeyCtx *)(uintptr_t)pubKey, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &hashId, sizeof(hashId)); case BSL_CID_RSASSAPSS: { BSL_Param param[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, (void *)(uintptr_t)&alg->rsaPssParam.mdId, sizeof(alg->rsaPssParam.mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, (void *)(uintptr_t)&alg->rsaPssParam.mgfId, sizeof(alg->rsaPssParam.mgfId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, (void *)(uintptr_t)&alg->rsaPssParam.saltLen, sizeof(alg->rsaPssParam.saltLen), 0}, BSL_PARAM_END }; return CRYPT_EAL_PkeyCtrl((CRYPT_EAL_PkeyCtx *)(uintptr_t)pubKey, CRYPT_CTRL_SET_RSA_EMSA_PSS, param, 0); } #endif #ifdef HITLS_CRYPTO_SM2 case BSL_CID_SM2DSAWITHSM3: if (alg->sm2UserId.data != NULL) { return CRYPT_EAL_PkeyCtrl((CRYPT_EAL_PkeyCtx *)(uintptr_t)pubKey, CRYPT_CTRL_SET_SM2_USER_ID, alg->sm2UserId.data, alg->sm2UserId.dataLen); } return HITLS_PKI_SUCCESS; #endif default: return HITLS_PKI_SUCCESS; } } #endif int32_t HITLS_X509_CheckSignature(const CRYPT_EAL_PkeyCtx *pubKey, uint8_t *rawData, uint32_t rawDataLen, const HITLS_X509_Asn1AlgId *alg, const BSL_ASN1_BitString *signature) { int32_t ret; uint32_t hashId = X509_GetHashId(alg); if (hashId == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_GET_HASHID); return HITLS_X509_ERR_VFY_GET_HASHID; } CRYPT_EAL_PkeyCtx *verifyPubKey = CRYPT_EAL_PkeyDupCtx(pubKey); if (verifyPubKey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_DUP_PUBKEY); return HITLS_X509_ERR_VFY_DUP_PUBKEY; } #if defined(HITLS_CRYPTO_RSA) || defined(HITLS_CRYPTO_SM2) ret = X509_CtrlAlgInfo(verifyPubKey, hashId, alg); if (ret != HITLS_PKI_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(verifyPubKey); BSL_ERR_PUSH_ERROR(ret); return ret; } #endif ret = CRYPT_EAL_PkeyVerify(verifyPubKey, hashId, rawData, rawDataLen, signature->buff, signature->len); CRYPT_EAL_PkeyFreeCtx(verifyPubKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #ifdef HITLS_PKI_X509_VFY static int32_t X509_CheckAuthCertIssuer(BslList *authCertIssue, BSL_ASN1_List *issueName) { HITLS_X509_GeneralName *name = NULL; for (HITLS_X509_GeneralName *tmp = BSL_LIST_GET_FIRST(authCertIssue); tmp != NULL; tmp = BSL_LIST_GET_NEXT(authCertIssue)) { if (tmp->type == HITLS_X509_GN_DNNAME) { name = tmp; break; } } if (name == NULL) { return HITLS_X509_ERR_VFY_AKI_SKI_NOT_MATCH; } return HITLS_X509_CmpNameNode((BslList *)name->value.data, issueName); } int32_t HITLS_X509_CheckAki(HITLS_X509_Ext *issueExt, HITLS_X509_Ext *subjectExt, BSL_ASN1_List *issueName, BSL_ASN1_Buffer *serialNum) { HITLS_X509_ExtAki aki = {0}; HITLS_X509_ExtSki ski = {0}; int32_t ret = X509_ExtCtrl(issueExt, HITLS_X509_EXT_GET_SKI, (void *)&ski, sizeof(HITLS_X509_ExtSki)); if (ret != HITLS_PKI_SUCCESS && ret != HITLS_X509_ERR_EXT_NOT_FOUND) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (ret == HITLS_X509_ERR_EXT_NOT_FOUND) { return HITLS_PKI_SUCCESS; } ret = X509_ExtCtrl(subjectExt, HITLS_X509_EXT_GET_AKI, (void *)&aki, sizeof(HITLS_X509_ExtAki)); if (ret != HITLS_PKI_SUCCESS && ret != HITLS_X509_ERR_EXT_NOT_FOUND) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (ret == HITLS_X509_ERR_EXT_NOT_FOUND) { return HITLS_PKI_SUCCESS; } if (ski.kid.dataLen != aki.kid.dataLen || memcmp(ski.kid.data, aki.kid.data, ski.kid.dataLen) != 0) { HITLS_X509_ClearAuthorityKeyId(&aki); BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_AKI_SKI_NOT_MATCH); return HITLS_X509_ERR_VFY_AKI_SKI_NOT_MATCH; } if (aki.issuerName != NULL) { ret = X509_CheckAuthCertIssuer(aki.issuerName, issueName); HITLS_X509_ClearAuthorityKeyId(&aki); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_AKI_SKI_NOT_MATCH); return HITLS_X509_ERR_VFY_AKI_SKI_NOT_MATCH; } } if (aki.serialNum.dataLen != 0 && aki.serialNum.data != NULL) { if (aki.serialNum.dataLen != serialNum->len || memcmp(aki.serialNum.data, serialNum->buff, aki.serialNum.dataLen) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_AKI_SKI_NOT_MATCH); return HITLS_X509_ERR_VFY_AKI_SKI_NOT_MATCH; } } return HITLS_PKI_SUCCESS; } #endif // HITLS_PKI_X509_VFY #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CSR_GEN) #ifdef HITLS_CRYPTO_RSA static int32_t X509_SetRsaPssDefaultParam(CRYPT_EAL_PkeyCtx *prvKey, int32_t mdId, HITLS_X509_Asn1AlgId *signAlgId) { int32_t currentHash; int32_t ret = CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_GET_RSA_MD, &currentHash, sizeof(int32_t)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (currentHash == BSL_CID_UNKNOWN) { signAlgId->algId = BSL_CID_RSASSAPSS; signAlgId->rsaPssParam.mdId = mdId; signAlgId->rsaPssParam.mgfId = mdId; signAlgId->rsaPssParam.saltLen = 20; // 20: default saltLen BSL_Param param[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &signAlgId->rsaPssParam.saltLen, sizeof(signAlgId->rsaPssParam.saltLen), 0}, BSL_PARAM_END}; return CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_SET_RSA_EMSA_PSS, param, 0); } if (currentHash != mdId) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_MD_NOT_MATCH); return HITLS_X509_ERR_MD_NOT_MATCH; } int32_t currentMgfId; ret = CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_GET_RSA_MGF, &currentMgfId, sizeof(int32_t)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } int32_t saltLen; ret = CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_GET_RSA_SALTLEN, &saltLen, sizeof(int32_t)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } signAlgId->algId = BSL_CID_RSASSAPSS; signAlgId->rsaPssParam.mdId = currentHash; signAlgId->rsaPssParam.mgfId = currentMgfId; signAlgId->rsaPssParam.saltLen = saltLen; return ret; } static int32_t X509_SetRsaPssParam(CRYPT_EAL_PkeyCtx *prvKey, int32_t mdId, const HITLS_X509_SignAlgParam *algParam, bool checkKeyParam, HITLS_X509_Asn1AlgId *signAlgId) { if (algParam->rsaPss.mdId != (CRYPT_MD_AlgId)mdId) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_MD_NOT_MATCH); return HITLS_X509_ERR_MD_NOT_MATCH; } if (checkKeyParam) { int32_t ret = X509_CheckPssParam(prvKey, algParam->algId, &algParam->rsaPss); if (ret != HITLS_PKI_SUCCESS) { return ret; } } signAlgId->algId = BSL_CID_RSASSAPSS; signAlgId->rsaPssParam = algParam->rsaPss; BSL_Param param[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, (void *)&signAlgId->rsaPssParam.mdId, sizeof(algParam->rsaPss.mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, (void *)&signAlgId->rsaPssParam.mgfId, sizeof(algParam->rsaPss.mgfId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, (void *)&signAlgId->rsaPssParam.saltLen, sizeof(algParam->rsaPss.saltLen), 0}, BSL_PARAM_END}; return CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_SET_RSA_EMSA_PSS, param, 0); } static int32_t X509_SetRsaPkcsParam(CRYPT_EAL_PkeyCtx *prvKey, int32_t mdId, bool setPadding) { if (setPadding) { CRYPT_RsaPadType pad = CRYPT_EMSA_PKCSV15; int32_t ret = CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(CRYPT_RsaPadType)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } int32_t pkcs15Param = mdId; return CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcs15Param, sizeof(int32_t)); } static int32_t X509_SetRsaSignParam(CRYPT_EAL_PkeyCtx *prvKey, int32_t mdId, const HITLS_X509_SignAlgParam *algParam, HITLS_X509_Asn1AlgId *signAlgId) { CRYPT_RsaPadType pad; int32_t ret = CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_GET_RSA_PADDING, &pad, sizeof(CRYPT_RsaPadType)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } switch (pad) { case CRYPT_EMSA_PSS: if (algParam != NULL) { return X509_SetRsaPssParam(prvKey, mdId, algParam, true, signAlgId); } else { return X509_SetRsaPssDefaultParam(prvKey, mdId, signAlgId); } case CRYPT_EMSA_PKCSV15: if (algParam != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SIGN_PARAM); return HITLS_X509_ERR_SIGN_PARAM; } ret = X509_SetRsaPkcsParam(prvKey, mdId, false); break; default: if (algParam != NULL) { return X509_SetRsaPssParam(prvKey, mdId, algParam, false, signAlgId); } else { ret = X509_SetRsaPkcsParam(prvKey, mdId, true); } break; } if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } signAlgId->algId = BSL_OBJ_GetSignIdFromHashAndAsymId(BSL_CID_RSA, mdId); if (signAlgId->algId == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ENCODE_SIGNID); return HITLS_X509_ERR_ENCODE_SIGNID; } return HITLS_PKI_SUCCESS; } #endif // HITLS_CRYPTO_RSA #ifdef HITLS_CRYPTO_SM2 static int32_t X509_SetSm2SignParam(CRYPT_EAL_PkeyCtx *prvKey, int32_t mdId, const HITLS_X509_SignAlgParam *algParam, HITLS_X509_Asn1AlgId *signAlgId) { int32_t ret; if (mdId != BSL_CID_SM3) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ENCODE_SIGNID); return HITLS_X509_ERR_ENCODE_SIGNID; } signAlgId->algId = BSL_CID_SM2DSAWITHSM3; if (algParam != NULL && algParam->sm2UserId.data != NULL && algParam->sm2UserId.dataLen != 0) { ret = CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_SET_SM2_USER_ID, algParam->sm2UserId.data, algParam->sm2UserId.dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } signAlgId->sm2UserId.data = BSL_SAL_Dump(algParam->sm2UserId.data, algParam->sm2UserId.dataLen); if (signAlgId->sm2UserId.data == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } signAlgId->sm2UserId.dataLen = algParam->sm2UserId.dataLen; } return HITLS_PKI_SUCCESS; } #endif // HITLS_CRYPTO_SM2 int32_t HITLS_X509_Sign(int32_t mdId, const CRYPT_EAL_PkeyCtx *prvKey, const HITLS_X509_SignAlgParam *algParam, void *obj, HITLS_X509_SignCb signCb) { #if !defined(HITLS_CRYPTO_RSA) && !defined(HITLS_CRYPTO_SM2) (void)algParam; #endif if (!X509_IsValidHashAlg(mdId)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_HASHID); return HITLS_X509_ERR_HASHID; } CRYPT_PKEY_AlgId keyAlgId = CRYPT_EAL_PkeyGetId(prvKey); if (keyAlgId == CRYPT_PKEY_MAX) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_SIGN_ALG); return HITLS_X509_ERR_CERT_SIGN_ALG; } int32_t ret; CRYPT_EAL_PkeyCtx *signKey = (CRYPT_EAL_PkeyCtx *)(uintptr_t)prvKey; HITLS_X509_Asn1AlgId signAlgId = {0}; switch (keyAlgId) { #ifdef HITLS_CRYPTO_RSA case CRYPT_PKEY_RSA: signKey = CRYPT_EAL_PkeyDupCtx(prvKey); if (signKey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_DUP_PUBKEY); return HITLS_X509_ERR_VFY_DUP_PUBKEY; } ret = X509_SetRsaSignParam(signKey, mdId, algParam, &signAlgId); if (ret != HITLS_PKI_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(signKey); BSL_ERR_PUSH_ERROR(ret); return ret; } break; #endif #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_ED25519) case CRYPT_PKEY_ECDSA: case CRYPT_PKEY_ED25519: signAlgId.algId = BSL_OBJ_GetSignIdFromHashAndAsymId((BslCid)keyAlgId, (BslCid)mdId); if (signAlgId.algId == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ENCODE_SIGNID); return HITLS_X509_ERR_ENCODE_SIGNID; } break; #endif #ifdef HITLS_CRYPTO_SM2 case CRYPT_PKEY_SM2: signKey = CRYPT_EAL_PkeyDupCtx(prvKey); if (signKey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_DUP_PUBKEY); return HITLS_X509_ERR_VFY_DUP_PUBKEY; } ret = X509_SetSm2SignParam(signKey, mdId, algParam, &signAlgId); if (ret != HITLS_PKI_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(signKey); BSL_ERR_PUSH_ERROR(ret); return ret; } break; #endif default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_SIGN_ALG); return HITLS_X509_ERR_CERT_SIGN_ALG; } ret = signCb(mdId, signKey, &signAlgId, obj); #if defined(HITLS_CRYPTO_RSA) || defined(HITLS_CRYPTO_SM2) if (keyAlgId == CRYPT_PKEY_RSA || keyAlgId == CRYPT_PKEY_SM2) { CRYPT_EAL_PkeyFreeCtx(signKey); } #endif return ret; } #endif // HITLS_PKI_X509_CRT_GEN || HITLS_PKI_X509_CRL_GEN || HITLS_PKI_X509_CSR_GEN #endif // HITLS_PKI_X509
2301_79861745/bench_create
pki/x509_common/src/hitls_x509_common.c
C
unknown
40,199
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_X509 #include <stdint.h> #include "securec.h" #include "sal_atomic.h" #include "bsl_obj.h" #include "bsl_sal.h" #include "bsl_obj_internal.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_encode_decode_key.h" #include "hitls_pki_errno.h" #include "hitls_x509_local.h" #define HITLS_X509_DNNAME_MAX_NUM 100 #define SM2_MAX_ID_BITS 65535 #define SM2_MAX_ID_LENGTH (SM2_MAX_ID_BITS / 8) void HITLS_X509_FreeNameNode(HITLS_X509_NameNode *node) { if (node == NULL) { return; } BSL_SAL_FREE(node->nameType.buff); node->nameType.len = 0; node->nameType.tag = 0; BSL_SAL_FREE(node->nameValue.buff); node->nameValue.len = 0; node->nameValue.tag = 0; BSL_SAL_Free(node); } int32_t HITLS_X509_RefUp(BSL_SAL_RefCount *references, int32_t *val, uint32_t valLen) { if (val == NULL || valLen != sizeof(int)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } return BSL_SAL_AtomicUpReferences(references, val); } int32_t HITLS_X509_GetList(BslList *list, void *val, uint32_t valLen) { if (list == NULL || val == NULL || valLen != sizeof(BslList *)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *(BslList **)val = list; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_GetListBuff(BslList *list, void *val, uint32_t valLen) { if (list == NULL || val == NULL || valLen != sizeof(BslList *)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } BSL_ASN1_Buffer tmp = {0}; int32_t ret = HITLS_X509_EncodeNameList((BSL_ASN1_List *)list, &tmp); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer *res = (BSL_Buffer *)val; BSL_ASN1_TemplateItem item[] = {{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}}; BSL_ASN1_Template templ = {item, 1}; ret = BSL_ASN1_EncodeTemplate(&templ, &tmp, 1, &res->data, &res->dataLen); if (ret != BSL_SUCCESS) { BSL_SAL_Free(tmp.buff); return ret; } BSL_SAL_Free(tmp.buff); return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_GetPubKey(void *ealPubKey, void **val) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t ret = CRYPT_EAL_PkeyUpRef((CRYPT_EAL_PkeyCtx *)ealPubKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *val = ealPubKey; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_GetSignAlg(BslCid signAlgId, int32_t *val, uint32_t valLen) { if (val == NULL || valLen != sizeof(BslCid)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *val = signAlgId; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_GetSignMdAlg(const HITLS_X509_Asn1AlgId *signAlgId, int32_t *val, int32_t valLen) { if (val == NULL || valLen != sizeof(BslCid)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *val = signAlgId->algId == BSL_CID_RSASSAPSS ? signAlgId->rsaPssParam.mdId : BSL_OBJ_GetHashIdFromSignId(signAlgId->algId); return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_GetEncodeLen(uint32_t encodeLen, uint32_t *val, uint32_t valLen) { if (val == NULL || valLen != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *(uint32_t *)val = encodeLen; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_GetEncodeData(uint8_t *rawData, uint8_t **val) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *val = rawData; return HITLS_PKI_SUCCESS; } bool X509_IsValidHashAlg(CRYPT_MD_AlgId id) { return id == CRYPT_MD_MD5 || id == CRYPT_MD_SHA1 || id == CRYPT_MD_SHA224 || id == CRYPT_MD_SHA256 || id == CRYPT_MD_SHA384 || id == CRYPT_MD_SHA512 || id == CRYPT_MD_SM3; } #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CSR_GEN) || defined(HITLS_PKI_X509_CRL_GEN) int32_t HITLS_X509_SetPkey(void **pkey, void *val) { CRYPT_EAL_PkeyCtx *src = (CRYPT_EAL_PkeyCtx *)val; CRYPT_EAL_PkeyCtx **dest = (CRYPT_EAL_PkeyCtx **)pkey; if (*dest != NULL) { CRYPT_EAL_PkeyFreeCtx(*dest); *dest = NULL; } *dest = CRYPT_EAL_PkeyDupCtx(src); if (*dest == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_KEY); return HITLS_X509_ERR_SET_KEY; } return HITLS_PKI_SUCCESS; } static HITLS_X509_NameNode *DupNameNode(const HITLS_X509_NameNode *src) { /* Src is not null. */ HITLS_X509_NameNode *dest = BSL_SAL_Malloc(sizeof(HITLS_X509_NameNode)); if (dest == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } dest->layer = src->layer; // nameType dest->nameType = src->nameType; dest->nameType.len = src->nameType.len; if (dest->nameType.len != 0) { dest->nameType.buff = BSL_SAL_Dump(src->nameType.buff, src->nameType.len); if (dest->nameType.buff == NULL) { BSL_SAL_Free(dest); BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return NULL; } } // nameValue dest->nameValue = src->nameValue; dest->nameValue.len = src->nameValue.len; if (dest->nameValue.len != 0) { dest->nameValue.buff = BSL_SAL_Dump(src->nameValue.buff, src->nameValue.len); if (dest->nameValue.buff == NULL) { BSL_SAL_Free(dest->nameType.buff); BSL_SAL_Free(dest); BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return NULL; } } return dest; } #define X509_DN_NAME_ELEM_NUMBER 2 static int32_t X509EncodeNameNodeEntry(const HITLS_X509_NameNode *nameNode, BSL_ASN1_Buffer *asn1Buff) { BSL_ASN1_Buffer asnArr[X509_DN_NAME_ELEM_NUMBER] = { nameNode->nameType, nameNode->nameValue, }; BSL_ASN1_TemplateItem dnTempl[] = { {BSL_ASN1_TAG_OBJECT_ID, 0, 0}, {BSL_ASN1_TAG_ANY, 0, 0} }; BSL_ASN1_Buffer asnDnBuff = {}; BSL_ASN1_Template dntTempl = {dnTempl, sizeof(dnTempl) / sizeof(dnTempl[0])}; int32_t ret = BSL_ASN1_EncodeTemplate(&dntTempl, asnArr, X509_DN_NAME_ELEM_NUMBER, &asnDnBuff.buff, &asnDnBuff.len); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } asnDnBuff.tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; BSL_ASN1_TemplateItem seqItem = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}; BSL_ASN1_Template seqTempl = {&seqItem, 1}; ret = BSL_ASN1_EncodeTemplate(&seqTempl, &asnDnBuff, 1, &asn1Buff->buff, &asn1Buff->len); BSL_SAL_FREE(asnDnBuff.buff); return ret; } typedef struct { HITLS_X509_NameNode *node; BSL_ASN1_Buffer *encode; } NameNodePack; /** * X.690: 11.6 Set-of components * https://www.itu.int/rec/T-REC-X.690-202102-I/en * The encodings of the component values of a set-of value shall appear in ascending order, the encodings * being compared as octet strings with the shorter components being padded at their trailing end with 0-octets. * NOTE - The padding octets are for comparison purposes only and do not appear in the encodings. */ static int32_t CmpDnNameByEncode(const void *pDnName1, const void *pDnName2) { const NameNodePack *node1 = *(const NameNodePack **)(uintptr_t)pDnName1; const NameNodePack *node2 = *(const NameNodePack **)(uintptr_t)pDnName2; int res; BSL_ASN1_Buffer *asn1Buff = node1->encode; BSL_ASN1_Buffer *asn2Buff = node2->encode; if (asn1Buff->len == asn2Buff->len) { res = memcmp(asn1Buff->buff, asn2Buff->buff, asn2Buff->len); } else { uint32_t minSize = asn1Buff->len < asn2Buff->len ? asn1Buff->len : asn2Buff->len; res = memcmp(asn1Buff->buff, asn2Buff->buff, minSize); if (res == 0) { res = asn1Buff->len == minSize ? -1 : 1; } } return res; } /** * RFC 5280: * section 7.1: * Representation of internationalized names in distinguished names is * covered in Sections 4.1.2.4, Issuer Name, and 4.1.2.6, Subject Name. * Standard naming attributes, such as common name, employ the * DirectoryString type, which supports internationalized names through * a variety of language encodings. Conforming implementations MUST * support UTF8String and PrintableString. * appendix-A.1: * X520SerialNumber ::= PrintableString (SIZE (1..ub-serial-number)) * X520countryName ::= PrintableString * X520dnQualifier ::= PrintableString */ static uint8_t GetAsn1TypeByCid(BslCid cid) { switch (cid) { case BSL_CID_AT_SERIALNUMBER: case BSL_CID_AT_COUNTRYNAME: case BSL_CID_AT_DNQUALIFIER: return BSL_ASN1_TAG_PRINTABLESTRING; case BSL_CID_DOMAINCOMPONENT: return BSL_ASN1_TAG_IA5STRING; default: return BSL_ASN1_TAG_UTF8STRING; } } static void FreeNodePack(NameNodePack *node) { if (node == NULL) { return; } if (node->encode != NULL) { // the node->node has been pushed in other list. BSL_SAL_FREE(node->encode->buff); BSL_SAL_Free(node->encode); } BSL_SAL_Free(node); return; } int32_t HITLS_X509_SetNameList(BslList **dest, void *val, uint32_t valLen) { if (dest == NULL || val == NULL || valLen != sizeof(BslList)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } BslList *src = (BslList *)val; BSL_LIST_FREE(*dest, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); *dest = BSL_LIST_Copy(src, (BSL_LIST_PFUNC_DUP)DupNameNode, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); if (*dest == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_NAME_LIST); return HITLS_X509_ERR_SET_NAME_LIST; } return HITLS_PKI_SUCCESS; } static int32_t FillNameNodes(HITLS_X509_NameNode *layer2, BslCid cid, uint8_t *data, uint32_t dataLen) { BslOidString *oid = BSL_OBJ_GetOID(cid); if (oid == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_DNNAME_UNKNOWN); return HITLS_X509_ERR_SET_DNNAME_UNKNOWN; } layer2->layer = 2; // 2: The layer of sequence layer2->nameType.tag = BSL_ASN1_TAG_OBJECT_ID; layer2->nameValue.tag = GetAsn1TypeByCid(cid); layer2->nameType.buff = BSL_SAL_Dump((uint8_t *)oid->octs, oid->octetLen); layer2->nameValue.buff = BSL_SAL_Dump(data, dataLen); if (layer2->nameType.buff == NULL || layer2->nameValue.buff == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } layer2->nameType.len = oid->octetLen; layer2->nameValue.len = dataLen; return HITLS_PKI_SUCCESS; } static int32_t X509AddDnNameItemToList(BslList *dnNameList, BslCid cid, uint8_t *data, uint32_t dataLen) { if (data == NULL || dataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } const BslAsn1DnInfo *asn1StrInfo = BSL_OBJ_GetDnInfoFromCid(cid); if (asn1StrInfo == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_DNNAME_UNKNOWN); return HITLS_X509_ERR_SET_DNNAME_UNKNOWN; } if (asn1StrInfo->max != -1 && ((int32_t)dataLen < asn1StrInfo->min || (int32_t)dataLen > asn1StrInfo->max)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_DNNAME_INVALID_LEN); return HITLS_X509_ERR_SET_DNNAME_INVALID_LEN; } BSL_ASN1_Buffer *encode = BSL_SAL_Calloc(1u, sizeof(HITLS_X509_NameNode)); if (encode == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } HITLS_X509_NameNode *layer2 = BSL_SAL_Calloc(1, sizeof(HITLS_X509_NameNode)); if (layer2 == NULL) { BSL_SAL_FREE(encode); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = FillNameNodes(layer2, cid, data, dataLen); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(encode); HITLS_X509_FreeNameNode(layer2); return ret; } ret = X509EncodeNameNodeEntry(layer2, encode); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(encode); HITLS_X509_FreeNameNode(layer2); return ret; } NameNodePack pack = {layer2, encode}; ret = HITLS_X509_AddListItemDefault(&pack, sizeof(NameNodePack), dnNameList); if (ret != BSL_SUCCESS) { HITLS_X509_FreeNameNode(layer2); BSL_SAL_FREE(encode->buff); BSL_SAL_Free(encode); } return ret; } static int32_t X509AddDnNamesToList(BslList *list, BslList *dnNameList) { HITLS_X509_NameNode *layer1 = BSL_SAL_Calloc(1, sizeof(HITLS_X509_NameNode)); if (layer1 == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } layer1->layer = 1; int32_t ret = BSL_LIST_AddElement(list, layer1, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); HITLS_X509_FreeNameNode(layer1); return ret; } NameNodePack *node = BSL_LIST_GET_FIRST(dnNameList); while (node != NULL) { ret = BSL_LIST_AddElement(list, node->node, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } node = BSL_LIST_GET_NEXT(dnNameList); } return ret; } BslList *HITLS_X509_DnListNew(void) { return BSL_LIST_New(sizeof(HITLS_X509_NameNode)); } void HITLS_X509_DnListFree(BslList *dnList) { BSL_LIST_FREE(dnList, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); } int32_t HITLS_X509_AddDnName(BslList *list, HITLS_X509_DN *dnNames, uint32_t size) { if (list == NULL || dnNames == NULL || size == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (BSL_LIST_COUNT(list) == HITLS_X509_DNNAME_MAX_NUM) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_DNNAME_TOOMUCH); return HITLS_X509_ERR_SET_DNNAME_TOOMUCH; } BslList *dnNameList = BSL_LIST_New(sizeof(NameNodePack)); if (dnNameList == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret; for (uint32_t i = 0; i < size; i++) { ret = X509AddDnNameItemToList(dnNameList, dnNames[i].cid, dnNames[i].data, dnNames[i].dataLen); if (ret != HITLS_PKI_SUCCESS) { goto EXIT; } } // sort dnNameList = BSL_LIST_Sort(dnNameList, CmpDnNameByEncode); if (dnNameList == NULL) { ret = HITLS_X509_ERR_SORT_NAME_NODE; goto EXIT; } // add dnNameList to list ret = X509AddDnNamesToList(list, dnNameList); EXIT: BSL_LIST_FREE(dnNameList, (BSL_LIST_PFUNC_FREE)FreeNodePack); return ret; } #endif #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) int32_t HITLS_X509_SetSerial(BSL_ASN1_Buffer *serial, const void *val, uint32_t valLen) { if (valLen <= 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_INVALID_SERIAL_NUM); return HITLS_X509_ERR_CERT_INVALID_SERIAL_NUM; } const uint8_t *src = (const uint8_t *)val; serial->buff = BSL_SAL_Dump(src, valLen); if (serial->buff == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } serial->len = valLen; serial->tag = BSL_ASN1_TAG_INTEGER; return HITLS_PKI_SUCCESS; } #endif #if defined(HITLS_PKI_X509_CRT) || defined(HITLS_PKI_X509_CRL) int32_t HITLS_X509_GetSerial(BSL_ASN1_Buffer *serial, void *val, uint32_t valLen) { if (valLen != sizeof(BSL_Buffer)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (serial->buff == NULL || serial->len == 0 || serial->tag != BSL_ASN1_TAG_INTEGER) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } BSL_Buffer *buff = (BSL_Buffer *)val; buff->data = serial->buff; buff->dataLen = serial->len; return HITLS_PKI_SUCCESS; } #endif #ifdef HITLS_CRYPTO_SM2 int32_t HITLS_X509_SetSm2UserId(BSL_Buffer *sm2UserId, void *val, uint32_t valLen) { if (valLen == 0 || valLen > SM2_MAX_ID_LENGTH) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } BSL_SAL_FREE(sm2UserId->data); sm2UserId->data = BSL_SAL_Calloc(valLen, 1u); if (sm2UserId->data == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } (void) memcpy_s(sm2UserId->data, valLen, (uint8_t *)val, valLen); sm2UserId->dataLen = (uint32_t)valLen; return HITLS_PKI_SUCCESS; } #endif // HITLS_CRYPTO_SM2 #endif // HITLS_PKI_X509
2301_79861745/bench_create
pki/x509_common/src/hitls_x509_ctrl.c
C
unknown
17,567
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_X509 #include "securec.h" #include "bsl_obj.h" #include "bsl_obj_internal.h" #include "bsl_sal.h" #include "bsl_types.h" #include "bsl_err_internal.h" #include "hitls_pki_errno.h" #include "hitls_x509_local.h" #define BITS_OF_BYTE 8 #define HITLS_X509_EXT_NOT_FOUND 1 #define HITLS_X509_EXT_KEYUSAGE_UNUSED_BIT 0xFFFF7F00 // Only 9 bits are used. typedef enum { HITLS_X509_EXT_OID_IDX, HITLS_X509_EXT_CRITICAL_IDX, HITLS_X509_EXT_VALUE_IDX, HITLS_X509_EXT_MAX } HITLS_X509_EXT_IDX; /** * RFC 5280: section-4.2.1.9 * BasicConstraints ::= SEQUENCE { * cA BOOLEAN DEFAULT FALSE, * pathLenConstraint INTEGER (0..MAX) OPTIONAL } */ static BSL_ASN1_TemplateItem g_bConsTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_BOOLEAN, BSL_ASN1_FLAG_DEFAULT, 1}, {BSL_ASN1_TAG_INTEGER, BSL_ASN1_FLAG_OPTIONAL, 1}, }; typedef enum { HITLS_X509_EXT_BC_CA_IDX, HITLS_X509_EXT_BC_PATHLEN_IDX, HITLS_X509_EXT_BC_MAX } HITLS_X509_EXT_BASICCONSTRAINTS; /** * RFC 5280: section-4.2.1.1 * AuthorityKeyIdentifier ::= SEQUENCE { * keyIdentifier [0] KeyIdentifier OPTIONAL, * authorityCertIssuer [1] GeneralNames OPTIONAL, * authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL } */ #define HITLS_X509_CTX_SPECIFIC_TAG_AKID_KID 0 #define HITLS_X509_CTX_SPECIFIC_TAG_AKID_ISSUER 1 #define HITLS_X509_CTX_SPECIFIC_TAG_AKID_SERIAL 2 static BSL_ASN1_TemplateItem g_akidTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* KeyIdentifier */ {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_X509_CTX_SPECIFIC_TAG_AKID_KID, BSL_ASN1_FLAG_OPTIONAL, 1}, /* authorityCertIssuer */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_X509_CTX_SPECIFIC_TAG_AKID_ISSUER, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY, 1}, /* authorityCertSerialNumber */ {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_X509_CTX_SPECIFIC_TAG_AKID_SERIAL, BSL_ASN1_FLAG_OPTIONAL, 1}, }; typedef enum { HITLS_X509_EXT_AKI_KID_IDX, HITLS_X509_EXT_AKI_ISSUER_IDX, HITLS_X509_EXT_AKI_SERIAL_IDX, HITLS_X509_EXT_AKI_MAX, } HITLS_X509_EXT_AKI; /** * RFC 5280: section-4.2.1.2 * Two common methods for generating key identifiers from the public key are: * (1) The kid is composed of 160-bit sha1 hash of the BIT STRING subjectPublicKey. * (2) The kid is composed of a 4-bit type field with the value 0100 followed by the lease significant 60 bits of the * sha1 hash of the BIT STRING subjectPublicKey. */ #define HITLS_X509_KID_MIN_LEN 8 #define HITLS_X509_KID_MAX_LEN 20 #define HITLS_X509_CRLNUMBER_MIN_LEN 1 #define HITLS_X509_CRLNUMBER_MAX_LEN 20 /** * RFC 5280: section-4.2.1.6 * SubjectAltName ::= GeneralNames * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName * GeneralName ::= CHOICE { * otherName [0] OtherName, -- not support * rfc822Name [1] IA5String, * dNSName [2] IA5String, * x400Address [3] ORAddress, -- not support * directoryName [4] Name, * ediPartyName [5] EDIPartyName, -- not support * uniformResourceIdentifier [6] IA5String, * iPAddress [7] OCTET STRING, * registeredID [8] OBJECT IDENTIFIER -- not support * } */ #define HITLS_X509_GENERALNAME_OTHER_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | 0) #define HITLS_X509_GENERALNAME_RFC822_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | 1) #define HITLS_X509_GENERALNAME_DNS_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | 2) #define HITLS_X509_GENERALNAME_X400_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | 3) #define HITLS_X509_GENERALNAME_DIR_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | 4) #define HITLS_X509_GENERALNAME_EDI_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | 5) #define HITLS_X509_GENERALNAME_URI_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | 6) #define HITLS_X509_GENERALNAME_IP_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | 7) #define HITLS_X509_GENERALNAME_RID_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | 8) typedef struct { uint8_t tag; int32_t type; } HITLS_X509_GeneralNameMap; static HITLS_X509_GeneralNameMap g_generalNameMap[] = { {HITLS_X509_GENERALNAME_OTHER_TAG, HITLS_X509_GN_OTHER}, {HITLS_X509_GENERALNAME_RFC822_TAG, HITLS_X509_GN_EMAIL}, {HITLS_X509_GENERALNAME_DNS_TAG, HITLS_X509_GN_DNS}, {HITLS_X509_GENERALNAME_X400_TAG, HITLS_X509_GN_X400}, {HITLS_X509_GENERALNAME_DIR_TAG, HITLS_X509_GN_DNNAME}, {HITLS_X509_GENERALNAME_EDI_TAG, HITLS_X509_GN_EDI}, {HITLS_X509_GENERALNAME_URI_TAG, HITLS_X509_GN_URI}, {HITLS_X509_GENERALNAME_IP_TAG, HITLS_X509_GN_IP}, {HITLS_X509_GENERALNAME_RID_TAG, HITLS_X509_GN_RID}, }; static int32_t CmpExtByCid(const void *pExt, const void *pCid) { const HITLS_X509_ExtEntry *ext = pExt; BslCid cid = *(const BslCid *)pCid; return cid == ext->cid ? 0 : HITLS_X509_EXT_NOT_FOUND; } #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CRL_PARSE) || defined(HITLS_PKI_X509_CSR) static int32_t CmpExtByOid(const void *pExt, const void *pOid) { const HITLS_X509_ExtEntry *ext = pExt; const BSL_ASN1_Buffer *oid = pOid; if (ext->extnId.len != oid->len) { return HITLS_X509_EXT_NOT_FOUND; } return memcmp(ext->extnId.buff, oid->buff, oid->len) == 0 ? 0 : HITLS_X509_EXT_NOT_FOUND; } static int32_t ParseExtKeyUsage(HITLS_X509_ExtEntry *extEntry, HITLS_X509_CertExt *ext) { uint32_t len; uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_BITSTRING, &temp, &tempLen, &len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Buffer asn = {BSL_ASN1_TAG_BITSTRING, len, temp}; BSL_ASN1_BitString bitString = {0}; ret = BSL_ASN1_DecodePrimitiveItem(&asn, &bitString); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (bitString.len > sizeof(ext->keyUsage)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_EXT_KU); return HITLS_X509_ERR_PARSE_EXT_KU; } for (uint32_t i = 0; i < bitString.len; i++) { ext->keyUsage |= (bitString.buff[i] << (BITS_OF_BYTE * i)); } ext->extFlags |= HITLS_X509_EXT_FLAG_KUSAGE; return HITLS_PKI_SUCCESS; } static int32_t ParseExtBasicConstraints(HITLS_X509_ExtEntry *extEntry, HITLS_X509_CertExt *ext) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; BSL_ASN1_Buffer asnArr[HITLS_X509_EXT_BC_MAX] = {0}; BSL_ASN1_Template templ = {g_bConsTempl, sizeof(g_bConsTempl) / sizeof(g_bConsTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asnArr, HITLS_X509_EXT_BC_MAX); if (tempLen != 0) { ret = HITLS_X509_ERR_PARSE_EXT_BUF; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (asnArr[HITLS_X509_EXT_BC_CA_IDX].tag != 0) { ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_EXT_BC_CA_IDX], &ext->isCa); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } if (asnArr[HITLS_X509_EXT_BC_PATHLEN_IDX].tag != 0) { ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_EXT_BC_PATHLEN_IDX], &ext->maxPathLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } ext->extFlags |= HITLS_X509_EXT_FLAG_BCONS; return ret; } #endif static int32_t ParseDirName(uint8_t **encode, uint32_t *encLen, BslList **list) { uint32_t valueLen; int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, encode, encLen, &valueLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *list = BSL_LIST_New(sizeof(HITLS_X509_NameNode)); if (*list == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } BSL_ASN1_Buffer asn = {.buff = *encode, .len = valueLen}; ret = HITLS_X509_ParseNameList(&asn, *list); if (ret == BSL_SUCCESS) { *encode += valueLen; *encLen -= valueLen; } else { BSL_LIST_FREE(*list, NULL); } return ret; } static int32_t ParseGeneralName(uint8_t tag, uint8_t **encode, uint32_t *encLen, uint32_t nameLen, BslList *list) { int32_t type = -1; int32_t ret; BslList *dirNames = NULL; BSL_Buffer value = {0}; for (uint32_t i = 0; i < sizeof(g_generalNameMap) / sizeof(g_generalNameMap[0]); i++) { if (g_generalNameMap[i].tag == tag) { type = g_generalNameMap[i].type; break; } } if (type == -1) { return HITLS_X509_ERR_PARSE_SAN_ITEM_UNKNOW; } if (tag == HITLS_X509_GENERALNAME_DIR_TAG) { ret = ParseDirName(encode, encLen, &dirNames); if (ret != HITLS_PKI_SUCCESS) { return ret; } value.data = (uint8_t *)dirNames; value.dataLen = sizeof(BslList *); } else { value.data = *encode; value.dataLen = nameLen; } HITLS_X509_GeneralName *name = BSL_SAL_Calloc(1, sizeof(HITLS_X509_GeneralName)); if (name == NULL) { if (dirNames != NULL) { BSL_LIST_FREE(dirNames, NULL); } BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } name->type = type; name->value = value; ret = BSL_LIST_AddElement(list, name, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { BSL_LIST_FREE(dirNames, NULL); BSL_SAL_Free(name); } return ret; } static void FreeGeneralName(void *data) { HITLS_X509_GeneralName *name = (HITLS_X509_GeneralName *)data; if (name->type == HITLS_X509_GN_DNNAME) { BSL_LIST_DeleteAll((BslList *)name->value.data, NULL); BSL_SAL_Free(name->value.data); } BSL_SAL_Free(data); } void HITLS_X509_FreeGeneralName(HITLS_X509_GeneralName *data) { if (data == NULL) { return; } if (data->type == HITLS_X509_GN_DNNAME) { BSL_LIST_DeleteAll((BslList *)data->value.data, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); } BSL_SAL_Free(data->value.data); BSL_SAL_Free(data); } void HITLS_X509_ClearGeneralNames(BslList *names) { if (names == NULL) { return; } BSL_LIST_DeleteAll(names, (BSL_LIST_PFUNC_FREE)FreeGeneralName); } HITLS_X509_Ext *X509_ExtNew(HITLS_X509_Ext *ext, int32_t type) { HITLS_X509_Ext *tmp = NULL; if (ext == NULL) { tmp = (HITLS_X509_Ext *)BSL_SAL_Calloc(1, sizeof(HITLS_X509_Ext)); if (tmp == NULL) { return NULL; } ext = tmp; } ext->type = type; ext->extList = BSL_LIST_New(sizeof(HITLS_X509_ExtEntry *)); if (ext->extList == NULL) { BSL_SAL_Free(tmp); return NULL; } if (type != HITLS_X509_EXT_TYPE_CRL) { ext->extData = BSL_SAL_Calloc(1, sizeof(HITLS_X509_CertExt)); if (ext->extData == NULL) { BSL_SAL_Free(ext->extList); ext->extList = NULL; BSL_SAL_Free(tmp); return NULL; } ((HITLS_X509_CertExt *)(ext->extData))->maxPathLen = -1; } return ext; } void X509_ExtFree(HITLS_X509_Ext *ext, bool isFreeOut) { if (ext == NULL) { return; } if ((ext->flag & HITLS_X509_EXT_FLAG_PARSE) != 0) { BSL_LIST_FREE(ext->extList, NULL); } else { BSL_LIST_FREE(ext->extList, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); } BSL_SAL_Free(ext->extData); if (isFreeOut) { BSL_SAL_Free(ext); } } int32_t HITLS_X509_ParseGeneralNames(uint8_t *encode, uint32_t encLen, BslList *list) { uint8_t *buff = encode; uint32_t buffLen = encLen; uint32_t nameValueLen; uint8_t tag; int32_t ret = HITLS_PKI_SUCCESS; while (buffLen != 0) { // tag tag = *buff; buff++; buffLen--; // length ret = BSL_ASN1_DecodeLen(&buff, &buffLen, false, &nameValueLen); if (ret != BSL_SUCCESS) { break; } if (nameValueLen == 0) { continue; } // value ret = ParseGeneralName(tag, &buff, &buffLen, nameValueLen, list); if (ret != BSL_SUCCESS) { break; } if (tag != HITLS_X509_GENERALNAME_DIR_TAG) { buff += nameValueLen; buffLen -= nameValueLen; } } if (ret != BSL_SUCCESS) { HITLS_X509_ClearGeneralNames(list); BSL_ERR_PUSH_ERROR(ret); } return ret; } void HITLS_X509_ClearAuthorityKeyId(HITLS_X509_ExtAki *aki) { if (aki == NULL) { return; } if (aki->issuerName != NULL) { HITLS_X509_ClearGeneralNames(aki->issuerName); BSL_SAL_Free(aki->issuerName); aki->issuerName = NULL; } } int32_t HITLS_X509_ParseAuthorityKeyId(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtAki *aki) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; BslList *list = NULL; BSL_ASN1_Buffer asnArr[HITLS_X509_EXT_AKI_MAX] = {0}; BSL_ASN1_Template templ = {g_akidTempl, sizeof(g_akidTempl) / sizeof(g_akidTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asnArr, HITLS_X509_EXT_AKI_MAX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (asnArr[HITLS_X509_EXT_AKI_KID_IDX].tag != 0) { aki->kid.data = asnArr[HITLS_X509_EXT_AKI_KID_IDX].buff; aki->kid.dataLen = asnArr[HITLS_X509_EXT_AKI_KID_IDX].len; } /** * ITU-T x509: 8.2.2.1 Authority key identifier extension * authorityCertIssuer PRESENT, authorityCertSerialNumber PRESENT * authorityCertIssuer ABSENT, authorityCertSerialNumber ABSENT */ if ((asnArr[HITLS_X509_EXT_AKI_SERIAL_IDX].buff != NULL && asnArr[HITLS_X509_EXT_AKI_ISSUER_IDX].buff == NULL) || (asnArr[HITLS_X509_EXT_AKI_SERIAL_IDX].buff == NULL && asnArr[HITLS_X509_EXT_AKI_ISSUER_IDX].buff != NULL)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_ILLEGAL_AKI); return HITLS_X509_ERR_EXT_ILLEGAL_AKI; } if (asnArr[HITLS_X509_EXT_AKI_SERIAL_IDX].tag != 0) { aki->serialNum.data = asnArr[HITLS_X509_EXT_AKI_SERIAL_IDX].buff; aki->serialNum.dataLen = asnArr[HITLS_X509_EXT_AKI_SERIAL_IDX].len; } if (asnArr[HITLS_X509_EXT_AKI_ISSUER_IDX].tag != 0) { list = BSL_LIST_New(sizeof(HITLS_X509_GeneralName)); if (list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_AKI); return HITLS_X509_ERR_PARSE_AKI; } ret = HITLS_X509_ParseGeneralNames( asnArr[HITLS_X509_EXT_AKI_ISSUER_IDX].buff, asnArr[HITLS_X509_EXT_AKI_ISSUER_IDX].len, list); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(list); BSL_ERR_PUSH_ERROR(ret); return ret; } aki->issuerName = list; } aki->critical = extEntry->critical; return ret; } int32_t HITLS_X509_ParseSubjectKeyId(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtSki *ski) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; uint32_t kidLen = 0; int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_OCTETSTRING, &temp, &tempLen, &kidLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ski->kid.data = temp; ski->kid.dataLen = kidLen; ski->critical = extEntry->critical; return ret; } int32_t X509_ParseCrlNumber(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtCrlNumber *crlNumber) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; uint32_t valueLen = 0; // CRL Number is encoded as an INTEGER int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_INTEGER, &temp, &tempLen, &valueLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // Check CRL Number length if (valueLen < HITLS_X509_CRLNUMBER_MIN_LEN || valueLen > HITLS_X509_CRLNUMBER_MAX_LEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_CRLNUMBER); return HITLS_X509_ERR_EXT_CRLNUMBER; } // Store CRL Number value crlNumber->crlNumber.data = temp; crlNumber->crlNumber.dataLen = valueLen; crlNumber->critical = extEntry->critical; return HITLS_PKI_SUCCESS; } #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CRL_PARSE) || defined(HITLS_PKI_X509_CSR_PARSE) static int32_t ParseExKeyUsageList(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { (void)param; if (layer == 1) { return HITLS_PKI_SUCCESS; } BSL_Buffer *buff = BSL_SAL_Malloc(sizeof(BSL_Buffer)); if (buff == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_EXKU_ITEM); return HITLS_X509_ERR_PARSE_EXKU_ITEM; } buff->data = asn->buff; buff->dataLen = asn->len; int32_t ret = BSL_LIST_AddElement(list, buff, BSL_LIST_POS_AFTER); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BSL_SAL_Free(buff); } return ret; } int32_t HITLS_X509_ParseExtendedKeyUsage(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtExKeyUsage *exku) { uint8_t expTag[] = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_TAG_OBJECT_ID}; BSL_ASN1_DecodeListParam listParam = {sizeof(expTag) / sizeof(uint8_t), expTag}; BslList *list = BSL_LIST_New(sizeof(BSL_Buffer)); if (list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_EXKU); return HITLS_X509_ERR_PARSE_EXKU; } int32_t ret = BSL_ASN1_DecodeListItem(&listParam, &extEntry->extnValue, ParseExKeyUsageList, NULL, list); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_DeleteAll(list, NULL); BSL_SAL_Free(list); return ret; } exku->critical = extEntry->critical; exku->oidList = list; return ret; } void HITLS_X509_ClearSubjectAltName(HITLS_X509_ExtSan *san) { if (san == NULL) { return; } if (san->names != NULL) { HITLS_X509_ClearGeneralNames(san->names); BSL_SAL_Free(san->names); san->names = NULL; } } int32_t HITLS_X509_ParseSubjectAltName(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtSan *san) { uint32_t len; uint8_t *buff = extEntry->extnValue.buff; uint32_t buffLen = extEntry->extnValue.len; // skip the sequence int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, &buff, &buffLen, &len); if (ret == BSL_SUCCESS && buffLen != len) { ret = HITLS_X509_ERR_PARSE_NO_ENOUGH; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslList *list = BSL_LIST_New(sizeof(HITLS_X509_GeneralName)); if (list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_SAN); return HITLS_X509_ERR_PARSE_SAN; } ret = HITLS_X509_ParseGeneralNames(buff, len, list); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(list); BSL_ERR_PUSH_ERROR(ret); return ret; } san->names = list; san->critical = extEntry->critical; return ret; } void HITLS_X509_ClearExtendedKeyUsage(HITLS_X509_ExtExKeyUsage *exku) { if (exku == NULL) { return; } BSL_LIST_FREE(exku->oidList, NULL); } #endif #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CRL_PARSE) || defined(HITLS_PKI_X509_CSR) static BSL_ASN1_TemplateItem g_x509ExtTempl[] = { {BSL_ASN1_TAG_OBJECT_ID, 0, 0}, {BSL_ASN1_TAG_BOOLEAN, BSL_ASN1_FLAG_DEFAULT, 0}, {BSL_ASN1_TAG_OCTETSTRING, 0, 0}, }; int32_t HITLS_X509_ParseExtItem(BSL_ASN1_Buffer *extItem, HITLS_X509_ExtEntry *extEntry) { uint8_t *temp = extItem->buff; uint32_t tempLen = extItem->len; BSL_ASN1_Buffer asnArr[HITLS_X509_EXT_MAX] = {0}; BSL_ASN1_Template templ = {g_x509ExtTempl, sizeof(g_x509ExtTempl) / sizeof(g_x509ExtTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asnArr, HITLS_X509_EXT_MAX); if (tempLen != 0) { ret = HITLS_X509_ERR_PARSE_EXT_BUF; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // extnid extEntry->extnId = asnArr[HITLS_X509_EXT_OID_IDX]; BslOidString oid = {extEntry->extnId.len, (char *)extEntry->extnId.buff, 0}; extEntry->cid = BSL_OBJ_GetCID(&oid); // critical if (asnArr[HITLS_X509_EXT_CRITICAL_IDX].tag == 0) { extEntry->critical = false; } else { ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_EXT_CRITICAL_IDX], &extEntry->critical); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } extEntry->extnValue = asnArr[HITLS_X509_EXT_VALUE_IDX]; return ret; } #endif #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CSR_GEN) static void FreeExtEntryCont(HITLS_X509_ExtEntry *entry) { BSL_SAL_FREE(entry->extnId.buff); BSL_SAL_FREE(entry->extnValue.buff); entry->extnId.len = 0; entry->extnValue.len = 0; } static int32_t GetExtEntryByCid(BslList *extList, BslCid cid, HITLS_X509_ExtEntry **entry, bool *isNew) { BslOidString *oid = BSL_OBJ_GetOID(cid); if (oid == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_OID); return HITLS_X509_ERR_EXT_OID; } HITLS_X509_ExtEntry *extEntry = BSL_LIST_Search(extList, &cid, CmpExtByCid, NULL); if (extEntry != NULL) { *isNew = false; FreeExtEntryCont(extEntry); extEntry->critical = false; } else { extEntry = BSL_SAL_Calloc(1, sizeof(HITLS_X509_ExtEntry)); if (extEntry == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } *isNew = true; } extEntry->cid = cid; extEntry->extnId.tag = BSL_ASN1_TAG_OBJECT_ID; extEntry->extnId.len = oid->octetLen; if (extEntry->extnId.len != 0) { extEntry->extnId.buff = BSL_SAL_Dump(oid->octs, oid->octetLen); if (extEntry->extnId.buff == NULL) { if (*isNew) { BSL_SAL_Free(extEntry); } BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } } extEntry->extnValue.tag = BSL_ASN1_TAG_OCTETSTRING; *entry = extEntry; return HITLS_PKI_SUCCESS; } #endif #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CRL_PARSE) || defined(HITLS_PKI_X509_CSR) static int32_t ParseExtAsnItem(BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { HITLS_X509_Ext *ext = param; HITLS_X509_ExtEntry extEntry = {0}; int32_t ret = HITLS_X509_ParseExtItem(asn, &extEntry); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // Check if the extension already exists. if (BSL_LIST_Search(list, &extEntry.extnId, CmpExtByOid, NULL) != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_EXT_REPEAT); return HITLS_X509_ERR_PARSE_EXT_REPEAT; } // Add the extension to list. ret = HITLS_X509_AddListItemDefault(&extEntry, sizeof(HITLS_X509_ExtEntry), list); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString oid = {extEntry.extnId.len, (char *)extEntry.extnId.buff, 0}; switch (BSL_OBJ_GetCID(&oid)) { case BSL_CID_CE_KEYUSAGE: return ParseExtKeyUsage(&extEntry, (HITLS_X509_CertExt *)ext->extData); case BSL_CID_CE_BASICCONSTRAINTS: return ParseExtBasicConstraints(&extEntry, (HITLS_X509_CertExt *)ext->extData); default: return HITLS_PKI_SUCCESS; } } static int32_t ParseExtSeqof(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { return layer == 1 ? HITLS_PKI_SUCCESS : ParseExtAsnItem(asn, param, list); } int32_t HITLS_X509_ParseExt(BSL_ASN1_Buffer *ext, HITLS_X509_Ext *certExt) { if (certExt == NULL || certExt->extData == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_PARSE_AFTER_SET); return HITLS_X509_ERR_EXT_PARSE_AFTER_SET; } if ((certExt->flag & HITLS_X509_EXT_FLAG_GEN) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_PARSE_AFTER_SET); return HITLS_X509_ERR_EXT_PARSE_AFTER_SET; } // x509 v1 if (ext->tag == 0) { return HITLS_PKI_SUCCESS; } uint8_t expTag[] = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE}; BSL_ASN1_DecodeListParam listParam = {2, expTag}; int ret = BSL_ASN1_DecodeListItem(&listParam, ext, &ParseExtSeqof, certExt, certExt->extList); if (ret != BSL_SUCCESS) { BSL_LIST_DeleteAll(certExt->extList, NULL); BSL_ERR_PUSH_ERROR(ret); return ret; } certExt->flag |= HITLS_X509_EXT_FLAG_PARSE; return ret; } #endif #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CSR_GEN) static int32_t SetExtBCons(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { const HITLS_X509_ExtBCons *bCons = (const HITLS_X509_ExtBCons *)val; BSL_ASN1_Template templ = {g_bConsTempl, sizeof(g_bConsTempl) / sizeof(g_bConsTempl[0])}; /** * RFC 5280: section-4.2.1.9 * BasicConstraints ::= SEQUENCE { * cA BOOLEAN DEFAULT FALSE, * pathLenConstraint INTEGER (0..MAX) OPTIONAL } */ BSL_ASN1_Buffer asns[] = { {BSL_ASN1_TAG_BOOLEAN, bCons->isCa ? sizeof(bool) : 0, bCons->isCa ? (uint8_t *)(uintptr_t)&bCons->isCa : NULL}, {BSL_ASN1_TAG_INTEGER, 0, NULL}, }; int32_t ret; if (bCons->maxPathLen >= 0) { ret = BSL_ASN1_EncodeLimb(BSL_ASN1_TAG_INTEGER, (uint64_t)bCons->maxPathLen, asns + 1); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } ret = BSL_ASN1_EncodeTemplate( &templ, asns, sizeof(asns) / sizeof(asns[0]), &entry->extnValue.buff, &entry->extnValue.len); BSL_SAL_Free(asns[1].buff); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } entry->critical = bCons->critical; HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)ext->extData; certExt->isCa = bCons->isCa; certExt->maxPathLen = bCons->maxPathLen; certExt->extFlags |= HITLS_X509_EXT_FLAG_BCONS; return HITLS_PKI_SUCCESS; } static int32_t SetExtKeyUsage(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { const HITLS_X509_ExtKeyUsage *ku = (const HITLS_X509_ExtKeyUsage *)val; if (ku->keyUsage == 0 || (ku->keyUsage & HITLS_X509_EXT_KEYUSAGE_UNUSED_BIT) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_KU); return HITLS_X509_ERR_EXT_KU; } // bit string uint16_t keyUsage = (uint16_t)ku->keyUsage; BSL_ASN1_BitString bs = {0}; bs.len = (keyUsage & HITLS_X509_EXT_KU_DECIPHER_ONLY) == 0 ? 1 : 2; // 2: decipher only is not 0 uint8_t buff[2] = {0}; // The max length of content(BitString, except unused bits) is 2 bytes. buff[0] = (uint8_t)keyUsage; buff[1] = (uint8_t)(keyUsage >> 8); // 8: 8 bits per byte bs.buff = buff; uint8_t tmp = bs.len == 1 ? (uint8_t)keyUsage : (uint8_t)(keyUsage >> BITS_OF_BYTE); for (int32_t i = 1; i < BITS_OF_BYTE; i++) { if ((uint8_t)(tmp << i) == 0) { bs.unusedBits = BITS_OF_BYTE - i; break; } } // encode bit string BSL_ASN1_Buffer asn = {BSL_ASN1_TAG_BITSTRING, sizeof(BSL_ASN1_BitString), (uint8_t *)&bs}; BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_BITSTRING, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, &asn, 1, &entry->extnValue.buff, &entry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } entry->critical = ku->critical; HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)ext->extData; certExt->extFlags |= HITLS_X509_EXT_FLAG_KUSAGE; return ret; } static int32_t SetExtAki(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { (void)ext; const HITLS_X509_ExtAki *aki = (const HITLS_X509_ExtAki *)val; entry->critical = aki->critical; if (aki->kid.dataLen < HITLS_X509_KID_MIN_LEN || aki->kid.dataLen > HITLS_X509_KID_MAX_LEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_KID); return HITLS_X509_ERR_EXT_KID; } BSL_ASN1_Buffer asns[] = { {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_X509_CTX_SPECIFIC_TAG_AKID_KID, aki->kid.dataLen, aki->kid.data}, {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_X509_CTX_SPECIFIC_TAG_AKID_ISSUER, 0, NULL}, {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_X509_CTX_SPECIFIC_TAG_AKID_SERIAL, 0, NULL}, }; BSL_ASN1_Template templ = {g_akidTempl, sizeof(g_akidTempl) / sizeof(g_akidTempl[0])}; int32_t ret = BSL_ASN1_EncodeTemplate( &templ, asns, sizeof(asns) / sizeof(asns[0]), &entry->extnValue.buff, &entry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t SetExtSki(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { (void)ext; const HITLS_X509_ExtSki *ski = (const HITLS_X509_ExtSki *)val; entry->critical = ski->critical; if (ski->kid.dataLen < HITLS_X509_KID_MIN_LEN || ski->kid.dataLen > HITLS_X509_KID_MAX_LEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_KID); return HITLS_X509_ERR_EXT_KID; } BSL_ASN1_Buffer asn = {BSL_ASN1_TAG_OCTETSTRING, ski->kid.dataLen, ski->kid.data}; BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_OCTETSTRING, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, &asn, 1, &entry->extnValue.buff, &entry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static void SetAsn1Templ(BSL_Buffer *value, uint8_t tag, BSL_ASN1_TemplateItem *item, BSL_ASN1_Buffer *asn) { item->tag = tag; asn->tag = tag; asn->len = value->dataLen; asn->buff = value->data; } static void FreeGnAsns(BSL_ASN1_Buffer *asns, uint32_t number) { for (uint32_t i = 0; i < number; i++) { if (asns[i].tag == HITLS_X509_GENERALNAME_DIR_TAG) { BSL_SAL_Free(asns[i].buff); } } BSL_SAL_Free(asns); } static int32_t GetSanDirNameExtnValue(BslList *dirNames, BSL_ASN1_Buffer *extnValue) { BSL_ASN1_Buffer tmp = {0}; int32_t ret = HITLS_X509_EncodeNameList((BSL_ASN1_List *)dirNames, &tmp); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; ret = BSL_ASN1_EncodeTemplate(&templ, &tmp, 1, &extnValue->buff, &extnValue->len); BSL_SAL_Free(tmp.buff); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } extnValue->tag = HITLS_X509_GENERALNAME_DIR_TAG; return ret; } static int32_t SetGnEncodeParam(BslList *names, BSL_ASN1_TemplateItem *items, BSL_ASN1_Buffer *asns) { HITLS_X509_GeneralName **name = BSL_LIST_First(names); BSL_ASN1_TemplateItem *item = items; BSL_ASN1_Buffer *asn = asns; int32_t ret; while (name != NULL) { if ((*name)->value.data == NULL || (*name)->value.dataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SAN_ELE); return HITLS_X509_ERR_EXT_SAN_ELE; } switch ((*name)->type) { case HITLS_X509_GN_EMAIL: SetAsn1Templ(&(*name)->value, HITLS_X509_GENERALNAME_RFC822_TAG, item, asn); break; case HITLS_X509_GN_DNS: SetAsn1Templ(&(*name)->value, HITLS_X509_GENERALNAME_DNS_TAG, item, asn); break; case HITLS_X509_GN_DNNAME: ret = GetSanDirNameExtnValue((BSL_ASN1_List *)(*name)->value.data, asn); if (ret != HITLS_PKI_SUCCESS) { return ret; } item->tag = HITLS_X509_GENERALNAME_DIR_TAG; break; case HITLS_X509_GN_URI: SetAsn1Templ(&(*name)->value, HITLS_X509_GENERALNAME_URI_TAG, item, asn); break; case HITLS_X509_GN_IP: SetAsn1Templ(&(*name)->value, HITLS_X509_GENERALNAME_IP_TAG, item, asn); break; default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_GN_UNSUPPORT); return HITLS_X509_ERR_EXT_GN_UNSUPPORT; } item->depth = 1; item++; asn++; name = BSL_LIST_Next(names); } return HITLS_PKI_SUCCESS; } static int32_t AllocEncodeParam(BSL_ASN1_TemplateItem **items, uint32_t itemNum, BSL_ASN1_Buffer **asns, uint32_t asnNum) { *items = BSL_SAL_Calloc(itemNum, sizeof(BSL_ASN1_TemplateItem)); // sequence + names if (*items == NULL) { return BSL_MALLOC_FAIL; } *asns = BSL_SAL_Calloc(asnNum, sizeof(BSL_ASN1_Buffer)); if (*asns == NULL) { BSL_SAL_Free(*items); *items = NULL; return BSL_MALLOC_FAIL; } return HITLS_PKI_SUCCESS; } static int32_t SetExtGeneralNames(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { (void)ext; const HITLS_X509_ExtSan *san = (const HITLS_X509_ExtSan *)val; if (san->names == NULL || BSL_LIST_COUNT(san->names) <= 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SAN); return HITLS_X509_ERR_EXT_SAN; } entry->critical = san->critical; /* Encode extnValue */ BSL_ASN1_TemplateItem *items = NULL; BSL_ASN1_Buffer *asns = NULL; uint32_t number = (uint32_t)BSL_LIST_COUNT(san->names); int32_t ret = AllocEncodeParam(&items, 1 + number, &asns, number); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } items[0].depth = 0; items[0].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; ret = SetGnEncodeParam(san->names, items + 1, asns); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(items); FreeGnAsns(asns, number); BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Template templ = {items, number + 1}; ret = BSL_ASN1_EncodeTemplate(&templ, asns, number, &entry->extnValue.buff, &entry->extnValue.len); BSL_SAL_Free(items); FreeGnAsns(asns, number); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t SetExtExKeyUsage(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { (void)ext; const HITLS_X509_ExtExKeyUsage *exku = (const HITLS_X509_ExtExKeyUsage *)val; if (exku->oidList == NULL || BSL_LIST_COUNT(exku->oidList) <= 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_EXTENDED_KU); return HITLS_X509_ERR_EXT_EXTENDED_KU; } entry->critical = exku->critical; BSL_ASN1_TemplateItem *items = NULL; BSL_ASN1_Buffer *asns = NULL; uint32_t number = (uint32_t)BSL_LIST_COUNT(exku->oidList); int32_t ret = AllocEncodeParam(&items, number + 1, &asns, number); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } items[0].depth = 0; items[0].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; BSL_Buffer **buffer = BSL_LIST_First(exku->oidList); for (uint32_t i = 0; i < number; i++) { if (buffer == NULL || *buffer == NULL || (*buffer)->dataLen == 0 || (*buffer)->data == NULL) { BSL_SAL_Free(items); BSL_SAL_Free(asns); BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_EXTENDED_KU_ELE); return HITLS_X509_ERR_EXT_EXTENDED_KU_ELE; } items[i + 1].depth = 1; items[i + 1].tag = BSL_ASN1_TAG_OBJECT_ID; asns[i].tag = BSL_ASN1_TAG_OBJECT_ID; asns[i].len = (*buffer)->dataLen; asns[i].buff = (*buffer)->data; buffer = BSL_LIST_Next(exku->oidList); } BSL_ASN1_Template templ = {items, number + 1}; ret = BSL_ASN1_EncodeTemplate(&templ, asns, number, &entry->extnValue.buff, &entry->extnValue.len); BSL_SAL_Free(items); BSL_SAL_Free(asns); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t SetExtCrlNumber(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { if (ext->type != HITLS_X509_EXT_TYPE_CRL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET); return HITLS_X509_ERR_EXT_SET; } const HITLS_X509_ExtCrlNumber *crlNumber = (const HITLS_X509_ExtCrlNumber *)val; entry->critical = crlNumber->critical; if (crlNumber->crlNumber.dataLen < HITLS_X509_CRLNUMBER_MIN_LEN || crlNumber->crlNumber.dataLen > HITLS_X509_CRLNUMBER_MAX_LEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_CRLNUMBER); return HITLS_X509_ERR_EXT_CRLNUMBER; } BSL_ASN1_Buffer asn = {BSL_ASN1_TAG_INTEGER, crlNumber->crlNumber.dataLen, crlNumber->crlNumber.data}; BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_INTEGER, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, &asn, 1, &entry->extnValue.buff, &entry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t HITLS_X509_SetExtList(void *param, BslList *extList, BslCid cid, BSL_Buffer *val, EncodeExtCb encodeExt) { HITLS_X509_ExtEntry *extEntry = NULL; bool isNew; int32_t ret = GetExtEntryByCid(extList, cid, &extEntry, &isNew); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = encodeExt(param, extEntry, val->data); if (ret != HITLS_PKI_SUCCESS) { FreeExtEntryCont(extEntry); if (isNew) { BSL_SAL_Free(extEntry); } return ret; } if (isNew) { ret = BSL_LIST_AddElement(extList, extEntry, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); FreeExtEntryCont(extEntry); BSL_SAL_Free(extEntry); return ret; } } return HITLS_PKI_SUCCESS; } static int32_t SetExt(HITLS_X509_Ext *ext, BslCid cid, BSL_Buffer *val, uint32_t expectLen, EncodeExtCb encodeExt) { if ((ext->flag & HITLS_X509_EXT_FLAG_PARSE) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET_AFTER_PARSE); return HITLS_X509_ERR_EXT_SET_AFTER_PARSE; } if (val->dataLen != expectLen) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t ret = HITLS_X509_SetExtList(ext, ext->extList, cid, val, encodeExt); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ext->flag |= HITLS_X509_EXT_FLAG_GEN; return ret; } static int32_t SetExtCtrl(HITLS_X509_Ext *ext, int32_t cmd, void *val, uint32_t valLen) { BSL_Buffer buff = {val, valLen}; switch (cmd) { case HITLS_X509_EXT_SET_BCONS: return SetExt(ext, BSL_CID_CE_BASICCONSTRAINTS, &buff, sizeof(HITLS_X509_ExtBCons), (EncodeExtCb)SetExtBCons); case HITLS_X509_EXT_SET_KUSAGE: return SetExt(ext, BSL_CID_CE_KEYUSAGE, &buff, sizeof(HITLS_X509_ExtKeyUsage), (EncodeExtCb)SetExtKeyUsage); case HITLS_X509_EXT_SET_AKI: return SetExt(ext, BSL_CID_CE_AUTHORITYKEYIDENTIFIER, &buff, sizeof(HITLS_X509_ExtAki), (EncodeExtCb)SetExtAki); case HITLS_X509_EXT_SET_SKI: return SetExt(ext, BSL_CID_CE_SUBJECTKEYIDENTIFIER, &buff, sizeof(HITLS_X509_ExtSki), (EncodeExtCb)SetExtSki); case HITLS_X509_EXT_SET_SAN: return SetExt(ext, BSL_CID_CE_SUBJECTALTNAME, &buff, sizeof(HITLS_X509_ExtSan), (EncodeExtCb)SetExtGeneralNames); case HITLS_X509_EXT_SET_EXKUSAGE: return SetExt(ext, BSL_CID_CE_EXTKEYUSAGE, &buff, sizeof(HITLS_X509_ExtExKeyUsage), (EncodeExtCb)SetExtExKeyUsage); case HITLS_X509_EXT_SET_CRLNUMBER: return SetExt(ext, BSL_CID_CE_CRLNUMBER, &buff, sizeof(HITLS_X509_ExtCrlNumber), (EncodeExtCb)SetExtCrlNumber); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } int32_t HITLS_X509_SetGeneralNames(HITLS_X509_ExtEntry *extEntry, void *val) { if (extEntry == NULL || val == NULL) { return BSL_NULL_INPUT; } return SetExtGeneralNames(NULL, extEntry, val); } #endif int32_t HITLS_X509_GetExt(BslList *ext, BslCid cid, BSL_Buffer *val, uint32_t expectLen, DecodeExtCb decodeExt) { if (ext == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_NOT_FOUND); return HITLS_X509_ERR_EXT_NOT_FOUND; } if (val->dataLen != expectLen) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } HITLS_X509_ExtEntry *extEntry = BSL_LIST_Search(ext, &cid, CmpExtByCid, NULL); if (extEntry == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_NOT_FOUND); return HITLS_X509_ERR_EXT_NOT_FOUND; } return decodeExt(extEntry, val->data); } static int32_t GetExtKeyUsage(HITLS_X509_Ext *ext, uint32_t *val, uint32_t valLen) { if (val == NULL || valLen != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)ext->extData; *val = certExt->extFlags & HITLS_X509_EXT_FLAG_KUSAGE ? certExt->keyUsage : HITLS_X509_EXT_KU_NONE; return HITLS_PKI_SUCCESS; } static int32_t GetExtCtrl(HITLS_X509_Ext *ext, int32_t cmd, void *val, uint32_t valLen) { BSL_Buffer buff = {val, valLen}; switch (cmd) { case HITLS_X509_EXT_GET_SKI: return HITLS_X509_GetExt(ext->extList, BSL_CID_CE_SUBJECTKEYIDENTIFIER, &buff, sizeof(HITLS_X509_ExtSki), (DecodeExtCb)HITLS_X509_ParseSubjectKeyId); case HITLS_X509_EXT_GET_AKI: return HITLS_X509_GetExt(ext->extList, BSL_CID_CE_AUTHORITYKEYIDENTIFIER, &buff, sizeof(HITLS_X509_ExtAki), (DecodeExtCb)HITLS_X509_ParseAuthorityKeyId); case HITLS_X509_EXT_GET_CRLNUMBER: return HITLS_X509_GetExt(ext->extList, BSL_CID_CE_CRLNUMBER, &buff, sizeof(HITLS_X509_ExtCrlNumber), (DecodeExtCb)X509_ParseCrlNumber); case HITLS_X509_EXT_GET_KUSAGE: return GetExtKeyUsage(ext, val, valLen); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } static int32_t CheckExtByCid(HITLS_X509_Ext *ext, int32_t cid, bool *val, uint32_t valLen) { if (valLen != sizeof(bool)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *val = BSL_LIST_Search(ext->extList, &cid, CmpExtByCid, NULL) != NULL; return HITLS_PKI_SUCCESS; } bool X509_CheckCmdValid(int32_t *cmdSet, uint32_t cmdSize, int32_t cmd) { for (uint32_t i = 0; i < cmdSize; i++) { if (cmd == cmdSet[i]) { return true; } } return false; } int32_t X509_ExtCtrl(HITLS_X509_Ext *ext, int32_t cmd, void *val, uint32_t valLen) { #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CSR_GEN) if (cmd >= HITLS_X509_EXT_SET_SKI && cmd < HITLS_X509_EXT_GET_SKI) { return SetExtCtrl(ext, cmd, val, valLen); } #endif if (cmd >= HITLS_X509_EXT_GET_SKI && cmd < HITLS_X509_EXT_CHECK_SKI) { return GetExtCtrl(ext, cmd, val, valLen); } if (cmd >= HITLS_X509_EXT_CHECK_SKI && cmd < HITLS_X509_CSR_GET_ATTRIBUTES) { return CheckExtByCid(ext, BSL_CID_CE_SUBJECTKEYIDENTIFIER, val, valLen); } BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t HITLS_X509_ExtCtrl(HITLS_X509_Ext *ext, int32_t cmd, void *val, uint32_t valLen) { if (ext == NULL || val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (ext->type == HITLS_X509_EXT_TYPE_CERT || ext->type == HITLS_X509_EXT_TYPE_CRL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_UNSUPPORT); return HITLS_X509_ERR_EXT_UNSUPPORT; } static int32_t cmdSet[] = {HITLS_X509_EXT_SET_SKI, HITLS_X509_EXT_SET_AKI, HITLS_X509_EXT_SET_KUSAGE, HITLS_X509_EXT_SET_SAN, HITLS_X509_EXT_SET_BCONS, HITLS_X509_EXT_SET_EXKUSAGE, HITLS_X509_EXT_GET_SKI, HITLS_X509_EXT_GET_AKI, HITLS_X509_EXT_CHECK_SKI, HITLS_X509_EXT_GET_KUSAGE}; if (!X509_CheckCmdValid(cmdSet, sizeof(cmdSet) / sizeof(int32_t), cmd)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_UNSUPPORT); return HITLS_X509_ERR_EXT_UNSUPPORT; } return X509_ExtCtrl(ext, cmd, val, valLen); } void HITLS_X509_ExtEntryFree(HITLS_X509_ExtEntry *entry) { if (entry == NULL) { return; } BSL_SAL_FREE(entry->extnId.buff); BSL_SAL_FREE(entry->extnValue.buff); BSL_SAL_Free(entry); } #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CSR_GEN) /** * RFC 5280: section-4.1 * Extension ::= SEQUENCE { extnID OBJECT IDENTIFIER, critical BOOLEAN DEFAULT FALSE, extnValue OCTET STRING -- contains the DER encoding of an ASN.1 value -- corresponding to the extension type identified -- by extnID } */ static BSL_ASN1_TemplateItem g_extSeqTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_OBJECT_ID, 0, 1}, {BSL_ASN1_TAG_BOOLEAN, BSL_ASN1_FLAG_DEFAULT, 1}, {BSL_ASN1_TAG_OCTETSTRING, 1, 1}, }; #define X509_CRLEXT_ELEM_NUMBER 3 int32_t HITLS_X509_EncodeExtEntry(BSL_ASN1_List *list, BSL_ASN1_Buffer *ext) { uint32_t count = (uint32_t)BSL_LIST_COUNT(list); BSL_ASN1_Buffer *asnBuf = BSL_SAL_Malloc(count * X509_CRLEXT_ELEM_NUMBER * sizeof(BSL_ASN1_Buffer)); if (asnBuf == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } uint32_t iter = 0; HITLS_X509_ExtEntry *node = NULL; for (node = BSL_LIST_GET_FIRST(list); node != NULL; node = BSL_LIST_GET_NEXT(list)) { asnBuf[iter].tag = node->extnId.tag; asnBuf[iter].buff = node->extnId.buff; asnBuf[iter++].len = node->extnId.len; asnBuf[iter].tag = BSL_ASN1_TAG_BOOLEAN; asnBuf[iter].len = node->critical ? 1 : 0; asnBuf[iter++].buff = node->critical ? (uint8_t *)&(node->critical) : NULL; asnBuf[iter].tag = node->extnValue.tag; asnBuf[iter].buff = node->extnValue.buff; asnBuf[iter++].len = node->extnValue.len; } BSL_ASN1_Template templ = {g_extSeqTempl, sizeof(g_extSeqTempl) / sizeof(g_extSeqTempl[0])}; int32_t ret = BSL_ASN1_EncodeListItem(BSL_ASN1_TAG_SEQUENCE, count, &templ, asnBuf, iter, ext); BSL_SAL_Free(asnBuf); return ret; } int32_t HITLS_X509_EncodeExt(uint8_t tag, BSL_ASN1_List *list, BSL_ASN1_Buffer *ext) { if (BSL_LIST_COUNT(list) <= 0) { ext->tag = tag; ext->len = 0; ext->buff = NULL; return HITLS_PKI_SUCCESS; } BSL_ASN1_Buffer extbuff = {0}; int32_t ret = HITLS_X509_EncodeExtEntry(list, &extbuff); if (ret != HITLS_PKI_SUCCESS) { return ret; } BSL_ASN1_TemplateItem extTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, }; BSL_ASN1_Template templ = {extTempl, 1}; ret = BSL_ASN1_EncodeTemplate(&templ, &extbuff, 1, &(ext->buff), &(ext->len)); BSL_SAL_Free(extbuff.buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ext->tag = tag; return HITLS_PKI_SUCCESS; } #endif // HITLS_PKI_X509_CRT_GEN || HITLS_PKI_X509_CRL_GEN || HITLS_PKI_X509_CSR_GEN #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) HITLS_X509_ExtEntry *X509_DupExtEntry(const HITLS_X509_ExtEntry *src) { /* Src is not null. */ HITLS_X509_ExtEntry *dest = BSL_SAL_Malloc(sizeof(HITLS_X509_ExtEntry)); if (dest == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } dest->cid = src->cid; dest->critical = src->critical; // extId dest->extnId.tag = src->extnId.tag; dest->extnId.len = src->extnId.len; if (src->extnId.len != 0) { dest->extnId.buff = BSL_SAL_Dump(src->extnId.buff, src->extnId.len); if (dest->extnId.buff == NULL) { BSL_SAL_Free(dest); BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return NULL; } } // extnValue dest->extnValue.tag = src->extnValue.tag; dest->extnValue.len = src->extnValue.len; if (src->extnValue.len != 0) { dest->extnValue.buff = BSL_SAL_Dump(src->extnValue.buff, src->extnValue.len); if (dest->extnValue.buff == NULL) { BSL_SAL_Free(dest->extnId.buff); BSL_SAL_Free(dest); BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return NULL; } } return dest; } #endif #ifdef HITLS_PKI_X509_CRT_GEN int32_t HITLS_X509_ExtReplace(HITLS_X509_Ext *dest, HITLS_X509_Ext *src) { if (dest == NULL || dest->extData == NULL || src == NULL || src->extData == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((dest->flag & HITLS_X509_EXT_FLAG_PARSE) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET_AFTER_PARSE); return HITLS_X509_ERR_EXT_SET_AFTER_PARSE; } HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)dest->extData; HITLS_X509_CertExt *srcExt = (HITLS_X509_CertExt *)src->extData; certExt->isCa = srcExt->isCa; certExt->maxPathLen = srcExt->maxPathLen; certExt->keyUsage = srcExt->keyUsage; certExt->extFlags = srcExt->extFlags; if (BSL_LIST_COUNT(src->extList) <= 0) { BSL_LIST_DeleteAll(dest->extList, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); return HITLS_PKI_SUCCESS; } BslList *list = BSL_LIST_Copy(src->extList, (BSL_LIST_PFUNC_DUP)X509_DupExtEntry, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); if (list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET); return HITLS_X509_ERR_EXT_SET; } BSL_LIST_FREE(dest->extList, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); dest->extList = list; dest->flag |= HITLS_X509_EXT_FLAG_GEN; return HITLS_PKI_SUCCESS; } #endif HITLS_X509_Ext *HITLS_X509_ExtNew(int32_t type) { if (type == HITLS_X509_EXT_TYPE_CERT || type == HITLS_X509_EXT_TYPE_CRL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return NULL; } return X509_ExtNew(NULL, type); } void HITLS_X509_ExtFree(HITLS_X509_Ext *ext) { X509_ExtFree(ext, true); } #endif // HITLS_PKI_X509
2301_79861745/bench_create
pki/x509_common/src/hitls_x509_ext.c
C
unknown
52,232
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_CRL_LOCAL_H #define HITLS_CRL_LOCAL_H #include "hitls_build.h" #ifdef HITLS_PKI_X509_CRL #include <stdint.h> #include "bsl_asn1_internal.h" #include "bsl_obj.h" #include "sal_atomic.h" #include "hitls_x509_local.h" #ifdef __cplusplus extern "C" { #endif #define HITLS_X509_CRL_PARSE_FLAG 0x01 #define HITLS_X509_CRL_GEN_FLAG 0x02 #define BSL_TIME_REVOKE_TIME_IS_GMT 0x4 typedef struct _HITLS_X509_CrlEntry { uint8_t flag; BSL_ASN1_Buffer serialNumber; BSL_TIME time; BSL_ASN1_List *extList; } HITLS_X509_CrlEntry; typedef struct { uint8_t *tbsRawData; uint32_t tbsRawDataLen; int32_t version; HITLS_X509_Asn1AlgId signAlgId; BSL_ASN1_List *issuerName; HITLS_X509_ValidTime validTime; BSL_ASN1_List *revokedCerts; HITLS_X509_Ext crlExt; } HITLS_X509_CrlTbs; typedef enum { HITLS_X509_CRL_STATE_NEW = 0, HITLS_X509_CRL_STATE_SET, HITLS_X509_CRL_STATE_SIGN, HITLS_X509_CRL_STATE_GEN, } HITLS_X509_CRL_STATE; typedef struct _HITLS_X509_Crl { uint8_t flag; uint8_t state; uint8_t *rawData; uint32_t rawDataLen; HITLS_X509_CrlTbs tbs; HITLS_X509_Asn1AlgId signAlgId; BSL_ASN1_BitString signature; BSL_SAL_RefCount references; } HITLS_X509_Crl; int32_t HITLS_ParseCrlExtInvalidTime(HITLS_X509_ExtEntry *extEntry, void *val); int32_t HITLS_ParseCrlExtReason(HITLS_X509_ExtEntry *extEntry, void *val); #ifdef __cplusplus } #endif #endif // HITLS_PKI_X509_CRL #endif // HITLS_CRL_LOCAL_H
2301_79861745/bench_create
pki/x509_crl/include/hitls_crl_local.h
C
unknown
2,054
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_X509_CRL #include "securec.h" #include "bsl_sal.h" #include "bsl_obj_internal.h" #include "bsl_log_internal.h" #ifdef HITLS_BSL_PEM #include "bsl_pem_internal.h" #endif #include "bsl_err_internal.h" #include "sal_time.h" #ifdef HITLS_BSL_SAL_FILE #include "sal_file.h" #endif #include "crypt_errno.h" #include "hitls_pki_errno.h" #include "hitls_x509_local.h" #include "hitls_crl_local.h" #include "hitls_pki_crl.h" #define HITLS_CRL_CTX_SPECIFIC_TAG_EXTENSION 0 #ifdef HITLS_PKI_X509_CRL_PARSE BSL_ASN1_TemplateItem g_crlTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* x509 */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* tbs */ /* 2: version */ {BSL_ASN1_TAG_INTEGER, BSL_ASN1_FLAG_DEFAULT, 2}, /* 2: signature info */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, {BSL_ASN1_TAG_OBJECT_ID, 0, 3}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 3}, // 6 /* 2: issuer */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 2}, /* 2: validity */ {BSL_ASN1_TAG_CHOICE, 0, 2}, {BSL_ASN1_TAG_CHOICE, BSL_ASN1_FLAG_OPTIONAL, 2}, /* 2: revoked crl list */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME | BSL_ASN1_FLAG_OPTIONAL, 2}, /* 2: extension */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CRL_CTX_SPECIFIC_TAG_EXTENSION, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 2}, // 11 {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* signAlg */ {BSL_ASN1_TAG_OBJECT_ID, 0, 2}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 2}, {BSL_ASN1_TAG_BITSTRING, 0, 1} /* sig */ }; typedef enum { HITLS_X509_CRL_VERSION_IDX, HITLS_X509_CRL_TBS_SIGNALG_OID_IDX, HITLS_X509_CRL_TBS_SIGNALG_ANY_IDX, HITLS_X509_CRL_ISSUER_IDX, HITLS_X509_CRL_BEFORE_VALID_IDX, HITLS_X509_CRL_AFTER_VALID_IDX, HITLS_X509_CRL_CRL_LIST_IDX, HITLS_X509_CRL_EXT_IDX, HITLS_X509_CRL_SIGNALG_IDX, HITLS_X509_CRL_SIGNALG_ANY_IDX, HITLS_X509_CRL_SIGN_IDX, HITLS_X509_CRL_MAX_IDX, } HITLS_X509_CRL_IDX; int32_t HITLS_X509_CrlTagGetOrCheck(int32_t type, uint32_t idx, void *data, void *expVal) { (void) idx; switch (type) { case BSL_ASN1_TYPE_CHECK_CHOICE_TAG: { uint8_t tag = *(uint8_t *) data; if ((tag == BSL_ASN1_TAG_UTCTIME) || (tag == BSL_ASN1_TAG_GENERALIZEDTIME)) { *(uint8_t *) expVal = tag; return BSL_SUCCESS; } return HITLS_X509_ERR_CHECK_TAG; } case BSL_ASN1_TYPE_GET_ANY_TAG: { BSL_ASN1_Buffer *param = (BSL_ASN1_Buffer *) data; BslOidString oidStr = {param->len, (char *)param->buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_UNKNOWN) { return HITLS_X509_ERR_GET_ANY_TAG; } if (cid == BSL_CID_RSASSAPSS) { // note: any It can be encoded empty or it can be null *(uint8_t *) expVal = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; return BSL_SUCCESS; } else { *(uint8_t *) expVal = BSL_ASN1_TAG_NULL; // is null return BSL_SUCCESS; } return HITLS_X509_ERR_GET_ANY_TAG; } default: return HITLS_X509_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_X509_CRL_PARSE void HITLS_X509_CrlFree(HITLS_X509_Crl *crl) { if (crl == NULL) { return; } int ret = 0; BSL_SAL_AtomicDownReferences(&(crl->references), &ret); if (ret > 0) { return; } if ((crl->flag & HITLS_X509_CRL_GEN_FLAG) != 0) { BSL_LIST_FREE(crl->tbs.issuerName, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); BSL_SAL_FREE(crl->tbs.tbsRawData); BSL_SAL_FREE(crl->signature.buff); } else { BSL_LIST_FREE(crl->tbs.issuerName, NULL); } #ifdef HITLS_CRYPTO_SM2 if (crl->signAlgId.algId == BSL_CID_SM2DSAWITHSM3) { BSL_SAL_FREE(crl->signAlgId.sm2UserId.data); } #endif BSL_LIST_FREE(crl->tbs.revokedCerts, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlEntryFree); X509_ExtFree(&crl->tbs.crlExt, false); BSL_SAL_ReferencesFree(&(crl->references)); BSL_SAL_FREE(crl->rawData); BSL_SAL_Free(crl); return; } HITLS_X509_Crl *HITLS_X509_CrlNew(void) { HITLS_X509_Crl *crl = NULL; BSL_ASN1_List *issuerName = NULL; BSL_ASN1_List *entryList = NULL; HITLS_X509_Ext *ext = NULL; crl = (HITLS_X509_Crl *)BSL_SAL_Calloc(1, sizeof(HITLS_X509_Crl)); if (crl == NULL) { return NULL; } issuerName = BSL_LIST_New(sizeof(HITLS_X509_NameNode)); if (issuerName == NULL) { goto ERR; } entryList = BSL_LIST_New(sizeof(HITLS_X509_CrlEntry)); if (entryList == NULL) { goto ERR; } ext = X509_ExtNew(&crl->tbs.crlExt, HITLS_X509_EXT_TYPE_CRL); if (ext == NULL) { goto ERR; } BSL_SAL_ReferencesInit(&(crl->references)); crl->tbs.issuerName = issuerName; crl->tbs.revokedCerts = entryList; crl->state = HITLS_X509_CRL_STATE_NEW; return crl; ERR: BSL_SAL_Free(crl); BSL_SAL_Free(issuerName); BSL_SAL_Free(entryList); return NULL; } #ifdef HITLS_PKI_X509_CRL_PARSE int32_t HITLS_CRL_ParseExtAsnItem(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { (void) param; (void) layer; HITLS_X509_ExtEntry extEntry = {0}; int32_t ret = HITLS_X509_ParseExtItem(asn, &extEntry); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return HITLS_X509_AddListItemDefault(&extEntry, sizeof(HITLS_X509_ExtEntry), list); } int32_t HITLS_CRL_ParseExtSeqof(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { if (layer == 1) { return HITLS_PKI_SUCCESS; } return HITLS_CRL_ParseExtAsnItem(layer, asn, param, list); } int32_t HITLS_X509_ParseCrlExt(BSL_ASN1_Buffer *ext, HITLS_X509_Crl *crl) { if ((crl->tbs.crlExt.flag & HITLS_X509_EXT_FLAG_GEN) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_PARSE_AFTER_SET); return HITLS_X509_ERR_EXT_PARSE_AFTER_SET; } uint8_t expTag[] = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE}; BSL_ASN1_DecodeListParam listParam = {2, expTag}; int32_t ret = BSL_ASN1_DecodeListItem(&listParam, ext, &HITLS_CRL_ParseExtSeqof, crl, crl->tbs.crlExt.extList); if (ret != BSL_SUCCESS) { BSL_LIST_DeleteAll(crl->tbs.crlExt.extList, NULL); BSL_ERR_PUSH_ERROR(ret); return ret; } crl->tbs.crlExt.flag |= HITLS_X509_EXT_FLAG_PARSE; return ret; } BSL_ASN1_TemplateItem g_crlEntryTempl[] = { {BSL_ASN1_TAG_INTEGER, 0, 0}, {BSL_ASN1_TAG_CHOICE, 0, 0}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY, 0} }; typedef enum { HITLS_X509_CRLENTRY_NUM_IDX, HITLS_X509_CRLENTRY_TIME_IDX, HITLS_X509_CRLENTRY_EXT_IDX, HITLS_X509_CRLENTRY_MAX_IDX } HITLS_X509_CRLENTRY_IDX; #endif // HITLS_PKI_X509_CRL_PARSE int32_t HITLS_X509_CrlEntryChoiceCheck(int32_t type, uint32_t idx, void *data, void *expVal) { (void) idx; (void) expVal; if (type == BSL_ASN1_TYPE_CHECK_CHOICE_TAG) { uint8_t tag = *(uint8_t *) data; if ((tag & BSL_ASN1_TAG_UTCTIME) != 0 || (tag & BSL_ASN1_TAG_GENERALIZEDTIME) != 0) { *(uint8_t *) expVal = tag; return BSL_SUCCESS; } return HITLS_X509_ERR_CHECK_TAG; } return HITLS_X509_ERR_CHECK_TAG; } #ifdef HITLS_PKI_X509_CRL_PARSE static int32_t DecodeCrlRevokeExt(BSL_ASN1_Buffer *asnArr, HITLS_X509_CrlEntry *crlEntry) { if (asnArr->buff == NULL) { return HITLS_PKI_SUCCESS; } BslList *list = BSL_LIST_New(sizeof(HITLS_X509_ExtEntry)); if (list == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } uint8_t expTag = (BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE); BSL_ASN1_DecodeListParam listParam = {1, &expTag}; int32_t ret = BSL_ASN1_DecodeListItem(&listParam, asnArr, (BSL_ASN1_ParseListAsnItem)HITLS_CRL_ParseExtAsnItem, NULL, list); if (ret != BSL_SUCCESS) { BSL_LIST_FREE(list, NULL); return ret; } crlEntry->extList = list; return HITLS_PKI_SUCCESS; } int32_t HITLS_CRL_ParseCrlEntry(BSL_ASN1_Buffer *extItem, HITLS_X509_CrlEntry *crlEntry) { uint8_t *temp = extItem->buff; uint32_t tempLen = extItem->len; BSL_ASN1_Buffer asnArr[HITLS_X509_CRLENTRY_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_crlEntryTempl, sizeof(g_crlEntryTempl) / sizeof(g_crlEntryTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, HITLS_X509_CrlEntryChoiceCheck, &temp, &tempLen, asnArr, HITLS_X509_CRLENTRY_MAX_IDX); if (tempLen != 0) { ret = HITLS_X509_ERR_CRL_ENTRY; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } crlEntry->serialNumber = asnArr[HITLS_X509_CRLENTRY_NUM_IDX]; ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CRLENTRY_TIME_IDX], &crlEntry->time); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (asnArr[HITLS_X509_CRLENTRY_TIME_IDX].tag == BSL_ASN1_TAG_GENERALIZEDTIME) { crlEntry->flag |= BSL_TIME_REVOKE_TIME_IS_GMT; } ret = DecodeCrlRevokeExt(&asnArr[HITLS_X509_CRLENTRY_EXT_IDX], crlEntry); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t HITLS_CRL_ParseCrlAsnItem(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { (void) param; (void) layer; HITLS_X509_CrlEntry crlEntry = {0}; int32_t ret = HITLS_CRL_ParseCrlEntry(asn, &crlEntry); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } crlEntry.flag |= HITLS_X509_CRL_PARSE_FLAG; return HITLS_X509_AddListItemDefault(&crlEntry, sizeof(HITLS_X509_CrlEntry), list); } int32_t HITLS_X509_ParseCrlList(BSL_ASN1_Buffer *crl, BSL_ASN1_List *list) { // crl is optional if (crl->tag == 0) { return HITLS_PKI_SUCCESS; } uint8_t expTag = (BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE); BSL_ASN1_DecodeListParam listParam = {1, &expTag}; int32_t ret = BSL_ASN1_DecodeListItem(&listParam, crl, &HITLS_CRL_ParseCrlAsnItem, NULL, list); if (ret != BSL_SUCCESS) { BSL_LIST_DeleteAll(list, NULL); } return ret; } int32_t HITLS_X509_ParseCrlTbs(BSL_ASN1_Buffer *asnArr, HITLS_X509_Crl *crl) { int32_t ret; if (asnArr[HITLS_X509_CRL_VERSION_IDX].tag != 0) { ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CRL_VERSION_IDX], &crl->tbs.version); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } else { crl->tbs.version = 0; } // sign alg ret = HITLS_X509_ParseSignAlgInfo(&asnArr[HITLS_X509_CRL_TBS_SIGNALG_OID_IDX], &asnArr[HITLS_X509_CRL_TBS_SIGNALG_ANY_IDX], &crl->tbs.signAlgId); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // issuer name ret = HITLS_X509_ParseNameList(&asnArr[HITLS_X509_CRL_ISSUER_IDX], crl->tbs.issuerName); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // validity ret = HITLS_X509_ParseTime(&asnArr[HITLS_X509_CRL_BEFORE_VALID_IDX], &asnArr[HITLS_X509_CRL_AFTER_VALID_IDX], &crl->tbs.validTime); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // crl list ret = HITLS_X509_ParseCrlList(&asnArr[HITLS_X509_CRL_CRL_LIST_IDX], crl->tbs.revokedCerts); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // ext ret = HITLS_X509_ParseCrlExt(&asnArr[HITLS_X509_CRL_EXT_IDX], crl); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } return ret; ERR: BSL_LIST_DeleteAll(crl->tbs.issuerName, NULL); BSL_LIST_DeleteAll(crl->tbs.revokedCerts, NULL); return ret; } #endif // HITLS_PKI_X509_CRL_PARSE #ifdef HITLS_PKI_X509_CRL_GEN static void X509_EncodeCrlValidTime(HITLS_X509_ValidTime *crlTime, BSL_ASN1_Buffer *validTime) { validTime[0].tag = (crlTime->flag & BSL_TIME_BEFORE_IS_UTC) != 0 ? BSL_ASN1_TAG_UTCTIME : BSL_ASN1_TAG_GENERALIZEDTIME; validTime[0].len = sizeof(BSL_TIME); validTime[0].buff = (uint8_t *)&(crlTime->start); validTime[1].tag = (crlTime->flag & BSL_TIME_AFTER_IS_UTC) != 0 ? BSL_ASN1_TAG_UTCTIME : BSL_ASN1_TAG_GENERALIZEDTIME; if ((crlTime->flag & BSL_TIME_AFTER_SET) != 0) { validTime[1].len = sizeof(BSL_TIME); validTime[1].buff = (uint8_t *)&(crlTime->end); } else { validTime[1].len = 0; validTime[1].buff = NULL; } } static int32_t X509_EncodeCrlEntry(HITLS_X509_CrlEntry *crlEntry, BSL_ASN1_Buffer *asnBuf) { asnBuf[0].tag = crlEntry->serialNumber.tag; asnBuf[0].buff = crlEntry->serialNumber.buff; asnBuf[0].len = crlEntry->serialNumber.len; asnBuf[1].tag = (crlEntry->flag & BSL_TIME_REVOKE_TIME_IS_GMT) != 0 ? BSL_ASN1_TAG_GENERALIZEDTIME : BSL_ASN1_TAG_UTCTIME; asnBuf[1].buff = (uint8_t *)&(crlEntry->time); asnBuf[1].len = sizeof(BSL_TIME); if (crlEntry->extList != NULL && BSL_LIST_COUNT(crlEntry->extList) > 0) { return HITLS_X509_EncodeExtEntry(crlEntry->extList, &asnBuf[2]); // 2: extensions } else { asnBuf[2].tag = 0; // 2: extensions asnBuf[2].buff = NULL; // 2: extensions asnBuf[2].len = 0; // 2: extensions return HITLS_PKI_SUCCESS; } } #define X509_CRLENTRY_ELEM_NUMBER 3 int32_t HITLS_X509_EncodeRevokeCrlList(BSL_ASN1_List *crlList, BSL_ASN1_Buffer *revokeBuf) { int32_t count = BSL_LIST_COUNT(crlList); if (count <= 0) { revokeBuf->buff = NULL; revokeBuf->len = 0; revokeBuf->tag = BSL_ASN1_TAG_SEQUENCE; return HITLS_PKI_SUCCESS; } BSL_ASN1_Buffer *asnBuf = BSL_SAL_Malloc((uint32_t)count * sizeof(BSL_ASN1_Buffer) * X509_CRLENTRY_ELEM_NUMBER); if (asnBuf == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } (void)memset_s(asnBuf, (uint32_t)count * sizeof(BSL_ASN1_Buffer) * X509_CRLENTRY_ELEM_NUMBER, 0, (uint32_t)count * sizeof(BSL_ASN1_Buffer) * X509_CRLENTRY_ELEM_NUMBER); HITLS_X509_CrlEntry *crlEntry = NULL; uint32_t iter = 0; int32_t ret; for (crlEntry = BSL_LIST_GET_FIRST(crlList); crlEntry != NULL; crlEntry = BSL_LIST_GET_NEXT(crlList)) { ret = X509_EncodeCrlEntry(crlEntry, &asnBuf[iter]); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } iter += X509_CRLENTRY_ELEM_NUMBER; } BSL_ASN1_TemplateItem crlEntryTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_SAME | BSL_ASN1_FLAG_OPTIONAL, 0}, {BSL_ASN1_TAG_INTEGER, 0, 1}, {BSL_ASN1_TAG_CHOICE, 0, 1}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_OPTIONAL, 1} }; BSL_ASN1_Template templ = {crlEntryTempl, sizeof(crlEntryTempl) / sizeof(crlEntryTempl[0])}; ret = BSL_ASN1_EncodeListItem(BSL_ASN1_TAG_SEQUENCE, (uint32_t)count, &templ, asnBuf, iter, revokeBuf); EXIT: for (int32_t i = 0; i < count; i++) { /** * The memory for the extension in CRLentry needs to be freed up. * The subscript 2 corresponds to the extension. */ BSL_SAL_Free(asnBuf[i * X509_CRLENTRY_ELEM_NUMBER + 2].buff); } BSL_SAL_Free(asnBuf); return ret; } BSL_ASN1_TemplateItem g_crlTbsTempl[] = { /* 1: version */ {BSL_ASN1_TAG_INTEGER, BSL_ASN1_FLAG_DEFAULT, 0}, /* 2: signature info */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 0}, /* 3: issuer */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 0}, /* 4-5: validity */ {BSL_ASN1_TAG_CHOICE, 0, 0}, {BSL_ASN1_TAG_CHOICE, BSL_ASN1_FLAG_OPTIONAL, 0}, /* 6: revoked crl list */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME | BSL_ASN1_FLAG_OPTIONAL, 0}, /* 7: extension */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CRL_CTX_SPECIFIC_TAG_EXTENSION, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 0}, // 11 }; int32_t HITLS_X509_EncodeCrlExt(HITLS_X509_Ext *crlExt, BSL_ASN1_Buffer *ext) { return HITLS_X509_EncodeExt( BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CRL_CTX_SPECIFIC_TAG_EXTENSION, crlExt->extList, ext); } /** * RFC 5280 sec 5.1.2.1 * This optional field describes the version of the encoded CRL. When * extensions are used, as required by this profile, this field MUST be * present and MUST specify version 2 (the integer value is 1). */ static void X509_EncodeVersion(uint8_t *version, BSL_ASN1_Buffer *asn) { if (*version == 1) { asn->tag = BSL_ASN1_TAG_INTEGER; asn->len = 1; asn->buff = version; } else { asn->tag = BSL_ASN1_TAG_INTEGER; asn->len = 0; asn->buff = NULL; } } #define X509_CRLTBS_ELEM_NUMBER 7 int32_t HITLS_X509_EncodeCrlTbsRaw(HITLS_X509_CrlTbs *crlTbs, BSL_ASN1_Buffer *asn) { BSL_ASN1_Buffer asnArr[X509_CRLTBS_ELEM_NUMBER] = {0}; uint8_t version = (uint8_t)crlTbs->version; X509_EncodeVersion(&version, asnArr); // 0 is version BSL_ASN1_Buffer *signAlgAsn = &asnArr[1]; // 1 is signAlg BSL_ASN1_Buffer *issuerAsn = &asnArr[2]; // 2 is issuer name BSL_ASN1_Buffer *revokeBuf = &asnArr[5]; // 5 is revoke list BSL_ASN1_Buffer *crlExt = &asnArr[6]; // 6 is crl extension int32_t ret = HITLS_X509_EncodeSignAlgInfo(&crlTbs->signAlgId, signAlgAsn); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_EncodeNameList(crlTbs->issuerName, issuerAsn); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } X509_EncodeCrlValidTime(&crlTbs->validTime, &asnArr[3]); // 3 is valid time ret = HITLS_X509_EncodeRevokeCrlList(crlTbs->revokedCerts, revokeBuf); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = HITLS_X509_EncodeCrlExt(&(crlTbs->crlExt), crlExt); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } BSL_ASN1_Template templ = {g_crlTbsTempl, sizeof(g_crlTbsTempl) / sizeof(g_crlTbsTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, X509_CRLTBS_ELEM_NUMBER, &(asn->buff), &(asn->len)); if (ret != HITLS_PKI_SUCCESS) { goto EXIT; } asn->tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; EXIT: BSL_SAL_Free(signAlgAsn->buff); if (issuerAsn->buff != NULL) { BSL_SAL_Free(issuerAsn->buff); } if (revokeBuf->buff != NULL) { BSL_SAL_Free(revokeBuf->buff); } if (crlExt->buff != NULL) { BSL_SAL_Free(crlExt->buff); } return ret; } #define X509_CRL_ELEM_NUMBER 3 int32_t EncodeAsn1Crl(HITLS_X509_Crl *crl) { if (crl->signature.buff == NULL || crl->signature.len == 0 || crl->tbs.tbsRawData == NULL || crl->tbs.tbsRawDataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_NOT_SIGNED); return HITLS_X509_ERR_CRL_NOT_SIGNED; } BSL_ASN1_Buffer asnArr[X509_CRL_ELEM_NUMBER] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, crl->tbs.tbsRawDataLen, crl->tbs.tbsRawData}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}, {BSL_ASN1_TAG_BITSTRING, sizeof(BSL_ASN1_BitString), (uint8_t *)&crl->signature}, }; uint32_t valLen = 0; int32_t ret = BSL_ASN1_DecodeTagLen(asnArr[0].tag, &asnArr[0].buff, &asnArr[0].len, &valLen); // 0 is tbs if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_EncodeSignAlgInfo(&crl->signAlgId, &asnArr[1]); // 1 is signAlg if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_TemplateItem crlTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* crl */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 1}, /* tbs */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 1}, /* signAlg */ {BSL_ASN1_TAG_BITSTRING, 0, 1} /* sig */ }; BSL_ASN1_Template templ = {crlTempl, sizeof(crlTempl) / sizeof(crlTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, X509_CRL_ELEM_NUMBER, &crl->rawData, &crl->rawDataLen); BSL_SAL_Free(asnArr[1].buff); return ret; } /** * @brief Encode ASN.1 crl * * @param crl [IN] Pointer to the crl structure * @param buff [OUT] Pointer to the buffer. * If NULL, only the ASN.1 crl is encoded. * If non-NULL, the DER encoding content of the crl is stored in buff * @return int32_t Return value, 0 means success, other values mean failure */ int32_t HITLS_X509_EncodeAsn1Crl(HITLS_X509_Crl *crl, BSL_Buffer *buff) { int32_t ret; if ((crl->flag & HITLS_X509_CRL_GEN_FLAG) != 0) { if (crl->state != HITLS_X509_CRL_STATE_SIGN && crl->state != HITLS_X509_CRL_STATE_GEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_NOT_SIGNED); return HITLS_X509_ERR_CRL_NOT_SIGNED; } if (crl->state == HITLS_X509_CRL_STATE_SIGN) { ret = EncodeAsn1Crl(crl); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } crl->state = HITLS_X509_CRL_STATE_GEN; } } if (crl->rawData == NULL || crl->rawDataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_NOT_SIGNED); return HITLS_X509_ERR_CRL_NOT_SIGNED; } if (buff == NULL) { return HITLS_PKI_SUCCESS; } buff->data = BSL_SAL_Dump(crl->rawData, crl->rawDataLen); if (buff->data == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } buff->dataLen = crl->rawDataLen; return HITLS_PKI_SUCCESS; } #ifdef HITLS_BSL_PEM int32_t HITLS_X509_EncodePemCrl(HITLS_X509_Crl *crl, BSL_Buffer *buff) { int32_t ret = HITLS_X509_EncodeAsn1Crl(crl, NULL); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_PEM_Symbol symbol = {BSL_PEM_CRL_BEGIN_STR, BSL_PEM_CRL_END_STR}; return BSL_PEM_EncodeAsn1ToPem(crl->rawData, crl->rawDataLen, &symbol, (char **)&buff->data, &buff->dataLen); } #endif // HITLS_BSL_PEM static int32_t X509_CheckCrlRevoke(HITLS_X509_Crl *crl) { BSL_ASN1_List *revokedCerts = crl->tbs.revokedCerts; if (revokedCerts != NULL) { HITLS_X509_CrlEntry *entry = NULL; for (entry = BSL_LIST_GET_FIRST(revokedCerts); entry != NULL; entry = BSL_LIST_GET_NEXT(revokedCerts)) { // Check serial number if (entry->serialNumber.buff == NULL || entry->serialNumber.len == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_ENTRY); return HITLS_X509_ERR_CRL_ENTRY; } // Check revocation time if (!BSL_DateTimeCheck(&entry->time)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_TIME_INVALID); return HITLS_X509_ERR_CRL_TIME_INVALID; } // If entry has extensions and CRL version is v1, that's an error if (entry->extList != NULL && BSL_LIST_COUNT(entry->extList) > 0 && crl->tbs.version == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_INACCURACY_VERSION); return HITLS_X509_ERR_CRL_INACCURACY_VERSION; } } } return HITLS_PKI_SUCCESS; } static int32_t X509_CheckCrlTbs(HITLS_X509_Crl *crl) { int32_t ret; if (crl->tbs.version != 0 && crl->tbs.version != 1) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_INACCURACY_VERSION); return HITLS_X509_ERR_CRL_INACCURACY_VERSION; } if (crl->tbs.crlExt.extList != NULL && BSL_LIST_COUNT(crl->tbs.crlExt.extList) > 0) { if (crl->tbs.version != 1) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_INACCURACY_VERSION); return HITLS_X509_ERR_CRL_INACCURACY_VERSION; } } // Check issuer name if (crl->tbs.issuerName == NULL || BSL_LIST_COUNT(crl->tbs.issuerName) <= 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_ISSUER_EMPTY); return HITLS_X509_ERR_CRL_ISSUER_EMPTY; } // Check validity time if ((crl->tbs.validTime.flag & BSL_TIME_BEFORE_SET) == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_THISUPDATE_UNEXIST); return HITLS_X509_ERR_CRL_THISUPDATE_UNEXIST; } // If nextUpdate is set, check it's after thisUpdate if ((crl->tbs.validTime.flag & BSL_TIME_AFTER_SET) != 0) { ret = BSL_SAL_DateTimeCompare(&crl->tbs.validTime.start, &crl->tbs.validTime.end, NULL); if (ret != BSL_TIME_DATE_BEFORE) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_TIME_INVALID); return HITLS_X509_ERR_CRL_TIME_INVALID; } } ret = X509_CheckCrlRevoke(crl); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t HITLS_X509_CrlGenBuff(int32_t format, HITLS_X509_Crl *crl, BSL_Buffer *buff) { if (crl == NULL || buff == NULL || buff->data != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (format) { case BSL_FORMAT_ASN1: return HITLS_X509_EncodeAsn1Crl(crl, buff); #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: return HITLS_X509_EncodePemCrl(crl, buff); #endif // HITLS_BSL_PEM default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_X509_CrlGenFile(int32_t format, HITLS_X509_Crl *crl, const char *path) { if (path == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } BSL_Buffer buff = {0}; int32_t ret = HITLS_X509_CrlGenBuff(format, crl, &buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_SAL_WriteFile(path, buff.data, buff.dataLen); BSL_SAL_Free(buff.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_PKI_X509_CRL_GEN #ifdef HITLS_PKI_X509_CRL_PARSE int32_t HITLS_X509_ParseAsn1Crl(uint8_t *encode, uint32_t encodeLen, HITLS_X509_Crl *crl) { uint8_t *temp = encode; uint32_t tempLen = encodeLen; crl->rawData = encode; // crl takes over the encode immediately. if ((crl->flag & HITLS_X509_CRL_GEN_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } // template parse BSL_ASN1_Buffer asnArr[HITLS_X509_CRL_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_crlTempl, sizeof(g_crlTempl) / sizeof(g_crlTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, HITLS_X509_CrlTagGetOrCheck, &temp, &tempLen, asnArr, HITLS_X509_CRL_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // parse tbs raw data ret = HITLS_X509_ParseTbsRawData(encode, encodeLen, &crl->tbs.tbsRawData, &crl->tbs.tbsRawDataLen); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // parse tbs ret = HITLS_X509_ParseCrlTbs(asnArr, crl); if (ret != HITLS_PKI_SUCCESS) { return ret; } // parse sign alg ret = HITLS_X509_ParseSignAlgInfo(&asnArr[HITLS_X509_CRL_SIGNALG_IDX], &asnArr[HITLS_X509_CRL_SIGNALG_ANY_IDX], &crl->signAlgId); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // parse signature ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CRL_SIGN_IDX], &crl->signature); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } crl->rawDataLen = encodeLen - tempLen; crl->flag |= HITLS_X509_CRL_PARSE_FLAG; return HITLS_PKI_SUCCESS; ERR: BSL_LIST_DeleteAll(crl->tbs.issuerName, NULL); BSL_LIST_DeleteAll(crl->tbs.revokedCerts, NULL); BSL_LIST_DeleteAll(crl->tbs.crlExt.extList, NULL); return ret; } int32_t HITLS_X509_CrlParseBundleBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_List **crlList) { if (encode == NULL || encode->data == NULL || encode->dataLen == 0 || crlList == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } X509_ParseFuncCbk crlCbk = { .asn1Parse = (HITLS_X509_Asn1Parse)HITLS_X509_ParseAsn1Crl, .x509New = (HITLS_X509_New)HITLS_X509_CrlNew, .x509Free = (HITLS_X509_Free)HITLS_X509_CrlFree, }; HITLS_X509_List *list = BSL_LIST_New(sizeof(HITLS_X509_Crl)); if (list == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = HITLS_X509_ParseX509(NULL, NULL, format, encode, false, &crlCbk, list); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlFree); BSL_ERR_PUSH_ERROR(ret); return ret; } *crlList = list; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CrlParseBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_Crl **crl) { HITLS_X509_List *list = NULL; if (crl == NULL || *crl != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t ret = HITLS_X509_CrlParseBundleBuff(format, encode, &list); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } HITLS_X509_Crl *tmp = BSL_LIST_GET_FIRST(list); int ref; ret = HITLS_X509_CrlCtrl(tmp, HITLS_X509_REF_UP, &ref, sizeof(int)); BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlFree); if (ret != HITLS_PKI_SUCCESS) { return ret; } *crl = tmp; return HITLS_PKI_SUCCESS; } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_X509_CrlParseFile(int32_t format, const char *path, HITLS_X509_Crl **crl) { uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { return ret; } BSL_Buffer encode = {data, dataLen}; ret = HITLS_X509_CrlParseBuff(format, &encode, crl); BSL_SAL_Free(data); return ret; } int32_t HITLS_X509_CrlParseBundleFile(int32_t format, const char *path, HITLS_X509_List **crlList) { uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { return ret; } BSL_Buffer encode = {data, dataLen}; ret = HITLS_X509_CrlParseBundleBuff(format, &encode, crlList); BSL_SAL_Free(data); return ret; } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_PKI_X509_CRL_PARSE static int32_t X509_CrlRefUp(HITLS_X509_Crl *crl, int32_t *val, uint32_t valLen) { if (val == NULL || valLen != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } return BSL_SAL_AtomicUpReferences(&crl->references, val); } static int32_t X509_CrlGetThisUpdate(HITLS_X509_Crl *crl, BSL_TIME *val, uint32_t valLen) { if (valLen != sizeof(BSL_TIME)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((crl->tbs.validTime.flag & BSL_TIME_BEFORE_SET) == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_THISUPDATE_UNEXIST); return HITLS_X509_ERR_CRL_THISUPDATE_UNEXIST; } *val = crl->tbs.validTime.start; return HITLS_PKI_SUCCESS; } static int32_t X509_CrlGetNextUpdate(HITLS_X509_Crl *crl, BSL_TIME *val, uint32_t valLen) { if (valLen != sizeof(BSL_TIME)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((crl->tbs.validTime.flag & BSL_TIME_AFTER_SET) == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_NEXTUPDATE_UNEXIST); return HITLS_X509_ERR_CRL_NEXTUPDATE_UNEXIST; } *val = crl->tbs.validTime.end; return HITLS_PKI_SUCCESS; } static int32_t X509_CrlGetVersion(HITLS_X509_Crl *crl, int32_t *val, uint32_t valLen) { if (valLen != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } // CRL version is stored as v2(1), v1(0) *val = crl->tbs.version; return HITLS_PKI_SUCCESS; } static int32_t X509_CrlGetRevokeList(HITLS_X509_Crl *crl, BSL_ASN1_List **val, uint32_t valLen) { if (valLen != sizeof(BSL_ASN1_List *)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (crl->tbs.revokedCerts == NULL) { *val = NULL; BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_REVOKELIST_UNEXIST); return HITLS_X509_ERR_CRL_REVOKELIST_UNEXIST; } *val = crl->tbs.revokedCerts; return HITLS_PKI_SUCCESS; } static int32_t X509_CrlGetCtrl(HITLS_X509_Crl *crl, int32_t cmd, void *val, uint32_t valLen) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (cmd) { case HITLS_X509_GET_VERSION: return X509_CrlGetVersion(crl, val, valLen); case HITLS_X509_GET_BEFORE_TIME: return X509_CrlGetThisUpdate(crl, val, valLen); case HITLS_X509_GET_AFTER_TIME: return X509_CrlGetNextUpdate(crl, val, valLen); case HITLS_X509_GET_ISSUER_DN: return HITLS_X509_GetList(crl->tbs.issuerName, val, valLen); case HITLS_X509_GET_REVOKELIST: return X509_CrlGetRevokeList(crl, val, valLen); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #ifdef HITLS_PKI_X509_CRL_GEN static int32_t CrlSetTime(void *dest, uint8_t *val, uint32_t valLen) { if (valLen != sizeof(BSL_TIME) || !BSL_DateTimeCheck((BSL_TIME *)val)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } (void)memcpy_s(dest, valLen, val, valLen); return HITLS_PKI_SUCCESS; } static int32_t CrlSetThisUpdateTime(HITLS_X509_ValidTime *time, uint8_t *val, uint32_t valLen) { int32_t ret = CrlSetTime(&(time->start), val, valLen); if (ret != HITLS_PKI_SUCCESS) { return ret; } time->flag |= BSL_TIME_BEFORE_SET; return HITLS_PKI_SUCCESS; } static int32_t CrlSetNextUpdateTime(HITLS_X509_ValidTime *time, uint8_t *val, uint32_t valLen) { int32_t ret = CrlSetTime(&(time->end), val, valLen); if (ret != HITLS_PKI_SUCCESS) { return ret; } time->flag |= BSL_TIME_AFTER_SET; return HITLS_PKI_SUCCESS; } static HITLS_X509_CrlEntry *X509_CrlEntryDup(const HITLS_X509_CrlEntry *src) { HITLS_X509_CrlEntry *dest = (HITLS_X509_CrlEntry *)BSL_SAL_Malloc(sizeof(HITLS_X509_CrlEntry)); if (dest == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } (void)memset_s(dest, sizeof(HITLS_X509_CrlEntry), 0, sizeof(HITLS_X509_CrlEntry)); dest->serialNumber.buff = BSL_SAL_Dump(src->serialNumber.buff, src->serialNumber.len); if (dest->serialNumber.buff == NULL) { BSL_SAL_Free(dest); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } dest->serialNumber.len = src->serialNumber.len; dest->serialNumber.tag = src->serialNumber.tag; dest->time = src->time; dest->flag = src->flag; dest->flag &= ~HITLS_X509_CRL_PARSE_FLAG; dest->flag |= HITLS_X509_CRL_GEN_FLAG; if (src->extList != NULL) { dest->extList = BSL_LIST_Copy(src->extList, (BSL_LIST_PFUNC_DUP)X509_DupExtEntry, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); if (dest->extList == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET); goto ERR; } } return dest; ERR: BSL_SAL_Free(dest->serialNumber.buff); BSL_SAL_Free(dest); return NULL; } static void X509_CrlEntryFree(HITLS_X509_CrlEntry *entry) { if (entry == NULL) { return; } BSL_SAL_Free(entry->serialNumber.buff); BSL_LIST_FREE(entry->extList, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); BSL_SAL_Free(entry); } int32_t HITLS_X509_CrlAddRevokedCert(HITLS_X509_Crl *crl, void *val) { HITLS_X509_CrlEntry *entry = (HITLS_X509_CrlEntry *)val; if (entry->serialNumber.buff == NULL || entry->serialNumber.len == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_ENTRY); return HITLS_X509_ERR_CRL_ENTRY; } if (!BSL_DateTimeCheck(&entry->time)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_ENTRY); return HITLS_X509_ERR_CRL_ENTRY; } if (crl->tbs.revokedCerts == NULL) { crl->tbs.revokedCerts = BSL_LIST_New(sizeof(HITLS_X509_CrlEntry)); if (crl->tbs.revokedCerts == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } } HITLS_X509_CrlEntry *newEntry = X509_CrlEntryDup(entry); if (newEntry == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = BSL_LIST_AddElement(crl->tbs.revokedCerts, newEntry, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { X509_CrlEntryFree(newEntry); BSL_ERR_PUSH_ERROR(ret); return ret; } // If the CRL version is v1 and an extended revocation certificate is added, it needs to be upgraded to v2 if (crl->tbs.version == 0 && entry->extList != NULL) { crl->tbs.version = 1; // v2 } return HITLS_PKI_SUCCESS; } static int32_t X509_CrlSetVersion(HITLS_X509_Crl *crl, int32_t *val, uint32_t valLen) { if (valLen != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t version = *val; if (version != 0 && version != 1) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } crl->tbs.version = version; return HITLS_PKI_SUCCESS; } static int32_t X509_CrlSetCtrl(HITLS_X509_Crl *crl, int32_t cmd, void *val, uint32_t valLen) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((crl->flag & HITLS_X509_CRL_PARSE_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_AFTER_PARSE); return HITLS_X509_ERR_SET_AFTER_PARSE; } crl->flag |= HITLS_X509_CRL_GEN_FLAG; crl->state = HITLS_X509_CRL_STATE_SET; switch (cmd) { case HITLS_X509_SET_VERSION: return X509_CrlSetVersion(crl, val, valLen); case HITLS_X509_SET_ISSUER_DN: return HITLS_X509_SetNameList(&crl->tbs.issuerName, val, valLen); case HITLS_X509_SET_BEFORE_TIME: return CrlSetThisUpdateTime(&crl->tbs.validTime, val, valLen); case HITLS_X509_SET_AFTER_TIME: return CrlSetNextUpdateTime(&crl->tbs.validTime, val, valLen); case HITLS_X509_CRL_ADD_REVOKED_CERT: return HITLS_X509_CrlAddRevokedCert(crl, val); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_X509_CRL_GEN int32_t HITLS_X509_CrlCtrl(HITLS_X509_Crl *crl, int32_t cmd, void *val, uint32_t valLen) { if (crl == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (cmd == HITLS_X509_REF_UP) { return X509_CrlRefUp(crl, val, valLen); #ifdef HITLS_CRYPTO_SM2 } else if (cmd == HITLS_X509_SET_VFY_SM2_USER_ID) { if (crl->signAlgId.algId != BSL_CID_SM2DSAWITHSM3) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_SIGNALG_NOT_MATCH); return HITLS_X509_ERR_VFY_SIGNALG_NOT_MATCH; } return HITLS_X509_SetSm2UserId(&crl->signAlgId.sm2UserId, val, valLen); #endif } else if (cmd >= HITLS_X509_GET_ENCODELEN && cmd < HITLS_X509_SET_VERSION) { return X509_CrlGetCtrl(crl, cmd, val, valLen); } else if (cmd < HITLS_X509_EXT_SET_SKI) { #ifdef HITLS_PKI_X509_CRL_GEN return X509_CrlSetCtrl(crl, cmd, val, valLen); #else BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_FUNC_UNSUPPORT); return HITLS_X509_ERR_FUNC_UNSUPPORT; #endif } else if (cmd <= HITLS_X509_EXT_CHECK_SKI) { static int32_t cmdSet[] = {HITLS_X509_EXT_SET_CRLNUMBER, HITLS_X509_EXT_SET_AKI, HITLS_X509_EXT_GET_CRLNUMBER, HITLS_X509_EXT_GET_AKI, HITLS_X509_EXT_GET_KUSAGE}; if (!X509_CheckCmdValid(cmdSet, sizeof(cmdSet) / sizeof(int32_t), cmd)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_UNSUPPORT); return HITLS_X509_ERR_EXT_UNSUPPORT; } return X509_ExtCtrl(&crl->tbs.crlExt, cmd, val, valLen); } else { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } int32_t HITLS_X509_CrlVerify(void *pubkey, const HITLS_X509_Crl *crl) { if (pubkey == NULL || crl == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((crl->flag & HITLS_X509_CRL_GEN_FLAG) != 0 && (crl->state != HITLS_X509_CRL_STATE_SIGN) && (crl->state != HITLS_X509_CRL_STATE_GEN)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_NOT_SIGNED); return HITLS_X509_ERR_CRL_NOT_SIGNED; } int32_t ret = HITLS_X509_CheckAlg(pubkey, &(crl->signAlgId)); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = HITLS_X509_CheckSignature(pubkey, crl->tbs.tbsRawData, crl->tbs.tbsRawDataLen, &(crl->signAlgId), &crl->signature); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } HITLS_X509_CrlEntry *HITLS_X509_CrlEntryNew(void) { HITLS_X509_CrlEntry *entry = BSL_SAL_Malloc(sizeof(HITLS_X509_CrlEntry)); if (entry == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } (void)memset_s(entry, sizeof(HITLS_X509_CrlEntry), 0, sizeof(HITLS_X509_CrlEntry)); entry->flag |= HITLS_X509_CRL_GEN_FLAG; return entry; } void HITLS_X509_CrlEntryFree(HITLS_X509_CrlEntry *entry) { if (entry == NULL) { return; } if ((entry->flag & HITLS_X509_CRL_GEN_FLAG) != 0) { BSL_SAL_Free(entry->serialNumber.buff); BSL_LIST_FREE(entry->extList, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); } else { BSL_LIST_FREE(entry->extList, NULL); } BSL_SAL_Free(entry); } static int32_t X509_CrlGetRevokedRevokeTime(HITLS_X509_CrlEntry *entry, void *val, uint32_t valLen) { if (valLen != sizeof(BSL_TIME)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *(BSL_TIME *)val = entry->time; return HITLS_PKI_SUCCESS; } #ifdef HITLS_PKI_X509_CRL_GEN static int32_t X509_CrlSetRevokedExt(HITLS_X509_CrlEntry *entry, BslCid cid, BSL_Buffer *buff, uint32_t exceptLen, EncodeExtCb encodeExt) { if (buff->dataLen != exceptLen) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (entry->extList == NULL) { entry->extList = BSL_LIST_New(sizeof(HITLS_X509_ExtEntry)); if (entry->extList == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } } return HITLS_X509_SetExtList(NULL, entry->extList, cid, buff, encodeExt); } static int32_t SetExtInvalidTime(void *param, HITLS_X509_ExtEntry *entry, const void *val) { (void)param; const HITLS_X509_RevokeExtTime *invalidTime = (const HITLS_X509_RevokeExtTime *)val; entry->critical = invalidTime->critical; BSL_ASN1_Buffer asns = {0}; /** * CRL issuers conforming to this profile MUST encode thisUpdate as UTCTime for dates through the year 2049. * CRL issuers conforming to this profile MUST encode thisUpdate as GeneralizedTime for dates in the year * 2050 or later. */ if (invalidTime->time.year >= 2050) { asns.tag = BSL_ASN1_TAG_GENERALIZEDTIME; } else { asns.tag = BSL_ASN1_TAG_UTCTIME; } asns.len = sizeof(BSL_TIME); asns.buff = (uint8_t *)(uintptr_t)&invalidTime->time; BSL_ASN1_TemplateItem templItem = {BSL_ASN1_TAG_CHOICE, 0, 0}; BSL_ASN1_Template templ = {&templItem, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, &asns, 1, &entry->extnValue.buff, &entry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t SetExtReason(void *param, HITLS_X509_ExtEntry *extEntry, void *val) { (void)param; HITLS_X509_RevokeExtReason *reason = (HITLS_X509_RevokeExtReason *)val; if (reason->reason < HITLS_X509_REVOKED_REASON_UNSPECIFIED || reason->reason > HITLS_X509_REVOKED_REASON_AA_COMPROMISE) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } extEntry->critical = reason->critical; uint8_t tmp = (uint8_t)reason->reason; // int32_t -> uint8_t: avoid value errors in bit-endian scenario BSL_ASN1_Buffer asns = {BSL_ASN1_TAG_ENUMERATED, sizeof(uint8_t), (uint8_t *)&tmp}; BSL_ASN1_TemplateItem items = {BSL_ASN1_TAG_ENUMERATED, 0, 0}; BSL_ASN1_Template reasonTempl = {&items, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&reasonTempl, &asns, 1, &extEntry->extnValue.buff, &extEntry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_PKI_X509_CRL_GEN static int32_t SetExtCertificateIssuer(void *param, HITLS_X509_ExtEntry *extEntry, void *val) { (void)param; return HITLS_X509_SetGeneralNames(extEntry, val); } int32_t HITLS_ParseCrlExtInvalidTime(HITLS_X509_ExtEntry *extEntry, void *val) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; BSL_ASN1_Buffer asn = {0}; BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_CHOICE, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, HITLS_X509_CrlEntryChoiceCheck, &temp, &tempLen, &asn, 1); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_ASN1_DecodePrimitiveItem(&asn, val); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t HITLS_ParseCrlExtReason(HITLS_X509_ExtEntry *extEntry, void *val) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; BSL_ASN1_Buffer asn = {0}; BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_ENUMERATED, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, HITLS_X509_CrlEntryChoiceCheck, &temp, &tempLen, &asn, 1); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_ASN1_DecodePrimitiveItem(&asn, val); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t DecodeExtCertIssuer(HITLS_X509_ExtEntry *extEntry, BslList **val) { BslList *list = BSL_LIST_New(sizeof(HITLS_X509_GeneralName)); if (list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_AKI); return HITLS_X509_ERR_PARSE_AKI; } int32_t ret = HITLS_X509_ParseGeneralNames(extEntry->extnValue.buff, extEntry->extnValue.len, list); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(list); BSL_ERR_PUSH_ERROR(ret); return ret; } *val = list; return HITLS_PKI_SUCCESS; } #ifdef HITLS_PKI_X509_CRL_GEN static int32_t RevokedSet(HITLS_X509_CrlEntry *revoked, int32_t cmd, void *val, uint32_t valLen) { if ((revoked->flag & HITLS_X509_CRL_PARSE_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET_AFTER_PARSE); return HITLS_X509_ERR_EXT_SET_AFTER_PARSE; } BSL_Buffer buff = {val, valLen}; switch (cmd) { case HITLS_X509_CRL_SET_REVOKED_SERIALNUM: return HITLS_X509_SetSerial(&revoked->serialNumber, val, valLen); case HITLS_X509_CRL_SET_REVOKED_REVOKE_TIME: return CrlSetTime(&revoked->time, val, valLen); case HITLS_X509_CRL_SET_REVOKED_INVALID_TIME: return X509_CrlSetRevokedExt(revoked, BSL_CID_CE_INVALIDITYDATE, &buff, sizeof(HITLS_X509_RevokeExtTime), (EncodeExtCb)SetExtInvalidTime); case HITLS_X509_CRL_SET_REVOKED_REASON: return X509_CrlSetRevokedExt(revoked, BSL_CID_CE_CRLREASONS, &buff, sizeof(HITLS_X509_RevokeExtReason), (EncodeExtCb)SetExtReason); case HITLS_X509_CRL_SET_REVOKED_CERTISSUER: return X509_CrlSetRevokedExt(revoked, BSL_CID_CE_CERTIFICATEISSUER, &buff, sizeof(HITLS_X509_RevokeExtCertIssuer), (EncodeExtCb)SetExtCertificateIssuer); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_X509_CRL_GEN static int32_t RevokedGet(HITLS_X509_CrlEntry *revoked, int32_t cmd, void *val, uint32_t valLen) { BSL_Buffer buff = {val, valLen}; switch (cmd) { case HITLS_X509_CRL_GET_REVOKED_REVOKE_TIME: return X509_CrlGetRevokedRevokeTime(revoked, val, valLen); case HITLS_X509_CRL_GET_REVOKED_SERIALNUM: return HITLS_X509_GetSerial(&revoked->serialNumber, val, valLen); case HITLS_X509_CRL_GET_REVOKED_INVALID_TIME: return HITLS_X509_GetExt(revoked->extList, BSL_CID_CE_INVALIDITYDATE, &buff, sizeof(BSL_TIME), (DecodeExtCb)HITLS_ParseCrlExtInvalidTime); case HITLS_X509_CRL_GET_REVOKED_REASON: return HITLS_X509_GetExt(revoked->extList, BSL_CID_CE_CRLREASONS, &buff, sizeof(int32_t), (DecodeExtCb)HITLS_ParseCrlExtReason); case HITLS_X509_CRL_GET_REVOKED_CERTISSUER: return HITLS_X509_GetExt(revoked->extList, BSL_CID_CE_CERTIFICATEISSUER, &buff, sizeof(BslList *), (DecodeExtCb)DecodeExtCertIssuer); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } int32_t HITLS_X509_CrlEntryCtrl(HITLS_X509_CrlEntry *revoked, int32_t cmd, void *val, uint32_t valLen) { if (revoked == NULL || val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } #ifdef HITLS_PKI_X509_CRL_GEN if (cmd < HITLS_X509_CRL_GET_REVOKED_SERIALNUM) { return RevokedSet(revoked, cmd, val, valLen); } #endif return RevokedGet(revoked, cmd, val, valLen); } #ifdef HITLS_PKI_X509_CRL_GEN static int32_t CrlSignCb(int32_t mdId, CRYPT_EAL_PkeyCtx *prvKey, HITLS_X509_Asn1AlgId *signAlgId, HITLS_X509_Crl *crl) { BSL_Buffer signBuff = {0}; BSL_ASN1_Buffer tbsCertList = {0}; crl->signAlgId = *signAlgId; crl->tbs.signAlgId = *signAlgId; int32_t ret = HITLS_X509_EncodeCrlTbsRaw(&crl->tbs, &tbsCertList); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = HITLS_X509_SignAsn1Data(prvKey, mdId, &tbsCertList, &signBuff, &crl->signature); BSL_SAL_Free(tbsCertList.buff); if (ret != HITLS_PKI_SUCCESS) { return ret; } crl->tbs.tbsRawData = signBuff.data; crl->tbs.tbsRawDataLen = signBuff.dataLen; crl->state = HITLS_X509_CRL_STATE_SIGN; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CrlSign(int32_t mdId, const CRYPT_EAL_PkeyCtx *prvKey, const HITLS_X509_SignAlgParam *algParam, HITLS_X509_Crl *crl) { if (crl == NULL || prvKey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((crl->flag & HITLS_X509_CRL_PARSE_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SIGN_AFTER_PARSE); return HITLS_X509_ERR_SIGN_AFTER_PARSE; } if (crl->state == HITLS_X509_CRL_STATE_SIGN || crl->state == HITLS_X509_CRL_STATE_GEN) { return HITLS_PKI_SUCCESS; } int32_t ret = X509_CheckCrlTbs(crl); if (ret != HITLS_PKI_SUCCESS) { return ret; } BSL_SAL_FREE(crl->signature.buff); crl->signature.len = 0; BSL_SAL_FREE(crl->tbs.tbsRawData); crl->tbs.tbsRawDataLen = 0; BSL_SAL_FREE(crl->rawData); crl->rawDataLen = 0; #ifdef HITLS_CRYPTO_SM2 if (crl->signAlgId.algId == BSL_CID_SM2DSAWITHSM3) { BSL_SAL_FREE(crl->signAlgId.sm2UserId.data); crl->signAlgId.sm2UserId.dataLen = 0; } #endif return HITLS_X509_Sign(mdId, prvKey, algParam, crl, (HITLS_X509_SignCb)CrlSignCb); } #endif // HITLS_PKI_X509_CRL_GEN #endif // HITLS_PKI_X509_CRL
2301_79861745/bench_create
pki/x509_crl/src/hitls_x509_crl.c
C
unknown
54,553
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_CSR_LOCAL_H #define HITLS_CSR_LOCAL_H #include "hitls_build.h" #ifdef HITLS_PKI_X509_CSR #include <stdint.h> #include "bsl_asn1_internal.h" #include "bsl_obj.h" #include "sal_atomic.h" #include "hitls_x509_local.h" #ifdef __cplusplus extern "C" { #endif typedef struct _HITLS_X509_ReqInfo { uint8_t *reqInfoRawData; uint32_t reqInfoRawDataLen; int32_t version; BSL_ASN1_List *subjectName; /* Entry is HITLS_X509_NameNode */ void *ealPubKey; HITLS_X509_Attrs *attributes; } HITLS_X509_ReqInfo; typedef enum { HITLS_X509_CSR_STATE_NEW = 0, HITLS_X509_CSR_STATE_SET, HITLS_X509_CSR_STATE_SIGN, HITLS_X509_CSR_STATE_GEN, } HITLS_X509_CSR_STATE; /* PKCS #10 */ typedef struct _HITLS_X509_Csr { uint8_t flag; // Used to mark csr parsing or generation, indicating resource release behavior. uint8_t state; uint8_t *rawData; uint32_t rawDataLen; HITLS_X509_ReqInfo reqInfo; HITLS_X509_Asn1AlgId signAlgId; BSL_ASN1_BitString signature; BSL_SAL_RefCount references; CRYPT_EAL_LibCtx *libCtx; // Provider context const char *attrName; // Provider attribute name } HITLS_X509_Csr; #ifdef __cplusplus } #endif #endif // HITLS_PKI_X509_CSR #endif // HITLS_CSR_LOCAL_H
2301_79861745/bench_create
pki/x509_csr/include/hitls_csr_local.h
C
unknown
1,823
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_X509_CSR #include "securec.h" #include "bsl_sal.h" #include "bsl_asn1_internal.h" #include "bsl_obj_internal.h" #include "bsl_err_internal.h" #ifdef HITLS_BSL_PEM #include "bsl_pem_internal.h" #endif // HITLS_BSL_PEM #include "bsl_log_internal.h" #include "hitls_pki_errno.h" #include "crypt_encode_decode_key.h" #include "crypt_errno.h" #ifdef HITLS_BSL_SAL_FILE #include "sal_file.h" #endif #include "crypt_eal_codecs.h" #include "hitls_csr_local.h" #include "hitls_pki_utils.h" #include "hitls_pki_csr.h" #define HITLS_CSR_CTX_SPECIFIC_TAG_ATTRIBUTE 0 #define HITLS_X509_CSR_PARSE_FLAG 0x01 #define HITLS_X509_CSR_GEN_FLAG 0x02 #ifdef HITLS_PKI_X509_CSR_PARSE /** * RFC2986: section 4 * CertificationRequest ::= SEQUENCE { * certificationRequestInfo CertificationRequestInfo, * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, * signature BIT STRING * } */ BSL_ASN1_TemplateItem g_csrTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* PKCS10 csr */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* req info */ /* 2: version */ {BSL_ASN1_TAG_INTEGER, 0, 2}, /* 2: subject name */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 2}, /* 2: public key info */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 2}, /* 2: attributes */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CSR_CTX_SPECIFIC_TAG_ATTRIBUTE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 2}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* signAlg */ {BSL_ASN1_TAG_OBJECT_ID, 0, 2}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 2}, {BSL_ASN1_TAG_BITSTRING, 0, 1} /* sig */ }; typedef enum { HITLS_X509_CSR_REQINFO_VERSION_IDX = 0, HITLS_X509_CSR_REQINFO_SUBJECT_NAME_IDX = 1, HITLS_X509_CSR_REQINFO_PUBKEY_INFO_IDX = 2, HITLS_X509_CSR_REQINFO_ATTRS_IDX = 3, HITLS_X509_CSR_SIGNALG_OID_IDX = 4, HITLS_X509_CSR_SIGNALG_ANY_IDX = 5, HITLS_X509_CSR_SIGN_IDX = 6, HITLS_X509_CSR_MAX_IDX = 7, } HITLS_X509_CSR_IDX; #endif // HITLS_PKI_X509_CSR_PARSE HITLS_X509_Csr *HITLS_X509_CsrNew(void) { HITLS_X509_Csr *csr = NULL; BSL_ASN1_List *subjectName = NULL; HITLS_X509_Attrs *attributes = NULL; csr = (HITLS_X509_Csr *)BSL_SAL_Calloc(1, sizeof(HITLS_X509_Csr)); if (csr == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } subjectName = BSL_LIST_New(sizeof(HITLS_X509_NameNode)); if (subjectName == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); goto ERR; } attributes = HITLS_X509_AttrsNew(); if (attributes == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); goto ERR; } BSL_SAL_ReferencesInit(&(csr->references)); csr->reqInfo.subjectName = subjectName; csr->reqInfo.attributes = attributes; csr->state = HITLS_X509_CSR_STATE_NEW; return csr; ERR: BSL_SAL_FREE(subjectName); HITLS_X509_AttrsFree(attributes, NULL); BSL_SAL_FREE(csr); return NULL; } HITLS_X509_Csr *HITLS_X509_ProviderCsrNew(HITLS_PKI_LibCtx *libCtx, const char *attrName) { HITLS_X509_Csr *csr = HITLS_X509_CsrNew(); if (csr == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } csr->libCtx = libCtx; csr->attrName = attrName; return csr; } void HITLS_X509_CsrFree(HITLS_X509_Csr *csr) { if (csr == NULL) { return; } int ret = 0; BSL_SAL_AtomicDownReferences(&(csr->references), &ret); if (ret > 0) { return; } BSL_SAL_ReferencesFree(&(csr->references)); if (csr->flag == HITLS_X509_CSR_GEN_FLAG) { BSL_LIST_FREE(csr->reqInfo.subjectName, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); BSL_SAL_FREE(csr->reqInfo.reqInfoRawData); BSL_SAL_FREE(csr->signature.buff); } else { BSL_LIST_FREE(csr->reqInfo.subjectName, NULL); } #ifdef HITLS_CRYPTO_SM2 if (csr->signAlgId.algId == BSL_CID_SM2DSAWITHSM3) { BSL_SAL_FREE(csr->signAlgId.sm2UserId.data); csr->signAlgId.sm2UserId.dataLen = 0; } #endif HITLS_X509_AttrsFree(csr->reqInfo.attributes, NULL); csr->reqInfo.attributes = NULL; BSL_SAL_FREE(csr->rawData); CRYPT_EAL_PkeyFreeCtx(csr->reqInfo.ealPubKey); csr->reqInfo.ealPubKey = NULL; BSL_SAL_FREE(csr); } #ifdef HITLS_PKI_X509_CSR_PARSE int32_t HITLS_X509_CsrTagGetOrCheck(int32_t type, uint32_t idx, void *data, void *expVal) { (void)idx; if (type == BSL_ASN1_TYPE_GET_ANY_TAG) { BSL_ASN1_Buffer *param = (BSL_ASN1_Buffer *)data; BslOidString oidStr = {param->len, (char *)param->buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_UNKNOWN) { return HITLS_X509_ERR_GET_ANY_TAG; } if (cid == BSL_CID_RSASSAPSS) { /* note: any It can be encoded empty or it can be null */ *(uint8_t *)expVal = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; return BSL_SUCCESS; } else { *(uint8_t *)expVal = BSL_ASN1_TAG_NULL; // is null return BSL_SUCCESS; } } return HITLS_X509_ERR_INVALID_PARAM; } static int32_t ParseCertRequestInfo(BSL_ASN1_Buffer *asnArr, HITLS_X509_Csr *csr) { int32_t ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CSR_REQINFO_VERSION_IDX], &csr->reqInfo.version); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* subject name */ ret = HITLS_X509_ParseNameList(&asnArr[HITLS_X509_CSR_REQINFO_SUBJECT_NAME_IDX], csr->reqInfo.subjectName); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* public key info */ BSL_Buffer subPubKeyBuff = {asnArr[HITLS_X509_CSR_REQINFO_PUBKEY_INFO_IDX].buff, asnArr[HITLS_X509_CSR_REQINFO_PUBKEY_INFO_IDX].len}; ret = CRYPT_EAL_ProviderDecodeBuffKey(csr->libCtx, csr->attrName, BSL_CID_UNKNOWN, "ASN1", "PUBKEY_SUBKEY_WITHOUT_SEQ", &subPubKeyBuff, NULL, (CRYPT_EAL_PkeyCtx **)&csr->reqInfo.ealPubKey); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } /* attributes */ ret = HITLS_X509_ParseAttrList(&asnArr[HITLS_X509_CSR_REQINFO_ATTRS_IDX], csr->reqInfo.attributes, NULL, NULL); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } return ret; ERR: if (csr->reqInfo.ealPubKey != NULL) { CRYPT_EAL_PkeyFreeCtx(csr->reqInfo.ealPubKey); csr->reqInfo.ealPubKey = NULL; } BSL_LIST_FREE(csr->reqInfo.subjectName, NULL); return ret; } static int32_t X509CsrBuffAsn1Parse(uint8_t *encode, uint32_t encodeLen, HITLS_X509_Csr *csr) { uint8_t *temp = encode; uint32_t tempLen = encodeLen; // template parse BSL_ASN1_Buffer asnArr[HITLS_X509_CSR_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_csrTempl, sizeof(g_csrTempl) / sizeof(g_csrTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, HITLS_X509_CsrTagGetOrCheck, &temp, &tempLen, asnArr, HITLS_X509_CSR_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // parse reqInfo raw data ret = HITLS_X509_ParseTbsRawData(encode, encodeLen, &csr->reqInfo.reqInfoRawData, &csr->reqInfo.reqInfoRawDataLen); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // parse reqInfo ret = ParseCertRequestInfo(asnArr, csr); if (ret != HITLS_PKI_SUCCESS) { goto ERR; } // parse sign alg ret = HITLS_X509_ParseSignAlgInfo(&asnArr[HITLS_X509_CSR_SIGNALG_OID_IDX], &asnArr[HITLS_X509_CSR_SIGNALG_ANY_IDX], &csr->signAlgId); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // parse signature ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CSR_SIGN_IDX], &csr->signature); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } csr->rawData = encode; csr->rawDataLen = encodeLen - tempLen; return HITLS_PKI_SUCCESS; ERR: HITLS_X509_AttrsFree(csr->reqInfo.attributes, NULL); csr->reqInfo.attributes = NULL; BSL_LIST_FREE(csr->reqInfo.subjectName, NULL); if (csr->reqInfo.ealPubKey != NULL) { CRYPT_EAL_PkeyFreeCtx(csr->reqInfo.ealPubKey); csr->reqInfo.ealPubKey = NULL; } return ret; } static int32_t X509CsrAsn1Parse(bool isCopy, const BSL_Buffer *encode, HITLS_X509_Csr *csr) { uint8_t *data = encode->data; uint32_t dataLen = encode->dataLen; if ((csr->flag & HITLS_X509_CSR_GEN_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } uint8_t *tmp = NULL; if (isCopy) { tmp = (uint8_t *)BSL_SAL_Dump(data, dataLen); if (tmp == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } data = tmp; } int32_t ret = X509CsrBuffAsn1Parse(data, dataLen, csr); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(tmp); return ret; } csr->flag |= HITLS_X509_CSR_PARSE_FLAG; return HITLS_PKI_SUCCESS; } #ifdef HITLS_BSL_PEM static int32_t X509CsrPemParse(const BSL_Buffer *encode, HITLS_X509_Csr *csr) { uint8_t *tmpBuf = encode->data; uint32_t tmpBufLen = encode->dataLen; BSL_Buffer asn1Buf = {NULL, 0}; BSL_PEM_Symbol symbol = {BSL_PEM_CERT_REQ_BEGIN_STR, BSL_PEM_CERT_REQ_END_STR}; int32_t ret = BSL_PEM_DecodePemToAsn1((char **)&tmpBuf, &tmpBufLen, &symbol, &asn1Buf.data, &asn1Buf.dataLen); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = X509CsrAsn1Parse(false, &asn1Buf, csr); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(asn1Buf.data); BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_BSL_PEM int32_t HITLS_X509_CsrParseBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_Csr **csr) { if (encode == NULL || csr == NULL || *csr != NULL || encode->data == NULL || encode->dataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t ret; HITLS_X509_Csr *tempCsr = HITLS_X509_CsrNew(); if (tempCsr == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } switch (format) { case BSL_FORMAT_ASN1: ret = X509CsrAsn1Parse(true, encode, tempCsr); break; #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: ret = X509CsrPemParse(encode, tempCsr); break; #endif // HITLS_BSL_PEM default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_FORMAT_UNSUPPORT); ret = HITLS_X509_ERR_FORMAT_UNSUPPORT; break; } if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); HITLS_X509_CsrFree(tempCsr); return ret; } *csr = tempCsr; return ret; } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_X509_CsrParseFile(int32_t format, const char *path, HITLS_X509_Csr **csr) { if (path == NULL || csr == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer encode = {data, dataLen}; ret = HITLS_X509_CsrParseBuff(format, &encode, csr); BSL_SAL_Free(data); return ret; } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_PKI_X509_CSR_PARSE #ifdef HITLS_PKI_X509_CSR_GEN static int32_t CheckCsrValid(HITLS_X509_Csr *csr) { if (csr->reqInfo.ealPubKey == NULL) { return HITLS_X509_ERR_CSR_INVALID_PUBKEY; } if (csr->reqInfo.subjectName == NULL || BSL_LIST_COUNT(csr->reqInfo.subjectName) <= 0) { return HITLS_X509_ERR_CSR_INVALID_SUBJECT_DN; } return HITLS_PKI_SUCCESS; } static int32_t EncodeCsrReqInfoItem(HITLS_X509_ReqInfo *reqInfo, BSL_ASN1_Buffer *subject, BSL_ASN1_Buffer *publicKey, BSL_ASN1_Buffer *attributes) { /* encode subject name */ int32_t ret = HITLS_X509_EncodeNameList(reqInfo->subjectName, subject); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* encode public key */ BSL_Buffer pub = {0}; ret = CRYPT_EAL_EncodePubKeyBuffInternal(reqInfo->ealPubKey, BSL_FORMAT_ASN1, CRYPT_PUBKEY_SUBKEY, false, &pub); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } /* encode attribute */ ret = HITLS_X509_EncodeAttrList( BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CSR_CTX_SPECIFIC_TAG_ATTRIBUTE, reqInfo->attributes, NULL, attributes); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } publicKey->buff = pub.data; publicKey->len = pub.dataLen; return ret; ERR: BSL_SAL_FREE(subject->buff); BSL_SAL_FREE(pub.data); BSL_SAL_FREE(attributes->buff); return ret; } static BSL_ASN1_TemplateItem g_reqInfoTempl[] = { /* version */ {BSL_ASN1_TAG_INTEGER, 0, 0}, /* subject name */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 0}, /* public key */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 0}, /* attributes */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CSR_CTX_SPECIFIC_TAG_ATTRIBUTE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 0}, }; #define HITLS_X509_CSR_REQINFO_SIZE 4 static int32_t EncodeCsrReqInfo(HITLS_X509_ReqInfo *reqInfo, BSL_ASN1_Buffer *reqInfoBuff) { BSL_ASN1_Buffer subject = {0, 0, NULL}; BSL_ASN1_Buffer publicKey = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}; BSL_ASN1_Buffer attributes = {0, 0, NULL}; int ret = EncodeCsrReqInfoItem(reqInfo, &subject, &publicKey, &attributes); if (ret != HITLS_PKI_SUCCESS) { return ret; } uint8_t version = (uint8_t)reqInfo->version; BSL_ASN1_Template templ = { g_reqInfoTempl, sizeof(g_reqInfoTempl) / sizeof(g_reqInfoTempl[0]) }; BSL_ASN1_Buffer reqInfoAsn[HITLS_X509_CSR_REQINFO_SIZE] = { {BSL_ASN1_TAG_INTEGER, 1, &version}, subject, publicKey, attributes }; ret = BSL_ASN1_EncodeTemplate(&templ, reqInfoAsn, HITLS_X509_CSR_REQINFO_SIZE, &reqInfoBuff->buff, &reqInfoBuff->len); BSL_SAL_FREE(subject.buff); BSL_SAL_FREE(publicKey.buff); BSL_SAL_FREE(attributes.buff); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } BSL_ASN1_TemplateItem g_briefCsrTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* pkcs10 csr */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* reqInfo */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* signAlg */ {BSL_ASN1_TAG_BITSTRING, 0, 1} /* sig */ }; #define HITLS_X509_CSR_BRIEF_SIZE 3 static int32_t X509EncodeAsn1CsrCore(HITLS_X509_Csr *csr) { if (csr->signature.buff == NULL || csr->signature.len == 0 || csr->reqInfo.reqInfoRawData == NULL || csr->reqInfo.reqInfoRawDataLen == 0 || csr->signAlgId.algId == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CSR_NOT_SIGNED); return HITLS_X509_ERR_CSR_NOT_SIGNED; } BSL_ASN1_Buffer asnArr[HITLS_X509_CSR_BRIEF_SIZE] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, csr->reqInfo.reqInfoRawDataLen, csr->reqInfo.reqInfoRawData}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}, {BSL_ASN1_TAG_BITSTRING, sizeof(BSL_ASN1_BitString), (uint8_t *)&csr->signature} }; uint32_t valLen = 0; int32_t ret = BSL_ASN1_DecodeTagLen(asnArr[0].tag, &asnArr[0].buff, &asnArr[0].len, &valLen); // 0 is reqInfo if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_EncodeSignAlgInfo(&csr->signAlgId, &asnArr[1]); // 1 is signAlg if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Template csrTempl = { g_briefCsrTempl, sizeof(g_briefCsrTempl) / sizeof(g_briefCsrTempl[0]) }; ret = BSL_ASN1_EncodeTemplate(&csrTempl, asnArr, HITLS_X509_CSR_BRIEF_SIZE, &csr->rawData, &csr->rawDataLen); BSL_SAL_FREE(asnArr[1].buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } /** * @brief Encode ASN.1 csr * * @param csr [IN] Pointer to the csr structure * @param buff [OUT] Pointer to the buffer. * If NULL, only the ASN.1 csr is encoded. * If non-NULL, the DER encoding content of the csr is stored in buff * @return int32_t Return value, 0 means success, other values mean failure */ static int32_t X509EncodeAsn1Csr(HITLS_X509_Csr *csr, BSL_Buffer *buff) { int32_t ret; if ((csr->flag & HITLS_X509_CSR_GEN_FLAG) != 0) { if (csr->state != HITLS_X509_CSR_STATE_SIGN && csr->state != HITLS_X509_CSR_STATE_GEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CSR_NOT_SIGNED); return HITLS_X509_ERR_CSR_NOT_SIGNED; } if (csr->state == HITLS_X509_CSR_STATE_SIGN) { ret = X509EncodeAsn1CsrCore(csr); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } csr->state = HITLS_X509_CSR_STATE_GEN; } } if (csr->rawData == NULL || csr->rawDataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CSR_NOT_SIGNED); return HITLS_X509_ERR_CSR_NOT_SIGNED; } if (buff == NULL) { return HITLS_PKI_SUCCESS; } buff->data = BSL_SAL_Dump(csr->rawData, csr->rawDataLen); if (buff->data == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } buff->dataLen = csr->rawDataLen; return HITLS_PKI_SUCCESS; } #ifdef HITLS_BSL_PEM static int32_t X509EncodePemCsr(HITLS_X509_Csr *csr, BSL_Buffer *buff) { BSL_Buffer asn1 = {0}; int32_t ret = X509EncodeAsn1Csr(csr, &asn1); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer base64 = {0}; BSL_PEM_Symbol symbol = {BSL_PEM_CERT_REQ_BEGIN_STR, BSL_PEM_CERT_REQ_END_STR}; ret = BSL_PEM_EncodeAsn1ToPem(asn1.data, asn1.dataLen, &symbol, (char **)&base64.data, &base64.dataLen); BSL_SAL_FREE(asn1.data); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } buff->data = base64.data; buff->dataLen = base64.dataLen; return HITLS_PKI_SUCCESS; } #endif // HITLS_BSL_PEM int32_t HITLS_X509_CsrGenBuff(int32_t format, HITLS_X509_Csr *csr, BSL_Buffer *buff) { if (csr == NULL || buff == NULL || buff->data != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (format) { case BSL_FORMAT_ASN1: return X509EncodeAsn1Csr(csr, buff); #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: return X509EncodePemCsr(csr, buff); #endif // HITLS_BSL_PEM default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_FORMAT_UNSUPPORT); return HITLS_X509_ERR_FORMAT_UNSUPPORT; } } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_X509_CsrGenFile(int32_t format, HITLS_X509_Csr *csr, const char *path) { if (path == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } BSL_Buffer encode = { NULL, 0}; int32_t ret = HITLS_X509_CsrGenBuff(format, csr, &encode); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_SAL_WriteFile(path, encode.data, encode.dataLen); BSL_SAL_Free(encode.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_PKI_X509_CSR_GEN static int32_t X509GetAttr(HITLS_X509_Attrs *attrs, HITLS_X509_Attrs **val, uint32_t valLen) { if (val == NULL || valLen != sizeof(HITLS_X509_Attrs *)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *val = attrs; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CsrCtrl(HITLS_X509_Csr *csr, int32_t cmd, void *val, uint32_t valLen) { if (csr == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (((csr->flag & HITLS_X509_CSR_PARSE_FLAG) != 0) && cmd >= HITLS_X509_SET_VERSION && cmd < HITLS_X509_EXT_SET_SKI) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_AFTER_PARSE); return HITLS_X509_ERR_SET_AFTER_PARSE; } switch (cmd) { case HITLS_X509_REF_UP: return HITLS_X509_RefUp(&csr->references, val, valLen); #ifdef HITLS_PKI_X509_CSR_GEN case HITLS_X509_SET_PUBKEY: csr->flag |= HITLS_X509_CSR_GEN_FLAG; csr->state = HITLS_X509_CSR_STATE_SET; return HITLS_X509_SetPkey(&csr->reqInfo.ealPubKey, val); case HITLS_X509_ADD_SUBJECT_NAME: csr->flag |= HITLS_X509_CSR_GEN_FLAG; csr->state = HITLS_X509_CSR_STATE_SET; return HITLS_X509_AddDnName(csr->reqInfo.subjectName, (HITLS_X509_DN *)val, valLen); #ifdef HITLS_CRYPTO_SM2 case HITLS_X509_SET_VFY_SM2_USER_ID: if (csr->signAlgId.algId != BSL_CID_SM2DSA && csr->signAlgId.algId != BSL_CID_SM2DSAWITHSM3) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_SIGNALG_NOT_MATCH); return HITLS_X509_ERR_VFY_SIGNALG_NOT_MATCH; } return HITLS_X509_SetSm2UserId(&csr->signAlgId.sm2UserId, val, valLen); #endif #endif case HITLS_X509_GET_ENCODELEN: return HITLS_X509_GetEncodeLen(csr->rawDataLen, val, valLen); case HITLS_X509_GET_ENCODE: return HITLS_X509_GetEncodeData(csr->rawData, val); case HITLS_X509_GET_PUBKEY: return HITLS_X509_GetPubKey(csr->reqInfo.ealPubKey, val); case HITLS_X509_GET_SIGNALG: return HITLS_X509_GetSignAlg(csr->signAlgId.algId, (int32_t *)val, valLen); case HITLS_X509_GET_SUBJECT_DN: return HITLS_X509_GetList(csr->reqInfo.subjectName, val, valLen); case HITLS_X509_CSR_GET_ATTRIBUTES: return X509GetAttr(csr->reqInfo.attributes, val, valLen); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } int32_t HITLS_X509_CsrVerify(HITLS_X509_Csr *csr) { if (csr == NULL || csr->reqInfo.ealPubKey == NULL || csr->reqInfo.reqInfoRawData == NULL || csr->signature.buff == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t ret = HITLS_X509_CheckSignature((const CRYPT_EAL_PkeyCtx *)csr->reqInfo.ealPubKey, csr->reqInfo.reqInfoRawData, csr->reqInfo.reqInfoRawDataLen, &csr->signAlgId, &csr->signature); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #ifdef HITLS_PKI_X509_CSR_GEN int32_t CsrSignCb(int32_t mdId, CRYPT_EAL_PkeyCtx *prvKey, HITLS_X509_Asn1AlgId *signAlgId, HITLS_X509_Csr *csr) { BSL_ASN1_Buffer reqInfoAsn1 = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}; BSL_Buffer signBuff = {NULL, 0}; csr->signAlgId = *signAlgId; int32_t ret = CRYPT_EAL_PkeyPairCheck((CRYPT_EAL_PkeyCtx *)csr->reqInfo.ealPubKey, prvKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = EncodeCsrReqInfo(&csr->reqInfo, &reqInfoAsn1); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_SignAsn1Data(prvKey, mdId, &reqInfoAsn1, &signBuff, &csr->signature); BSL_SAL_Free(reqInfoAsn1.buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } csr->reqInfo.reqInfoRawData = signBuff.data; csr->reqInfo.reqInfoRawDataLen = signBuff.dataLen; csr->state = HITLS_X509_CSR_STATE_SIGN; return ret; } int32_t HITLS_X509_CsrSign(int32_t mdId, const CRYPT_EAL_PkeyCtx *prvKey, const HITLS_X509_SignAlgParam *algParam, HITLS_X509_Csr *csr) { if (csr == NULL || prvKey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((csr->flag & HITLS_X509_CSR_PARSE_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SIGN_AFTER_PARSE); return HITLS_X509_ERR_SIGN_AFTER_PARSE; } if (csr->state == HITLS_X509_CSR_STATE_SIGN || csr->state == HITLS_X509_CSR_STATE_GEN) { return HITLS_PKI_SUCCESS; } int32_t ret = CheckCsrValid(csr); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_SAL_FREE(csr->signature.buff); csr->signature.len = 0; BSL_SAL_FREE(csr->reqInfo.reqInfoRawData); csr->reqInfo.reqInfoRawDataLen = 0; BSL_SAL_FREE(csr->rawData); csr->rawDataLen = 0; #ifdef HITLS_CRYPTO_SM2 if (csr->signAlgId.algId == BSL_CID_SM2DSAWITHSM3) { BSL_SAL_FREE(csr->signAlgId.sm2UserId.data); csr->signAlgId.sm2UserId.dataLen = 0; } #endif return HITLS_X509_Sign(mdId, prvKey, algParam, csr, (HITLS_X509_SignCb)CsrSignCb); } #endif // HITLS_PKI_X509_CSR_GEN #endif // HITLS_PKI_X509_CSR
2301_79861745/bench_create
pki/x509_csr/src/hitls_x509_csr.c
C
unknown
26,575
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_X509_VERIFY_H #define HITLS_X509_VERIFY_H #include "hitls_build.h" #ifdef HITLS_PKI_X509_VFY #include <stdint.h> #include "bsl_asn1_internal.h" #include "bsl_list.h" #include "hitls_pki_x509.h" #include "sal_atomic.h" #ifdef __cplusplus extern "C" { #endif typedef enum { HITLS_X509_VFY_FLAG_SECBITS = 0x100000000, HITLS_X509_VFY_FLAG_TIME = 0x200000000, } HITLS_X509_IN_VerifyFlag; typedef struct _HITLS_X509_VerifyParam { int32_t maxDepth; int64_t time; uint32_t securityBits; uint64_t flags; #ifdef HITLS_CRYPTO_SM2 BSL_Buffer sm2UserId; #endif } HITLS_X509_VerifyParam; struct _HITLS_X509_StoreCtx { HITLS_X509_List *store; HITLS_X509_List *crl; BSL_SAL_RefCount references; HITLS_X509_VerifyParam verifyParam; BslList *caPaths; // List of CA directory paths for on-demand loading (char*) CRYPT_EAL_LibCtx *libCtx; // Provider context const char *attrName; // Provider attribute name }; int32_t HITLS_X509_VerifyParamAndExt(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain); /* * Verify the CRL, which is the default full certificate chain validation. * You can configure not to verify or only verify the terminal certificate */ int32_t HITLS_X509_VerifyCrl(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain); int32_t HITLS_X509_GetIssuerFromStore(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert, HITLS_X509_Cert **issuer); #ifdef __cplusplus } #endif #endif // HITLS_PKI_X509_VFY #endif // HITLS_X509_VERIFY_H
2301_79861745/bench_create
pki/x509_verify/include/hitls_x509_verify.h
C
unknown
2,094
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_X509_VFY #include <string.h> #include "securec.h" #include "hitls_pki_x509.h" #include "hitls_pki_cert.h" #include "bsl_types.h" #include "sal_atomic.h" #include "bsl_err_internal.h" #include "hitls_crl_local.h" #include "hitls_cert_local.h" #include "hitls_x509_local.h" #include "bsl_obj_internal.h" #include "hitls_pki_errno.h" #include "bsl_list.h" #include "bsl_list_internal.h" #include "hitls_x509_verify.h" #include "crypt_eal_md.h" #include "crypt_algid.h" #include "crypt_errno.h" #define CRYPT_SHA1_DIGESTSIZE 20 #define MAX_PATH_LEN 4096 typedef int32_t (*HITLS_X509_TrvListCallBack)(void *ctx, void *node); typedef int32_t (*HITLS_X509_TrvListWithParentCallBack)(void *ctx, void *node, void *parent); // lists can be cert, ext, and so on. static int32_t HITLS_X509_TrvList(BslList *list, HITLS_X509_TrvListCallBack callBack, void *ctx) { int32_t ret = HITLS_PKI_SUCCESS; void *node = BSL_LIST_GET_FIRST(list); while (node != NULL) { ret = callBack(ctx, node); if (ret != BSL_SUCCESS) { return ret; } node = BSL_LIST_GET_NEXT(list); } return ret; } // lists can be cert, ext, and so on. static int32_t HITLS_X509_TrvListWithParent(BslList *list, HITLS_X509_TrvListWithParentCallBack callBack, void *ctx) { int32_t ret = HITLS_PKI_SUCCESS; void *node = BSL_LIST_GET_FIRST(list); void *parentNode = BSL_LIST_GET_NEXT(list); while (node != NULL && parentNode != NULL) { ret = callBack(ctx, node, parentNode); if (ret != BSL_SUCCESS) { return ret; } node = parentNode; parentNode = BSL_LIST_GET_NEXT(list); } return ret; } #define HITLS_X509_MAX_DEPTH 20 void HITLS_X509_StoreCtxFree(HITLS_X509_StoreCtx *storeCtx) { if (storeCtx == NULL) { return; } int ret; (void)BSL_SAL_AtomicDownReferences(&storeCtx->references, &ret); if (ret > 0) { return; } #ifdef HITLS_CRYPTO_SM2 BSL_SAL_FREE(storeCtx->verifyParam.sm2UserId.data); #endif BSL_LIST_FREE(storeCtx->store, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); BSL_LIST_FREE(storeCtx->crl, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlFree); // Free CA paths list if (storeCtx->caPaths != NULL) { BSL_LIST_FREE(storeCtx->caPaths, (BSL_LIST_PFUNC_FREE)BSL_SAL_Free); } BSL_SAL_ReferencesFree(&storeCtx->references); BSL_SAL_Free(storeCtx); } static int32_t X509_CrlCmp(HITLS_X509_Crl *crlOri, HITLS_X509_Crl *crl) { if (crlOri == crl) { return 0; } if (HITLS_X509_CmpNameNode(crlOri->tbs.issuerName, crl->tbs.issuerName) != 0) { return 1; } if (crlOri->tbs.tbsRawDataLen != crl->tbs.tbsRawDataLen) { return 1; } return memcmp(crlOri->tbs.tbsRawData, crl->tbs.tbsRawData, crl->tbs.tbsRawDataLen); } static int32_t X509_CertCmp(HITLS_X509_Cert *certOri, HITLS_X509_Cert *cert) { if (certOri == cert) { return 0; } if (HITLS_X509_CmpNameNode(certOri->tbs.subjectName, cert->tbs.subjectName) != 0) { return 1; } if (certOri->tbs.tbsRawDataLen != cert->tbs.tbsRawDataLen) { return 1; } return memcmp(certOri->tbs.tbsRawData, cert->tbs.tbsRawData, cert->tbs.tbsRawDataLen); } HITLS_X509_StoreCtx *HITLS_X509_StoreCtxNew(void) { HITLS_X509_StoreCtx *ctx = (HITLS_X509_StoreCtx *)BSL_SAL_Malloc(sizeof(HITLS_X509_StoreCtx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } (void)memset_s(ctx, sizeof(HITLS_X509_StoreCtx), 0, sizeof(HITLS_X509_StoreCtx)); ctx->store = BSL_LIST_New(sizeof(HITLS_X509_Cert *)); if (ctx->store == NULL) { BSL_SAL_Free(ctx); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } ctx->crl = BSL_LIST_New(sizeof(HITLS_X509_Crl *)); if (ctx->crl == NULL) { BSL_SAL_FREE(ctx->store); BSL_SAL_Free(ctx); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } // Initialize CA paths list ctx->caPaths = BSL_LIST_New(sizeof(char *)); if (ctx->caPaths == NULL) { BSL_SAL_FREE(ctx->store); BSL_SAL_FREE(ctx->crl); BSL_SAL_Free(ctx); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } ctx->verifyParam.maxDepth = HITLS_X509_MAX_DEPTH; ctx->verifyParam.securityBits = 128; // 128: The default number of secure bits. BSL_SAL_ReferencesInit(&(ctx->references)); return ctx; } static int32_t X509_SetMaxDepth(HITLS_X509_StoreCtx *storeCtx, int32_t *val, uint32_t valLen) { if (valLen != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t depth = *val; if (depth > HITLS_X509_MAX_DEPTH) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } storeCtx->verifyParam.maxDepth = depth; return HITLS_PKI_SUCCESS; } static int32_t X509_GetMaxDepth(HITLS_X509_StoreCtx *storeCtx, int32_t *val, uint32_t valLen) { if (valLen != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *val = storeCtx->verifyParam.maxDepth; return HITLS_PKI_SUCCESS; } static int32_t X509_SetParamFlag(HITLS_X509_StoreCtx *storeCtx, uint64_t *val, uint32_t valLen) { if (valLen != sizeof(uint64_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } storeCtx->verifyParam.flags |= *val; return HITLS_PKI_SUCCESS; } static int32_t X509_GetParamFlag(HITLS_X509_StoreCtx *storeCtx, uint64_t *val, uint32_t valLen) { if (valLen != sizeof(uint64_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *val = storeCtx->verifyParam.flags; return HITLS_PKI_SUCCESS; } static int32_t X509_SetVerifyTime(HITLS_X509_StoreCtx *storeCtx, int64_t *val, uint32_t valLen) { if (valLen != sizeof(int64_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } storeCtx->verifyParam.time = *val; storeCtx->verifyParam.flags |= HITLS_X509_VFY_FLAG_TIME; return HITLS_PKI_SUCCESS; } static int32_t X509_SetVerifySecurityBits(HITLS_X509_StoreCtx *storeCtx, uint32_t *val, uint32_t valLen) { if (valLen != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } storeCtx->verifyParam.securityBits = *val; storeCtx->verifyParam.flags |= HITLS_X509_VFY_FLAG_SECBITS; return HITLS_PKI_SUCCESS; } static int32_t X509_ClearParamFlag(HITLS_X509_StoreCtx *storeCtx, uint64_t *val, uint32_t valLen) { if (valLen != sizeof(uint64_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } storeCtx->verifyParam.flags &= ~(*val); return HITLS_PKI_SUCCESS; } static int32_t X509_CheckCert(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert) { if (!HITLS_X509_CertIsCA(cert)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_NOT_CA); return HITLS_X509_ERR_CERT_NOT_CA; } HITLS_X509_List *certStore = storeCtx->store; HITLS_X509_Cert *tmp = BSL_LIST_SearchEx(certStore, cert, (BSL_LIST_PFUNC_CMP)X509_CertCmp); if (tmp != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_EXIST); return HITLS_X509_ERR_CERT_EXIST; } return HITLS_PKI_SUCCESS; } static int32_t X509_SetCA(HITLS_X509_StoreCtx *storeCtx, void *val, bool isCopy) { int32_t ret = X509_CheckCert(storeCtx, val); if (ret != HITLS_PKI_SUCCESS) { return ret; } if (isCopy) { int ref; ret = HITLS_X509_CertCtrl(val, HITLS_X509_REF_UP, &ref, sizeof(int)); if (ret != HITLS_PKI_SUCCESS) { return ret; } } ret = BSL_LIST_AddElement(storeCtx->store, val, BSL_LIST_POS_BEFORE); if (ret != HITLS_PKI_SUCCESS) { if (isCopy) { HITLS_X509_CertFree(val); } BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t X509_CheckCRL(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Crl *crl) { HITLS_X509_List *crlStore = storeCtx->crl; HITLS_X509_Crl *tmp = BSL_LIST_SearchEx(crlStore, crl, (BSL_LIST_PFUNC_CMP)X509_CrlCmp); if (tmp != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_EXIST); return HITLS_X509_ERR_CRL_EXIST; } return HITLS_PKI_SUCCESS; } static int32_t X509_SetCRL(HITLS_X509_StoreCtx *storeCtx, void *val) { int32_t ret = X509_CheckCRL(storeCtx, val); if (ret != HITLS_PKI_SUCCESS) { return ret; } int ref; ret = HITLS_X509_CrlCtrl(val, HITLS_X509_REF_UP, &ref, sizeof(int)); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = BSL_LIST_AddElement(storeCtx->crl, val, BSL_LIST_POS_BEFORE); if (ret != HITLS_PKI_SUCCESS) { HITLS_X509_CrlFree(val); BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t X509_AddCAPath(HITLS_X509_StoreCtx *storeCtx, const void *val, uint32_t valLen) { if (val == NULL || valLen == 0 || valLen > MAX_PATH_LEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } const char *caPath = (const char *)val; char *existPath = BSL_LIST_GET_FIRST(storeCtx->caPaths); while (existPath != NULL) { if (memcmp(existPath, caPath, valLen) == 0 && strlen(existPath) == valLen) { return HITLS_PKI_SUCCESS; } existPath = BSL_LIST_GET_NEXT(storeCtx->caPaths); } // Allocate and copy new path char *pathCopy = BSL_SAL_Calloc(valLen + 1, sizeof(char)); if (pathCopy == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } if (memcpy_s(pathCopy, valLen, caPath, valLen) != EOK) { BSL_SAL_Free(pathCopy); BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } // Add to paths list int32_t ret = BSL_LIST_AddElement(storeCtx->caPaths, pathCopy, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { BSL_SAL_Free(pathCopy); BSL_ERR_PUSH_ERROR(ret); return ret; } return HITLS_PKI_SUCCESS; } static int32_t X509_ClearCRL(HITLS_X509_StoreCtx *storeCtx) { if (storeCtx->crl == NULL) { return HITLS_PKI_SUCCESS; } BSL_LIST_DeleteAll(storeCtx->crl, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlFree); return HITLS_PKI_SUCCESS; } static int32_t X509_RefUp(HITLS_X509_StoreCtx *storeCtx, void *val, uint32_t valLen) { if (valLen != sizeof(int)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } return BSL_SAL_AtomicUpReferences(&storeCtx->references, val); } int32_t HITLS_X509_StoreCtxCtrl(HITLS_X509_StoreCtx *storeCtx, int32_t cmd, void *val, uint32_t valLen) { if (storeCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } // Allow val to be NULL only for specific commands like CLEAR_CRL if (val == NULL && cmd != HITLS_X509_STORECTX_CLEAR_CRL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (cmd) { case HITLS_X509_STORECTX_SET_PARAM_DEPTH: return X509_SetMaxDepth(storeCtx, val, valLen); case HITLS_X509_STORECTX_SET_PARAM_FLAGS: return X509_SetParamFlag(storeCtx, val, valLen); case HITLS_X509_STORECTX_SET_TIME: return X509_SetVerifyTime(storeCtx, val, valLen); case HITLS_X509_STORECTX_SET_SECBITS: return X509_SetVerifySecurityBits(storeCtx, val, valLen); case HITLS_X509_STORECTX_CLR_PARAM_FLAGS: return X509_ClearParamFlag(storeCtx, val, valLen); case HITLS_X509_STORECTX_DEEP_COPY_SET_CA: return X509_SetCA(storeCtx, val, true); case HITLS_X509_STORECTX_SHALLOW_COPY_SET_CA: return X509_SetCA(storeCtx, val, false); case HITLS_X509_STORECTX_SET_CRL: return X509_SetCRL(storeCtx, val); case HITLS_X509_STORECTX_CLEAR_CRL: return X509_ClearCRL(storeCtx); case HITLS_X509_STORECTX_REF_UP: return X509_RefUp(storeCtx, val, valLen); #ifdef HITLS_CRYPTO_SM2 case HITLS_X509_STORECTX_SET_VFY_SM2_USERID: return HITLS_X509_SetSm2UserId(&storeCtx->verifyParam.sm2UserId, val, valLen); #endif case HITLS_X509_STORECTX_GET_PARAM_DEPTH: return X509_GetMaxDepth(storeCtx, val, valLen); case HITLS_X509_STORECTX_GET_PARAM_FLAGS: return X509_GetParamFlag(storeCtx, val, valLen); case HITLS_X509_STORECTX_ADD_CA_PATH: return X509_AddCAPath(storeCtx, val, valLen); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } int32_t HITLS_X509_CheckTime(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_ValidTime *validTime) { int64_t start = 0; int64_t end = 0; if ((storeCtx->verifyParam.flags & HITLS_X509_VFY_FLAG_TIME) == 0) { return HITLS_PKI_SUCCESS; } int32_t ret = BSL_SAL_DateToUtcTimeConvert(&validTime->start, &start); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (start > storeCtx->verifyParam.time) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_TIME_FUTURE); return HITLS_X509_ERR_TIME_FUTURE; } if ((validTime->flag & BSL_TIME_AFTER_SET) == 0) { return HITLS_PKI_SUCCESS; } ret = BSL_SAL_DateToUtcTimeConvert(&validTime->end, &end); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (end < storeCtx->verifyParam.time) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_TIME_EXPIRED); return HITLS_X509_ERR_TIME_EXPIRED; } return HITLS_PKI_SUCCESS; } static int32_t X509_AddCertToChain(HITLS_X509_List *chain, HITLS_X509_Cert *cert) { int ref; int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_REF_UP, &ref, sizeof(int)); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = BSL_LIST_AddElement(chain, cert, BSL_LIST_POS_END); if (ret != HITLS_PKI_SUCCESS) { HITLS_X509_CertFree(cert); BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t X509_GetIssueFromChain(HITLS_X509_List *certChain, HITLS_X509_Cert *cert, HITLS_X509_Cert **issue) { int32_t ret; for (HITLS_X509_Cert *tmp = BSL_LIST_GET_FIRST(certChain); tmp != NULL; tmp = BSL_LIST_GET_NEXT(certChain)) { bool res = false; ret = HITLS_X509_CheckIssued(tmp, cert, &res); if (ret != HITLS_PKI_SUCCESS) { return ret; } if (!res) { continue; } *issue = tmp; return HITLS_PKI_SUCCESS; } BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); return HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND; } #ifdef HITLS_PKI_X509_VFY_LOCATION static int32_t CheckAndAddIssuerCert(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *candidateCert, HITLS_X509_Cert *cert, HITLS_X509_Cert **issue, bool *issueInTrust) { bool res = false; int32_t ret = HITLS_X509_CheckIssued(candidateCert, cert, &res); if (ret == HITLS_PKI_SUCCESS && res) { *issue = candidateCert; *issueInTrust = true; ret = X509_SetCA(storeCtx, candidateCert, false); if (ret == HITLS_PKI_SUCCESS) { return HITLS_PKI_SUCCESS; } } return HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND; } static int32_t HITLS_X509_GetCertBySubjectDer(HITLS_X509_StoreCtx *storeCtx, const BSL_ASN1_Buffer *subjectDerData, HITLS_X509_Cert *cert, HITLS_X509_Cert **issue, bool *issueInTrust) { // Only try on-demand loading from CA paths using hash-based lookup if (storeCtx->caPaths == NULL || BSL_LIST_COUNT(storeCtx->caPaths) <= 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); return HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND; } // Calculate hash from canon-encoded subject DN uint32_t hash = 0; uint8_t digest[CRYPT_SHA1_DIGESTSIZE]; uint32_t digestLen = CRYPT_SHA1_DIGESTSIZE; int32_t ret = HITLS_PKI_SUCCESS; CRYPT_EAL_MdCTX *mdCtx = CRYPT_EAL_ProviderMdNewCtx(storeCtx->libCtx, CRYPT_MD_SHA1, storeCtx->attrName); if (mdCtx != NULL) { if (CRYPT_EAL_MdInit(mdCtx) == CRYPT_SUCCESS && CRYPT_EAL_MdUpdate(mdCtx, subjectDerData->buff, subjectDerData->len) == CRYPT_SUCCESS) { if (CRYPT_EAL_MdFinal(mdCtx, digest, &digestLen) == CRYPT_SUCCESS && digestLen >= 4) { hash = (uint32_t)digest[0] | ((uint32_t)digest[1] << 8) | ((uint32_t)digest[2] << 16) | ((uint32_t)digest[3] << 24); } } CRYPT_EAL_MdFreeCtx(mdCtx); } if (hash == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); return HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND; } // Try to load certificate using hash-based file lookup from CA paths char *caPath = BSL_LIST_GET_FIRST(storeCtx->caPaths); while (caPath != NULL) { int32_t seq = 0; while (1) { char filename[MAX_PATH_LEN] = {0}; if (snprintf_s(filename, sizeof(filename), sizeof(filename) - 1, "%s/%08x.%d", caPath, hash, seq) < 0) { break; } HITLS_X509_Cert *candidateCert = NULL; ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, filename, &candidateCert); if (ret != HITLS_PKI_SUCCESS) { break; } if (CheckAndAddIssuerCert(storeCtx, candidateCert, cert, issue, issueInTrust) == HITLS_PKI_SUCCESS) { return HITLS_PKI_SUCCESS; } HITLS_X509_CertFree(candidateCert); seq++; } caPath = BSL_LIST_GET_NEXT(storeCtx->caPaths); } BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); return HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND; } static int32_t FindIssuerByDer(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert, HITLS_X509_Cert **issue, bool *issueInTrust) { BslList *rawIssuer = NULL; BSL_ASN1_Buffer issuerDerData = {0}; int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ISSUER_DN, &rawIssuer, sizeof(BslList *)); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = HITLS_X509_EncodeCanonNameList(rawIssuer, &issuerDerData); if (ret != HITLS_PKI_SUCCESS) { return ret; } if (issuerDerData.buff != NULL && issuerDerData.len > 0) { ret = HITLS_X509_GetCertBySubjectDer(storeCtx, &issuerDerData, cert, issue, issueInTrust); BSL_SAL_FREE(issuerDerData.buff); if (ret != HITLS_PKI_SUCCESS) { return ret; } } return HITLS_PKI_SUCCESS; } #endif int32_t X509_FindIssueCert(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *certChain, HITLS_X509_Cert *cert, HITLS_X509_Cert **issue, bool *issueInTrust) { // First try to find issuer in explicitly loaded store HITLS_X509_List *store = storeCtx->store; int32_t ret = X509_GetIssueFromChain(store, cert, issue); if (ret == HITLS_PKI_SUCCESS) { *issueInTrust = true; return ret; } // Then try the certificate chain if provided if (certChain != NULL) { ret = X509_GetIssueFromChain(certChain, cert, issue); if (ret == HITLS_PKI_SUCCESS) { *issueInTrust = false; return ret; } } #ifdef HITLS_PKI_X509_VFY_LOCATION // If we have CA paths set, try on-demand loading based on issuer DER-encoded DN if (BSL_LIST_COUNT(storeCtx->caPaths) > 0) { ret = FindIssuerByDer(storeCtx, cert, issue, issueInTrust); if (ret == HITLS_PKI_SUCCESS) { return HITLS_PKI_SUCCESS; } } #endif BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); return ret; } int32_t X509_BuildChain(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *certChain, HITLS_X509_Cert *cert, HITLS_X509_List *chain, HITLS_X509_Cert **root) { HITLS_X509_Cert *cur = cert; int32_t ret; while (cur != NULL) { HITLS_X509_Cert *issue = NULL; bool isTrustCa = false; ret = X509_FindIssueCert(storeCtx, certChain, cur, &issue, &isTrustCa); if (ret != HITLS_PKI_SUCCESS) { return ret; } // depth if (BSL_LIST_COUNT(chain) + 1 > storeCtx->verifyParam.maxDepth) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CHAIN_DEPTH_UP_LIMIT); return HITLS_X509_ERR_CHAIN_DEPTH_UP_LIMIT; } bool selfSigned = false; ret = HITLS_X509_CheckIssued(issue, issue, &selfSigned); if (ret != HITLS_PKI_SUCCESS) { return ret; } if (selfSigned) { if (root != NULL && isTrustCa) { *root = issue; } break; } ret = X509_AddCertToChain(chain, issue); if (ret != HITLS_PKI_SUCCESS) { return ret; } cur = issue; } return HITLS_PKI_SUCCESS; } static HITLS_X509_List *X509_NewCertChain(HITLS_X509_Cert *cert) { HITLS_X509_List *tmpChain = BSL_LIST_New(sizeof(HITLS_X509_Cert *)); if (tmpChain == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } int32_t ret = X509_AddCertToChain(tmpChain, cert); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(tmpChain); BSL_ERR_PUSH_ERROR(ret); return NULL; } return tmpChain; } static int32_t HITLS_X509_CertChainBuildWithRoot(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert, HITLS_X509_List **chain) { HITLS_X509_List *tmpChain = X509_NewCertChain(cert); if (tmpChain == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } HITLS_X509_Cert *root = NULL; int32_t ret = X509_BuildChain(storeCtx, NULL, cert, tmpChain, &root); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } if (root == NULL) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return HITLS_X509_ERR_ROOT_CERT_NOT_FOUND; } if (X509_CertCmp(cert, root) != 0) { ret = X509_AddCertToChain(tmpChain, root); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } } *chain = tmpChain; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CertChainBuild(HITLS_X509_StoreCtx *storeCtx, bool isWithRoot, HITLS_X509_Cert *cert, HITLS_X509_List **chain) { if (storeCtx == NULL || cert == NULL || chain == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (isWithRoot) { return HITLS_X509_CertChainBuildWithRoot(storeCtx, cert, chain); } HITLS_X509_List *tmpChain = X509_NewCertChain(cert); if (tmpChain == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } bool selfSigned = false; int32_t ret = HITLS_X509_CheckIssued(cert, cert, &selfSigned); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } if (selfSigned) { *chain = tmpChain; return HITLS_PKI_SUCCESS; } (void)X509_BuildChain(storeCtx, NULL, cert, tmpChain, NULL); *chain = tmpChain; return HITLS_PKI_SUCCESS; } static int32_t HITLS_X509_SecBitsCheck(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert) { uint32_t secBits = CRYPT_EAL_PkeyGetSecurityBits(cert->tbs.ealPubKey); if (secBits < storeCtx->verifyParam.securityBits) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_CHECK_SECBITS); return HITLS_X509_ERR_VFY_CHECK_SECBITS; } return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CheckVerifyParam(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain) { if ((storeCtx->verifyParam.flags & HITLS_X509_VFY_FLAG_SECBITS) != 0) { return HITLS_X509_TrvList(chain, (HITLS_X509_TrvListCallBack)HITLS_X509_SecBitsCheck, storeCtx); } return HITLS_PKI_SUCCESS; } static int32_t HITLS_X509_CheckCertExtNode(void *ctx, HITLS_X509_ExtEntry *extNode) { (void)ctx; if (extNode->cid != BSL_CID_CE_KEYUSAGE && extNode->cid != BSL_CID_CE_BASICCONSTRAINTS && extNode->critical == true) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PROCESS_CRITICALEXT); return HITLS_X509_ERR_PROCESS_CRITICALEXT; // not process critical ext } return HITLS_PKI_SUCCESS; } static int32_t HITLS_X509_CheckCertExt(void *ctx, HITLS_X509_Cert *cert) { (void) ctx; if (cert->tbs.version != 2) { // no ext v1 cert return HITLS_PKI_SUCCESS; } return HITLS_X509_TrvList(cert->tbs.ext.extList, (HITLS_X509_TrvListCallBack)HITLS_X509_CheckCertExtNode, NULL); } int32_t HITLS_X509_VerifyParamAndExt(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain) { int32_t ret = HITLS_X509_CheckVerifyParam(storeCtx, chain); if (ret != HITLS_PKI_SUCCESS) { return ret; } return HITLS_X509_TrvList(chain, (HITLS_X509_TrvListCallBack)HITLS_X509_CheckCertExt, NULL); } int32_t HITLS_X509_CheckCertRevoked(HITLS_X509_Cert *cert, HITLS_X509_CrlEntry *crlEntry) { if (cert->tbs.serialNum.tag == crlEntry->serialNumber.tag && cert->tbs.serialNum.len == crlEntry->serialNumber.len && memcmp(cert->tbs.serialNum.buff, crlEntry->serialNumber.buff, crlEntry->serialNumber.len) == 0) { return HITLS_X509_ERR_VFY_CERT_REVOKED; } return HITLS_PKI_SUCCESS; } static int32_t X509_StoreCheckSignature(const BSL_Buffer *sm2UserId, const CRYPT_EAL_PkeyCtx *pubKey, uint8_t *rawData, uint32_t rawDataLen, HITLS_X509_Asn1AlgId *alg, BSL_ASN1_BitString *signature) { #ifdef HITLS_CRYPTO_SM2 bool isHasUserId = true; if (alg->sm2UserId.data == NULL) { alg->sm2UserId = *sm2UserId; isHasUserId = false; } #else (void)sm2UserId; #endif int32_t ret = HITLS_X509_CheckSignature(pubKey, rawData, rawDataLen, alg, signature); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } #ifdef HITLS_CRYPTO_SM2 if (!isHasUserId) { alg->sm2UserId.data = NULL; alg->sm2UserId.dataLen = 0; } #endif return ret; } int32_t HITLS_X509_CheckCertCrl(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert, HITLS_X509_Cert *parent) { int32_t ret = HITLS_X509_ERR_CRL_NOT_FOUND; HITLS_X509_Crl *crl = BSL_LIST_GET_FIRST(storeCtx->crl); HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)parent->tbs.ext.extData; if ((certExt->extFlags & HITLS_X509_EXT_FLAG_KUSAGE) != 0) { if ((certExt->keyUsage & HITLS_X509_EXT_KU_CRL_SIGN) == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_KU_NO_CRLSIGN); return HITLS_X509_ERR_VFY_KU_NO_CRLSIGN; } } while (crl != NULL) { if (HITLS_X509_CmpNameNode(crl->tbs.issuerName, parent->tbs.subjectName) != 0) { crl = BSL_LIST_GET_NEXT(storeCtx->crl); continue; } if (cert->tbs.version == HITLS_X509_VERSION_3 && crl->tbs.version == 1) { if (HITLS_X509_CheckAki(&parent->tbs.ext, &crl->tbs.crlExt, parent->tbs.issuerName, &parent->tbs.serialNum) != HITLS_PKI_SUCCESS) { crl = BSL_LIST_GET_NEXT(storeCtx->crl); continue; } } if (HITLS_X509_CheckTime(storeCtx, &(crl->tbs.validTime)) != HITLS_PKI_SUCCESS) { crl = BSL_LIST_GET_NEXT(storeCtx->crl); continue; } ret = HITLS_X509_TrvList(crl->tbs.crlExt.extList, (HITLS_X509_TrvListCallBack)HITLS_X509_CheckCertExtNode, NULL); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } #ifdef HITLS_CRYPTO_SM2 ret = X509_StoreCheckSignature(&storeCtx->verifyParam.sm2UserId, parent->tbs.ealPubKey, crl->tbs.tbsRawData, crl->tbs.tbsRawDataLen, &(crl->signAlgId), &(crl->signature)); #else ret = X509_StoreCheckSignature(NULL, parent->tbs.ealPubKey, crl->tbs.tbsRawData, crl->tbs.tbsRawDataLen, &(crl->signAlgId), &(crl->signature)); #endif if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = HITLS_X509_TrvList(crl->tbs.revokedCerts, (HITLS_X509_TrvListCallBack)HITLS_X509_CheckCertRevoked, cert); if (ret != HITLS_PKI_SUCCESS) { return ret; } crl = BSL_LIST_GET_NEXT(storeCtx->crl); } return ret; } int32_t HITLS_X509_VerifyCrl(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain) { // Only the self-signed certificate, and the CRL is not verified if (BSL_LIST_COUNT(chain) == 1) { return HITLS_PKI_SUCCESS; } if ((storeCtx->verifyParam.flags & HITLS_X509_VFY_FLAG_CRL_ALL) != 0) { // Device certificate check is included return HITLS_X509_TrvListWithParent(chain, (HITLS_X509_TrvListWithParentCallBack)HITLS_X509_CheckCertCrl, storeCtx); } if ((storeCtx->verifyParam.flags & HITLS_X509_VFY_FLAG_CRL_DEV) != 0) { HITLS_X509_Cert *cert = BSL_LIST_GET_FIRST(chain); HITLS_X509_Cert *parent = BSL_LIST_GET_NEXT(chain); return HITLS_X509_CheckCertCrl(storeCtx, cert, parent); } return HITLS_PKI_SUCCESS; } int32_t X509_VerifyChainCert(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain) { HITLS_X509_Cert *issue = BSL_LIST_GET_LAST(chain); HITLS_X509_Cert *cur = issue; int32_t ret; while (cur != NULL) { if ((storeCtx->verifyParam.flags & HITLS_X509_VFY_FLAG_TIME) != 0) { ret = HITLS_X509_CheckTime(storeCtx, &cur->tbs.validTime); if (ret != HITLS_PKI_SUCCESS) { return ret; } } #ifdef HITLS_CRYPTO_SM2 ret = X509_StoreCheckSignature(&storeCtx->verifyParam.sm2UserId, issue->tbs.ealPubKey, cur->tbs.tbsRawData, cur->tbs.tbsRawDataLen, &cur->signAlgId, &cur->signature); #else ret = X509_StoreCheckSignature(NULL, issue->tbs.ealPubKey, cur->tbs.tbsRawData, cur->tbs.tbsRawDataLen, &cur->signAlgId, &cur->signature); #endif if (ret != HITLS_PKI_SUCCESS) { return ret; } issue = cur; cur = BSL_LIST_GET_PREV(chain); }; return HITLS_PKI_SUCCESS; } static int32_t X509_GetVerifyCertChain(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain, HITLS_X509_List **comChain) { HITLS_X509_Cert *cert = BSL_LIST_GET_FIRST(chain); if (cert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } HITLS_X509_List *tmpChain = X509_NewCertChain(cert); if (tmpChain == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } HITLS_X509_Cert *root = NULL; int32_t ret = X509_BuildChain(storeCtx, chain, cert, tmpChain, &root); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); BSL_ERR_PUSH_ERROR(ret); return ret; } if (root == NULL) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ROOT_CERT_NOT_FOUND); return HITLS_X509_ERR_ROOT_CERT_NOT_FOUND; } if (X509_CertCmp(cert, root) != 0) { ret = X509_AddCertToChain(tmpChain, root); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } } *comChain = tmpChain; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CertVerify(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain) { if (storeCtx == NULL || chain == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (BSL_LIST_COUNT(chain) <= 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_CHAIN_COUNT_IS0); return HITLS_X509_ERR_CERT_CHAIN_COUNT_IS0; } HITLS_X509_List *tmpChain = NULL; int32_t ret = X509_GetVerifyCertChain(storeCtx, chain, &tmpChain); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = HITLS_X509_VerifyParamAndExt(storeCtx, tmpChain); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } ret = HITLS_X509_VerifyCrl(storeCtx, tmpChain); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } ret = X509_VerifyChainCert(storeCtx, tmpChain); BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } HITLS_X509_StoreCtx *HITLS_X509_ProviderStoreCtxNew(HITLS_PKI_LibCtx *libCtx, const char *attrName) { HITLS_X509_StoreCtx *storeCtx = HITLS_X509_StoreCtxNew(); if (storeCtx == NULL) { return NULL; } storeCtx->libCtx = libCtx; storeCtx->attrName = attrName; return storeCtx; } #endif // HITLS_PKI_X509_VFY
2301_79861745/bench_create
pki/x509_verify/src/hitls_x509_verify.c
C
unknown
34,275
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. import sys sys.dont_write_bytecode = True import json import os import re sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__)))) from methods import trans2list, unique_list, save_json_file class Feature: def __init__(self, name, target, is_lib, parent, children, deps, opts, impl, ins_set): self.name = name self.target = target self.is_lib = is_lib # Indicates whether the target file is a lib or exe file. self.parent = parent self.children = children self.deps = deps self.opts = opts self.impl = impl # Implementation mode self.ins_set = ins_set # Instruction Set @classmethod def simple(cls, name, target, is_lib, parent, impl): return Feature(name, target, is_lib, parent, [], [], [], impl, []) class FeatureParser: """ Parsing feature files """ lib_dir_map = { "hitls_bsl": "bsl", "hitls_crypto": "crypto", "hitls_tls": "tls", "hitls_pki": "pki", "hitls_auth": "auth" } def __init__(self, file_path): self._fp = file_path with open(file_path, 'r', encoding='utf-8') as f: self._cfg = json.loads(f.read()) self._file_check() # Features and related information. self._feas_info = self._get_feas_info() # Assembly type supported by the openHiTLS. self._asm_types = self._get_asm_types() @property def libs(self): return self._cfg['libs'] @property def executes(self): return self._cfg['executes'] @property def modules(self): return self._cfg['modules'] @property def asm_types(self): return self._asm_types @property def feas_info(self): return self._feas_info def _file_check(self): if 'libs' not in self._cfg or 'modules' not in self._cfg: raise FileNotFoundError("The format of file %s is incorrect." % self._fp) @staticmethod def _add_key_value(obj, key, value): if value: obj[key] = value def _add_fea(self, feas_info, feature: Feature): fea_name = feature.name feas_info.setdefault(fea_name, {}) if feature.is_lib: self._add_key_value(feas_info[fea_name], 'lib', feature.target) else: self._add_key_value(feas_info[fea_name], 'execute', feature.target) self._add_key_value(feas_info[fea_name], 'parent', feature.parent) self._add_key_value(feas_info[fea_name], 'children', feature.children) self._add_key_value(feas_info[fea_name], 'opts', feature.opts) self._add_key_value(feas_info[fea_name], 'deps', feature.deps) feas_info[fea_name].setdefault('impl', {}) feas_info[fea_name]['impl'][feature.impl] = feature.ins_set if feature.ins_set else [] def _parse_fea_obj(self, name, target, is_lib, parent, impl, fea_obj, feas_info): feature = Feature.simple(name, target, is_lib, parent, impl) if not fea_obj: self._add_fea(feas_info, feature) return feature.deps = fea_obj.get('deps', None) feature.opts = fea_obj.get('opts', None) feature.ins_set = fea_obj.get('ins_set', None) non_sub_keys = ['opts', 'deps', 'ins_set', 'help'] for key, obj in fea_obj.items(): if key not in non_sub_keys: feature.children.append(key) self._parse_fea_obj(key, target, is_lib, name, impl, obj, feas_info) self._add_fea(feas_info, feature) def parse_fearuers(self, all_feas, tmp_feas_info, target, target_obj, is_lib): tmp_feas_info[target] = {} for impl, impl_obj in target_obj['features'].items(): for fea, fea_obj in impl_obj.items(): self._parse_fea_obj(fea, target, is_lib, None, impl, fea_obj, tmp_feas_info[target]) # Check that feature names in different target are unique. tgt_feas = set(tmp_feas_info[target].keys()) repeat_feas = all_feas.intersection(tgt_feas) if len(repeat_feas) != 0: raise ValueError("Error: feature '%s' has been defined in other target." % (repeat_feas)) all_feas.update(tgt_feas) def _get_feas_info(self): """ description: Parse the feature.json file to obtain feature information and check that feature names in different libraries are unique. return: feas_info: { "children":[], "parent":[], "deps":[], "opts":[[],[]], "lib":"", "execute":"" "impl":{"c":[], "armv8:[], ...}, # [] lists the instruction sets supported by the feature. } """ all_feas = set() tmp_feas_info = {} for lib, lib_obj in self._cfg['libs'].items(): self.parse_fearuers(all_feas, tmp_feas_info, lib, lib_obj, True) for exe, exe_obj in self._cfg['executes'].items(): self.parse_fearuers(all_feas, tmp_feas_info, exe, exe_obj, False) feas_info = {} for obj in tmp_feas_info.values(): feas_info.update(obj) self._fill_fea_modules(feas_info) self._correct_impl(feas_info) return feas_info def _fill_fea_modules(self, feas_info): for top_mod in self.modules: for mod, mod_obj in self.modules[top_mod].items(): formated_mod = "{}::{}".format(top_mod, mod) for fea in mod_obj.get('.features', []): if fea not in feas_info: raise ValueError("Unrecognized '%s' in '.features' of '%s::%s'" % (fea, top_mod, mod)) if 'modules' not in feas_info[fea]: feas_info[fea]['modules'] = [formated_mod] else: feas_info[fea]['modules'].append(formated_mod) @staticmethod def _correct_impl(feas_info): """Updated the implementation modes of sub-features based on the parent feature.""" for fea in feas_info.keys(): parent = feas_info[fea].get('parent', '') if not parent: continue if len(feas_info[fea]['impl'].keys()) == 1 and 'c' in feas_info[fea]['impl']: feas_info[fea]['impl'] = feas_info[parent]['impl'] def _get_asm_types(self): asm_type_set = set() [asm_type_set.update(self.libs[lib]['features'].keys()) for lib in self.libs.keys()] asm_type_set.discard('c') asm_type_set.add('no_asm') return asm_type_set def get_module_deps(self, module, dep_list, result): return self._get_module_deps(module, dep_list, result) def _get_module_deps(self, module, dep_list, result): """ Recursively obtains the modules on which the modules depend. module: [IN] module name, such as crypto::sha2 dep_list: [OUT] Dependency list, which is an intermediate variable result: [OUT] result """ top_module, sub_module = module.split('::') mod_obj = self.modules[top_module][sub_module] if '.deps' not in mod_obj: result.update(dep_list) return for dep_mod in mod_obj['.deps']: if dep_mod in dep_list: # A dependency that already exists in a dependency chain is a circular dependency. raise Exception("Cyclic dependency") dep_list.append(dep_mod) self._get_module_deps(dep_mod, dep_list, result) dep_list.pop() def get_mod_srcs(self, top_mod, sub_mod, mod_obj): srcs = self._cfg['modules'][top_mod][sub_mod]['.srcs'] asm_type = mod_obj.get('asmType', 'c') inc = mod_obj.get('incSet', '') blurred_srcs = [] if not isinstance(srcs, dict): blurred_srcs.extend(trans2list(srcs)) return blurred_srcs blurred_srcs.extend(trans2list(srcs.get('public', []))) if asm_type == 'c': blurred_srcs.extend(trans2list(srcs.get('no_asm', []))) return blurred_srcs if asm_type not in srcs: raise ValueError("Missing '.srcs[%s]' in modules '%s::%s'" % (asm_type, top_mod, sub_mod)) if not isinstance(srcs[asm_type], dict): blurred_srcs.extend(trans2list(srcs[asm_type])) return blurred_srcs if inc: blurred_srcs.extend(trans2list(srcs[asm_type][inc])) else: first_key = list(srcs[asm_type].keys())[0] blurred_srcs.extend(trans2list(srcs[asm_type][first_key])) return blurred_srcs class FeatureConfigParser: """ Parses the user feature configuration file. """ # Specifications of keys and values in the file. key_value = { "system": {"require": False, "type": str, "choices": ["linux", ""], "default": "linux"}, "bits": {"require": False, "type": int, "choices": [32, 64], "default": 64}, "endian": {"require": True, "type": str, "choices": ["little", "big"], "default": "little"}, "libType": { "require": True, "type": list, "choices": ["static", "shared", "object"], "default": ["static", "shared", "object"] }, "asmType":{"require": True, "type": str, "choices": [], "default": "no_asm"}, "libs":{"require": True, "type": dict, "choices": [], "default": {}}, "bundleLibs":{"require": False, "type": bool, "choices": [True, False], "default": False}, "securecLib":{"require": False, "type": str, "choices": ["boundscheck", "securec", "sec_shared.z", ""], "default": "boundscheck"}, "executes":{"require": False, "type": dict, "default": {}} } def __init__(self, features: FeatureParser, file_path): self._features = features self._config_file = file_path with open(file_path, 'r', encoding='utf-8') as f: self._cfg = json.loads(f.read()) self.key_value['asmType']['choices'] = list(features.asm_types) self.key_value['libs']['choices'] = list(features.libs) self._file_check() @classmethod def default_cfg(cls): config = {} for key in cls.key_value.keys(): if cls.key_value[key]["require"]: config[key] = cls.key_value[key]["default"] return config @property def libs(self): return self._cfg['libs'] @property def executes(self): return self._cfg.get('executes', {}) @property def lib_type(self): return trans2list(self._cfg['libType']) @property def asm_type(self): return self._cfg['asmType'] @property def bundle_libs(self): if 'bundleLibs' in self._cfg: return self._cfg['bundleLibs'] return self.key_value['bundleLibs']['default'] @property def securec_lib(self): if 'securecLib' in self._cfg: return self._cfg['securecLib'] return self.key_value['securecLib']['default'] @staticmethod def _get_fea_and_inc(asm_fea): if '::' in asm_fea: return asm_fea.split('::') else: return asm_fea, '' def enable_executes(self, targets): for target in targets: if 'executes' not in self._cfg: self._cfg['executes'] = {target: {}} else: self._cfg['executes'][target] = {} exe_objs = [] for fea, fea_obj in self._features.feas_info.items(): if fea_obj.get('execute', '') != target: continue for i in fea_obj['impl'].keys(): self._cfg['executes'][target].setdefault(i, []) self._cfg['executes'][target][i].append(fea) def _asm_fea_check(self, asm_fea, asm_type, info): fea, inc = self._get_fea_and_inc(asm_fea) feas_info = self._features.feas_info if fea not in feas_info: raise ValueError("Unsupported '%s' in %s" % (fea, info)) if asm_type not in feas_info[fea]['impl']: raise ValueError("Feature '%s' has no assembly implementation of type '%s' in %s" % (fea, asm_type, info)) if inc: if inc not in feas_info[fea]['impl'] and inc not in feas_info[fea]['impl'][asm_type]: raise ValueError("Unsupported instruction set of '%s' in %s" % (asm_fea, info)) return fea, inc def _file_check(self): for key, value in self.key_value.items(): if value['require']: if key not in self._cfg.keys(): raise ValueError("Error feature_config file: missing '%s'" % key) for key, value in self._cfg.items(): if key not in self.key_value.keys(): raise ValueError("Error feature_config file: unsupported config '%s'" % key) if not isinstance(value, self.key_value.get(key).get("type")): raise ValueError("Error feature_config file: wrong type of '%s'" % key) value_type = type(value) if value_type == str or value_type == str: if value not in self.key_value.get(key).get("choices"): if key == "system": print("Info: There is no {} implementation by default, you should set its SAL callbacks to make it work.".format(value)) continue raise ValueError("Error feature_config file: wrong value of '%s'" % key) elif value_type == list: choices = set(self.key_value[key]["choices"]) if not set(value).issubset(choices): raise ValueError("Error feature_config file: wrong value of '%s'" % key) for lib, lib_obj in self._cfg['libs'].items(): if lib not in self._features.libs: raise ValueError("Error feature_config file: unsupported lib '%s'" % lib) for fea in lib_obj.get('c', []): if fea not in self._features.feas_info: raise ValueError("Error feature_config file: unsupported fea '%s' in lib '%s'" % (fea, lib)) asm_feas = [] for asm_fea in lib_obj.get('asm', []): fea, _ = self._asm_fea_check(asm_fea, self.asm_type, 'feature_config file') if fea in asm_feas: raise ValueError("Error feature_config file: duplicate assembly feature '%s'" % fea) asm_feas.append(fea) def set_param(self, key, value, set_default=True): if key == 'bundleLibs': self._cfg[key] = value return if value: self._cfg[key] = value return if not set_default: return if key not in self._cfg or not self._cfg[key]: print("Warning: Configuration item '{}' is missing and has been set to the default value '{}'.".format( key, self.key_value.get(key).get('default'))) self._cfg[key] = self.key_value.get(key).get('default') def _get_related_feas(self, fea, feas_info, related: set): related.add(fea) if 'parent' in feas_info[fea]: parent = feas_info[fea]['parent'] for dep in feas_info[parent].get('deps', []): self._get_related_feas(dep, feas_info, related) if 'children' in feas_info[fea]: for child in feas_info[fea]['children']: self._get_related_feas(child, feas_info, related) if 'deps' in feas_info[fea]: for dep in feas_info[fea]['deps']: self._get_related_feas(dep, feas_info, related) def _get_parents(self, disables): parents = set() for d in disables: relation = self._features.feas_info.get(d) if relation and 'parent' in relation: parents.add(relation['parent']) return parents def _add_depend_feas(self, enable_feas, feas_info): related = set() for f in enable_feas: fea, inc = self._get_fea_and_inc(f) self._get_related_feas(fea, feas_info, related) enable_feas.update(related) def _check_asm_fea_enable(self, enable_feas, feas, feas_info): not_in_enable = [] for f in feas: fea, _ = self._get_fea_and_inc(f) if fea in enable_feas: # This feature is already in the enable list. continue rel = feas_info[fea] is_enable = False while('parent' in rel): parent = rel['parent'] if parent in enable_feas: # This feature is already in the enable list. is_enable = True break rel = feas_info[parent] if not is_enable: not_in_enable.append(fea) if not_in_enable: raise ValueError("To add '%s' assembly requires add it to 'enable' list" % not_in_enable) def get_enable_feas(self, arg_enable, arg_asm): """ Get the enabled features form: 1. build/feature_config.json 2. argument: enable list 3. argument: asm list """ enable_feas = set() enable_asm_feas = set() # 1. Exist feas in build/feature_config.json for _, lib_obj in self._cfg['libs'].items(): enable_feas.update(lib_obj.get('c', [])) enable_asm_feas.update(lib_obj.get('asm', [])) # 2. Obtains the properties from the input parameter: enable list. feas_info = self._features.feas_info if 'all' in arg_enable: # all features enable_feas.update(set(x for x in feas_info.keys())) else: for enable in arg_enable: if enable in self._features.libs: # features in a lib enable_feas.update(set(x for x, y in feas_info.items() if enable == y.get('lib', ''))) else: # The feature is not lib and needs to be added separately. enable_feas.add(enable) enable_feas.update(enable_asm_feas) self._add_depend_feas(enable_feas, feas_info) self._check_asm_fea_enable(enable_feas, arg_asm, feas_info) enable_asm_feas.update(arg_asm) return enable_feas, enable_asm_feas def _add_feature(self, fea, impl_type, inc=''): add_fea = fea if inc == '' else '{}::{}'.format(fea, inc) lib = self._features.feas_info[fea]['lib'] if lib not in self._cfg['libs']: self._cfg['libs'][lib] = {impl_type: [add_fea]} elif impl_type not in self._cfg['libs'][lib]: self._cfg['libs'][lib][impl_type] = [add_fea] elif fea not in self._cfg['libs'][lib][impl_type]: self._cfg['libs'][lib][impl_type].append(add_fea) def set_asm_type(self, asm_type): if self._cfg['asmType'] == 'no_asm': self._cfg['asmType'] = asm_type elif self._cfg['asmType'] != asm_type: raise ValueError('Error asmType: %s is different from feature_config file.' % (asm_type)) def set_asm_features(self, enable_feas, asm_feas, asm_type): feas_info = self._features.feas_info # Clear the assembly features first. for lib in self._cfg['libs']: if 'asm' in self._cfg['libs'][lib]: self._cfg['libs'][lib]['asm'] = [] # Add assembly features. if asm_feas: for asm_feature in asm_feas: fea, inc = self._asm_fea_check(asm_feature, asm_type, 'input asm list') if inc and inc != asm_type: raise ValueError("Input instruction '%s' is not the same as 'asm_type' '%s'" % (inc, asm_type)) self._add_feature(fea, 'asm', inc) else: for fea in enable_feas: if asm_type not in feas_info[fea]['impl']: continue self._add_feature(fea, 'asm') def set_c_features(self, enable_feas): for f in enable_feas: fea, _ = self._get_fea_and_inc(f) if self._features.feas_info[fea].get('execute'): continue if 'c' in self._features.feas_info[fea]['impl']: self._add_feature(fea, 'c') def _update_enable_feature(self, features, disables): """ The sub-feature macro is derived from the parent feature macro in the code. Therefore, the sub-feature is removed and the parent feature is retained. """ disable_parents = self._get_parents(disables) tmp_feas = features.copy() enable_set = set() feas_info = self._features.feas_info for f in tmp_feas: fea, _ = self._get_fea_and_inc(f) rel = feas_info[fea] if fea in disable_parents: if 'children' in rel: enable_set.update(rel['children']) enable_set.discard(fea) else: is_fea_contained = False while 'parent' in rel: if rel['parent'] in disables: raise Exception("The 'disables' features {} and 'enables' featrues {} conflict".format(fea, disables)) if rel['parent'] in features: is_fea_contained = True break rel = feas_info[rel['parent']] if not is_fea_contained: enable_set.add(fea) enable_set.difference_update(set(disables)) return list(enable_set) def check_bn_config(self): lib = 'hitls_crypto' if lib not in self._cfg['libs']: return has_bn = False bn_pattern = "bn_" for impl_type in self._cfg['libs'][lib]: if 'bn' in self._cfg['libs'][lib][impl_type]: has_bn = True break for fea in self._cfg['libs'][lib][impl_type]: if re.match(bn_pattern, fea) : has_bn = True break if has_bn and 'bits' not in self._cfg: raise ValueError("If 'bn' is used, the 'bits' of the system must be configured.") def _re_sort_lib(self): # Change the key sequence of the 'libs' dictionary. Otherwise, the compilation fails. lib_sort = ['hitls_bsl', 'hitls_crypto', 'hitls_tls', "hitls_pki", "hitls_auth"] libs = self.libs.copy() self._cfg['libs'].clear() for lib in lib_sort: if lib in libs: self._cfg['libs'][lib] = libs[lib].copy() def update_feature(self, enables, disables, gen_cmake): ''' update feature: 1. Add the default lib and features: hitls_bsl: sal 2. Delete features based on the relationship between features. ''' libs = self._cfg['libs'] if len(libs) == 0: if gen_cmake: raise ValueError("No features are enabled.") else: return libs.setdefault('hitls_bsl', {'c':['sal']}) if 'hitls_bsl' not in libs: libs['hitls_bsl'] = {'c':['sal']} elif 'c' not in libs['hitls_bsl']: libs['hitls_bsl']['c'] = ['sal'] elif 'sal' not in libs['hitls_bsl']['c']: libs['hitls_bsl']['c'].append('sal') for lib in libs: if 'c' in libs[lib]: libs[lib]['c'] = self._update_enable_feature(libs[lib]['c'], disables) libs[lib]['c'].sort() if 'asm' in libs[lib]: libs[lib]['asm'] = self._update_enable_feature(libs[lib]['asm'], disables) libs[lib]['asm'].sort() self._re_sort_lib() if 'all' in enables: self.set_param('system', None) self.set_param('bits', None) def save(self, path): save_json_file(self._cfg, path) def get_fea_macros(self): macros = set() for lib, lib_value in self.libs.items(): lib_upper = lib.upper() for fea in lib_value.get('c', []): macros.add("-D%s_%s" % (lib_upper, fea.upper())) for fea in lib_value.get('asm', []): fea = fea.split('::')[0] macros.add("-D%s_%s" % (lib_upper, fea.upper())) if 'bn' in fea: macros.add("-D%s_%s_%s" % (lib_upper, 'BN', self.asm_type.upper())) else: macros.add("-D%s_%s_%s" % (lib_upper, fea.upper(), self.asm_type.upper())) if lib_upper not in macros: macros.add("-D%s" % lib_upper) if self._cfg['endian'] == 'big': macros.add("-DHITLS_BIG_ENDIAN") if self._cfg.get('system', "") == "linux": macros.add("-DHITLS_BSL_SAL_LINUX") bits = self._cfg.get('bits', 0) if bits == 32: macros.add("-DHITLS_THIRTY_TWO_BITS") elif bits == 64: macros.add("-DHITLS_SIXTY_FOUR_BITS") return list(macros) def _re_get_fea_modules(self, fea, feas_info, asm_type, inc, modules): """Obtain the modules on which the current feature and subfeature depend.""" for mod in feas_info[fea].get('modules', []): modules.setdefault(mod, {}) modules[mod]["asmType"] = asm_type if inc: modules[mod]["incSet"] = inc for child in feas_info[fea].get('children', []): self._re_get_fea_modules(child, feas_info, asm_type, inc, modules) def _get_target_modules(self, target, is_lib): modules = {} feas_info = self._features.feas_info obj = self.libs if is_lib else self.executes for fea in obj[target].get('c', []): self._re_get_fea_modules(fea, feas_info, 'c', '', modules) for asm_fea in obj[target].get('asm', []): fea, inc = self._get_fea_and_inc(asm_fea) self._re_get_fea_modules(fea, feas_info, self.asm_type, inc, modules) for mod in modules: mod_dep_mods = set() self._features.get_module_deps(mod, [], mod_dep_mods) modules[mod]['deps'] = list(mod_dep_mods) if len(modules.keys()) == 0: raise ValueError("Error: no module is enabled in %s" % target) return modules def get_enable_modules(self): """ Obtain the modules required for compiling each lib features and the modules on which the lib feature depends (for obtaining the include directory). 1. Add modules and their dependent modules based on features. 2. Check whether the dependent modules are enabled. return: {'lib/exe':{"mod1":{"deps":[], "asmType":"", "incSet":""}}} Module format: top_dir::sub_dir """ enable_libs_mods = {} enable_exes_mods = {} enable_mods = set() for lib in self.libs.keys(): enable_libs_mods[lib] = self._get_target_modules(lib, True) enable_mods.update(enable_libs_mods[lib]) for exe in self.executes.keys(): enable_exes_mods[exe] = self._get_target_modules(exe, False) enable_mods.update(enable_exes_mods[exe]) # Check whether the dependent module is enabled. for lib in enable_libs_mods.keys(): for mod in enable_libs_mods[lib]: for dep_mod in enable_libs_mods[lib][mod].get('deps', []): if dep_mod == "platform::Secure_C": continue if dep_mod not in enable_mods: raise ValueError("Error: '%s' depends on '%s', but '%s' is disabled." % (mod, dep_mod, dep_mod)) for exe in enable_exes_mods.keys(): for mod in enable_exes_mods[exe]: for dep_mod in enable_exes_mods[exe][mod].get('deps', []): if dep_mod == "platform::Secure_C": continue if dep_mod not in enable_mods: raise ValueError("Error: '%s' depends on '%s', but '%s' is disabled." % (mod, dep_mod, dep_mod)) return enable_libs_mods, enable_exes_mods def filter_no_asm_config(self): self._cfg['asmType'] = 'no_asm' for lib in self._cfg['libs']: if 'asm' in self._cfg['libs'][lib]: self._cfg['libs'][lib]['asm'] = [] def _check_fea_opts_arr(self, opts, fea, enable_feas): for opt_arr in opts: has_opt = False for opt_fea in opt_arr: if opt_fea in enable_feas: has_opt = True break parent = self._features.feas_info[opt_fea].get('parent', '') while parent: if parent in enable_feas: has_opt = True break parent = self._features.feas_info[parent].get('parent', '') if has_opt: break if not has_opt: raise ValueError("At leaset one fea in %s must be enabled for '%s*'" % (opt_arr, fea)) def _check_opts(self, fea, enable_feas): if 'opts' not in self._features.feas_info[fea]: return opts = self._features.feas_info[fea]['opts'] if not isinstance(opts[0], list): opts = [opts] self._check_fea_opts_arr(opts, fea, enable_feas) def _check_family_opts(self, fea, key, enable_feas): values = self._features.feas_info[fea].get(key, []) if not isinstance(values, list): values = [values] for value in values: self._check_opts(value, enable_feas) self._check_family_opts(value, key, enable_feas) def check_fea_opts(self): enable_feas = set() for _, lib_obj in self.libs.items(): enable_feas.update(lib_obj.get('c', [])) enable_feas.update(lib_obj.get('asm', [])) for fea in enable_feas: fea = fea.split("::")[0] self._check_opts(fea, enable_feas) self._check_family_opts(fea, 'parent', enable_feas) self._check_family_opts(fea, 'children', enable_feas) class CompleteOptionParser: """ Parses all compilation options. """ # Sequence in which compilation options are added, including all compilation option types. option_order = [ "CC_DEBUG_FLAGS", "CC_OPT_LEVEL", # Optimization Level "CC_OVERALL_FLAGS", # Overall Options "CC_WARN_FLAGS", # Warning options "CC_LANGUAGE_FLAGS", # Language Options "CC_CDG_FLAGS", # Code Generation Options "CC_MD_DEPENDENT_FLAGS", # Machine-Dependent Options "CC_OPT_FLAGS", # Optimization Options "CC_SEC_FLAGS", # Secure compilation options "CC_DEFINE_FLAGS", # Custom Macro "CC_USER_DEFINE_FLAGS", # User-defined compilation options are reserved. ] def __init__(self, file_path): self._fp = file_path with open(file_path, 'r') as f: self._cfg = json.loads(f.read()) self._file_check() self._option_type_map = {} for option_type in self._cfg['compileFlag']: for option in trans2list(self._cfg['compileFlag'][option_type]): self._option_type_map[option] = option_type @property def option_type_map(self): return self._option_type_map @property def type_options_map(self): return self._cfg['compileFlag'] def _file_check(self): if 'compileFlag' not in self._cfg or 'linkFlag' not in self._cfg: raise FileNotFoundError("The format of file %s is incorrect." % self._fp) for option_type in self._cfg['compileFlag']: if option_type not in self.option_order: raise FileNotFoundError("The format of file %s is incorrect." % self._fp) class CompileConfigParser: """ Parse the user compilation configuration file. """ def __init__(self, all_options: CompleteOptionParser, file_path=''): with open(file_path, 'r') as f: self._cfg = json.loads(f.read()) self._all_options = all_options @property def options(self): return self._cfg['compileFlag'] @property def link_flags(self): return self._cfg['linkFlag'] @classmethod def default_cfg(cls): config = { 'compileFlag': {}, 'linkFlag': {} } return config def save(self, path): save_json_file(self._cfg, path) def change_options(self, options, is_add): option_op = 'CC_FLAGS_ADD' if is_add else 'CC_FLAGS_DEL' for option in options: option_type = 'CC_USER_DEFINE_FLAGS' if option in self._all_options.option_type_map: option_type = self._all_options.option_type_map[option] if option_type not in self._cfg['compileFlag']: self._cfg['compileFlag'][option_type] = {} flags = self._cfg['compileFlag'][option_type] flags[option_op] = unique_list(flags.get(option_op, []) + [option]) def change_link_flags(self, flags, is_add): link_op = 'LINK_FLAG_ADD' if is_add else 'LINK_FLAG_DEL' new_flags = self._cfg['linkFlag'].get(link_op, []) + flags self._cfg['linkFlag'][link_op] = unique_list(new_flags) def add_debug_options(self): flags_add = {'CC_FLAGS_ADD': ['-g3', '-gdwarf-2']} flags_del = {'CC_FLAGS_DEL': ['-O2', '-D_FORTIFY_SOURCE=2']} self._cfg['compileFlag']['CC_DEBUG_FLAGS'] = flags_add self._cfg['compileFlag']['CC_OPT_LEVEL'] = flags_del def filter_hitls_defines(self): for flag in list(self.link_flags.keys()): del self.link_flags[flag] for flag in list(self.options.keys()): if flag != 'CC_USER_DEFINE_FLAGS' and flag != 'CC_DEFINE_FLAGS': del self.options[flag] class CompileParser: """ Parse the compile.json file. json key and value: compileFlag: compilation options linkFlag: link option """ def __init__(self, all_options: CompleteOptionParser, file_path): self._fp = file_path self._all_options = all_options with open(file_path, 'r') as f: self._cfg = json.loads(f.read()) self._file_check() @property def options(self): return self._cfg["compileFlag"] @property def link_flags(self): return self._cfg["linkFlag"] def _file_check(self): if 'compileFlag' not in self._cfg or 'linkFlag' not in self._cfg: raise FileNotFoundError("Error compile file: missing 'compileFlag' or 'linkFlag'") for option_type in self.options: if option_type == 'CC_USER_DEFINE_FLAGS': continue if option_type not in self._all_options.type_options_map: raise ValueError("no '{}' option type in complete_options.json".format(option_type)) for option in self.options[option_type]: if option not in self._all_options.type_options_map[option_type]: raise ValueError("unrecognized option '{}' in type {}.".format(option, option_type)) for option_type in self._cfg['linkFlag']: if option_type not in ['PUBLIC', 'SHARED', 'EXE']: raise FileNotFoundError('Incorrect file format: %s' % self._fp) def union_options(self, custom_cfg: CompileConfigParser): options = [] for option_type in CompleteOptionParser.option_order: options.extend(self.options.get(option_type, [])) if option_type not in custom_cfg.options: continue for option in custom_cfg.options[option_type].get('CC_FLAGS_ADD', []): if option not in options: options.append(option) for option in custom_cfg.options[option_type].get('CC_FLAGS_DEL', []): if option in options: options.remove(option) flags = self.link_flags for flag in custom_cfg.link_flags.get('LINK_FLAG_ADD', []): if flag not in flags['PUBLIC']: flags['PUBLIC'].append(flag) if flag not in flags['EXE']: flags['EXE'].append(flag) if flag not in flags['SHARED']: flags['SHARED'].append(flag) for flag in custom_cfg.link_flags.get('LINK_FLAG_DEL', []): if flag in flags['PUBLIC']: flags['PUBLIC'].remove(flag) if flag in flags['EXE']: flags['EXE'].remove(flag) if flag in flags['SHARED']: flags['SHARED'].remove(flag) return options, flags
2301_79861745/bench_create
script/config_parser.py
Python
unknown
37,566
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. import shutil import sys sys.dont_write_bytecode = True import os import json # Convert x to list def trans2list(x): if x == None: return [] if type(x) == list: return x if type(x) == set: return x if type(x) == str: return [x] raise ValueError('Unsupported type: "%s"' % type(x)) def unique_list(x): """ Deduplicate the list. """ return list(dict.fromkeys(x)) def copy_file(src_file, dest_file, isCoverd=True): if not os.path.exists(src_file): raise FileNotFoundError('Src file not found: ' + src_file) if os.path.exists(dest_file): if isCoverd: shutil.copy2(src_file, dest_file) else: shutil.copy2(src_file, dest_file) def save_json_file(content, path): with open(path, 'w') as f: f.write(json.dumps(content, indent=4))
2301_79861745/bench_create
script/methods.py
Python
unknown
1,386
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. cmake_minimum_required(VERSION 3.16 FATAL_ERROR) PROJECT(openHiTLS_TEST) set(openHiTLS_SRC "${PROJECT_SOURCE_DIR}/..") if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64") option(__x86_64__ "x86" ON) endif() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -Werror -Wformat=2 -Wno-format-nonliteral -Wno-deprecated-declarations -Wno-unused-but-set-variable -Wl,--wrap=REC_Read -Wl,--wrap=REC_Write") message(STATUS "System processor :${CMAKE_SYSTEM_PROCESSOR}") message(STATUS "Enable bsl uio sctp :${ENABLE_UIO_SCTP}") if(CMAKE_SIZEOF_VOID_P EQUAL 8) message(STATUS "System architecture: 64") else() message(STATUS "System architecture: 32") endif() if(ENABLE_GCOV) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage -lgcov") endif() if(ENABLE_ASAN) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address -fno-stack-protector -fno-omit-frame-pointer") endif() if(CUSTOM_CFLAGS) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CUSTOM_CFLAGS}") endif() if(DEBUG) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -g") endif() if(PRINT_TO_TERMINAL) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DPRINT_TO_TERMINAL=${PRINT_TO_TERMINAL}") endif() if(ENABLE_FAIL_REPEAT) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DENABLE_FAIL_REPEAT=${ENABLE_FAIL_REPEAT}") endif() if(OS_BIG_ENDIAN) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mbig-endian") endif() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_FILE_OFFSET_BITS=64") string(FIND "${CUSTOM_CFLAGS}" "-DHITLS_PKI" BUILD_PKI) string(FIND "${CUSTOM_CFLAGS}" "-DHITLS_AUTH" BUILD_AUTH) string(FIND "${CUSTOM_CFLAGS}" "-DHITLS_CRYPTO" BUILD_CRYPTO) string(FIND "${CUSTOM_CFLAGS}" "-DHITLS_TLS" BUILD_TLS) include(ExternalProject) ExternalProject_Add(gen_testcase SOURCE_DIR ${openHiTLS_SRC} PREFIX "" BINARY_DIR ${openHiTLS_SRC}/testcode/framework/gen_test/build/ INSTALL_DIR "" UPDATE_COMMAND "" CONFIGURE_COMMAND cmake -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS} -DPRINT_TO_TERMINAL=${ENABLE_PRINT} .. BUILD_COMMAND make INSTALL_COMMAND "" BUILD_ALWAYS FALSE LOG_BUILD TRUE LOG_DOWNLOAD TRUE EXCLUDE_FROM_ALL TRUE LOG_OUTPUT_ON_FAILURE TRUE ) add_subdirectory(${openHiTLS_SRC}/testcode/sdv) if(ENABLE_TLS AND ${BUILD_TLS} GREATER -1) add_subdirectory(${openHiTLS_SRC}/testcode/framework/tls) add_subdirectory(${openHiTLS_SRC}/testcode/framework/process) add_dependencies(gen_testcase process) endif()
2301_79861745/bench_create
testcode/CMakeLists.txt
CMake
unknown
3,043
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t X25519SetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)paraId; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen curve25519 key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void X25519TearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t X25519KeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "X25519 keyGen"); return rc; } static int32_t Ed25519SetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { return X25519SetUp(ctx, bench, ops, paraId); } static void Ed25519TearDown(void *ctx) { X25519TearDown(ctx); } static int32_t Ed25519KeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "Ed25519 keyGen"); return rc; } static int32_t X25519KeyDerive(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; CRYPT_EAL_PkeyCtx *peerCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_X25519); if (peerCtx == NULL) { printf("Failed to create peer context\n"); return CRYPT_MEM_ALLOC_FAIL; } rc = CRYPT_EAL_PkeyGen(peerCtx); if (rc != CRYPT_SUCCESS) { printf("Failed to gen peer key.\n"); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } uint8_t sharedKey[32]; uint32_t sharedKeyLen = sizeof(sharedKey); BENCH_TIMES(CRYPT_EAL_PkeyComputeShareKey(ctx, peerCtx, sharedKey, &sharedKeyLen), rc, CRYPT_SUCCESS, -1, opts->times, "X25519 keyDerive"); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { if (opts->hashId != CRYPT_MD_SHA512) { printf("Wrong Hash Algorithm Id for Ed25519. Must be SHA512."); return -1; } hashId = opts->hashId; } return hashId; } static int32_t Ed25519SignInner(void *ctx, int32_t hashId) { uint8_t plainText[32]; uint8_t signature[64]; uint32_t signatureLen = sizeof(signature); return CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); } static int32_t Ed25519Sign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } BENCH_TIMES(Ed25519SignInner(ctx, hashId), rc, CRYPT_SUCCESS, -1, opts->times, "ed25519 sign"); return rc; } static int32_t Ed25519Verify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } uint8_t plainText[32]; uint8_t signature[64]; uint32_t signatureLen = sizeof(signature); rc = CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } BENCH_TIMES(CRYPT_EAL_PkeyVerify(ctx, hashId, plainText, sizeof(plainText), signature, signatureLen), rc, CRYPT_SUCCESS, -1, opts->times, "ed25519 verify"); return rc; } DEFINE_OPS_KX(X25519, CRYPT_PKEY_X25519); DEFINE_BENCH_CTX_FIXLEN(X25519); DEFINE_OPS_SIGN(Ed25519, CRYPT_PKEY_ED25519, CRYPT_MD_SHA512); DEFINE_BENCH_CTX_FIXLEN(Ed25519);
2301_79861745/bench_create
testcode/benchmark/25519_bench.c
C
unknown
4,462
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. cmake_minimum_required(VERSION 3.16 FATAL_ERROR) PROJECT(openHiTLS_BENCHMARK) set(OPENHITLS_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..) set(BENCHS sm2_bench.c slh_dsa_bench.c ecdsa_bench.c md_bench.c cipher_bench.c mac_bench.c dh_bench.c ecdh_bench.c 25519_bench.c mldsa_bench.c mlkem_bench.c) add_compile_options(-g) add_link_options(-z noexecstack) add_executable(openhitls_benchmark benchmark.c ${BENCHS}) # target_link_options(openhitls_benchmark PRIVATE -fsanitize=address) target_link_directories(openhitls_benchmark PRIVATE ${OPENHITLS_ROOT}/build ${OPENHITLS_ROOT}/platform/Secure_C/lib) target_include_directories(openhitls_benchmark PRIVATE ${OPENHITLS_ROOT}/include/crypto ${OPENHITLS_ROOT}/include/bsl ${OPENHITLS_ROOT}/platform/Secure_C/include) target_link_libraries(openhitls_benchmark PRIVATE hitls_crypto hitls_bsl boundscheck)
2301_79861745/bench_create
testcode/benchmark/CMakeLists.txt
CMake
unknown
1,542
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <string.h> #include "crypt_errno.h" #include "crypt_algid.h" #include "crypt_eal_rand.h" #include "benchmark.h" extern BenchCtx Sm2BenchCtx; extern BenchCtx SlhDsaBenchCtx; extern BenchCtx EcdsaBenchCtx; extern BenchCtx MdBenchCtx; extern BenchCtx CipherBenchCtx; extern BenchCtx MacBenchCtx; extern BenchCtx DhBenchCtx; extern BenchCtx EcdhBenchCtx; extern BenchCtx RsaBenchCtx; extern BenchCtx X25519BenchCtx; extern BenchCtx Ed25519BenchCtx; extern BenchCtx MldsaBenchCtx; extern BenchCtx MlkemBenchCtx; BenchCtx *g_benchs[] = { &Sm2BenchCtx, &SlhDsaBenchCtx, &EcdsaBenchCtx, &MdBenchCtx, &CipherBenchCtx, &MacBenchCtx, &DhBenchCtx, &EcdhBenchCtx, &X25519BenchCtx, &Ed25519BenchCtx, &MldsaBenchCtx, &MlkemBenchCtx, }; typedef struct { const char *s; int32_t id; } StrIdMap; static StrIdMap g_strIdMap[] = { {"md5", CRYPT_MD_MD5}, {"sha1", CRYPT_MD_SHA1}, {"sha224", CRYPT_MD_SHA224}, {"sha256", CRYPT_MD_SHA256}, {"sha384", CRYPT_MD_SHA384}, {"sha512", CRYPT_MD_SHA512}, {"sha3-224", CRYPT_MD_SHA3_224}, {"sha3-256", CRYPT_MD_SHA3_256}, {"sha3-384", CRYPT_MD_SHA3_384}, {"sha3-512", CRYPT_MD_SHA3_512}, {"shake128", CRYPT_MD_SHAKE128}, {"shake256", CRYPT_MD_SHAKE256}, {"sm3", CRYPT_MD_SM3}, {"SLH-DSA-SHA2-128S", CRYPT_SLH_DSA_SHA2_128S}, {"SLH-DSA-SHAKE-128S", CRYPT_SLH_DSA_SHAKE_128S}, {"SLH-DSA-SHA2-128F", CRYPT_SLH_DSA_SHA2_128F}, {"SLH-DSA-SHAKE-128F", CRYPT_SLH_DSA_SHAKE_128F}, {"SLH-DSA-SHA2-192S", CRYPT_SLH_DSA_SHA2_192S}, {"SLH-DSA-SHAKE-192S", CRYPT_SLH_DSA_SHAKE_192S}, {"SLH-DSA-SHA2-192F", CRYPT_SLH_DSA_SHA2_192F}, {"SLH-DSA-SHAKE-192F", CRYPT_SLH_DSA_SHAKE_192F}, {"SLH-DSA-SHA2-256S", CRYPT_SLH_DSA_SHA2_256S}, {"SLH-DSA-SHAKE-256S", CRYPT_SLH_DSA_SHAKE_256S}, {"SLH-DSA-SHA2-256F", CRYPT_SLH_DSA_SHA2_256F}, {"SLH-DSA-SHAKE-256F", CRYPT_SLH_DSA_SHAKE_256F}, {"nistp224", CRYPT_ECC_NISTP224}, {"nistp256", CRYPT_ECC_NISTP256}, {"nistp384", CRYPT_ECC_NISTP384}, {"nistp521", CRYPT_ECC_NISTP521}, {"brainpoolP256r1", CRYPT_ECC_BRAINPOOLP256R1}, {"brainpoolP384r1", CRYPT_ECC_BRAINPOOLP384R1}, {"brainpoolP512r1", CRYPT_ECC_BRAINPOOLP512R1}, {"aes128-cbc", CRYPT_CIPHER_AES128_CBC}, {"aes128-ctr", CRYPT_CIPHER_AES128_CTR}, {"aes128-ecb", CRYPT_CIPHER_AES128_ECB}, {"aes128-xts", CRYPT_CIPHER_AES128_XTS}, {"aes128-ccm", CRYPT_CIPHER_AES128_CCM}, {"aes128-gcm", CRYPT_CIPHER_AES128_GCM}, {"aes128-cfb", CRYPT_CIPHER_AES128_CFB}, {"aes128-ofb", CRYPT_CIPHER_AES128_OFB}, {"aes192-cbc", CRYPT_CIPHER_AES192_CBC}, {"aes192-ctr", CRYPT_CIPHER_AES192_CTR}, {"aes192-ecb", CRYPT_CIPHER_AES192_ECB}, {"aes192-ccm", CRYPT_CIPHER_AES192_CCM}, {"aes192-gcm", CRYPT_CIPHER_AES192_GCM}, {"aes192-cfb", CRYPT_CIPHER_AES192_CFB}, {"aes192-ofb", CRYPT_CIPHER_AES192_OFB}, {"aes256-cbc", CRYPT_CIPHER_AES256_CBC}, {"aes256-ctr", CRYPT_CIPHER_AES256_CTR}, {"aes256-ecb", CRYPT_CIPHER_AES256_ECB}, {"aes256-xts", CRYPT_CIPHER_AES256_XTS}, {"aes256-ccm", CRYPT_CIPHER_AES256_CCM}, {"aes256-gcm", CRYPT_CIPHER_AES256_GCM}, {"aes256-cfb", CRYPT_CIPHER_AES256_CFB}, {"aes256-ofb", CRYPT_CIPHER_AES256_OFB}, {"sm4-cbc", CRYPT_CIPHER_SM4_CBC}, {"sm4-ecb", CRYPT_CIPHER_SM4_ECB}, {"sm4-ctr", CRYPT_CIPHER_SM4_CTR}, {"sm4-gcm", CRYPT_CIPHER_SM4_GCM}, {"sm4-cfb", CRYPT_CIPHER_SM4_CFB}, {"sm4-ofb", CRYPT_CIPHER_SM4_OFB}, {"sm4-xts", CRYPT_CIPHER_SM4_XTS}, {"chacha20-poly1305", CRYPT_CIPHER_CHACHA20_POLY1305}, {"hmac-md5", CRYPT_MAC_HMAC_MD5}, {"hmac-sha1", CRYPT_MAC_HMAC_SHA1}, {"hmac-sha224", CRYPT_MAC_HMAC_SHA224}, {"hmac-sha256", CRYPT_MAC_HMAC_SHA256}, {"hmac-sha384", CRYPT_MAC_HMAC_SHA384}, {"hmac-sha512", CRYPT_MAC_HMAC_SHA512}, {"hmac-sha3-224", CRYPT_MAC_HMAC_SHA3_224}, {"hmac-sha3-256", CRYPT_MAC_HMAC_SHA3_256}, {"hmac-sha3-384", CRYPT_MAC_HMAC_SHA3_384}, {"hmac-sha3-512", CRYPT_MAC_HMAC_SHA3_512}, {"hmac-sha3-224", CRYPT_MAC_HMAC_SHA3_224}, {"hmac-sha3-256", CRYPT_MAC_HMAC_SHA3_256}, {"hmac-sm3", CRYPT_MAC_HMAC_SM3}, {"cmac-aes128", CRYPT_MAC_CMAC_AES128}, {"cmac-aes192", CRYPT_MAC_CMAC_AES192}, {"cmac-aes256", CRYPT_MAC_CMAC_AES256}, {"cmac-sm4", CRYPT_MAC_CMAC_SM4}, {"cbc-mac-sm4", CRYPT_MAC_CBC_MAC_SM4}, {"gmac-aes128", CRYPT_MAC_GMAC_AES128}, {"gmac-aes192", CRYPT_MAC_GMAC_AES192}, {"gmac-aes256", CRYPT_MAC_GMAC_AES256}, {"siphash64", CRYPT_MAC_SIPHASH64}, {"siphash128", CRYPT_MAC_SIPHASH128}, {"dh-rfc2409-768", CRYPT_DH_RFC2409_768}, {"dh-rfc2409-1024", CRYPT_DH_RFC2409_1024}, {"dh-rfc3526-1536", CRYPT_DH_RFC3526_1536}, {"dh-rfc3526-2048", CRYPT_DH_RFC3526_2048}, {"dh-rfc3526-3072", CRYPT_DH_RFC3526_3072}, {"dh-rfc3526-4096", CRYPT_DH_RFC3526_4096}, {"dh-rfc3526-6144", CRYPT_DH_RFC3526_6144}, {"dh-rfc3526-8192", CRYPT_DH_RFC3526_8192}, {"dh-rfc7919-2048", CRYPT_DH_RFC7919_2048}, {"dh-rfc7919-3072", CRYPT_DH_RFC7919_3072}, {"dh-rfc7919-4096", CRYPT_DH_RFC7919_4096}, {"dh-rfc7919-6144", CRYPT_DH_RFC7919_6144}, {"dh-rfc7919-8192", CRYPT_DH_RFC7919_8192}, }; static int32_t AlgStr2Id(char *str) { for (int i = 0; i < SIZEOF(g_strIdMap); i++) { if (strncasecmp(g_strIdMap[i].s, str, strlen(g_strIdMap[i].s)) == 0) { return g_strIdMap[i].id; } } return -1; } const char *GetAlgName(int32_t algId) { for (int i = 0; i < SIZEOF(g_strIdMap); i++) { if (g_strIdMap[i].id == algId) { return g_strIdMap[i].s; } } return ""; } static void PrintUsage(void) { printf("Usage: openhitls_benchmark [options]\n"); printf("Options:\n"); printf(" -a <algorithm> Specify algorithm to benchmark (e.g., sm2*, sm2-KeyGen, *KeyGen)\n"); printf(" -t <times> Number of times to run each benchmark\n"); printf(" -s <seconds> Number of seconds to run each benchmark\n"); printf(" -l <len> Length of the payload to benchmark\n"); printf(" -d <digest id> Digest algorithm id before sign\n"); printf(" -p <para id> Parameter id to benchmark\n"); printf(" -h Show this help message\n"); } static void ParseOptions(int argc, char **argv, BenchOptions *opts) { int c; while ((c = getopt(argc, argv, "a:t:s:l:d:p:h")) != -1) { switch (c) { case 'a': opts->algorithm = optarg; break; case 't': opts->times = (uint32_t)atoi(optarg); break; case 's': opts->seconds = (uint32_t)atoi(optarg); break; case 'l': opts->len = (uint32_t)atoi(optarg); break; case 'd': opts->hashId = AlgStr2Id(optarg); break; case 'p': opts->paraId = AlgStr2Id(optarg); break; case 'h': PrintUsage(); exit(0); default: PrintUsage(); exit(1); } } } bool MatchAlgorithm(const char *pattern, const char *name) { if (pattern == NULL) { return true; } // it's operation benchmark if (strncmp(pattern, "*-", 2) == 0) { return true; } size_t patternLen = strlen(pattern); size_t nameLen = strlen(name); const char *asterisk = strchr(pattern, '*'); if (asterisk != NULL) { // Process prefix wildcard "*XXX" if (pattern[0] == '*') { // Check if pattern is "*XXX" return (nameLen >= patternLen - 1) && (strcasecmp(name + nameLen - (patternLen - 1), pattern + 1) == 0); } // Process suffix wildcard "XXX*" if (pattern[patternLen - 1] == '*') { return strncasecmp(name, pattern, patternLen - 1) == 0; } return false; } return strncasecmp(pattern, name, strlen(name)) == 0; } static uint32_t MatchOperation(const char *pattern, BenchCtx *bench) { uint32_t re = 0; for (uint32_t i = 0; i < bench->opsNum; i++) { const Operation *op = &bench->ctxOps->ops[i]; const char *hyphen = strchr(pattern, '-'); if (hyphen != NULL) { size_t algoLen = strlen(bench->name); const char *operation = hyphen + 1; // Match algorithm part before hyphen if (strncasecmp(operation, op->name + algoLen, strlen(operation)) == 0) { re |= op->id; } } else { // not match a operation, config default supported operation re |= op->id; } } return re; } static int32_t InstantOperation(const Operation *op, void *ctx, BenchCtx *bench, BenchOptions *opts) { if (op->id & KEY_GEN_ID) { return ((KeyGen)op->oper)(ctx, bench, opts); } if (op->id & KEY_DERIVE_ID) { return ((KeyDerive)op->oper)(ctx, bench, opts); } if (op->id & ENC_ID) { return ((Enc)op->oper)(ctx, bench, opts); } if (op->id & DEC_ID) { return ((Dec)op->oper)(ctx, bench, opts); } if (op->id & SIGN_ID) { return ((Sign)op->oper)(ctx, bench, opts); } if (op->id & VERIFY_ID) { return ((Verify)op->oper)(ctx, bench, opts); } if (op->id & ONESHOT_ID) { return ((OneShot)op->oper)(ctx, bench, opts); } if (op->id & ENCAPS_ID) { return ((Encaps)op->oper)(ctx, bench, opts); } if (op->id & DECAPS_ID) { return ((Decaps)op->oper)(ctx, bench, opts); } return CRYPT_NOT_SUPPORT; } static void ResetOptions(BenchOptions *opts, BenchCtx *benchCtx) { if (opts->seconds == 0) { opts->seconds = benchCtx->seconds; } if (opts->times == 0) { opts->times = benchCtx->times; } } static void DoBenchTest(BenchCtx *benchs, const CtxOps *ctxOps, const Operation *op, BenchOptions *algOpts) { void *ctx = NULL; BENCH_SETUP(ctx, benchs, ctxOps, algOpts->paraId); if (op->id & KEY_GEN_ID || op->id & KEY_DERIVE_ID) { // keygen and keyderive just do one fixed len. int32_t ret = InstantOperation(op, ctx, benchs, algOpts); if (ret != CRYPT_SUCCESS) { printf("Failed to %s, ret = %08x\n", op->name, ret); } } else { bool is_match = false; for (int i = 0; i < benchs->lensNum; i++) { if (algOpts->len != -1 && algOpts->len != benchs->lens[i]) { continue; } BENCH_SETUP(ctx, benchs, ctxOps, algOpts->paraId); BenchOptions tmpOpts = *algOpts; tmpOpts.len = benchs->lens[i]; int32_t ret = InstantOperation(op, ctx, benchs, &tmpOpts); if (ret != CRYPT_SUCCESS) { printf("Failed to %s, ret = %08x\n", op->name, ret); } is_match = true; } if (algOpts->len != -1 && !is_match) { int32_t ret = InstantOperation(op, ctx, benchs, algOpts); if (ret != CRYPT_SUCCESS) { printf("Failed to %s, ret = %08x\n", op->name, ret); } } } BENCH_TEARDOWN(ctx, ctxOps); } int main(int argc, char **argv) { int32_t ret; BenchOptions opts = {0}; // default options opts.algorithm = "*"; // all algorithms opts.filteredOps = 0x3F; // all operations opts.paraId = -1; // fake hash id opts.hashId = -1; // fake hash id opts.len = -1; // fake len ParseOptions(argc, argv, &opts); ret = CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default", NULL, 0, NULL); if (ret != CRYPT_SUCCESS) { printf("Failed to initialize random number generator\n"); return -1; } printf("%-35s, %10s, %15s, %15s, %20s\n", "algorithm operation", "len", "run times", "time elapsed(ms)", "ops/s"); for (int i = 0; i < SIZEOF(g_benchs); i++) { const CtxOps *ctxOps = g_benchs[i]->ctxOps; BenchOptions algOpts = opts; ResetOptions(&algOpts, g_benchs[i]); // filtering benchmark test if (!MatchAlgorithm(opts.algorithm, g_benchs[i]->name)) { continue; } opts.filteredOps = MatchOperation(opts.algorithm, g_benchs[i]); for (int j = 0; j < g_benchs[i]->opsNum; j++) { const Operation *op = &ctxOps->ops[j]; if ((uint32_t)(op->id & opts.filteredOps) == 0U) { continue; } BenchOptions tmpOpts = algOpts; if (tmpOpts.paraId != -1 || g_benchs[i]->paraIdsNum == 0) { DoBenchTest(g_benchs[i], ctxOps, op, &tmpOpts); } else { for (int k = 0; k < g_benchs[i]->paraIdsNum; k++) { tmpOpts.paraId = g_benchs[i]->paraIds[k]; DoBenchTest(g_benchs[i], ctxOps, op, &tmpOpts); } } } } return 0; }
2301_79861745/bench_create
testcode/benchmark/benchmark.c
C
unknown
13,679
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef BENCHMARK_H #define BENCHMARK_H #include <stdint.h> #include <string.h> #include <stdio.h> #include <time.h> #include <sys/time.h> #define BENCH_TIMES(func, rc, ok, len, times, header) \ { \ struct timespec start, end; \ clock_gettime(CLOCK_REALTIME, &start); \ for (int i = 0; i < times; i++) { \ rc = func; \ if (rc != ok) { \ printf("Error: %s, ret = %08x\n", #func, rc); \ break; \ } \ } \ clock_gettime(CLOCK_REALTIME, &end); \ uint64_t elapsedTime = (end.tv_sec - start.tv_sec) * 1000000000 + (end.tv_nsec - start.tv_nsec); \ printf("%-35s, %10d, %15d, %16.2f, %20.2f\n", header, len, times, (double)elapsedTime / 1000000, \ ((double)times * 1000000000) / elapsedTime); \ } #define BENCH_TIMES_VA(func, rc, ok, len, times, headerFmt, ...) \ { \ char header[256] = {0}; \ snprintf(header, sizeof(header), headerFmt, ##__VA_ARGS__); \ BENCH_TIMES(func, rc, ok, len, times, header); \ } #define BENCH_SECONDS(func, rc, ok, len, secs, header) \ { \ struct timespec start, end; \ uint64_t totalTime = secs * 1000000000; \ uint64_t elapsedTime = 0; \ uint64_t cnt = 0; \ while (elapsedTime < totalTime) { \ clock_gettime(CLOCK_REALTIME, &start); \ rc = func; \ if (rc != ok) { \ printf("Error: %s, ret = %08x\n", #func, rc); \ break; \ } \ clock_gettime(CLOCK_REALTIME, &end); \ elapsedTime += (end.tv_sec - start.tv_sec) * 1000000000 + (end.tv_nsec - start.tv_nsec); \ cnt++; \ } \ printf("%-35s, %10d, %15d, %16.2f, %20.2f\n", header, len, cnt, elapsedTime / 1000000, \ ((double)times * 1000000000) / elapsedTime); \ } #define BENCH_SETUP(ctx, bench, ops, id) \ do { \ int32_t ret; \ ret = ops->setUp(&ctx, bench, ops, id); \ if (ret != CRYPT_SUCCESS) { \ printf("Failed to setup benchmark testcase: %08x\n", ret); \ return; \ } \ } while (0) #define BENCH_TEARDOWN(ctx, ops) \ do { \ ops->tearDown(ctx); \ } while (0) // sizeof array #define SIZEOF(a) (sizeof(a) / sizeof(a[0])) static inline void Hex2Bin(const char *hex, uint8_t *bin, uint32_t *len) { *len = strlen(hex) / 2; for (uint32_t i = 0; i < *len; i++) { sscanf(hex + i * 2, "%2hhx", &bin[i]); } } // 定义命令行选项结构 typedef struct { char *algorithm; // -a 选项指定的算法 uint32_t filteredOps; uint32_t times; // -t 选项指定的运行次数 uint32_t seconds; // -s 选项指定的运行时间 uint32_t len; int32_t paraId; int32_t hashId; } BenchOptions; typedef struct BenchCtx_ BenchCtx; typedef struct CtxOps_ CtxOps; // every benchmark testcase should define "NewCtx" and "FreeCtx" typedef int32_t (*SetUp)(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t id); typedef void (*TearDown)(void *ctx); typedef int32_t (*KeyGen)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*KeyDerive)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Enc)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Dec)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Sign)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Verify)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*OneShot)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Encaps)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Decaps)(void *ctx, BenchCtx *bench, BenchOptions *opts); // return true if not be filetered; else return false. typedef bool (*ParaFilterCb)(BenchOptions *opts, int32_t paraId); typedef struct { uint32_t id; const char *name; void *oper; } Operation; struct CtxOps_ { int32_t algId; int32_t hashId; SetUp setUp; TearDown tearDown; Operation ops[]; }; #define KEY_GEN_ID 1U #define KEY_DERIVE_ID 2U #define ENC_ID 4U #define DEC_ID 8U #define SIGN_ID 16U #define VERIFY_ID 32U #define ONESHOT_ID 64U #define ENCAPS_ID 128U #define DECAPS_ID 256U static int32_t g_lens[] = {16, 64, 256, 1024, 8192, 16384}; static uint8_t g_plain[16384]; static uint8_t g_out[16384]; static uint8_t g_key[32] = {1}; static uint8_t g_iv[16]; #define DEFINE_OPER(id, oper) {id, #oper, oper} #define DEFINE_OPS(alg, id, hId) \ static const CtxOps alg##CtxOps = { \ .algId = id, \ .hashId = hId, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(KEY_GEN_ID, alg##KeyGen), \ DEFINE_OPER(KEY_DERIVE_ID, alg##KeyDerive), \ DEFINE_OPER(ENC_ID, alg##Enc), \ DEFINE_OPER(DEC_ID, alg##Dec), \ DEFINE_OPER(SIGN_ID, alg##Sign), \ DEFINE_OPER(VERIFY_ID, alg##Verify), \ }, \ } #define DEFINE_OPS_SIGN(alg, id, hId) \ static const CtxOps alg##CtxOps = { \ .algId = id, \ .hashId = hId, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(KEY_GEN_ID, alg##KeyGen), \ DEFINE_OPER(SIGN_ID, alg##Sign), \ DEFINE_OPER(VERIFY_ID, alg##Verify), \ }, \ } #define DEFINE_OPS_CIPHER(alg, id) \ static const CtxOps alg##CtxOps = { \ .algId = id, \ .hashId = id, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(ENC_ID, alg##Enc), \ DEFINE_OPER(DEC_ID, alg##Dec), \ }, \ } #define DEFINE_OPS_MD(alg) \ static const CtxOps alg##CtxOps = { \ .algId = CRYPT_MD_MAX, \ .hashId = CRYPT_MD_MAX, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(ONESHOT_ID, alg##OneShot), \ }, \ } #define DEFINE_OPS_KX(alg, id) \ static const CtxOps alg##CtxOps = { \ .algId = id, \ .hashId = CRYPT_MD_MAX, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(KEY_GEN_ID, alg##KeyGen), \ DEFINE_OPER(KEY_DERIVE_ID, alg##KeyDerive), \ }, \ } #define DEFINE_OPS_KEM(alg, id) \ static const CtxOps alg##CtxOps = { \ .algId = id, \ .hashId = CRYPT_MD_MAX, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(KEY_GEN_ID, alg##KeyGen), \ DEFINE_OPER(ENCAPS_ID, alg##Encaps), \ DEFINE_OPER(DECAPS_ID, alg##Decaps), \ }, \ } typedef struct BenchCtx_ { const char *name; const char *desc; const CtxOps *ctxOps; int32_t opsNum; int32_t *paraIds; uint32_t paraIdsNum; int32_t *lens; uint32_t lensNum; int32_t times; int32_t seconds; } BenchCtx; #define DEFINE_BENCH_CTX_PARA_TIMES_LEN(alg, pId, pIdNum, ts, l, ln) \ BenchCtx alg##BenchCtx = { \ .name = #alg, \ .desc = #alg " benchmark", \ .ctxOps = &alg##CtxOps, \ .opsNum = SIZEOF(alg##CtxOps.ops), \ .paraIds = pId, \ .paraIdsNum = pIdNum, \ .lens = l, \ .lensNum = ln, \ .times = ts, \ .seconds = 0, \ } #define DEFINE_BENCH_CTX_PARA_TIMES(alg, pId, pIdNum, ts) \ DEFINE_BENCH_CTX_PARA_TIMES_LEN(alg, pId, pIdNum, ts, g_lens, SIZEOF(g_lens)) #define DEFINE_BENCH_CTX_PARA_TIMES_FIXLEN(alg, pId, pIdNum, ts) \ DEFINE_BENCH_CTX_PARA_TIMES_LEN(alg, pId, pIdNum, ts, g_lens, 1) // default to run 10000 times #define DEFINE_BENCH_CTX_PARA(alg, pId, pIdNum) DEFINE_BENCH_CTX_PARA_TIMES(alg, pId, pIdNum, 10000) #define DEFINE_BENCH_CTX_PARA_FIXLEN(alg, pId, pIdNum) DEFINE_BENCH_CTX_PARA_TIMES_FIXLEN(alg, pId, pIdNum, 10000) #define DEFINE_BENCH_CTX(alg) DEFINE_BENCH_CTX_PARA(alg, NULL, 0) #define DEFINE_BENCH_CTX_FIXLEN(alg) DEFINE_BENCH_CTX_PARA_FIXLEN(alg, NULL, 0) bool MatchAlgorithm(const char *pattern, const char *name); const char *GetAlgName(int32_t hashId); #endif /* BENCHMARK_H */
2301_79861745/bench_create
testcode/benchmark/benchmark.h
C
unknown
13,697
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_cipher.h" #include "benchmark.h" static int32_t CipherSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { *ctx = CRYPT_EAL_CipherNewCtx(paraId); if (*ctx == NULL) { printf("Failed to new cipher ctx\n"); return CRYPT_ERR_ALGID; } return CRYPT_SUCCESS; } static void CipherTearDown(void *ctx) { if (ctx != NULL) { CRYPT_EAL_CipherFreeCtx(ctx); } } static int32_t DoCipherEnc(void *ctx, BenchOptions *opts) { uint8_t out[16384]; // Maximum output size uint32_t outLen = sizeof(out); return CRYPT_EAL_CipherUpdate(ctx, g_plain, opts->len, out, &outLen); } static CRYPT_EAL_CipherCtx *InitCipherCtx(int32_t paraId, uint32_t keyLen, uint32_t ivLen, bool isEnc) { int rc; CRYPT_EAL_CipherCtx *cipher = CRYPT_EAL_CipherNewCtx(paraId); if (cipher == NULL) { return NULL; } // the iv len of ccm is in [7, 13] rc = CRYPT_EAL_CipherInit(cipher, g_key, keyLen, g_iv, ivLen, isEnc); if (rc != CRYPT_SUCCESS) { printf("init ccm cipher failed\n"); return NULL; } return cipher; } static int32_t DoCcmEnc(void *ctx, BenchOptions *opts, uint32_t keyLen, uint32_t ivLen) { // aead do a complete init->ctrl->update->final process. (void)ctx; int rc; int32_t paraId = opts->paraId; uint32_t aad[32] = {1, 2, 3}; uint64_t msgLen = opts->len; uint32_t outLen = sizeof(g_out); uint8_t tag[16]; uint32_t tagLen = sizeof(tag); CRYPT_EAL_CipherCtx *cipher = InitCipherCtx(paraId, keyLen, ivLen, true); if (cipher == NULL) { return CRYPT_ERR_ALGID; } if ((rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_MSGLEN, &msgLen, sizeof(msgLen))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_AAD, aad, sizeof(aad))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherUpdate(cipher, g_plain, opts->len, g_out, &outLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_GET_TAG, tag, tagLen)) != CRYPT_SUCCESS) { printf("do ccm enc failed\n"); goto ERR; } ERR: CRYPT_EAL_CipherFreeCtx(cipher); return rc; } static int32_t DoCcmDec(void *ctx, BenchOptions *opts, uint32_t keyLen, uint32_t ivLen) { // aead do a complete init->ctrl->update->final process. (void)ctx; int rc; int32_t paraId = opts->paraId; uint32_t aad[32] = {1, 2, 3}; uint64_t msgLen = opts->len; uint32_t outLen = sizeof(g_out); CRYPT_EAL_CipherCtx *cipher = InitCipherCtx(paraId, keyLen, ivLen, false); if (cipher == NULL) { return CRYPT_ERR_ALGID; } if ((rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_MSGLEN, &msgLen, sizeof(msgLen))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_AAD, aad, sizeof(aad))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherUpdate(cipher, g_plain, opts->len, g_out, &outLen)) != CRYPT_SUCCESS) { printf("do ccm dec failed\n"); goto ERR; } ERR: CRYPT_EAL_CipherFreeCtx(cipher); return rc; } static int32_t DoGcmEnc(void *ctx, BenchOptions *opts, uint32_t keyLen, uint32_t ivLen) { // aead do a complete init->ctrl->update->final process. (void)ctx; int rc; int32_t paraId = opts->paraId; uint32_t aad[32] = {1, 2, 3}; uint8_t tag[16]; uint32_t tagLen = sizeof(tag); uint32_t outLen = sizeof(g_out); CRYPT_EAL_CipherCtx *cipher = InitCipherCtx(paraId, keyLen, ivLen, true); if (cipher == NULL) { return CRYPT_ERR_ALGID; } if ((rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_AAD, aad, sizeof(aad))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherUpdate(cipher, g_plain, opts->len, g_out, &outLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_GET_TAG, tag, sizeof(tag))) != CRYPT_SUCCESS) { printf("do gcm enc failed\n"); goto ERR; } ERR: CRYPT_EAL_CipherFreeCtx(cipher); return rc; } static int32_t DoGcmDec(void *ctx, BenchOptions *opts, uint32_t keyLen, uint32_t ivLen) { // aead do a complete init->ctrl->update->final process. (void)ctx; int rc; int32_t paraId = opts->paraId; uint32_t aad[32] = {1, 2, 3}; uint8_t tag[16]; uint32_t tagLen = sizeof(tag); uint32_t outLen = sizeof(g_out); CRYPT_EAL_CipherCtx *cipher = InitCipherCtx(paraId, keyLen, ivLen, false); if (cipher == NULL) { return CRYPT_ERR_ALGID; } if ((rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_AAD, aad, sizeof(aad))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherUpdate(cipher, g_plain, opts->len, g_out, &outLen)) != CRYPT_SUCCESS) { printf("do gcm enc failed\n"); goto ERR; } ERR: CRYPT_EAL_CipherFreeCtx(cipher); return rc; } static int32_t CipherEnc(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *cipherName = GetAlgName(paraId); uint32_t keyLen = 16; uint32_t ivLen = 16; if ((rc = CRYPT_EAL_CipherGetInfo(paraId, CRYPT_INFO_KEY_LEN, &keyLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherGetInfo(paraId, CRYPT_INFO_IV_LEN, &ivLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherInit(ctx, g_key, keyLen, g_iv, ivLen, true)) != CRYPT_SUCCESS) { return rc; } // aead if (paraId == CRYPT_CIPHER_AES128_CCM || paraId == CRYPT_CIPHER_AES192_CCM || paraId == CRYPT_CIPHER_AES256_CCM) { BENCH_TIMES_VA(DoCcmEnc(ctx, opts, keyLen, ivLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s encrypt", cipherName); } else if (paraId == CRYPT_CIPHER_AES128_GCM || paraId == CRYPT_CIPHER_AES192_GCM || paraId == CRYPT_CIPHER_AES256_GCM || paraId == CRYPT_CIPHER_SM4_GCM) { BENCH_TIMES_VA(DoGcmEnc(ctx, opts, keyLen, ivLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s encrypt", cipherName); } else { BENCH_TIMES_VA(DoCipherEnc(ctx, opts), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s encrypt", cipherName); } return rc; } static int32_t CipherDec(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *cipherName = GetAlgName(paraId); uint32_t keyLen = 16; uint32_t ivLen = 16; if ((rc = CRYPT_EAL_CipherGetInfo(paraId, CRYPT_INFO_KEY_LEN, &keyLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherGetInfo(paraId, CRYPT_INFO_IV_LEN, &ivLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherInit(ctx, g_key, keyLen, g_iv, ivLen, false)) != CRYPT_SUCCESS) { return rc; } // aead if (paraId == CRYPT_CIPHER_AES128_CCM || paraId == CRYPT_CIPHER_AES192_CCM || paraId == CRYPT_CIPHER_AES256_CCM) { BENCH_TIMES_VA(DoCcmDec(ctx, opts, keyLen, ivLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s decrypt", cipherName); } else if (paraId == CRYPT_CIPHER_AES128_GCM || paraId == CRYPT_CIPHER_AES192_GCM || paraId == CRYPT_CIPHER_AES256_GCM || paraId == CRYPT_CIPHER_SM4_GCM) { BENCH_TIMES_VA(DoGcmDec(ctx, opts, keyLen, ivLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s decrypt", cipherName); } else { BENCH_TIMES_VA(DoCipherEnc(ctx, opts), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s decrypt", cipherName); } return rc; } static int32_t g_paraIds[] = { // AES-128 modes CRYPT_CIPHER_AES128_CBC, CRYPT_CIPHER_AES128_CTR, CRYPT_CIPHER_AES128_ECB, CRYPT_CIPHER_AES128_XTS, CRYPT_CIPHER_AES128_CCM, CRYPT_CIPHER_AES128_GCM, CRYPT_CIPHER_AES128_CFB, CRYPT_CIPHER_AES128_OFB, // AES-192 modes CRYPT_CIPHER_AES192_CBC, CRYPT_CIPHER_AES192_CTR, CRYPT_CIPHER_AES192_ECB, CRYPT_CIPHER_AES192_CCM, CRYPT_CIPHER_AES192_GCM, CRYPT_CIPHER_AES192_CFB, CRYPT_CIPHER_AES192_OFB, // AES-256 modes CRYPT_CIPHER_AES256_CBC, CRYPT_CIPHER_AES256_CTR, CRYPT_CIPHER_AES256_ECB, CRYPT_CIPHER_AES256_XTS, CRYPT_CIPHER_AES256_CCM, CRYPT_CIPHER_AES256_GCM, CRYPT_CIPHER_AES256_CFB, CRYPT_CIPHER_AES256_OFB, // SM4 modes CRYPT_CIPHER_SM4_XTS, CRYPT_CIPHER_SM4_CBC, CRYPT_CIPHER_SM4_ECB, CRYPT_CIPHER_SM4_CTR, CRYPT_CIPHER_SM4_GCM, CRYPT_CIPHER_SM4_CFB, CRYPT_CIPHER_SM4_OFB, // ChaCha20-Poly1305 CRYPT_CIPHER_CHACHA20_POLY1305, }; DEFINE_OPS_CIPHER(Cipher, CRYPT_PKEY_MAX); DEFINE_BENCH_CTX_PARA(Cipher, g_paraIds, SIZEOF(g_paraIds));
2301_79861745/bench_create
testcode/benchmark/cipher_bench.c
C
unknown
9,405
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t DhSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { int32_t ret; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } ret = CRYPT_EAL_PkeySetParaById(pkeyCtx, paraId); if (ret != CRYPT_SUCCESS) { printf("Failed to set para: %d.\n", paraId); return ret; } ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen dh key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void DhTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t DhKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; int32_t paraId = opts->paraId; const char *group = GetAlgName(paraId); BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s dh keyGen", group); return rc; } static int32_t DhKeyDerive(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *group = GetAlgName(paraId); // Create a peer context for key exchange CRYPT_EAL_PkeyCtx *peerCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_DH); if (peerCtx == NULL) { printf("Failed to create peer context\n"); return CRYPT_MEM_ALLOC_FAIL; } rc = CRYPT_EAL_PkeySetParaById(peerCtx, paraId); if (rc != CRYPT_SUCCESS) { printf("Failed to set peer para: %d.\n", paraId); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } rc = CRYPT_EAL_PkeyGen(peerCtx); if (rc != CRYPT_SUCCESS) { printf("Failed to gen peer key.\n"); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } uint8_t sharedKey[4096]; // DH can have larger key sizes uint32_t sharedKeyLen = sizeof(sharedKey); BENCH_TIMES_VA(CRYPT_EAL_PkeyComputeShareKey(ctx, peerCtx, sharedKey, &sharedKeyLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s dh keyDervie", group); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } static int32_t g_paraIds[] = { CRYPT_DH_RFC2409_768, CRYPT_DH_RFC2409_1024, CRYPT_DH_RFC3526_1536, CRYPT_DH_RFC3526_2048, CRYPT_DH_RFC3526_3072, CRYPT_DH_RFC3526_4096, CRYPT_DH_RFC3526_6144, CRYPT_DH_RFC3526_8192, CRYPT_DH_RFC7919_2048, CRYPT_DH_RFC7919_3072, CRYPT_DH_RFC7919_4096, CRYPT_DH_RFC7919_6144, CRYPT_DH_RFC7919_8192, }; DEFINE_OPS_KX(Dh, CRYPT_PKEY_DH); DEFINE_BENCH_CTX_PARA_TIMES_FIXLEN(Dh, g_paraIds, SIZEOF(g_paraIds), 1000);
2301_79861745/bench_create
testcode/benchmark/dh_bench.c
C
unknown
3,319
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t EcdhSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { int32_t ret; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } ret = CRYPT_EAL_PkeySetParaById(pkeyCtx, paraId); if (ret != CRYPT_SUCCESS) { printf("Failed to set para: %d.\n", paraId); return ret; } ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen ecdh key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void EcdhTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t EcdhKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; int32_t paraId = opts->paraId; const char *curve = GetAlgName(paraId); BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s ecdh keyGen", curve); return rc; } static int32_t EcdhKeyDerive(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *curve = GetAlgName(paraId); // Create a peer context for key exchange CRYPT_EAL_PkeyCtx *peerCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); if (peerCtx == NULL) { printf("Failed to create peer context\n"); return CRYPT_MEM_ALLOC_FAIL; } rc = CRYPT_EAL_PkeySetParaById(peerCtx, paraId); if (rc != CRYPT_SUCCESS) { printf("Failed to set peer para: %d.\n", paraId); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } rc = CRYPT_EAL_PkeyGen(peerCtx); if (rc != CRYPT_SUCCESS) { printf("Failed to gen peer key.\n"); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } uint8_t sharedKey[256]; uint32_t sharedKeyLen = sizeof(sharedKey); BENCH_TIMES_VA(CRYPT_EAL_PkeyComputeShareKey(ctx, peerCtx, sharedKey, &sharedKeyLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s ecdh keyDerive", curve); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } static int32_t g_paraIds[] = { CRYPT_ECC_NISTP224, CRYPT_ECC_NISTP256, CRYPT_ECC_NISTP384, CRYPT_ECC_NISTP521, CRYPT_ECC_BRAINPOOLP256R1, CRYPT_ECC_BRAINPOOLP384R1, CRYPT_ECC_BRAINPOOLP512R1, }; DEFINE_OPS_KX(Ecdh, CRYPT_PKEY_ECDH); DEFINE_BENCH_CTX_PARA_FIXLEN(Ecdh, g_paraIds, SIZEOF(g_paraIds));
2301_79861745/bench_create
testcode/benchmark/ecdh_bench.c
C
unknown
3,175
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t EcdsaSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { int32_t ret; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } ret = CRYPT_EAL_PkeySetParaById(pkeyCtx, paraId); if (ret != CRYPT_SUCCESS) { printf("Failed to set para: %d.\n", paraId); return ret; } ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen ecdsa key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void EcdsaTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t EcdsaKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; int32_t paraId = opts->paraId; const char *curve = GetAlgName(paraId); BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s keyGen", curve); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { hashId = opts->hashId; } return hashId; } static int32_t EcdsaSignInner(void *ctx, int32_t hashId, int32_t len) { uint8_t signature[256]; uint32_t signatureLen = sizeof(signature); return CRYPT_EAL_PkeySign(ctx, hashId, g_plain, len, signature, &signatureLen); } static int32_t EcdsaSign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *curve = GetAlgName(paraId); int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } const char *mdName = GetAlgName(hashId); BENCH_TIMES_VA(EcdsaSignInner(ctx, hashId, opts->len), rc, CRYPT_SUCCESS, -1, opts->times, "%s-%s sign", curve, mdName); return rc; } static int32_t EcdsaVerify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *curve = GetAlgName(paraId); int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } uint8_t signature[256]; uint32_t signatureLen = sizeof(signature); rc = CRYPT_EAL_PkeySign(ctx, hashId, g_plain, opts->len, signature, &signatureLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } const char *mdName = GetAlgName(hashId); BENCH_TIMES_VA(CRYPT_EAL_PkeyVerify(ctx, hashId, g_plain, opts->len, signature, signatureLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s-%s verify", curve, mdName); return rc; } static int32_t g_paraIds[] = { CRYPT_ECC_NISTP224, CRYPT_ECC_NISTP256, CRYPT_ECC_NISTP384, CRYPT_ECC_NISTP521, CRYPT_ECC_BRAINPOOLP256R1, CRYPT_ECC_BRAINPOOLP384R1, CRYPT_ECC_BRAINPOOLP512R1, }; DEFINE_OPS_SIGN(Ecdsa, CRYPT_PKEY_ECDSA, CRYPT_MD_SHA256); DEFINE_BENCH_CTX_PARA_FIXLEN(Ecdsa, g_paraIds, SIZEOF(g_paraIds));
2301_79861745/bench_create
testcode/benchmark/ecdsa_bench.c
C
unknown
3,761
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_mac.h" #include "benchmark.h" static int32_t MacSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)ctx; (void)bench; (void)ops; (void)paraId; return CRYPT_SUCCESS; } static void MacTearDown(void *ctx) { (void)ctx; } static int32_t DoMacCtrl(CRYPT_EAL_MacCtx *mac, int32_t paraId) { if (paraId == CRYPT_MAC_CBC_MAC_SM4) { // cbc-mac-sm4 only support zeros padding CRYPT_PaddingType padType = CRYPT_PADDING_ZEROS; return CRYPT_EAL_MacCtrl(mac, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(padType)); } return CRYPT_SUCCESS; } static int32_t DoMac(void *ctx, BenchCtx *bench, BenchOptions *opts, uint32_t keyLen, uint32_t digestLen) { (void)ctx; (void)bench; int32_t rc = CRYPT_SUCCESS; int32_t paraId = opts->paraId; uint8_t digest[256]; CRYPT_EAL_MacCtx *mac = CRYPT_EAL_MacNewCtx(paraId); if (mac == NULL) { return CRYPT_ERR_ALGID; } if ((rc = CRYPT_EAL_MacInit(mac, g_key, keyLen)) != CRYPT_SUCCESS || (rc = DoMacCtrl(mac, paraId)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_MacUpdate(mac, g_plain, opts->len)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_MacFinal(mac, digest, &digestLen)) != CRYPT_SUCCESS) { printf("do mac init failed\n"); goto ERR; } ERR: CRYPT_EAL_MacFreeCtx(mac); return rc; } static int32_t MacOneShot(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *macName = GetAlgName(paraId); uint32_t keyLen = 16; uint32_t digestLen = 256; if (paraId == CRYPT_MAC_CMAC_AES192 || paraId == CRYPT_MAC_GMAC_AES192) { keyLen = 24; } if (paraId == CRYPT_MAC_CMAC_AES256 || paraId == CRYPT_MAC_GMAC_AES256) { keyLen = 32; } if (paraId == CRYPT_MAC_GMAC_AES128 || paraId == CRYPT_MAC_GMAC_AES192 || paraId == CRYPT_MAC_GMAC_AES256) { digestLen = 16; } BENCH_TIMES_VA(DoMac(ctx, bench, opts, keyLen, digestLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s mac", macName); return rc; } static int32_t g_paraIds[] = { CRYPT_MAC_HMAC_MD5, CRYPT_MAC_HMAC_SHA1, CRYPT_MAC_HMAC_SHA224, CRYPT_MAC_HMAC_SHA256, CRYPT_MAC_HMAC_SHA384, CRYPT_MAC_HMAC_SHA512, CRYPT_MAC_HMAC_SHA3_224, CRYPT_MAC_HMAC_SHA3_256, CRYPT_MAC_HMAC_SHA3_384, CRYPT_MAC_HMAC_SHA3_512, CRYPT_MAC_HMAC_SM3, CRYPT_MAC_CMAC_AES128, CRYPT_MAC_CMAC_AES192, CRYPT_MAC_CMAC_AES256, CRYPT_MAC_CMAC_SM4, CRYPT_MAC_CBC_MAC_SM4, CRYPT_MAC_GMAC_AES128, CRYPT_MAC_GMAC_AES192, CRYPT_MAC_GMAC_AES256, CRYPT_MAC_SIPHASH64, CRYPT_MAC_SIPHASH128, }; DEFINE_OPS_MD(Mac); DEFINE_BENCH_CTX_PARA(Mac, g_paraIds, SIZEOF(g_paraIds));
2301_79861745/bench_create
testcode/benchmark/mac_bench.c
C
unknown
3,424
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t MdSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)ctx; (void)bench; (void)ops; (void)paraId; return CRYPT_SUCCESS; } static void MdTearDown(void *ctx) { (void)ctx; } static int32_t MdOneShot(void *ctx, BenchCtx *bench, BenchOptions *opts) { (void)ctx; int rc; int32_t paraId = opts->paraId; const char *mdName = GetAlgName(paraId); uint8_t digest[64]; // Maximum digest size for supported algorithms uint32_t digestLen = sizeof(digest); BENCH_TIMES_VA(CRYPT_EAL_Md(paraId, g_plain, opts->len, digest, &digestLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s digest", mdName); return rc; } static int32_t g_paraIds[] = { CRYPT_MD_MD5, CRYPT_MD_SHA1, CRYPT_MD_SHA224, CRYPT_MD_SHA256, CRYPT_MD_SHA384, CRYPT_MD_SHA512, CRYPT_MD_SHA3_224, CRYPT_MD_SHA3_256, CRYPT_MD_SHA3_384, CRYPT_MD_SHA3_512, CRYPT_MD_SHAKE128, CRYPT_MD_SHAKE256, CRYPT_MD_SM3, }; DEFINE_OPS_MD(Md); DEFINE_BENCH_CTX_PARA(Md, g_paraIds, SIZEOF(g_paraIds));
2301_79861745/bench_create
testcode/benchmark/md_bench.c
C
unknown
1,763
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" const char *GetParaName(int32_t paraId) { switch (paraId) { case CRYPT_MLDSA_TYPE_MLDSA_44: return "mldsa-44"; case CRYPT_MLDSA_TYPE_MLDSA_65: return "mldsa-65"; case CRYPT_MLDSA_TYPE_MLDSA_87: return "mldsa-87"; default: break; } return ""; } static int32_t MldsaSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)paraId; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_PARA_BY_ID, &paraId, sizeof(paraId)); if (ret != CRYPT_SUCCESS) { printf("Failed to set mldsa alg info.\n"); return ret; } ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen mldsa key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void MldsaTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t MldsaKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s keyGen", GetParaName(opts->paraId)); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { hashId = opts->hashId; } return hashId; } static int32_t MldsaSignInner(void *ctx, int32_t hashId) { uint8_t plainText[32]; uint8_t signature[5120]; // ML-DSA can have larger signatures uint32_t signatureLen = sizeof(signature); return CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); } static int32_t MldsaSign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } BENCH_TIMES_VA(MldsaSignInner(ctx, hashId), rc, CRYPT_SUCCESS, -1, opts->times, "%s sign", GetParaName(opts->paraId)); return rc; } static int32_t MldsaVerify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } uint8_t plainText[32]; uint8_t signature[5120]; // ML-DSA can have larger signatures uint32_t signatureLen = sizeof(signature); rc = CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } BENCH_TIMES_VA(CRYPT_EAL_PkeyVerify(ctx, hashId, plainText, sizeof(plainText), signature, signatureLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s verify", GetParaName(opts->paraId)); return rc; } static int32_t g_paraIds[] = { CRYPT_MLDSA_TYPE_MLDSA_44, CRYPT_MLDSA_TYPE_MLDSA_65, CRYPT_MLDSA_TYPE_MLDSA_87, }; DEFINE_OPS_SIGN(Mldsa, CRYPT_PKEY_ML_DSA, CRYPT_MD_SHA256); DEFINE_BENCH_CTX_PARA_FIXLEN(Mldsa, g_paraIds, SIZEOF(g_paraIds));
2301_79861745/bench_create
testcode/benchmark/mldsa_bench.c
C
unknown
3,893
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static const char *GetParaName(int32_t paraId) { switch (paraId) { case CRYPT_KEM_TYPE_MLKEM_512: return "mlkem-512"; case CRYPT_KEM_TYPE_MLKEM_768: return "mlkem-768"; case CRYPT_KEM_TYPE_MLKEM_1024: return "mlkem-1024"; default: return "unknown"; } return ""; } static int32_t MlkemSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)paraId; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_PARA_BY_ID, &paraId, sizeof(paraId)); if (ret != CRYPT_SUCCESS) { printf("Failed to set mldsa alg info.\n"); return ret; } ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen mlkem key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void MlkemTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t MlkemKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s keyGen", GetParaName(opts->paraId)); return rc; } static int32_t MlkemEncaps(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; uint8_t ciphertext[2048]; // ML-KEM can have larger ciphertexts uint32_t ciphertextLen = sizeof(ciphertext); uint8_t sharedKey[32]; uint32_t sharedKeyLen = sizeof(sharedKey); BENCH_TIMES_VA(CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &ciphertextLen, sharedKey, &sharedKeyLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s encaps", GetParaName(opts->paraId)); return rc; } static int32_t MlkemDecaps(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; uint8_t ciphertext[2048]; // ML-KEM can have larger ciphertexts uint32_t ciphertextLen = sizeof(ciphertext); uint8_t sharedKey[32]; uint32_t sharedKeyLen = sizeof(sharedKey); // First encap to get a valid ciphertext rc = CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &ciphertextLen, sharedKey, &sharedKeyLen); if (rc != CRYPT_SUCCESS) { printf("Failed to encap\n"); return rc; } BENCH_TIMES_VA(CRYPT_EAL_PkeyDecaps(ctx, ciphertext, ciphertextLen, sharedKey, &sharedKeyLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s decaps", GetParaName(opts->paraId)); return rc; } static int32_t g_paraIds[] = { CRYPT_KEM_TYPE_MLKEM_512, CRYPT_KEM_TYPE_MLKEM_768, CRYPT_KEM_TYPE_MLKEM_1024, }; DEFINE_OPS_KEM(Mlkem, CRYPT_PKEY_ML_KEM); DEFINE_BENCH_CTX_PARA_FIXLEN(Mlkem, g_paraIds, SIZEOF(g_paraIds));
2301_79861745/bench_create
testcode/benchmark/mlkem_bench.c
C
unknown
3,535
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t RsaSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)paraId; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen rsa key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void RsaTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t RsaKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "rsa keyGen"); return rc; } static int32_t RsaEncInner(void *ctx) { uint8_t plainText[32]; uint8_t cipherText[512]; // RSA can have larger output uint32_t outLen = sizeof(cipherText); return CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen); } static int32_t RsaEnc(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(RsaEncInner(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "rsa enc"); return rc; } static int32_t RsaDec(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; uint8_t plainText[32]; uint32_t plainTextLen = sizeof(plainText); uint8_t cipherText[512]; // RSA can have larger output uint32_t outLen = sizeof(cipherText); rc = CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen); if (rc != CRYPT_SUCCESS) { printf("Failed to encrypt\n"); return rc; } BENCH_TIMES(CRYPT_EAL_PkeyDecrypt(ctx, cipherText, outLen, plainText, &plainTextLen), rc, CRYPT_SUCCESS, -1, opts->times, "rsa dec"); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { hashId = opts->hashId; } return hashId; } static int32_t RsaSignInner(void *ctx, int32_t hashId) { uint8_t plainText[32]; uint8_t signature[512]; // RSA can have larger signatures uint32_t signatureLen = sizeof(signature); return CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); } static int32_t RsaSign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } BENCH_TIMES(RsaSignInner(ctx, hashId), rc, CRYPT_SUCCESS, -1, opts->times, "rsa sign"); return rc; } static int32_t RsaVerify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } uint8_t plainText[32]; uint8_t signature[512]; // RSA can have larger signatures uint32_t signatureLen = sizeof(signature); rc = CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } BENCH_TIMES(CRYPT_EAL_PkeyVerify(ctx, hashId, plainText, sizeof(plainText), signature, signatureLen), rc, CRYPT_SUCCESS, -1, opts->times, "rsa verify"); return rc; } DEFINE_OPS(Rsa, CRYPT_PKEY_RSA, CRYPT_MD_SHA256); DEFINE_BENCH_CTX_FIXLEN(Rsa);
2301_79861745/bench_create
testcode/benchmark/rsa_bench.c
C
unknown
4,123
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "benchmark.h" static int32_t SlhDsaSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int rc = CRYPT_SUCCESS; CRYPT_PKEY_ParaId algId = paraId; rc = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_PARA_BY_ID, (void *)&algId, sizeof(algId)); if (rc != CRYPT_SUCCESS) { return rc; } rc = CRYPT_EAL_PkeyGen(pkeyCtx); if (rc != CRYPT_SUCCESS) { printf("Failed to gen slhdsa key.\n"); return rc; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void SlhDsaTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t SlhDsaKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; CRYPT_PKEY_ParaId paraId = opts->paraId; rc = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_PARA_BY_ID, (void *)&paraId, sizeof(paraId)); if (rc != CRYPT_SUCCESS) { return rc; } BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s keyGen", GetAlgName(paraId)); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { hashId = opts->hashId; } return hashId; } static int32_t SlhDsaSignInner(void *ctx, int32_t hashId, int32_t len) { static uint8_t sign[51200]; // maximum len is 49856 uint32_t signLen = sizeof(sign); return CRYPT_EAL_PkeySign(ctx, hashId, g_plain, len, sign, &signLen); } static int32_t SlhDsaSign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); BENCH_TIMES_VA(SlhDsaSignInner(ctx, hashId, opts->len), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s sign", GetAlgName(opts->paraId)); return rc; } static int32_t SlhDsaVerify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; static uint8_t sign[51200]; // maximum len is 49856 uint32_t signLen = sizeof(sign); int32_t hashId = GetHashId(bench, opts); rc = CRYPT_EAL_PkeySign(ctx, hashId, g_plain, opts->len, sign, &signLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } BENCH_TIMES_VA(CRYPT_EAL_PkeyVerify(ctx, hashId, g_plain, opts->len, sign, signLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s verify", GetAlgName(opts->paraId)); return rc; } static int32_t g_paraIds[] = { CRYPT_SLH_DSA_SHA2_128S, CRYPT_SLH_DSA_SHAKE_128S, CRYPT_SLH_DSA_SHA2_128F, CRYPT_SLH_DSA_SHAKE_128F, CRYPT_SLH_DSA_SHA2_192S, CRYPT_SLH_DSA_SHAKE_192S, CRYPT_SLH_DSA_SHA2_192F, CRYPT_SLH_DSA_SHAKE_192F, CRYPT_SLH_DSA_SHA2_256S, CRYPT_SLH_DSA_SHAKE_256S, CRYPT_SLH_DSA_SHA2_256F, CRYPT_SLH_DSA_SHAKE_256F, }; DEFINE_OPS_SIGN(SlhDsa, CRYPT_PKEY_SLH_DSA, CRYPT_MD_SHA256); DEFINE_BENCH_CTX_PARA_FIXLEN(SlhDsa, g_paraIds, SIZEOF(g_paraIds));
2301_79861745/bench_create
testcode/benchmark/slh_dsa_bench.c
C
unknown
3,723
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t Sm2SetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)paraId; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen sm2 key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void Sm2TearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t Sm2KeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 keyGen"); return rc; } static int32_t Sm2KeyDeriveInner(void *ctx, void *peerCtx) { int rc = CRYPT_SUCCESS; uint8_t localR[128] = {0}; rc = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)); if (rc != CRYPT_SUCCESS) { printf("Failed to generate R\n"); return rc; } uint8_t shareKey[64] = {0}; uint32_t shareKeyLen = sizeof(shareKey); rc = CRYPT_EAL_PkeyComputeShareKey(ctx, peerCtx, shareKey, &shareKeyLen); if (rc != CRYPT_SUCCESS) { printf("Failed to compute share key\n"); return rc; } return CRYPT_SUCCESS; } static int32_t Sm2KeyDerive(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; CRYPT_EAL_PkeyCtx *peerCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SM2); if (peerCtx == NULL || CRYPT_EAL_PkeyGen(peerCtx) != CRYPT_SUCCESS) { printf("Failed to create pkey context\n"); CRYPT_EAL_PkeyFreeCtx(peerCtx); rc = CRYPT_MEM_ALLOC_FAIL; goto ERR_OUT; } char *peerRHex = "04acc27688a6f7b706098bc91ff3ad1bff7dc2802cdb14ccccdb0a90471f9bd7072fedac0494b2ffc4d6853876c79b8f301c6573ad0aa50f39fc87181e1a1b46fe"; uint8_t peerR[128] = {0}; uint32_t peerRLen = sizeof(peerR); Hex2Bin(peerRHex, peerR, &peerRLen); rc = CRYPT_EAL_PkeyCtrl(peerCtx, CRYPT_CTRL_SET_SM2_R, peerR, peerRLen); if (rc != CRYPT_SUCCESS) { printf("Failed to set R\n"); goto ERR_OUT; } BENCH_TIMES(Sm2KeyDeriveInner(ctx, peerCtx), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 keyDerive"); ERR_OUT: CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } static int32_t Sm2EncInner(void *ctx) { uint8_t plainText[32]; uint8_t cipherText[256]; // > 32 + 97 + 12 uint32_t outLen = sizeof(cipherText); return CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen); } static int32_t Sm2Enc(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(Sm2EncInner(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 enc"); return rc; } static int32_t Sm2Dec(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; uint8_t plainText[32]; uint32_t plainTextLen = sizeof(plainText); uint8_t cipherText[256]; // > 32 + 97 + 12 uint32_t outLen = sizeof(cipherText); rc = CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen); if (rc != CRYPT_SUCCESS) { printf("Failed to encrypt\n"); return rc; } BENCH_TIMES(CRYPT_EAL_PkeyDecrypt(ctx, cipherText, outLen, plainText, &plainTextLen), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 dec"); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { if (CRYPT_EAL_MdGetDigestSize(opts->hashId) != 32) { printf("Wrong Hash Algorithm Id for Sm2."); return -1; } hashId = opts->hashId; } return hashId; } static int32_t Sm2SignInner(void *ctx, int32_t hashId) { uint8_t plainText[32]; uint8_t signature[256]; uint32_t signatureLen = sizeof(signature); return CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); } static int32_t Sm2Sign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } BENCH_TIMES(Sm2SignInner(ctx, hashId), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 sign"); return rc; } static int32_t Sm2Verify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } uint8_t plainText[32]; uint8_t signature[256]; uint32_t signatureLen = sizeof(signature); rc = CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } BENCH_TIMES(CRYPT_EAL_PkeyVerify(ctx, hashId, plainText, sizeof(plainText), signature, signatureLen), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 verify"); return rc; } DEFINE_OPS(Sm2, CRYPT_PKEY_SM2, CRYPT_MD_SM3); DEFINE_BENCH_CTX_FIXLEN(Sm2);
2301_79861745/bench_create
testcode/benchmark/sm2_bench.c
C
unknown
5,785
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <signal.h> #include <stdarg.h> #include <unistd.h> #include "securec.h" #define BUF_SIZE (65536 * 17) #define MAX_RAND_SIZE (1024 * 16) #define MAX_PATH 1024 #define MAX_FILE_NAME 200 #define MAX_IN_CASES 100000 #define OUTPUT_LINE_LENGTH 60 #ifdef FAIL_REPEAT_RUN #define FAIL_TRY_TIMES 3 #else #define FAIL_TRY_TIMES 0 #endif #define FUNCTION_LOG_FORMAT "./log/%s.%s.log" #define SUITE_LOG_FORMAT "./log/%s.log" #define LOCAL_DIR "./" typedef struct { char buf[MAX_DATA_LINE_LEN]; char *arg[MAX_ARGUMENT_COUNT]; char testVectorName[MAX_FILE_NAME]; uint32_t argLen; } TestArgs; typedef struct { void *param[MAX_ARGUMENT_COUNT]; int paramCount; int intParam[MAX_ARGUMENT_COUNT]; int intParamCount; Hex hexParam[MAX_ARGUMENT_COUNT]; int hexParamCount; } TestParam; static TestArgs *g_executeCases[MAX_IN_CASES]; static int g_executeCount = 0; static int ConvertStringCase(const TestArgs *arg) { for (uint32_t i = 1; i < arg->argLen; i += 2) { if (strcmp(arg->arg[i], "char") == 0 || strcmp(arg->arg[i], "Hex") == 0) { if (ConvertString((char **)&(arg->arg[i+1])) != 0) { return 1; } } } return 0; } static int LoadDataFile(const char *fileName) { if (g_executeCount > 0) { return 0; } FILE *fpDatax = fopen(fileName, "r"); if (fpDatax == NULL) { Print("Error opening file\n"); return (-1); } int rt = 0; for (int i = 0; i < MAX_IN_CASES; i++) { g_executeCases[i] = (TestArgs *)malloc(sizeof(TestArgs)); if (g_executeCases[i] == NULL) { rt = -1; goto EXIT; } g_executeCases[i]->argLen = MAX_ARGUMENT_COUNT; if (ReadLine(fpDatax, g_executeCases[i]->testVectorName, MAX_FILE_NAME, 1, 1) != 0) { free(g_executeCases[i]); goto EXIT; } if (ReadLine(fpDatax, g_executeCases[i]->buf, MAX_DATA_LINE_LEN, 1, 1) != 0) { free(g_executeCases[i]); Print("Read vector failed, test vector should have 2 lines, here there's only one\n"); rt = -1; goto EXIT; } if (SplitArguments(g_executeCases[i]->buf, strlen(g_executeCases[i]->buf), g_executeCases[i]->arg, &(g_executeCases[i]->argLen)) != 0) { free(g_executeCases[i]); rt = -1; goto EXIT; } if (ConvertStringCase(g_executeCases[i]) == 1) { free(g_executeCases[i]); rt = -1; goto EXIT; } g_executeCount += 1; } char tmpName[MAX_FILE_NAME]; if (ReadLine(fpDatax, tmpName, MAX_FILE_NAME, 1, 1) == 0) { Print("More test cases than max case num %d\n", MAX_IN_CASES); rt = -1; } EXIT: if (rt != 0) { for (int i = 0; i < g_executeCount; i++) { free(g_executeCases[i]); } g_executeCount = 0; } (void)fclose(fpDatax); return rt; }
2301_79861745/bench_create
testcode/common/execute_base.c
C
unknown
3,546
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <setjmp.h> #include <time.h> #include <sys/time.h> static jmp_buf env; static int isSubProc = 0; int *GetJmpAddress(void) { return &isSubProc; } void handleSignal() { siglongjmp(env, 1); } static void PrintCaseName(FILE *logFile, bool showDetail, const char *name) { // print a minimum of 4 dots int32_t dotCount = (OUTPUT_LINE_LENGTH - (int32_t)strlen(name) >= 4) ? (OUTPUT_LINE_LENGTH - (int32_t)strlen(name)) : 4; if (showDetail) { Print("%s", name); for (int32_t j = 0; j < dotCount; j++) { Print("."); } } (void)fprintf(logFile, "%s", name); for (int32_t j = 0; j < dotCount; j++) { (void)fprintf(logFile, "."); } } static int ParseArgs(const TestArgs *arg, TestParam *info) { info->hexParamCount = 0; info->intParamCount = 0; info->paramCount = 0; for (uint32_t i = 1; i < arg->argLen; i += 2) { // 2 if (strcmp(arg->arg[i], "int") == 0) { if (ConvertInt(arg->arg[i + 1], &(info->intParam[info->intParamCount])) == 0) { info->param[info->paramCount] = &(info->intParam[info->intParamCount]); info->intParamCount++; } else { Print("\nERROR: Int param conversion failed for:\n\"%s\"\n", arg->arg[i + 1]); return 1; } } else if (strcmp(arg->arg[i], "char") == 0) { info->param[info->paramCount] = arg->arg[i+1]; } else if (strcmp(arg->arg[i], "Hex") == 0) { if (ConvertHex(arg->arg[i + 1], &(info->hexParam[info->hexParamCount])) != 0) { Print("\nERROR: Hex param conversion failed for:\n\"%s\"\n", arg->arg[i + 1]); return 1; } info->param[info->paramCount] = &(info->hexParam[info->hexParamCount]); info->hexParamCount++; } else if (strcmp(arg->arg[i], "exp") == 0) { int expId = 0; if (ConvertInt(arg->arg[i + 1], &expId) != 0 || getExpression(expId, &(info->intParam[info->intParamCount])) != 0) { Print("\nERROR: Macro param conversion failed\n"); return 1; } info->param[info->paramCount] = &(info->intParam[info->intParamCount]); info->intParamCount++; } else { return 1; } info->paramCount++; } return 0; } static int PrintCaseNameResult(FILE *logFile, int vectorCount, int skipCount, int passCount, time_t beginTime) { char suitePrefix[OUTPUT_LINE_LENGTH] = {0}; (void)snprintf_truncated_s(suitePrefix, sizeof(suitePrefix), "%s", suiteName); size_t leftSize = sizeof(suitePrefix) - 1 - strlen(suitePrefix); if (leftSize > 0) { (void)memset_s(suitePrefix + strlen(suitePrefix), sizeof(suitePrefix) - strlen(suitePrefix), '.', leftSize); } int failCount = vectorCount - passCount - skipCount; if (failCount == 0) { Print("%sPASS || Run %-6d testcases, passed: %-6d, skipped: %-6d, failed: %-6d useSec:%-5lu\n", suitePrefix, vectorCount, passCount, skipCount, failCount, time(NULL) - beginTime); } else { Print("%sFAIL || Run %-6d testcases, passed: %-6d, skipped: %-6d, failed: %-6d useSec:%-5lu\n", suitePrefix, vectorCount, passCount, skipCount, failCount, time(NULL) - beginTime); } time_t rawtime; struct tm *timeinfo; (void)time(&rawtime); timeinfo = localtime(&rawtime); (void)fprintf(logFile, "End time: %s", asctime(timeinfo)); (void)fprintf(logFile, "Result: Run %d tests, Passed: %d, Skipped: %d, Failed: %d\n", vectorCount, passCount, skipCount, failCount); return failCount; } static int ProcessCases(FILE *logFile, bool showDetail, int targetFuncId) { (void)logFile; volatile int vectorCount = 0; volatile int passCount = 0; volatile int skipCount = 0; volatile int tryNum; time_t beginTime = time(NULL); struct timespec start, end; for (volatile int i = 0; i < g_executeCount; i++) { int funcId = strtoul(g_executeCases[i]->arg[0], NULL, 10); // 10 if (funcId < 0 || funcId > ((int)(sizeof(test_funcs)/sizeof(TestWrapper)))) { Print("funcId false!\n"); return 1; } if ((targetFuncId != -1) && (funcId != targetFuncId)) { continue; } (void)fprintf(logFile, "%s ", funcName[funcId]); PrintCaseName(logFile, showDetail, g_executeCases[i]->testVectorName); TestParam io; if (ParseArgs(g_executeCases[i], &io) != 0) { return -1; } TestWrapper fp = test_funcs[funcId]; g_testResult.result = TEST_RESULT_SUCCEED; tryNum = 0; clock_gettime(CLOCK_REALTIME, &start); do { if (tryNum > 0) { sleep(10); g_testResult.result = TEST_RESULT_SUCCEED; } tryNum++; #ifdef ASAN fp(io.param); #else // Executing Function if (signal(SIGSEGV, handleSignal) == SIG_ERR) { return -1; } int r = sigsetjmp(env, 1); if (r == 0) { fp(io.param); } else if (r == 1){ g_testResult.result = TEST_RESULT_FAILED; } if (isSubProc != 0) { break; } #endif } while ((g_testResult.result == TEST_RESULT_FAILED) && (tryNum < FAIL_TRY_TIMES)); if (g_testResult.result == TEST_RESULT_SUCCEED) { passCount++; } else if (g_testResult.result == TEST_RESULT_SKIPPED) { skipCount++; } vectorCount++; clock_gettime(CLOCK_REALTIME, &end); uint64_t elapsedms = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_nsec - start.tv_nsec) / 1000000; PrintResult(showDetail, g_executeCases[i]->testVectorName, elapsedms); PrintLog(logFile); for (int j = 0; j < io.hexParamCount; j++) { FreeHex(&io.hexParam[j]); } if (isSubProc != 0) { break; } } return PrintCaseNameResult(logFile, vectorCount, skipCount, passCount, beginTime); } static int ExecuteTest(const char *fileName, bool showDetail, int targetFuncId) { if (LoadDataFile(fileName) != 0) { return -1; } FILE *logFile = NULL; char logFileName[MAX_FILE_NAME] = {0}; if (targetFuncId == -1) { if (sprintf_s(logFileName, MAX_FILE_NAME, SUITE_LOG_FORMAT, suiteName) <= 0) { Print("An error occurred while creating the log file\n"); return (-1); } } else { if (sprintf_s(logFileName, MAX_FILE_NAME, FUNCTION_LOG_FORMAT, suiteName, funcName[targetFuncId]) <= 0) { Print("An error occurred while creating the log file\n"); return (-1); } } time_t rawtime = time(NULL); if (rawtime == 0) { return -1; } logFile = fopen(logFileName, "w"); if (logFile != NULL) { struct tm *timeinfo; timeinfo = localtime(&rawtime); if (fprintf(logFile, "Begin time: %s", asctime(timeinfo)) <= 0) { fclose(logFile); return -1; } } int rt = ProcessCases(logFile, showDetail, targetFuncId); if (logFile != NULL) { fclose(logFile); } return rt; } int ProcessMutiArgs(int argc, char **argv, const char *fileName) { int printDetail = 1; int curTestCnt = 0; int ret = -1; int testCnt = sizeof(test_funcs) / sizeof(test_funcs[0]); int *funcIndex = malloc(sizeof(int) * testCnt); int found; if (funcIndex == NULL) { return ret; } for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "NO_DETAIL") == 0) { printDetail = 0; continue; } found = 0; for (int j = 0; j < testCnt; j++) { if (strcmp(argv[i], funcName[j]) == 0) { funcIndex[curTestCnt++] = j; found = 1; break; } } if (found != 1) { Print("test function '%s' do not exist\n", argv[i]); goto EXIT; } } if (curTestCnt == 0) { ret = ExecuteTest(fileName, printDetail, -1); goto EXIT; } for (int i = 0; i < curTestCnt; i++) { if (ExecuteTest(fileName, printDetail, funcIndex[i]) != 0) { goto EXIT; } } ret = 0; EXIT: free(funcIndex); return ret; } int main(int argc, char **argv) { signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); int ret = 0; #ifndef PRINT_TO_TERMINAL char testOutputName[MAX_FILE_NAME] = {0}; if (sprintf_s(testOutputName, MAX_FILE_NAME, "%s.output", suiteName) <= 0) { return 0; } FILE *fp = fopen(testOutputName, "w"); if (fp == NULL) { return 1; } SetOutputFile(fp); #endif char testName[MAX_FILE_PATH_LEN]; if (sprintf_s(testName, MAX_FILE_PATH_LEN, "%s.datax", suiteName) <= 0) { goto EXIT; } if (argc == 1) { ret = ExecuteTest(testName, 1, -1); } else { ret = ProcessMutiArgs(argc, argv, testName); } if (ret != 0) { Print("execute test failed\n"); } for (int i = 0; i < g_executeCount; i++) { free(g_executeCases[i]); } EXIT: #ifndef PRINT_TO_TERMINAL (void)fclose(fp); #endif return ret; }
2301_79861745/bench_create
testcode/common/execute_test.c
C
unknown
9,964
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. cmake_minimum_required(VERSION 3.16 FATAL_ERROR) project(demo) message(status "HITLS_ROOT: ${HITLS_ROOT}") set(HITLS_ROOT ../..) set(HITLS_INCLUDE ${HITLS_ROOT}/include/bsl ${HITLS_ROOT}/include/crypto ${HITLS_ROOT}/include/tls ${HITLS_ROOT}/include/pki ${HITLS_ROOT}/include/auth ${HITLS_ROOT}/config/macro_config ${HITLS_ROOT}/platform/Secure_C/include) if(CUSTOM_CFLAGS) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CUSTOM_CFLAGS}") endif() if(ENABLE_GCOV) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage -lgcov") endif() if(ENABLE_ASAN) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address -fno-stack-protector -fno-omit-frame-pointer") endif() add_library(DEMO_INTF INTERFACE) target_compile_options(DEMO_INTF INTERFACE -g) target_link_directories(DEMO_INTF INTERFACE ${HITLS_ROOT}/build ${HITLS_ROOT}/platform/Secure_C/lib/) target_link_libraries(DEMO_INTF INTERFACE hitls_tls hitls_pki hitls_auth hitls_crypto hitls_bsl boundscheck pthread dl) target_include_directories(DEMO_INTF INTERFACE ${HITLS_INCLUDE}) file(GLOB TESTS "*.c") foreach(testcase ${TESTS}) get_filename_component(testname ${testcase} NAME_WLE) add_executable(${testname} ${testcase}) target_link_libraries(${testname} PRIVATE DEMO_INTF) endforeach()
2301_79861745/bench_create
testcode/demo/CMakeLists.txt
CMake
unknown
1,948
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_eal_init.h" #include "crypt_algid.h" #include "crypt_eal_rand.h" #include "hitls_error.h" #include "hitls_config.h" #include "hitls.h" #include "hitls_cert_init.h" #include "hitls_cert.h" #include "hitls_crypt_init.h" #include "hitls_pki_cert.h" #include "crypt_errno.h" #define CERTS_PATH "../../../testcode/testdata/tls/certificate/der/ecdsa_sha256/" #define HTTP_BUF_MAXLEN (18 * 1024) /* 18KB */ int main(int32_t argc, char *argv[]) { int32_t exitValue = -1; int32_t ret = 0; HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; BSL_UIO *uio = NULL; int fd = 0; HITLS_X509_Cert *rootCA = NULL; HITLS_X509_Cert *subCA = NULL; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); return ret; } HITLS_CertMethodInit(); HITLS_CryptMethodInit(); fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { printf("Create socket failed.\n"); goto EXIT; } int option = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) { close(fd); printf("setsockopt SO_REUSEADDR failed.\n"); goto EXIT; } // Set the protocol and port number struct sockaddr_in serverAddr; (void)memset_s(&serverAddr, sizeof(serverAddr), 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(12345); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); if (connect(fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 0) { printf("connect failed.\n"); goto EXIT; } config = HITLS_CFG_NewTLS12Config(); if (config == NULL) { printf("HITLS_CFG_NewTLS12Config failed.\n"); goto EXIT; } ret = HITLS_CFG_SetCheckKeyUsage(config, false); // disable cert keyusage check if (ret != HITLS_SUCCESS) { printf("Disable check KeyUsage failed.\n"); goto EXIT; } /* 加载证书:需要用户实现 */ ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, CERTS_PATH "ca.der", &rootCA); if (ret != HITLS_SUCCESS) { printf("Parse ca failed.\n"); goto EXIT; } ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, CERTS_PATH "inter.der", &subCA); if (ret != HITLS_SUCCESS) { printf("Parse subca failed.\n"); goto EXIT; } HITLS_CFG_AddCertToStore(config, rootCA, TLS_CERT_STORE_TYPE_DEFAULT, true); HITLS_CFG_AddCertToStore(config, subCA, TLS_CERT_STORE_TYPE_DEFAULT, true); /* 新建openHiTLS上下文 */ ctx = HITLS_New(config); if (ctx == NULL) { printf("HITLS_New failed.\n"); goto EXIT; } uio = BSL_UIO_New(BSL_UIO_TcpMethod()); if (uio == NULL) { printf("BSL_UIO_New failed.\n"); goto EXIT; } ret = BSL_UIO_Ctrl(uio, BSL_UIO_SET_FD, (int32_t)sizeof(fd), &fd); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("BSL_UIO_SET_FD failed, fd = %u.\n", fd); goto EXIT; } ret = HITLS_SetUio(ctx, uio); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("HITLS_SetUio failed. ret = 0x%x.\n", ret); goto EXIT; } /* 进行TLS连接、用户需按实际场景考虑返回值 */ ret = HITLS_Connect(ctx); if (ret != HITLS_SUCCESS) { printf("HITLS_Connect failed, ret = 0x%x.\n", ret); goto EXIT; } /* 向对端发送报文、用户需按实际场景考虑返回值 */ const uint8_t sndBuf[] = "Hi, this is client\n"; uint32_t writeLen = 0; ret = HITLS_Write(ctx, sndBuf, sizeof(sndBuf), &writeLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Write error:error code:%d\n", ret); goto EXIT; } /* 读取对端报文、用户需按实际场景考虑返回值 */ uint8_t readBuf[HTTP_BUF_MAXLEN + 1] = {0}; uint32_t readLen = 0; ret = HITLS_Read(ctx, readBuf, HTTP_BUF_MAXLEN, &readLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Read failed, ret = 0x%x.\n", ret); goto EXIT; } printf("get from server size:%u :%s\n", readLen, readBuf); exitValue = 0; EXIT: HITLS_Close(ctx); HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); close(fd); HITLS_X509_CertFree(rootCA); HITLS_X509_CertFree(subCA); BSL_UIO_Free(uio); return exitValue; }
2301_79861745/bench_create
testcode/demo/client.c
C
unknown
4,608
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "crypt_types.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_eal_init.h" #include "crypt_errno.h" #include "crypt_eal_rand.h" void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } int main(void) { int ret; uint8_t output[100] = {0}; uint32_t len = 100; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); return ret; } // Obtain the random number sequence of the **len** value. ret = CRYPT_EAL_RandbytesEx(NULL, output, len); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Randbytes: error code is %x\n", ret); PrintLastError(); goto EXIT; } printf("random value is: "); // Output the random number. for (uint32_t i = 0; i < len; i++) { printf("%02x", output[i]); } printf("\n"); // Reseeding ret = CRYPT_EAL_RandSeedEx(NULL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_RandSeed: error code is %x\n", ret); PrintLastError(); goto EXIT; } // Obtain the random number sequence of the **len** value. ret = CRYPT_EAL_RandbytesEx(NULL, output, len); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Randbytes: error code is %x\n", ret); PrintLastError(); goto EXIT; } printf("random value is: "); // Output the random number. for (uint32_t i = 0; i < len; i++) { printf("%02x", output[i]); } printf("\n"); EXIT: // Release the context memory. CRYPT_EAL_RandDeinit(); BSL_ERR_DeInit(); return 0; }
2301_79861745/bench_create
testcode/demo/drbg.c
C
unknown
2,396
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "crypt_types.h" #include "crypt_eal_pkey.h" // Header file for key exchange. #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_eal_init.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_rand.h" void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } int main(void) { int ret; uint8_t prikey[] = {0x7d, 0x7d, 0xc5, 0xf7, 0x1e, 0xb2, 0x9d, 0xda, 0xf8, 0x0d, 0x62, 0x14, 0x63, 0x2e, 0xea, 0xe0, 0x3d, 0x90, 0x58, 0xaf, 0x1f, 0xb6, 0xd2, 0x2e, 0xd8, 0x0b, 0xad, 0xb6, 0x2b, 0xc1, 0xa5, 0x34}; uint8_t pubkey[] = {0x04, 0x70, 0x0c, 0x48, 0xf7, 0x7f, 0x56, 0x58, 0x4c, 0x5c, 0xc6, 0x32, 0xca, 0x65, 0x64, 0x0d, 0xb9, 0x1b, 0x6b, 0xac, 0xce, 0x3a, 0x4d, 0xf6, 0xb4, 0x2c, 0xe7, 0xcc, 0x83, 0x88, 0x33, 0xd2, 0x87, 0xdb, 0x71, 0xe5, 0x09, 0xe3, 0xfd, 0x9b, 0x06, 0x0d, 0xdb, 0x20, 0xba, 0x5c, 0x51, 0xdc, 0xc5, 0x94, 0x8d, 0x46, 0xfb, 0xf6, 0x40, 0xdf, 0xe0, 0x44, 0x17, 0x82, 0xca, 0xb8, 0x5f, 0xa4, 0xac}; uint8_t resSharekey[] = {0x46, 0xfc, 0x62, 0x10, 0x64, 0x20, 0xff, 0x01, 0x2e, 0x54, 0xa4, 0x34, 0xfb, 0xdd, 0x2d, 0x25, 0xcc, 0xc5, 0x85, 0x20, 0x60, 0x56, 0x1e, 0x68, 0x04, 0x0d, 0xd7, 0x77, 0x89, 0x97, 0xbd, 0x7b}; CRYPT_EAL_PkeyPrv prvKey = {0}; CRYPT_EAL_PkeyPub pubKey = {0}; uint32_t shareLen; uint8_t *shareKey; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyCtx *pubCtx = NULL; CRYPT_PKEY_ParaId id = CRYPT_ECC_NISTP256; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); goto EXIT; } prvCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); pubCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); if (prvCtx == NULL || pubCtx == NULL) { goto EXIT; } // Set the curve parameters. ret = CRYPT_EAL_PkeySetParaById(prvCtx, id); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the private key of one end. prvKey.id = CRYPT_PKEY_ECDH; prvKey.key.eccPrv.len = sizeof(prikey); prvKey.key.eccPrv.data = prikey; ret = CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the curve parameters. ret = CRYPT_EAL_PkeySetParaById(pubCtx, id); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the public key of the other end. pubKey.id = CRYPT_PKEY_ECDH; pubKey.key.eccPub.len = sizeof(pubkey); pubKey.key.eccPub.data = pubkey; ret = CRYPT_EAL_PkeySetPub(pubCtx, &pubKey); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // The shared key involves only the X axis. The length of the public key is not compressed in the returned results. shareLen = CRYPT_EAL_PkeyGetKeyLen(prvCtx) / 2; shareKey = (uint8_t *)BSL_SAL_Malloc(shareLen); if (shareKey == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; PrintLastError(); goto EXIT; } // Calculate the shared key. ret = CRYPT_EAL_PkeyComputeShareKey(prvCtx, pubCtx, shareKey, &shareLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Compare the calculation result with the expected one. if (shareLen != sizeof(resSharekey) || memcmp(shareKey, resSharekey, shareLen) != 0) { printf("failed to compare test results\n"); ret = -1; goto EXIT; } printf("pass \n"); EXIT: // Release the context memory. CRYPT_EAL_RandDeinit(); CRYPT_EAL_PkeyFreeCtx(prvCtx); CRYPT_EAL_PkeyFreeCtx(pubCtx); BSL_SAL_Free(shareKey); BSL_ERR_DeInit(); return 0; }
2301_79861745/bench_create
testcode/demo/ecdh.c
C
unknown
4,715
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "crypt_errno.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_eal_md.h" #define PBKDF2_PARAM_LEN (4) void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } int main(void) { int ret = 0; CRYPT_EAL_MdCTX *ctx = NULL; uint8_t digest[32] = {0}; unsigned int digestLen = 32; uint8_t data[] = {0x1b, 0x50, 0x3f, 0xb9, 0xa7, 0x3b, 0x16, 0xad, 0xa3, 0xfc, 0xf1, 0x04, 0x26, 0x23, 0xae, 0x76, 0x10}; uint8_t expResult[] = {0xd5, 0xc3, 0x03, 0x15, 0xf7, 0x2e, 0xd0, 0x5f, 0xe5, 0x19, 0xa1, 0xbf, 0x75, 0xab, 0x5f, 0xd0, 0xff, 0xec, 0x5a, 0xc1, 0xac, 0xb0, 0xda, 0xf6, 0x6b, 0x6b, 0x76, 0x95, 0x98, 0x59, 0x45, 0x09}; ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA256); if (ctx == NULL) { PrintLastError(); goto EXIT; } ret = CRYPT_EAL_MdInit(ctx); if (ret != 0) { PrintLastError(); goto EXIT; } ret = CRYPT_EAL_MdUpdate(ctx, data, sizeof(data)); if (ret != 0) { PrintLastError(); goto EXIT; } ret = CRYPT_EAL_MdFinal(ctx, digest, &digestLen); if (ret != 0) { PrintLastError(); goto EXIT; } printf("hash result: "); for (uint32_t i = 0; i < digestLen; i++) { printf("%02x", digest[i]); } printf("\n"); // result compare if (digestLen != sizeof(expResult) || memcmp(expResult, digest, digestLen) != 0) { printf("hash result comparison failed\n"); goto EXIT; } printf("pass \n"); EXIT: BSL_ERR_DeInit(); CRYPT_EAL_MdFreeCtx(ctx); return ret; }
2301_79861745/bench_create
testcode/demo/hash.c
C
unknown
2,355
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "crypt_errno.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_eal_kdf.h" #include "bsl_params.h" #include "crypt_params_key.h" #define PBKDF2_PARAM_LEN (4) void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } int main(void) { int32_t ret; uint8_t key[] = {0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64}; uint8_t salt[] = {0x4e, 0x61, 0x43, 0x6c}; uint32_t iterations = 80000; uint8_t result[] = { 0x4d, 0xdc, 0xd8, 0xf6, 0x0b, 0x98, 0xbe, 0x21, 0x83, 0x0c, 0xee, 0x5e, 0xf2, 0x27, 0x01, 0xf9, 0x64, 0x1a, 0x44, 0x18, 0xd0, 0x4c, 0x04, 0x14, 0xae, 0xff, 0x08, 0x87, 0x6b, 0x34, 0xab, 0x56, 0xa1, 0xd4, 0x25, 0xa1, 0x22, 0x58, 0x33, 0x54, 0x9a, 0xdb, 0x84, 0x1b, 0x51, 0xc9, 0xb3, 0x17, 0x6a, 0x27, 0x2b, 0xde, 0xbb, 0xa1, 0xd0, 0x78, 0x47, 0x8f, 0x62, 0xb3, 0x97, 0xf3, 0x3c, 0x8d}; uint8_t out[sizeof(result)] = {0}; uint32_t outLen = sizeof(result); CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_PBKDF2); if (ctx == NULL) { PrintLastError(); goto EXIT; } CRYPT_MAC_AlgId id = CRYPT_MAC_HMAC_SHA256; BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &id, sizeof(id)); (void)BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key, sizeof(key)); (void)BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, sizeof(salt)); (void)BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &iterations, sizeof(iterations)); ret = CRYPT_EAL_KdfSetParam(ctx, params); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } ret = CRYPT_EAL_KdfDerive(ctx, out, outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } if (memcmp(out, result, sizeof(result)) != 0) { printf("failed to compare test results\n"); ret = -1; goto EXIT; } printf("pass \n"); EXIT: BSL_ERR_DeInit(); CRYPT_EAL_KdfFreeCtx(ctx); return ret; }
2301_79861745/bench_create
testcode/demo/pbkdf2.c
C
unknown
3,047
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include "auth_privpass_token.h" #include "auth_params.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_eal_init.h" #include "crypt_eal_rand.h" #include "auth_errno.h" #include "crypt_errno.h" uint8_t pubKey[] = {0x30, 0x82, 0x01, 0x52, 0x30, 0x3d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0a, 0x30, 0x30, 0xa0, 0x0d, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0xa1, 0x1a, 0x30, 0x18, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x08, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0xa2, 0x03, 0x02, 0x01, 0x30, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xcb, 0x1a, 0xed, 0x6b, 0x6a, 0x95, 0xf5, 0xb1, 0xce, 0x01, 0x3a, 0x4c, 0xfc, 0xab, 0x25, 0xb9, 0x4b, 0x2e, 0x64, 0xa2, 0x30, 0x34, 0xe4, 0x25, 0x0a, 0x7e, 0xab, 0x43, 0xc0, 0xdf, 0x3a, 0x8c, 0x12, 0x99, 0x3a, 0xf1, 0x2b, 0x11, 0x19, 0x08, 0xd4, 0xb4, 0x71, 0xbe, 0xc3, 0x1d, 0x4b, 0x6c, 0x9a, 0xd9, 0xcd, 0xda, 0x90, 0x61, 0x2a, 0x2e, 0xe9, 0x03, 0x52, 0x3e, 0x6d, 0xe5, 0xa2, 0x24, 0xd6, 0xb0, 0x2f, 0x09, 0xe5, 0xc3, 0x74, 0xd0, 0xcf, 0xe0, 0x1d, 0x8f, 0x52, 0x9c, 0x50, 0x0a, 0x78, 0xa2, 0xf6, 0x79, 0x08, 0xfa, 0x68, 0x2b, 0x5a, 0x2b, 0x43, 0x0c, 0x81, 0xea, 0xf1, 0xaf, 0x72, 0xd7, 0xb5, 0xe7, 0x94, 0xfc, 0x98, 0xa3, 0x13, 0x92, 0x76, 0x87, 0x97, 0x57, 0xce, 0x45, 0x3b, 0x52, 0x6e, 0xf9, 0xbf, 0x6c, 0xeb, 0x99, 0x97, 0x9b, 0x84, 0x23, 0xb9, 0x0f, 0x44, 0x61, 0xa2, 0x2a, 0xf3, 0x7a, 0xab, 0x0c, 0xf5, 0x73, 0x3f, 0x75, 0x97, 0xab, 0xe4, 0x4d, 0x31, 0xc7, 0x32, 0xdb, 0x68, 0xa1, 0x81, 0xc6, 0xcb, 0xbe, 0x60, 0x7d, 0x8c, 0x0e, 0x52, 0xe0, 0x65, 0x5f, 0xd9, 0x99, 0x6d, 0xc5, 0x84, 0xec, 0xa0, 0xbe, 0x87, 0xaf, 0xbc, 0xd7, 0x8a, 0x33, 0x7d, 0x17, 0xb1, 0xdb, 0xa9, 0xe8, 0x28, 0xbb, 0xd8, 0x1e, 0x29, 0x13, 0x17, 0x14, 0x4e, 0x7f, 0xf8, 0x9f, 0x55, 0x61, 0x97, 0x09, 0xb0, 0x96, 0xcb, 0xb9, 0xea, 0x47, 0x4c, 0xea, 0xd2, 0x64, 0xc2, 0x07, 0x3f, 0xe4, 0x97, 0x40, 0xc0, 0x1f, 0x00, 0xe1, 0x09, 0x10, 0x60, 0x66, 0x98, 0x3d, 0x21, 0xe5, 0xf8, 0x3f, 0x08, 0x6e, 0x2e, 0x82, 0x3c, 0x87, 0x9c, 0xd4, 0x3c, 0xef, 0x70, 0x0d, 0x2a, 0x35, 0x2a, 0x9b, 0xab, 0xd6, 0x12, 0xd0, 0x3c, 0xad, 0x02, 0xdb, 0x13, 0x4b, 0x7e, 0x22, 0x5a, 0x5f, 0x02, 0x03, 0x01, 0x00, 0x01}; uint8_t privKey[] = {0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x42, 0x45, 0x47, 0x49, 0x4E, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4B, 0x45, 0x59, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x0A, 0x4D, 0x49, 0x49, 0x45, 0x76, 0x51, 0x49, 0x42, 0x41, 0x44, 0x41, 0x4E, 0x42, 0x67, 0x6B, 0x71, 0x68, 0x6B, 0x69, 0x47, 0x39, 0x77, 0x30, 0x42, 0x41, 0x51, 0x45, 0x46, 0x41, 0x41, 0x53, 0x43, 0x42, 0x4B, 0x63, 0x77, 0x67, 0x67, 0x53, 0x6A, 0x41, 0x67, 0x45, 0x41, 0x41, 0x6F, 0x49, 0x42, 0x41, 0x51, 0x44, 0x4C, 0x47, 0x75, 0x31, 0x72, 0x61, 0x70, 0x58, 0x31, 0x73, 0x63, 0x34, 0x42, 0x0A, 0x4F, 0x6B, 0x7A, 0x38, 0x71, 0x79, 0x57, 0x35, 0x53, 0x79, 0x35, 0x6B, 0x6F, 0x6A, 0x41, 0x30, 0x35, 0x43, 0x55, 0x4B, 0x66, 0x71, 0x74, 0x44, 0x77, 0x4E, 0x38, 0x36, 0x6A, 0x42, 0x4B, 0x5A, 0x4F, 0x76, 0x45, 0x72, 0x45, 0x52, 0x6B, 0x49, 0x31, 0x4C, 0x52, 0x78, 0x76, 0x73, 0x4D, 0x64, 0x53, 0x32, 0x79, 0x61, 0x32, 0x63, 0x33, 0x61, 0x6B, 0x47, 0x45, 0x71, 0x4C, 0x75, 0x6B, 0x44, 0x0A, 0x55, 0x6A, 0x35, 0x74, 0x35, 0x61, 0x49, 0x6B, 0x31, 0x72, 0x41, 0x76, 0x43, 0x65, 0x58, 0x44, 0x64, 0x4E, 0x44, 0x50, 0x34, 0x42, 0x32, 0x50, 0x55, 0x70, 0x78, 0x51, 0x43, 0x6E, 0x69, 0x69, 0x39, 0x6E, 0x6B, 0x49, 0x2B, 0x6D, 0x67, 0x72, 0x57, 0x69, 0x74, 0x44, 0x44, 0x49, 0x48, 0x71, 0x38, 0x61, 0x39, 0x79, 0x31, 0x37, 0x58, 0x6E, 0x6C, 0x50, 0x79, 0x59, 0x6F, 0x78, 0x4F, 0x53, 0x0A, 0x64, 0x6F, 0x65, 0x58, 0x56, 0x38, 0x35, 0x46, 0x4F, 0x31, 0x4A, 0x75, 0x2B, 0x62, 0x39, 0x73, 0x36, 0x35, 0x6D, 0x58, 0x6D, 0x34, 0x51, 0x6A, 0x75, 0x51, 0x39, 0x45, 0x59, 0x61, 0x49, 0x71, 0x38, 0x33, 0x71, 0x72, 0x44, 0x50, 0x56, 0x7A, 0x50, 0x33, 0x57, 0x58, 0x71, 0x2B, 0x52, 0x4E, 0x4D, 0x63, 0x63, 0x79, 0x32, 0x32, 0x69, 0x68, 0x67, 0x63, 0x62, 0x4C, 0x76, 0x6D, 0x42, 0x39, 0x0A, 0x6A, 0x41, 0x35, 0x53, 0x34, 0x47, 0x56, 0x66, 0x32, 0x5A, 0x6C, 0x74, 0x78, 0x59, 0x54, 0x73, 0x6F, 0x4C, 0x36, 0x48, 0x72, 0x37, 0x7A, 0x58, 0x69, 0x6A, 0x4E, 0x39, 0x46, 0x37, 0x48, 0x62, 0x71, 0x65, 0x67, 0x6F, 0x75, 0x39, 0x67, 0x65, 0x4B, 0x52, 0x4D, 0x58, 0x46, 0x45, 0x35, 0x2F, 0x2B, 0x4A, 0x39, 0x56, 0x59, 0x5A, 0x63, 0x4A, 0x73, 0x4A, 0x62, 0x4C, 0x75, 0x65, 0x70, 0x48, 0x0A, 0x54, 0x4F, 0x72, 0x53, 0x5A, 0x4D, 0x49, 0x48, 0x50, 0x2B, 0x53, 0x58, 0x51, 0x4D, 0x41, 0x66, 0x41, 0x4F, 0x45, 0x4A, 0x45, 0x47, 0x42, 0x6D, 0x6D, 0x44, 0x30, 0x68, 0x35, 0x66, 0x67, 0x2F, 0x43, 0x47, 0x34, 0x75, 0x67, 0x6A, 0x79, 0x48, 0x6E, 0x4E, 0x51, 0x38, 0x37, 0x33, 0x41, 0x4E, 0x4B, 0x6A, 0x55, 0x71, 0x6D, 0x36, 0x76, 0x57, 0x45, 0x74, 0x41, 0x38, 0x72, 0x51, 0x4C, 0x62, 0x0A, 0x45, 0x30, 0x74, 0x2B, 0x49, 0x6C, 0x70, 0x66, 0x41, 0x67, 0x4D, 0x42, 0x41, 0x41, 0x45, 0x43, 0x67, 0x67, 0x45, 0x41, 0x4C, 0x7A, 0x43, 0x62, 0x64, 0x7A, 0x69, 0x31, 0x6A, 0x50, 0x64, 0x35, 0x38, 0x4D, 0x6B, 0x56, 0x2B, 0x43, 0x4C, 0x66, 0x79, 0x66, 0x53, 0x51, 0x32, 0x2B, 0x72, 0x66, 0x48, 0x6E, 0x72, 0x66, 0x72, 0x46, 0x65, 0x50, 0x2F, 0x56, 0x63, 0x44, 0x78, 0x72, 0x75, 0x69, 0x0A, 0x32, 0x70, 0x31, 0x61, 0x53, 0x58, 0x4A, 0x59, 0x69, 0x62, 0x65, 0x36, 0x45, 0x53, 0x2B, 0x4D, 0x62, 0x2F, 0x4D, 0x46, 0x55, 0x64, 0x6C, 0x48, 0x50, 0x67, 0x41, 0x4C, 0x77, 0x31, 0x78, 0x51, 0x34, 0x57, 0x65, 0x72, 0x66, 0x36, 0x63, 0x36, 0x44, 0x43, 0x73, 0x68, 0x6C, 0x6C, 0x78, 0x4C, 0x57, 0x53, 0x56, 0x38, 0x47, 0x73, 0x42, 0x73, 0x76, 0x63, 0x38, 0x6F, 0x36, 0x47, 0x50, 0x32, 0x0A, 0x63, 0x59, 0x36, 0x6F, 0x77, 0x70, 0x42, 0x44, 0x77, 0x63, 0x62, 0x61, 0x68, 0x47, 0x4B, 0x55, 0x6B, 0x50, 0x30, 0x45, 0x6B, 0x62, 0x39, 0x53, 0x30, 0x58, 0x4C, 0x4A, 0x57, 0x63, 0x47, 0x53, 0x47, 0x35, 0x61, 0x55, 0x6E, 0x48, 0x4A, 0x58, 0x52, 0x37, 0x69, 0x6E, 0x78, 0x34, 0x63, 0x5A, 0x6C, 0x66, 0x6F, 0x4C, 0x6E, 0x72, 0x45, 0x51, 0x65, 0x36, 0x68, 0x55, 0x78, 0x73, 0x4D, 0x71, 0x0A, 0x62, 0x30, 0x64, 0x48, 0x78, 0x64, 0x48, 0x44, 0x42, 0x4D, 0x64, 0x47, 0x66, 0x56, 0x57, 0x77, 0x67, 0x4B, 0x6F, 0x6A, 0x4F, 0x6A, 0x70, 0x53, 0x2F, 0x39, 0x38, 0x6D, 0x45, 0x55, 0x79, 0x37, 0x56, 0x42, 0x2F, 0x36, 0x61, 0x32, 0x6C, 0x72, 0x65, 0x67, 0x6C, 0x76, 0x6A, 0x63, 0x2F, 0x32, 0x6E, 0x4B, 0x43, 0x4B, 0x74, 0x59, 0x37, 0x37, 0x44, 0x37, 0x64, 0x54, 0x71, 0x6C, 0x47, 0x46, 0x0A, 0x78, 0x7A, 0x41, 0x42, 0x61, 0x57, 0x75, 0x38, 0x36, 0x4D, 0x43, 0x5A, 0x34, 0x2F, 0x51, 0x31, 0x33, 0x4C, 0x76, 0x2B, 0x42, 0x65, 0x66, 0x62, 0x71, 0x74, 0x49, 0x39, 0x73, 0x71, 0x5A, 0x5A, 0x77, 0x6A, 0x72, 0x64, 0x55, 0x68, 0x51, 0x48, 0x38, 0x56, 0x43, 0x78, 0x72, 0x79, 0x32, 0x51, 0x56, 0x4D, 0x51, 0x57, 0x51, 0x69, 0x6E, 0x57, 0x68, 0x41, 0x74, 0x36, 0x4D, 0x71, 0x54, 0x34, 0x0A, 0x53, 0x42, 0x53, 0x54, 0x72, 0x6F, 0x6C, 0x5A, 0x7A, 0x77, 0x72, 0x71, 0x6A, 0x65, 0x38, 0x4D, 0x50, 0x4A, 0x39, 0x31, 0x75, 0x61, 0x4E, 0x4D, 0x64, 0x58, 0x47, 0x4C, 0x63, 0x48, 0x4C, 0x49, 0x32, 0x36, 0x73, 0x58, 0x7A, 0x76, 0x37, 0x4B, 0x53, 0x51, 0x4B, 0x42, 0x67, 0x51, 0x44, 0x76, 0x63, 0x77, 0x73, 0x50, 0x55, 0x55, 0x76, 0x41, 0x39, 0x5A, 0x32, 0x5A, 0x58, 0x39, 0x58, 0x35, 0x0A, 0x6D, 0x49, 0x78, 0x4D, 0x54, 0x42, 0x4E, 0x64, 0x45, 0x46, 0x7A, 0x56, 0x62, 0x55, 0x50, 0x75, 0x4B, 0x4B, 0x41, 0x31, 0x79, 0x57, 0x6E, 0x31, 0x55, 0x4D, 0x44, 0x4E, 0x63, 0x55, 0x6A, 0x71, 0x68, 0x2B, 0x7A, 0x65, 0x2F, 0x37, 0x6B, 0x33, 0x79, 0x46, 0x78, 0x6B, 0x68, 0x30, 0x51, 0x46, 0x33, 0x31, 0x62, 0x71, 0x36, 0x30, 0x65, 0x4C, 0x39, 0x30, 0x47, 0x49, 0x53, 0x69, 0x41, 0x4F, 0x0A, 0x35, 0x4B, 0x4F, 0x57, 0x4D, 0x39, 0x45, 0x4B, 0x6F, 0x2B, 0x78, 0x41, 0x51, 0x32, 0x62, 0x61, 0x4B, 0x31, 0x4D, 0x66, 0x4F, 0x59, 0x31, 0x47, 0x2B, 0x38, 0x6A, 0x7A, 0x42, 0x58, 0x55, 0x70, 0x42, 0x73, 0x39, 0x34, 0x6B, 0x35, 0x33, 0x53, 0x38, 0x38, 0x79, 0x58, 0x6D, 0x4B, 0x36, 0x6E, 0x79, 0x64, 0x67, 0x76, 0x37, 0x30, 0x42, 0x4A, 0x38, 0x5A, 0x68, 0x35, 0x66, 0x6B, 0x55, 0x71, 0x0A, 0x57, 0x32, 0x30, 0x6F, 0x53, 0x62, 0x68, 0x6B, 0x68, 0x6A, 0x52, 0x64, 0x53, 0x7A, 0x48, 0x32, 0x6B, 0x52, 0x47, 0x69, 0x72, 0x67, 0x2B, 0x55, 0x53, 0x77, 0x4B, 0x42, 0x67, 0x51, 0x44, 0x5A, 0x4A, 0x4D, 0x6E, 0x72, 0x79, 0x32, 0x45, 0x78, 0x61, 0x2F, 0x33, 0x45, 0x71, 0x37, 0x50, 0x62, 0x6F, 0x73, 0x78, 0x41, 0x50, 0x4D, 0x69, 0x59, 0x6E, 0x6B, 0x35, 0x4A, 0x41, 0x50, 0x53, 0x47, 0x0A, 0x79, 0x32, 0x7A, 0x30, 0x5A, 0x37, 0x54, 0x55, 0x62, 0x2B, 0x75, 0x48, 0x51, 0x4F, 0x2F, 0x2B, 0x78, 0x50, 0x4D, 0x37, 0x6E, 0x43, 0x30, 0x75, 0x79, 0x4C, 0x49, 0x4D, 0x44, 0x39, 0x6C, 0x61, 0x54, 0x4D, 0x48, 0x77, 0x6E, 0x36, 0x73, 0x37, 0x2F, 0x4C, 0x62, 0x47, 0x6F, 0x45, 0x50, 0x31, 0x57, 0x52, 0x67, 0x70, 0x6F, 0x59, 0x48, 0x2F, 0x42, 0x31, 0x34, 0x6B, 0x2F, 0x52, 0x6E, 0x36, 0x0A, 0x66, 0x75, 0x77, 0x52, 0x4E, 0x36, 0x32, 0x49, 0x6F, 0x39, 0x74, 0x63, 0x39, 0x2B, 0x41, 0x43, 0x4C, 0x74, 0x55, 0x42, 0x37, 0x76, 0x74, 0x47, 0x61, 0x79, 0x33, 0x2B, 0x67, 0x52, 0x77, 0x59, 0x74, 0x53, 0x43, 0x32, 0x62, 0x35, 0x65, 0x64, 0x38, 0x6C, 0x49, 0x69, 0x65, 0x67, 0x74, 0x54, 0x6B, 0x65, 0x61, 0x30, 0x68, 0x30, 0x75, 0x44, 0x53, 0x52, 0x78, 0x41, 0x74, 0x56, 0x73, 0x33, 0x0A, 0x6E, 0x35, 0x6B, 0x79, 0x61, 0x32, 0x51, 0x39, 0x76, 0x51, 0x4B, 0x42, 0x67, 0x46, 0x4A, 0x75, 0x46, 0x7A, 0x4F, 0x5A, 0x74, 0x2B, 0x74, 0x67, 0x59, 0x6E, 0x57, 0x6E, 0x51, 0x55, 0x45, 0x67, 0x57, 0x38, 0x50, 0x30, 0x4F, 0x49, 0x4A, 0x45, 0x48, 0x4D, 0x45, 0x34, 0x55, 0x54, 0x64, 0x4F, 0x63, 0x77, 0x43, 0x78, 0x4B, 0x72, 0x48, 0x52, 0x72, 0x39, 0x33, 0x4A, 0x6A, 0x75, 0x46, 0x32, 0x0A, 0x45, 0x33, 0x77, 0x64, 0x4B, 0x6F, 0x54, 0x69, 0x69, 0x37, 0x50, 0x72, 0x77, 0x4F, 0x59, 0x49, 0x6F, 0x61, 0x4A, 0x54, 0x68, 0x70, 0x6A, 0x50, 0x63, 0x4A, 0x62, 0x62, 0x64, 0x62, 0x66, 0x4B, 0x79, 0x2B, 0x6E, 0x73, 0x51, 0x70, 0x31, 0x59, 0x47, 0x76, 0x39, 0x77, 0x64, 0x4A, 0x72, 0x4D, 0x61, 0x56, 0x77, 0x4A, 0x63, 0x76, 0x49, 0x70, 0x77, 0x56, 0x36, 0x76, 0x31, 0x55, 0x70, 0x66, 0x0A, 0x56, 0x74, 0x4C, 0x61, 0x64, 0x6D, 0x31, 0x6C, 0x6B, 0x6C, 0x76, 0x70, 0x71, 0x73, 0x36, 0x47, 0x4E, 0x4D, 0x38, 0x6A, 0x6E, 0x4D, 0x30, 0x58, 0x78, 0x33, 0x61, 0x6A, 0x6D, 0x6D, 0x6E, 0x66, 0x65, 0x57, 0x39, 0x79, 0x47, 0x58, 0x45, 0x35, 0x70, 0x68, 0x4D, 0x72, 0x7A, 0x4C, 0x4A, 0x6C, 0x39, 0x46, 0x30, 0x39, 0x63, 0x49, 0x32, 0x4C, 0x41, 0x6F, 0x47, 0x42, 0x41, 0x4E, 0x58, 0x76, 0x0A, 0x75, 0x67, 0x56, 0x58, 0x72, 0x70, 0x32, 0x62, 0x73, 0x54, 0x31, 0x6F, 0x6B, 0x64, 0x36, 0x75, 0x53, 0x61, 0x42, 0x73, 0x67, 0x70, 0x4A, 0x6A, 0x50, 0x65, 0x77, 0x4E, 0x52, 0x64, 0x33, 0x63, 0x5A, 0x4B, 0x39, 0x7A, 0x30, 0x61, 0x53, 0x50, 0x31, 0x44, 0x54, 0x41, 0x31, 0x50, 0x4E, 0x6B, 0x70, 0x65, 0x51, 0x77, 0x48, 0x67, 0x2F, 0x2B, 0x36, 0x66, 0x53, 0x61, 0x56, 0x4F, 0x48, 0x7A, 0x0A, 0x79, 0x41, 0x78, 0x44, 0x73, 0x39, 0x68, 0x35, 0x52, 0x72, 0x62, 0x78, 0x52, 0x61, 0x4E, 0x66, 0x73, 0x54, 0x2B, 0x72, 0x41, 0x55, 0x48, 0x37, 0x78, 0x31, 0x53, 0x59, 0x44, 0x56, 0x56, 0x51, 0x59, 0x56, 0x4D, 0x68, 0x55, 0x52, 0x62, 0x54, 0x6F, 0x5A, 0x65, 0x36, 0x47, 0x2F, 0x6A, 0x71, 0x6E, 0x54, 0x43, 0x33, 0x66, 0x4E, 0x66, 0x48, 0x56, 0x31, 0x78, 0x74, 0x5A, 0x66, 0x6F, 0x74, 0x0A, 0x30, 0x6C, 0x6F, 0x4D, 0x48, 0x67, 0x77, 0x65, 0x70, 0x36, 0x2B, 0x53, 0x49, 0x4D, 0x43, 0x6F, 0x65, 0x65, 0x32, 0x5A, 0x63, 0x74, 0x75, 0x5A, 0x56, 0x33, 0x32, 0x6C, 0x63, 0x49, 0x61, 0x66, 0x39, 0x72, 0x62, 0x48, 0x4F, 0x63, 0x37, 0x64, 0x41, 0x6F, 0x47, 0x41, 0x65, 0x51, 0x38, 0x6B, 0x38, 0x53, 0x49, 0x4C, 0x4E, 0x47, 0x36, 0x44, 0x4F, 0x41, 0x33, 0x31, 0x54, 0x45, 0x35, 0x50, 0x0A, 0x6D, 0x30, 0x31, 0x41, 0x4A, 0x49, 0x59, 0x77, 0x37, 0x41, 0x6C, 0x52, 0x33, 0x75, 0x6F, 0x2F, 0x52, 0x4E, 0x61, 0x43, 0x2B, 0x78, 0x59, 0x64, 0x50, 0x55, 0x33, 0x54, 0x73, 0x6B, 0x75, 0x41, 0x4C, 0x78, 0x78, 0x69, 0x44, 0x52, 0x2F, 0x57, 0x73, 0x4C, 0x45, 0x51, 0x42, 0x43, 0x6A, 0x6B, 0x46, 0x57, 0x6D, 0x6D, 0x4A, 0x41, 0x57, 0x6E, 0x51, 0x55, 0x44, 0x74, 0x62, 0x6E, 0x59, 0x4E, 0x0A, 0x53, 0x63, 0x77, 0x52, 0x38, 0x47, 0x32, 0x4A, 0x36, 0x46, 0x6E, 0x72, 0x45, 0x43, 0x74, 0x62, 0x74, 0x79, 0x73, 0x37, 0x33, 0x57, 0x41, 0x56, 0x47, 0x6F, 0x6F, 0x46, 0x5A, 0x6E, 0x63, 0x6D, 0x50, 0x4C, 0x50, 0x38, 0x6C, 0x78, 0x4C, 0x79, 0x62, 0x6C, 0x53, 0x42, 0x44, 0x45, 0x4C, 0x79, 0x61, 0x5A, 0x76, 0x2F, 0x62, 0x41, 0x73, 0x50, 0x6C, 0x4D, 0x4F, 0x39, 0x62, 0x44, 0x35, 0x63, 0x0A, 0x4A, 0x2B, 0x4E, 0x53, 0x42, 0x61, 0x61, 0x2B, 0x6F, 0x69, 0x4C, 0x6C, 0x31, 0x77, 0x6D, 0x43, 0x61, 0x35, 0x4D, 0x43, 0x66, 0x6C, 0x63, 0x3D, 0x0A, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x45, 0x4E, 0x44, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4B, 0x45, 0x59, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x0A}; void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } void PrintHex(const uint8_t* data, uint32_t len) { for (uint32_t i = 0; i < len; i++) { printf("%02X", data[i]); if ((i + 1) % 16 == 0 && i + 1 < len) { printf("\n"); } else { printf(" "); } } printf("\n"); } int main(void) { int32_t ret = 1; HITLS_AUTH_PrivPassCtx *client = NULL; HITLS_AUTH_PrivPassCtx *issuer = NULL; HITLS_AUTH_PrivPassCtx *server = NULL; HITLS_AUTH_PrivPassToken *tokenChallenge = NULL; HITLS_AUTH_PrivPassToken *tokenRequest = NULL; HITLS_AUTH_PrivPassToken *tokenResponse = NULL; HITLS_AUTH_PrivPassToken *finalToken = NULL; uint8_t *tokenChallengeBuff = NULL; uint32_t tokenChallengeLen = 0; uint8_t *tokenRequestBuff = NULL; uint32_t tokenRequestLen = 0; uint8_t *tokenResponseBuff = NULL; uint32_t tokenResponseLen = 0; uint8_t *finalTokenBuff = NULL; uint32_t finalTokenLen = 0; // Construct parameter structure uint16_t tokenTypeValue = 0x0002; uint8_t issuerName[] = "Example Issuer"; uint8_t redemption[] = ""; // Length must be 0 or 32 uint8_t originInfo[] = "Example Origin"; BSL_Param param[5] = { {AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_TYPE, BSL_PARAM_TYPE_UINT16, &tokenTypeValue, 2, 2}, {AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ISSUERNAME, BSL_PARAM_TYPE_OCTETS_PTR, issuerName, sizeof(issuerName), sizeof(issuerName)}, {AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_REDEMPTION, BSL_PARAM_TYPE_OCTETS_PTR, redemption, 0, 0}, {AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ORIGININFO, BSL_PARAM_TYPE_OCTETS_PTR, originInfo, sizeof(originInfo), sizeof(originInfo)}, BSL_PARAM_END }; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } client = HITLS_AUTH_PrivPassNewCtx(HITLS_AUTH_PRIVPASS_PUB_VERIFY_TOKENS); issuer = HITLS_AUTH_PrivPassNewCtx(HITLS_AUTH_PRIVPASS_PUB_VERIFY_TOKENS); server = HITLS_AUTH_PrivPassNewCtx(HITLS_AUTH_PRIVPASS_PUB_VERIFY_TOKENS); if (!client || !issuer || !server) { printf("Failed to create contexts\n"); PrintLastError(); goto EXIT; } // Set keys if (HITLS_AUTH_PrivPassSetPubkey(client, pubKey, sizeof(pubKey)) != HITLS_AUTH_SUCCESS || HITLS_AUTH_PrivPassSetPubkey(issuer, pubKey, sizeof(pubKey)) != HITLS_AUTH_SUCCESS || HITLS_AUTH_PrivPassSetPrvkey(issuer, NULL, privKey, sizeof(privKey)) != HITLS_AUTH_SUCCESS || HITLS_AUTH_PrivPassSetPubkey(server, pubKey, sizeof(pubKey)) != HITLS_AUTH_SUCCESS) { printf("Failed to set keys\n"); PrintLastError(); goto EXIT; } printf("\ntokenChallenge: server ------> client\n"); if (HITLS_AUTH_PrivPassGenTokenChallenge(server, param, &tokenChallenge) != HITLS_AUTH_SUCCESS) { printf("Failed to generate token challenge\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(server, tokenChallenge, NULL, &tokenChallengeLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token challenge\n"); PrintLastError(); goto EXIT; } tokenChallengeBuff = BSL_SAL_Malloc(tokenChallengeLen); if (tokenChallengeBuff == NULL) { printf("Failed to allocate memory for token challenge\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(server, tokenChallenge, tokenChallengeBuff, &tokenChallengeLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token challenge\n"); PrintLastError(); goto EXIT; } PrintHex(tokenChallengeBuff, tokenChallengeLen); printf("\ntokenRequest: client ------> issuer\n"); if (HITLS_AUTH_PrivPassGenTokenReq(client, tokenChallenge, &tokenRequest) != HITLS_AUTH_SUCCESS) { printf("Failed to generate token request\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, tokenRequest, NULL, &tokenRequestLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token request\n"); PrintLastError(); goto EXIT; } tokenRequestBuff = BSL_SAL_Malloc(tokenRequestLen); if (tokenRequestBuff == NULL) { printf("Failed to allocate memory for token request\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, tokenRequest, tokenRequestBuff, &tokenRequestLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token request\n"); PrintLastError(); goto EXIT; } PrintHex(tokenRequestBuff, tokenRequestLen); printf("\ntokenResponse: issuer ------> client\n"); if (HITLS_AUTH_PrivPassGenTokenResponse(issuer, tokenRequest, &tokenResponse) != HITLS_AUTH_SUCCESS) { printf("Failed to generate token response\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, tokenResponse, NULL, &tokenResponseLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token response\n"); PrintLastError(); goto EXIT; } tokenResponseBuff = BSL_SAL_Malloc(tokenResponseLen); if (tokenResponseBuff == NULL) { printf("Failed to allocate memory for token response\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, tokenResponse, tokenResponseBuff, &tokenResponseLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token response\n"); PrintLastError(); goto EXIT; } PrintHex(tokenResponseBuff, tokenResponseLen); printf("\nfinalToken: client ------> server\n"); if (HITLS_AUTH_PrivPassGenToken(client, tokenChallenge, tokenResponse, &finalToken) != HITLS_AUTH_SUCCESS) { printf("Failed to generate final token\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, finalToken, NULL, &finalTokenLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize final token\n"); PrintLastError(); goto EXIT; } finalTokenBuff = BSL_SAL_Malloc(finalTokenLen); if (finalTokenBuff == NULL) { printf("Failed to allocate memory for final token\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, finalToken, finalTokenBuff, &finalTokenLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize final token\n"); PrintLastError(); goto EXIT; } PrintHex(finalTokenBuff, finalTokenLen); printf("\nverifyToken: server\n"); if (HITLS_AUTH_PrivPassVerifyToken(server, tokenChallenge, finalToken) != HITLS_AUTH_SUCCESS) { printf("Token verification failed\n"); PrintLastError(); goto EXIT; } printf("Privacy pass public token verify process completed successfully!\n"); ret = HITLS_AUTH_SUCCESS; EXIT: HITLS_AUTH_PrivPassFreeToken(tokenChallenge); HITLS_AUTH_PrivPassFreeToken(tokenRequest); HITLS_AUTH_PrivPassFreeToken(tokenResponse); HITLS_AUTH_PrivPassFreeToken(finalToken); HITLS_AUTH_PrivPassFreeCtx(client); HITLS_AUTH_PrivPassFreeCtx(issuer); HITLS_AUTH_PrivPassFreeCtx(server); BSL_SAL_FREE(tokenChallengeBuff); BSL_SAL_FREE(tokenRequestBuff); BSL_SAL_FREE(tokenResponseBuff); BSL_SAL_FREE(finalTokenBuff); return ret; }
2301_79861745/bench_create
testcode/demo/privpass_token.c
C
unknown
20,588
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_eal_init.h" #include "crypt_eal_rand.h" #include "crypt_eal_pkey.h" #include "crypt_eal_codecs.h" #include "hitls_error.h" #include "hitls_config.h" #include "hitls.h" #include "hitls_cert_init.h" #include "hitls_cert.h" #include "hitls_crypt_init.h" #include "hitls_pki_cert.h" #include "crypt_errno.h" #define CERTS_PATH "../../../testcode/testdata/tls/certificate/der/ecdsa_sha256/" #define HTTP_BUF_MAXLEN (18 * 1024) /* 18KB */ int main(int32_t argc, char *argv[]) { int32_t exitValue = -1; int32_t ret = 0; HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; BSL_UIO *uio = NULL; int fd = 0; int infd = 0; HITLS_X509_Cert *rootCA = NULL; HITLS_X509_Cert *subCA = NULL; HITLS_X509_Cert *serverCert = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); return -1; } HITLS_CertMethodInit(); HITLS_CryptMethodInit(); fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { printf("Create socket failed.\n"); return -1; } int option = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) { printf("setsockopt SO_REUSEADDR failed.\n"); goto EXIT; } struct sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(12345); serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 0) { printf("bind failed.\n"); goto EXIT; } if (listen(fd, 5) != 0) { printf("listen socket fail\n"); goto EXIT; } struct sockaddr_in clientAddr; unsigned int len = sizeof(struct sockaddr_in); infd = accept(fd, (struct sockaddr *)&clientAddr, &len); if (infd < 0) { printf("accept failed.\n"); goto EXIT; } config = HITLS_CFG_NewTLS12Config(); if (config == NULL) { printf("HITLS_CFG_NewTLS12Config failed.\n"); goto EXIT; } ret = HITLS_CFG_SetClientVerifySupport(config, false); // disable peer verify if (ret != HITLS_SUCCESS) { printf("Disable peer verify faild.\n"); goto EXIT; } /* 加载证书:需要用户实现 */ ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, CERTS_PATH "ca.der", &rootCA); if (ret != HITLS_SUCCESS) { printf("Parse ca failed.\n"); goto EXIT; } ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, CERTS_PATH "inter.der", &subCA); if (ret != HITLS_SUCCESS) { printf("Parse subca failed.\n"); goto EXIT; } HITLS_CFG_AddCertToStore(config, rootCA, TLS_CERT_STORE_TYPE_DEFAULT, true); HITLS_CFG_AddCertToStore(config, subCA, TLS_CERT_STORE_TYPE_DEFAULT, true); HITLS_CFG_LoadCertFile(config, CERTS_PATH "server.der", TLS_PARSE_FORMAT_ASN1); HITLS_CFG_LoadKeyFile(config, CERTS_PATH "server.key.der", TLS_PARSE_FORMAT_ASN1); /* 新建openHiTLS上下文 */ ctx = HITLS_New(config); if (ctx == NULL) { printf("HITLS_New failed.\n"); goto EXIT; } /* 用户可按需实现method */ uio = BSL_UIO_New(BSL_UIO_TcpMethod()); if (uio == NULL) { printf("BSL_UIO_New failed.\n"); goto EXIT; } ret = BSL_UIO_Ctrl(uio, BSL_UIO_SET_FD, (int32_t)sizeof(fd), &infd); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("BSL_UIO_SET_FD failed, fd = %u.\n", fd); goto EXIT; } ret = HITLS_SetUio(ctx, uio); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("HITLS_SetUio failed. ret = 0x%x.\n", ret); goto EXIT; } /* 进行TLS连接、用户需按实际场景考虑返回值 */ ret = HITLS_Accept(ctx); if (ret != HITLS_SUCCESS) { printf("HITLS_Accept failed, ret = 0x%x.\n", ret); goto EXIT; } /* 读取对端报文、用户需按实际场景考虑返回值 */ uint8_t readBuf[HTTP_BUF_MAXLEN + 1] = {0}; uint32_t readLen = 0; ret = HITLS_Read(ctx, readBuf, HTTP_BUF_MAXLEN, &readLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Read failed, ret = 0x%x.\n", ret); goto EXIT; } printf("get from client size:%u :%s\n", readLen, readBuf); /* 向对端发送报文、用户需按实际场景考虑返回值 */ const uint8_t sndBuf[] = "Hi, this is server\n"; uint32_t writeLen = 0; ret = HITLS_Write(ctx, sndBuf, sizeof(sndBuf), &writeLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Write error:error code:%d\n", ret); goto EXIT; } exitValue = 0; EXIT: HITLS_Close(ctx); HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); close(fd); close(infd); HITLS_X509_CertFree(rootCA); HITLS_X509_CertFree(subCA); HITLS_X509_CertFree(serverCert); CRYPT_EAL_PkeyFreeCtx(pkey); BSL_UIO_Free(uio); return exitValue; }
2301_79861745/bench_create
testcode/demo/server.c
C
unknown
5,224
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "crypt_eal_pkey.h" // Header file of the interfaces for asymmetric encryption and decryption. #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_rand.h" #include "crypt_eal_init.h" #include "crypt_types.h" void *StdMalloc(uint32_t len) { return malloc((uint32_t)len); } void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } int main(void) { int32_t ret; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SM2); if (pkey == NULL) { PrintLastError(); goto EXIT; } // Generate a key pair. ret = CRYPT_EAL_PkeyGen(pkey); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_PkeyGen: error code is %x\n", ret); PrintLastError(); goto EXIT; } // Data to be encrypted. char *data = "test enc data"; uint32_t dataLen = 12; uint8_t ecrypt[125] = {0}; uint32_t ecryptLen = 125; uint8_t dcrypt[125] = {0}; uint32_t dcryptLen = 125; // Encrypt data. ret = CRYPT_EAL_PkeyEncrypt(pkey, data, dataLen, ecrypt, &ecryptLen); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_PkeyEncrypt: error code is %x\n", ret); PrintLastError(); goto EXIT; } // Decrypt data. ret = CRYPT_EAL_PkeyDecrypt(pkey, ecrypt, ecryptLen, dcrypt, &dcryptLen); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_PkeyDecrypt: error code is %x\n", ret); PrintLastError(); goto EXIT; } if (memcmp(dcrypt, data, dataLen) == 0) { printf("encrypt and decrypt success\n"); } else { ret = -1; } EXIT: // Release the context memory. CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_RandDeinit(); BSL_ERR_DeInit(); return ret; }
2301_79861745/bench_create
testcode/demo/sm2enc.c
C
unknown
2,712
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "crypt_eal_pkey.h" // Header file for signature verification. #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_rand.h" #include "crypt_eal_init.h" void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line);// Obtain the name and number of lines of the error file. printf("failed at file %s at line %d\n", file, line); } int main(void) { int ret; uint8_t userId[32] = {0}; uint8_t key[32] = {0}; uint8_t msg[32] = {0}; uint8_t signBuf[100] = {0}; uint32_t signLen = sizeof(signBuf); CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyCtx *ctx = NULL; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); goto EXIT; } ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SM2); if (ctx == NULL) { goto EXIT; } // Set a user ID. ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Generate a key pair. ret = CRYPT_EAL_PkeyGen(ctx); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Sign. ret = CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, &signLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Verify the signature. ret = CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, signLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } printf("pass \n"); EXIT: // Release the context memory. CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_RandDeinit(); BSL_ERR_DeInit(); return ret; }
2301_79861745/bench_create
testcode/demo/sm2sign.c
C
unknown
2,679
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "crypt_eal_cipher.h" // Header file of the interfaces for symmetric encryption and decryption. #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" // Algorithm ID list. #include "crypt_errno.h" // Error code list. void *StdMalloc(uint32_t len) { return malloc((size_t)len); } void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); // Obtain the name and number of lines of the error file. printf("failed at file %s at line %d\n", file, line); } int main(void) { uint8_t data[10] = {0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x1c, 0x14}; uint8_t iv[16] = {0}; uint8_t key[16] = {0}; uint32_t dataLen = sizeof(data); uint8_t cipherText[100]; uint8_t plainText[100]; uint32_t outTotalLen = 0; uint32_t outLen = sizeof(cipherText); uint32_t cipherTextLen; int32_t ret; printf("plain text to be encrypted: "); for (uint32_t i = 0; i < dataLen; i++) { printf("%02x", data[i]); } printf("\n"); // Create a context. CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_SM4_CBC); if (ctx == NULL) { PrintLastError(); BSL_ERR_DeInit(); return 1; } /* * During initialization, the last input parameter can be true or false. true indicates encryption, * and false indicates decryption. */ ret = CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true); if (ret != CRYPT_SUCCESS) { // Output the error code. You can find the error information in **crypt_errno.h** based on the error code. printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the padding mode. ret = CRYPT_EAL_CipherSetPadding(ctx, CRYPT_PADDING_PKCS7); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } /** * Enter the data to be calculated. This interface can be called for multiple times. * The input value of **outLen** is the length of the ciphertext, * and the output value is the amount of processed data. * */ ret = CRYPT_EAL_CipherUpdate(ctx, data, dataLen, cipherText, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; outLen = sizeof(cipherText) - outTotalLen; ret = CRYPT_EAL_CipherFinal(ctx, cipherText + outTotalLen, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; printf("cipher text value is: "); for (uint32_t i = 0; i < outTotalLen; i++) { printf("%02x", cipherText[i]); } printf("\n"); // Start decryption. cipherTextLen = outTotalLen; outTotalLen = 0; outLen = sizeof(plainText); // When initializing the decryption function, set the last input parameter to false. ret = CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), false); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the padding mode, which must be the same as that for encryption. ret = CRYPT_EAL_CipherSetPadding(ctx, CRYPT_PADDING_PKCS7); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Enter the ciphertext data. ret = CRYPT_EAL_CipherUpdate(ctx, cipherText, cipherTextLen, plainText, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; outLen = sizeof(plainText) - outTotalLen; // Decrypt the last segment of data and remove the filled content. ret = CRYPT_EAL_CipherFinal(ctx, plainText + outTotalLen, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; printf("decrypted plain text value is: "); for (uint32_t i = 0; i < outTotalLen; i++) { printf("%02x", plainText[i]); } printf("\n"); if (outTotalLen != dataLen || memcmp(plainText, data, dataLen) != 0) { printf("plaintext comparison failed\n"); goto EXIT; } printf("pass \n"); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); BSL_ERR_DeInit(); return ret; }
2301_79861745/bench_create
testcode/demo/sm4cbc.c
C
unknown
5,187
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_eal_init.h" #include "crypt_algid.h" #include "crypt_eal_rand.h" #include "hitls_error.h" #include "hitls_config.h" #include "hitls.h" #include "hitls_cert_init.h" #include "hitls_cert.h" #include "hitls_crypt_init.h" #include "hitls_pki_cert.h" #include "crypt_errno.h" #include "bsl_log.h" #define CERTS_PATH "../../../testcode/testdata/tls/certificate/der/sm2_with_userid/" #define HTTP_BUF_MAXLEN (18 * 1024) /* 18KB */ static int32_t HiTLSInit() { // Registration certificate, crypto callback int32_t ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); return -1; } HITLS_CertMethodInit(); HITLS_CryptMethodInit(); } int main(int32_t argc, char *argv[]) { int32_t exitValue = -1; int32_t ret = 0; int32_t port = 12345; HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; BSL_UIO *uio = NULL; int fd = 0; HITLS_X509_Cert *rootCA = NULL; HITLS_X509_Cert *subCA = NULL; if (HiTLSInit() != 0) { goto EXIT; } fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { printf("Create socket failed.\n"); goto EXIT; } int option = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) { close(fd); printf("setsockopt SO_REUSEADDR failed.\n"); goto EXIT; } // Set the protocol and port number struct sockaddr_in serverAddr; (void)memset_s(&serverAddr, sizeof(serverAddr), 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); if (connect(fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 0) { printf("connect failed.\n"); goto EXIT; } config = HITLS_CFG_NewTLCPConfig(); if (config == NULL) { printf("HITLS_CFG_NewTLS12Config failed.\n"); goto EXIT; } ret = HITLS_CFG_SetCheckKeyUsage(config, false); // disable cert keyusage check if (ret != HITLS_SUCCESS) { printf("Disable check KeyUsage failed.\n"); goto EXIT; } /* Load root certificate and intermediate certificate */ ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, CERTS_PATH "ca.crt", &rootCA); if (ret != HITLS_SUCCESS) { printf("Parse ca failed.\n"); goto EXIT; } ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, CERTS_PATH "inter.crt", &subCA); if (ret != HITLS_SUCCESS) { printf("Parse subca failed.\n"); goto EXIT; } HITLS_CFG_AddCertToStore(config, rootCA, TLS_CERT_STORE_TYPE_DEFAULT, true); HITLS_CFG_AddCertToStore(config, subCA, TLS_CERT_STORE_TYPE_DEFAULT, true); // Load signature certificate HITLS_CERT_X509 *signCert = NULL; HITLS_CERT_X509 *signPkey = NULL; signCert = HITLS_CFG_ParseCert(config, CERTS_PATH "sign.crt", strlen(CERTS_PATH "sign.crt"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (signCert == NULL) { printf("Parse signCert failed.\n"); goto EXIT; } signPkey = HITLS_CFG_ParseKey(config, CERTS_PATH "sign.key", strlen(CERTS_PATH "sign.key"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (signPkey == NULL) { printf("Parse signPkey failed.\n"); goto EXIT; } HITLS_CFG_SetTlcpCertificate(config, signCert, TLS_PARSE_FORMAT_ASN1, false); HITLS_CFG_SetTlcpPrivateKey(config, signPkey, TLS_PARSE_FORMAT_ASN1, false); // Load encryption certificate HITLS_CERT_X509 *encCert = NULL; HITLS_CERT_X509 *encPkey = NULL; encCert = HITLS_CFG_ParseCert(config, CERTS_PATH "enc.crt", strlen(CERTS_PATH "enc.crt"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (encCert == NULL) { printf("Parse encCert failed.\n"); goto EXIT; } encPkey = HITLS_CFG_ParseKey(config, CERTS_PATH "enc.key", strlen(CERTS_PATH "enc.key"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (encPkey == NULL) { printf("Parse encPkey failed.\n"); goto EXIT; } HITLS_CFG_SetTlcpCertificate(config, encCert, TLS_PARSE_FORMAT_ASN1, true); HITLS_CFG_SetTlcpPrivateKey(config, encPkey, TLS_PARSE_FORMAT_ASN1, true); /* Create a new openHiTLS ctx */ ctx = HITLS_New(config); if (ctx == NULL) { printf("HITLS_New failed.\n"); goto EXIT; } uio = BSL_UIO_New(BSL_UIO_TcpMethod()); if (uio == NULL) { printf("BSL_UIO_New failed.\n"); goto EXIT; } ret = BSL_UIO_Ctrl(uio, BSL_UIO_SET_FD, (int32_t)sizeof(fd), &fd); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("BSL_UIO_SET_FD failed, fd = %u.\n", fd); goto EXIT; } ret = HITLS_SetUio(ctx, uio); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("HITLS_SetUio failed. ret = 0x%x.\n", ret); goto EXIT; } /* To establish a TLS connection, users need to consider the return value based on the actual scenario */ ret = HITLS_Connect(ctx); if (ret != HITLS_SUCCESS) { printf("HITLS_Connect failed, ret = 0x%x.\n", ret); goto EXIT; } /* Sending messages to the other end, users need to consider the return value according to the actual scenario */ const uint8_t sndBuf[] = "Hi, this is tlcp client\n"; uint32_t writeLen = 0; ret = HITLS_Write(ctx, sndBuf, sizeof(sndBuf), &writeLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Write error:error code:%d\n", ret); goto EXIT; } /* Read the message from the other end, and the user needs to consider the return value according to the actual scenario */ uint8_t readBuf[HTTP_BUF_MAXLEN + 1] = {0}; uint32_t readLen = 0; ret = HITLS_Read(ctx, readBuf, HTTP_BUF_MAXLEN, &readLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Read failed, ret = 0x%x.\n", ret); goto EXIT; } printf("get from server size:%u :%s\n", readLen, readBuf); exitValue = 0; EXIT: HITLS_Close(ctx); HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); close(fd); HITLS_X509_CertFree(rootCA); HITLS_X509_CertFree(subCA); BSL_UIO_Free(uio); return exitValue; }
2301_79861745/bench_create
testcode/demo/tlcp_client.c
C
unknown
6,480
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_eal_init.h" #include "crypt_eal_rand.h" #include "crypt_eal_pkey.h" #include "crypt_eal_codecs.h" #include "hitls_error.h" #include "hitls_config.h" #include "hitls.h" #include "hitls_cert_init.h" #include "hitls_cert.h" #include "hitls_crypt_init.h" #include "hitls_pki_cert.h" #include "crypt_errno.h" #include "bsl_log.h" #define CERTS_PATH "../../../testcode/testdata/tls/certificate/der/sm2_with_userid/" #define HTTP_BUF_MAXLEN (18 * 1024) /* 18KB */ static int32_t HiTLSInit() { // Registration certificate, crypto callback int32_t ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); return -1; } HITLS_CertMethodInit(); HITLS_CryptMethodInit(); } int main(int32_t argc, char *argv[]) { int32_t exitValue = -1; int32_t ret = 0; int32_t port = 12345; HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; BSL_UIO *uio = NULL; int fd = 0; int infd = 0; HITLS_X509_Cert *rootCA = NULL; HITLS_X509_Cert *subCA = NULL; HITLS_X509_Cert *serverCert = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; if (HiTLSInit() != 0) { goto EXIT; } fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { printf("Create socket failed.\n"); return -1; } int option = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) { printf("setsockopt SO_REUSEADDR failed.\n"); goto EXIT; } struct sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 0) { printf("bind failed.\n"); goto EXIT; } if (listen(fd, 5) != 0) { printf("listen socket fail\n"); goto EXIT; } struct sockaddr_in clientAddr; unsigned int len = sizeof(struct sockaddr_in); infd = accept(fd, (struct sockaddr *)&clientAddr, &len); if (infd < 0) { printf("accept failed.\n"); goto EXIT; } config = HITLS_CFG_NewTLCPConfig(); if (config == NULL) { printf("HITLS_CFG_NewTLS12Config failed.\n"); goto EXIT; } ret = HITLS_CFG_SetClientVerifySupport(config, false); // disable peer verify if (ret != HITLS_SUCCESS) { printf("Disable peer verify faild.\n"); goto EXIT; } /* Load root certificate and intermediate certificate */ ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, CERTS_PATH "ca.crt", &rootCA); if (ret != HITLS_SUCCESS) { printf("Parse ca failed.\n"); goto EXIT; } ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, CERTS_PATH "inter.crt", &subCA); if (ret != HITLS_SUCCESS) { printf("Parse subca failed.\n"); goto EXIT; } HITLS_CFG_AddCertToStore(config, rootCA, TLS_CERT_STORE_TYPE_DEFAULT, true); HITLS_CFG_AddCertToStore(config, subCA, TLS_CERT_STORE_TYPE_DEFAULT, true); // Load signature certificate HITLS_CERT_X509 *signCert = NULL; HITLS_CERT_X509 *signPkey = NULL; signCert = HITLS_CFG_ParseCert(config, CERTS_PATH "sign.crt", strlen(CERTS_PATH "sign.crt"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (signCert == NULL) { printf("Parse signCert failed.\n"); goto EXIT; } signPkey = HITLS_CFG_ParseKey(config, CERTS_PATH "sign.key", strlen(CERTS_PATH "sign.key"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (signPkey == NULL) { printf("Parse signPkey failed.\n"); goto EXIT; } HITLS_CFG_SetTlcpCertificate(config, signCert, TLS_PARSE_FORMAT_ASN1, false); HITLS_CFG_SetTlcpPrivateKey(config, signPkey, TLS_PARSE_FORMAT_ASN1, false); // Load encryption certificate HITLS_CERT_X509 *encCert = NULL; HITLS_CERT_X509 *encPkey = NULL; encCert = HITLS_CFG_ParseCert(config, CERTS_PATH "enc.crt", strlen(CERTS_PATH "enc.crt"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (encCert == NULL) { printf("Parse encCert failed.\n"); goto EXIT; } encPkey = HITLS_CFG_ParseKey(config, CERTS_PATH "enc.key", strlen(CERTS_PATH "enc.key"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (encPkey == NULL) { printf("Parse encPkey failed.\n"); goto EXIT; } HITLS_CFG_SetTlcpCertificate(config, encCert, TLS_PARSE_FORMAT_ASN1, true); HITLS_CFG_SetTlcpPrivateKey(config, encPkey, TLS_PARSE_FORMAT_ASN1, true); /* Create a new openHiTLS ctx */ ctx = HITLS_New(config); if (ctx == NULL) { printf("HITLS_New failed.\n"); goto EXIT; } /* Users can implement methods as needed */ uio = BSL_UIO_New(BSL_UIO_TcpMethod()); if (uio == NULL) { printf("BSL_UIO_New failed.\n"); goto EXIT; } ret = BSL_UIO_Ctrl(uio, BSL_UIO_SET_FD, (int32_t)sizeof(fd), &infd); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("BSL_UIO_SET_FD failed, fd = %u.\n", fd); goto EXIT; } ret = HITLS_SetUio(ctx, uio); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("HITLS_SetUio failed. ret = 0x%x.\n", ret); goto EXIT; } /* To establish a TLS connection, users need to consider the return value based on the actual scenario */ ret = HITLS_Accept(ctx); if (ret != HITLS_SUCCESS) { printf("HITLS_Accept failed, ret = 0x%x.\n", ret); goto EXIT; } /* Sending messages to the other end, users need to consider the return value according to the actual scenario */ uint8_t readBuf[HTTP_BUF_MAXLEN + 1] = {0}; uint32_t readLen = 0; ret = HITLS_Read(ctx, readBuf, HTTP_BUF_MAXLEN, &readLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Read failed, ret = 0x%x.\n", ret); goto EXIT; } printf("get from client size:%u :%s\n", readLen, readBuf); /* Read the message from the other end, and the user needs to consider the return value according to the actual scenario */ const uint8_t sndBuf[] = "Hi, this is tlcp server\n"; uint32_t writeLen = 0; ret = HITLS_Write(ctx, sndBuf, sizeof(sndBuf), &writeLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Write error:error code:%d\n", ret); goto EXIT; } exitValue = 0; EXIT: HITLS_Close(ctx); HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); close(fd); close(infd); HITLS_X509_CertFree(rootCA); HITLS_X509_CertFree(subCA); HITLS_X509_CertFree(serverCert); CRYPT_EAL_PkeyFreeCtx(pkey); BSL_UIO_Free(uio); return exitValue; }
2301_79861745/bench_create
testcode/demo/tlcp_server.c
C
unknown
6,937
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdbool.h> #include "helper.h" #include "crypt_algid.h" #include "hitls_build.h" #include "crypto_test_util.h" #define ERR_ID (-1) typedef struct { int id; int offset; } MdAlgMap; static MdAlgMap g_mdAlgMap[] = { { CRYPT_MD_MD5, 0 }, { CRYPT_MD_SHA1, 1 }, { CRYPT_MD_SHA224, 2 }, { CRYPT_MD_SHA256, 3 }, { CRYPT_MD_SHA384, 4 }, { CRYPT_MD_SHA512, 5 }, { CRYPT_MD_SHA3_224, 6 }, { CRYPT_MD_SHA3_256, 7 }, { CRYPT_MD_SHA3_384, 8 }, { CRYPT_MD_SHA3_512, 9 }, { CRYPT_MD_SHAKE128, 10 }, { CRYPT_MD_SHAKE256, 11 }, { CRYPT_MD_SM3, 12 }, }; #define MD_ALG_MAP_CNT ((int)(sizeof(g_mdAlgMap) / sizeof(MdAlgMap))) // All MD algorithms are available by default. static int g_mdDisableTable[MD_ALG_MAP_CNT] = { 0 }; static bool g_isInitMd = false; static int g_avlRandAlg = -1; static bool g_isInitRandAlg = false; static void InitMdTable(void) { if (g_isInitMd) { return; } #ifndef HITLS_CRYPTO_MD5 g_mdDisableTable[0] = 1; #endif #ifndef HITLS_CRYPTO_SHA1 g_mdDisableTable[1] = 1; #endif #ifndef HITLS_CRYPTO_SHA224 g_mdDisableTable[2] = 1; #endif #ifndef HITLS_CRYPTO_SHA256 g_mdDisableTable[3] = 1; #endif #ifndef HITLS_CRYPTO_SHA384 g_mdDisableTable[4] = 1; #endif #ifndef HITLS_CRYPTO_SHA512 g_mdDisableTable[5] = 1; #endif #ifndef HITLS_CRYPTO_SHA3 g_mdDisableTable[6] = 1; g_mdDisableTable[7] = 1; g_mdDisableTable[8] = 1; g_mdDisableTable[9] = 1; g_mdDisableTable[10] = 1; g_mdDisableTable[11] = 1; #endif #ifndef HITLS_CRYPTO_SM3 g_mdDisableTable[12] = 1; #endif g_isInitMd = true; } static bool IsDrbgHashDisabled(void) { #ifdef HITLS_CRYPTO_DRBG_HASH return false; #else return true; #endif } static bool IsDrbgHmacDisabled(void) { #ifdef HITLS_CRYPTO_DRBG_HMAC return false; #else return true; #endif } static bool IsDrbgCtrDisabled(void) { #ifdef HITLS_CRYPTO_DRBG_CTR return false; #else return true; #endif } static bool IsDrbgCtrSm4Disabled() { #if defined(HITLS_CRYPTO_DRBG_CTR) && defined(HITLS_CRYPTO_DRBG_GM) && defined(HITLS_CRYPTO_SM4) return false; #else return true; #endif } static int GetDrbgHashAlgId(void) { InitMdTable(); // CRYPT_RAND_SHA256 is preferred (224 depends on 256). if (g_mdDisableTable[3] == 0) { return CRYPT_RAND_SHA256; } if (g_mdDisableTable[5] == 0) { return CRYPT_RAND_SHA512; } if (g_mdDisableTable[1] == 0) { return CRYPT_RAND_SHA1; } if (g_mdDisableTable[12] == 0) { return CRYPT_RAND_SM3; } return ERR_ID; } static int GetDrbgHmacAlgId(void) { InitMdTable(); if (g_mdDisableTable[3] == 0) { return CRYPT_RAND_HMAC_SHA256; } if (g_mdDisableTable[5] == 0) { return CRYPT_RAND_HMAC_SHA512; } if (g_mdDisableTable[1] == 0) { return CRYPT_RAND_HMAC_SHA1; } return ERR_ID; } bool IsMdAlgDisabled(int id) { InitMdTable(); bool res = false; // By default, this algorithm is not disabled. for (int i = 0; i < MD_ALG_MAP_CNT; i++) { if (id == g_mdAlgMap[i].id) { res = g_mdDisableTable[g_mdAlgMap[i].offset] == 1; break; } } return res; } bool IsHmacAlgDisabled(int id) { #ifdef HITLS_CRYPTO_HMAC InitMdTable(); switch (id) { case CRYPT_MAC_HMAC_MD5: return g_mdDisableTable[0] == 1; case CRYPT_MAC_HMAC_SHA1: return g_mdDisableTable[1] == 1; case CRYPT_MAC_HMAC_SHA224: return g_mdDisableTable[2] == 1; case CRYPT_MAC_HMAC_SHA256: return g_mdDisableTable[3] == 1; case CRYPT_MAC_HMAC_SHA384: return g_mdDisableTable[4] == 1; case CRYPT_MAC_HMAC_SHA512: return g_mdDisableTable[5] == 1; case CRYPT_MAC_HMAC_SHA3_224: return g_mdDisableTable[6] == 1; case CRYPT_MAC_HMAC_SHA3_256: return g_mdDisableTable[7] == 1; case CRYPT_MAC_HMAC_SHA3_384: return g_mdDisableTable[8] == 1; case CRYPT_MAC_HMAC_SHA3_512: return g_mdDisableTable[9] == 1; case CRYPT_MAC_HMAC_SM3: return g_mdDisableTable[12] == 1; default: return false; } #else (void)id; return false; #endif } bool IsMacAlgDisabled(int id) { switch (id) { case CRYPT_MAC_HMAC_MD5: case CRYPT_MAC_HMAC_SHA1: case CRYPT_MAC_HMAC_SHA224: case CRYPT_MAC_HMAC_SHA256: case CRYPT_MAC_HMAC_SHA384: case CRYPT_MAC_HMAC_SHA512: case CRYPT_MAC_HMAC_SM3: return IsHmacAlgDisabled(id); case CRYPT_MAC_CBC_MAC_SM4: #ifdef HITLS_CRYPTO_CBC_MAC return false; #else return true; #endif default: return false; } } bool IsDrbgHashAlgDisabled(int id) { if (IsDrbgHashDisabled()) { return true; } InitMdTable(); switch (id) { case CRYPT_RAND_SHA1: return g_mdDisableTable[1] == 1; case CRYPT_RAND_SHA224: return g_mdDisableTable[2] == 1; case CRYPT_RAND_SHA256: return g_mdDisableTable[3] == 1; case CRYPT_RAND_SHA384: return g_mdDisableTable[4] == 1; case CRYPT_RAND_SHA512: return g_mdDisableTable[5] == 1; case CRYPT_RAND_SM3: #ifdef HITLS_CRYPTO_DRBG_GM return g_mdDisableTable[12] == 1; #else return true; #endif default: return false; } } bool IsDrbgHmacAlgDisabled(int id) { if (IsDrbgHmacDisabled()) { return true; } InitMdTable(); switch (id) { case CRYPT_RAND_HMAC_SHA1: return g_mdDisableTable[1] == 1; case CRYPT_RAND_HMAC_SHA224: return g_mdDisableTable[2] == 1; case CRYPT_RAND_HMAC_SHA256: return g_mdDisableTable[3] == 1; case CRYPT_RAND_HMAC_SHA384: return g_mdDisableTable[4] == 1; case CRYPT_RAND_HMAC_SHA512: return g_mdDisableTable[5] == 1; default: return false; } } int GetAvailableRandAlgId(void) { if (g_isInitRandAlg) { return g_avlRandAlg; } g_isInitRandAlg = true; if (!IsDrbgHashDisabled()) { g_avlRandAlg = GetDrbgHashAlgId(); if (g_avlRandAlg != ERR_ID) { return g_avlRandAlg; } } if (!IsDrbgHmacDisabled()) { g_avlRandAlg = GetDrbgHmacAlgId(); if (g_avlRandAlg != ERR_ID) { return g_avlRandAlg; } } if (!IsDrbgCtrDisabled()) { g_avlRandAlg = CRYPT_RAND_AES256_CTR; return g_avlRandAlg; } return g_avlRandAlg; } bool IsRandAlgDisabled(int id) { switch (id) { case CRYPT_RAND_SHA1: case CRYPT_RAND_SHA224: case CRYPT_RAND_SHA256: case CRYPT_RAND_SHA384: case CRYPT_RAND_SHA512: case CRYPT_RAND_SM3: return IsDrbgHashAlgDisabled(id); case CRYPT_RAND_HMAC_SHA1: case CRYPT_RAND_HMAC_SHA224: case CRYPT_RAND_HMAC_SHA256: case CRYPT_RAND_HMAC_SHA384: case CRYPT_RAND_HMAC_SHA512: return IsDrbgHmacAlgDisabled(id); case CRYPT_RAND_AES128_CTR: case CRYPT_RAND_AES192_CTR: case CRYPT_RAND_AES256_CTR: case CRYPT_RAND_AES128_CTR_DF: case CRYPT_RAND_AES192_CTR_DF: case CRYPT_RAND_AES256_CTR_DF: return IsDrbgCtrDisabled(); case CRYPT_RAND_SM4_CTR_DF: return IsDrbgCtrSm4Disabled(); default: return false; } return false; } bool IsAesAlgDisabled(int id) { #ifdef HITLS_CRYPTO_AES switch (id) { #ifndef HITLS_CRYPTO_CBC case CRYPT_CIPHER_AES128_CBC: case CRYPT_CIPHER_AES192_CBC: case CRYPT_CIPHER_AES256_CBC: return true; #endif #ifndef HITLS_CRYPTO_ECB case CRYPT_CIPHER_AES128_ECB: case CRYPT_CIPHER_AES192_ECB: case CRYPT_CIPHER_AES256_ECB: return true; #endif #ifndef HITLS_CRYPTO_CTR case CRYPT_CIPHER_AES128_CTR: case CRYPT_CIPHER_AES192_CTR: case CRYPT_CIPHER_AES256_CTR: return true; #endif #ifndef HITLS_CRYPTO_CCM case CRYPT_CIPHER_AES128_CCM: case CRYPT_CIPHER_AES192_CCM: case CRYPT_CIPHER_AES256_CCM: return true; #endif #ifndef HITLS_CRYPTO_GCM case CRYPT_CIPHER_AES128_GCM: case CRYPT_CIPHER_AES192_GCM: case CRYPT_CIPHER_AES256_GCM: return true; #endif #ifndef HITLS_CRYPTO_CFB case CRYPT_CIPHER_AES128_CFB: case CRYPT_CIPHER_AES192_CFB: case CRYPT_CIPHER_AES256_CFB: return true; #endif #ifndef HITLS_CRYPTO_OFB case CRYPT_CIPHER_AES128_OFB: case CRYPT_CIPHER_AES192_OFB: case CRYPT_CIPHER_AES256_OFB: return true; #endif #ifndef HITLS_CRYPTO_XTS case CRYPT_CIPHER_AES128_XTS: case CRYPT_CIPHER_AES256_XTS: return true; #endif default: return false; // Unsupported algorithm ID } #else (void)id; return true; #endif } bool IsSm4AlgDisabled(int id) { #ifdef HITLS_CRYPTO_SM4 switch (id) { #ifndef HITLS_CRYPTO_XTS case CRYPT_CIPHER_SM4_XTS: return true; #endif #ifndef HITLS_CRYPTO_CBC case CRYPT_CIPHER_SM4_CBC: return true; #endif #ifndef HITLS_CRYPTO_ECB case CRYPT_CIPHER_SM4_ECB: return true; #endif #ifndef HITLS_CRYPTO_CTR case CRYPT_CIPHER_SM4_CTR: return true; #endif #ifndef HITLS_CRYPTO_GCM case CRYPT_CIPHER_SM4_GCM: return true; #endif #ifndef HITLS_CRYPTO_CFB case CRYPT_CIPHER_SM4_CFB: return true; #endif #ifndef HITLS_CRYPTO_OFB case CRYPT_CIPHER_SM4_OFB: return true; #endif default: return false; // Unsupported algorithm ID } #else (void)id; return true; #endif } bool IsCipherAlgDisabled(int id) { switch (id) { case CRYPT_CIPHER_AES128_CBC: case CRYPT_CIPHER_AES192_CBC: case CRYPT_CIPHER_AES256_CBC: case CRYPT_CIPHER_AES128_CTR: case CRYPT_CIPHER_AES192_CTR: case CRYPT_CIPHER_AES256_CTR: case CRYPT_CIPHER_AES128_CCM: case CRYPT_CIPHER_AES192_CCM: case CRYPT_CIPHER_AES256_CCM: case CRYPT_CIPHER_AES128_GCM: case CRYPT_CIPHER_AES192_GCM: case CRYPT_CIPHER_AES256_GCM: case CRYPT_CIPHER_AES128_CFB: case CRYPT_CIPHER_AES192_CFB: case CRYPT_CIPHER_AES256_CFB: case CRYPT_CIPHER_AES128_OFB: case CRYPT_CIPHER_AES192_OFB: case CRYPT_CIPHER_AES256_OFB: return IsAesAlgDisabled(id); case CRYPT_CIPHER_CHACHA20_POLY1305: #if !defined(HITLS_CRYPTO_CHACHA20) && !defined(HITLS_CRYPTO_CHACHA20POLY1305) return true; #else return false; #endif case CRYPT_CIPHER_SM4_XTS: case CRYPT_CIPHER_SM4_CBC: case CRYPT_CIPHER_SM4_CTR: case CRYPT_CIPHER_SM4_GCM: case CRYPT_CIPHER_SM4_CFB: case CRYPT_CIPHER_SM4_OFB: return IsSm4AlgDisabled(id); default: return false; } } bool IsCmacAlgDisabled(int id) { #ifdef HITLS_CRYPTO_CMAC switch (id) { #ifndef HITLS_CRYPTO_CMAC_AES case CRYPT_MAC_CMAC_AES128: case CRYPT_MAC_CMAC_AES192: case CRYPT_MAC_CMAC_AES256: return true; #endif #ifndef HITLS_CRYPTO_CMAC_SM4 case CRYPT_MAC_CMAC_SM4: return true; #endif default: return false; // Unsupported algorithm ID } #else (void)id; return true; #endif } bool IsCurveDisabled(int eccId) { switch (eccId) { #ifdef HITLS_CRYPTO_CURVE_NISTP224 case CRYPT_ECC_NISTP224: return false; #endif #ifdef HITLS_CRYPTO_CURVE_NISTP256 case CRYPT_ECC_NISTP256: return false; #endif #ifdef HITLS_CRYPTO_CURVE_NISTP384 case CRYPT_ECC_NISTP384: return false; #endif #ifdef HITLS_CRYPTO_CURVE_NISTP521 case CRYPT_ECC_NISTP521: return false; #endif #ifdef HITLS_CRYPTO_CURVE_BP256R1 case CRYPT_ECC_BRAINPOOLP256R1: return false; #endif #ifdef HITLS_CRYPTO_CURVE_BP384R1 case CRYPT_ECC_BRAINPOOLP384R1: return false; #endif #ifdef HITLS_CRYPTO_CURVE_BP512R1 case CRYPT_ECC_BRAINPOOLP512R1: return false; #endif #ifdef HITLS_CRYPTO_CURVE_192WAPI case CRYPT_ECC_192WAPI: return false; #endif default: return true; } } bool IsCurve25519AlgDisabled(int id) { if (id == CRYPT_PKEY_ED25519) { #ifndef HITLS_CRYPTO_ED25519 return true; #else return false; #endif } if (id == CRYPT_PKEY_X25519) { #ifndef HITLS_CRYPTO_X25519 return true; #else return false; #endif } return false; // Unsupported algorithm ID }
2301_79861745/bench_create
testcode/framework/crypto/alg_check.c
C
unknown
13,604
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include <pthread.h> #include <unistd.h> #include <fcntl.h> #include "hitls_build.h" #include "bsl_sal.h" #include "bsl_errno.h" #include "crypt_errno.h" #include "crypt_types.h" #include "crypt_eal_md.h" #include "eal_md_local.h" #include "crypt_eal_rand.h" #include "crypt_eal_mac.h" #include "crypt_eal_init.h" #include "test.h" #include "helper.h" #include "crypto_test_util.h" #include "securec.h" #include "crypt_util_rand.h" #ifndef HITLS_BSL_SAL_MEM void *TestMalloc(uint32_t len) { return malloc((size_t)len); } #endif void TestMemInit(void) { #ifdef HITLS_BSL_SAL_MEM return; #else BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_MALLOC, TestMalloc); BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_FREE, free); #endif } #if defined(HITLS_CRYPTO_EAL) && defined(HITLS_CRYPTO_DRBG) typedef struct { CRYPT_Data *entropy; CRYPT_Data *nonce; CRYPT_Data *pers; CRYPT_Data *addin1; CRYPT_Data *entropyPR1; CRYPT_Data *addin2; CRYPT_Data *entropyPR2; CRYPT_Data *retBits; } DRBG_Vec_t; #ifndef HITLS_CRYPTO_ENTROPY static int32_t GetEntropy(void *ctx, CRYPT_Data *entropy, uint32_t strength, CRYPT_Range *lenRange) { if (lenRange == NULL) { Print("getEntropy Error lenRange NULL\n"); return CRYPT_NULL_INPUT; } if (ctx == NULL || entropy == NULL) { Print("getEntropy Error\n"); lenRange->max = strength; return CRYPT_NULL_INPUT; } DRBG_Vec_t *seedCtx = (DRBG_Vec_t *)ctx; entropy->data = seedCtx->entropy->data; entropy->len = seedCtx->entropy->len; return CRYPT_SUCCESS; } static void CleanEntropy(void *ctx, CRYPT_Data *entropy) { (void)ctx; (void)entropy; return; } #endif int32_t TestSimpleRand(uint8_t *buff, uint32_t len) { int rand = open("/dev/urandom", O_RDONLY); if (rand < 0) { printf("open /dev/urandom failed.\n"); return -1; } int l = read(rand, buff, len); if (l < 0) { printf("read from /dev/urandom failed. errno: %d.\n", errno); close(rand); return -1; } close(rand); return 0; } int32_t TestSimpleRandEx(void *libCtx, uint8_t *buff, uint32_t len) { (void)libCtx; return TestSimpleRand(buff, len); } int TestRandInitEx(void *libCtx) { (void)libCtx; int drbgAlgId = GetAvailableRandAlgId(); int32_t ret; if (drbgAlgId == -1) { Print("Drbg algs are disabled."); return CRYPT_NOT_SUPPORT; } #ifndef HITLS_CRYPTO_ENTROPY CRYPT_RandSeedMethod seedMeth = {GetEntropy, CleanEntropy, NULL, NULL}; uint8_t entropy[64] = {0}; CRYPT_Data tempEntropy = {entropy, sizeof(entropy)}; DRBG_Vec_t seedCtx = {0}; seedCtx.entropy = &tempEntropy; #endif #ifdef HITLS_CRYPTO_PROVIDER #ifndef HITLS_CRYPTO_ENTROPY BSL_Param param[4] = {0}; (void)BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_RAND_SEEDCTX, BSL_PARAM_TYPE_CTX_PTR, &seedCtx, 0); (void)BSL_PARAM_InitValue(&param[1], CRYPT_PARAM_RAND_SEED_GETENTROPY, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.getEntropy, 0); (void)BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_RAND_SEED_CLEANENTROPY, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.cleanEntropy, 0); ret = CRYPT_EAL_ProviderRandInitCtx(NULL, (CRYPT_RAND_AlgId)drbgAlgId, "provider=default", NULL, 0, param); #else ret = CRYPT_EAL_ProviderRandInitCtx(libCtx, (CRYPT_RAND_AlgId)drbgAlgId, "provider=default", NULL, 0, NULL); #endif #else #ifndef HITLS_CRYPTO_ENTROPY ret = CRYPT_EAL_RandInit(drbgAlgId, &seedMeth, (void *)&seedCtx, NULL, 0); #else ret = CRYPT_EAL_RandInit(drbgAlgId, NULL, NULL, NULL, 0); #endif #endif if (ret == CRYPT_EAL_ERR_DRBG_REPEAT_INIT) { ret = CRYPT_SUCCESS; } return ret; } int TestRandInit(void) { return TestRandInitEx(NULL); } void TestRandDeInit(void) { #ifdef HITLS_CRYPTO_PROVIDER CRYPT_EAL_RandDeinitEx(NULL); #else CRYPT_EAL_RandDeinit(); #endif } #endif #if defined(HITLS_CRYPTO_EAL) && defined(HITLS_CRYPTO_MAC) uint32_t TestGetMacLen(int algId) { switch (algId) { case CRYPT_MAC_HMAC_MD5: return 16; case CRYPT_MAC_HMAC_SHA1: return 20; case CRYPT_MAC_HMAC_SHA224: case CRYPT_MAC_HMAC_SHA3_224: return 28; case CRYPT_MAC_HMAC_SHA256: case CRYPT_MAC_HMAC_SHA3_256: return 32; case CRYPT_MAC_HMAC_SHA384: case CRYPT_MAC_HMAC_SHA3_384: return 48; case CRYPT_MAC_HMAC_SHA512: case CRYPT_MAC_HMAC_SHA3_512: return 64; case CRYPT_MAC_HMAC_SM3: return 32; case CRYPT_MAC_CMAC_AES128: case CRYPT_MAC_CMAC_AES192: case CRYPT_MAC_CMAC_AES256: return 16; // AES block size case CRYPT_MAC_CMAC_SM4: return 16;// SM4 block size case CRYPT_MAC_CBC_MAC_SM4: return 16;// SM4 block size case CRYPT_MAC_SIPHASH64: return 8; case CRYPT_MAC_SIPHASH128: return 16; default: return 0; } } void TestMacSameAddr(int algId, Hex *key, Hex *data, Hex *mac) { uint32_t outLen = data->len > mac->len ? data->len : mac->len; uint8_t out[outLen]; CRYPT_EAL_MacCtx *ctx = NULL; int padType = CRYPT_PADDING_ZEROS; ASSERT_EQ(memcpy_s(out, outLen, data->x, data->len), 0); TestMemInit(); ASSERT_TRUE((ctx = CRYPT_EAL_MacNewCtx(algId)) != NULL); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key->x, key->len), CRYPT_SUCCESS); if (algId == CRYPT_MAC_CBC_MAC_SM4) { ASSERT_EQ(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(int)), CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, out, data->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("mac result cmp", out, outLen, mac->x, mac->len); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } void TestMacAddrNotAlign(int algId, Hex *key, Hex *data, Hex *mac) { uint32_t outLen = data->len > mac->len ? data->len : mac->len; uint8_t out[outLen]; CRYPT_EAL_MacCtx *ctx = NULL; int padType = CRYPT_PADDING_ZEROS; uint8_t keyTmp[key->len + 1] __attribute__((aligned(8))); uint8_t dataTmp[data->len + 1] __attribute__((aligned(8))); uint8_t *pKey = keyTmp + 1; uint8_t *pData = dataTmp + 1; ASSERT_TRUE(memcpy_s(pKey, key->len, key->x, key->len) == EOK); ASSERT_TRUE(memcpy_s(pData, data->len, data->x, data->len) == EOK); TestMemInit(); ASSERT_TRUE((ctx = CRYPT_EAL_MacNewCtx(algId)) != NULL); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, pKey, key->len), CRYPT_SUCCESS); if (algId == CRYPT_MAC_CBC_MAC_SM4) { ASSERT_EQ(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(int)), CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, pData, data->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("mac result cmp", out, outLen, mac->x, mac->len); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } #endif #ifdef HITLS_CRYPTO_CIPHER CRYPT_EAL_CipherCtx *TestCipherNewCtx(CRYPT_EAL_LibCtx *libCtx, int32_t id, const char *attrName, int isProvider) { #ifdef HITLS_CRYPTO_PROVIDER if (isProvider == 1) { if (CRYPT_EAL_Init(0) != CRYPT_SUCCESS) { return NULL; } return CRYPT_EAL_ProviderCipherNewCtx(libCtx, id, attrName); } else { return CRYPT_EAL_CipherNewCtx(id); } #else (void)libCtx; (void)attrName; (void)isProvider; return CRYPT_EAL_CipherNewCtx(id); #endif } #endif #ifdef HITLS_CRYPTO_PKEY CRYPT_EAL_PkeyCtx *TestPkeyNewCtx( CRYPT_EAL_LibCtx *libCtx, int32_t id, uint32_t operType, const char *attrName, int isProvider) { #ifdef HITLS_CRYPTO_PROVIDER if (isProvider == 1) { #ifdef HITLS_CRYPTO_EALINIT if (CRYPT_EAL_Init(0) != CRYPT_SUCCESS) { return NULL; } #endif return CRYPT_EAL_ProviderPkeyNewCtx(libCtx, id, operType, attrName); } else { return CRYPT_EAL_PkeyNewCtx(id); } #else (void)libCtx; (void)operType; (void)attrName; (void)isProvider; return CRYPT_EAL_PkeyNewCtx(id); #endif } #endif
2301_79861745/bench_create
testcode/framework/crypto/crypto_test_util.c
C
unknown
8,760
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPTO_TEST_UTIL_H #define CRYPTO_TEST_UTIL_H #include "hitls_build.h" #include "crypt_eal_cipher.h" #include "crypt_eal_pkey.h" #ifdef __cplusplus extern "C" { #endif void TestMemInit(void); int TestRandInit(void); int TestRandInitEx(void *libCtx); void TestRandDeInit(void); bool IsMdAlgDisabled(int id); bool IsHmacAlgDisabled(int id); bool IsMacAlgDisabled(int id); bool IsDrbgHashAlgDisabled(int id); bool IsDrbgHmacAlgDisabled(int id); int GetAvailableRandAlgId(void); bool IsRandAlgDisabled(int id); bool IsAesAlgDisabled(int id); bool IsSm4AlgDisabled(int id); bool IsCipherAlgDisabled(int id); bool IsCmacAlgDisabled(int id); bool IsCurveDisabled(int eccId); bool IsCurve25519AlgDisabled(int id); int32_t TestSimpleRand(uint8_t *buff, uint32_t len); int32_t TestSimpleRandEx(void *libCtx, uint8_t *buff, uint32_t len); #if defined(HITLS_CRYPTO_EAL) && defined(HITLS_CRYPTO_MAC) uint32_t TestGetMacLen(int algId); void TestMacSameAddr(int algId, Hex *key, Hex *data, Hex *mac); void TestMacAddrNotAlign(int algId, Hex *key, Hex *data, Hex *mac); #endif #ifdef HITLS_CRYPTO_CIPHER CRYPT_EAL_CipherCtx *TestCipherNewCtx(CRYPT_EAL_LibCtx *libCtx, int32_t id, const char *attrName, int isProvider); #endif #ifdef HITLS_CRYPTO_PKEY CRYPT_EAL_PkeyCtx *TestPkeyNewCtx( CRYPT_EAL_LibCtx *libCtx, int32_t id, uint32_t operType, const char *attrName, int isProvider); #endif #ifdef __cplusplus } #endif #endif // CRYPTO_TEST_UTIL_H
2301_79861745/bench_create
testcode/framework/crypto/crypto_test_util.h
C
unknown
2,009
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. cmake_minimum_required(VERSION 3.16 FATAL_ERROR) project(GEN_TEST) set(GEN_TESTCASE "gen_testcase") set(HITLS_SRC ${PROJECT_SOURCE_DIR}/../../..) set(EXECUTABLE_OUTPUT_PATH ${HITLS_SRC}/testcode/output) set(SECURTE_INCLUDE ${HITLS_SRC}/platform/Secure_C/include) set(GEN_SOURCE_SRC ${PROJECT_SOURCE_DIR}/main.c ${PROJECT_SOURCE_DIR}/helper.c ${PROJECT_SOURCE_DIR}/test.c ) include_directories(${SECURTE_INCLUDE} ${HITLS_SRC}/testcode/framework/include ${HITLS_SRC}/testcode/framework/crypto ${HITLS_SRC}/config/macro_config ${HITLS_SRC}/crypto/include ${HITLS_SRC}/include/crypto ${HITLS_SRC}/include/bsl ${HITLS_SRC}/bsl/err/include ) add_executable(${GEN_TESTCASE} ${GEN_SOURCE_SRC}) if(PRINT_TO_TERMINAL) target_compile_options(${GEN_TESTCASE} PRIVATE -DPRINT_TO_TERMINAL) endif() target_link_directories(${GEN_TESTCASE} PRIVATE ${HITLS_SRC}/platform/Secure_C/lib ) target_link_libraries(${GEN_TESTCASE} boundscheck )
2301_79861745/bench_create
testcode/framework/gen_test/CMakeLists.txt
CMake
unknown
1,511
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "helper.h" #include <dirent.h> #include "securec.h" #include "crypt_utils.h" #define INCLUDE_BASE "/* INCLUDE_BASE" #define BEGIN_HEADER "/* BEGIN_HEADER */" #define END_HEADER "/* END_HEADER */" #define BEGIN_CASE "/* BEGIN_CASE */" #define END_CASE "/* END_CASE */" #define PRINT_TESTSUITES_TAG "</testsuites>\n" #define PRINT_TESTSUITE_TAG " </testsuite>\n" #define PRINT_TESTCASE_TAG " </testcase>\n" #define PRINT_TESTCASE_LIST_TAG " <testcase name=\"%s\" status=\"run\" time=\"0\" classname=\"%s\" />\n" #define PRINT_FAILURE_TAG " <failure message=\"failed\" type=\"\" />\n" #define LINE_BREAK_SYMBOL '\n' #define LINE_HEAD_SYMBOL '\r' FunctionTable g_testFunc[MAX_TEST_FUCNTION_COUNT]; int g_testFuncCount = 0; char g_expTable[MAX_EXPRESSION_COUNT][MAX_EXPRESSION_LEN]; int g_expCount = 0; FILE *g_fpOutput = NULL; int g_lineCount = 0; char g_suiteFileName[MAX_FILE_PATH_LEN]; void SetOutputFile(FILE *fp) { g_fpOutput = fp; } FILE *GetOutputFile(void) { return g_fpOutput; } void FreeHex(Hex *data) { if (data == NULL) { return; } data->len = 0; if (data->x != NULL) { free(data->x); data->x = NULL; } } Hex *NewHex(void) { Hex *data = (Hex *)malloc(sizeof(Hex)); if (data == NULL) { return NULL; } data->len = 0; data->x = NULL; return data; } int IsInt(const char *str) { uint32_t i = 0; if (str[0] == '-') { i = 1; } for (; i < strlen(str); i++) { if (str[i] > '9' || str[i] < '0') { return 0; } } return 1; } void Print(const char *fmt, ...) { #ifdef PRINT_TO_TERMINAL va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); #else va_list args; va_start(args, fmt); (void)vfprintf(g_fpOutput, fmt, args); va_end(args); #endif } int ReadLine(FILE *file, char *buf, uint32_t bufLen, bool skipHash, bool skipEmptyLine) { int foundLine = 0; int i; char *ret = NULL; while (!foundLine) { ret = fgets(buf, bufLen, file); if (ret == NULL) { return -1; } g_lineCount++; int len = strlen(buf); if ((buf[0] == '#') && skipHash) { continue; } if (!skipEmptyLine) { foundLine = 1; } for (i = 0; i < len; i++) { char cur = buf[i]; if (cur != ' ' && cur != LINE_BREAK_SYMBOL && cur != LINE_HEAD_SYMBOL) { foundLine = 1; } if (cur == LINE_BREAK_SYMBOL || cur == LINE_HEAD_SYMBOL) { buf[i] = '\0'; break; } } } return 0; } int SplitArguments(char *inStr, uint32_t inLen, char **outParam, uint32_t *paramLen) { uint32_t cur = 0; uint32_t count = 0; bool inString = false; char *in = inStr; char **param = outParam; param[count] = &in[cur]; count++; cur++; if (count > *paramLen) { return 1; } while (cur < inLen && in[cur] != '\0') { if (in[cur] == '\"') { inString = !inString; } if (in[cur] == ':' && !inString) { if (cur == inLen - 1) { param[count] = &in[cur]; } else { param[count] = &in[cur + 1]; count++; } if (count > *paramLen) { printf("Exceed maximum param limit, expect num %u, actual num %u\n", *paramLen, count); return 1; } in[cur] = '\0'; } cur++; } if (in[cur - 1] == '\n') { in[cur - 1] = '\0'; } *paramLen = count; if (inString) { return 1; } return 0; } static int g_fuzzEnd = 0; int CheckTag(char *in, uint32_t len) { char *cur = in; while (*cur == ' ') { cur++; } uint32_t beginHeaderLen = strlen(BEGIN_HEADER); uint32_t endHeaderLen = strlen(END_HEADER); uint32_t beginCaseLen = strlen(BEGIN_CASE); uint32_t endCaseLen = strlen(END_CASE); uint32_t includeBaseLen = strlen(INCLUDE_BASE); if ((len >= beginHeaderLen) && (strlen(cur) >= beginHeaderLen) && (strncmp(cur, BEGIN_HEADER, beginHeaderLen) == 0)) { return TAG_BEGIN_HEADER; } else if ((len >= endHeaderLen) && (strlen(cur) >= endHeaderLen) && (strncmp(cur, END_HEADER, endHeaderLen) == 0)) { return TAG_END_HEADER; } else if ((len >= beginCaseLen) && (strlen(cur) >= beginCaseLen) && (strncmp(cur, BEGIN_CASE, beginCaseLen) == 0)) { return TAG_BEGIN_CASE; } else if ((len >= endCaseLen) && (strlen(cur) >= endCaseLen) && (strncmp(cur, END_CASE, endCaseLen) == 0)) { return TAG_END_CASE; } else if ((len >= includeBaseLen) && (strlen(cur) >= includeBaseLen) && (strncmp(cur, INCLUDE_BASE, includeBaseLen) == 0)) { return TAG_INCLUDE_BASE; } return TAG_NOT_TAG; } static int ClearVoid(const char *in, const uint32_t inLen, uint32_t *cur, uint32_t *prev) { uint32_t localCur = *cur; uint32_t localPrev; while (localCur < inLen && in[localCur] == ' ') { localCur++; } localPrev = localCur; if (strncmp(&in[localCur], "void", strlen("void")) != 0) { return 1; } localCur += strlen("void"); while (localCur < inLen && in[localCur] == ' ') { localCur++; } localPrev = localCur; *cur = localCur; *prev = localPrev; return 0; } static int NextArgument(const char *in, const uint32_t inLen, uint32_t *cur) { uint32_t localCur = *cur; while (localCur < inLen && in[localCur] != ',' && in[localCur] != ')') { localCur++; } if (localCur >= inLen) { return 1; } *cur = localCur; return 0; } static int CheckType(const char *in, const uint32_t cur, const uint32_t prev, int *outType) { int *type = outType; if ((cur - prev == strlen("int")) && (strncmp(&in[prev], "int", strlen("int")) == 0)) { *type = ARG_TYPE_INT; } else if ((cur - prev == strlen("Hex")) && (strncmp(&in[prev], "Hex", strlen("Hex")) == 0)) { *type = ARG_TYPE_HEX; } else if ((cur - prev == strlen("char")) && (strncmp(&in[prev], "char", strlen("char")) == 0)) { *type = ARG_TYPE_STR; } else { return 1; } return 0; } int ReadFunction(const char *in, const uint32_t inLen, char *outFuncName, uint32_t outLen, int argv[MAX_ARGUMENT_COUNT], uint32_t *argCount) { uint32_t cur = 0; uint32_t prev = 0; char *funcName = outFuncName; if (ClearVoid(in, inLen, &cur, &prev) != 0) { return 1; } // get function name while (cur < inLen && in[cur] != '(') { cur++; } if (cur >= inLen) { return 1; } if (strncpy_s(funcName, outLen, &in[prev], cur - prev) != 0) { return 1; } funcName[cur - prev] = '\0'; cur++; // get argument types uint32_t count = 0; while (cur < inLen) { while (cur < inLen && in[cur] == ' ') { cur++; } prev = cur; while (cur < inLen && in[cur] != ' ' && in[cur] != ',' && in[cur] != '*' && in[cur] != ')') { cur++; } if (in[cur] == ')') { break; } if (cur == inLen || in[cur] == ',') { return 1; } int type = -1; if (CheckType(in, cur, prev, &type) != 0) { Print("******\nERROR: check type failed at: \n"); return 1; } argv[count] = type; count++; if (NextArgument(in, inLen, &cur) != 0) { return 1; } if (in[cur] == ')') { break; } cur++; } *argCount = count; return 0; } int AddFunction(const char *funcName, int argv[MAX_ARGUMENT_COUNT], const uint32_t argCount) { if (g_testFuncCount >= MAX_TEST_FUCNTION_COUNT || argCount > MAX_ARGUMENT_COUNT) { return 1; } if (strcpy_s(g_testFunc[g_testFuncCount].name, MAX_TEST_FUNCTION_NAME, funcName) != 0) { return 1; } g_testFunc[g_testFuncCount].argCount = argCount; for (uint32_t i = 0; i < argCount; i++) { g_testFunc[g_testFuncCount].argType[i] = argv[i]; } g_testFunc[g_testFuncCount].id = g_testFuncCount; g_testFuncCount++; return 0; } int GenFunctionWrapper(FILE *file, FunctionTable *function) { int ret; ret = fprintf(file, "void %s_wrapper(void **param)\n", function->name); if (ret < 0) { return 1; } ret = fprintf(file, "{\n"); if (ret < 0) { return 1; } ret = fprintf(file, " (void)signal(SIGALRM, handleAlarmSignal);\n"); if (ret < 0) { return 1; } ret = fprintf(file, " alarm(600u);\n"); if (ret < 0) { return 1; } if (function->argCount == 0) { ret = fprintf(file, " (void) param;\n"); if (ret < 0) { return 1; } } ret = fprintf(file, " %s(", function->name); if (ret < 0) { return 1; } for (uint32_t i = 0; i < function->argCount; i++) { if (function->argType[i] == ARG_TYPE_INT) { ret = fprintf(file, "*((int*)param[%d])", (int)i); if (ret < 0) { return 1; } } else if (function->argType[i] == ARG_TYPE_STR) { ret = fprintf(file, "(char*)param[%d]", (int)i); if (ret < 0) { return 1; } } else if (function->argType[i] == ARG_TYPE_HEX) { ret = fprintf(file, "(Hex*)param[%d]", (int)i); if (ret < 0) { return 1; } } if (i != function->argCount - 1) { ret = fprintf(file, ", "); if (ret < 0) { return 1; } } } ret = fprintf(file, ");\n}\n\n"); if (ret < 0) { return 1; } return 0; } int GenFunctionPointer(FILE *file) { if (file == NULL) { return 1; } int ret; ret = fprintf(file, "%s\n\n", "typedef void (*TestWrapper)(void **param);"); if (ret < 0) { return 1; } ret = fprintf(file, "%s\n%s\n", "TestWrapper test_funcs[] = ", "{"); if (ret < 0) { return 1; } for (int i = 0; i < g_testFuncCount; i++) { ret = fprintf(file, " %s_wrapper, \n", g_testFunc[i].name); if (ret < 0) { return 1; } } ret = fprintf(file, "%s\n", "};"); if (ret < 0) { return 1; } return 0; } static int ConnectFunction(char *lineBuf, uint32_t bufLen, FILE *fp) { char buf[MAX_FUNCTION_LINE_LEN]; bool reachEnd = false; int ret = 0; while (!reachEnd) { for (int i = 0; lineBuf[i] != '\0'; i++) { if (lineBuf[i] == ')') { ret = 0; reachEnd = true; } if (lineBuf[i] == '{') { ret = 1; reachEnd = true; } } if (reachEnd) { break; } if (ReadLine(fp, buf, MAX_FUNCTION_LINE_LEN, 0, 0) == 0) { if (strcat_s(lineBuf, bufLen, buf) != 0) { return 1; } } else { return 1; } } return ret; } int ScanAllFunction(FILE *inFile, FILE *outFile) { char buf[MAX_FUNCTION_LINE_LEN]; int ret = 0; uint32_t len = MAX_ARGUMENT_COUNT; bool inFunction = false; bool isDeclaration = true; int arguments[MAX_ARGUMENT_COUNT]; char funcName[MAX_TEST_FUNCTION_NAME]; while (ReadLine(inFile, buf, MAX_FUNCTION_LINE_LEN, 0, 0) == 0) { int curTag = CheckTag(buf, strlen(buf)); if (curTag == TAG_NOT_TAG) { if (!inFunction) { fprintf(outFile, "%s\n", buf); continue; } } else if (curTag == TAG_BEGIN_CASE) { if (!inFunction) { inFunction = true; isDeclaration = true; continue; } Print("ERROR: missing end case tag\n"); return 1; } else if (curTag == TAG_END_CASE) { if (inFunction) { inFunction = false; fprintf(outFile, "\n"); continue; } return 1; } else { return 1; } if (isDeclaration) { if (ConnectFunction(buf, sizeof(buf), inFile) != 0) { Print("******\nERROR: connect function failed at: \n"); Print("%s\n", buf); return 1; } ret = ReadFunction(buf, strlen(buf), funcName, sizeof(funcName), arguments, &len); if (ret != 0) { Print("*******\nERROR: Read function failed at: \n"); Print("%s\n", buf); return ret; } ret = AddFunction(funcName, arguments, len); if (ret != 0) { return ret; } isDeclaration = false; len = MAX_ARGUMENT_COUNT; } (void)fprintf(outFile, "%s\n", buf); } return 0; } static int IncludeBase(char *line, uint32_t len, FILE *outFile, const char *dir) { if (len < strlen(INCLUDE_BASE)) { return 1; } char *name = &line[strlen(INCLUDE_BASE)]; while (*name == ' ') { name++; } if (*name == '\0') { return 1; } char *end = name; while (*end != ' ') { end++; } *end = '\0'; char fileBuf[MAX_FILE_PATH_LEN]; if (snprintf_s(fileBuf, MAX_FILE_PATH_LEN, MAX_FILE_PATH_LEN, BASE_FILE_FORMAT, dir, name) == -1) { return 1; } g_lineCount = 0; FILE *fpBase = fopen(fileBuf, "r"); if (fpBase == NULL) { Print("ERROR:Open the base file. %s An error occurred when\n", fileBuf); return 1; } int ret; char buf[MAX_FUNCTION_LINE_LEN]; while (ReadLine(fpBase, buf, MAX_FUNCTION_LINE_LEN, 0, 0) == 0) { ret = fprintf(outFile, "%s\n", buf); if (ret < 0) { goto EXIT; } } EXIT: if (fclose(fpBase) != 0) { Print("base file close failed\n"); } return 0; } int WriteHeader(FILE *outFile) { if (fprintf(outFile, "#include \"helper.h\"\n#include \"test.h\"\n#include <time.h>\n#include <unistd.h>\n") < 0) { return 1; } return 0; } int ScanHeader(FILE *inFile, FILE *outFile, const char *dir) { char buf[MAX_FUNCTION_LINE_LEN]; bool inHeader = false; while (ReadLine(inFile, buf, MAX_FUNCTION_LINE_LEN, 0, !inHeader) == 0) { int curTag = CheckTag(buf, strlen(buf)); if (curTag == TAG_BEGIN_HEADER) { if (!inHeader) { inHeader = true; } else { Print("******\nERROR: duplicate begin header tag\n"); return 1; } } else if (curTag == TAG_END_HEADER) { if (inHeader) { (void)fprintf(outFile, "%s\n", buf); return 0; } else { Print("******\nERROR: found end header without begin\n"); return 1; } } else if (curTag == TAG_INCLUDE_BASE) { int tmpLineCount = g_lineCount; if (IncludeBase(buf, strlen(buf), outFile, dir) != 0) { Print("******\nERROR: include base file failed\n"); return 1; } g_lineCount = tmpLineCount; continue; } else if (curTag != TAG_NOT_TAG) { Print("******\nERROR: missing end header tag\n"); return 1; } (void)fprintf(outFile, "%s\n", buf); } return 0; } static int AddExp(const char *exp) { if (g_expCount >= MAX_EXPRESSION_COUNT) { Print("Too much macros. Max macro count is %d\n", MAX_EXPRESSION_COUNT); return -1; } for (int i = 0; i < g_expCount; i++) { if (strcmp(exp, g_expTable[i]) == 0) { return i; } } if (strcpy_s(g_expTable[g_expCount], MAX_EXPRESSION_LEN, exp) != 0) { Print("Macro too long, max length is %d\n", MAX_EXPRESSION_LEN); return -1; } g_expCount++; return g_expCount - 1; } static int GetFuncIdByName(const char *name, uint32_t len) { int funcId = -1; for (int i = 0; i < g_testFuncCount; i++) { if ((len < MAX_TEST_FUNCTION_NAME) && (strcmp(name, g_testFunc[i].name) == 0)) { funcId = i; break; } } return funcId; } int GenDatax(FILE *inFile, FILE *outFile) { char buf[MAX_DATA_LINE_LEN]; char title[MAX_DATA_LINE_LEN]; int ret; int funcId = -1; char *param[MAX_ARGUMENT_COUNT]; uint32_t paramLen = MAX_ARGUMENT_COUNT; while (ReadLine(inFile, title, MAX_DATA_LINE_LEN, 1, 1) == 0) { ret = fprintf(outFile, "%s\n", title); if (ret < 0) { return 1; } if ((ReadLine(inFile, buf, MAX_DATA_LINE_LEN, 1, 1) != 0)) { return 1; } paramLen = MAX_ARGUMENT_COUNT; ret = SplitArguments(buf, strlen(buf), param, &paramLen); if (ret != 0) { Print("******\nERROR: Generate datax failed: split argument failed at testcase:\n"); Print("%s\n", title); return ret; } funcId = GetFuncIdByName(param[0], strlen(param[0])); if (funcId == -1) { Print("******\nERROR: Generate datax failed: no function id for %s at testcase:\n", param[0]); Print("%s\n", title); return 1; } if (paramLen != g_testFunc[funcId].argCount + 1) { Print("******\nERROR: Generate datax failed: invalid argument count for function %s at testcase:\n", param[0]); Print("%s\n", title); return 1; } ret = fprintf(outFile, "%d:", funcId); if (ret < 0) { return 1; } int expId = 0; for (uint32_t i = 0; i < g_testFunc[funcId].argCount; i++) { if (g_testFunc[funcId].argType[i] == ARG_TYPE_INT && (IsInt(param[i + 1]) == 1)) { ret = fprintf(outFile, "int:%s", param[i + 1]); } else if (g_testFunc[funcId].argType[i] == ARG_TYPE_INT && (!IsInt(param[i + 1]))) { expId = AddExp(param[i + 1]); ret = fprintf(outFile, "exp:%d", expId); } else if (g_testFunc[funcId].argType[i] == ARG_TYPE_STR) { ret = fprintf(outFile, "char:%s", param[i + 1]); } else if (g_testFunc[funcId].argType[i] == ARG_TYPE_HEX) { ret = fprintf(outFile, "Hex:%s", param[i + 1]); } else { Print("invalid argument type\n"); return 1; } if (ret < 0) { return 1; } if (i != g_testFunc[funcId].argCount - 1) { ret = fprintf(outFile, ":"); } if (expId == -1) { return 1; } expId = 0; } ret = fprintf(outFile, "\n\n"); if (ret < 0) { return 1; } } return 0; } int GenExpTable(FILE *outFile) { int ret; ret = fprintf(outFile, "int getExpression(int expId, int *out)\n{\n"); if (ret < 0) { return 1; } if (g_expCount == 0) { ret = fprintf(outFile, " (void) out;\n (void) expId;\n"); if (ret < 0) { return 1; } } ret = fprintf(outFile, " int ret = 0;\n"); if (ret < 0) { return 1; } ret = fprintf(outFile, " switch (expId)\n {\n"); if (ret < 0) { return 1; } for (int i = 0; i < g_expCount; i++) { ret = fprintf(outFile, " case %d:\n", i); if (ret < 0) { return 1; } ret = fprintf(outFile, " *out = %s;\n", g_expTable[i]); if (ret < 0) { return 1; } ret = fprintf(outFile, " break;\n"); if (ret < 0) { return 1; } } ret = fprintf(outFile, " default:\n"); if (ret < 0) { return 1; } ret = fprintf(outFile, " ret = 1;\n"); if (ret < 0) { return 1; } ret = fprintf(outFile, " break;\n"); if (ret < 0) { return 1; } ret = fprintf(outFile, " }\n return ret;\n}\n"); if (ret < 0) { return 1; } return 0; } int LoadFunctionName(FILE *outFile) { int ret; ret = fprintf(outFile, "const char * funcName[] = {\n"); if (ret < 0) { return 1; } for (int i = 0; i < g_testFuncCount; i++) { ret = fprintf(outFile, " \"%s\",\n", g_testFunc[i].name); if (ret < 0) { return 1; } } ret = fprintf(outFile, "};\n\n"); if (ret < 0) { return 1; } return 0; } int LoadHelper(FILE *inFile, FILE *outFile) { int ret; char buf[MAX_FUNCTION_LINE_LEN]; if (inFile == NULL || outFile == NULL) { return 1; } while (fgets(buf, MAX_FUNCTION_LINE_LEN, inFile) != NULL) { ret = fprintf(outFile, "%s", buf); if (ret < 0) { return 1; } } (void)fprintf(outFile, "\n\n"); return 0; } int SplitHex(Hex *src, Hex *dest, int max) { uint32_t blocks = src->len / SPILT_HEX_BLOCK_SIZE; uint32_t remain = src->len % SPILT_HEX_BLOCK_SIZE; uint32_t i; if (blocks + 1 > (uint32_t)max) { return 0; } for (i = 0; i < blocks; i++) { dest[i].x = src->x + i * SPILT_HEX_BLOCK_SIZE; dest[i].len = SPILT_HEX_BLOCK_SIZE; } if (remain == 0) { return blocks; } else { dest[i].x = src->x + i * SPILT_HEX_BLOCK_SIZE; dest[i].len = remain; return blocks + 1; } } int SplitHexRand(Hex *src, Hex *dest, int max) { uint32_t left = src->len; int id = 0; if (left <= 3) { dest[id].x = src->x; dest[id].len = left; id++; return id; } while (left > 3) { dest[id].x = src->x + (src->len - left); uint16_t clen = GET_UINT16_LE(dest[id].x, 0); dest[id].len = clen > left ? left : clen; left -= dest[id].len; id++; if (id > max - 1) { break; } } if (left > 0) { dest[id - 1].len += left; } return id; } FILE *OpenFile(const char *name, const char *option, const char *format) { FILE *fp = NULL; char fileBuf[MAX_FILE_PATH_LEN]; if (snprintf_s(fileBuf, MAX_FILE_PATH_LEN, MAX_FILE_PATH_LEN, format, name) == -1) { Print("argument too long\n"); return NULL; } fp = fopen(fileBuf, option); return fp; } int StripDir(const char *in, char *suiteName, const uint32_t suiteNameLen, char *dir, const uint32_t dirNameLen) { int len = strlen(in); int begin = len - 1; char *localDir = dir; char *localSuiteName = suiteName; while (begin >= 0 && in[begin] != '/') { begin--; } if (begin < 0) { return 1; } if (strncpy_s(localDir, dirNameLen, in, begin) != 0) { return 1; } if (strcpy_s(localSuiteName, suiteNameLen, &in[begin + 1]) != 0) { return 1; } if (strcpy_s(g_suiteFileName, MAX_FILE_PATH_LEN, &in[begin + 1]) != 0) { return 1; } return 0; } int ScanFunctionFile(FILE *fpIn, FILE *fpOut, const char *dir) { int ret; ret = ScanHeader(fpIn, fpOut, dir); if (ret != 0) { Print("scan header failed\n"); return 1; } ret = ScanAllFunction(fpIn, fpOut); if (ret != 0) { Print("scan function failed\n"); return 1; } if (fprintf(fpOut, "\n void handleAlarmSignal(int signum)\n{\n\ (void)signum; \n\ fprintf(stderr, \"timeout 600\\n\");\n\ exit(-1);\n}\n") < 0) { return 1; } for (int i = 0; i < g_testFuncCount; i++) { ret = GenFunctionWrapper(fpOut, &g_testFunc[i]); if (ret < 0) { Print("generate function wrapper failed\n"); return 1; } } if (g_fuzzEnd == 1) { ret = fprintf(fpOut, "#define FREE_FUZZ_TC 1\n\n"); } else { ret = fprintf(fpOut, "#define FREE_FUZZ_TC 0\n\n"); } if (ret < 0) { return 1; } return 0; } static bool IsSuite(char *buf, uint32_t bufLen) { uint32_t beginTagLen = strlen("Begin time:"); uint32_t endTagLen = strlen("End time:"); uint32_t resultTagLen = strlen("Result:"); uint32_t atTagLen = strlen("at:"); if (bufLen >= beginTagLen && strncmp(buf, "Begin time:", beginTagLen) == 0) { return false; } else if (bufLen >= endTagLen && strncmp(buf, "End time:", endTagLen) == 0) { return false; } else if (bufLen >= resultTagLen && strncmp(buf, "Result:", resultTagLen) == 0) { return false; } else if (bufLen >= atTagLen && strncmp(buf, "at:", atTagLen) == 0) { return false; } return true; } static int ReadAllLogFile(DIR *logDir, int *totalSuiteCount, FILE *outFile, TestSuiteResult *result, int resultLen) { struct dirent *dir = NULL; int suiteCount = 0; int cur; DIR *localLogDir = logDir; // Stores the execution results of all test cases. FILE *fpAllLog = OpenFile("result.log", "w+", "%s"); if (fpAllLog == NULL) { return 1; } FILE *fpLog = NULL; while ((dir = readdir(localLogDir)) != NULL) { char buf[MAX_LOG_LEN]; uint32_t bufLen = sizeof(buf); if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) { continue; } // len of ".log" is 4 if (strlen(dir->d_name) <= 4 || strlen(dir->d_name) > MAX_FILE_PATH_LEN - 1) { (void)fclose(fpAllLog); return 1; } fpLog = OpenFile(dir->d_name, "r", LOG_FILE_FORMAT); if (fpLog == NULL) { (void)fclose(fpAllLog); return 1; } if (suiteCount >= resultLen) { Print("Reached maximum suite count\n"); (void)fclose(fpLog); (void)fclose(fpAllLog); return 1; } if (strcpy_s(result[suiteCount].name, MAX_TEST_FUNCTION_NAME - 1, dir->d_name) != EOK) { Print("Dir's Name is too long\n"); (void)fclose(fpLog); (void)fclose(fpAllLog); return 1; } // len of ".log" is 4 result[suiteCount].name[strlen(dir->d_name) - 4] = '\0'; result[suiteCount].total = 0; result[suiteCount].pass = 0; result[suiteCount].skip = 0; result[suiteCount].line = 0; while (ReadLine(fpLog, buf, bufLen, 0, 0) == 0) { char testCaseName[MAX_TEST_FUNCTION_NAME]; memset_s(testCaseName, MAX_TEST_FUNCTION_NAME, 0, MAX_TEST_FUNCTION_NAME); if (!IsSuite(buf, strlen(buf))) { continue; } result[suiteCount].total++; cur = 0; while (buf[cur] != '\0' && !(buf[cur] == '.' && buf[cur + 1] == '.')) { cur++; } if (buf[cur] == '\0') { Print("Read log file %s failed\n", dir->d_name); (void)fclose(fpLog); (void)fclose(fpAllLog); return 1; } if (strncpy_s(testCaseName, sizeof(testCaseName) - 1, buf, cur) != EOK) { Print("TestCaseName is too long\n"); (void)fclose(fpLog); (void)fclose(fpAllLog); return 1; } testCaseName[cur] = '\0'; while (buf[cur] == '.') { cur++; } if (strncmp(&buf[cur], "pass", strlen("pass")) == 0) { result[suiteCount].pass++; result[suiteCount].line++; (void)fprintf(outFile, PRINT_TESTCASE_LIST_TAG, testCaseName, result[suiteCount].name); (void)fprintf(fpAllLog, "%s %s\n", testCaseName, "PASS"); } else if (strncmp(&buf[cur], "skip", strlen("skip")) == 0) { result[suiteCount].skip++; result[suiteCount].line++; (void)fprintf(outFile, PRINT_TESTCASE_LIST_TAG, testCaseName, result[suiteCount].name); (void)fprintf(fpAllLog, "%s %s\n", testCaseName, "SKIP"); } else { result[suiteCount].line += 3; // Incorrect test case requires 3 lines (void)fprintf(outFile, PRINT_TESTCASE_LIST_TAG, testCaseName, result[suiteCount].name); (void)fprintf(fpAllLog, "%s %s\n", testCaseName, "FAIL"); (void)fprintf(outFile, PRINT_FAILURE_TAG); (void)fprintf(outFile, PRINT_TESTCASE_TAG); } } suiteCount++; cur = 0; (void)fclose(fpLog); } *totalSuiteCount = suiteCount; (void)fclose(fpAllLog); return 0; } static int GenResultFile(FILE *in, FILE *out, TestSuiteResult result[MAX_SUITE_COUNT], int testSuiteCount) { int totalTests = 0; int totalPass = 0; int totalSkip = 0; if (testSuiteCount >= MAX_SUITE_COUNT) { Print("suites count too great\n"); return 1; } for (int i = 0; i < testSuiteCount; i++) { totalTests += result[i].total; totalPass += result[i].pass; totalSkip += result[i].skip; } (void)fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); (void)fprintf(out, "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" errors=\"0\" ", totalTests, totalTests - totalPass - totalSkip, totalSkip); (void)fprintf(out, "timestamp=\"0000-00-00T00:00:00\" time=\"0\" name=\"AllTests\">\n"); for (int i = 0; i < testSuiteCount; i++) { (void)fprintf(out, " <testsuite name=\"%s\" tests=\"%d\" skips = \"%d\" failures=\"%d\" ", result[i].name, result[i].total, result[i].skip, result[i].total - result[i].pass - result[i].skip); (void)fprintf(out, "disabled=\"0\" errors=\"0\" time=\"0\">\n"); for (int j = 0; j < result[i].line; j++) { char buf[MAX_LOG_LEN]; if (fgets(buf, sizeof(buf), in) != NULL) { (void)fputs(buf, out); } else { return 1; } } (void)fprintf(out, PRINT_TESTSUITE_TAG); } (void)fprintf(out, PRINT_TESTSUITES_TAG); return 0; } int GenResult(void) { int ret; TestSuiteResult result[MAX_SUITE_COUNT]; int testSuiteCount = 0; DIR *logDir = NULL; logDir = opendir(LOG_FILE_DIR); if (logDir == NULL) { Print("fail to open log directory\n"); return 1; } FILE *fpTmp = NULL; fpTmp = fopen("tmp.txt", "w+"); if (fpTmp == NULL) { Print("open tmp.txt failed\n"); (void)closedir(logDir); return 1; } FILE *fpResult = NULL; fpResult = fopen("result.xml", "w"); if (fpResult == NULL) { Print("open result.xml failed\n"); (void)closedir(logDir); (void)fclose(fpTmp); (void)remove("tmp.txt"); return 1; } ret = ReadAllLogFile(logDir, &testSuiteCount, fpTmp, result, sizeof(result)); if (ret != 0) { Print("read log failed\n"); goto EXIT; } rewind(fpTmp); ret = GenResultFile(fpTmp, fpResult, result, testSuiteCount); if (ret != 0) { Print("gen result failed\n"); goto EXIT; } EXIT: (void)closedir(logDir); (void)fclose(fpTmp); (void)fclose(fpResult); (void)remove("tmp.txt"); return ret; }
2301_79861745/bench_create
testcode/framework/gen_test/helper.c
C
unknown
32,462
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "securec.h" #include "helper.h" #define EXECUTE_BASE_FILE "../common/execute_base.c" #define EXECUTE_TEST_FILE "../common/execute_test.c" typedef struct { char suiteName[MAX_FILE_PATH_LEN]; char dir[MAX_FILE_PATH_LEN]; FILE *fpIn; FILE *fpOut; FILE *fpData; FILE *fpBase; FILE *fpDatax; FILE *fpHelper; } GenTestParams; int WriteToFile(GenTestParams *genParam) { int ret = 0; ret = WriteHeader(genParam->fpOut); if (ret != 0) { return ret; } // Scanned test_suite_xxx.c, and write fpOut ret = ScanFunctionFile(genParam->fpIn, genParam->fpOut, genParam->dir); if (ret != 0) { return ret; } ret = GenFunctionPointer(genParam->fpOut); if (ret != 0) { return ret; } ret = GenDatax(genParam->fpData, genParam->fpDatax); if (ret != 0) { Print("gen datax failed\n"); return ret; } ret = GenExpTable(genParam->fpOut); if (ret != 0) { return ret; } ret = LoadFunctionName(genParam->fpOut); if (ret != 0) { return ret; } (void)fprintf(genParam->fpOut, "char suiteName[200] = \"%s\";\n\n", genParam->suiteName); // Write execute_base.c to fpOut ret = LoadHelper(genParam->fpBase, genParam->fpOut); if (ret != 0) { return ret; } // Write execute_test.c to fpOut return LoadHelper(genParam->fpHelper, genParam->fpOut); } int main(int argc, char **argv) { (void)argc; #ifndef PRINT_TO_TERMINAL FILE *fp = fopen("GenTest.output", "a"); if (fp == NULL) { return 1; } SetOutputFile(fp); #endif if (strcmp(argv[1], "GenReport") == 0) { int resultRet = GenResult(); #ifndef PRINT_TO_TERMINAL (void)fclose(fp); #endif return resultRet; } int ret = 0; GenTestParams genParam = {0}; StripDir(argv[1], genParam.suiteName, MAX_FILE_PATH_LEN, genParam.dir, MAX_FILE_PATH_LEN); // Read test_suite_xxx.c genParam.fpIn = OpenFile(argv[1], "r", "%s.c"); if (genParam.fpIn == NULL) { Print("Open %s.c error occurred while file\n", argv[1]); #ifndef PRINT_TO_TERMINAL (void)fclose(fp); #endif return -1; } // Output file testcode/output/test_suite_xxx.c genParam.fpOut = OpenFile(genParam.suiteName, "w", "%s.c"); if (genParam.fpOut == NULL) { Print("Error generating c file\n"); ret = 1; goto END_FP_IN; } genParam.fpData = OpenFile(argv[1], "r", "%s.data"); if (genParam.fpData == NULL) { Print("An error occurred while opening the data file.\n"); ret = 1; goto END_FP_OUT; } genParam.fpDatax = OpenFile(genParam.suiteName, "w", "%s.datax"); if (genParam.fpDatax == NULL) { Print("Error generating datax file\n"); ret = 1; goto END_FP_DATA; } genParam.fpBase = fopen(EXECUTE_BASE_FILE, "r"); if (genParam.fpBase == NULL) { Print("An error occurred when opening the base file.\n"); ret = 1; goto END_FP_DATAX; } genParam.fpHelper = fopen(EXECUTE_TEST_FILE, "r"); if (genParam.fpHelper == NULL) { Print("Error opening secondary file\n"); ret = 1; goto END_FP_BASE; } ret = WriteToFile(&genParam); (void)fclose(genParam.fpHelper); END_FP_BASE: (void)fclose(genParam.fpBase); END_FP_DATAX: (void)fclose(genParam.fpDatax); END_FP_DATA: (void)fclose(genParam.fpData); END_FP_OUT: (void)fclose(genParam.fpOut); END_FP_IN: (void)fclose(genParam.fpIn); #ifndef PRINT_TO_TERMINAL (void)fclose(fp); #endif return ret; }
2301_79861745/bench_create
testcode/framework/gen_test/main.c
C
unknown
4,190
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "securec.h" #include "helper.h" #include "test.h" TestInfo g_testResult; int ConvertInt(const char *intStr, int *outNum) { int *num = outNum; uint32_t i = 0; if (intStr[0] == '-') { i = 1; } for (; i < strlen(intStr); i++) { if (intStr[i] > '9' || intStr[i] < '0') { return 1; } } // Decimal *num = strtol(intStr, NULL, 10); return 0; } int ConvertString(char **str) { if ((*str)[0] != '"') { return 1; } uint32_t back = strlen(*str) - 1; if ((*str)[back] != '"') { back--; if ((*str)[back] != '"') { return 1; } } (*str)[back] = '\0'; (*str)++; return 0; } int IsValidHexChar(char c) { if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { return 0; } return 1; } int ConvertHex(const char *str, Hex *output) { uint32_t len = strlen(str); if (len == 0) { output->x = NULL; output->len = 0; return 0; } // The length of a hex string must be a multiple of 2. if (len % 2 != 0) { return 1; } // Length of the hex string/2 = Length of the byte stream len = len / 2; output->x = (uint8_t *)malloc(len * sizeof(uint8_t)); if (output->x == NULL) { return 1; } output->len = len; // Every 2 bytes in a group for (uint32_t i = 0; i < 2 * len; i += 2) { if ((IsValidHexChar(str[i]) == 1) || (IsValidHexChar(str[i + 1]) == 1)) { goto ERR; } // hex to int formulas: (Hex % 32 + 9) % 25 = int, hex output->x[i / 2] = (str[i] % 32 + 9) % 25 * 16 + (str[i + 1] % 32 + 9) % 25; } return 0; ERR: free(output->x); output->len = 0; return 1; } void RecordFailure(const char *test, const char *filename) { g_testResult.result = TEST_RESULT_FAILED; if (strcpy_s(g_testResult.test, sizeof(g_testResult.test), test) != 0) { Print("failure log failed: message too long\n"); } if (strcpy_s(g_testResult.filename, sizeof(g_testResult.filename), filename) != 0) { Print("failure log failed: filename too long\n"); } } void SkipTest(const char *filename) { g_testResult.result = TEST_RESULT_SKIPPED; if (strcpy_s(g_testResult.filename, sizeof(g_testResult.filename), filename) != 0) { Print("failure log failed: filename too long\n"); } } void PrintResult(bool showDetail, char *vectorName, uint64_t useTime) { if (showDetail) { if (g_testResult.result == TEST_RESULT_SUCCEED) { Print("pass. use ms: %ld\n", useTime); } else if (g_testResult.result == TEST_RESULT_SKIPPED) { Print("skip\n"); } else { Print("failed\n"); Print("at: (%s) in %s\n", g_testResult.test, g_testResult.filename); } } else if (g_testResult.result == TEST_RESULT_FAILED) { Print("\nfailed at vector: %s\n", vectorName); Print("at: (%s) in %s\n", g_testResult.test, g_testResult.filename); } } void PrintLog(FILE *logFile) { int ret; if (g_testResult.result == TEST_RESULT_SUCCEED) { ret = fprintf(logFile, "pass\n"); if (ret < 0) { Print("write to log file failed\n"); } } else if (g_testResult.result == TEST_RESULT_SKIPPED) { ret = fprintf(logFile, "skip\n"); if (ret < 0) { Print("write to log file failed\n"); } } else { ret = fprintf(logFile, "failed\n"); if (ret < 0) { Print("write to log file failed\n"); } ret = fprintf(logFile, "at: (%s) in in %s\n", g_testResult.test, g_testResult.filename); if (ret < 0) { Print("write to log file failed\n"); } } } void PrintDiff(const uint8_t *str1, uint32_t size1, const uint8_t *str2, uint32_t size2) { Print("\nCompare different:\nstr1: "); uint32_t i; for (i = 0; i < size1; i++) { Print("%02X ", str1[i]); } Print("\nstr2: "); for (i = 0; i < size2; i++) { Print("%02X ", str2[i]); } Print("\n"); }
2301_79861745/bench_create
testcode/framework/gen_test/test.c
C
unknown
4,697
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HELPER_H #define HELPER_H #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #include <stdarg.h> #ifdef __cplusplus extern "C" { #endif #define MAX_TEST_FUCNTION_COUNT 100 #define MAX_TEST_FUNCTION_NAME 500 #define MAX_ARGUMENT_COUNT 50 #define MAX_EXPRESSION_COUNT 100 #define MAX_EXPRESSION_LEN 100 #define MAX_DATA_LINE_LEN 120000 #define MAX_FUNCTION_LINE_LEN 512 #define MAX_FILE_PATH_LEN 300 #define MAX_SUITE_COUNT 600 #define MAX_LOG_LEN 500 #define TAG_NOT_TAG 0 #define TAG_BEGIN_HEADER 1 #define TAG_END_HEADER 2 #define TAG_BEGIN_CASE 3 #define TAG_END_CASE 4 #define TAG_INCLUDE_BASE 5 #define SPILT_HEX_BLOCK_SIZE 4 #define ARG_TYPE_INT 1 #define ARG_TYPE_STR 2 #define ARG_TYPE_HEX 3 #define BASE_FILE_FORMAT "%s/%s.base.c" #define LOG_FILE_DIR "./log/" #define LOG_FILE_FORMAT "./log/%s" #define FUZZ_PRINT_EXECUTES "\r%d" typedef struct { char name[MAX_FILE_PATH_LEN]; int total; int pass; int skip; int line; } TestSuiteResult; typedef struct { char name[MAX_TEST_FUNCTION_NAME]; int id; int argType[MAX_ARGUMENT_COUNT]; uint32_t argCount; } FunctionTable; typedef struct { uint8_t *x; uint32_t len; } Hex; extern FunctionTable g_testFunc[MAX_TEST_FUCNTION_COUNT]; extern int g_testFuncCount; extern char g_expTable[MAX_EXPRESSION_COUNT][MAX_EXPRESSION_LEN]; extern int g_expCount; void Print(const char *fmt, ...); void SetOutputFile(FILE *fp); FILE *GetOutputFile(void); void FreeHex(Hex *data); Hex *NewHex(void); int IsInt(const char *str); int ReadLine(FILE *file, char *buf, uint32_t bufLen, bool skipHash, bool skipEmptyLine); int SplitArguments(char *inStr, uint32_t inLen, char **outParam, uint32_t *paramLen); int ReadFunction(const char *in, const uint32_t inLen, char *outFuncName, uint32_t outLen, int argv[MAX_ARGUMENT_COUNT], uint32_t *argCount); int AddFunction(const char *funcName, int argv[MAX_ARGUMENT_COUNT], const uint32_t argCount); int CheckTag(char *in, uint32_t len); int GenFunctionWrapper(FILE *file, FunctionTable *function); int ScanAllFunction(FILE *inFile, FILE *outFile); int ScanHeader(FILE *inFile, FILE *outFile, const char *dir); int GenFunctionPointer(FILE *file); int GenDatax(FILE *inFile, FILE *outFile); int GenExpTable(FILE *outFile); int LoadFunctionName(FILE *outFile); int LoadHelper(FILE *inFile, FILE *outFile); int ScanFunctionFile(FILE *fpIn, FILE *fpOut, const char *dir); int StripDir(const char *in, char *suiteName, const uint32_t suiteNameLen, char *dir, const uint32_t dirNameLen); FILE *OpenFile(const char *name, const char *option, const char *format); int GenResult(void); int SplitHex(Hex *src, Hex *dest, int max); int SplitHexRand(Hex *src, Hex *dest, int max); int WriteHeader(FILE *outFile); #ifdef __cplusplus } #endif #endif // HELPER_H
2301_79861745/bench_create
testcode/framework/include/helper.h
C
unknown
3,408
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef TEST_H #define TEST_H #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #include <signal.h> #include <setjmp.h> #include <sys/wait.h> #include <time.h> #include "helper.h" #include "crypto_test_util.h" #ifdef __cplusplus extern "C" { #endif #define TEST_RESULT_SUCCEED 0 #define TEST_RESULT_FAILED 1 #define TEST_RESULT_SKIPPED 2 typedef struct { int result; char test[512]; char filename[256]; } TestInfo; #define TRUE_OR_EXIT(TEST) \ do { \ if (!(TEST)) { \ goto EXIT; \ } \ } while (0) #define TRUE_OR_ABRT(TEST) \ do { \ if (!(TEST)) { \ raise(SIGABRT); \ } \ } while (0) #define PRINT_ABRT(TEST) \ do { \ if (!(TEST)) { \ goto ABORT; \ } \ } while (0) #define ASSERT_TRUE(TEST) \ do { \ if (!(TEST)) { \ RecordFailure(#TEST, __FILE__); \ goto EXIT; \ } \ } while (0) #define ASSERT_EQ(VALUE1, VALUE2) \ do { \ int64_t value1__ = (int64_t)(VALUE1); \ int64_t value2__ = (int64_t)(VALUE2); \ if (value1__ != value2__) { \ RecordFailure(#VALUE1 #VALUE2, __FILE__); \ Print("\nvalue is %d (0x%x).\nexpect %d (0x%x).\n", value1__, value1__, value2__, value2__); \ goto EXIT; \ } \ } while (0) #define ASSERT_LT(VALUE1, VALUE2) \ do { \ int64_t value1__ = (int64_t)(VALUE1); \ int64_t value2__ = (int64_t)(VALUE2); \ if (!(value1__ < value2__)) { \ RecordFailure(#VALUE1 #VALUE2, __FILE__); \ Print("\nvalue is %d (0x%x).\nexpect %d (0x%x).\n", value1__, value1__, value2__, value2__); \ goto EXIT; \ } \ } while (0) #define ASSERT_EQ_LOG(LOG, VALUE1, VALUE2) \ do { \ int64_t value1__ = (int64_t)(VALUE1); \ int64_t value2__ = (int64_t)(VALUE2); \ if (value1__ != value2__) { \ RecordFailure(LOG, __FILE__); \ Print("\nvalue is %d (0x%x).\nexpect %d (0x%x).\n", value1__, value1__, value2__, value2__); \ goto EXIT; \ } \ } while (0) #define ASSERT_NE(VALUE1, VALUE2) \ do { \ int64_t value1__ = (int64_t)(VALUE1); \ int64_t value2__ = (int64_t)(VALUE2); \ if (value1__ == value2__) { \ RecordFailure(#VALUE1#VALUE2, __FILE__); \ Print("\nvalue is the same: %d (0x%x).\n", value1__, value2__); \ goto EXIT; \ } \ } while (0) #define ASSERT_TRUE_AND_LOG(LOG, TEST) \ do { \ if (!(TEST)) { \ RecordFailure(LOG, __FILE__); \ goto EXIT; \ } \ } while (0) #define ASSERT_COMPARE(LOG, STR1, SIZE1, STR2, SIZE2) \ do { \ ASSERT_TRUE_AND_LOG(LOG, (SIZE1) == (SIZE2)); \ if (memcmp((STR1), (STR2), (SIZE1)) != 0) { \ RecordFailure((LOG), __FILE__); \ PrintDiff((uint8_t *)(STR1), (uint32_t)(SIZE1), (uint8_t *)(STR2), (uint32_t)(SIZE2)); \ goto EXIT; \ } \ } while (0) #define SKIP_TEST() \ do {\ SkipTest(__FILE__); \ return; \ } while (0) extern int *GetJmpAddress(void); #ifndef TEST_NO_SUBPROC #define SUB_PROC 1 #define SUB_PROC_BEGIN(parentAction) if (fork() > 0) parentAction #define SUB_PROC_END() *GetJmpAddress() = SUB_PROC; return #define SUB_PROC_WAIT(times) for (uint16_t i = 0; i < times; i++) wait(NULL) #else #define SUB_PROC 0 #define SUB_PROC_BEGIN(parentAction) #define SUB_PROC_END() #define SUB_PROC_WAIT(times) #endif extern TestInfo g_testResult; int ConvertInt(const char *intStr, int *outNum); int ConvertString(char **str); int ConvertHex(const char *str, Hex *output); void RecordFailure(const char *test, const char *filename); void SkipTest(const char *filename); void PrintResult(bool showDetail, char *vectorName, uint64_t useTime); void PrintLog(FILE *logFile); void PrintDiff(const uint8_t *str1, uint32_t size1, const uint8_t *str2, uint32_t size2); #ifdef __cplusplus } #endif #endif // TEST_H
2301_79861745/bench_create
testcode/framework/include/test.h
C
unknown
6,498
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. add_executable(process ${openHiTLS_SRC}/testcode/framework/process/process.c) set_target_properties(process PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${openHiTLS_SRC}/testcode/output" ) target_include_directories(process PRIVATE ${openHiTLS_SRC}/platform/Secure_C/include ${openHiTLS_SRC}/testcode/framework/tls/resource/include ${openHiTLS_SRC}/testcode/framework/tls/base/include ${openHiTLS_SRC}/testcode/framework/tls/process/include ${openHiTLS_SRC}/testcode/framework/tls/include ${openHiTLS_SRC}/testcode/framework/tls/transfer/include ${openHiTLS_SRC}/testcode/framework/tls/rpc/include ${openHiTLS_SRC}/include/bsl ${openHiTLS_SRC}/include/crypto ${openHiTLS_SRC}/bsl/sal/include ${openHiTLS_SRC}/bsl/hash/include ${openHiTLS_SRC}/bsl/uio/src ${openHiTLS_SRC}/bsl/uio/include ${openHiTLS_SRC}/include/tls ${openHiTLS_SRC}/include/crypto ${openHiTLS_SRC}/tls/include ${openHiTLS_SRC}/config/macro_config ) target_link_directories(process PRIVATE ${openHiTLS_SRC}/build ${openHiTLS_SRC}/testcode/output/lib ${openHiTLS_SRC}/platform/Secure_C/lib ) set(PROCESS_LIBS tls_hlt tls_frame hitls_tls) if(ENABLE_PKI AND ${BUILD_PKI} GREATER -1) list(APPEND PROCESS_LIBS hitls_pki) endif() list(APPEND PROCESS_LIBS hitls_crypto hitls_bsl boundscheck pthread dl rec_wrapper) target_link_libraries(process ${PROCESS_LIBS})
2301_79861745/bench_create
testcode/framework/process/CMakeLists.txt
CMake
unknown
1,991
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdlib.h> #include <signal.h> #include <unistd.h> #include <stdbool.h> #include <semaphore.h> #include "securec.h" #include "channel_res.h" #include "handle_cmd.h" #include "tls_res.h" #include "control_channel.h" #include "logger.h" #include "lock.h" #include "rpc_func.h" #include "hlt_type.h" #include "hlt.h" #include "process.h" #define DOMAIN_PATH_LEN (128) #define SUCCESS 0 #define ERROR (-1) #define ASSERT_RETURN(condition, log) \ do { \ if (!(condition)) { \ LOG_ERROR(log); \ return ERROR; \ } \ } while (0) int IsFeedbackResult(ControlChannelRes *channelInfo) { int i, ret; ControlChannelBuf dataBuf = {0}; OsLock(channelInfo->sendBufferLock); if (channelInfo->sendBufferNum == 0) { OsUnLock(channelInfo->sendBufferLock); return SUCCESS; } i = 0; while (channelInfo->sendBufferNum > 0) { ret = memcpy_s(dataBuf.data, CONTROL_CHANNEL_MAX_MSG_LEN, channelInfo->sendBuffer[i], strlen((char*)(channelInfo->sendBuffer[i]))); if (ret != EOK) { LOG_ERROR("MemCpy Error"); OsUnLock(channelInfo->sendBufferLock); return ERROR; } dataBuf.dataLen = strlen((char*)channelInfo->sendBuffer[i]); LOG_DEBUG("Remote Process Send Result %s", dataBuf.data); ret = ControlChannelWrite(channelInfo->sockFd, channelInfo->peerDomainPath, &dataBuf); if (ret != EOK) { LOG_ERROR("ControlChannelWrite Error, Msg is %s, ret is %d\n", dataBuf.data, ret); OsUnLock(channelInfo->sendBufferLock); return ERROR; } LOG_DEBUG("Remote Process Send Result %s Success", dataBuf.data); channelInfo->sendBufferNum--; i++; } OsUnLock(channelInfo->sendBufferLock); return SUCCESS; } void FreeThreadRes(pthread_t *threadList, int threadNum) { for (int i = 0; i < threadNum; i++) { pthread_cancel(threadList[i]); pthread_join(threadList[i], NULL); } return; } void ThreadExcuteCmd(void *param) { CmdData cmdData = {0}; if (memcpy_s(&cmdData, sizeof(cmdData), (CmdData *)param, sizeof(CmdData)) != EOK) { free(param); return; } free(param); ControlChannelRes *channelInfo = GetControlChannelRes(); (int)ExecuteCmd(&cmdData); PushResultToChannelSendBuffer(channelInfo, cmdData.result); return; } int main(int argc, char **argv) { int ret, sctpFd; ControlChannelRes* channelInfo = NULL; ControlChannelBuf dataBuf; CmdData exitCmdData = {0}; CmdData* cmdData = NULL; Process* process = NULL; pid_t ppid = atoi(argv[4]); (void)ppid; // Do not set the output buffer setbuf(stdout, NULL); LOG_DEBUG("argv value is %d", argc); ret = InitProcess(); ASSERT_RETURN(ret == SUCCESS, "InitProcess Error"); process = GetProcess(); process->remoteFlag = 1; // Must be marked as a remote process process->tlsType = atoi(argv[1]); // The first parameter indicates the Hitls function ret = memcpy_s(process->srcDomainPath, DOMAIN_PATH_LEN, argv[2], strlen(argv[2])); // The second parameter indicates the local IP address ASSERT_RETURN(ret == SUCCESS, "memcpy process->srcDomainPath Error"); ret = memcpy_s(process->peerDomainPath, DOMAIN_PATH_LEN, argv[3], strlen(argv[3])); // The third parameter indicates the address of the control process ASSERT_RETURN(ret == SUCCESS, "memcpy process->srcDomainPath Error"); // Dependent library initialization ret = HLT_LibraryInit(process->tlsType); ASSERT_RETURN(ret == SUCCESS, "HLT_TlsRegCallback Error"); // Initialize the linked list for storing CTX and SSL ret = InitTlsResList(); ASSERT_RETURN(ret == SUCCESS, "InitTlsResList Error"); // Initializes the global variable that stores the control channel information. ret = InitControlChannelRes(process->srcDomainPath, strlen(process->srcDomainPath), process->peerDomainPath, strlen(process->peerDomainPath)); ASSERT_RETURN(ret == SUCCESS, "ChannelInfoInit Error"); // Creating a Control Link UDP DOMAIN SOCKET channelInfo = GetControlChannelRes(); ret = ControlChannelInit(channelInfo); ASSERT_RETURN(ret == SUCCESS, "ControlChannelInit Error"); // Print information LOG_DEBUG("Create Remote Process Successful"); // The message is sent to the peer end, indicating that the process is started successfully PushResultToChannelSendBuffer(channelInfo, "0|HEART"); while (1) { if (kill(ppid, 0) != 0) { LOG_DEBUG("\nthe parent process [%u] does not exist, I want to exist\n", ppid); break; } // Waiting for the command from the peer end ret = ControlChannelRead(channelInfo->sockFd, &dataBuf); if (ret == 0) { // Receives a message, parses the message, and performs related operations LOG_DEBUG("Remote Process Rcv Cmd Is: %s", dataBuf.data); cmdData = (CmdData*)malloc(sizeof(CmdData)); if (cmdData == NULL) { LOG_ERROR("Malloc cmdData Error"); break; } ret = ParseCmdFromBuf(&dataBuf, cmdData); if (ret != SUCCESS) { LOG_ERROR("ParseCmdFromBuf Error ..."); free(cmdData); break; } if (strncmp((char *)cmdData->funcId, "HLT_RpcProcessExit", strlen("HLT_RpcProcessExit")) == 0) { // Indicates that the process needs to exit sctpFd = atoi((char *)cmdData->paras[0]); (void)sprintf_s((char *)exitCmdData.result, sizeof(exitCmdData.result), "%s|%s|%d", cmdData->id, cmdData->funcId, sctpFd); PushResultToChannelSendBuffer(channelInfo, exitCmdData.result); free(cmdData); break; } ThreadExcuteCmd(cmdData); } // Check whether feedback is required ret = IsFeedbackResult(channelInfo); if (ret != 0) { break; } } LOG_DEBUG("Process Return"); (void)IsFeedbackResult(channelInfo); // Clearing Resources FreeControlChannelRes(); FreeTlsResList(); FreeProcess(); if (sctpFd > 0) { close(sctpFd); } return SUCCESS; }
2301_79861745/bench_create
testcode/framework/process/process.c
C
unknown
7,075
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <errno.h> #include <limits.h> #include <memory.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdbool.h> #include <sys/mman.h> #include "stub_replace.h" #ifdef HITLS_BIG_ENDIAN #include "crypt_utils.h" #endif /* The LSB of the function pointer indicates the thumb function. The LSB of the actual address needs to be cleared. */ #define REAL_ADDR(ptr) (void *)(((uintptr_t)(ptr)) & (~(uintptr_t)1)) /* * Used to record the size of the system memory page. */ static long g_pageSize = -1; /* * Obtains the start address of the memory page where the specified function code is located. * fn - Function Address (Function Pointer) */ static inline void *FuncPageGet(uintptr_t fn) { return (void *)(fn & (~(g_pageSize - 1))); } /* * This file does not use the memcpy function of the system. In this way, the mempcy function of * the system can be dynamically replaced by STUB_Replace. */ static int32_t StubCopy(void *dest, void *src, uint32_t size) { if ((src == NULL) || (dest == NULL)) { return ERANGE; } uint8_t *localDst = (uint8_t *)(dest); uint8_t *localSrc = (uint8_t *)(src); for (uint32_t i = 0; i < size; i++) { localDst[i] = localSrc[i]; } return 0; } /* * This file does not use the memset function of the system. In this way, the memset function of * the system can be dynamically replaced by STUB_Replace. */ static void StubSet(void *dest, int val, uint32_t size) { if (dest == NULL) { return; } uint8_t *localDst = (uint8_t *)(dest); for (uint32_t i = 0; i < size; i++) { localDst[i] = val; } } #if defined(__arm__) || defined(__thumb__) static int ReplaceT32(void *srcFn, const void *stubFn) { uint16_t instr1 = 0xF000; uint16_t instr2; uint32_t imm; /* * The difference between the jump instruction and srcFn is 4 bytes. The current address is obtained by * subtracting 4 bytes from the PC. */ uint32_t addrDiff = REAL_ADDR(stubFn) - (REAL_ADDR(srcFn) + 4) - 4; /* * 32-bit test occurrence address: srcFn - stubFn, the scope is out of range, * temporarily comment on the following scope judgment. * if (abs((int32_t)addrDiff) >= 0x100000) { // Max jump range * return -1; * } */ if (((uintptr_t)stubFn) & 0x01) { // Thumb instruction set BL corresponding machine code is [1 1 1 1 0 S imm10][1 1 J1 1 J2 imm11] // Address offset calculation: I1: NOT(J1 EOR S); I2: NOT(J2 EOR S); // imm32: SignExtend(S:I1:I2:imm10:imm11:'0', 32) instr2 = 0xF800; // Corresponding bit of machine code J1 J2 take 1 if (stubFn < srcFn) { instr1 = 0xF400; // The corresponding bit S of the machine code is 1. } imm = addrDiff >> 1; // The address is shifted right by one bit. imm &= (1 << 21) - 1; // Lower 21 bits instr1 |= (imm >> 11) & 0x3FF; // Move rightwards by 11 digits and take imm10. instr2 |= (imm & 0x7FF); } else { // Thumb instruction set BLX corresponding machine code is [1 1 1 1 0 S imm10H][1 1 J1 0 J2 imm10L H] // Address offset calculation: I1 = NOT(J1 EOR S); I2 = NOT(J2 EOR S) // imm32 = SignExtend(S:I1:I2:imm10H:imm10L:'00', 32) instr2 = 0xE800; // J1 and J2 corresponding to the machine code are set to 1. if (stubFn < srcFn) { instr1 = 0xF400; // The corresponding bit S of the machine code is 1. } imm = addrDiff >> 2; // Shift right by 2 bits imm &= (1 << 20) - 1; // Take lower 20 bits instr1 |= (imm >> 10) & 0x3FF; // Take 10 bits instr2 |= (imm & 0x3FF) << 1; // Take lower 10 bits } uint8_t *text = (uint8_t*)REAL_ADDR(srcFn); ((uint16_t *)text)[0] = 0xb580; ((uint16_t *)text)[1] = 0xaf00; ((uint16_t *)text)[2] = instr1; // BL/BLX offset 2 ((uint16_t *)text)[3] = instr2; // Offset 3 ((uint16_t *)text)[4] = 0xaf00; // Offset 4 ((uint16_t *)text)[5] = 0xbd80; // Offset 5 return 0; } static int ReplaceA32(void *srcFn, const void *stubFn) { uint32_t inst; uint32_t addrDiff = REAL_ADDR(stubFn) - (srcFn + 4) - 8; uint32_t imm24; if (abs((int32_t)addrDiff) >= 0x1000000) { // Max jump range return -1; } if (((uintptr_t)stubFn) & 0x01) { // a32 instruction set BLX corresponding machine code is [1 1 1 1 1 0 1 H imm24] // imm32 = SignExtend(imm24:H:'0', 32) uint32_t h = (addrDiff & 0b10) >> 1; // bit[1] of the address difference imm24 = (addrDiff >> 2); // Shift right by 2 bits imm24 &= (1 << 24) - 1; // Take lower 24 bits inst = 0xfa000000 | imm24 | (h << 24); // h is located in bit[24]. } else { // a32 instruction set BL corresponding machine code is [(!= 1111) 1 0 1 1 imm24] // imm32 = SignExtend(imm24:'00', 32) imm24 = (addrDiff >> 2); // Shift right by 2 bits imm24 &= (1 << 24) - 1; // Take lower 24 bits inst = 0xeb000000 | imm24; } ((uint32_t *)srcFn)[0] = 0xe92d4000; ((uint32_t *)srcFn)[1] = inst; // BL/BLX ((uint32_t *)srcFn)[2] = 0xe8bd8000; // Offset 2 return 0; } #endif /* * Replaces the specified function with the specified stub function. * stubInfo - Record information about stub replacement, which is used for STUB_Reset restoration. * srcFn - Functions in the source code * stubFn - You need to replace the stub function that is inserted into the run. * return - 0:Success, non-zero:Error code */ int STUB_Replace(FuncStubInfo *stubInfo, void *srcFn, const void *stubFn) { (void)stubFn; #if defined(__arm__) || defined(__thumb__) stubInfo->fn = REAL_ADDR(srcFn); #else stubInfo->fn = srcFn; #endif StubCopy(stubInfo->codeBuf, (char *)(stubInfo->fn), CODESIZE); bool nextPage = false; uintptr_t srcPoint = (uintptr_t)srcFn; if ((g_pageSize - (srcPoint % g_pageSize)) < CODESIZE) { nextPage = true; } /* To modify instruction content corresponding to the source function, add memory write permission first */ if (mprotect(FuncPageGet(srcPoint), g_pageSize, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to w+r+x faild"); return -1; } if (nextPage) { if (mprotect(FuncPageGet(srcPoint + CODESIZE), g_pageSize, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to w+r+x faild"); return -1; } } #if defined(__x86_64__) /* * Short jump mode: Change to jmp jump instruction, and set jump position (the offset of the current position). * However, the offset cannot exceed 32 bits. There is a restriction on 64-bit systems. * [*(unsigned char *)srcFn = (unsigned char)0xE9;] [*(unsigned int *)((unsigned char *)srcFn + 1) = * (unsigned char *)stubFn - (unsigned char *)srcFn - CODESIZE;] Long jump mode: * Directly use a 64-bit address to jump, the following method is used. */ unsigned char *tmpBuf = (unsigned char *)srcFn; int idx = 0; tmpBuf[idx++] = 0xFF; // 0xFF 0x25 Constructing a long jump instruction tmpBuf[idx++] = 0x25; // 0xFF 0x25 Constructing a long jump instruction tmpBuf[idx++] = 0x0; tmpBuf[idx++] = 0x0; tmpBuf[idx++] = 0x0; tmpBuf[idx++] = 0x0; tmpBuf[idx++] = (((uintptr_t)stubFn) & 0xff); tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 8) & 0xff); // Obtain the address by little-endian shift by 8 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 16) & 0xff); // Obtain the address by little-endian shift by 16 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 24) & 0xff); // Obtain the address by little-endian shift by 24 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 32) & 0xff); // Obtain the address by little-endian shift by 32 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 40) & 0xff); // Obtain the address by little-endian shift by 40 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 48) & 0xff); // Obtain the address by little-endian shift by 48 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 56) & 0xff); // Obtain the address by little-endian shift by 56 bits #elif defined(__aarch64__) || defined(_M_ARM64) /* ldr x9, PC+8 br x9 addr */ uint32_t ldrIns = 0x58000040 | 9; // 9 = 1001 uint32_t brIns = 0xd61f0120 | (9 << 5); // 9 << 5 #ifdef HITLS_BIG_ENDIAN ldrIns = CRYPT_SWAP32(ldrIns); brIns = CRYPT_SWAP32(brIns); #endif ((uint32_t *)srcFn)[0] = ldrIns; ((uint32_t *)srcFn)[1] = brIns; /* ldr x9, + 8 */ *(long long *)((char *)srcFn + 8) = (long long)stubFn; #elif defined(__arm__) || defined(__thumb__) if (((uintptr_t)srcFn) & 0x01) { if (ReplaceT32(srcFn, stubFn) != 0) { return -1; } } else { if (ReplaceA32(srcFn, stubFn) != 0) { return -1; } } #elif defined(__i386__) unsigned long tmpAdd = (unsigned long)stubFn - (unsigned long)(srcFn + 5); unsigned char *tmpBuf = (unsigned char *)srcFn; *(tmpBuf + 0) = 0xe9; *(unsigned long *)(tmpBuf + 1) = tmpAdd; #endif /* Flush cached instructions into */ __builtin___clear_cache((char *)(stubInfo->fn), (char *)(stubInfo->fn) + CODESIZE); /* The modification is complete. Remove the memory write permission. */ if (mprotect(FuncPageGet(srcPoint), g_pageSize, PROT_READ | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to r+x failed"); return -1; } if (nextPage) { if (mprotect(FuncPageGet(srcPoint + CODESIZE), g_pageSize, PROT_READ | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to r+x failed"); return -1; } } return 0; } /* * Restore the source function and remove the instrumentation. * stubInfo - Information logged when instrumentation * return - 0:Success, non-zero:Error code */ int STUB_Reset(FuncStubInfo *stubInfo) { bool nextPage = false; if (stubInfo->fn == NULL) { return -1; } uintptr_t srcPoint = (uintptr_t)stubInfo->fn; if ((g_pageSize - (srcPoint % g_pageSize)) < CODESIZE) { nextPage = true; } /* To modify instruction content corresponding to the source function, add memory write permission first */ if (mprotect(FuncPageGet((uintptr_t)stubInfo->fn), g_pageSize, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) { perror("STUB_Reset: error mprotect to w+r+x faild"); return -1; } if (nextPage) { if (mprotect(FuncPageGet(srcPoint + CODESIZE), g_pageSize, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to w+r+x faild"); return -1; } } /* Restore the recorded rewritten original function mov/push/mov a few instructions */ if (StubCopy(stubInfo->fn, stubInfo->codeBuf, CODESIZE) < 0) { return -1; } /* Flush cached instructions into */ __builtin___clear_cache((char *)stubInfo->fn, (char *)stubInfo->fn + CODESIZE); /* If recovered, disable the memory modification permission. */ if (mprotect(FuncPageGet((uintptr_t)stubInfo->fn), g_pageSize, PROT_READ | PROT_EXEC) < 0) { perror("STUB_Reset: error mprotect to r+x failed"); return -1; } if (nextPage) { if (mprotect(FuncPageGet(srcPoint + CODESIZE), g_pageSize, PROT_READ | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to r+x failed"); return -1; } } StubSet(stubInfo, 0, sizeof(FuncStubInfo)); return 0; } /* * Initialize the dynamic stub change function and obtain the memory page size. Invoke the function once. * return - 0:Success, non-zero:Error code */ int STUB_Init(void) { if (g_pageSize != -1) { return 0; } g_pageSize = sysconf(_SC_PAGE_SIZE); if (g_pageSize < 0) { perror("STUB_Init: get system _SC_PAGE_SIZE configure failed"); return -1; } return 0; }
2301_79861745/bench_create
testcode/framework/stub/stub_replace.c
C
unknown
12,791
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef STUB_REPALCE_H #define STUB_REPALCE_H #include <stdint.h> #if defined(__x86_64__) /* * The first 14 bytes of the function entry are used to construct the jump instruction. * Short jump instruction is 5 bytes, and Long jump instruction is 14 bytes. */ #define CODESIZE 14U #elif defined(__aarch64__) || defined(_M_ARM64) /* ARM64 needs 16 bytes to construct the jump instruction. */ #define CODESIZE 16U #elif defined(__arm__) /* ARM32 needs 12 bytes to construct the jump instruction. */ #define CODESIZE 12U #endif #ifdef __cplusplus extern "C" { #endif typedef struct { void *fn; unsigned char codeBuf[CODESIZE]; } FuncStubInfo; /* * Initialize the dynamic stub change function. Invoke the function once. * return - 0:Success, non-zero:Error code */ int STUB_Init(void); /* * Replaces the specified function with the specified stub function. * stubInfo - Record information about stub replacement, which is used for STUB_Reset restoration. * srcFn - Functions in the source code * stubFn - Need to replace the stub function that is inserted into the run. * return - 0:Success, non-zero:Error code */ int STUB_Replace(FuncStubInfo *stubInfo, void *srcFn, const void *stubFn); /* * Restore the source function and remove the instrumentation. * stubInfo - Information logged when instrumentation * return - 0:Success, non-zero:Error code */ int STUB_Reset(FuncStubInfo *stubInfo); #ifdef __cplusplus } #endif #endif // STUB_REPALCE_H
2301_79861745/bench_create
testcode/framework/stub/stub_replace.h
C
unknown
2,018
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. SET(DT_LIBNAME "tls_frame") SET(HLT_LIBNAME "tls_hlt") SET(WRAPPER_LIBNAME "rec_wrapper") add_library(TLS_TEST_INTF INTERFACE) if(TLS_DEBUG) add_compile_definitions(TLS_TEST_INTF INTERFACE TLS_DEBUG) endif() target_include_directories(TLS_TEST_INTF INTERFACE ${openHiTLS_SRC}/platform/Secure_C/include ${openHiTLS_SRC}/include ${openHiTLS_SRC}/include/tls ${openHiTLS_SRC}/include/bsl ${openHiTLS_SRC}/include/crypto ${openHiTLS_SRC}/include/pki ${openHiTLS_SRC}/config/macro_config ${openHiTLS_SRC}/bsl/list/include ${openHiTLS_SRC}/bsl/obj/include ${openHiTLS_SRC}/bsl/include ${openHiTLS_SRC}/bsl/sal/include ${openHiTLS_SRC}/bsl/log/include ${openHiTLS_SRC}/bsl/time/include ${openHiTLS_SRC}/bsl/async/include ${openHiTLS_SRC}/bsl/hash/include ${openHiTLS_SRC}/bsl/uio/include ${openHiTLS_SRC}/bsl/uio/src ${openHiTLS_SRC}/pki/x509_cert/include ${openHiTLS_SRC}/tls/cert/hitls_x509_adapt ${openHiTLS_SRC}/tls/include ${openHiTLS_SRC}/tls/cert/cert_self ${openHiTLS_SRC}/tls/cert/include ${openHiTLS_SRC}/tls/config/include ${openHiTLS_SRC}/tls/cm/include ${openHiTLS_SRC}/tls/record/include ${openHiTLS_SRC}/tls/record/src ${openHiTLS_SRC}/tls/handshake/cookie/include ${openHiTLS_SRC}/tls/handshake/common/include ${openHiTLS_SRC}/tls/crypt/include/ ${openHiTLS_SRC}/tls/handshake/parse/include ${openHiTLS_SRC}/tls/handshake/pack/src ${openHiTLS_SRC}/tls/handshake/pack/include ${openHiTLS_SRC}/tls/ccs/include ${openHiTLS_SRC}/tls/alert/include ${openHiTLS_SRC}/tls/crypt/crypt_self ${openHiTLS_SRC}/testcode/framework/stub ${openHiTLS_SRC}/testcode/framework/tls/include ${openHiTLS_SRC}/testcode/framework/tls/io/include ${openHiTLS_SRC}/testcode/framework/tls/cert/include ${openHiTLS_SRC}/testcode/framework/tls/crypt/include ${openHiTLS_SRC}/testcode/framework/tls/msg/include ${openHiTLS_SRC}/testcode/framework/tls/base/include ${openHiTLS_SRC}/testcode/framework/tls/resource/include ${openHiTLS_SRC}/testcode/framework/tls/rpc/include ${openHiTLS_SRC}/testcode/framework/tls/process/include ${openHiTLS_SRC}/testcode/framework/tls/transfer/include ${openHiTLS_SRC}/testcode/framework/tls/frame/src ${openHiTLS_SRC}/testcode/framework/tls/io/src ${openHiTLS_SRC}/testcode/framework/tls/func_wrapper/include ${openHiTLS_SRC}/testcode/framework/tls/callback/include ${openHiTLS_SRC}/tls/feature/custom_extensions/include ) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/crypt/src CRYPT_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/io/src IO_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/frame/src FRAME_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/msg/src MSG_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/base/src BASE_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/resource/src RESOURCE_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/process/src PROCESS_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/rpc/src RPC_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/transfer/src TRANSFER_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/callback/src CALLBACK_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/func_wrapper/src WRAPPER_SRC) SET(WRAPPER_SRC ${WRAPPER_SRC} ${openHiTLS_SRC}/testcode/framework/stub/stub_replace.c) target_compile_options(TLS_TEST_INTF INTERFACE -g) add_library(${HLT_LIBNAME} STATIC ${BASE_SRC} ${RESOURCE_SRC} ${CALLBACK_SRC} ${PROCESS_SRC} ${RPC_SRC} ${TRANSFER_SRC}) target_link_libraries(${HLT_LIBNAME} PRIVATE TLS_TEST_INTF) add_library(${DT_LIBNAME} STATIC ${BASE_SRC} ${CALLBACK_SRC} ${CRYPT_SRC} ${IO_SRC} ${FRAME_SRC} ${MSG_SRC}) target_link_libraries(${DT_LIBNAME} PRIVATE TLS_TEST_INTF) add_library(${WRAPPER_LIBNAME} STATIC ${WRAPPER_SRC}) target_link_libraries(${WRAPPER_LIBNAME} PRIVATE TLS_TEST_INTF) set_target_properties(${HLT_LIBNAME} ${DT_LIBNAME} ${WRAPPER_LIBNAME} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY "${openHiTLS_SRC}/testcode/output/lib" )
2301_79861745/bench_create
testcode/framework/tls/CMakeLists.txt
CMake
unknown
4,778
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef __LOCK_H__ #define __LOCK_H__ #include <pthread.h> typedef pthread_mutex_t Lock; /** * @brief Create a lock resource */ Lock *OsLockNew(void); /** * @brief Lock */ int OsLock(Lock *lock); /** * @brief Unlock */ int OsUnLock(Lock *lock); /** * @brief Release the lock resource */ void OsLockDestroy(Lock *lock); #endif // __LOCK_H__
2301_79861745/bench_create
testcode/framework/tls/base/include/lock.h
C
unknown
895
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef __LOGGER_H__ #define __LOGGER_H__ #include <stdio.h> #include <stdint.h> #include "securec.h" #ifdef __cplusplus extern "C" { #endif #define LOG_MAX_SIZE 1024 typedef enum { ENUM_LOG_LEVEL_TRACE, /* Basic level */ ENUM_LOG_LEVEL_DEBUG, /* Debugging level */ ENUM_LOG_LEVEL_WARNING, /* Warning level */ ENUM_LOG_LEVEL_ERROR, /* Error level */ ENUM_LOG_LEVEL_FATAL /* Fatal level */ } LogLevel; /** * @ingroup log * @brief Record error information based on the log level * * @par * Record error information based on the log level * * @attention * * @param[in] level Log level * @param[in] file File where the error information is stored * @param[in] line Number of the line where the error information is stored * @param[in] fmt Format character string for printing * * @retval 0 Success * @retval others failure */ int LogWrite(LogLevel level, const char *file, int line, const char *fmt, ...); #define LOG_DEBUG(...) LogWrite(ENUM_LOG_LEVEL_DEBUG, __FILE__, __LINE__, __VA_ARGS__) #define LOG_ERROR(...) LogWrite(ENUM_LOG_LEVEL_ERROR, __FILE__, __LINE__, __VA_ARGS__) #ifdef __cplusplus } #endif // __cplusplus #endif // __LOGGER_H__
2301_79861745/bench_create
testcode/framework/tls/base/include/logger.h
C
unknown
1,738
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <pthread.h> #include <stdint.h> #include "securec.h" #include "logger.h" #include "lock.h" Lock *OsLockNew(void) { pthread_mutexattr_t attr; Lock *lock; if ((lock = (Lock *)malloc(sizeof(pthread_mutex_t))) == NULL) { LOG_ERROR("OAL_Malloc error"); return NULL; } pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); if (pthread_mutex_init(lock, &attr) != 0) { LOG_ERROR("pthread_mutex_init error"); pthread_mutexattr_destroy(&attr); free(lock); return NULL; } pthread_mutexattr_destroy(&attr); return lock; } int OsLock(Lock *lock) { if (pthread_mutex_lock(lock) != 0) { LOG_ERROR("pthread_mutex_lock error"); return -1; } return 0; } int OsUnLock(Lock *lock) { if (pthread_mutex_unlock(lock) != 0) { LOG_ERROR("pthread_mutex_unlock error"); return -1; } return 0; } void OsLockDestroy(Lock *lock) { if (lock == NULL) { return; } pthread_mutex_destroy(lock); free(lock); }
2301_79861745/bench_create
testcode/framework/tls/base/src/lock.c
C
unknown
1,635
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <unistd.h> #include "logger.h" LogLevel GetLogLevel(void) { #ifdef TLS_DEBUG return ENUM_LOG_LEVEL_TRACE; #else return ENUM_LOG_LEVEL_FATAL; #endif } static const char *ConvertLevel2Str(LogLevel level) { switch (level) { case ENUM_LOG_LEVEL_TRACE: return "TRACE"; case ENUM_LOG_LEVEL_DEBUG: return "DEBUG"; case ENUM_LOG_LEVEL_WARNING: return "WARNING"; case ENUM_LOG_LEVEL_ERROR: return "ERROR"; case ENUM_LOG_LEVEL_FATAL: return "FATAL"; default: return "UNKNOWN"; } } int LogWrite(LogLevel level, const char *file, int line, const char *fmt, ...) { int len, ilen; LogLevel curLevel; va_list vargs; int tmpLevel = level; char logBuf[LOG_MAX_SIZE] = {0}; if ((tmpLevel < ENUM_LOG_LEVEL_TRACE) || (tmpLevel > ENUM_LOG_LEVEL_FATAL)) { return 0; } // Print logs whose levels are higher than or equal to the current level. curLevel = GetLogLevel(); if (level < curLevel) { return 0; } // Process the log header if (file == NULL || line == 0) { len = snprintf_s(logBuf, LOG_MAX_SIZE, (size_t)(LOG_MAX_SIZE - 1), "[%d_TEST_%s]", getpid(), ConvertLevel2Str((LogLevel)tmpLevel)); } else { len = snprintf_s(logBuf, LOG_MAX_SIZE, (size_t)(LOG_MAX_SIZE - 1), "[%d_TEST_%s][%s:%d]", getpid(), ConvertLevel2Str((LogLevel)tmpLevel), file, line); } if (len < 0 || len > LOG_MAX_SIZE - 1) { return 0; } va_start(vargs, fmt); ilen = vsnprintf_s(logBuf + len, (size_t)(LOG_MAX_SIZE - len), (size_t)(LOG_MAX_SIZE - len - 1), fmt, vargs); if (ilen < 0 || ilen > LOG_MAX_SIZE - len - 1) { // In the case of overflow truncation, the maximum value is used len = LOG_MAX_SIZE; logBuf[len - 1] = '\0'; goto EXIT; } len += ilen; logBuf[len] = '\n'; logBuf[len + 1] = '\0'; EXIT: va_end(vargs); #ifdef TLS_DEBUG printf("%s", logBuf); #endif return 0; }
2301_79861745/bench_create
testcode/framework/tls/base/src/logger.c
C
unknown
2,629
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CERT_CALLBACK_H #define CERT_CALLBACK_H #include "hlt_type.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Certificate callback */ int32_t RegCertCallback(CertCallbackType type); /** * @brief Memory callback */ int32_t RegMemCallback(MemCallbackType type); /** * @brief Loading Certificates and Private Keys by hitls x509 */ int32_t HiTLS_X509_LoadCertAndKey(HITLS_Config *tlsCfg, const char *caFile, const char *chainFile, const char *eeFile, const char *signFile, const char *privateKeyFile, const char *signPrivateKeyFile); void BinLogFixLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para1, void *para2, void *para3, void *para4); void BinLogVarLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para); void RegDefaultMemCallback(void); #ifdef __cplusplus } #endif #endif // CERT_CALLBACK_H
2301_79861745/bench_create
testcode/framework/tls/callback/include/cert_callback.h
C
unknown
1,443
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <unistd.h> #include <stdbool.h> #include <stdio.h> #include "hitls_build.h" #include "crypt_eal_pkey.h" #include "hlt_type.h" #include "hitls_cert_type.h" #include "hitls_cert.h" #include "hitls_type.h" #include "hitls_cert_reg.h" #include "hitls_config.h" #include "hitls_cert.h" #include "hitls_cert_init.h" #include "bsl_sal.h" #include "bsl_log.h" #include "bsl_err.h" #include "logger.h" #include "tls_config.h" #include "tls.h" #include "bsl_list.h" #include "hitls_x509_adapt.h" #include "hitls_cert_init.h" #include "hitls_pki_x509.h" #include "cert_method.h" #define SUCCESS 0 #define ERROR (-1) #define SINGLE_CERT_LEN (512) #define CERT_FILE_LEN (4 * 1024) int32_t RegCertCallback(CertCallbackType type) { switch (type) { case CERT_CALLBACK_DEFAULT: #ifndef HITLS_TLS_FEATURE_PROVIDER HITLS_CertMethodInit(); #endif break; default: return ERROR; } return SUCCESS; } void BinLogFixLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para1, void *para2, void *para3, void *para4) { (void)logLevel; (void)logType; printf("logId:%u\t", logId); printf(format, para1, para2, para3, para4); printf("\n"); return; } void BinLogVarLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para) { (void)logLevel; (void)logType; printf("logId:%u\t", logId); printf(format, para); printf("\n"); return; } void RegDefaultMemCallback(void) { BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_MALLOC, malloc); BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_FREE, free); BSL_ERR_Init(); BSL_LOG_SetBinLogLevel(BSL_LOG_LEVEL_DEBUG); #ifdef TLS_DEBUG BSL_LOG_BinLogFuncs logFunc = { BinLogFixLenFunc, BinLogVarLenFunc }; BSL_LOG_RegBinLogFunc(&logFunc); #endif LOG_DEBUG("HiTLS RegDefaultMemCallback"); return; } int32_t RegMemCallback(MemCallbackType type) { switch (type) { case MEM_CALLBACK_DEFAULT : RegDefaultMemCallback(); break; default: return ERROR; } return SUCCESS; } HITLS_CERT_X509 *HiTLS_X509_LoadCertFile(HITLS_Config *tlsCfg, const char *file) { #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_Lib_Ctx *libCtx = LIBCTX_FROM_CONFIG(tlsCfg); const char *attrName = ATTRIBUTE_FROM_CONFIG(tlsCfg); return HITLS_CERT_ProviderCertParse(libCtx, attrName, (const uint8_t *)file, strlen(file) + 1, TLS_PARSE_TYPE_FILE, "ASN1"); #else return HITLS_X509_Adapt_CertParse(tlsCfg, (const uint8_t *)file, strlen(file) + 1, TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); #endif } void *HiTLS_X509_LoadCertListToStore(HITLS_Config *tlsCfg, const char *fileList) { int32_t ret; char certList[MAX_CERT_LEN] = {0}; char certPath[SINGLE_CERT_LEN] = {0}; ret = memcpy_s(certList, MAX_CERT_LEN, fileList, strlen(fileList)); if (ret != EOK) { LOG_ERROR("memcpy_s Error"); return NULL; } void *store = SAL_CERT_StoreNew(tlsCfg->certMgrCtx); if(store == NULL){ LOG_ERROR("SAL_CERT_StoreNew Error"); return NULL; } char *rest = NULL; char *token = strtok_s(certList, ":", &rest); do { (void)memset_s(certPath, SINGLE_CERT_LEN, 0, SINGLE_CERT_LEN); ret = sprintf_s(certPath, SINGLE_CERT_LEN, "%s%s", DEFAULT_CERT_PATH, token); if (ret <= 0) { LOG_ERROR("sprintf_s Error"); HITLS_X509_StoreCtxFree(store); return NULL; } LOG_DEBUG("Load Cert Path is %s", certPath); HITLS_CERT_X509 *cert = HiTLS_X509_LoadCertFile(tlsCfg, certPath); if (cert == NULL) { HITLS_X509_StoreCtxFree(store); return NULL; } ret = HITLS_X509_Adapt_StoreCtrl(tlsCfg, store, CERT_STORE_CTRL_ADD_CERT_LIST, cert, NULL); if (ret != SUCCESS) { LOG_ERROR("X509_STORE_add_cert Error: path = %s.", certPath); HITLS_X509_StoreCtxFree(store); return NULL; } token = strtok_s(NULL, ":", &rest); } while (token != NULL); return store; } int32_t HITLS_X509_LoadEECertList(HITLS_Config *tlsCfg, const char *eeFileList, bool isEnc) { int32_t ret; HITLS_CERT_X509 *cert = NULL; char certList[MAX_CERT_LEN] = {0}; char certPath[SINGLE_CERT_LEN] = {0}; ret = memcpy_s(certList, MAX_CERT_LEN, eeFileList, strlen(eeFileList)); if (ret != EOK) { LOG_ERROR("memcpy_s Error"); return ERROR; } char *rest = NULL; char *token = strtok_s(certList, ":", &rest); do { (void)memset_s(certPath, SINGLE_CERT_LEN, 0, SINGLE_CERT_LEN); ret = sprintf_s(certPath, SINGLE_CERT_LEN, "%s%s", DEFAULT_CERT_PATH, token); if (ret <= 0) { LOG_ERROR("sprintf_s Error"); return ERROR; } LOG_DEBUG("Load Cert Path is %s", certPath); cert = HiTLS_X509_LoadCertFile(tlsCfg, certPath); if (cert == NULL) { LOG_ERROR("LoadCert Error: path = %s", certPath); return ERROR; } if (isEnc == true) { ret = HITLS_CFG_SetTlcpCertificate(tlsCfg, cert, 0, isEnc); } else { ret = HITLS_CFG_SetCertificate(tlsCfg, cert, 0); } if (ret != SUCCESS) { LOG_ERROR("HITLS_CFG_SetCertificate Error: path = %s.", certPath); HITLS_X509_Adapt_CertFree(cert); return ERROR; } token = strtok_s(NULL, ":", &rest); } while (token != NULL); return SUCCESS; } int32_t HITLS_X509_LoadPrivateKeyList(HITLS_Config *tlsCfg, const char *keyFileList, bool isEnc) { int32_t ret; HITLS_CERT_Key *key = NULL; char fileList[MAX_CERT_LEN] = {0}; char filePath[SINGLE_CERT_LEN] = {0}; ret = memcpy_s(fileList, MAX_CERT_LEN, keyFileList, strlen(keyFileList)); if (ret != EOK) { LOG_ERROR("memcpy_s Error"); return ERROR; } char *rest = NULL; char *token = strtok_s(fileList, ":", &rest); do { (void)memset_s(filePath, SINGLE_CERT_LEN, 0, SINGLE_CERT_LEN); ret = sprintf_s(filePath, SINGLE_CERT_LEN, "%s%s", DEFAULT_CERT_PATH, token); if (ret <= 0) { LOG_ERROR("sprintf_s Error"); return ERROR; } LOG_DEBUG("Load Cert Path is %s", filePath); #ifdef HITLS_TLS_FEATURE_PROVIDER key = HITLS_X509_Adapt_ProviderKeyParse(tlsCfg, (const uint8_t *)filePath, strlen(filePath), TLS_PARSE_TYPE_FILE, "ASN1", NULL); #else key = HITLS_X509_Adapt_KeyParse(tlsCfg, (const uint8_t *)filePath, strlen(filePath), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); #endif if (key == NULL) { LOG_ERROR("LoadCert Error: path = %s.", filePath); return ERROR; } if (isEnc == true) { ret = HITLS_CFG_SetTlcpPrivateKey(tlsCfg, key, 0, isEnc); } else { ret = HITLS_CFG_SetPrivateKey(tlsCfg, key, 0); } if (ret != SUCCESS) { LOG_ERROR("HITLS_CFG_SetPrivateKey Error: path = %s.", filePath); CRYPT_EAL_PkeyFreeCtx(key); return ERROR; } token = strtok_s(NULL, ":", &rest); } while (token != NULL); return SUCCESS; } void FRAME_HITLS_X509_FreeCert(HITLS_CERT_Store *caStore, HITLS_CERT_Store *chainStore) { if (caStore != NULL) { HITLS_X509_StoreCtxFree(caStore); } if (chainStore != NULL) { HITLS_X509_StoreCtxFree(chainStore); } return; } int32_t HiTLS_X509_LoadCertAndKey(HITLS_Config *tlsCfg, const char *caFile, const char *chainFile, const char *eeFile, const char *signFile, const char *privateKeyFile, const char *signPrivateKeyFile) { int32_t ret; if ((caFile != NULL) && (strncmp(caFile, "NULL", strlen(caFile)) != 0)) { HITLS_CERT_Store *caStore = HiTLS_X509_LoadCertListToStore(tlsCfg, caFile); if (caStore == NULL) { return ERROR; } ret = HITLS_CFG_SetCertStore(tlsCfg, caStore, 0); if (ret != SUCCESS) { HITLS_X509_StoreCtxFree(caStore); return ret; } } if ((chainFile != NULL) && (strncmp(chainFile, "NULL", strlen(chainFile)) != 0)) { HITLS_CERT_Store *chainStore = HiTLS_X509_LoadCertListToStore(tlsCfg, chainFile); if (chainStore == NULL) { return ERROR; } ret = HITLS_CFG_SetChainStore(tlsCfg, chainStore, 0); if (ret != SUCCESS) { HITLS_X509_StoreCtxFree(chainStore); return ret; } } bool hasTlcpSignCert = ((signFile != NULL) && (strncmp(signFile, "NULL", strlen(signFile)) != 0)); if (hasTlcpSignCert) { ret = HITLS_X509_LoadEECertList(tlsCfg, signFile, false); if (ret != SUCCESS) { return ret; } } if ((eeFile != NULL) && (strncmp(eeFile, "NULL", strlen(eeFile)) != 0)) { ret = HITLS_X509_LoadEECertList(tlsCfg, eeFile, hasTlcpSignCert); if (ret != SUCCESS) { return ret; } } if ((signPrivateKeyFile != NULL) && (strncmp(signPrivateKeyFile, "NULL", strlen(signPrivateKeyFile)) != 0)) { ret = HITLS_X509_LoadPrivateKeyList(tlsCfg, signPrivateKeyFile, false); if (ret != SUCCESS) { return ret; } if ((privateKeyFile != NULL) && (strncmp(privateKeyFile, "NULL", strlen(eeFile)) != 0)) { ret = HITLS_X509_LoadPrivateKeyList(tlsCfg, privateKeyFile, true); if (ret != SUCCESS) { return ret; } } } else { if ((privateKeyFile != NULL) && (strncmp(privateKeyFile, "NULL", strlen(eeFile)) != 0)) { ret = HITLS_X509_LoadPrivateKeyList(tlsCfg, privateKeyFile, false); if (ret != SUCCESS) { return ret; } } } return SUCCESS; }
2301_79861745/bench_create
testcode/framework/tls/callback/src/cert_callback.c
C
unknown
10,467