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.
*/
#ifndef HITLS_APP_CRL_H
#define HITLS_APP_CRL_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_CrlMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2401_83913325/openHiTLS_1 | apps/include/app_crl.h | C | unknown | 734 |
/*
* 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_APP_DGST_H
#define HITLS_APP_DGST_H
#include <stdint.h>
#include <stddef.h>
#include "crypt_algid.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
const int mdId;
const char *mdAlgName;
} HITLS_AlgList;
int32_t HITLS_DgstMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2401_83913325/openHiTLS_1 | apps/include/app_dgst.h | C | unknown | 866 |
/*
* 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_APP_ENC_H
#define HITLS_APP_ENC_H
#include <stdint.h>
#include <limits.h>
#ifdef __cplusplus
extern "C" {
#endif
#define REC_ITERATION_TIMES 10000
#define REC_MAX_FILE_LENGEN 512
#define REC_MAX_FILENAME_LENGTH PATH_MAX
#define REC_MAX_MAC_KEY_LEN 64
#define REC_MAX_KEY_LENGTH 64
#define REC_MAX_IV_LENGTH 16
#define REC_HEX_BASE 16
#define REC_SALT_LEN 8
#define REC_HEX_BUF_LENGTH 8
#define REC_MIN_PRE_LENGTH 6
#define REC_DOUBLE 2
#define MAX_BUFSIZE 4096
#define XTS_MIN_DATALEN 16
#define BUF_SAFE_BLOCK 16
#define BUF_READABLE_BLOCK 32
#define IS_SUPPORT_GET_EOF 1
typedef struct {
const int cipherId;
const char *cipherAlgName;
} HITLS_CipherAlgList;
typedef struct {
const int macId;
const char *macAlgName;
} HITLS_MacAlgList;
int32_t HITLS_EncMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_enc.h | C | unknown | 1,610 |
/*
* 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_APP_ERRNO_H
#define HITLS_APP_ERRNO_H
#ifdef __cplusplus
extern "C" {
#endif
#define HITLS_APP_SUCCESS 0
// The return value of HITLS APP ranges from 0, 1, 3 to 125.
// 3 to 125 are external error codes.
enum HITLS_APP_ERROR {
HITLS_APP_HELP = 0x1, /* *< the subcommand has the help option */
HITLS_APP_SECUREC_FAIL, /* *< error returned by the safe function */
HITLS_APP_MEM_ALLOC_FAIL, /* *< failed to apply for memory resources */
HITLS_APP_INVALID_ARG, /* *< invalid parameter */
HITLS_APP_INTERNAL_EXCEPTION,
HITLS_APP_ENCODE_FAIL, /* *< encodeing failure */
HITLS_APP_CRYPTO_FAIL,
HITLS_APP_PASSWD_FAIL,
HITLS_APP_UIO_FAIL,
HITLS_APP_STDIN_FAIL, /* *< incorrect stdin input */
HITLS_APP_INFO_CMP_FAIL, /* *< failed to match the received information with the parameter */
HITLS_APP_INVALID_DN_TYPE,
HITLS_APP_INVALID_DN_VALUE,
HITLS_APP_INVALID_GENERAL_NAME_TYPE,
HITLS_APP_INVALID_GENERAL_NAME,
HITLS_APP_INVALID_IP,
HITLS_APP_ERR_CONF_GET_SECTION,
HITLS_APP_NO_EXT,
HITLS_APP_INIT_FAILED,
HITLS_APP_COPY_ARGS_FAILED,
HITLS_APP_OPT_UNKOWN, /* *< option error */
HITLS_APP_OPT_NAME_INVALID, /* *< the subcommand name is invalid */
HITLS_APP_OPT_VALUETYPE_INVALID, /* *< the parameter type of the subcommand is invalid */
HITLS_APP_OPT_TYPE_INVALID, /* *< the subcommand type is invalid */
HITLS_APP_OPT_VALUE_INVALID, /* *< the subcommand parameter value is invalid */
HITLS_APP_DECODE_FAIL, /* *< decoding failure */
HITLS_APP_CERT_VERIFY_FAIL, /* *< certificate verification failed */
HITLS_APP_X509_FAIL, /* *< x509-related error. */
HITLS_APP_SAL_FAIL, /* *< sal-related error. */
HITLS_APP_BSL_FAIL, /* *< bsl-related error. */
HITLS_APP_CONF_FAIL, /* *< conf-related error. */
HITLS_APP_LOAD_CERT_FAIL, /* *< Failed to load the cert. */
HITLS_APP_LOAD_CSR_FAIL, /* *< Failed to load the csr. */
HITLS_APP_LOAD_KEY_FAIL, /* *< Failed to load the public and private keys. */
HITLS_APP_ENCODE_KEY_FAIL, /* *< Failed to encode the public and private keys. */
/* TLS Client/Server specific errors */
HITLS_APP_ERR_CREATE_CTX, /* *< Failed to create TLS context */
HITLS_APP_ERR_CONNECT, /* *< Failed to connect to server */
HITLS_APP_ERR_LISTEN, /* *< Failed to create listening socket */
HITLS_APP_ERR_HANDSHAKE, /* *< TLS handshake failed */
HITLS_APP_ERR_SEND_DATA, /* *< Failed to send data */
HITLS_APP_ERR_SET_CIPHER, /* *< Failed to set cipher suites */
HITLS_APP_ERR_SET_SIGNATURE, /* *< Failed to set signature algorithms */
HITLS_APP_ERR_SET_GROUPS, /* *< Failed to set curves/groups */
HITLS_APP_ERR_LOAD_CA, /* *< Failed to load CA certificate */
HITLS_APP_ERR_SET_VERIFY, /* *< Failed to set verification options */
HITLS_APP_ERR_SET_TLCP_CERT, /* *< Failed to set TLCP certificate */
HITLS_APP_ERR_SET_COOKIE, /* *< Failed to set cookie exchange */
HITLS_APP_ERR_RESOLVE_HOST, /* *< Failed to resolve hostname */
HITLS_APP_ROOT_CHECK_FAIL, /* *< root user check failed. */
HITLS_APP_INTEGRITY_VERIFY_FAIL, /* *< integrity verify failed. */
HITLS_APP_MAX = 126, /* *< maximum of the error code */
};
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_errno.h | C | unknown | 4,298 |
/*
* 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_APP_FUNCTION_H
#define HITLS_APP_FUNCTION_H
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
FUNC_TYPE_NONE, // default
FUNC_TYPE_GENERAL, // general command
} HITLS_CmdFuncType;
typedef struct {
const char *name; // second-class command name
HITLS_CmdFuncType type; // type of command
int (*main)(int argc, char *argv[]); // second-class entry function
} HITLS_CmdFunc;
int AppGetProgFunc(const char *proName, HITLS_CmdFunc *func);
void AppPrintFuncList(void);
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_function.h | C | unknown | 1,129 |
/*
* 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_APP_GENPKEY_H
#define HITLS_APP_GENPKEY_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_GenPkeyMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_Genpkey_H | 2401_83913325/openHiTLS_1 | apps/include/app_genpkey.h | C | unknown | 769 |
/*
* 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_APP_GENRSA_H
#define HITLS_APP_GENRSA_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define REC_MAX_PEM_FILELEN 65537
#define REC_MAX_PKEY_LENGTH 16384
#define REC_MIN_PKEY_LENGTH 512
#define REC_ALG_NUM_EACHLINE 4
typedef struct {
const int id;
const char *algName;
} HITLS_APPAlgList;
int32_t HITLS_GenRSAMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2401_83913325/openHiTLS_1 | apps/include/app_genrsa.h | C | unknown | 967 |
/*
* 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_APP_HELP_H
#define HITLS_APP_HELP_H
#ifdef __cplusplus
extern "C" {
#endif
int HITLS_HelpMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_help.h | C | unknown | 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_APP_KDF_H
#define HITLS_APP_KDF_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_KdfMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_kdf.h | C | unknown | 734 |
/*
* 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_APP_KEYMGMT_H
#define HITLS_APP_KEYMGMT_H
#include <stdint.h>
#include "app_sm.h"
#include "crypt_eal_pkey.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef HITLS_APP_SM_MODE
#define HITLS_APP_MAX_KEY_LEN 64
#define HITLS_APP_UUID_LEN 32
typedef struct {
int32_t version;
uint8_t uuid[HITLS_APP_UUID_LEN];
int32_t algId;
int64_t createTime;
int64_t expireTime;
} HITLS_APP_KeyAttr;
typedef struct {
uint8_t key[HITLS_APP_MAX_KEY_LEN];
uint32_t keyLen;
CRYPT_EAL_PkeyCtx *pkeyCtx;
HITLS_APP_KeyAttr attr;
} HITLS_APP_KeyInfo;
/**
* @ingroup app_keymgmt
* @brief The function type to send the key.
*
* @param ctx [IN] The context of the function.
* @param buf [IN] The buffer to send the key.
* @param len [IN] The length of the buffer.
*
* @retval #HITLS_APP_SUCCESS.
* For other error codes, see app_errno.h.
*/
typedef int32_t (*HITLS_APP_SendFunc)(void *ctx, const void *buf, uint32_t len);
/**
* @ingroup app_keymgmt
* @brief The function type to receive the key.
*
* @param ctx [IN] The context of the function.
* @param buf [OUT] The buffer to receive.
* @param len [IN] The length of the buffer.
*
* @retval #HITLS_APP_SUCCESS.
* For other error codes, see app_errno.h.
*/
typedef int32_t (*HITLS_APP_RecvFunc)(void *ctx, void *buf, uint32_t len);
/**
* @ingroup app_keymgmt
* @brief The main function of the key management module.
*
* @param argc [IN] The number of arguments.
* @param argv [IN] The arguments.
*
* @retval #HITLS_APP_SUCCESS.
* For other error codes, see app_errno.h.
*/
int32_t HITLS_KeyMgmtMain(int argc, char *argv[]);
/**
* @ingroup app_keymgmt
* @brief Find the key from the key file.
*
* @param provider [IN] The provider of the application.
* @param smParam [IN] The parameter of the SM mode.
* @param algId [IN] The algorithm ID of the key.
* @param keyInfo [OUT] The key information.
*
* @retval #HITLS_APP_SUCCESS.
* For other error codes, see app_errno.h.
*/
int32_t HITLS_APP_FindKey(AppProvider *provider, HITLS_APP_SM_Param *smParam, int32_t algId,
HITLS_APP_KeyInfo *keyInfo);
/**
* @ingroup app_keymgmt
* @brief Send the key to the remote device.
*
* @param provider [IN] The provider of the application.
* @param smParam [IN] The parameter of the SM mode.
* @param sendFunc [IN] The function to send the key.
* @param ctx [IN] The context of the function.
*
* @retval #HITLS_APP_SUCCESS.
* For other error codes, see app_errno.h.
*/
int32_t HITLS_APP_SendKey(AppProvider *provider, HITLS_APP_SM_Param *smParam, HITLS_APP_SendFunc sendFunc, void *ctx);
/**
* @ingroup app_keymgmt
* @brief Receive the key from the remote device.
*
* @param provider [IN] The provider of the application.
* @param smParam [IN] The parameter of the SM mode, don't need uuid.
* @param iter [IN] The iteration times for pkcs12 encryption.
* @param saltLen [IN] The salt length for pkcs12 encryption.
* @param recvFunc [IN] The function to receive the key.
* @param ctx [IN] The context of the function.
*
* @retval #HITLS_APP_SUCCESS.
* For other error codes, see app_errno.h.
*/
int32_t HITLS_APP_ReceiveKey(AppProvider *provider, HITLS_APP_SM_Param *smParam, int32_t iter, int32_t saltLen,
HITLS_APP_RecvFunc recvFunc, void *ctx);
#endif
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_keymgmt.h | C | unknown | 3,983 |
/*
* 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_APP_LIST_H
#define HITLS_APP_LIST_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
HITLS_APP_LIST_OPT_ALL_ALG = 2,
HITLS_APP_LIST_OPT_DGST_ALG,
HITLS_APP_LIST_OPT_CIPHER_ALG,
HITLS_APP_LIST_OPT_ASYM_ALG,
HITLS_APP_LIST_OPT_MAC_ALG,
HITLS_APP_LIST_OPT_RAND_ALG,
HITLS_APP_LIST_OPT_KDF_ALG,
HITLS_APP_LIST_OPT_CURVES
} HITLSListOptType;
int HITLS_ListMain(int argc, char *argv[]);
int32_t HITLS_APP_GetCidByName(const char *name, int32_t type);
const char *HITLS_APP_GetNameByCid(int32_t cid, int32_t type);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_LIST_H
| 2401_83913325/openHiTLS_1 | apps/include/app_list.h | C | unknown | 1,183 |
/*
* 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_APP_MAC_H
#define HITLS_APP_MAC_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_MacMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_mac.h | C | unknown | 734 |
/*
* 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_APP_OPT_H
#define HITLS_APP_OPT_H
#include <stdint.h>
#include "bsl_uio.h"
#include "bsl_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define HILTS_APP_FORMAT_UNDEF 0
#define HITLS_APP_FORMAT_PEM BSL_FORMAT_PEM // 1
#define HITLS_APP_FORMAT_ASN1 BSL_FORMAT_ASN1 // 2
#define HITLS_APP_FORMAT_TEXT 3
#define HITLS_APP_FORMAT_BASE64 4
#define HITLS_APP_FORMAT_HEX 5
#define HITLS_APP_FORMAT_BINARY 6
#define HITLS_APP_SHAKE128_SIZE 16
#define HITLS_APP_SHAKE256_SIZE 32
#define HITLS_APP_PROV_ENUM \
HITLS_APP_OPT_PROVIDER, \
HITLS_APP_OPT_PROVIDER_PATH, \
HITLS_APP_OPT_PROVIDER_ATTR \
#define HITLS_APP_PROV_OPTIONS \
{"provider", HITLS_APP_OPT_PROVIDER, HITLS_APP_OPT_VALUETYPE_STRING, \
"Specify the cryptographic service provider"}, \
{"provider-path", HITLS_APP_OPT_PROVIDER_PATH, HITLS_APP_OPT_VALUETYPE_STRING, \
"Set the path to the cryptographic service provider"}, \
{"provider-attr", HITLS_APP_OPT_PROVIDER_ATTR, HITLS_APP_OPT_VALUETYPE_STRING, \
"Set additional attributes for the cryptographic service provider"} \
#define HITLS_APP_PROV_CASES(optType, provider) \
switch (optType) { \
case HITLS_APP_OPT_PROVIDER: \
(provider)->providerName = HITLS_APP_OptGetValueStr(); \
break; \
case HITLS_APP_OPT_PROVIDER_PATH: \
(provider)->providerPath = HITLS_APP_OptGetValueStr(); \
break; \
case HITLS_APP_OPT_PROVIDER_ATTR: \
(provider)->providerAttr = HITLS_APP_OptGetValueStr(); \
break; \
default: \
break; \
}
typedef enum {
HITLS_APP_OPT_VALUETYPE_NONE = 0,
HITLS_APP_OPT_VALUETYPE_NO_VALUE = 1,
HITLS_APP_OPT_VALUETYPE_IN_FILE,
HITLS_APP_OPT_VALUETYPE_OUT_FILE,
HITLS_APP_OPT_VALUETYPE_STRING,
HITLS_APP_OPT_VALUETYPE_PARAMTERS,
HITLS_APP_OPT_VALUETYPE_DIR,
HITLS_APP_OPT_VALUETYPE_INT,
HITLS_APP_OPT_VALUETYPE_UINT,
HITLS_APP_OPT_VALUETYPE_POSITIVE_INT,
HITLS_APP_OPT_VALUETYPE_LONG,
HITLS_APP_OPT_VALUETYPE_ULONG,
HITLS_APP_OPT_VALUETYPE_FMT_PEMDER,
HITLS_APP_OPT_VALUETYPE_FMT_ANY,
HITLS_APP_OPT_VALUETYPE_MAX,
} HITLS_ValueType;
typedef enum {
HITLS_APP_OPT_VALUECLASS_NONE = 0,
HITLS_APP_OPT_VALUECLASS_NO_VALUE = 1,
HITLS_APP_OPT_VALUECLASS_STR,
HITLS_APP_OPT_VALUECLASS_DIR,
HITLS_APP_OPT_VALUECLASS_INT,
HITLS_APP_OPT_VALUECLASS_LONG,
HITLS_APP_OPT_VALUECLASS_FMT,
HITLS_APP_OPT_VALUECLASS_MAX,
} HITLS_ValueClass;
typedef enum {
HITLS_APP_OPT_ERR = -1,
HITLS_APP_OPT_EOF = 0,
HITLS_APP_OPT_PARAM = HITLS_APP_OPT_EOF,
HITLS_APP_OPT_HELP = 1,
} HITLS_OptChoice;
typedef struct {
const char *name; // option name
const int optType; // option type
int valueType; // options with parameters(type)
const char *help; // description of this option
} HITLS_CmdOption;
/**
* @ingroup HITLS_APP
* @brief Initialization of command-line argument parsing (internal function)
*
* @param argc [IN] number of options
* @param argv [IN] pointer to an array of options
* @param opts [IN] command option table
*
* @retval command name of command-line argument
*/
int32_t HITLS_APP_OptBegin(int32_t argc, char **argv, const HITLS_CmdOption *opts);
/**
* @ingroup HITLS_APP
* @brief Parse next command-line argument (internal function)
*
* @param void
*
* @retval int32 option type
*/
int32_t HITLS_APP_OptNext(void);
/**
* @ingroup HITLS_APP
* @brief Finish parsing options
*
* @param void
*
* @retval void
*/
void HITLS_APP_OptEnd(void);
/**
* @ingroup HITLS_APP
* @brief Print command line parsing
*
* @param opts command option table
*
* @retval void
*/
void HITLS_APP_OptHelpPrint(const HITLS_CmdOption *opts);
/**
* @ingroup HITLS_APP
* @brief Get the number of remaining options
*
* @param void
*
* @retval int32 number of remaining options
*/
int32_t HITLS_APP_GetRestOptNum(void);
/**
* @ingroup HITLS_APP
* @brief Get the remaining options
*
* @param void
*
* @retval char** the address of remaining options
*/
char **HITLS_APP_GetRestOpt(void);
/**
* @ingroup HITLS_APP
* @brief Get command option
* @param void
* @retval char* command option
*/
char *HITLS_APP_OptGetValueStr(void);
/**
* @ingroup HITLS_APP
* @brief option string to int
* @param valueS [IN] string value
* @param valueL [OUT] int value
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetInt(const char *valueS, int32_t *valueI);
/**
* @ingroup HITLS_APP
* @brief option string to uint32_t
* @param valueS [IN] string value
* @param valueL [OUT] uint32_t value
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetUint32(const char *valueS, uint32_t *valueU);
/**
* @ingroup HITLS_APP
* @brief Get the name of the current second-class command
*
* @param void
*
* @retval char* command name
*/
char *HITLS_APP_GetProgName(void);
/**
* @ingroup HITLS_APP
* @brief option string to long
*
* @param valueS [IN] string value
* @param valueL [OUT] long value
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetLong(const char *valueS, long *valueL);
/**
* @ingroup HITLS_APP
* @brief Get the format type from the option value
*
* @param valueS [IN] string of value
* @param type [IN] value type
* @param formatType [OUT] format type
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetFormatType(const char *valueS, HITLS_ValueType type, BSL_ParseFormat *formatType);
/**
* @ingroup HITLS_APP
* @brief Get UIO type from option value
*
* @param filename [IN] name of input file
* @param mode [IN] method of opening a file
* @param flag [OUT] whether the closing of the standard input/output window is bound to the UIO
*
* @retval BSL_UIO * when succeeded, NULL when failed
*/
BSL_UIO* HITLS_APP_UioOpen(const char* filename, char mode, int32_t flag);
/**
* @ingroup HITLS_APP
* @brief Converts a character string to a character string in Base64 format and output the buf to UIO
*
* @param buf [IN] content to be encoded
* @param inBufLen [IN] the length of content to be encoded
* @param outBuf [IN] Encoded content
* @param outBufLen [IN] the length of encoded content
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptToBase64(uint8_t *buf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen);
/**
* @ingroup HITLS_APP
* @brief Converts a character string to a hexadecimal character string and output the buf to UIO
*
* @param buf [IN] content to be encoded
* @param inBufLen [IN] the length of content to be encoded
* @param outBuf [IN] Encoded content
* @param outBufLen [IN] the length of encoded content
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptToHex(uint8_t *buf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen);
/**
* @ingroup HITLS_APP
* @brief Output the buf to UIO
*
* @param uio [IN] output UIO
* @param buf [IN] output buf
* @param outLen [IN] the length of output buf
* @param format [IN] output format
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptWriteUio(BSL_UIO* uio, uint8_t* buf, uint32_t outLen, int32_t format);
/**
* @ingroup HITLS_APP
* @brief Read the content in the UIO to the readBuf
*
* @param uio [IN] input UIO
* @param readBuf [IN] buf which uio read
* @param readBufLen [IN] the length of readBuf
* @param maxBufLen [IN] the maximum length to be read.
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptReadUio(BSL_UIO *uio, uint8_t **readBuf, uint64_t *readBufLen, uint64_t maxBufLen);
/**
* @ingroup HITLS_APP
* @brief Get unknown option name
*
* @retval char*
*/
const char *HITLS_APP_OptGetUnKownOptName();
#ifdef __cplusplus
}
#endif
#endif
| 2401_83913325/openHiTLS_1 | apps/include/app_opt.h | C | unknown | 8,673 |
/*
* 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_APP_PASSWD_H
#define HITLS_APP_PASSWD_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define REC_MAX_ITER_TIMES 999999999
#define REC_DEF_ITER_TIMES 5000
#define REC_MAX_ARRAY_LEN 1025
#define REC_MIN_ITER_TIMES 1000
#define REC_SHA512_BLOCKSIZE 64
#define REC_HASH_BUF_LEN 64
#define REC_MIN_PREFIX_LEN 37
#define REC_MAX_SALTLEN 16
#define REC_SHA512_SALTLEN 16
#define REC_TEN 10
#define REC_PRE_ITER_LEN 8
#define REC_SEVEN 7
#define REC_SHA512_ALGTAG 6
#define REC_SHA256_ALGTAG 5
#define REC_PRE_TAG_LEN 3
#define REC_THREE 3
#define REC_TWO 2
#define REC_MD5_ALGTAG 1
int32_t HITLS_PasswdMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2401_83913325/openHiTLS_1 | apps/include/app_passwd.h | C | unknown | 1,429 |
/*
* 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_APP_PKCS12_H
#define HITLS_APP_PKCS12_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_PKCS12Main(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_pkcs12.h | C | unknown | 745 |
/*
* 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_APP_PKEY_H
#define HITLS_APP_PKEY_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_PkeyMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_PKEY_H | 2401_83913325/openHiTLS_1 | apps/include/app_pkey.h | C | unknown | 757 |
/*
* 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_APP_PKEYUTL_H
#define HITLS_APP_PKEYUTL_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_PkeyUtlMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_pkeyutl.h | C | unknown | 773 |
/*
* 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_APP_LOG_H
#define HITLS_APP_LOG_H
#include <stdio.h>
#include <stdint.h>
#include "bsl_uio.h"
#ifdef __cplusplus
extern "C" {
#endif
#define AppPrintInfo AppPrintError
/**
* @ingroup HITLS_APPS
* @brief Print output to UIO
*
* @param uio [IN] UIO to be printed
* @param format [IN] Log format character string
* @param... [IN] format Parameter
* @retval int32_t
*/
int32_t AppPrint(BSL_UIO *uio, const char *format, ...);
/**
* @ingroup HiTLS_APPS
* @brief Print the output to stderr.
*
* @param format [IN] Log format character string
* @param... [IN] format Parameter
* @retval void
*/
void AppPrintError(const char *format, ...);
/**
* @ingroup HiTLS_APPS
* @brief Initialize the PrintErrUIO.
*
* @param fp [IN] File pointer, for example, stderr.
* @retval int32_t
*/
int32_t AppPrintErrorUioInit(FILE *fp);
/**
* @ingroup HiTLS_APPS
* @brief Deinitialize the PrintErrUIO.
*
* @retval void
*/
void AppPrintErrorUioUnInit(void);
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_print.h | C | unknown | 1,563 |
/*
* 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_APP_PROVIDER_H
#define HITLS_APP_PROVIDER_H
#include <stdint.h>
#include "crypt_types.h"
#include "crypt_eal_provider.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
char *providerName;
char *providerPath;
char *providerAttr;
} AppProvider;
CRYPT_EAL_LibCtx *APP_Create_LibCtx(void);
CRYPT_EAL_LibCtx *APP_GetCurrent_LibCtx(void);
int32_t HITLS_APP_LoadProvider(const char *searchPath, const char *providerName);
void HITLS_APP_FreeLibCtx(void);
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_provider.h | C | unknown | 1,067 |
/*
* 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_APP_RAND_H
#define HITLS_APP_RAND_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_RandMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_rand.h | C | unknown | 737 |
/*
* 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_APP_REQ_H
#define HITLS_APP_REQ_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_ReqMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_REQ_H | 2401_83913325/openHiTLS_1 | apps/include/app_req.h | C | unknown | 753 |
/*
* 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_APP_RSA_H
#define HITLS_APP_RSA_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_RsaMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_rsa.h | C | unknown | 734 |
/*
* 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 APP_SERVER_H
#define APP_SERVER_H
#include <stdint.h>
#include "app_provider.h"
#include "app_sm.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Server parameters structure */
typedef struct {
/* Listen parameters */
char *bindAddr;
int port;
int backlog;
/* Protocol parameters */
char *protocol;
char *cipherSuites;
/* Certificate parameters */
char *caFile;
char *caChain;
bool verifyClient;
int verifyDepth;
/* TLCP parameters */
char *tlcpEncCert;
char *tlcpEncKey;
char *tlcpSignCert;
char *tlcpSignKey;
/* Service parameters */
bool acceptOnce;
int maxConnections;
/* Output parameters */
bool quiet;
bool state;
/* Format parameters */
BSL_ParseFormat certFormat;
BSL_ParseFormat keyFormat;
AppProvider *provider;
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param *smParam;
#endif
} HITLS_ServerParams;
/**
* @brief Main entry point for s_server tool
* @param argc Number of command line arguments
* @param argv Array of command line arguments
* @return Application exit code
*/
int HITLS_ServerMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif /* APP_SERVER_H */ | 2401_83913325/openHiTLS_1 | apps/include/app_server.h | C | unknown | 1,860 |
/*
* 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_APP_SM_H
#define HITLS_APP_SM_H
#include <stdint.h>
#include <limits.h>
#include "app_provider.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef HITLS_APP_SM_MODE
#define HITLS_SM_OPTIONS_ENUM \
HITLS_SM_OPT_SM, \
HITLS_SM_OPT_UUID, \
HITLS_SM_OPT_WORKPATH
#define HITLS_SM_OPTIONS \
{"sm", HITLS_SM_OPT_SM, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Enable SM mode"}, \
{"uuid", HITLS_SM_OPT_UUID, HITLS_APP_OPT_VALUETYPE_STRING, "UUID of the key (repeatable)"}, \
{"workpath", HITLS_SM_OPT_WORKPATH, HITLS_APP_OPT_VALUETYPE_DIR, "Specify the working directory"}
#define HITLS_APP_SM_CASES(optType, smParam) \
switch (optType) { \
case HITLS_SM_OPT_SM: \
(smParam)->smTag = 1; \
break; \
case HITLS_SM_OPT_UUID: \
(smParam)->uuid = HITLS_APP_OptGetValueStr(); \
break; \
case HITLS_SM_OPT_WORKPATH: \
(smParam)->workPath = HITLS_APP_OptGetValueStr(); \
break; \
default: \
break; \
}
typedef enum {
HITLS_APP_SM_STATUS_CLOSE = 0,
HITLS_APP_SM_STATUS_OPEN = 1,
HITLS_APP_SM_STATUS_INIT = 2,
HITLS_APP_SM_STATUS_SELFTEST = 3,
HITLS_APP_SM_STATUS_MANAGER = 4,
HITLS_APP_SM_STATUS_KEY_PARAMETER_INPUT = 5,
HITLS_APP_SM_STATUS_APPORVED = 6,
HITLS_APP_SM_STATUS_ERROR = 7,
} HITLS_APP_SM_Status;
typedef struct {
char *uuid;
int32_t smTag;
char *workPath;
uint8_t *password;
uint32_t passwordLen;
int32_t status;
} HITLS_APP_SM_Param;
/**
* @ingroup app_sm
* @brief Initialize the SM mode.
* @note Need to init random number generator before use.
*
* @param provider [IN] The provider of the application.
* @param workPath [IN] The working directory.
* @param password [OUT] The password.
*
* @retval #HITLS_APP_SUCCESS.
* For other error codes, see app_errno.h.
*/
int32_t HITLS_APP_SM_Init(AppProvider *provider, const char *workPath, char **password, int32_t *status);
int32_t HITLS_APP_SM_IntegrityCheck(AppProvider *provider);
int32_t HITLS_APP_SM_PeriodicRandomCheck(AppProvider *provider);
char *HITLS_APP_GetAppPath(void);
int32_t HITLS_APP_SM_RootUserCheck(void);
void HITLS_APP_SM_PrintLog(int32_t ret);
#endif
#ifdef __cplusplus
}
#endif
#endif | 2401_83913325/openHiTLS_1 | apps/include/app_sm.h | C | unknown | 3,398 |
/*
* Shandong University — School of Cyber Science and Technology
* Cryptography Engineering Course (2025)
*
* Course Project Contribution
* Contributor: ShaoYan Zhang, XiaoKai Gong, YiMing Zhou, HeYang Ding
* Instructor: Weijia Wang
*
* Description:
* This code is part of the official output of the 2025 Cryptography Engineering
* course at the School of Cyber Science and Technology, Shandong University.
* It reflects the project work and research conducted by the contributor(s)
* under the supervision of the instructor.
*/
#ifndef HITLS_APP_SPEED_H
#define HITLS_APP_SPEED_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define CIPHER_ALG_PER_LINE 4
#define CRYPT_SUCCESS 0
#define CRYPT_FAILURE 1
#define KB_TO_MB_FACTOR 1024.0
#define USEC_TO_SEC_FACTOR 1000000.0
#define MIN_ELAPSED_THRESHOLD 0.0001
#define IV_LENGTH 16
#define ENCRYPT_EXTRA_BUFFER_LEN 32
#define TEST_BLOCK_SIZES_LEN 6
#define SECONDS 3
#define MAX_KEY_LEN 64
#define MAX_MAC_LEN 128
#define MAX_THREADS 32
#define AES192_KEY_LENGTH 24
#define AES256_KEY_LENGTH 32
#define AES128_KEY_LENGTH 16
#define HMAC_SHA512_KEY_LENGTH 64
#define DEFAULT_HMAC_KEY_LENGTH 32
// Automatic test block size array
static const int TEST_BLOCK_SIZES[TEST_BLOCK_SIZES_LEN] = {16, 64, 256, 1024, 8192, 16384};
// Cipher algorithm list structure
typedef struct {
const int cipherId;
const char *cipherAlgName;
} HITLS_CipherList;
// MAC algorithm list structure
typedef struct {
const int macId;
const char *macAlgName;
} HITLS_MacList;
// Performance test main function
int32_t HITLS_SpeedMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2401_83913325/openHiTLS_1 | apps/include/app_speed.h | C | unknown | 1,779 |
/*
* 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 APP_TLS_COMMON_H
#define APP_TLS_COMMON_H
#include <stdint.h>
#include <stdbool.h>
#include "bsl_types.h"
#include "bsl_uio.h"
#include "hitls_config.h"
#include "hitls_pki_cert.h"
#include "hitls.h"
#include "hitls_cert.h"
#include "crypt_eal_pkey.h"
#include "app_provider.h"
#include "app_sm.h"
#ifdef __cplusplus
extern "C" {
#endif
#define APP_HEARTBEAT_LEN 17
#define DEFAULT_DTLCP_PORT 54000
/* Protocol types */
typedef enum {
APP_PROTOCOL_TLS, // International standard TLS protocol (default)
APP_PROTOCOL_TLCP,
APP_PROTOCOL_DTLCP,
} APP_ProtocolType;
/* Network address structure */
typedef struct {
char *host;
int port;
} APP_NetworkAddr;
/* Certificate configuration structure */
typedef struct {
char *keyPass;
char *caFile;
char *caChain;
BSL_ParseFormat certFormat;
BSL_ParseFormat keyFormat;
/* TLCP specific certificates */
char *tlcpEncCert;
char *tlcpEncKey;
char *tlcpSignCert;
char *tlcpSignKey;
AppProvider *provider;
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param *smParam;
#endif
} APP_CertConfig;
/**
* @brief Parse protocol type from string
* @param protocolStr Protocol string (tls12, tls13, dtls12, tlcp)
* @return Protocol type or -1 on error
*/
APP_ProtocolType ParseProtocolType(const char *protocolStr);
/**
* @brief Create TLS configuration based on protocol type
* @param protocol Protocol type
* @return HITLS configuration or NULL on error
*/
HITLS_Config *CreateProtocolConfig(APP_ProtocolType protocol, AppProvider *provider);
/**
* @brief Configure cipher suites
* @param config TLS configuration
* @param cipherStr Cipher suite string
* @param is_tls13 Whether it's TLS1.3 cipher suites
* @return Success or error code
*/
int ConfigureCipherSuites(HITLS_Config *config, const char *cipherStr, APP_ProtocolType protocol);
/**
* @brief Load certificate from file
* @param certFile Certificate file path
* @param format Certificate format
* @param provider Provider configuration
* @return Certificate object or NULL on error
*/
HITLS_X509_Cert *LoadCertFromFile(const char *certFile, BSL_ParseFormat format, AppProvider *provider);
/**
* @brief Configure certificate verification
* @param config TLS configuration
* @param certConfig Certificate configuration
* @param isClient Whether it's client configuration
* @param verifyPeer Whether to verify peer certificate
* @param verifyDepth Certificate chain verification depth
* @return Success or error code
*/
int ConfCertVerification(HITLS_Config *config, APP_CertConfig *certConfig,
bool verifyPeer, int verifyDepth);
/**
* @brief Configure TLCP certificates (dual certificates)
* @param config TLS configuration
* @param certConfig Certificate configuration
* @param isClient Whether it's client configuration
* @return Success or error code
*/
int ConfigureTLCPCertificates(HITLS_Config *config, APP_CertConfig *certConfig);
/**
* @brief Create TCP socket and connect to server
* @param addr Network address
* @param timeout Connection timeout in seconds
* @return Socket file descriptor or -1 on error
*/
int CreateTCPSocket(APP_NetworkAddr *addr, int timeout);
/**
* @brief Create UDP socket and connect to server
* @param addr Network address
* @param timeout Connection timeout in seconds
* @return Socket file descriptor or -1 on error
*/
int CreateUDPSocket(APP_NetworkAddr *addr, int timeout);
/**
* @brief Create TCP listening socket
* @param addr Network address
* @param backlog Listen backlog
* @return Socket file descriptor or -1 on error
*/
int CreateTCPListenSocket(APP_NetworkAddr *addr, int backlog);
/**
* @brief Create UDP listening socket
* @param addr Network address
* @return Socket file descriptor or -1 on error
*/
int CreateUDPListenSocket(APP_NetworkAddr *addr, int timeout);
/**
* @brief Accept TCP connection
* @param listenFd Listening socket
* @return Client socket file descriptor or -1 on error
*/
int AcceptTCPConnection(int listenFd);
/**
* @brief Print TLS connection information
* @param ctx TLS context
* @param showState Whether to show handshake state
*/
void PrintConnectionInfo(HITLS_Ctx *ctx, bool showState);
/**
* @brief Print certificate chain
* @param ctx TLS context
*/
void PrintCertificateChain(HITLS_Ctx *ctx);
/**
* @brief Print handshake state
* @param ctx TLS context
*/
void PrintHandshakeState(HITLS_Ctx *ctx);
/**
* @brief Parse host:port string
* @param connectStr Connection string in format "host:port"
* @param addr Output network address
* @return Success or error code
*/
int ParseConnectString(const char *connectStr, APP_NetworkAddr *addr);
int32_t GetHeartBeat(uint8_t *buffer, uint32_t *len);
int32_t ParseHeartBeat(uint8_t *buffer, uint32_t len);
#ifdef __cplusplus
}
#endif
#endif /* APP_TLS_COMMON_H */ | 2401_83913325/openHiTLS_1 | apps/include/app_tls_common.h | C | unknown | 5,590 |
/*
* 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 APP_UTILS_H
#define APP_UTILS_H
#include <stddef.h>
#include <stdint.h>
#include "bsl_ui.h"
#include "bsl_types.h"
#include "crypt_eal_pkey.h"
#include "app_conf.h"
#include "app_provider.h"
#include "app_sm.h"
#include "hitls_csr_local.h"
#ifdef __cplusplus
extern "C" {
#endif
#define APP_MAX_PASS_LENGTH 1024
#define APP_MIN_PASS_LENGTH 1
#define APP_FILE_MAX_SIZE_KB 256
#define APP_FILE_MAX_SIZE (APP_FILE_MAX_SIZE_KB * 1024) // 256KB
#define APP_MAX_PATH_LEN PATH_MAX
#define DEFAULT_SALTLEN 16
#define DEFAULT_ITCNT 2048
void *ExpandingMem(void *oldPtr, size_t newSize, size_t oldSize);
/**
* @ingroup apps
*
* @brief Apps Function for Checking the Validity of Key Characters
*
* @attention If the key length needs to be limited, the caller needs to limit the key length outside the function.
*
* @param password [IN] Key entered by the user
* @param passwordLen [IN] Length of the key entered by the user
*
* @retval The key is valid:HITLS_APP_SUCCESS
* @retval The key is invalid:HITLS_APP_PASSWD_FAIL
*/
int32_t HITLS_APP_CheckPasswd(const uint8_t *password, const uint32_t passwordLen);
/**
* @ingroup apps
*
* @brief Apps Function for Verifying Passwd Received by the BSL_UI_ReadPwdUtil()
*
* @attention callBackData is the default callback structure APP_DefaultPassCBData.
*
* @param ui [IN] Input/Output Stream
* @param buff [IN] Buffer for receiving passwd
* @param buffLen [IN] Length of the buffer for receiving passwd
* @param callBackData [IN] Key verification information.
*
* @retval The key is valid:HITLS_APP_SUCCESS
* @retval The key is invalid:HITLS_APP_PASSWD_FAIL
*/
int32_t HITLS_APP_DefaultPassCB(BSL_UI *ui, char *buff, uint32_t buffLen, void *callBackData);
int32_t HITLS_APP_Passwd(char *buf, int32_t bufMaxLen, int32_t flag, void *userdata);
void HITLS_APP_PrintPassErrlog(void);
/**
* @ingroup apps
*
* @brief Obtain the password from the command line argument.
*
* @attention pass: The memory needs to be released automatically.
*
* @param passArg [IN] Command line password parameters
* @param pass [OUT] Parsed password
*
* @retval The key is valid:HITLS_APP_SUCCESS
* @retval The key is invalid:HITLS_APP_PASSWD_FAIL
*/
int32_t HITLS_APP_ParsePasswd(const char *passArg, char **pass);
int32_t HITLS_APP_GetPasswd(BSL_UI_ReadPwdParam *param, char **passin, uint8_t **pass, uint32_t *passLen);
/**
* @ingroup apps
*
* @brief Load the public key.
*
* @attention If inFilePath is empty, it is read from the standard input.
*
* @param inFilePath [IN] file name
* @param informat [IN] Public Key Format
*
* @retval CRYPT_EAL_PkeyCtx
*/
CRYPT_EAL_PkeyCtx *HITLS_APP_LoadPubKey(const char *inFilePath, BSL_ParseFormat informat);
/**
* @ingroup apps
*
* @brief Load the private key using provider attributes.
*
* @attention If inFilePath or passin is empty, it is read from the standard input.
* The provider attribute (attrName) is used to specify the provider for key loading.
*
* @param libCtx [IN] Library context
* @param attrName [IN] Provider attribute name
* @param inFilePath [IN] File name
* @param informat [IN] Private Key Format
* @param passin [IN/OUT] Parsed password
*
* @retval CRYPT_EAL_PkeyCtx
*/
CRYPT_EAL_PkeyCtx *HITLS_APP_ProviderLoadPrvKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName,
const char *inFilePath, BSL_ParseFormat informat, char **passin);
/**
* @ingroup apps
*
* @brief Load the private key.
*
* @attention If inFilePath or passin is empty, it is read from the standard input.
*
* @param inFilePath [IN] file name
* @param informat [IN] Private Key Format
* @param passin [IN/OUT] Parsed password
*
* @retval CRYPT_EAL_PkeyCtx
*/
CRYPT_EAL_PkeyCtx *HITLS_APP_LoadPrvKey(const char *inFilePath, BSL_ParseFormat informat, char **passin);
/**
* @ingroup apps
*
* @brief Print the public key.
*
* @attention If outFilePath is empty, the standard output is displayed.
*
* @param pkey [IN] key
* @param outFilePath [IN] file name
* @param outformat [IN] Public Key Format
*
* @retval HITLS_APP_SUCCESS
* @retval HITLS_APP_INVALID_ARG
* @retval HITLS_APP_ENCODE_KEY_FAIL
* @retval HITLS_APP_UIO_FAIL
*/
int32_t HITLS_APP_PrintPubKey(CRYPT_EAL_PkeyCtx *pkey, const char *outFilePath, BSL_ParseFormat outformat);
/**
* @ingroup apps
*
* @brief Print the private key.
*
* @attention If outFilePath is empty, the standard output is displayed, If passout is empty, it is read
* from the standard input.
*
* @param pkey [IN] key
* @param outFilePath [IN] file name
* @param outformat [IN] Private Key Format
* @param cipherAlgCid [IN] Encryption algorithm cid
* @param passout [IN/OUT] encryption password
*
* @retval HITLS_APP_SUCCESS
* @retval HITLS_APP_INVALID_ARG
* @retval HITLS_APP_ENCODE_KEY_FAIL
* @retval HITLS_APP_UIO_FAIL
*/
int32_t HITLS_APP_PrintPrvKey(CRYPT_EAL_PkeyCtx *pkey, const char *outFilePath, BSL_ParseFormat outformat,
int32_t cipherAlgCid, char **passout);
typedef struct {
const char *name;
BSL_ParseFormat outformat;
int32_t cipherAlgCid;
bool text;
bool noout;
} AppKeyPrintParam;
int32_t HITLS_APP_PrintPrvKeyByUio(BSL_UIO *uio, CRYPT_EAL_PkeyCtx *pkey, AppKeyPrintParam *printKeyParam,
char **passout);
/**
* @ingroup apps
*
* @brief Obtain and check the encryption algorithm.
*
* @param name [IN] encryption name
* @param symId [IN/OUT] encryption algorithm cid
*
* @retval HITLS_APP_SUCCESS
* @retval HITLS_APP_INVALID_ARG
*/
int32_t HITLS_APP_GetAndCheckCipherOpt(const char *name, int32_t *symId);
/**
* @ingroup apps
*
* @brief Load the cert.
*
* @param inPath [IN] cert path
* @param inform [IN] cert format
*
* @retval HITLS_X509_Cert
*/
HITLS_X509_Cert *HITLS_APP_LoadCert(const char *inPath, BSL_ParseFormat inform);
/**
* @ingroup apps
*
* @brief Load the csr.
*
* @param inPath [IN] csr path
* @param inform [IN] csr format
*
* @retval HITLS_X509_Csr
*/
HITLS_X509_Csr *HITLS_APP_LoadCsr(const char *inPath, BSL_ParseFormat inform);
int32_t HITLS_APP_GetAndCheckHashOpt(const char *name, int32_t *hashId);
int32_t HITLS_APP_PrintText(const BSL_Buffer *csrBuf, const char *outFileName);
int32_t HITLS_APP_HexToByte(const char *hex, uint8_t **bin, uint32_t *len);
CRYPT_EAL_PkeyCtx *HITLS_APP_GenRsaPkeyCtx(uint32_t bits);
int32_t HITLS_APP_StrToHex(const char *str, uint8_t *hex, uint32_t *hexLen);
typedef struct {
int32_t randAlgId;
AppProvider *provider;
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param *smParam;
#endif
} AppInitParam;
int32_t HITLS_APP_Init(AppInitParam *param);
void HITLS_APP_Deinit(AppInitParam *param, int32_t ret);
int32_t HITLS_APP_GetTime(int64_t *time);
#ifdef __cplusplus
}
#endif
#endif // APP_UTILS_H | 2401_83913325/openHiTLS_1 | apps/include/app_utils.h | C | unknown | 7,582 |
/*
* 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_APP_VERIFY_H
#define HITLS_APP_VERIFY_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_VerifyMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2401_83913325/openHiTLS_1 | apps/include/app_verify.h | C | unknown | 744 |
/*
* 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_APP_X509_H
#define HITLS_APP_X509_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_X509Main(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_X509_H | 2401_83913325/openHiTLS_1 | apps/include/app_x509.h | C | unknown | 757 |
/*
* 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:
*#include "hitls_config.h"
* 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 "app_client.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <signal.h>
#include <unistd.h>
#include "securec.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_tls_common.h"
#include "app_provider.h"
#include "app_sm.h"
#include "app_keymgmt.h"
#include "app_utils.h"
#include "hitls.h"
#include "hitls_cert_init.h"
#include "hitls_session.h"
#include "crypt_errno.h"
#include "hitls_crypt_init.h"
#include "bsl_uio.h"
#include "crypt_eal_init.h"
#include "crypt_eal_rand.h"
#include "bsl_sal.h"
#include "bsl_err.h"
#include "sal_net.h"
#include "bsl_log.h"
#define HTTP_BUF_MAXLEN (18 * 1024)
#define IS_SUPPORT_GET_EOF 1
#define MAX_BUFSIZE (1024 * 8)
#define HEARTBEAT_MISS_COUNT 3
#define HEARTBEAT_INTERVAL 1
/* Client option types */
typedef enum {
HITLS_CLIENT_OPT_HOST = 2,
HITLS_CLIENT_OPT_PORT,
/* Protocol options */
HITLS_CLIENT_OPT_TLS,
HITLS_CLIENT_OPT_TLCP,
HITLS_CLIENT_OPT_DTLCP,
HITLS_CLIENT_OPT_CIPHER,
/* Certificate options */
HITLS_CLIENT_OPT_CAFILE,
HITLS_CLIENT_OPT_CHAINCAFILE,
HITLS_CLIENT_OPT_NO_VERIFY,
/* TLCP options */
HITLS_CLIENT_OPT_TLCP_ENC_CERT,
HITLS_CLIENT_OPT_TLCP_ENC_KEY,
HITLS_CLIENT_OPT_TLCP_SIGN_CERT,
HITLS_CLIENT_OPT_TLCP_SIGN_KEY,
/* Output options */
HITLS_CLIENT_OPT_QUIET,
HITLS_CLIENT_OPT_STATE,
HITLS_CLIENT_OPT_PREXIT,
/* Format options */
HITLS_CLIENT_OPT_CERTFORM,
HITLS_CLIENT_OPT_KEYFORM,
HITLS_APP_PROV_ENUM,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS_ENUM,
#endif
HITLS_CLIENT_OPT_MAX,
} HITLS_ClientOptType;
/* Command line options for s_client */
static const HITLS_CmdOption g_clientOptions[] = {
/* Connection options */
{"host", HITLS_CLIENT_OPT_HOST, HITLS_APP_OPT_VALUETYPE_STRING, "Target hostname or IP address"},
{"port", HITLS_CLIENT_OPT_PORT, HITLS_APP_OPT_VALUETYPE_UINT, "Target port number (default 443)"},
/* Protocol options */
{"tls", HITLS_CLIENT_OPT_TLS, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Use TLS protocol (default)"},
{"tlcp", HITLS_CLIENT_OPT_TLCP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Use TLCP protocol"},
{"dtlcp", HITLS_CLIENT_OPT_DTLCP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Use DTLCP protocol"},
{"cipher", HITLS_CLIENT_OPT_CIPHER, HITLS_APP_OPT_VALUETYPE_STRING, "Specify cipher suites"},
/* Certificate options */
{"CAfile", HITLS_CLIENT_OPT_CAFILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "CA certificate file"},
{"chainCAfile", HITLS_CLIENT_OPT_CHAINCAFILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "CA file for certificate chain"},
{"noverify", HITLS_CLIENT_OPT_NO_VERIFY, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Don't verify server certificate"},
/* TLCP options */
{"tlcp_enc_cert", HITLS_CLIENT_OPT_TLCP_ENC_CERT, HITLS_APP_OPT_VALUETYPE_IN_FILE, "TLCP encryption certificate"},
{"tlcp_enc_key", HITLS_CLIENT_OPT_TLCP_ENC_KEY, HITLS_APP_OPT_VALUETYPE_IN_FILE, "TLCP encryption private key"},
{"tlcp_sign_cert", HITLS_CLIENT_OPT_TLCP_SIGN_CERT, HITLS_APP_OPT_VALUETYPE_IN_FILE, "TLCP signature certificate"},
{"tlcp_sign_key", HITLS_CLIENT_OPT_TLCP_SIGN_KEY, HITLS_APP_OPT_VALUETYPE_IN_FILE, "TLCP signature private key"},
/* Output options */
{"quiet", HITLS_CLIENT_OPT_QUIET, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Quiet mode"},
{"state", HITLS_CLIENT_OPT_STATE, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Show handshake state"},
{"prexit", HITLS_CLIENT_OPT_PREXIT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Exit after handshake"},
/* Format options */
{"certform", HITLS_CLIENT_OPT_CERTFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Certificate format (PEM|DER)"},
{"keyform", HITLS_CLIENT_OPT_KEYFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Private key format (PEM|DER)"},
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Show help"},
HITLS_APP_PROV_OPTIONS,
#ifdef HITLS_APP_SM_MODE
/* SM mode options */
HITLS_SM_OPTIONS,
#endif
{NULL, 0, 0, NULL}
};
#ifdef HITLS_APP_SM_MODE
/* Thread client parameters structure */
typedef struct {
HITLS_Ctx *ctx;
int ret;
} ThreadClientArgs;
#endif
static int32_t CreateConfigAndConnection(HITLS_ClientParams *params, HITLS_Config **config, BSL_UIO **uio,
HITLS_Ctx **ctx);
static void InitClientParams(HITLS_ClientParams *params, AppProvider *provider)
{
if (params == NULL || provider == NULL) {
return;
}
/* Set default values */
params->port = 4433;
params->connectTimeout = 10;
params->protocol = NULL;
params->verifyDepth = 9;
params->certFormat = BSL_FORMAT_PEM;
params->keyFormat = BSL_FORMAT_PEM;
params->provider = provider;
params->verifyNone = false;
}
typedef int (*ClientOptHandleFunc)(HITLS_ClientParams *params);
typedef struct {
int optType;
ClientOptHandleFunc func;
} ClientOptHandleFuncMap;
static int HandleClientHost(HITLS_ClientParams *params)
{
params->host = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleClientPort(HITLS_ClientParams *params)
{
return HITLS_APP_OptGetUint32(HITLS_APP_OptGetValueStr(), (uint32_t*)¶ms->port);
}
static int HandleClientTLS(HITLS_ClientParams *params)
{
params->protocol = "tls";
return HITLS_APP_SUCCESS;
}
static int HandleClientTLCP(HITLS_ClientParams *params)
{
params->protocol = "tlcp";
return HITLS_APP_SUCCESS;
}
static int HandleClientDTLCP(HITLS_ClientParams *params)
{
params->protocol = "dtlcp";
return HITLS_APP_SUCCESS;
}
static int HandleClientCipher(HITLS_ClientParams *params)
{
params->cipherSuites = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleClientCAFile(HITLS_ClientParams *params)
{
params->caFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleClientCAChain(HITLS_ClientParams *params)
{
params->caChain = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleClientNoVerify(HITLS_ClientParams *params)
{
params->verifyNone = true;
return HITLS_APP_SUCCESS;
}
static int HandleClientTLCPEncCert(HITLS_ClientParams *params)
{
params->tlcpEncCert = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleClientTLCPEncKey(HITLS_ClientParams *params)
{
params->tlcpEncKey = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleClientTLCPSignCert(HITLS_ClientParams *params)
{
params->tlcpSignCert = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleClientTLCPSignKey(HITLS_ClientParams *params)
{
params->tlcpSignKey = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleClientQuiet(HITLS_ClientParams *params)
{
params->quiet = true;
return HITLS_APP_SUCCESS;
}
static int HandleClientState(HITLS_ClientParams *params)
{
params->state = true;
return HITLS_APP_SUCCESS;
}
static int HandleClientPrexit(HITLS_ClientParams *params)
{
params->prexit = true;
return HITLS_APP_SUCCESS;
}
static int HandleClientCertForm(HITLS_ClientParams *params)
{
return HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(),
HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, ¶ms->certFormat);
}
static int HandleClientKeyForm(HITLS_ClientParams *params)
{
return HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(),
HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, ¶ms->keyFormat);
}
static int HandleClientHelp(HITLS_ClientParams *params)
{
(void)params; // Unused parameter
HITLS_APP_OptHelpPrint(g_clientOptions);
return HITLS_APP_HELP;
}
static const ClientOptHandleFuncMap g_clientOptHandleFuncMap[] = {
{HITLS_CLIENT_OPT_HOST, HandleClientHost},
{HITLS_CLIENT_OPT_PORT, HandleClientPort},
{HITLS_CLIENT_OPT_TLS, HandleClientTLS},
{HITLS_CLIENT_OPT_TLCP, HandleClientTLCP},
{HITLS_CLIENT_OPT_DTLCP, HandleClientDTLCP},
{HITLS_CLIENT_OPT_CIPHER, HandleClientCipher},
{HITLS_CLIENT_OPT_CAFILE, HandleClientCAFile},
{HITLS_CLIENT_OPT_CHAINCAFILE, HandleClientCAChain},
{HITLS_CLIENT_OPT_NO_VERIFY, HandleClientNoVerify},
{HITLS_CLIENT_OPT_TLCP_ENC_CERT, HandleClientTLCPEncCert},
{HITLS_CLIENT_OPT_TLCP_ENC_KEY, HandleClientTLCPEncKey},
{HITLS_CLIENT_OPT_TLCP_SIGN_CERT, HandleClientTLCPSignCert},
{HITLS_CLIENT_OPT_TLCP_SIGN_KEY, HandleClientTLCPSignKey},
{HITLS_CLIENT_OPT_QUIET, HandleClientQuiet},
{HITLS_CLIENT_OPT_STATE, HandleClientState},
{HITLS_CLIENT_OPT_PREXIT, HandleClientPrexit},
{HITLS_CLIENT_OPT_CERTFORM, HandleClientCertForm},
{HITLS_CLIENT_OPT_KEYFORM, HandleClientKeyForm},
{HITLS_APP_OPT_HELP, HandleClientHelp},
};
static int ParseClientOptLoop(HITLS_ClientParams *params)
{
int ret = HITLS_APP_SUCCESS;
int opt;
while ((opt = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF && ret == HITLS_APP_SUCCESS) {
for (size_t i = 0; i < sizeof(g_clientOptHandleFuncMap)/sizeof(g_clientOptHandleFuncMap[0]); ++i) {
if (g_clientOptHandleFuncMap[i].optType == opt) {
ret = g_clientOptHandleFuncMap[i].func(params);
break;
}
}
HITLS_APP_PROV_CASES(opt, params->provider)
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_CASES(opt, params->smParam);
#endif
}
if (HITLS_APP_GetRestOptNum() != 0) {
AppPrintError("Extra arguments given.\n");
AppPrintError("pkeyutl: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return ret;
}
static int32_t CheckSmParam(HITLS_ClientParams *params)
{
#ifdef HITLS_APP_SM_MODE
if (params->smParam->smTag == 1) {
if (params->smParam->uuid == NULL) {
AppPrintError("client: The uuid is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (params->smParam->workPath == NULL) {
AppPrintError("client: The workpath is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
}
#else
(void) params;
#endif
return HITLS_APP_SUCCESS;
}
int ParseClientOptions(int argc, char *argv[], HITLS_ClientParams *params, AppProvider *provider)
{
if (params == NULL) {
return HITLS_APP_INVALID_ARG;
}
InitClientParams(params, provider);
int opt = HITLS_APP_OptBegin(argc, argv, g_clientOptions);
if (opt != HITLS_APP_SUCCESS) {
AppPrintError("Failed to initialize option parser\n");
return opt;
}
int loopRet = ParseClientOptLoop(params);
if (loopRet != HITLS_APP_SUCCESS) {
if (loopRet != HITLS_APP_HELP) {
AppPrintError("Failed to parse client options: 0x%x\n", loopRet);
}
return loopRet;
}
HITLS_APP_OptEnd();
/* Validate required parameters */
if (params->host == NULL) {
AppPrintError("Host must be specified\n");
return HITLS_APP_INVALID_ARG;
}
int32_t ret = CheckSmParam(params);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return HITLS_APP_SUCCESS;
}
static HITLS_Config *CreateClientConfig(HITLS_ClientParams *params)
{
if (params == NULL) {
return NULL;
}
/* Determine protocol type */
APP_ProtocolType protocol = ParseProtocolType(params->protocol);
/* Create base configuration */
HITLS_Config *config = CreateProtocolConfig(protocol, params->provider);
if (config == NULL) {
return NULL;
}
int ret = HITLS_SUCCESS;
/* Configure cipher suites */
if (params->cipherSuites) {
ret = ConfigureCipherSuites(config, params->cipherSuites, protocol);
if (ret != HITLS_APP_SUCCESS) {
HITLS_CFG_FreeConfig(config);
return NULL;
}
}
/* Configure certificate verification */
APP_CertConfig certConfig = {
.caFile = params->caFile,
.caChain = params->caChain,
.certFormat = params->certFormat,
.keyFormat = params->keyFormat,
.tlcpEncCert = params->tlcpEncCert,
.tlcpEncKey = params->tlcpEncKey,
.tlcpSignCert = params->tlcpSignCert,
.tlcpSignKey = params->tlcpSignKey,
.provider = params->provider,
#ifdef HITLS_APP_SM_MODE
.smParam = params->smParam,
#endif
};
ret = ConfCertVerification(config, &certConfig, !params->verifyNone, params->verifyDepth);
if (ret != HITLS_APP_SUCCESS) {
HITLS_CFG_FreeConfig(config);
return NULL;
}
/* Configure client certificate if provided */
if (protocol == APP_PROTOCOL_TLCP || protocol == APP_PROTOCOL_DTLCP) {
ret = ConfigureTLCPCertificates(config, &certConfig);
}
if (ret != HITLS_APP_SUCCESS) {
HITLS_CFG_FreeConfig(config);
return NULL;
}
return config;
}
static BSL_UIO *CreateClientConnection(HITLS_ClientParams *params)
{
if (params == NULL || params->host == NULL) {
return NULL;
}
APP_NetworkAddr addr = {
.host = params->host,
.port = params->port,
};
int sockfd = -1;
BSL_UIO *uio = NULL;
/* Create socket based on protocol */
APP_ProtocolType protocol = ParseProtocolType(params->protocol);
if (protocol == APP_PROTOCOL_DTLCP) {
sockfd = CreateUDPSocket(&addr, params->connectTimeout);
uio = BSL_UIO_New(BSL_UIO_UdpMethod());
} else {
sockfd = CreateTCPSocket(&addr, params->connectTimeout);
uio = BSL_UIO_New(BSL_UIO_TcpMethod());
}
if (sockfd < 0 || uio == NULL) {
if (sockfd >= 0) {
BSL_SAL_SockClose(sockfd);
}
if (uio) {
BSL_UIO_Free(uio);
}
return NULL;
}
/* Set socket to UIO */
int ret = BSL_UIO_Ctrl(uio, BSL_UIO_SET_FD, sizeof(sockfd), &sockfd);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to set socket to UIO: 0x%x\n", ret);
BSL_SAL_SockClose(sockfd);
BSL_UIO_Free(uio);
return NULL;
}
if (protocol == APP_PROTOCOL_DTLCP) {
BSL_SAL_SockAddr serverAddr = NULL;
ret = SAL_SockAddrNew(&serverAddr);
if (ret != BSL_SUCCESS) {
BSL_UIO_Free(uio);
BSL_SAL_SockClose(sockfd);
return NULL;
}
int32_t addrLen = (int32_t)SAL_SockAddrSize(serverAddr);
if (getpeername(sockfd, (struct sockaddr*)serverAddr, (socklen_t *)&addrLen) == 0) {
ret = BSL_UIO_Ctrl(uio, BSL_UIO_UDP_SET_CONNECTED, addrLen, serverAddr);
if (ret != BSL_SUCCESS) {
SAL_SockAddrFree(serverAddr);
BSL_SAL_SockClose(sockfd);
BSL_UIO_Free(uio);
return NULL;
}
}
SAL_SockAddrFree(serverAddr);
}
BSL_UIO_SetInit(uio, true);
if (!params->quiet) {
AppPrintInfo("Connected to %s:%d\n", params->host, params->port);
}
return uio;
}
static int PerformClientHandshake(HITLS_Ctx *ctx, HITLS_ClientParams *params)
{
if (ctx == NULL || params == NULL) {
return HITLS_APP_INVALID_ARG;
}
if (!params->quiet) {
AppPrintInfo("Starting TLS handshake...\n");
}
/* Perform handshake */
int ret;
do {
ret = HITLS_Connect(ctx);
if (ret == HITLS_SUCCESS) {
break;
}
if (ret != HITLS_REC_NORMAL_RECV_BUF_EMPTY && ret != HITLS_REC_NORMAL_IO_BUSY) {
AppPrintError("TLS handshake failed: 0x%x\n", ret);
return HITLS_APP_ERR_HANDSHAKE;
}
/* Non-blocking I/O, retry */
usleep(10000); /* Sleep 10000us. */
} while (ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY || ret == HITLS_REC_NORMAL_IO_BUSY);
if (!params->quiet) {
AppPrintInfo("TLS handshake completed successfully\n");
/* Print connection information */
PrintConnectionInfo(ctx, params->state);
}
return HITLS_APP_SUCCESS;
}
#ifdef HITLS_APP_SM_MODE
static int32_t SendKeyCallback(void *ctx, const void *buf, uint32_t len)
{
uint32_t written = 0;
int32_t ret = HITLS_Write(ctx, (const uint8_t *)buf, len, &written);
if (ret != HITLS_SUCCESS) {
return ret;
}
if (written != len) {
return HITLS_APP_ERR_SEND_DATA;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandleSm(HITLS_Ctx *ctx, HITLS_ClientParams *params)
{
int32_t ret = HITLS_APP_SendKey(params->provider, params->smParam, SendKeyCallback, ctx);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("client: Failed to send key: 0x%x\n", ret);
return ret;
}
AppPrintError("client: Sent key to server successfully!\n");
uint8_t buffer[8192];
uint32_t readLen = 0;
ret = HITLS_Read(ctx, buffer, sizeof(buffer) - 1, &readLen);
if (ret == HITLS_SUCCESS && readLen > 0) {
buffer[readLen] = '\0';
if (!params->quiet) {
AppPrintError("client: Received %u bytes:\n%s\n", readLen, buffer);
}
} else if (ret != HITLS_SUCCESS) {
AppPrintError("client: Failed to read response: 0x%x\n", ret);
}
return HITLS_APP_SUCCESS;
}
#endif
static int HandleClientDataExchange(HITLS_Ctx *ctx, HITLS_ClientParams *params)
{
if (ctx == NULL || params == NULL) {
return HITLS_APP_INVALID_ARG;
}
#ifdef HITLS_APP_SM_MODE
if (params->smParam->smTag == 1) {
return HandleSm(ctx, params);
}
#endif
int ret = HITLS_APP_SUCCESS;
bool isEof = false;
uint32_t readLen = 0;
BSL_UIO *readUio = HITLS_APP_UioOpen(NULL, 'r', 0);
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
if (readUio == NULL) {
AppPrintError("s_client: Failed to open stdin\n");
return HITLS_APP_UIO_FAIL;
}
/* Interactive mode if no specific data to send */
if (!params->prexit) {
if (!params->quiet) {
AppPrintInfo("Interactive mode - type messages (Ctrl+C to exit):\n");
}
char inputBuffer[HTTP_BUF_MAXLEN];
while (BSL_UIO_Ctrl(readUio, BSL_UIO_FILE_GET_EOF, IS_SUPPORT_GET_EOF, &isEof) == BSL_SUCCESS && !isEof) {
if (BSL_UIO_Read(readUio, inputBuffer, HTTP_BUF_MAXLEN, &readLen) != BSL_SUCCESS) {
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to obtain the content from the STDIN\n");
return HITLS_APP_STDIN_FAIL;
}
if (readLen > 0 && inputBuffer[readLen - 1] == '\n') {
inputBuffer[readLen - 1] = '\0';
readLen--;
}
if (readLen == 0) {
continue;
}
uint32_t written = 0;
ret = HITLS_Write(ctx, (const uint8_t *)inputBuffer, readLen, &written);
if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to send data: 0x%x\n", ret);
break;
}
/* Try to read response */
uint8_t response[HTTP_BUF_MAXLEN];
uint32_t read_len = 0;
ret = HITLS_Read(ctx, response, sizeof(response) - 1, &read_len);
if (ret == HITLS_SUCCESS && read_len > 0) {
response[read_len] = '\0';
AppPrintInfo("Response: %s\n", response);
}
}
}
BSL_UIO_Free(readUio);
return HITLS_APP_SUCCESS;
}
static void CleanupClientResources(HITLS_Ctx *ctx, HITLS_Config *config, BSL_UIO *uio)
{
if (ctx) {
HITLS_Close(ctx);
HITLS_Free(ctx);
}
if (config) {
HITLS_CFG_FreeConfig(config);
}
if (uio) {
/* Close socket */
int fd = -1;
BSL_UIO_Ctrl(uio, BSL_UIO_GET_FD, 0, &fd);
if (fd >= 0) {
BSL_SAL_SockClose(fd);
}
BSL_UIO_Free(uio);
}
}
#ifdef HITLS_APP_SM_MODE
static volatile bool g_serverOk = false;
static volatile bool g_loopFlag = true;
static int32_t ReceiveHeartBeat(HITLS_Ctx *ctx)
{
uint8_t buffer[APP_HEARTBEAT_LEN] = {0};
uint32_t len = sizeof(buffer);
uint32_t readLen = 0;
int32_t ret = HITLS_Read(ctx, buffer, len, &readLen);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = ParseHeartBeat(buffer, readLen);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return HITLS_APP_SUCCESS;
}
static int32_t SendHeartBeat(HITLS_Ctx *ctx)
{
uint8_t buffer[APP_HEARTBEAT_LEN] = {0};
uint32_t len = sizeof(buffer);
uint32_t written = 0;
int32_t ret = GetHeartBeat(buffer, &len);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
(void)HITLS_Write(ctx, buffer, len, &written);
return HITLS_APP_SUCCESS;
}
static int32_t SendAndReceiveHeartBeat(HITLS_Ctx *ctx, uint32_t *missedCount)
{
int32_t ret = SendHeartBeat(ctx);
if (ret != HITLS_APP_SUCCESS) {
g_serverOk = false;
return ret;
}
ret = ReceiveHeartBeat(ctx);
if (ret != HITLS_APP_SUCCESS) {
(*missedCount)++;
g_serverOk = false;
return HITLS_APP_SUCCESS;
}
*missedCount = 0;
g_serverOk = true;
return ret;
}
static int32_t HandleOneHeartBeat(HITLS_Ctx *ctx)
{
uint32_t missedCount = 0;
int32_t ret = HITLS_APP_SUCCESS;
ret = SendAndReceiveHeartBeat(ctx, &missedCount);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
while (g_loopFlag) {
BSL_SAL_Sleep(HEARTBEAT_INTERVAL);
ret = SendAndReceiveHeartBeat(ctx, &missedCount);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (missedCount > HEARTBEAT_MISS_COUNT) {
break;
}
}
return ret;
}
/* Thread server function */
static void *ThreadClientMainLoop(void *arg)
{
ThreadClientArgs *threadArgs = (ThreadClientArgs *)arg;
if (threadArgs == NULL) {
return NULL;
}
threadArgs->ret = HandleOneHeartBeat(threadArgs->ctx);
return NULL;
}
static int32_t ConfirmAction(void)
{
int ret = HITLS_APP_SUCCESS;
AppPrintError("Please enter 'y' to confirm send key to server\n");
char readBuf[MAX_BUFSIZE] = {0};
uint32_t readLen = MAX_BUFSIZE;
BSL_UIO *rUio = HITLS_APP_UioOpen(NULL, 'r', 1);
if (rUio == NULL) {
AppPrintError("Failed to open the stdin.\n");
return HITLS_APP_UIO_FAIL;
}
if (BSL_UIO_Read(rUio, readBuf, MAX_BUFSIZE, &readLen) != BSL_SUCCESS) {
(void)AppPrintError("Failed to obtain the content from the STDIN\n");
BSL_UIO_Free(rUio);
return HITLS_APP_UIO_FAIL;
}
if (readLen == 0 || readLen == MAX_BUFSIZE) {
AppPrintError("Failed to read the input content\n");
BSL_UIO_Free(rUio);
return HITLS_APP_STDIN_FAIL;
}
if (strcmp(readBuf, "y") != 0 && strcmp(readBuf, "Y") != 0 && strcmp(readBuf, "yes") != 0 &&
strcmp(readBuf, "YES") != 0 && strcmp(readBuf, "Yes") != 0) {
ret = HITLS_APP_INVALID_ARG;
AppPrintError("cancel send key to server.\n");
}
BSL_UIO_Free(rUio);
return ret;
}
static int32_t SendHeartBeatAndConfirm(HITLS_ClientParams *params)
{
int ret = HITLS_APP_SUCCESS;
HITLS_Config *dtlcpConfig = NULL;
BSL_UIO *dtlcpUio = NULL;
HITLS_Ctx *dtlcpCtx = NULL;
HITLS_ClientParams dtlcpParams = {0};
(void)memcpy_s(&dtlcpParams, sizeof(dtlcpParams), params, sizeof(*params));
dtlcpParams.protocol = "dtlcp";
dtlcpParams.port = DEFAULT_DTLCP_PORT;
do {
ret = CreateConfigAndConnection(&dtlcpParams, &dtlcpConfig, &dtlcpUio, &dtlcpCtx);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("client: Failed to create config and connection: 0x%x\n", ret);
break;
}
BSL_SAL_ThreadId thread = NULL;
ThreadClientArgs threadArgs = {dtlcpCtx, 0};
ret = BSL_SAL_ThreadCreate(&thread, ThreadClientMainLoop, &threadArgs);
if (ret != BSL_SUCCESS) {
AppPrintError("client: Failed to create dtlcp client thread.\n");
ret = HITLS_APP_SAL_FAIL;
break;
}
ret = ConfirmAction();
g_loopFlag = false;
BSL_SAL_ThreadClose(thread);
if (ret != HITLS_APP_SUCCESS) {
break;
}
if (threadArgs.ret != HITLS_APP_SUCCESS) {
AppPrintError("client: Dtlcp client thread failed with errCode: 0x%x.\n", threadArgs.ret);
ret = threadArgs.ret;
break;
}
if (!g_serverOk) {
AppPrintError("client: Server is not ok.\n");
ret = HITLS_APP_ERR_CONNECT;
break;
}
} while (0);
CleanupClientResources(dtlcpCtx, dtlcpConfig, dtlcpUio);
return ret;
}
#endif
static int32_t CreateConfigAndConnection(HITLS_ClientParams *params, HITLS_Config **config, BSL_UIO **uio,
HITLS_Ctx **ctx)
{
int ret = HITLS_APP_SUCCESS;
HITLS_Config *configTmp = NULL;
BSL_UIO *uioTmp = NULL;
HITLS_Ctx *ctxTmp = NULL;
do {
/* Create TLS configuration */
configTmp = CreateClientConfig(params);
if (configTmp == NULL) {
AppPrintError("client: Failed to create TLS configuration\n");
ret = HITLS_APP_INVALID_ARG;
break;
}
/* Establish network connection */
uioTmp = CreateClientConnection(params);
if (uioTmp == NULL) {
AppPrintError("client: Failed to establish network connection\n");
ret = HITLS_APP_ERR_CONNECT;
break;
}
/* Create TLS context */
ctxTmp = HITLS_New(configTmp);
if (ctxTmp == NULL) {
AppPrintError("client: Failed to create TLS context\n");
ret = HITLS_APP_ERR_CREATE_CTX;
break;
}
/* Associate UIO with TLS context */
ret = HITLS_SetUio(ctxTmp, uioTmp);
if (ret != HITLS_SUCCESS) {
AppPrintError("client: Failed to set UIO: 0x%x\n", ret);
ret = HITLS_APP_UIO_FAIL;
break;
}
/* Perform TLS handshake */
ret = PerformClientHandshake(ctxTmp, params);
if (ret != HITLS_APP_SUCCESS) {
break;
}
*config = configTmp;
*uio = uioTmp;
*ctx = ctxTmp;
return HITLS_APP_SUCCESS;
} while (0);
CleanupClientResources(ctxTmp, configTmp, uioTmp);
return ret;
}
int HITLS_ClientMain(int argc, char *argv[])
{
AppProvider appProvider = {NULL, NULL, NULL};
HITLS_ClientParams params = {0};
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param smParam = {NULL, 0, NULL, NULL, 0, HITLS_APP_SM_STATUS_OPEN};
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider, &smParam};
params.smParam = &smParam;
#else
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider};
#endif
HITLS_Config *config = NULL;
HITLS_Ctx *ctx = NULL;
BSL_UIO *uio = NULL;
int ret = HITLS_APP_SUCCESS;
/* Initialize library */
/* BSL memory callbacks are already set up in BSL module */
BSL_ERR_Init();
/* Initialize print UIO for error and info output */
ret = AppPrintErrorUioInit(stderr);
if (ret != HITLS_APP_SUCCESS) {
return HITLS_APP_INIT_FAILED;
}
ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL);
if (ret != CRYPT_SUCCESS) {
AppPrintError("Failed to initialize crypto library: 0x%x\n", ret);
return HITLS_APP_INIT_FAILED;
}
HITLS_CertMethodInit();
HITLS_CryptMethodInit();
/* Parse command line options */
ret = ParseClientOptions(argc, argv, ¶ms, &appProvider);
if (ret != HITLS_APP_SUCCESS) {
goto cleanup;
}
ret = HITLS_APP_Init(&initParam);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("client: Failed to initialize app: 0x%x\n", ret);
goto cleanup;
}
#ifdef HITLS_APP_SM_MODE
if (params.smParam->smTag == 1) {
ret = SendHeartBeatAndConfirm(¶ms);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("client: Failed to send heartbeat and confirm failed: 0x%x\n", ret);
goto cleanup;
}
}
#endif
ret = CreateConfigAndConnection(¶ms, &config, &uio, &ctx);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("client: Failed to create config and connection: 0x%x\n", ret);
goto cleanup;
}
/* Exit after handshake if requested */
if (params.prexit) {
if (!params.quiet) {
AppPrintInfo("client: Handshake completed, exiting as requested\n");
}
ret = HITLS_APP_SUCCESS;
goto cleanup;
}
/* Handle data exchange */
ret = HandleClientDataExchange(ctx, ¶ms);
cleanup:
CleanupClientResources(ctx, config, uio);
if (!params.quiet && ret == HITLS_APP_SUCCESS) {
AppPrintInfo("Client completed successfully\n");
}
HITLS_APP_Deinit(&initParam, ret);
/* Cleanup print UIO */
AppPrintErrorUioUnInit();
return ret;
} | 2401_83913325/openHiTLS_1 | apps/src/app_client.c | C | unknown | 30,874 |
/*
* 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 "app_conf.h"
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#if defined(__linux__) || defined(__unix__) || defined(__APPLE__) || defined(__MACH__)
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#else
#error "only support linux and macOS"
#endif
#include "securec.h"
#include "app_errno.h"
#include "bsl_sal.h"
#include "bsl_obj.h"
#include "bsl_obj_internal.h"
#include "bsl_list.h"
#include "hitls_pki_errno.h"
#include "hitls_x509_local.h"
#include "app_errno.h"
#include "app_opt.h"
#include "app_print.h"
#include "app_conf.h"
#define MAX_DN_LIST_SIZE 99
#define X509_EXT_SAN_VALUE_MAX_CNT 30 // san
#define IPV4_VALUE_MAX_CNT 4
#define IPV6_VALUE_STR_MAX_CNT 8
#define IPV6_VALUE_MAX_CNT 16
#define IPV6_EACH_VALUE_STR_LEN 4
#define EXT_STR_CRITICAL "critical"
typedef int32_t (*ProcExtCnfFunc)(BSL_CONF *cnf, bool critical, const char *cnfValue, ProcExtCallBack procExt,
void *ctx);
typedef struct {
char *name;
ProcExtCnfFunc func;
} X509ExtInfo;
typedef struct {
char *name;
int32_t keyUsage;
} X509KeyUsageMap;
#define X509_EXT_BCONS_VALUE_MAX_CNT 2 // ca and pathlen
#define X509_EXT_BCONS_SUB_VALUE_MAX_CNT 2 // ca:TRUE|FALSE or pathlen:num
#define X509_EXT_KU_VALUE_MAX_CNT 9 // 9 key usages
#define X509_EXT_EXKU_VALUE_MAX_CNT 6 // 6 extended key usages
#define X509_EXT_SKI_VALUE_MAX_CNT 1 // kid
#define X509_EXT_AKI_VALUE_MAX_CNT 1 // kid
#define X509_EXT_AKI_SUB_VALUE_MAX_CNT 2 // keyid:always
static X509KeyUsageMap g_kuMap[X509_EXT_KU_VALUE_MAX_CNT] = {
{HITLS_CFG_X509_EXT_KU_DIGITAL_SIGN, HITLS_X509_EXT_KU_DIGITAL_SIGN},
{HITLS_CFG_X509_EXT_KU_NON_REPUDIATION, HITLS_X509_EXT_KU_NON_REPUDIATION},
{HITLS_CFG_X509_EXT_KU_KEY_ENCIPHERMENT, HITLS_X509_EXT_KU_KEY_ENCIPHERMENT},
{HITLS_CFG_X509_EXT_KU_DATA_ENCIPHERMENT, HITLS_X509_EXT_KU_DATA_ENCIPHERMENT},
{HITLS_CFG_X509_EXT_KU_KEY_AGREEMENT, HITLS_X509_EXT_KU_KEY_AGREEMENT},
{HITLS_CFG_X509_EXT_KU_KEY_CERT_SIGN, HITLS_X509_EXT_KU_KEY_CERT_SIGN},
{HITLS_CFG_X509_EXT_KU_CRL_SIGN, HITLS_X509_EXT_KU_CRL_SIGN},
{HITLS_CFG_X509_EXT_KU_ENCIPHER_ONLY, HITLS_X509_EXT_KU_ENCIPHER_ONLY},
{HITLS_CFG_X509_EXT_KU_DECIPHER_ONLY, HITLS_X509_EXT_KU_DECIPHER_ONLY},
};
static X509KeyUsageMap g_exKuMap[X509_EXT_EXKU_VALUE_MAX_CNT] = {
{HITLS_CFG_X509_EXT_EXKU_SERVER_AUTH, BSL_CID_KP_SERVERAUTH},
{HITLS_CFG_X509_EXT_EXKU_CLIENT_AUTH, BSL_CID_KP_CLIENTAUTH},
{HITLS_CFG_X509_EXT_EXKU_CODE_SING, BSL_CID_KP_CODESIGNING},
{HITLS_CFG_X509_EXT_EXKU_EMAIL_PROT, BSL_CID_KP_EMAILPROTECTION},
{HITLS_CFG_X509_EXT_EXKU_TIME_STAMP, BSL_CID_KP_TIMESTAMPING},
{HITLS_CFG_X509_EXT_EXKU_OCSP_SIGN, BSL_CID_KP_OCSPSIGNING},
};
static bool isSpace(char c)
{
return c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r' || c == ' ';
}
static void SkipSpace(char **value)
{
char *tmp = *value;
char *end = *value + strlen(*value);
while (isSpace(*tmp) && tmp != end) {
tmp++;
}
*value = tmp;
}
static int32_t FindEndIdx(char *str, char separator, int32_t beginIdx, int32_t currIdx, bool allowEmpty)
{
while (currIdx >= 0 && (isSpace(str[currIdx]) || str[currIdx] == separator)) {
currIdx--;
}
if (beginIdx < currIdx) {
return currIdx + 1;
} else if (str[beginIdx] != separator) {
return beginIdx + 1;
} else if (allowEmpty) {
return beginIdx; // Empty substring
} else { // Empty substrings are not allowed.
return -1;
}
}
int32_t HITLS_APP_SplitString(const char *str, char separator, bool allowEmpty, char **strArr, uint32_t maxArrCnt,
uint32_t *realCnt)
{
if (str == NULL || strlen(str) == 0 || isSpace(separator) || strArr == NULL || maxArrCnt == 0 || realCnt == NULL) {
return HITLS_APP_INVALID_ARG;
}
// Delete leading spaces from input str.
char *tmp = (char *)(uintptr_t)str;
SkipSpace(&tmp);
// split
int32_t ret = HITLS_APP_SUCCESS;
char *res = strdup(tmp);
if (res == NULL) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
int32_t len = strlen(tmp);
int32_t begin;
int32_t end;
bool hasBegin = false;
*realCnt = 0;
for (int32_t i = 0; i < len; i++) {
if (!hasBegin) {
if (isSpace(res[i])) {
continue;
}
if (*realCnt == maxArrCnt) {
ret = HITLS_APP_CONF_FAIL;
break;
}
begin = i;
strArr[(*realCnt)++] = res + begin;
hasBegin = true;
}
if ((i + 1) != len && res[i] != separator) {
continue;
}
end = FindEndIdx(res, separator, begin, i, allowEmpty);
if (end == -1) {
ret = HITLS_APP_CONF_FAIL;
break;
}
res[end] = '\0';
hasBegin = false;
}
if (ret != HITLS_APP_SUCCESS) {
*realCnt = 0;
BSL_SAL_FREE(strArr[0]);
}
return ret;
}
static bool ExtGetCritical(char **value)
{
SkipSpace(value);
uint32_t criticalLen = strlen(EXT_STR_CRITICAL);
if (strlen(*value) < criticalLen || strncmp(*value, EXT_STR_CRITICAL, criticalLen) != 0) {
return false;
}
*value += criticalLen;
SkipSpace(value);
if (**value == ',') {
(*value)++;
}
return true;
}
static int32_t ParseBasicConstraints(char **value, HITLS_X509_ExtBCons *bCons)
{
if (strcmp(value[0], "CA") == 0) {
if (strcmp(value[1], "FALSE") == 0) {
bCons->isCa = false;
} else if (strcmp(value[1], "TRUE") == 0) {
bCons->isCa = true;
} else {
AppPrintError("Illegal value of basicConstraints CA: %s.\n", value[1]);
return HITLS_APP_CONF_FAIL;
}
return HITLS_APP_SUCCESS;
} else if (strcmp(value[0], "pathlen") != 0) {
AppPrintError("Unrecognized value of basicConstraints: %s.\n", value[0]);
return HITLS_APP_CONF_FAIL;
}
int32_t pathLen;
int32_t ret = HITLS_APP_OptGetInt(value[1], &pathLen);
if (ret != HITLS_APP_SUCCESS || pathLen < 0) {
AppPrintError("Illegal value of basicConstraints pathLen(>=0): %s.\n", value[1]);
return HITLS_APP_CONF_FAIL;
}
bCons->maxPathLen = pathLen;
return HITLS_APP_SUCCESS;
}
static int32_t ProcBasicConstraints(BSL_CONF *cnf, bool critical, const char *cnfValue,
ProcExtCallBack procExt, void *ctx)
{
(void)cnf;
HITLS_X509_ExtBCons bCons = {critical, false, -1};
char *valueList[X509_EXT_BCONS_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_BCONS_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split basicConstraints failed: %s.\n", cnfValue);
return ret;
}
for (uint32_t i = 0; i < valueCnt; i++) {
char *subList[X509_EXT_BCONS_VALUE_MAX_CNT] = {0};
uint32_t subCnt = 0;
ret = HITLS_APP_SplitString(valueList[i], ':', false, subList, X509_EXT_BCONS_VALUE_MAX_CNT, &subCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split sub-value of basicConstraints failed: %s.\n", valueList[i]);
BSL_SAL_Free(valueList[0]);
return ret;
}
if (subCnt != X509_EXT_BCONS_SUB_VALUE_MAX_CNT) {
AppPrintError("Illegal value of basicConstraints: %s.\n", valueList[i]);
BSL_SAL_Free(valueList[0]);
BSL_SAL_Free(subList[0]);
return HITLS_APP_CONF_FAIL;
}
ret = ParseBasicConstraints(subList, &bCons);
BSL_SAL_Free(subList[0]);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_Free(valueList[0]);
return ret;
}
}
BSL_SAL_Free(valueList[0]);
return procExt(BSL_CID_CE_BASICCONSTRAINTS, &bCons, ctx);
}
static int32_t ProcKeyUsage(BSL_CONF *cnf, bool critical, const char *cnfValue, ProcExtCallBack procExt, void *ctx)
{
(void)cnf;
HITLS_X509_ExtKeyUsage ku = {critical, 0};
char *valueList[X509_EXT_KU_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_KU_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split value of keyUsage falied: %s.\n", cnfValue);
return ret;
}
bool found;
for (uint32_t i = 0; i < valueCnt; i++) {
found = false;
for (uint32_t j = 0; j < X509_EXT_KU_VALUE_MAX_CNT; j++) {
if (strcmp(g_kuMap[j].name, valueList[i]) == 0) {
ku.keyUsage |= g_kuMap[j].keyUsage;
found = true;
break;
}
}
if (!found) {
AppPrintError("Unrecognized value of keyUsage: %s.\n", valueList[i]);
BSL_SAL_Free(valueList[0]);
return HITLS_APP_CONF_FAIL;
}
}
BSL_SAL_Free(valueList[0]);
return procExt(BSL_CID_CE_KEYUSAGE, &ku, ctx);
}
static int32_t CmpExKeyUsageByOid(const void *pCurr, const void *pOid)
{
const BSL_Buffer *curr = pCurr;
const BslOidString *oid = pOid;
if (curr->dataLen != oid->octetLen) {
return 1;
}
return memcmp(curr->data, oid->octs, curr->dataLen);
}
static int32_t AddExtendKeyUsage(BslOidString *oidStr, BslList *list)
{
BSL_Buffer *oid = BSL_SAL_Malloc(list->dataSize);
if (oid == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
oid->data = (uint8_t *)oidStr->octs;
oid->dataLen = oidStr->octetLen;
if (BSL_LIST_AddElement(list, oid, BSL_LIST_POS_END) != 0) {
BSL_SAL_Free(oid);
return HITLS_APP_SAL_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t ProcExtendedKeyUsage(BSL_CONF *cnf, bool critical, const char *cnfValue, ProcExtCallBack procExt,
void *ctx)
{
(void)cnf;
HITLS_X509_ExtExKeyUsage exku = {critical, NULL};
char *valueList[X509_EXT_EXKU_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_EXKU_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split value of extendedKeyUsage failed: %s.\n", cnfValue);
return ret;
}
exku.oidList = BSL_LIST_New(sizeof(BSL_Buffer));
if (exku.oidList == NULL) {
BSL_SAL_Free(valueList[0]);
AppPrintError("New list of extendedKeyUsage failed.\n");
return HITLS_APP_SAL_FAIL;
}
int32_t cid;
BslOidString *oidStr = NULL;
for (uint32_t i = 0; i < valueCnt; i++) {
cid = BSL_CID_UNKNOWN;
for (uint32_t j = 0; j < X509_EXT_EXKU_VALUE_MAX_CNT; j++) {
if (strcmp(g_exKuMap[j].name, valueList[i]) == 0) {
cid = g_exKuMap[j].keyUsage;
break;
}
}
oidStr = BSL_OBJ_GetOID(cid);
if (oidStr == NULL) {
AppPrintError("Unsupported extendedKeyUsage: %s.\n", valueList[i]);
ret = HITLS_APP_CONF_FAIL;
goto EXIT;
}
if (BSL_LIST_Search(exku.oidList, oidStr, (BSL_LIST_PFUNC_CMP)CmpExKeyUsageByOid, NULL) != NULL) {
continue;
}
ret = AddExtendKeyUsage(oidStr, exku.oidList);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Add extendedKeyUsage failed.\n");
goto EXIT;
}
}
ret = procExt(BSL_CID_CE_EXTKEYUSAGE, &exku, ctx);
EXIT:
BSL_SAL_Free(valueList[0]);
BSL_LIST_FREE(exku.oidList, NULL);
return ret;
}
static int32_t ProcSubjectKeyIdentifier(BSL_CONF *cnf, bool critical, const char *cnfValue, ProcExtCallBack procExt,
void *ctx)
{
(void)cnf;
HITLS_X509_ExtSki ski = {critical, {0}};
char *valueList[X509_EXT_SKI_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_SKI_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split value of subjectKeyIdentifier failed: %s.\n", cnfValue);
return ret;
}
if (strcmp(valueList[0], "hash") != 0) {
BSL_SAL_Free(valueList[0]);
AppPrintError("Illegal value of subjectKeyIdentifier: %s, only \"hash\" current is supported.\n", cnfValue);
return HITLS_APP_CONF_FAIL;
}
BSL_SAL_Free(valueList[0]);
return procExt(BSL_CID_CE_SUBJECTKEYIDENTIFIER, &ski, ctx);
}
static int32_t ParseAuthKeyIdentifier(char **value, uint32_t cnt, uint32_t *flag)
{
if (strcmp(value[0], "keyid") != 0) {
AppPrintError("Illegal type of authorityKeyIdentifier keyid: %s.\n", value[0]);
return HITLS_APP_CONF_FAIL;
}
if (cnt == 1) {
*flag |= HITLS_CFG_X509_EXT_AKI_KID;
return HITLS_APP_SUCCESS;
}
if (strcmp(value[1], "always") != 0) {
AppPrintError("Illegal value of authorityKeyIdentifier keyid: %s.\n", value[1]);
return HITLS_APP_CONF_FAIL;
}
*flag |= HITLS_CFG_X509_EXT_AKI_KID_ALWAYS;
return HITLS_APP_SUCCESS;
}
static int32_t ProcAuthKeyIdentifier(BSL_CONF *cnf, bool critical, const char *cnfValue, ProcExtCallBack procExt,
void *ctx)
{
(void)cnf;
HITLS_CFG_ExtAki aki = {{critical, {0}, NULL, {0}}, 0};
char *valueList[X509_EXT_AKI_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_AKI_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split value of authorityKeyIdentifier failed: %s.\n", cnfValue);
return ret;
}
for (uint32_t i = 0; i < valueCnt; i++) {
char *subList[X509_EXT_AKI_SUB_VALUE_MAX_CNT] = {0};
uint32_t subCnt = 0;
ret = HITLS_APP_SplitString(valueList[i], ':', false, subList, X509_EXT_AKI_SUB_VALUE_MAX_CNT, &subCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split sub-value of authorityKeyIdentifier failed: %s.\n", valueList[i]);
BSL_SAL_Free(valueList[0]);
return ret;
}
ret = ParseAuthKeyIdentifier(subList, subCnt, &aki.flag);
BSL_SAL_Free(subList[0]);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_Free(valueList[0]);
return ret;
}
}
BSL_SAL_Free(valueList[0]);
return procExt(BSL_CID_CE_AUTHORITYKEYIDENTIFIER, &aki, ctx);
}
typedef struct {
char *name;
HITLS_X509_GeneralNameType genNameType;
} X509GeneralNameMap;
static X509GeneralNameMap g_exSanMap[] = {
{HITLS_CFG_X509_EXT_SAN_EMAIL, HITLS_X509_GN_EMAIL},
{HITLS_CFG_X509_EXT_SAN_DNS, HITLS_X509_GN_DNS},
{HITLS_CFG_X509_EXT_SAN_DIR_NAME, HITLS_X509_GN_DNNAME},
{HITLS_CFG_X509_EXT_SAN_URI, HITLS_X509_GN_URI},
{HITLS_CFG_X509_EXT_SAN_IP, HITLS_X509_GN_IP},
};
static int32_t ParseGeneralSanValue(char *value, HITLS_X509_GeneralName *generalName)
{
generalName->value.data = (uint8_t *)strdup(value);
if (generalName->value.data == NULL) {
AppPrintError("Failed to copy value: %s.\n", value);
return HITLS_APP_MEM_ALLOC_FAIL;
}
generalName->value.dataLen = strlen(value);
return HITLS_APP_SUCCESS;
}
static int32_t ParseDirNamenValue(BSL_CONF *conf, char *value, HITLS_X509_GeneralName *generalName)
{
int32_t ret;
BslList *dirName = BSL_CONF_GetSection(conf, value);
if (dirName == NULL) {
AppPrintError("Failed to get section: %s.\n", value);
return HITLS_APP_ERR_CONF_GET_SECTION;
}
BslList *nameList = BSL_LIST_New(sizeof(HITLS_X509_NameNode *));
if (nameList == NULL) {
AppPrintError("New list of directory name list failed.\n");
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
BSL_CONF_KeyValue *node = BSL_LIST_GET_FIRST(dirName);
while (node != NULL) {
HITLS_X509_DN *dnName = BSL_SAL_Calloc(1, sizeof(HITLS_X509_DN));
if (dnName == NULL) {
AppPrintError("Failed to malloc X509 DN when parsing directory name.\n");
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
const BslAsn1DnInfo *info = BSL_OBJ_GetDnInfoFromShortName(node->key);
if (info == NULL) {
ret = HITLS_APP_INVALID_DN_TYPE;
BSL_SAL_FREE(dnName);
AppPrintError("Invalid short name of distinguish name.\n");
goto EXIT;
}
dnName->data = (uint8_t *)node->value;
dnName->dataLen = (uint32_t)strlen(node->value);
dnName->cid = info->cid;
ret = HITLS_X509_AddDnName(nameList, dnName, 1);
BSL_SAL_FREE(dnName);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("Failed to HITLS_X509_AddDnName.\n");
goto EXIT;
}
node = BSL_LIST_GET_NEXT(dirName);
}
generalName->value.data = (uint8_t *)nameList;
generalName->value.dataLen = (uint32_t)sizeof(BslList *);
return HITLS_APP_SUCCESS;
EXIT:
BSL_LIST_FREE(nameList, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode);
return ret;
}
static int32_t ParseIPValue(char *value, HITLS_X509_GeneralName *generalName)
{
struct sockaddr_in sockIpv4 = {};
struct sockaddr_in6 sockIpv6 = {};
char *ipv4ValueList[IPV4_VALUE_MAX_CNT] = {0};
uint32_t ipSize = 0;
if (inet_pton(AF_INET, value, &(sockIpv4.sin_addr)) == 1) {
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(value, '.', false, ipv4ValueList, IPV4_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (valueCnt != IPV4_VALUE_MAX_CNT) {
AppPrintError("Failed to split IP string, IP: %s.\n", value);
BSL_SAL_FREE(ipv4ValueList[0]);
return HITLS_APP_INVALID_IP;
}
// Normalize IPv4 octets by removing leading zeros (cross-platform fix)
// inet_pton() behavior differs on macOS vs Linux for leading zeros
for (uint32_t i = 0; i < IPV4_VALUE_MAX_CNT; i++) {
// Skip leading zeros, but keep "0" as "0"
char *octet = ipv4ValueList[i];
while (*octet == '0' && *(octet + 1) != '\0') {
octet++;
}
ipv4ValueList[i] = octet;
}
ipSize = IPV4_VALUE_MAX_CNT;
} else if (inet_pton(AF_INET6, value, &(sockIpv6.sin6_addr)) == 1) {
ipSize = IPV6_VALUE_MAX_CNT;
} else {
AppPrintError("Invalid IP format for directory name, IP: %s.\n", value);
return HITLS_APP_INVALID_IP;
}
generalName->value.data = BSL_SAL_Calloc(ipSize, sizeof(uint8_t));
if (generalName->value.data == NULL) {
AppPrintError("Invalid IP format for directory name, IP: %s.\n", value);
BSL_SAL_FREE(ipv4ValueList[0]);
return HITLS_APP_MEM_ALLOC_FAIL;
}
for (uint32_t i = 0; i < ipSize; i++) {
if (ipSize == IPV4_VALUE_MAX_CNT) {
generalName->value.data[i] = (uint8_t)BSL_SAL_Atoi(ipv4ValueList[i]);
} else {
generalName->value.data[i] = sockIpv6.sin6_addr.s6_addr[i];
}
}
generalName->value.dataLen = ipSize;
BSL_SAL_FREE(ipv4ValueList[0]);
return HITLS_APP_SUCCESS;
}
static int32_t ParseGeneralNameValue(BSL_CONF *conf, HITLS_X509_GeneralNameType type, char *value,
HITLS_X509_GeneralName *generalName)
{
int32_t ret;
generalName->type = type;
switch (type) {
case HITLS_X509_GN_EMAIL:
case HITLS_X509_GN_DNS:
case HITLS_X509_GN_URI:
ret = ParseGeneralSanValue(value, generalName);
break;
case HITLS_X509_GN_DNNAME:
ret = ParseDirNamenValue(conf, value, generalName);
break;
case HITLS_X509_GN_IP:
ret = ParseIPValue(value, generalName);
break;
default:
generalName->type = 0;
AppPrintError("Unsupported the type of general name, type: %u.\n", generalName->type);
return HITLS_APP_INVALID_GENERAL_NAME_TYPE;
}
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return ret;
}
static int32_t ParseGeneralName(BSL_CONF *conf, char *genNameStr, HITLS_X509_GeneralName *generalName)
{
char *key = genNameStr;
char *value = strstr(genNameStr, ":");
if (value == NULL) {
return HITLS_APP_INVALID_GENERAL_NAME_TYPE;
}
key[value - key] = '\0';
for (int i = strlen(key) - 1; i >= 0; i--) {
if (key[i] == ' ') {
key[i] = '\0';
}
}
value++;
while (*value == ' ') {
value++;
}
if (strlen(value) == 0) {
AppPrintError("The value of general name is not set, key: %s.\n", key);
return HITLS_APP_INVALID_GENERAL_NAME;
}
HITLS_X509_GeneralNameType type = HITLS_X509_GN_MAX;
for (uint32_t j = 0; j < sizeof(g_exSanMap) / sizeof(g_exSanMap[0]); j++) {
if (strcmp(g_exSanMap[j].name, key) == 0) {
type = g_exSanMap[j].genNameType;
break;
}
}
return ParseGeneralNameValue(conf, type, value, generalName);
}
static int32_t ProcExtSubjectAltName(BSL_CONF *conf, bool critical, const char *cnfValue, ProcExtCallBack procExt,
void *ctx)
{
HITLS_X509_ExtSan san = {critical, NULL};
char *valueList[X509_EXT_SAN_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_SAN_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
san.names = BSL_LIST_New(sizeof(HITLS_X509_GeneralName *));
if (san.names == NULL) {
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
// find type
for (uint32_t i = 0; i < valueCnt; i++) {
HITLS_X509_GeneralName *generalName = BSL_SAL_Calloc(1, sizeof(HITLS_X509_GeneralName));
if (generalName == NULL) {
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
ret = ParseGeneralName(conf, valueList[i], generalName);
if (ret != HITLS_APP_SUCCESS) {
HITLS_X509_FreeGeneralName(generalName);
goto EXIT;
}
ret = BSL_LIST_AddElement(san.names, generalName, BSL_LIST_POS_END);
if (ret != HITLS_APP_SUCCESS) {
HITLS_X509_FreeGeneralName(generalName);
goto EXIT;
}
}
ret = procExt(BSL_CID_CE_SUBJECTALTNAME, &san, ctx);
if (ret != HITLS_APP_SUCCESS) {
goto EXIT;
}
EXIT:
BSL_SAL_FREE(valueList[0]);
BSL_LIST_FREE(san.names, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeGeneralName);
return ret;
}
static X509ExtInfo g_exts[] = {
{HITLS_CFG_X509_EXT_AKI, (ProcExtCnfFunc)ProcAuthKeyIdentifier},
{HITLS_CFG_X509_EXT_SKI, (ProcExtCnfFunc)ProcSubjectKeyIdentifier},
{HITLS_CFG_X509_EXT_BCONS, (ProcExtCnfFunc)ProcBasicConstraints},
{HITLS_CFG_X509_EXT_KU, (ProcExtCnfFunc)ProcKeyUsage},
{HITLS_CFG_X509_EXT_EXKU, (ProcExtCnfFunc)ProcExtendedKeyUsage},
{HITLS_CFG_X509_EXT_SAN, (ProcExtCnfFunc)ProcExtSubjectAltName},
};
static int32_t AppConfProcExtEntry(BSL_CONF *cnf, BSL_CONF_KeyValue *cnfValue, ProcExtCallBack extCb, void *ctx)
{
if (cnfValue->key == NULL || cnfValue->value == NULL) {
return HITLS_APP_CONF_FAIL;
}
char *value = cnfValue->value;
bool critical = ExtGetCritical(&value);
for (uint32_t i = 0; i < sizeof(g_exts) / sizeof(g_exts[0]); i++) {
if (strcmp(cnfValue->key, g_exts[i].name) == 0) {
return g_exts[i].func(cnf, critical, value, extCb, ctx);
}
}
AppPrintError("Unsupported extension: %s.\n", cnfValue->key);
return HITLS_APP_CONF_FAIL;
}
int32_t HITLS_APP_CONF_ProcExt(BSL_CONF *cnf, const char *section, ProcExtCallBack extCb, void *ctx)
{
if (cnf == NULL || cnf->data == NULL || section == NULL || extCb == NULL) {
AppPrintError("Invalid input parameter.\n");
return HITLS_APP_CONF_FAIL;
}
int32_t ret = HITLS_APP_SUCCESS;
BslList *list = BSL_CONF_GetSection(cnf, section);
if (list == NULL) {
AppPrintError("Failed to get extension section: %s.\n", section);
return HITLS_APP_CONF_FAIL;
}
if (BSL_LIST_EMPTY(list)) {
return HITLS_APP_NO_EXT; // There is no configuration in the section.
}
BSL_CONF_KeyValue *cnfNode = BSL_LIST_GET_FIRST(list);
while (cnfNode != NULL) {
ret = AppConfProcExtEntry(cnf, cnfNode, extCb, ctx);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to process each x509 extension conf.\n");
return ret;
}
cnfNode = BSL_LIST_GET_NEXT(list);
}
return ret;
}
int32_t HiTLS_AddSubjDnNameToCsr(void *csr, BslList *nameList)
{
if (csr == NULL) {
AppPrintError("csr is null when add subject name to csr.\n");
return HITLS_APP_INVALID_ARG;
}
uint32_t count = BSL_LIST_COUNT(nameList);
HITLS_X509_DN *names = BSL_SAL_Calloc(count, sizeof(HITLS_X509_DN));
if (names == NULL) {
AppPrintError("Failed to malloc names when add subject name to csr.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
size_t index = 0;
HITLS_X509_DN *node = BSL_LIST_GET_FIRST(nameList);
while (node != NULL) {
names[index++] = *node;
node = BSL_LIST_GET_NEXT(nameList);
}
int32_t ret = HITLS_X509_CsrCtrl(csr, HITLS_X509_ADD_SUBJECT_NAME, names, count);
BSL_SAL_FREE(names);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("Failed to add subject name to csr.\n");
}
return ret;
}
static int32_t SetDnTypeAndValue(HITLS_X509_DN *name, const char *nameTypeStr, const char *nameValueStr)
{
const BslAsn1DnInfo *asn1DnInfo = BSL_OBJ_GetDnInfoFromShortName(nameTypeStr);
if (asn1DnInfo == NULL) {
AppPrintError("warning: Skip unknow distinguish name, name type: %s.\n", nameTypeStr);
return HITLS_APP_SUCCESS;
}
if (strlen(nameValueStr) == 0) {
AppPrintError("warning: No value provided for name type: %s.\n", nameTypeStr);
return HITLS_APP_SUCCESS;
}
name->cid = asn1DnInfo->cid;
name->dataLen = strlen(nameValueStr);
name->data = BSL_SAL_Dump(nameValueStr, strlen(nameValueStr) + 1);
if (name->data == NULL) {
AppPrintError("Failed to copy name value when process distinguish name: %s.\n", nameValueStr);
return HITLS_APP_MEM_ALLOC_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t GetDnTypeAndValue(const char **nameStr, HITLS_X509_DN *name, bool *isMultiVal)
{
char *nameTypeStr = NULL;
char *nameValueStr = NULL;
const char *p = *nameStr;
if (*p == '\0') {
return HITLS_APP_SUCCESS;
}
char *tmp = BSL_SAL_Dump(p, strlen(p) + 1);
if (tmp == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
nameTypeStr = tmp;
while (*p != '\0' && *p != '=') {
*tmp++ = *p++;
}
*tmp++ = '\0';
if (*p == '\0') {
AppPrintError("The type(%s) must be have value.\n", nameTypeStr);
BSL_SAL_FREE(nameTypeStr);
return HITLS_APP_INVALID_DN_VALUE;
}
p++; // skip '='
nameValueStr = tmp;
while (*p != '\0' && *p != '/') {
if (*p == '+') {
*isMultiVal = true;
break;
}
if (*p == '\\' && *++p == '\0') {
BSL_SAL_FREE(nameTypeStr);
AppPrintError("Error charactor.\n");
return HITLS_APP_INVALID_DN_VALUE;
}
*tmp++ = *p++;
}
if (*p == '/' || *p == '+') {
*tmp++ = '\0';
}
int32_t ret = SetDnTypeAndValue(name, nameTypeStr, nameValueStr);
BSL_SAL_FREE(nameTypeStr);
*nameStr = p;
return ret;
}
static void FreeX509Dn(HITLS_X509_DN *name)
{
if (name == NULL) {
return;
}
BSL_SAL_FREE(name->data);
BSL_SAL_FREE(name);
}
/* distinguish name format is /type0=value0/type1=value1/type2=... */
int32_t HITLS_APP_CFG_ProcDnName(const char *nameStr, AddDnNameCb addCb, void *ctx)
{
if (nameStr == NULL || addCb == NULL || strlen(nameStr) <= 1 || nameStr[0] != '/') {
return HITLS_APP_INVALID_ARG;
}
int32_t ret = HITLS_APP_SUCCESS;
BslList *dnNameList = NULL;
const char *p = nameStr;
bool isMultiVal = false;
while (*p != '\0') {
p++;
if (!isMultiVal) {
BSL_LIST_FREE(dnNameList, (BSL_LIST_PFUNC_FREE)FreeX509Dn);
dnNameList = BSL_LIST_New(sizeof(HITLS_X509_DN *));
if (dnNameList == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
}
HITLS_X509_DN *name = BSL_SAL_Calloc(1, sizeof(HITLS_X509_DN));
if (name == NULL) {
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
ret = GetDnTypeAndValue(&p, name, &isMultiVal);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(name);
goto EXIT;
}
if (name->data == NULL) {
BSL_SAL_FREE(name);
continue;
}
// add to list
ret = BSL_LIST_AddElement(dnNameList, name, BSL_LIST_POS_END);
if (ret != BSL_SUCCESS) {
BSL_SAL_FREE(name->data);
BSL_SAL_FREE(name);
goto EXIT;
}
if (*p == '/' || *p == '\0') {
// add to csr or cert
ret = addCb(ctx, dnNameList);
BSL_LIST_FREE(dnNameList, (BSL_LIST_PFUNC_FREE)FreeX509Dn);
if (ret != HITLS_APP_SUCCESS) {
goto EXIT;
}
isMultiVal = false;
}
}
if (ret == HITLS_APP_SUCCESS && dnNameList != NULL && BSL_LIST_COUNT(dnNameList) != 0) {
ret = addCb(ctx, dnNameList);
}
EXIT:
BSL_LIST_FREE(dnNameList, (BSL_LIST_PFUNC_FREE)FreeX509Dn);
return ret;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_conf.c | C | unknown | 30,334 |
/*
* 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 "app_crl.h"
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h>
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_types.h"
#include "hitls_pki_errno.h"
#include "crypt_eal_pkey.h"
#include "crypt_eal_rand.h"
#include "app_opt.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_conf.h"
#include "app_utils.h"
#define MAX_CRLFILE_SIZE (256 * 1024)
#define DEFAULT_CERT_SIZE 1024U
typedef enum OptionChoice {
HITLS_APP_OPT_CRL_ERR = -1,
HITLS_APP_OPT_CRL_EOF = 0,
// The first opt of each option is help and is equal to 1. The following opt can be customized.
HITLS_APP_OPT_CRL_HELP = 1,
HITLS_APP_OPT_CRL_IN,
HITLS_APP_OPT_CRL_NOOUT,
HITLS_APP_OPT_CRL_OUT,
HITLS_APP_OPT_CRL_NEXTUPDATE,
HITLS_APP_OPT_CRL_CAFILE,
HITLS_APP_OPT_CRL_INFORM,
HITLS_APP_OPT_CRL_OUTFORM,
} HITLSOptType;
const HITLS_CmdOption g_crlOpts[] = {
{"help", HITLS_APP_OPT_CRL_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"in", HITLS_APP_OPT_CRL_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file"},
{"noout", HITLS_APP_OPT_CRL_NOOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "No CRL output "},
{"out", HITLS_APP_OPT_CRL_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"nextupdate", HITLS_APP_OPT_CRL_NEXTUPDATE, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print CRL nextupdate"},
{"CAfile", HITLS_APP_OPT_CRL_CAFILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Verify CRL using CAFile"},
{"inform", HITLS_APP_OPT_CRL_INFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Input crl file format"},
{"outform", HITLS_APP_OPT_CRL_OUTFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Output crl file format"},
{NULL, 0, 0, NULL}
};
typedef struct {
BSL_ParseFormat inform;
BSL_ParseFormat outform;
char *infile;
char *cafile;
char *outfile;
bool noout;
bool nextupdate;
BSL_UIO *uio;
} CrlInfo;
static int32_t DecodeCertFile(uint8_t *infileBuf, uint64_t infileBufLen, HITLS_X509_Cert **tmp)
{
// The input parameter inBufLen is uint64_t, and PEM_decode requires bufLen of uint32_t. Check whether the
// conversion precision is lost.
uint32_t bufLen = (uint32_t)infileBufLen;
if ((uint64_t)bufLen != infileBufLen) {
return HITLS_APP_DECODE_FAIL;
}
BSL_Buffer encode = {infileBuf, bufLen};
return HITLS_X509_CertParseBuff(BSL_FORMAT_UNKNOWN, &encode, tmp);
}
static int32_t VerifyCrlFile(const char *caFile, const HITLS_X509_Crl *crl)
{
BSL_UIO *readUio = HITLS_APP_UioOpen(caFile, 'r', 0);
if (readUio == NULL) {
AppPrintError("Failed to open the file <%s>, No such file or directory\n", caFile);
return HITLS_APP_UIO_FAIL;
}
uint8_t *caFileBuf = NULL;
uint64_t caFileBufLen = 0;
int32_t ret = HITLS_APP_OptReadUio(readUio, &caFileBuf, &caFileBufLen, MAX_CRLFILE_SIZE);
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
BSL_UIO_Free(readUio);
if (ret != HITLS_APP_SUCCESS || caFileBuf == NULL || caFileBufLen == 0) {
BSL_SAL_FREE(caFileBuf);
AppPrintError("Failed to read CAfile from <%s>\n", caFile);
return HITLS_APP_UIO_FAIL;
}
HITLS_X509_Cert *cert = NULL;
ret = DecodeCertFile(caFileBuf, caFileBufLen, &cert); // Decode the CAfile content.
BSL_SAL_FREE(caFileBuf);
if (ret != HITLS_APP_SUCCESS) {
HITLS_X509_CertFree(cert);
AppPrintError("Failed to decode the CAfile <%s>\n", caFile);
return HITLS_APP_DECODE_FAIL;
}
CRYPT_EAL_PkeyCtx *pubKey = NULL;
// Obtaining the Public Key of the CA Certificate
ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_PUBKEY, &pubKey, sizeof(CRYPT_EAL_PkeyCtx *));
HITLS_X509_CertFree(cert);
if (pubKey == NULL) {
AppPrintError("Failed to getting CRL issuer certificate\n");
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CrlVerify(pubKey, crl);
CRYPT_EAL_PkeyFreeCtx((CRYPT_EAL_PkeyCtx *)pubKey);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("The verification result: failed\n");
return HITLS_APP_CERT_VERIFY_FAIL;
}
AppPrintError("The verification result: OK\n");
return HITLS_APP_SUCCESS;
}
static int32_t GetCrlInfoByStd(uint8_t **infileBuf, uint64_t *infileBufLen)
{
(void)AppPrintError("Please enter the key content\n");
size_t crlDataCapacity = DEFAULT_CERT_SIZE;
void *crlData = BSL_SAL_Calloc(crlDataCapacity, sizeof(uint8_t));
if (crlData == NULL) { return HITLS_APP_MEM_ALLOC_FAIL; }
size_t crlDataSize = 0;
bool isMatchCrlData = false;
while (true) {
char *buf = NULL;
size_t bufLen = 0;
ssize_t readLen = getline(&buf, &bufLen, stdin);
if (readLen <= 0) {
BSL_SAL_FREE(buf);
(void)AppPrintError("Failed to obtain the standard input.\n");
break;
}
if ((crlDataSize + readLen) > MAX_CRLFILE_SIZE) {
BSL_SAL_FREE(buf);
BSL_SAL_FREE(crlData);
AppPrintError("The stdin supports a maximum of %zu bytes.\n", MAX_CRLFILE_SIZE);
return HITLS_APP_STDIN_FAIL;
}
if ((crlDataSize + readLen) > crlDataCapacity) {
// If the space is insufficient, expand the capacity by twice.
size_t newCrlDataCapacity = crlDataCapacity << 1;
/* If the space is insufficient for two times of capacity expansion,
expand the capacity based on the actual length. */
if ((crlDataSize + readLen) > newCrlDataCapacity) {
newCrlDataCapacity = crlDataSize + readLen;
}
crlData = ExpandingMem(crlData, newCrlDataCapacity, crlDataCapacity);
crlDataCapacity = newCrlDataCapacity;
}
if (memcpy_s(crlData + crlDataSize, crlDataCapacity - crlDataSize, buf, readLen) != 0) {
BSL_SAL_FREE(buf);
BSL_SAL_FREE(crlData);
return HITLS_APP_SECUREC_FAIL;
}
crlDataSize += readLen;
if (strcmp(buf, "-----BEGIN X509 CRL-----\n") == 0) {
isMatchCrlData = true;
}
if (isMatchCrlData && (strcmp(buf, "-----END X509 CRL-----\n") == 0)) {
BSL_SAL_FREE(buf);
break;
}
BSL_SAL_FREE(buf);
}
*infileBuf = crlData;
*infileBufLen = crlDataSize;
return (crlDataSize > 0) ? HITLS_APP_SUCCESS : HITLS_APP_STDIN_FAIL;
}
static int32_t GetCrlInfoByFile(char *infile, uint8_t **infileBuf, uint64_t *infileBufLen)
{
int32_t readRet = HITLS_APP_SUCCESS;
BSL_UIO *uio = HITLS_APP_UioOpen(infile, 'r', 0);
if (uio == NULL) {
AppPrintError("Failed to open the CRL from <%s>, No such file or directory\n", infile);
return HITLS_APP_UIO_FAIL;
}
readRet = HITLS_APP_OptReadUio(uio, infileBuf, infileBufLen, MAX_CRLFILE_SIZE);
BSL_UIO_SetIsUnderlyingClosedByUio(uio, true);
BSL_UIO_Free(uio);
if (readRet != HITLS_APP_SUCCESS) {
AppPrintError("Failed to read the CRL from <%s>\n", infile);
return readRet;
}
return HITLS_APP_SUCCESS;
}
static int32_t GetCrlInfo(char *infile, uint8_t **infileBuf, uint64_t *infileBufLen)
{
int32_t getRet = HITLS_APP_SUCCESS;
if (infile == NULL) {
getRet = GetCrlInfoByStd(infileBuf, infileBufLen);
} else {
getRet = GetCrlInfoByFile(infile, infileBuf, infileBufLen);
}
return getRet;
}
static int32_t GetAndDecCRL(CrlInfo *outInfo, uint8_t **infileBuf, uint64_t *infileBufLen, HITLS_X509_Crl **crl)
{
int32_t ret = GetCrlInfo(outInfo->infile, infileBuf, infileBufLen); // Obtaining the CRL File Content
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to obtain the content of the CRL file.\n");
return ret;
}
BSL_Buffer buff = {*infileBuf, *infileBufLen};
ret = HITLS_X509_CrlParseBuff(outInfo->inform, &buff, crl);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("Failed to decode the CRL file.\n");
return HITLS_APP_DECODE_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t OutCrlFileInfo(BSL_UIO *uio, HITLS_X509_Crl *crl, uint32_t format)
{
BSL_Buffer encode = {0};
int32_t ret = HITLS_X509_CrlGenBuff(format, crl, &encode);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("Failed to convert the CRL.\n");
return HITLS_APP_ENCODE_FAIL;
}
ret = HITLS_APP_OptWriteUio(uio, encode.data, encode.dataLen, HITLS_APP_FORMAT_PEM);
BSL_SAL_FREE(encode.data);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("Failed to print the CRL content\n");
}
return ret;
}
static int32_t PrintNextUpdate(BSL_UIO *uio, HITLS_X509_Crl *crl)
{
BSL_TIME time = {0};
int32_t ret = HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_AFTER_TIME, &time, sizeof(BSL_TIME));
if (ret != HITLS_PKI_SUCCESS && ret != HITLS_X509_ERR_CRL_NEXTUPDATE_UNEXIST) {
(void)AppPrintError("Failed to get character string\n");
return HITLS_APP_X509_FAIL;
}
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_NEXTUPDATE, &time, sizeof(BSL_TIME), uio);
if (ret != HITLS_PKI_SUCCESS) {
(void)AppPrintError("Failed to get print string\n");
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t OptParse(CrlInfo *outInfo)
{
HITLSOptType optType;
int ret = HITLS_APP_SUCCESS;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_CRL_EOF) {
switch (optType) {
case HITLS_APP_OPT_CRL_EOF:
case HITLS_APP_OPT_CRL_ERR:
ret = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("crl: Use -help for summary.\n");
return ret;
case HITLS_APP_OPT_CRL_HELP:
ret = HITLS_APP_HELP;
(void)HITLS_APP_OptHelpPrint(g_crlOpts);
return ret;
case HITLS_APP_OPT_CRL_OUT:
outInfo->outfile = HITLS_APP_OptGetValueStr();
if (outInfo->outfile == NULL || strlen(outInfo->outfile) >= PATH_MAX) {
AppPrintError("The length of outfile error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_CRL_NOOUT:
outInfo->noout = true;
break;
case HITLS_APP_OPT_CRL_IN:
outInfo->infile = HITLS_APP_OptGetValueStr();
if (outInfo->infile == NULL || strlen(outInfo->infile) >= PATH_MAX) {
AppPrintError("The length of input file error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_CRL_CAFILE:
outInfo->cafile = HITLS_APP_OptGetValueStr();
if (outInfo->cafile == NULL || strlen(outInfo->cafile) >= PATH_MAX) {
AppPrintError("The length of CA file error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_CRL_NEXTUPDATE:
outInfo->nextupdate = true;
break;
case HITLS_APP_OPT_CRL_INFORM:
if (HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_PEMDER,
&outInfo->inform) != HITLS_APP_SUCCESS) {
AppPrintError("The informat of crl file error.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_CRL_OUTFORM:
if (HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_PEMDER,
&outInfo->outform) != HITLS_APP_SUCCESS) {
AppPrintError("The format of crl file error.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
default:
return HITLS_APP_OPT_UNKOWN;
}
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_CrlMain(int argc, char *argv[])
{
CrlInfo crlInfo = {0, BSL_FORMAT_PEM, NULL, NULL, NULL, false, false, NULL};
HITLS_X509_Crl *crl = NULL;
uint8_t *infileBuf = NULL;
uint64_t infileBufLen = 0;
int32_t mainRet = HITLS_APP_OptBegin(argc, argv, g_crlOpts);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("error in opt begin.\n");
goto end;
}
mainRet = OptParse(&crlInfo);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
int unParseParamNum = HITLS_APP_GetRestOptNum();
if (unParseParamNum != 0) { // The input parameters are not completely parsed.
(void)AppPrintError("Extra arguments given.\n");
(void)AppPrintError("crl: Use -help for summary.\n");
mainRet = HITLS_APP_OPT_UNKOWN;
goto end;
}
mainRet = GetAndDecCRL(&crlInfo, &infileBuf, &infileBufLen, &crl);
if (mainRet != HITLS_APP_SUCCESS) {
HITLS_X509_CrlFree(crl);
goto end;
}
crlInfo.uio = HITLS_APP_UioOpen(crlInfo.outfile, 'w', 0);
if (crlInfo.uio == NULL) {
(void)AppPrintError("Failed to open the standard output.");
mainRet = HITLS_APP_UIO_FAIL;
goto end;
}
BSL_UIO_SetIsUnderlyingClosedByUio(crlInfo.uio, !(crlInfo.outfile == NULL));
if (crlInfo.nextupdate == true) {
mainRet = PrintNextUpdate(crlInfo.uio, crl);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
}
if (crlInfo.cafile != NULL) {
mainRet = VerifyCrlFile(crlInfo.cafile, crl);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
}
if (crlInfo.noout == false) {
mainRet = OutCrlFileInfo(crlInfo.uio, crl, crlInfo.outform);
}
end:
HITLS_X509_CrlFree(crl);
BSL_SAL_FREE(infileBuf);
BSL_UIO_Free(crlInfo.uio);
HITLS_APP_OptEnd();
return mainRet;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_crl.c | C | unknown | 14,525 |
/*
* 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 "app_dgst.h"
#include <limits.h>
#include "string.h"
#include "securec.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_eal_md.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_pkey.h"
#include "crypt_eal_codecs.h"
#include "bsl_errno.h"
#include "app_opt.h"
#include "app_function.h"
#include "app_list.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_utils.h"
#include "app_sm.h"
#include "app_keymgmt.h"
#include "app_provider.h"
#define MAX_BUFSIZE (1024 * 8) // Indicates the length of a single digest during digest calculation.
#define IS_SUPPORT_GET_EOF 1
#define MAX_CERT_KEY_SIZE (256 * 1024)
typedef enum OptionChoice {
HITLS_APP_OPT_DGST_ERR = -1,
HITLS_APP_OPT_DGST_EOF = 0,
HITLS_APP_OPT_DGST_FILE = HITLS_APP_OPT_DGST_EOF,
HITLS_APP_OPT_DGST_HELP =
1, // The value of the help type of each opt option is 1. The following can be customized.
HITLS_APP_OPT_DGST_ALG,
HITLS_APP_OPT_DGST_OUT,
HITLS_APP_OPT_DGST_SIGN,
HITLS_APP_OPT_DGST_VERIFY,
HITLS_APP_OPT_DGST_SIGNATURE,
HITLS_APP_OPT_DGST_USERID,
HITLS_APP_PROV_ENUM,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS_ENUM,
#endif
} HITLSOptType;
const HITLS_CmdOption g_dgstOpts[] = {
{"help", HITLS_APP_OPT_DGST_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"md", HITLS_APP_OPT_DGST_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Digest algorithm"},
{"out", HITLS_APP_OPT_DGST_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output the summary result to a file"},
{"sign", HITLS_APP_OPT_DGST_SIGN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Private key for signature"},
{"verify", HITLS_APP_OPT_DGST_VERIFY, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Public key for signature verification"},
{"signature", HITLS_APP_OPT_DGST_SIGNATURE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Signature to be verified"},
{"userid", HITLS_APP_OPT_DGST_USERID, HITLS_APP_OPT_VALUETYPE_STRING, "User ID for SM2"},
HITLS_APP_PROV_OPTIONS,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS,
#endif
{"file...", HITLS_APP_OPT_DGST_FILE, HITLS_APP_OPT_VALUETYPE_PARAMTERS, "Files to be digested"},
{NULL, 0, 0, NULL}};
typedef struct {
char *algName;
int32_t algId;
uint32_t digestSize; // the length of default hash value of the algorithm
} AlgInfo;
typedef struct {
char *privateKeyFile; // private key file for signing
char *publicKeyFile; // public key file for verification
char *signatureFile; // signature file for verification
char *userid; // user ID for SM2
AppProvider *provider;
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param *smParam;
#endif
} SignInfo;
static AlgInfo g_dgstInfo = {"sha256", CRYPT_MD_SHA256, 0};
#ifdef HITLS_APP_SM_MODE
static SignInfo g_signInfo = {NULL, NULL, NULL, "1234567812345678", NULL, NULL};
#else
static SignInfo g_signInfo = {NULL, NULL, NULL, "1234567812345678", NULL};
#endif
static int32_t g_argc = 0;
static char **g_argv;
static int32_t OptParse(char **outfile);
static CRYPT_EAL_MdCTX *InitAlgDigest(CRYPT_MD_AlgId id);
static int32_t ReadFileToBuf(CRYPT_EAL_MdCTX *ctx, const char *filename);
static int32_t HashValToFinal(
uint8_t *hashBuf, uint32_t hashBufLen, uint8_t **buf, uint32_t *bufLen, const char *filename);
static int32_t MdFinalToBuf(CRYPT_EAL_MdCTX *ctx, uint8_t **buf, uint32_t *bufLen, const char *filename);
static int32_t BufOutToUio(const char *outfile, BSL_UIO *fileWriteUio, uint8_t *outBuf, uint32_t outBufLen);
static int32_t MultiFileSetCtx(CRYPT_EAL_MdCTX *ctx);
static int32_t StdSumAndOut(CRYPT_EAL_MdCTX *ctx, const char *outfile);
static int32_t FileSumOutFile(CRYPT_EAL_MdCTX *ctx, const char *outfile);
static int32_t FileSumOutStd(CRYPT_EAL_MdCTX *ctx);
static int32_t FileSumAndOut(CRYPT_EAL_MdCTX *ctx, const char *outfile);
static int32_t CalculateDgst(char *outfile)
{
int32_t ret = HITLS_APP_SUCCESS;
CRYPT_EAL_MdCTX *ctx = InitAlgDigest(g_dgstInfo.algId);
if (ctx == NULL) {
ret = HITLS_APP_CRYPTO_FAIL;
return ret;
}
#ifdef HITLS_APP_SM_MODE
if (g_signInfo.smParam->smTag == 1) {
g_signInfo.smParam->status = HITLS_APP_SM_STATUS_APPORVED;
}
#endif
if (g_dgstInfo.algId == CRYPT_MD_SHAKE128) {
g_dgstInfo.digestSize = HITLS_APP_SHAKE128_SIZE;
} else if (g_dgstInfo.algId == CRYPT_MD_SHAKE256) {
g_dgstInfo.digestSize = HITLS_APP_SHAKE256_SIZE;
} else {
g_dgstInfo.digestSize = CRYPT_EAL_MdGetDigestSize(g_dgstInfo.algId);
if (g_dgstInfo.digestSize == 0) {
ret = HITLS_APP_CRYPTO_FAIL;
(void)AppPrintError("dgst: Failed to obtain the default length of the algorithm(%s)\n", g_dgstInfo.algName);
CRYPT_EAL_MdFreeCtx(ctx);
return ret;
}
}
ret = (g_argc == 0) ? StdSumAndOut(ctx, outfile) : FileSumAndOut(ctx, outfile);
CRYPT_EAL_MdDeinit(ctx); // algorithm release
CRYPT_EAL_MdFreeCtx(ctx);
return ret;
}
static int32_t GetReadBuf(uint8_t **buf, uint64_t *bufLen, char *inFile, uint32_t maxSize)
{
if (buf == NULL || bufLen == NULL || *bufLen > UINT32_MAX) {
AppPrintError("dgst: Invalid parameters for GetReadBuf\n");
return HITLS_APP_INVALID_ARG;
}
BSL_UIO *readUio = HITLS_APP_UioOpen(inFile, 'r', 0);
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
if (readUio == NULL) {
if (inFile == NULL) {
AppPrintError("dgst: Failed to open stdin\n");
} else {
AppPrintError("dgst: Failed to open the file <%s>, No such file or directory\n", inFile);
}
return HITLS_APP_UIO_FAIL;
}
int32_t ret = HITLS_APP_OptReadUio(readUio, buf, bufLen, maxSize);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("dgst: Failed to read the content from the file <%s>\n", inFile);
}
BSL_UIO_Free(readUio);
return ret;
}
#ifdef HITLS_APP_SM_MODE
static int32_t GetPkeyCtxFromUuid(SignInfo *signInfo, char *uuid, CRYPT_EAL_PkeyCtx **ctx)
{
HITLS_APP_KeyInfo keyInfo = {0};
signInfo->smParam->uuid = uuid;
int32_t ret = HITLS_APP_FindKey(signInfo->provider, signInfo->smParam, CRYPT_PKEY_SM2, &keyInfo);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to find key, errCode: 0x%0x.\n", ret);
return ret;
}
*ctx = keyInfo.pkeyCtx;
return HITLS_APP_SUCCESS;
}
#endif
static int32_t CalculateSign(char *outfile, uint8_t *msgBuf, uint32_t msgBufLen)
{
int32_t ret = HITLS_APP_SUCCESS;
uint8_t *prvBuf = NULL;
uint64_t bufLen = 0;
uint8_t *signBuf = NULL;
uint32_t signLen;
BSL_Buffer prv = {0};
CRYPT_EAL_PkeyCtx *ctx = NULL;
do {
#ifdef HITLS_APP_SM_MODE
if (g_signInfo.smParam->smTag == 1) {
ret = GetPkeyCtxFromUuid(&g_signInfo, g_signInfo.privateKeyFile, &ctx);
if (ret != HITLS_APP_SUCCESS) {
break;
}
} else {
#endif
ret = GetReadBuf(&prvBuf, &bufLen, g_signInfo.privateKeyFile, MAX_CERT_KEY_SIZE);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("dgst: Failed to read the private key file\n");
break;
}
prv.data = prvBuf;
prv.dataLen = bufLen;
ret = CRYPT_EAL_ProviderDecodeBuffKey(APP_GetCurrent_LibCtx(), g_signInfo.provider->providerAttr,
BSL_CID_UNKNOWN, "PEM", "PRIKEY_PKCS8_UNENCRYPT", &prv, NULL, &ctx);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("dgst: Failed to decode the private key, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
#ifdef HITLS_APP_SM_MODE
}
#endif
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, g_signInfo.userid, strlen(g_signInfo.userid));
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("dgst: Failed to set the SM2 user ID, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
#ifdef HITLS_APP_SM_MODE
if (g_signInfo.smParam->smTag == 1) {
g_signInfo.smParam->status = HITLS_APP_SM_STATUS_APPORVED;
}
#endif
signLen = CRYPT_EAL_PkeyGetSignLen(ctx);
if (signLen == 0) {
(void)AppPrintError("dgst: Failed to get the signature length.\n");
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
signBuf = BSL_SAL_Malloc(signLen);
if (signBuf == NULL) {
(void)AppPrintError("dgst: Failed to allocate memory for the signature.\n");
ret = HITLS_APP_MEM_ALLOC_FAIL;
break;
}
ret = CRYPT_EAL_PkeySign(ctx, g_dgstInfo.algId, msgBuf, msgBufLen, signBuf, &signLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("dgst: Failed to sign the message, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(outfile, 'w', 0); // overwrite the original content
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
if (fileWriteUio == NULL) {
(void)AppPrintError("dgst: Failed to open the outfile\n");
ret = HITLS_APP_UIO_FAIL;
break;
}
ret = HITLS_APP_OptWriteUio(fileWriteUio, signBuf, signLen, HITLS_APP_FORMAT_HEX);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("dgst:Failed to export data to the outfile path\n");
}
BSL_UIO_Free(fileWriteUio);
} while (0);
CRYPT_EAL_RandDeinitEx(APP_GetCurrent_LibCtx());
BSL_SAL_ClearFree(prvBuf, bufLen);
CRYPT_EAL_PkeyFreeCtx(ctx);
BSL_SAL_FREE(signBuf);
return ret;
}
static int32_t GetPubKeyCtx(CRYPT_EAL_PkeyCtx **ctx)
{
int32_t ret = HITLS_APP_SUCCESS;
uint8_t *pubBuf = NULL;
uint64_t bufLen = 0;
BSL_Buffer pub = {0};
CRYPT_EAL_PkeyCtx *pkeyCtx = NULL;
#ifdef HITLS_APP_SM_MODE
if (g_signInfo.smParam->smTag == 1) {
ret = GetPkeyCtxFromUuid(&g_signInfo, g_signInfo.publicKeyFile, &pkeyCtx);
if (ret == HITLS_APP_SUCCESS) {
*ctx = pkeyCtx;
return HITLS_APP_SUCCESS;
}
}
#endif
ret = GetReadBuf(&pubBuf, &bufLen, g_signInfo.publicKeyFile, MAX_CERT_KEY_SIZE);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("dgst: Failed to read the public key file\n");
return ret;
}
pub.data = pubBuf;
pub.dataLen = bufLen;
ret = CRYPT_EAL_ProviderDecodeBuffKey(APP_GetCurrent_LibCtx(), g_signInfo.provider->providerAttr,
BSL_CID_UNKNOWN, "PEM", "PUBKEY_SUBKEY", &pub, NULL, &pkeyCtx);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("dgst: Failed to decode the public key, errCode: 0x%0x.\n", ret);
BSL_SAL_ClearFree(pubBuf, bufLen);
return HITLS_APP_CRYPTO_FAIL;
}
BSL_SAL_ClearFree(pubBuf, bufLen);
*ctx = pkeyCtx;
(void)AppPrintError("dgst: Get pub key ctx success!\n");
return HITLS_APP_SUCCESS;
}
static int32_t VerifySign(uint8_t *msgBuf, uint32_t msgBufLen)
{
int32_t ret = HITLS_APP_SUCCESS;
uint8_t *signBuf = NULL;
uint64_t signLen = 0;
uint8_t *hexBuf = NULL;
uint32_t hexLen;
CRYPT_EAL_PkeyCtx *ctx = NULL;
do {
ret = GetPubKeyCtx(&ctx);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = GetReadBuf(&signBuf, &signLen, g_signInfo.signatureFile, UINT32_MAX);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("dgst: Failed to read the signature file\n");
break;
}
hexBuf = BSL_SAL_Malloc(signLen * 2 + 1);
hexLen = signLen * 2;
ret = HITLS_APP_StrToHex((const char *)signBuf, hexBuf, &hexLen);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("dgst: Failed to convert signature to hex, ret=%d\n", ret);
break;
}
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, g_signInfo.userid, strlen(g_signInfo.userid));
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("dgst: Failed to set the SM2 user ID, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
#ifdef HITLS_APP_SM_MODE
if (g_signInfo.smParam->smTag == 1) {
g_signInfo.smParam->status = HITLS_APP_SM_STATUS_APPORVED;
}
#endif
ret = CRYPT_EAL_PkeyVerify(ctx, g_dgstInfo.algId, msgBuf, msgBufLen, hexBuf, hexLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("dgst: Failed to verify the message, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
(void)AppPrintError("verify success\n");
} while (0);
BSL_SAL_FREE(signBuf);
BSL_SAL_FREE(hexBuf);
CRYPT_EAL_PkeyFreeCtx(ctx);
return ret;
}
static int32_t CheckSmParam(SignInfo *signInfo)
{
#ifdef HITLS_APP_SM_MODE
if (signInfo->smParam->smTag == 1 && signInfo->smParam->workPath == NULL) {
AppPrintError("dgst: The workpath is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
#else
(void) signInfo;
#endif
return HITLS_APP_SUCCESS;
}
int32_t HITLS_DgstMain(int argc, char *argv[])
{
AppProvider appProvider = {NULL, NULL, NULL};
g_signInfo.provider = &appProvider;
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param smParam = {NULL, 0, NULL, NULL, 0, HITLS_APP_SM_STATUS_OPEN};
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider, &smParam};
g_signInfo.smParam = &smParam;
#else
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider};
#endif
char *outfile = NULL;
char *msgFile = NULL;
uint8_t *msgBuf = NULL;
uint64_t msgBufLen = 0;
int32_t mainRet = HITLS_APP_SUCCESS;
mainRet = HITLS_APP_OptBegin(argc, argv, g_dgstOpts);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("dgst: error in opt begin.\n");
goto end;
}
mainRet = OptParse(&outfile);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
mainRet = CheckSmParam(&g_signInfo);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
mainRet = HITLS_APP_Init(&initParam);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("dgst: Failed to init the application, errCode: 0x%x.\n", mainRet);
goto end;
}
g_argc = HITLS_APP_GetRestOptNum();
g_argv = HITLS_APP_GetRestOpt();
if (g_argc !=0) {
msgFile = g_argv[0];
}
if (g_signInfo.privateKeyFile == NULL && g_signInfo.publicKeyFile == NULL) {
mainRet = CalculateDgst(outfile);
} else if (g_signInfo.privateKeyFile != NULL && g_signInfo.publicKeyFile == NULL) {
mainRet = GetReadBuf(&msgBuf, &msgBufLen, msgFile, UINT32_MAX);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
mainRet = CalculateSign(outfile, msgBuf, (uint32_t)msgBufLen);
} else if (g_signInfo.publicKeyFile != NULL && g_signInfo.signatureFile != NULL) {
mainRet = GetReadBuf(&msgBuf, &msgBufLen, msgFile, UINT32_MAX);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
mainRet = VerifySign(msgBuf, msgBufLen);
} else {
(void)AppPrintError("dgst: Please add the signature file using the [-signature] option.\n");
mainRet = HITLS_APP_INVALID_ARG;
}
end:
BSL_SAL_FREE(msgBuf);
HITLS_APP_Deinit(&initParam, mainRet);
HITLS_APP_OptEnd();
return mainRet;
}
static int32_t StdSumAndOut(CRYPT_EAL_MdCTX *ctx, const char *outfile)
{
int32_t stdRet = HITLS_APP_SUCCESS;
BSL_UIO *readUio = HITLS_APP_UioOpen(NULL, 'r', 1);
if (readUio == NULL) {
AppPrintError("dgst: Failed to open the stdin\n");
return HITLS_APP_UIO_FAIL;
}
uint32_t readLen = MAX_BUFSIZE;
uint8_t readBuf[MAX_BUFSIZE] = {0};
bool isEof = false;
while (BSL_UIO_Ctrl(readUio, BSL_UIO_FILE_GET_EOF, IS_SUPPORT_GET_EOF, &isEof) == BSL_SUCCESS && !isEof) {
if (BSL_UIO_Read(readUio, readBuf, MAX_BUFSIZE, &readLen) != BSL_SUCCESS) {
BSL_UIO_Free(readUio);
(void)AppPrintError("dgst: Failed to obtain the content from the STDIN\n");
return HITLS_APP_STDIN_FAIL;
}
if (readLen == 0) {
break;
}
stdRet = CRYPT_EAL_MdUpdate(ctx, readBuf, readLen);
if (stdRet != CRYPT_SUCCESS) {
BSL_UIO_Free(readUio);
(void)AppPrintError("dgst: Failed to continuously summarize the STDIN content\n");
return HITLS_APP_CRYPTO_FAIL;
}
}
BSL_UIO_Free(readUio);
uint8_t *outBuf = NULL;
uint32_t outBufLen = 0;
// reads the final hash value to the buffer
stdRet = MdFinalToBuf(ctx, &outBuf, &outBufLen, "stdin");
if (stdRet != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(outBuf);
return stdRet;
}
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(outfile, 'w', 1);
if (fileWriteUio == NULL) {
BSL_UIO_Free(fileWriteUio);
BSL_SAL_FREE(outBuf);
AppPrintError("dgst: Failed to open the <%s>\n", outfile);
return HITLS_APP_UIO_FAIL;
}
// outputs the hash value to the UIO
stdRet = BufOutToUio(outfile, fileWriteUio, (uint8_t *)outBuf, outBufLen);
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
BSL_SAL_FREE(outBuf);
return stdRet;
}
static int32_t ReadFileToBuf(CRYPT_EAL_MdCTX *ctx, const char *filename)
{
int32_t readRet = HITLS_APP_SUCCESS;
BSL_UIO *readUio = HITLS_APP_UioOpen(filename, 'r', 0);
if (readUio == NULL) {
(void)AppPrintError("dgst: Failed to open the file <%s>, No such file or directory\n", filename);
return HITLS_APP_UIO_FAIL;
}
uint64_t readFileLen = 0;
readRet = BSL_UIO_Ctrl(readUio, BSL_UIO_PENDING, sizeof(readFileLen), &readFileLen);
if (readRet != BSL_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
BSL_UIO_Free(readUio);
(void)AppPrintError("dgst: Failed to obtain the content length\n");
return HITLS_APP_UIO_FAIL;
}
while (readFileLen > 0) {
uint8_t readBuf[MAX_BUFSIZE] = {0};
uint32_t bufLen = (readFileLen > MAX_BUFSIZE) ? MAX_BUFSIZE : (uint32_t)readFileLen;
uint32_t readLen = 0;
readRet = BSL_UIO_Read(readUio, readBuf, bufLen, &readLen); // read content to memory
if (readRet != BSL_SUCCESS || bufLen != readLen) {
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
BSL_UIO_Free(readUio);
(void)AppPrintError("dgst: Failed to read the input content\n");
return HITLS_APP_UIO_FAIL;
}
readRet = CRYPT_EAL_MdUpdate(ctx, readBuf, bufLen); // continuously enter summary content
if (readRet != CRYPT_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
BSL_UIO_Free(readUio);
(void)AppPrintError("dgst: Failed to continuously summarize the file content\n");
return HITLS_APP_CRYPTO_FAIL;
}
readFileLen -= bufLen;
}
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
BSL_UIO_Free(readUio);
return HITLS_APP_SUCCESS;
}
static int32_t BufOutToUio(const char *outfile, BSL_UIO *fileWriteUio, uint8_t *outBuf, uint32_t outBufLen)
{
int32_t outRet = HITLS_APP_SUCCESS;
if (outfile == NULL) {
BSL_UIO *stdOutUio = HITLS_APP_UioOpen(NULL, 'w', 0);
if (stdOutUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
outRet = HITLS_APP_OptWriteUio(stdOutUio, outBuf, outBufLen, HITLS_APP_FORMAT_TEXT);
BSL_UIO_Free(stdOutUio);
if (outRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("dgst: Failed to output the content to the screen\n");
return HITLS_APP_UIO_FAIL;
}
} else {
outRet = HITLS_APP_OptWriteUio(fileWriteUio, outBuf, outBufLen, HITLS_APP_FORMAT_TEXT);
if (outRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("dgst: Failed to export data to the file path: <%s>\n", outfile);
return HITLS_APP_UIO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t HashValToFinal(
uint8_t *hashBuf, uint32_t hashBufLen, uint8_t **buf, uint32_t *bufLen, const char *filename)
{
int32_t outRet = HITLS_APP_SUCCESS;
uint32_t hexBufLen = hashBufLen * 2 + 1;
uint8_t *hexBuf = (uint8_t *)BSL_SAL_Calloc(hexBufLen, sizeof(uint8_t)); // save the hexadecimal hash value
if (hexBuf == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
outRet = HITLS_APP_OptToHex(hashBuf, hashBufLen, (char *)hexBuf, hexBufLen);
if (outRet != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(hexBuf);
return HITLS_APP_ENCODE_FAIL;
}
uint32_t outBufLen;
if (g_argc == 0) {
// standard input(stdin) = hashValue,
// 5 indicates " " + "()" + "=" + "\n"
outBufLen = strlen("stdin") + hexBufLen + 5;
} else {
// 5: " " + "()" + "=" + "\n", and concatenate the string alg_name(filename1)=hash.
outBufLen = strlen(g_dgstInfo.algName) + strlen(filename) + hexBufLen + 5;
}
char *outBuf = (char *)BSL_SAL_Calloc(outBufLen, sizeof(char)); // save the concatenated hash value
if (outBuf == NULL) {
(void)AppPrintError("dgst: Failed to open the format control content space\n");
BSL_SAL_FREE(hexBuf);
return HITLS_APP_MEM_ALLOC_FAIL;
}
if (g_argc == 0) { // standard input
outRet = snprintf_s(outBuf, outBufLen, outBufLen - 1, "(%s)= %s\n", "stdin", (char *)hexBuf);
} else {
outRet = snprintf_s(
outBuf, outBufLen, outBufLen - 1, "%s(%s)= %s\n", g_dgstInfo.algName, filename, (char *)hexBuf);
}
uint32_t len = strlen(outBuf);
BSL_SAL_FREE(hexBuf);
if (outRet == -1) {
BSL_SAL_FREE(outBuf);
(void)AppPrintError("dgst: Failed to combine the output content\n");
return HITLS_APP_SECUREC_FAIL;
}
char *finalOutBuf = (char *)BSL_SAL_Calloc(len, sizeof(char));
if (memcpy_s(finalOutBuf, len, outBuf, strlen(outBuf)) != EOK) {
BSL_SAL_FREE(outBuf);
BSL_SAL_FREE(finalOutBuf);
return HITLS_APP_SECUREC_FAIL;
}
BSL_SAL_FREE(outBuf);
*buf = (uint8_t *)finalOutBuf;
*bufLen = len;
return HITLS_APP_SUCCESS;
}
static int32_t MdFinalToBuf(CRYPT_EAL_MdCTX *ctx, uint8_t **buf, uint32_t *bufLen, const char *filename)
{
int32_t outRet = HITLS_APP_SUCCESS;
// save the initial hash value
uint8_t *hashBuf = (uint8_t *)BSL_SAL_Calloc(g_dgstInfo.digestSize + 1, sizeof(uint8_t));
if (hashBuf == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
uint32_t hashBufLen = g_dgstInfo.digestSize;
outRet = CRYPT_EAL_MdFinal(ctx, hashBuf, &hashBufLen); // complete the digest and output the final digest to the buf
if (outRet != CRYPT_SUCCESS || hashBufLen < g_dgstInfo.digestSize) {
BSL_SAL_FREE(hashBuf);
(void)AppPrintError("dgst: filename: %s Failed to complete the final summary\n", filename);
return HITLS_APP_CRYPTO_FAIL;
}
outRet = HashValToFinal(hashBuf, hashBufLen, buf, bufLen, filename);
BSL_SAL_FREE(hashBuf);
return outRet;
}
static int32_t FileSumOutStd(CRYPT_EAL_MdCTX *ctx)
{
int32_t outRet = HITLS_APP_SUCCESS;
// Traverse the files that need to be digested, obtain the file content, calculate the file content digest,
// and output the digest to the UIO.
for (int i = 0; i < g_argc; ++i) {
outRet = CRYPT_EAL_MdDeinit(ctx); // md release
if (outRet != CRYPT_SUCCESS) {
(void)AppPrintError("dgst: Summary context deinit failed.\n");
return HITLS_APP_CRYPTO_FAIL;
}
outRet = CRYPT_EAL_MdInit(ctx); // md initialization
if (outRet != CRYPT_SUCCESS) {
(void)AppPrintError("dgst: Summary context creation failed.\n");
return HITLS_APP_CRYPTO_FAIL;
}
outRet = ReadFileToBuf(ctx, g_argv[i]); // read the file content by block and calculate the hash value
if (outRet != HITLS_APP_SUCCESS) {
return HITLS_APP_UIO_FAIL;
}
uint8_t *outBuf = NULL;
uint32_t outBufLen = 0;
outRet = MdFinalToBuf(ctx, &outBuf, &outBufLen, g_argv[i]); // read the final hash value to the buffer
if (outRet != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(outBuf);
(void)AppPrintError("dgst: Failed to output the final summary value\n");
return outRet;
}
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(NULL, 'w', 0); // the standard output is required for each file
if (fileWriteUio == NULL) {
BSL_SAL_FREE(outBuf);
(void)AppPrintError("dgst: Failed to open the stdout\n");
return HITLS_APP_UIO_FAIL;
}
outRet = BufOutToUio(NULL, fileWriteUio, (uint8_t *)outBuf, outBufLen); // output the hash value to the UIO
BSL_SAL_FREE(outBuf);
BSL_UIO_Free(fileWriteUio);
if (outRet != HITLS_APP_SUCCESS) { // Released after the standard output is complete
(void)AppPrintError("dgst: Failed to output the hash value\n");
return outRet;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t MultiFileSetCtx(CRYPT_EAL_MdCTX *ctx)
{
int32_t outRet = CRYPT_EAL_MdDeinit(ctx); // md release
if (outRet != CRYPT_SUCCESS) {
(void)AppPrintError("dgst: Summary context deinit failed.\n");
return HITLS_APP_CRYPTO_FAIL;
}
outRet = CRYPT_EAL_MdInit(ctx); // md initialization
if (outRet != CRYPT_SUCCESS) {
(void)AppPrintError("dgst: Summary context creation failed.\n");
return HITLS_APP_CRYPTO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t FileSumOutFile(CRYPT_EAL_MdCTX *ctx, const char *outfile)
{
int32_t outRet = HITLS_APP_SUCCESS;
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(outfile, 'w', 0); // overwrite the original content
if (fileWriteUio == NULL) {
(void)AppPrintError("dgst: Failed to open the file path: %s\n", outfile);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
fileWriteUio = HITLS_APP_UioOpen(outfile, 'a', 0);
if (fileWriteUio == NULL) {
(void)AppPrintError("dgst: Failed to open the file path: %s\n", outfile);
return HITLS_APP_UIO_FAIL;
}
for (int i = 0; i < g_argc; ++i) {
// Traverse the files that need to be digested, obtain the file content, calculate the file content digest,
// and output the digest to the UIO.
outRet = MultiFileSetCtx(ctx);
if (outRet != HITLS_APP_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
return outRet;
}
outRet = ReadFileToBuf(ctx, g_argv[i]); // read the file content by block and calculate the hash value
if (outRet != HITLS_APP_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
(void)AppPrintError("dgst: Failed to read the file content by block and calculate the hash value\n");
return HITLS_APP_UIO_FAIL;
}
uint8_t *outBuf = NULL;
uint32_t outBufLen = 0;
outRet = MdFinalToBuf(ctx, &outBuf, &outBufLen, g_argv[i]); // read the final hash value to the buffer
if (outRet != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(outBuf);
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
(void)AppPrintError("dgst: Failed to output the final summary value\n");
return outRet;
}
outRet = BufOutToUio(outfile, fileWriteUio, (uint8_t *)outBuf, outBufLen); // output the hash value to the UIO
BSL_SAL_FREE(outBuf);
if (outRet != HITLS_APP_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
return outRet;
}
}
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
return HITLS_APP_SUCCESS;
}
static int32_t FileSumAndOut(CRYPT_EAL_MdCTX *ctx, const char *outfile)
{
int32_t outRet = HITLS_APP_SUCCESS;
if (outfile == NULL) {
// standard output, w overwriting mode
outRet = FileSumOutStd(ctx);
} else {
// file output appending mode
outRet = FileSumOutFile(ctx, outfile);
}
return outRet;
}
static CRYPT_EAL_MdCTX *InitAlgDigest(CRYPT_MD_AlgId id)
{
CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_ProviderMdNewCtx(APP_GetCurrent_LibCtx(), id, g_signInfo.provider->providerAttr);
if (ctx == NULL) {
(void)AppPrintError("dgst: Failed to create the algorithm(%s) context\n", g_dgstInfo.algName);
return NULL;
}
int32_t ret = CRYPT_EAL_MdInit(ctx); // md initialization
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("dgst: Summary context creation failed\n");
CRYPT_EAL_MdFreeCtx(ctx);
return NULL;
}
return ctx;
}
static int32_t OptParse(char **outfile)
{
HITLSOptType optType;
int ret = HITLS_APP_SUCCESS;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_DGST_EOF) {
switch (optType) {
case HITLS_APP_OPT_DGST_EOF:
case HITLS_APP_OPT_DGST_ERR:
ret = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("dgst: Use -help for summary.\n");
return ret;
case HITLS_APP_OPT_DGST_HELP:
ret = HITLS_APP_HELP;
(void)HITLS_APP_OptHelpPrint(g_dgstOpts);
return ret;
case HITLS_APP_OPT_DGST_OUT:
*outfile = HITLS_APP_OptGetValueStr();
if (*outfile == NULL || strlen(*outfile) >= PATH_MAX) {
AppPrintError("dgst: The length of outfile error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_DGST_ALG:
g_dgstInfo.algName = HITLS_APP_OptGetValueStr();
if (g_dgstInfo.algName == NULL) {
return HITLS_APP_OPT_VALUE_INVALID;
}
g_dgstInfo.algId = HITLS_APP_GetCidByName(g_dgstInfo.algName, HITLS_APP_LIST_OPT_DGST_ALG);
if (g_dgstInfo.algId == BSL_CID_UNKNOWN) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_DGST_SIGN:
g_signInfo.privateKeyFile = HITLS_APP_OptGetValueStr();
if (g_signInfo.privateKeyFile == NULL) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_DGST_VERIFY:
g_signInfo.publicKeyFile = HITLS_APP_OptGetValueStr();
if (g_signInfo.publicKeyFile == NULL) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_DGST_SIGNATURE:
g_signInfo.signatureFile = HITLS_APP_OptGetValueStr();
if (g_signInfo.signatureFile == NULL) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_DGST_USERID:
g_signInfo.userid = HITLS_APP_OptGetValueStr();
if (g_signInfo.userid == NULL) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
#ifdef HITLS_APP_SM_MODE
case HITLS_SM_OPT_SM:
case HITLS_SM_OPT_UUID:
case HITLS_SM_OPT_WORKPATH:
#endif
case HITLS_APP_OPT_PROVIDER:
case HITLS_APP_OPT_PROVIDER_PATH:
case HITLS_APP_OPT_PROVIDER_ATTR:
break;
default:
return HITLS_APP_OPT_UNKOWN;
}
HITLS_APP_PROV_CASES(optType, g_signInfo.provider);
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_CASES(optType, g_signInfo.smParam);
#endif
}
return HITLS_APP_SUCCESS;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_dgst.c | C | unknown | 32,834 |
/*
* 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 "app_enc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <termios.h>
#include <unistd.h>
#include <sys/stat.h>
#include <securec.h>
#include "bsl_uio.h"
#include "app_utils.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_provider.h"
#include "app_sm.h"
#include "app_keymgmt.h"
#include "bsl_sal.h"
#include "bsl_ui.h"
#include "bsl_errno.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_kdf.h"
#include "crypt_algid.h"
#include "crypt_errno.h"
#include "crypt_params_key.h"
#define HITLS_APP_ENC_MAX_PARAM_NUM 5
typedef enum {
HITLS_APP_OPT_CIPHER_ALG = 2,
HITLS_APP_OPT_IN_FILE,
HITLS_APP_OPT_OUT_FILE,
HITLS_APP_OPT_DEC,
HITLS_APP_OPT_ENC,
HITLS_APP_OPT_MD,
HITLS_APP_OPT_PASS,
HITLS_APP_PROV_ENUM,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS_ENUM,
#endif
} HITLS_OptType;
static const HITLS_CmdOption g_encOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"cipher", HITLS_APP_OPT_CIPHER_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Cipher algorthm"},
{"in", HITLS_APP_OPT_IN_FILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file"},
{"out", HITLS_APP_OPT_OUT_FILE, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"dec", HITLS_APP_OPT_DEC, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Encryption operation"},
{"enc", HITLS_APP_OPT_ENC, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Decryption operation"},
{"md", HITLS_APP_OPT_MD, HITLS_APP_OPT_VALUETYPE_STRING, "Specified digest to create a key"},
{"pass", HITLS_APP_OPT_PASS, HITLS_APP_OPT_VALUETYPE_STRING, "Passphrase source, such as stdin ,file etc"},
HITLS_APP_PROV_OPTIONS,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS,
#endif
{NULL, 0, 0, NULL}
};
static const HITLS_CipherAlgList g_cIdList[] = {
{CRYPT_CIPHER_AES128_CBC, "aes128_cbc"},
{CRYPT_CIPHER_AES192_CBC, "aes192_cbc"},
{CRYPT_CIPHER_AES256_CBC, "aes256_cbc"},
{CRYPT_CIPHER_AES128_CTR, "aes128_ctr"},
{CRYPT_CIPHER_AES192_CTR, "aes192_ctr"},
{CRYPT_CIPHER_AES256_CTR, "aes256_ctr"},
{CRYPT_CIPHER_AES128_ECB, "aes128_ecb"},
{CRYPT_CIPHER_AES192_ECB, "aes192_ecb"},
{CRYPT_CIPHER_AES256_ECB, "aes256_ecb"},
{CRYPT_CIPHER_AES128_XTS, "aes128_xts"},
{CRYPT_CIPHER_AES256_XTS, "aes256_xts"},
{CRYPT_CIPHER_AES128_GCM, "aes128_gcm"},
{CRYPT_CIPHER_AES192_GCM, "aes192_gcm"},
{CRYPT_CIPHER_AES256_GCM, "aes256_gcm"},
{CRYPT_CIPHER_CHACHA20_POLY1305, "chacha20_poly1305"},
{CRYPT_CIPHER_SM4_CBC, "sm4_cbc"},
{CRYPT_CIPHER_SM4_ECB, "sm4_ecb"},
{CRYPT_CIPHER_SM4_CTR, "sm4_ctr"},
{CRYPT_CIPHER_SM4_GCM, "sm4_gcm"},
{CRYPT_CIPHER_SM4_CFB, "sm4_cfb"},
{CRYPT_CIPHER_SM4_OFB, "sm4_ofb"},
{CRYPT_CIPHER_SM4_XTS, "sm4_xts"},
{CRYPT_CIPHER_AES128_CFB, "aes128_cfb"},
{CRYPT_CIPHER_AES192_CFB, "aes192_cfb"},
{CRYPT_CIPHER_AES256_CFB, "aes256_cfb"},
{CRYPT_CIPHER_AES128_OFB, "aes128_ofb"},
{CRYPT_CIPHER_AES192_OFB, "aes192_ofb"},
{CRYPT_CIPHER_AES256_OFB, "aes256_ofb"},
};
static const HITLS_MacAlgList g_mIdList[] = {
{CRYPT_MAC_HMAC_MD5, "md5"},
{CRYPT_MAC_HMAC_SHA1, "sha1"},
{CRYPT_MAC_HMAC_SHA224, "sha224"},
{CRYPT_MAC_HMAC_SHA256, "sha256"},
{CRYPT_MAC_HMAC_SHA384, "sha384"},
{CRYPT_MAC_HMAC_SHA512, "sha512"},
{CRYPT_MAC_HMAC_SM3, "sm3"},
{CRYPT_MAC_HMAC_SHA3_224, "sha3_224"},
{CRYPT_MAC_HMAC_SHA3_256, "sha3_256"},
{CRYPT_MAC_HMAC_SHA3_384, "sha3_384"},
{CRYPT_MAC_HMAC_SHA3_512, "sha3_512"}
};
static const uint32_t CIPHER_IS_BlOCK[] = {
CRYPT_CIPHER_AES128_CBC,
CRYPT_CIPHER_AES192_CBC,
CRYPT_CIPHER_AES256_CBC,
CRYPT_CIPHER_AES128_ECB,
CRYPT_CIPHER_AES192_ECB,
CRYPT_CIPHER_AES256_ECB,
CRYPT_CIPHER_SM4_CBC,
CRYPT_CIPHER_SM4_ECB,
};
static const uint32_t CIPHER_IS_XTS[] = {
CRYPT_CIPHER_AES128_XTS,
CRYPT_CIPHER_AES256_XTS,
CRYPT_CIPHER_SM4_XTS,
};
typedef struct {
char *pass;
uint32_t passLen;
unsigned char *salt;
uint32_t saltLen;
unsigned char *iv;
uint32_t ivLen;
unsigned char *dKey;
uint32_t dKeyLen;
CRYPT_EAL_CipherCtx *ctx;
uint32_t blockSize;
} EncKeyParam;
typedef struct {
BSL_UIO *rUio;
BSL_UIO *wUio;
} EncUio;
typedef struct {
uint32_t version;
char *inFile;
char *outFile;
char *passOptStr; // Indicates the following value of the -pass option entered by the user.
int32_t cipherId; // Indicates the symmetric encryption algorithm ID entered by the user.
int32_t mdId; // Indicates the HMAC algorithm ID entered by the user.
int32_t encTag; // Indicates the encryption/decryption flag entered by the user.
uint32_t iter; // Indicates the number of iterations entered by the user.
EncKeyParam *keySet;
EncUio *encUio;
AppProvider *provider;
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param *smParam;
#endif
} EncCmdOpt;
static int32_t GetPwdFromFile(const char *fileArg, char *tmpPass);
static int32_t Str2HexStr(const unsigned char *buf, uint32_t bufLen, char *hexBuf, uint32_t hexBufLen);
static int32_t HexToStr(const char *hexBuf, unsigned char *buf);
static int32_t Int2Hex(uint32_t num, char *hexBuf);
static uint32_t Hex2Uint(char *hexBuf, int32_t *num);
static void PrintHMacAlgList(void);
static void PrintCipherAlgList(void);
static int32_t HexAndWrite(EncCmdOpt *encOpt, uint32_t decData, char *buf);
static int32_t ReadAndDec(EncCmdOpt *encOpt, char *hexBuf, uint32_t hexBufLen, int32_t *decData);
static int32_t GetCipherId(const char *name);
static int32_t GetHMacId(const char *mdName);
static int32_t GetPasswd(const char *arg, bool mode, char *resPass);
static int32_t CheckPasswd(const char *passwd);
// process for the ENC to receive subordinate options
static int32_t HandleOpt(EncCmdOpt *encOpt)
{
int32_t encOptType;
while ((encOptType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
HITLS_APP_PROV_CASES(encOptType, encOpt->provider);
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_CASES(encOptType, encOpt->smParam);
#endif
switch (encOptType) {
case HITLS_APP_OPT_EOF:
break;
case HITLS_APP_OPT_ERR:
AppPrintError("enc: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_OPT_HELP:
HITLS_APP_OptHelpPrint(g_encOpts);
return HITLS_APP_HELP;
case HITLS_APP_OPT_ENC:
encOpt->encTag = 1;
break;
case HITLS_APP_OPT_DEC:
encOpt->encTag = 0;
break;
case HITLS_APP_OPT_IN_FILE:
encOpt->inFile = HITLS_APP_OptGetValueStr();
break;
case HITLS_APP_OPT_OUT_FILE:
encOpt->outFile = HITLS_APP_OptGetValueStr();
break;
case HITLS_APP_OPT_PASS:
encOpt->passOptStr = HITLS_APP_OptGetValueStr();
break;
case HITLS_APP_OPT_MD:
if ((encOpt->mdId = GetHMacId(HITLS_APP_OptGetValueStr())) == -1) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_CIPHER_ALG:
if ((encOpt->cipherId = GetCipherId(HITLS_APP_OptGetValueStr())) == -1) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
default:
break;
}
}
// Obtain the number of parameters that cannot be parsed in the current version
// and print the error information and help list.
if (HITLS_APP_GetRestOptNum() != 0) {
AppPrintError("Extra arguments given.\n");
AppPrintError("enc: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckSmParam(EncCmdOpt *encOpt)
{
#ifdef HITLS_APP_SM_MODE
if (encOpt->smParam->smTag == 1) {
if (encOpt->smParam->uuid == NULL) {
AppPrintError("enc: The uuid is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (encOpt->smParam->workPath == NULL) {
AppPrintError("enc: The workpath is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
}
#else
(void)encOpt;
#endif
return HITLS_APP_SUCCESS;
}
// enc check the validity of option parameters
static int32_t CheckParam(EncCmdOpt *encOpt)
{
int32_t ret = CheckSmParam(encOpt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// if the -cipher option is not specified, an error is returned
if (encOpt->cipherId < 0) {
AppPrintError("The cipher algorithm is not specified.\n");
AppPrintError("enc: Use -help for summary.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
// if the user does not specify the encryption or decryption mode,
// an error is reported and the user is prompted to enter the following information
if (encOpt->encTag != 1 && encOpt->encTag != 0) {
AppPrintError("You have not entered the -enc or -dec option.\n");
AppPrintError("enc: Use -help for summary.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
// if the number of iterations is not set, the default value is 10000
if (encOpt->iter == 0) {
encOpt->iter = REC_ITERATION_TIMES;
}
// if the user does not transfer the digest algorithm, SHA256 is used by default to generate the derived key Dkey
if (encOpt->mdId < 0) {
encOpt->mdId = CRYPT_MAC_HMAC_SHA256;
}
// determine an ivLen based on the cipher ID entered by the user
if (CRYPT_EAL_CipherGetInfo(encOpt->cipherId, CRYPT_INFO_IV_LEN, &encOpt->keySet->ivLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to get the iv length from cipher ID.\n");
return HITLS_APP_CRYPTO_FAIL;
}
if (encOpt->inFile != NULL && strlen(encOpt->inFile) > REC_MAX_FILENAME_LENGTH) {
AppPrintError("The input file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (encOpt->outFile != NULL && strlen(encOpt->outFile) > REC_MAX_FILENAME_LENGTH) {
AppPrintError("The output file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
// enc determines the input and output paths
static int32_t HandleIO(EncCmdOpt *encOpt)
{
// Obtain the last value of the IN option.
// If there is no last value or this option does not exist, the standard input is used.
// If the file fails to be read, the process ends.
if (encOpt->inFile == NULL) {
// User doesn't input file upload path. Read the content directly entered by the user from the standard input.
encOpt->encUio->rUio = HITLS_APP_UioOpen(NULL, 'r', 1);
if (encOpt->encUio->rUio == NULL) {
AppPrintError("Failed to open the stdin.\n");
return HITLS_APP_UIO_FAIL;
}
} else {
// user inputs the file path and reads the content in the file from the file
encOpt->encUio->rUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (BSL_UIO_Ctrl(encOpt->encUio->rUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_READ, encOpt->inFile) != BSL_SUCCESS) {
AppPrintError("Failed to set infile mode.\n");
return HITLS_APP_UIO_FAIL;
}
if (encOpt->encUio->rUio == NULL) {
AppPrintError("Sorry, the file content fails to be read. Please check the file path.\n");
return HITLS_APP_UIO_FAIL;
}
}
// Obtain the post-value of the OUT option.
// If there is no post-value or the option does not exist, the standard output is used.
if (encOpt->outFile == NULL) {
encOpt->encUio->wUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (BSL_UIO_Ctrl(encOpt->encUio->wUio, BSL_UIO_FILE_PTR, 0, (void *)stdout) != BSL_SUCCESS) {
AppPrintError("Failed to set stdout mode.\n");
return HITLS_APP_UIO_FAIL;
}
} else {
// The file path transferred by the user is bound to the output file.
encOpt->encUio->wUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (BSL_UIO_Ctrl(encOpt->encUio->wUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_WRITE, encOpt->outFile) != BSL_SUCCESS ||
chmod(encOpt->outFile, S_IRUSR | S_IWUSR) != 0) {
AppPrintError("Failed to set outfile mode.\n");
return HITLS_APP_UIO_FAIL;
}
}
if (encOpt->encUio->wUio == NULL) {
AppPrintError("Failed to create the output pipeline.\n");
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static void FreeEnc(EncCmdOpt *encOpt)
{
if (encOpt->keySet->pass != NULL) {
BSL_SAL_ClearFree(encOpt->keySet->pass, encOpt->keySet->passLen);
}
if (encOpt->keySet->dKey != NULL) {
BSL_SAL_ClearFree(encOpt->keySet->dKey, encOpt->keySet->dKeyLen);
}
if (encOpt->keySet->salt != NULL) {
BSL_SAL_ClearFree(encOpt->keySet->salt, encOpt->keySet->saltLen);
}
if (encOpt->keySet->iv != NULL) {
BSL_SAL_ClearFree(encOpt->keySet->iv, encOpt->keySet->ivLen);
}
if (encOpt->keySet->ctx != NULL) {
CRYPT_EAL_CipherFreeCtx(encOpt->keySet->ctx);
}
if (encOpt->encUio->rUio != NULL) {
if (encOpt->inFile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(encOpt->encUio->rUio, true);
}
BSL_UIO_Free(encOpt->encUio->rUio);
}
if (encOpt->encUio->wUio != NULL) {
if (encOpt->outFile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(encOpt->encUio->wUio, true);
}
BSL_UIO_Free(encOpt->encUio->wUio);
}
return;
}
static int32_t ApplyForSpace(EncCmdOpt *encOpt)
{
if (encOpt == NULL || encOpt->keySet == NULL) {
return HITLS_APP_INVALID_ARG;
}
encOpt->keySet->pass = (char *)BSL_SAL_Calloc(APP_MAX_PASS_LENGTH + 1, sizeof(char));
if (encOpt->keySet->pass == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
encOpt->keySet->salt = (unsigned char *)BSL_SAL_Calloc(REC_SALT_LEN + 1, sizeof(unsigned char));
if (encOpt->keySet->salt == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
encOpt->keySet->saltLen = REC_SALT_LEN;
encOpt->keySet->iv = (unsigned char *)BSL_SAL_Calloc(REC_MAX_IV_LENGTH + 1, sizeof(unsigned char));
if (encOpt->keySet->iv == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
encOpt->keySet->dKey = (unsigned char *)BSL_SAL_Calloc(REC_MAX_MAC_KEY_LEN + 1, sizeof(unsigned char));
if (encOpt->keySet->dKey == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
return HITLS_APP_SUCCESS;
}
// enc parses the password entered by the user
static int32_t HandlePasswd(EncCmdOpt *encOpt)
{
#ifdef HITLS_APP_SM_MODE
if (encOpt->smParam->smTag == 1) {
return HITLS_APP_SUCCESS;
}
#endif
// If the user enters the last value of -pass, the system parses the value directly.
// If the user does not enter the value, the system reads the value from the standard input.
if (encOpt->passOptStr != NULL) {
// Parse the password, starting with "file:" or "pass:" can be parsed.
// Others cannot be parsed and an error is reported.
bool parsingMode = 1; // enable the parsing mode
if (GetPasswd(encOpt->passOptStr, parsingMode, encOpt->keySet->pass) != HITLS_APP_SUCCESS) {
AppPrintError("The password cannot be recognized. Enter '-pass file:filePath' or '-pass pass:passwd'.\n");
return HITLS_APP_PASSWD_FAIL;
}
} else {
AppPrintError("The password can contain the following characters:\n");
AppPrintError("a~z A~Z 0~9 ! \" # $ %% & ' ( ) * + , - . / : ; < = > ? @ [ \\ ] ^ _ ` { | } ~\n");
AppPrintError("The space is not supported.\n");
char buf[APP_MAX_PASS_LENGTH + 1] = {0};
uint32_t bufLen = APP_MAX_PASS_LENGTH + 1;
BSL_UI_ReadPwdParam param = {"passwd", NULL, true};
int32_t ret = BSL_UI_ReadPwdUtil(¶m, buf, &bufLen, HITLS_APP_DefaultPassCB, NULL);
if (ret == BSL_UI_READ_BUFF_TOO_LONG || ret == BSL_UI_READ_LEN_TOO_SHORT) {
HITLS_APP_PrintPassErrlog();
return HITLS_APP_PASSWD_FAIL;
}
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to read passwd from stdin.\n");
return HITLS_APP_PASSWD_FAIL;
}
bufLen -= 1;
buf[bufLen] = '\0';
bool parsingMode = 0; // close the parsing mode
if (GetPasswd(buf, parsingMode, encOpt->keySet->pass) != HITLS_APP_SUCCESS) {
(void)memset_s(buf, APP_MAX_PASS_LENGTH, 0, APP_MAX_PASS_LENGTH);
AppPrintError("The password cannot be recognized.Enter '-pass file:filePath' or '-pass pass:passwd'.\n");
return HITLS_APP_PASSWD_FAIL;
}
}
if (encOpt->keySet->pass == NULL) {
AppPrintError("Failed to get the passwd.\n");
return HITLS_APP_PASSWD_FAIL;
}
encOpt->keySet->passLen = strlen(encOpt->keySet->pass);
return HITLS_APP_SUCCESS;
}
static int32_t GenSaltAndIv(EncCmdOpt *encOpt)
{
// During encryption, salt and iv are randomly generated.
// use the random number API to generate the salt value
int32_t ret = CRYPT_EAL_RandbytesEx(APP_GetCurrent_LibCtx(), encOpt->keySet->salt, encOpt->keySet->saltLen);
if (ret != CRYPT_SUCCESS) {
AppPrintError("enc: Failed to generate the salt value, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
// use the random number API to generate the iv value
if (encOpt->keySet->ivLen > 0) {
ret = CRYPT_EAL_RandbytesEx(APP_GetCurrent_LibCtx(), encOpt->keySet->iv, encOpt->keySet->ivLen);
if (ret != CRYPT_SUCCESS) {
AppPrintError("enc: Failed to generate the iv value, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
// The enc encryption mode writes information to the file header.
static int32_t WriteEncFileHeader(EncCmdOpt *encOpt)
{
char hexDataBuf[REC_HEX_BUF_LENGTH + 1] = {0}; // Hexadecimal Data Generic Buffer
// Write the version, derived algorithm ID, salt information, iteration times, and IV information to the output file
// (Convert the character string to hexadecimal and eliminate '\0' after the character string.)
// convert and write the version number
int32_t ret;
if ((ret = HexAndWrite(encOpt, encOpt->version, hexDataBuf)) != HITLS_APP_SUCCESS) {
return ret;
}
// convert and write the ID of the derived algorithm
if ((ret = HexAndWrite(encOpt, encOpt->cipherId, hexDataBuf)) != HITLS_APP_SUCCESS) {
return ret;
}
// convert and write the saltlen
if ((ret = HexAndWrite(encOpt, encOpt->keySet->saltLen, hexDataBuf)) != HITLS_APP_SUCCESS) {
return ret;
}
// convert and write the salt value
char hSaltBuf[REC_SALT_LEN * REC_DOUBLE + 1] = {0}; // Hexadecimal salt buffer
if (Str2HexStr(encOpt->keySet->salt, REC_HEX_BUF_LENGTH, hSaltBuf, sizeof(hSaltBuf)) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
uint32_t writeLen = 0;
if (BSL_UIO_Write(encOpt->encUio->wUio, hSaltBuf, REC_SALT_LEN * REC_DOUBLE, &writeLen) != BSL_SUCCESS ||
writeLen != REC_SALT_LEN * REC_DOUBLE) {
return HITLS_APP_UIO_FAIL;
}
// convert and write the iteration times
if ((ret = HexAndWrite(encOpt, encOpt->iter, hexDataBuf)) != HITLS_APP_SUCCESS) {
return ret;
}
if (encOpt->keySet->ivLen > 0) {
// convert and write the ivlen
if ((ret = HexAndWrite(encOpt, encOpt->keySet->ivLen, hexDataBuf)) != HITLS_APP_SUCCESS) {
return ret;
}
// convert and write the iv
char hIvBuf[REC_MAX_IV_LENGTH * REC_DOUBLE + 1] = {0}; // hexadecimal iv buffer
if (Str2HexStr(encOpt->keySet->iv, encOpt->keySet->ivLen, hIvBuf, sizeof(hIvBuf)) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
if (BSL_UIO_Write(encOpt->encUio->wUio, hIvBuf, encOpt->keySet->ivLen * REC_DOUBLE, &writeLen) != BSL_SUCCESS ||
writeLen != encOpt->keySet->ivLen * REC_DOUBLE) {
return HITLS_APP_UIO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t HandleDecFileIv(EncCmdOpt *encOpt)
{
char hexDataBuf[REC_HEX_BUF_LENGTH + 1] = {0}; // hexadecimal data buffer
uint32_t hexBufLen = sizeof(hexDataBuf);
int32_t ret = HITLS_APP_SUCCESS;
// Read the length of the IV, convert it into decimal, and store it.
uint32_t tmpIvLen = 0;
if ((ret = ReadAndDec(encOpt, hexDataBuf, hexBufLen, (int32_t*)&tmpIvLen)) != HITLS_APP_SUCCESS) {
return ret;
}
if (tmpIvLen != encOpt->keySet->ivLen) {
AppPrintError("Iv length is error, iv length read from file is %u.\n", tmpIvLen);
return HITLS_APP_INFO_CMP_FAIL;
}
// Read iv based on ivLen, convert it into a decimal character string, and store it.
uint32_t readLen = 0;
char hIvBuf[REC_MAX_IV_LENGTH * REC_DOUBLE + 1] = {0}; // Hexadecimal iv buffer
if (BSL_UIO_Read(encOpt->encUio->rUio, hIvBuf, encOpt->keySet->ivLen * REC_DOUBLE, &readLen) != BSL_SUCCESS ||
readLen != encOpt->keySet->ivLen * REC_DOUBLE) {
return HITLS_APP_UIO_FAIL;
}
if (HexToStr(hIvBuf, encOpt->keySet->iv) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
return ret;
}
// The ENC decryption mode parses the file header data and receives the ciphertext in the input file.
static int32_t HandleDecFileHeader(EncCmdOpt *encOpt)
{
char hexDataBuf[REC_HEX_BUF_LENGTH + 1] = {0}; // hexadecimal data buffer
uint32_t hexBufLen = sizeof(hexDataBuf);
// Read the version, derived algorithm ID, salt information, iteration times, and IV information from the input file
// convert them into decimal and store for later decryption.
// The read data is in hexadecimal format and needs to be converted to decimal format.
// Read the version number, convert it to decimal, and compare it.
int32_t ret = HITLS_APP_SUCCESS;
uint32_t rVersion = 0; // Version number in the ciphertext
if ((ret = ReadAndDec(encOpt, hexDataBuf, hexBufLen, (int32_t *)&rVersion)) != HITLS_APP_SUCCESS) {
return ret;
}
// Compare the file version input by the user with the current ENC version.
// If the file version does not match, an error is reported.
if (rVersion != encOpt->version) {
AppPrintError("Error version. The enc version is %u, the file version is %u.\n", encOpt->version, rVersion);
return HITLS_APP_INFO_CMP_FAIL;
}
// Read the derived algorithm in the ciphertext, convert it to decimal and compare.
int32_t rCipherId = -1; // Decimal cipherID read from the file
if ((ret = ReadAndDec(encOpt, hexDataBuf, hexBufLen, &rCipherId)) != HITLS_APP_SUCCESS) {
return ret;
}
// Compare the algorithm entered by the user from the command line with the algorithm read.
// If the algorithm is incorrect, an error is reported.
if (encOpt->cipherId != rCipherId) {
AppPrintError("Cipher ID is %d, cipher ID read from file is %d.\n", encOpt->cipherId, rCipherId);
return HITLS_APP_INFO_CMP_FAIL;
}
// Read the salt length in the ciphertext, convert the salt length into decimal, and store the salt length.
if ((ret = ReadAndDec(encOpt, hexDataBuf, hexBufLen, (int32_t *)&encOpt->keySet->saltLen)) != HITLS_APP_SUCCESS) {
return ret;
}
if (encOpt->keySet->saltLen != REC_SALT_LEN) {
AppPrintError("Salt length is error, Salt length read from file is %u.\n", encOpt->keySet->saltLen);
return HITLS_APP_INFO_CMP_FAIL;
}
// Read the salt value in the ciphertext, convert the salt value into a decimal string, and store the string.
uint32_t readLen = 0;
char hSaltBuf[REC_SALT_LEN * REC_DOUBLE + 1] = {0}; // Hexadecimal salt buffer
if (BSL_UIO_Read(encOpt->encUio->rUio, hSaltBuf, REC_SALT_LEN * REC_DOUBLE, &readLen) != BSL_SUCCESS ||
readLen != REC_SALT_LEN * REC_DOUBLE) {
return HITLS_APP_UIO_FAIL;
}
if (HexToStr(hSaltBuf, encOpt->keySet->salt) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
// Read the times of iteration, convert the number to decimal, and store the number.
if ((ret = ReadAndDec(encOpt, hexDataBuf, hexBufLen, (int32_t *)&encOpt->iter)) != HITLS_APP_SUCCESS) {
return ret;
}
if (encOpt->keySet->ivLen > 0) {
if ((ret = HandleDecFileIv(encOpt)) != HITLS_APP_SUCCESS) {
return ret;
}
}
return ret;
}
#ifdef HITLS_APP_SM_MODE
static int32_t GetKeyFromP12(EncCmdOpt *encOpt)
{
HITLS_APP_KeyInfo keyInfo = {0};
int32_t ret = HITLS_APP_FindKey(encOpt->provider, encOpt->smParam, encOpt->cipherId, &keyInfo);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("enc: Failed to find key, errCode: 0x%x\n", ret);
return ret;
}
if (encOpt->keySet->dKeyLen != keyInfo.keyLen) {
AppPrintError("enc: Key length is not equal, dKeyLen: %u, keyLen: %u.\n", encOpt->keySet->dKeyLen,
keyInfo.keyLen);
BSL_SAL_CleanseData(keyInfo.key, keyInfo.keyLen);
return HITLS_APP_INVALID_ARG;
}
(void)memcpy_s(encOpt->keySet->dKey, encOpt->keySet->dKeyLen, keyInfo.key, keyInfo.keyLen);
BSL_SAL_CleanseData(keyInfo.key, keyInfo.keyLen);
return HITLS_APP_SUCCESS;
}
#endif
static int32_t GetCipherKey(EncCmdOpt *encOpt)
{
if (CRYPT_EAL_CipherGetInfo(encOpt->cipherId, CRYPT_INFO_KEY_LEN, &encOpt->keySet->dKeyLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
#ifdef HITLS_APP_SM_MODE
if (encOpt->smParam->smTag == 1) {
return GetKeyFromP12(encOpt);
}
#endif
CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_ProviderKdfNewCtx(APP_GetCurrent_LibCtx(), CRYPT_KDF_PBKDF2,
encOpt->provider->providerAttr);
if (ctx == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
int index = 0;
BSL_Param params[HITLS_APP_ENC_MAX_PARAM_NUM] = {{0}, {0}, {0}, {0}, BSL_PARAM_END};
(void)BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &encOpt->mdId,
sizeof(encOpt->mdId));
(void)BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS,
encOpt->keySet->pass, encOpt->keySet->passLen);
(void)BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS,
encOpt->keySet->salt, encOpt->keySet->saltLen);
(void)BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32,
&encOpt->iter, sizeof(encOpt->iter));
uint32_t ret = CRYPT_EAL_KdfSetParam(ctx, params);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_KdfFreeCtx(ctx);
return ret;
}
ret = CRYPT_EAL_KdfDerive(ctx, encOpt->keySet->dKey, encOpt->keySet->dKeyLen);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_KdfFreeCtx(ctx);
return ret;
}
// Delete sensitive information after the key is used.
CRYPT_EAL_KdfFreeCtx(ctx);
return BSL_SUCCESS;
}
static bool CipherIdIsValid(uint32_t id, const uint32_t *list, uint32_t num)
{
for (uint32_t i = 0; i < num; i++) {
if (id == list[i]) {
return true;
}
}
return false;
}
static bool IsBlockCipher(CRYPT_CIPHER_AlgId id)
{
if (CipherIdIsValid(id, CIPHER_IS_BlOCK, sizeof(CIPHER_IS_BlOCK) / sizeof(CIPHER_IS_BlOCK[0]))) {
return true;
}
return false;
}
static bool IsXtsCipher(CRYPT_CIPHER_AlgId id)
{
if (CipherIdIsValid(id, CIPHER_IS_XTS, sizeof(CIPHER_IS_XTS) / sizeof(CIPHER_IS_XTS[0]))) {
return true;
}
return false;
}
static int32_t XTSCipherUpdate(EncCmdOpt *encOpt, uint8_t *buf, uint32_t bufLen, uint8_t *res, uint32_t resLen)
{
uint32_t updateLen = bufLen;
if (CRYPT_EAL_CipherUpdate(encOpt->keySet->ctx, buf, bufLen, res, &updateLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to update the cipher.\n");
return HITLS_APP_CRYPTO_FAIL;
}
if (updateLen > resLen) {
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t writeLen = 0;
if (updateLen != 0 &&
(BSL_UIO_Write(encOpt->encUio->wUio, res, updateLen, &writeLen) != BSL_SUCCESS || writeLen != updateLen)) {
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t StreamCipherUpdate(EncCmdOpt *encOpt, uint8_t *readBuf, uint32_t readLen, uint8_t *resBuf,
uint32_t resLen)
{
uint32_t updateLen = 0;
uint32_t hBuffLen = readLen + encOpt->keySet->blockSize;
uint32_t blockNum = readLen / encOpt->keySet->blockSize;
uint32_t remainLen = readLen % encOpt->keySet->blockSize;
for (uint32_t i = 0; i < blockNum; ++i) {
hBuffLen = readLen + encOpt->keySet->blockSize - i * encOpt->keySet->blockSize;
if (CRYPT_EAL_CipherUpdate(encOpt->keySet->ctx, readBuf + (i * encOpt->keySet->blockSize),
encOpt->keySet->blockSize, resBuf + (i * encOpt->keySet->blockSize), &hBuffLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to update the cipher.\n");
return HITLS_APP_CRYPTO_FAIL;
}
updateLen += hBuffLen;
}
if (remainLen > 0) {
hBuffLen = readLen + encOpt->keySet->blockSize - updateLen;
if (CRYPT_EAL_CipherUpdate(encOpt->keySet->ctx, readBuf + updateLen, remainLen,
resBuf + updateLen, &hBuffLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to update the cipher.\n");
return HITLS_APP_CRYPTO_FAIL;
}
updateLen += hBuffLen;
}
if (updateLen > resLen) {
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t writeLen = 0;
if (updateLen != 0 &&
(BSL_UIO_Write(encOpt->encUio->wUio, resBuf, updateLen, &writeLen) != BSL_SUCCESS || writeLen != updateLen)) {
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t UpdateEncStdinEnd(EncCmdOpt *encOpt, uint8_t *cache, uint32_t cacheLen, uint8_t *resBuf, uint32_t resLen)
{
if (IsXtsCipher(encOpt->cipherId)) {
if (cacheLen < XTS_MIN_DATALEN) {
AppPrintError("The XTS algorithm does not support data less than 16 bytes.\n");
return HITLS_APP_CRYPTO_FAIL;
}
return XTSCipherUpdate(encOpt, cache, cacheLen, resBuf, resLen);
} else {
return StreamCipherUpdate(encOpt, cache, cacheLen, resBuf, resLen);
}
}
static int32_t UpdateEncStdin(EncCmdOpt *encOpt)
{
// now readFileLen == 0
int32_t ret = HITLS_APP_SUCCESS;
// Because the standard input is read in each 4K, the data required by the XTS update cannot be less than 16.
// Therefore, the remaining data cannot be less than 16 bytes. The buffer behavior is required.
// In the common buffer logic, the remaining data may be less than 16. As a result, the XTS algorithm update fails.
// Set the cacheArea, the size is maximum data length of each row (4 KB) plus the readable block size (32 bytes).
// If the length of the read data exceeds 32 bytes, the length of the last 16-byte secure block is reserved,
// the rest of the data is updated to avoid the failure of updating the rest and tail data.
uint8_t cacheArea[MAX_BUFSIZE + BUF_READABLE_BLOCK] = {0};
uint32_t cacheLen = 0;
uint8_t readBuf[MAX_BUFSIZE] = {0};
uint8_t resBuf[MAX_BUFSIZE + BUF_READABLE_BLOCK] = {0};
uint32_t readLen = MAX_BUFSIZE;
bool isEof = false;
while (BSL_UIO_Ctrl(encOpt->encUio->rUio, BSL_UIO_FILE_GET_EOF, IS_SUPPORT_GET_EOF, &isEof) == BSL_SUCCESS) {
readLen = MAX_BUFSIZE;
if (isEof) {
// End stdin. Update the remaining data. If the remaining data size is 16 ≤ dataLen < 32, the XTS is valid.
ret = UpdateEncStdinEnd(encOpt, cacheArea, cacheLen, resBuf, sizeof(resBuf));
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
break;
}
if (BSL_UIO_Read(encOpt->encUio->rUio, readBuf, MAX_BUFSIZE, &readLen) != BSL_SUCCESS) {
(void)AppPrintError("Failed to obtain the content from the STDIN\n");
return HITLS_APP_UIO_FAIL;
}
if (readLen == 0) {
AppPrintError("Failed to read the input content\n");
return HITLS_APP_STDIN_FAIL;
}
if (memcpy_s(cacheArea + cacheLen, MAX_BUFSIZE + BUF_READABLE_BLOCK - cacheLen, readBuf, readLen) != EOK) {
return HITLS_APP_COPY_ARGS_FAILED;
}
cacheLen += readLen;
if (cacheLen < BUF_READABLE_BLOCK) {
continue;
}
uint32_t readableLen = cacheLen - BUF_SAFE_BLOCK;
if (IsXtsCipher(encOpt->cipherId)) {
ret = XTSCipherUpdate(encOpt, cacheArea, readableLen, resBuf, sizeof(resBuf));
} else {
ret = StreamCipherUpdate(encOpt, cacheArea, readableLen, resBuf, sizeof(resBuf));
}
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// Place the secure block data in the cacheArea at the top and reset cacheLen.
if (memcpy_s(cacheArea, sizeof(cacheArea) - BUF_SAFE_BLOCK, cacheArea + readableLen, BUF_SAFE_BLOCK) != EOK) {
return HITLS_APP_COPY_ARGS_FAILED;
}
cacheLen = BUF_SAFE_BLOCK;
}
return HITLS_APP_SUCCESS;
}
static int32_t UpdateEncFile(EncCmdOpt *encOpt, uint64_t readFileLen)
{
if (readFileLen < XTS_MIN_DATALEN && IsXtsCipher(encOpt->cipherId)) {
AppPrintError("The XTS algorithm does not support data less than 16 bytes.\n");
return HITLS_APP_CRYPTO_FAIL;
}
// now readFileLen != 0
int32_t ret = HITLS_APP_SUCCESS;
uint8_t readBuf[MAX_BUFSIZE * REC_DOUBLE] = {0};
uint8_t resBuf[MAX_BUFSIZE * REC_DOUBLE] = {0};
uint32_t readLen = MAX_BUFSIZE * REC_DOUBLE;
uint32_t bufLen = MAX_BUFSIZE * REC_DOUBLE;
while (readFileLen > 0) {
if (readFileLen < MAX_BUFSIZE * REC_DOUBLE) {
bufLen = readFileLen;
readLen = readFileLen;
}
if (readFileLen >= MAX_BUFSIZE * REC_DOUBLE) {
bufLen = MAX_BUFSIZE;
readLen = MAX_BUFSIZE;
}
if (!IsXtsCipher(encOpt->cipherId)) {
bufLen = (readFileLen > MAX_BUFSIZE) ? MAX_BUFSIZE : readFileLen;
readLen = bufLen;
}
if (BSL_UIO_Read(encOpt->encUio->rUio, readBuf, bufLen, &readLen) != BSL_SUCCESS || bufLen != readLen) {
AppPrintError("Failed to read the input content\n");
return HITLS_APP_UIO_FAIL;
}
readFileLen -= readLen;
if (IsXtsCipher(encOpt->cipherId)) {
ret = XTSCipherUpdate(encOpt, readBuf, readLen, resBuf, sizeof(resBuf));
} else {
ret = StreamCipherUpdate(encOpt, readBuf, readLen, resBuf, sizeof(resBuf));
}
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t DoCipherUpdateEnc(EncCmdOpt *encOpt, uint64_t readFileLen)
{
int32_t updateRet = HITLS_APP_SUCCESS;
if (readFileLen > 0) {
updateRet = UpdateEncFile(encOpt, readFileLen);
} else {
updateRet = UpdateEncStdin(encOpt);
}
if (updateRet != HITLS_APP_SUCCESS) {
return updateRet;
}
return HITLS_APP_SUCCESS;
}
static int32_t DoCipherUpdateDec(EncCmdOpt *encOpt, uint64_t readFileLen)
{
if (readFileLen == 0 && encOpt->inFile == NULL) {
AppPrintError("In decryption mode, the standard input cannot be used to obtain the ciphertext.\n");
return HITLS_APP_STDIN_FAIL;
}
if (readFileLen < XTS_MIN_DATALEN && IsXtsCipher(encOpt->cipherId)) {
AppPrintError("The XTS algorithm does not support ciphertext less than 16 bytes.\n");
return HITLS_APP_CRYPTO_FAIL;
}
// now readFileLen != 0
uint8_t readBuf[MAX_BUFSIZE * REC_DOUBLE] = {0};
uint8_t resBuf[MAX_BUFSIZE * REC_DOUBLE] = {0};
uint32_t readLen = MAX_BUFSIZE * REC_DOUBLE;
uint32_t bufLen = MAX_BUFSIZE * REC_DOUBLE;
while (readFileLen > 0) {
if (readFileLen < MAX_BUFSIZE * REC_DOUBLE) {
bufLen = readFileLen;
}
if (readFileLen >= MAX_BUFSIZE * REC_DOUBLE) {
bufLen = MAX_BUFSIZE;
}
if (!IsXtsCipher(encOpt->cipherId)) {
bufLen = (readFileLen >= MAX_BUFSIZE) ? MAX_BUFSIZE : readFileLen;
}
readLen = 0;
if (BSL_UIO_Read(encOpt->encUio->rUio, readBuf, bufLen, &readLen) != BSL_SUCCESS || bufLen != readLen) {
AppPrintError("Failed to read the input content\n");
return HITLS_APP_UIO_FAIL;
}
readFileLen -= readLen;
uint32_t updateLen = readLen + encOpt->keySet->blockSize;
if (CRYPT_EAL_CipherUpdate(encOpt->keySet->ctx, readBuf, readLen, resBuf, &updateLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to update the cipher.\n");
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t writeLen = 0;
if (updateLen != 0 &&
(BSL_UIO_Write(encOpt->encUio->wUio, resBuf, updateLen, &writeLen) != BSL_SUCCESS ||
writeLen != updateLen)) {
AppPrintError("Failed to write the cipher text.\n");
return HITLS_APP_UIO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t DoCipherUpdate(EncCmdOpt *encOpt)
{
const uint32_t AES_BLOCK_SIZE = 16;
encOpt->keySet->blockSize = AES_BLOCK_SIZE;
uint64_t readFileLen = 0;
if (encOpt->inFile != NULL &&
BSL_UIO_Ctrl(encOpt->encUio->rUio, BSL_UIO_PENDING, sizeof(readFileLen), &readFileLen) != BSL_SUCCESS) {
(void)AppPrintError("Failed to obtain the content length\n");
return HITLS_APP_UIO_FAIL;
}
if (encOpt->inFile == NULL) {
AppPrintError("You have not entered the -in option. Please directly enter the file content on the terminal.\n");
}
int32_t updateRet = (encOpt->encTag == 0) ? DoCipherUpdateDec(encOpt, readFileLen)
: DoCipherUpdateEnc(encOpt, readFileLen);
if (updateRet != HITLS_APP_SUCCESS) {
return updateRet;
}
// The Aead algorithm does not perform final processing.
uint32_t isAeadId = 0;
if (CRYPT_EAL_CipherGetInfo(encOpt->cipherId, CRYPT_INFO_IS_AEAD, &isAeadId) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (isAeadId == 1) {
return HITLS_APP_SUCCESS;
}
uint32_t finLen = AES_BLOCK_SIZE;
uint8_t resBuf[MAX_BUFSIZE] = {0};
// Fill the data whose size is less than the block size and output the crypted data.
if (CRYPT_EAL_CipherFinal(encOpt->keySet->ctx, resBuf, &finLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to final the cipher.\n");
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t writeLen = 0;
if (finLen != 0 && (BSL_UIO_Write(encOpt->encUio->wUio, resBuf, finLen, &writeLen) != BSL_SUCCESS ||
writeLen != finLen)) {
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
// Enc encryption or decryption process
static int32_t EncOrDecProc(EncCmdOpt *encOpt)
{
if (GetCipherKey(encOpt) != BSL_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
// Create a cipher context.
encOpt->keySet->ctx = CRYPT_EAL_ProviderCipherNewCtx(APP_GetCurrent_LibCtx(), encOpt->cipherId,
encOpt->provider->providerAttr);
if (encOpt->keySet->ctx == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
// Initialize the symmetric encryption and decryption handle.
if (CRYPT_EAL_CipherInit(encOpt->keySet->ctx, encOpt->keySet->dKey, encOpt->keySet->dKeyLen, encOpt->keySet->iv,
encOpt->keySet->ivLen, encOpt->encTag) != CRYPT_SUCCESS) {
AppPrintError("Failed to init the cipher.\n");
(void)memset_s(encOpt->keySet->dKey, encOpt->keySet->dKeyLen, 0, encOpt->keySet->dKeyLen);
return HITLS_APP_CRYPTO_FAIL;
}
(void)memset_s(encOpt->keySet->dKey, encOpt->keySet->dKeyLen, 0, encOpt->keySet->dKeyLen);
if (IsBlockCipher(encOpt->cipherId)) {
if (CRYPT_EAL_CipherSetPadding(encOpt->keySet->ctx, CRYPT_PADDING_PKCS7) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
#ifdef HITLS_APP_SM_MODE
if (encOpt->smParam->smTag == 1) {
encOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
}
#endif
int32_t ret = HITLS_APP_SUCCESS;
if (encOpt->encTag == 1) {
if ((ret = WriteEncFileHeader(encOpt)) != HITLS_APP_SUCCESS) {
return ret;
}
}
if ((ret = DoCipherUpdate(encOpt)) != HITLS_APP_SUCCESS) {
return ret;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandleEnc(EncCmdOpt *encOpt)
{
int32_t ret = HITLS_APP_SUCCESS;
if ((ret = HandleIO(encOpt)) != HITLS_APP_SUCCESS) {
return ret;
}
if ((ret = ApplyForSpace(encOpt)) != HITLS_APP_SUCCESS) {
return ret;
}
if ((ret = HandlePasswd(encOpt)) != HITLS_APP_SUCCESS) {
return ret;
}
// The ciphertext format is
// [g_version:uint32][derived algID:uint32][saltlen:uint32][salt][iter times:uint32][ivlen:uint32][iv][ciphertext]
// If the user identifier is encrypted
if (encOpt->encTag == 1 && (ret = GenSaltAndIv(encOpt)) != HITLS_APP_SUCCESS) {
// Random salt and IV are generated in encryption mode.
return ret;
}
// If the user identifier is decrypted
if (encOpt->encTag == 0 && (ret = HandleDecFileHeader(encOpt)) != HITLS_APP_SUCCESS) {
// Decryption mode: Parse the file header data and receive the ciphertext in the input file.
return ret;
}
// Final encryption or decryption process
if ((ret = EncOrDecProc(encOpt)) != HITLS_APP_SUCCESS) {
return ret;
}
return HITLS_APP_SUCCESS;
}
// enc main function
int32_t HITLS_EncMain(int argc, char *argv[])
{
int32_t encRet = -1; // return value of enc
EncKeyParam keySet = {NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0};
EncUio encUio = {NULL, NULL};
AppProvider appProvider = {NULL, NULL, NULL};
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param smParam = {NULL, 0, NULL, NULL, 0, HITLS_APP_SM_STATUS_OPEN};
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider, &smParam};
EncCmdOpt encOpt = {1, NULL, NULL, NULL, -1, -1, -1, 0, &keySet, &encUio, &appProvider, &smParam};
#else
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider};
EncCmdOpt encOpt = {1, NULL, NULL, NULL, -1, -1, -1, 0, &keySet, &encUio, &appProvider};
#endif
if ((encRet = HITLS_APP_OptBegin(argc, argv, g_encOpts)) != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
goto End;
}
// Process of receiving the lower-level option of the ENC.
if ((encRet = HandleOpt(&encOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
// Check the validity of the lower-level option receiving parameter.
if ((encRet = CheckParam(&encOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
encRet = HITLS_APP_Init(&initParam);
if (encRet != HITLS_APP_SUCCESS) {
goto End;
}
if ((encRet = HandleEnc(&encOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
encRet = HITLS_APP_SUCCESS;
End:
HITLS_APP_Deinit(&initParam, encRet);
FreeEnc(&encOpt);
return encRet;
}
static int32_t GetCipherId(const char *name)
{
for (size_t i = 0; i < sizeof(g_cIdList) / sizeof(g_cIdList[0]); i++) {
if (strcmp(g_cIdList[i].cipherAlgName, name) == 0) {
return g_cIdList[i].cipherId;
}
}
PrintCipherAlgList();
return -1;
}
static int32_t GetHMacId(const char *mdName)
{
for (size_t i = 0; i < sizeof(g_mIdList) / sizeof(g_mIdList[0]); i++) {
if (strcmp(g_mIdList[i].macAlgName, mdName) == 0) {
return g_mIdList[i].macId;
}
}
PrintHMacAlgList();
return -1;
}
static void PrintHMacAlgList(void)
{
AppPrintError("The current version supports only the following digest algorithms:\n");
for (size_t i = 0; i < sizeof(g_mIdList) / sizeof(g_mIdList[0]); i++) {
AppPrintError("%-19s", g_mIdList[i].macAlgName);
// 4 algorithm names are displayed in each row
if ((i + 1) % 4 == 0 && i != sizeof(g_mIdList) - 1) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return;
}
static void PrintCipherAlgList(void)
{
AppPrintError("The current version supports only the following cipher algorithms:\n");
for (size_t i = 0; i < sizeof(g_cIdList) / sizeof(g_cIdList[0]); i++) {
AppPrintError("%-19s", g_cIdList[i].cipherAlgName);
// 4 algorithm names are displayed in each row
if ((i + 1) % 4 == 0 && i != sizeof(g_cIdList) - 1) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return;
}
static int32_t GetPasswd(const char *arg, bool mode, char *resPass)
{
const char filePrefix[] = "file:"; // Prefix of the file path
const char passPrefix[] = "pass:"; // Prefix of password form
if (mode) {
// Parsing mode. The prefix needs to be parsed. The parseable format starts with "file:" or "pass:".
// Other parameters cannot be parsed and an error is returned.
// Apply for a new memory and copy the unprocessed character string.
char tmpPassArg[APP_MAX_PASS_LENGTH * REC_DOUBLE] = {0};
if (strlen(arg) < APP_MIN_PASS_LENGTH ||
strcpy_s(tmpPassArg, sizeof(tmpPassArg) - 1, arg) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
if (strncmp(tmpPassArg, filePrefix, REC_MIN_PRE_LENGTH - 1) == 0) {
// In this case, the password mode is read from the file.
int32_t res;
if ((res = GetPwdFromFile(tmpPassArg, resPass)) != HITLS_APP_SUCCESS) {
AppPrintError("Failed to obtain the password from the file.\n");
return res;
}
} else if (strncmp(tmpPassArg, passPrefix, REC_MIN_PRE_LENGTH - 1) == 0) {
// In this case, the password mode is read from the user input.
// Obtain the password after the ':'.
char *context = NULL;
char *tmpPass = strtok_s(tmpPassArg, ":", &context);
tmpPass = strtok_s(NULL, ":", &context);
if (tmpPass == NULL) {
return HITLS_APP_SECUREC_FAIL;
}
// Check whether the password is correct. Unsupported characters are not allowed.
if (CheckPasswd(tmpPass) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
if (memcpy_s(resPass, APP_MAX_PASS_LENGTH, tmpPass, strlen(tmpPass)) != EOK) {
return HITLS_APP_COPY_ARGS_FAILED;
}
} else {
// The prefix format is invalid. An error is returned.
AppPrintError("Invalid prefix format.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
} else {
// In non-parse mode, the format is directly determined.
// The value can be 1 byte ≤ password ≤ 1024 bytes, and only specified characters are supported.
// If the operation is successful, the password is received. If the operation fails, an error is returned.
if (CheckPasswd(arg) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
if (memcpy_s(resPass, APP_MAX_PASS_LENGTH, arg, strlen(arg)) != EOK) {
return HITLS_APP_COPY_ARGS_FAILED;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t GetPwdFromFile(const char *fileArg, char *tmpPass)
{
// Apply for a new memory and copy the unprocessed character string.
char tmpFileArg[REC_MAX_FILENAME_LENGTH + REC_MIN_PRE_LENGTH + 1] = {0};
if (strcpy_s(tmpFileArg, REC_MAX_FILENAME_LENGTH + REC_MIN_PRE_LENGTH, fileArg) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
// Obtain the file path after the ':'.
char *filePath = NULL;
char *context = NULL;
filePath = strtok_s(tmpFileArg, ":", &context);
filePath = strtok_s(NULL, ":", &context);
if (filePath == NULL) {
return HITLS_APP_SECUREC_FAIL;
}
// Bind the password file UIO.
BSL_UIO *passUio = BSL_UIO_New(BSL_UIO_FileMethod());
char tmpPassBuf[APP_MAX_PASS_LENGTH * REC_DOUBLE] = {0};
if (BSL_UIO_Ctrl(passUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_READ, filePath) != BSL_SUCCESS) {
AppPrintError("Failed to set infile mode for passwd.\n");
BSL_UIO_SetIsUnderlyingClosedByUio(passUio, true);
BSL_UIO_Free(passUio);
return HITLS_APP_UIO_FAIL;
}
uint32_t rPassLen = 0;
if (BSL_UIO_Read(passUio, tmpPassBuf, sizeof(tmpPassBuf), &rPassLen) != BSL_SUCCESS || rPassLen <= 0) {
AppPrintError("Failed to read passwd from file.\n");
BSL_UIO_SetIsUnderlyingClosedByUio(passUio, true);
BSL_UIO_Free(passUio);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(passUio, true);
BSL_UIO_Free(passUio);
if (tmpPassBuf[rPassLen - 1] == '\n') {
tmpPassBuf[rPassLen - 1] = '\0';
rPassLen -= 1;
}
if (rPassLen > APP_MAX_PASS_LENGTH) {
HITLS_APP_PrintPassErrlog();
return HITLS_APP_PASSWD_FAIL;
}
// Check whether the password is correct. Unsupported characters are not allowed.
if (HITLS_APP_CheckPasswd((uint8_t *)tmpPassBuf, rPassLen) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
if (memcpy_s(tmpPass, APP_MAX_PASS_LENGTH, tmpPassBuf, strlen(tmpPassBuf)) != EOK) {
return HITLS_APP_COPY_ARGS_FAILED;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckPasswd(const char *passwd)
{
// Check the key length. The key length must be greater than or equal to 1 byte and less than or equal to 1024
// bytes.
int32_t passLen = strlen(passwd);
if (passLen > APP_MAX_PASS_LENGTH) {
HITLS_APP_PrintPassErrlog();
return HITLS_APP_PASSWD_FAIL;
}
return HITLS_APP_CheckPasswd((const uint8_t *)passwd, (uint32_t)passLen);
}
static int32_t Str2HexStr(const unsigned char *buf, uint32_t bufLen, char *hexBuf, uint32_t hexBufLen)
{
if (hexBufLen < bufLen * REC_DOUBLE + 1) {
return HITLS_APP_INVALID_ARG;
}
for (uint32_t i = 0; i < bufLen; i++) {
if (sprintf_s(hexBuf + i * REC_DOUBLE, bufLen * REC_DOUBLE + 1, "%02x", buf[i]) == -1) {
AppPrintError("BSL_SAL_Calloc Failed.\n");
return HITLS_APP_ENCODE_FAIL;
}
}
hexBuf[bufLen * REC_DOUBLE] = '\0';
return HITLS_APP_SUCCESS;
}
static int32_t HexToStr(const char *hexBuf, unsigned char *buf)
{
// Convert hexadecimal character string data into ASCII character data.
int len = strlen(hexBuf) / 2;
for (int i = 0; i < len; i++) {
uint32_t val;
if (sscanf_s(hexBuf + i * REC_DOUBLE, "%2x", &val) == -1) {
AppPrintError("error in converting hex str to str.\n");
return HITLS_APP_ENCODE_FAIL;
}
buf[i] = (unsigned char)val;
}
return HITLS_APP_SUCCESS;
}
static int32_t Int2Hex(uint32_t num, char *hexBuf)
{
int ret = snprintf_s(hexBuf, REC_HEX_BUF_LENGTH + 1, REC_HEX_BUF_LENGTH, "%08X", num);
if (strlen(hexBuf) != REC_HEX_BUF_LENGTH || ret == -1) {
AppPrintError("error in uint to hex.\n");
return HITLS_APP_ENCODE_FAIL;
}
return HITLS_APP_SUCCESS;
}
static uint32_t Hex2Uint(char *hexBuf, int32_t *num)
{
if (hexBuf == NULL) {
AppPrintError("No hex buffer here.\n");
return HITLS_APP_INVALID_ARG;
}
char *endptr = NULL;
*num = strtoul(hexBuf, &endptr, REC_HEX_BASE);
return HITLS_APP_SUCCESS;
}
static int32_t HexAndWrite(EncCmdOpt *encOpt, uint32_t decData, char *buf)
{
uint32_t writeLen = 0;
if (Int2Hex(decData, buf) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
if (BSL_UIO_Write(encOpt->encUio->wUio, buf, REC_HEX_BUF_LENGTH, &writeLen) != BSL_SUCCESS ||
writeLen != REC_HEX_BUF_LENGTH) {
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t ReadAndDec(EncCmdOpt *encOpt, char *hexBuf, uint32_t hexBufLen, int32_t *decData)
{
if (hexBufLen < REC_HEX_BUF_LENGTH + 1) {
return HITLS_APP_INVALID_ARG;
}
uint32_t readLen = 0;
if (BSL_UIO_Read(encOpt->encUio->rUio, hexBuf, REC_HEX_BUF_LENGTH, &readLen) != BSL_SUCCESS ||
readLen != REC_HEX_BUF_LENGTH) {
return HITLS_APP_UIO_FAIL;
}
if (Hex2Uint(hexBuf, decData) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
return HITLS_APP_SUCCESS;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_enc.c | C | unknown | 53,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 "app_function.h"
#include <string.h>
#include <stddef.h>
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_rand.h"
#include "app_enc.h"
#include "app_pkcs12.h"
#include "app_x509.h"
#include "app_list.h"
#include "app_rsa.h"
#include "app_dgst.h"
#include "app_crl.h"
#include "app_genrsa.h"
#include "app_verify.h"
#include "app_passwd.h"
#include "app_pkey.h"
#include "app_genpkey.h"
#include "app_req.h"
#include "app_mac.h"
#include "app_kdf.h"
#include "app_keymgmt.h"
#include "app_client.h"
#include "app_server.h"
#include "app_pkeyutl.h"
#include "app_speed.h"
HITLS_CmdFunc g_cmdFunc[] = {
{"help", FUNC_TYPE_GENERAL, HITLS_HelpMain},
{"rand", FUNC_TYPE_GENERAL, HITLS_RandMain},
{"enc", FUNC_TYPE_GENERAL, HITLS_EncMain},
{"pkcs12", FUNC_TYPE_GENERAL, HITLS_PKCS12Main},
{"rsa", FUNC_TYPE_GENERAL, HITLS_RsaMain},
{"x509", FUNC_TYPE_GENERAL, HITLS_X509Main},
{"list", FUNC_TYPE_GENERAL, HITLS_ListMain},
{"dgst", FUNC_TYPE_GENERAL, HITLS_DgstMain},
{"crl", FUNC_TYPE_GENERAL, HITLS_CrlMain},
{"genrsa", FUNC_TYPE_GENERAL, HITLS_GenRSAMain},
{"verify", FUNC_TYPE_GENERAL, HITLS_VerifyMain},
{"passwd", FUNC_TYPE_GENERAL, HITLS_PasswdMain},
{"pkey", FUNC_TYPE_GENERAL, HITLS_PkeyMain},
{"genpkey", FUNC_TYPE_GENERAL, HITLS_GenPkeyMain},
{"req", FUNC_TYPE_GENERAL, HITLS_ReqMain},
{"mac", FUNC_TYPE_GENERAL, HITLS_MacMain},
{"kdf", FUNC_TYPE_GENERAL, HITLS_KdfMain},
#ifdef HITLS_APP_SM_MODE
{"keymgmt", FUNC_TYPE_GENERAL, HITLS_KeyMgmtMain},
#endif
{"s_client", FUNC_TYPE_GENERAL, HITLS_ClientMain},
{"s_server", FUNC_TYPE_GENERAL, HITLS_ServerMain},
{"pkeyutl", FUNC_TYPE_GENERAL, HITLS_PkeyUtlMain},
{"speed", FUNC_TYPE_GENERAL, HITLS_SpeedMain},
{NULL, FUNC_TYPE_NONE, NULL}
};
static void AppGetFuncPrintfLen(size_t *maxLen)
{
size_t len = 0;
for (size_t i = 0; g_cmdFunc[i].name != NULL; i++) {
len = (len > strlen(g_cmdFunc[i].name)) ? len : strlen(g_cmdFunc[i].name);
}
*maxLen = len + 5; // The relative maximum length is filled with 5 spaces.
}
void AppPrintFuncList(void)
{
AppPrintError("HiTLS supports the following commands:\n");
size_t maxLen = 0;
AppGetFuncPrintfLen(&maxLen);
for (size_t i = 0; g_cmdFunc[i].name != NULL; i++) {
if (((i % 4) == 0) && (i != 0)) { // Print 4 functions in one line
AppPrintError("\n");
}
AppPrintError("%-*s", maxLen, g_cmdFunc[i].name);
}
AppPrintError("\n");
}
int AppGetProgFunc(const char *proName, HITLS_CmdFunc *func)
{
for (size_t i = 0; g_cmdFunc[i].name != NULL; i++) {
if (strcmp(proName, g_cmdFunc[i].name) == 0) {
func->type = g_cmdFunc[i].type;
func->main = g_cmdFunc[i].main;
break;
}
}
if (func->main == NULL) {
AppPrintError("Can not find the function : %s. ", proName);
return HITLS_APP_OPT_NAME_INVALID;
}
return HITLS_APP_SUCCESS;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_function.c | C | unknown | 3,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 "app_genpkey.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <securec.h>
#include <limits.h>
#include "app_errno.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_list.h"
#include "app_utils.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_rand.h"
#define RSA_KEYGEN_BITS_STR "rsa_keygen_bits:"
#define EC_PARAMGEN_CURVE_STR "ec_paramgen_curve:"
#define MLDSA_PARAM_STR "mldsa_param:"
#define RSA_KEYGEN_BITS_STR_LEN ((int)(sizeof(RSA_KEYGEN_BITS_STR) - 1))
#define EC_PARAMGEN_CURVE_LEN ((int)(sizeof(EC_PARAMGEN_CURVE_STR) - 1))
#define MLDSA_PARAM_LEN ((int)(sizeof(MLDSA_PARAM_STR) - 1))
#define MAX_PKEY_OPT_ARG 10U
#define DEFAULT_RSA_KEYGEN_BITS 2048U
typedef enum {
HITLS_APP_OPT_ALGORITHM = 2,
HITLS_APP_OPT_PKEYOPT,
HITLS_APP_OPT_CIPHER_ALG,
HITLS_APP_OPT_PASS,
HITLS_APP_OPT_PUBOUT,
HITLS_APP_OPT_OUT,
HITLS_APP_OPT_OUTFORM,
} HITLSOptType;
const HITLS_CmdOption g_genPkeyOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"algorithm", HITLS_APP_OPT_ALGORITHM, HITLS_APP_OPT_VALUETYPE_STRING, "Key algorithm (RSA, EC, ML-DSA)"},
{"pkeyopt", HITLS_APP_OPT_PKEYOPT, HITLS_APP_OPT_VALUETYPE_STRING, "Set key options (e.g., mldsa_param:ML-DSA-65)"},
{"", HITLS_APP_OPT_CIPHER_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Any supported cipher"},
{"pass", HITLS_APP_OPT_PASS, HITLS_APP_OPT_VALUETYPE_STRING, "Output file pass phrase source"},
{"pubout", HITLS_APP_OPT_PUBOUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output public key"},
{"out", HITLS_APP_OPT_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"outform", HITLS_APP_OPT_OUTFORM, HITLS_APP_OPT_VALUETYPE_STRING, "Output format (PEM or DER, default: PEM)"},
{NULL, 0, 0, NULL},
};
typedef struct {
char *algorithm;
char *pkeyOptArg[MAX_PKEY_OPT_ARG];
uint32_t pkeyOptArgNum;
} InputGenKeyPara;
typedef struct {
char *pubOut;
char *outFilePath;
char *passOutArg;
BSL_ParseFormat outFormat;
} OutPutGenKeyPara;
typedef struct {
uint32_t bits;
uint32_t pkeyParaId;
} GenPkeyOptPara;
typedef CRYPT_EAL_PkeyCtx *(*GenPkeyCtxFunc)(const GenPkeyOptPara *);
typedef struct {
CRYPT_EAL_PkeyCtx *pkey;
GenPkeyCtxFunc genPkeyCtxFunc;
GenPkeyOptPara genPkeyOptPara;
char *passout;
int32_t cipherAlgCid;
InputGenKeyPara inPara;
OutPutGenKeyPara outPara;
} GenPkeyOptCtx;
typedef int32_t (*GenPkeyOptHandleFunc)(GenPkeyOptCtx *);
typedef struct {
int optType;
GenPkeyOptHandleFunc func;
} GenPkeyOptHandleTable;
static int32_t GenPkeyOptErr(GenPkeyOptCtx *optCtx)
{
(void)optCtx;
AppPrintError("genpkey: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t GenPkeyOptHelp(GenPkeyOptCtx *optCtx)
{
(void)optCtx;
HITLS_APP_OptHelpPrint(g_genPkeyOpts);
return HITLS_APP_HELP;
}
static CRYPT_EAL_PkeyCtx *GenRsaPkeyCtx(const GenPkeyOptPara *optPara)
{
return HITLS_APP_GenRsaPkeyCtx(optPara->bits);
}
static CRYPT_EAL_PkeyCtx *GenEcPkeyCtx(const GenPkeyOptPara *optPara)
{
CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA,
CRYPT_EAL_PKEY_UNKNOWN_OPERATE, "provider=default");
if (pkey == NULL) {
AppPrintError("genpkey: Failed to initialize the EC private key.\n");
return NULL;
}
if (CRYPT_EAL_PkeySetParaById(pkey, optPara->pkeyParaId) != CRYPT_SUCCESS) {
AppPrintError("genpkey: Failed to set EC parameters.\n");
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
if (CRYPT_EAL_PkeyGen(pkey) != CRYPT_SUCCESS) {
AppPrintError("genpkey: Failed to generate the EC private key.\n");
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
return pkey;
}
static CRYPT_EAL_PkeyCtx *GenMlDsaPkeyCtx(const GenPkeyOptPara *optPara)
{
// Validate that a parameter was set
if (optPara->pkeyParaId == CRYPT_PKEY_PARAID_MAX) {
AppPrintError("genpkey: ML-DSA parameter not specified. Use -pkeyopt mldsa_param:ML-DSA-XX\n");
AppPrintError("Supported parameters: ML-DSA-44, ML-DSA-65, ML-DSA-87\n");
return NULL;
}
// Validate the parameter is a valid ML-DSA variant
if (optPara->pkeyParaId != CRYPT_MLDSA_TYPE_MLDSA_44 &&
optPara->pkeyParaId != CRYPT_MLDSA_TYPE_MLDSA_65 &&
optPara->pkeyParaId != CRYPT_MLDSA_TYPE_MLDSA_87) {
AppPrintError("genpkey: Invalid ML-DSA parameter ID: %u\n", optPara->pkeyParaId);
return NULL;
}
CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA,
CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default");
if (pkey == NULL) {
AppPrintError("genpkey: Failed to initialize the ML-DSA private key.\n");
return NULL;
}
if (CRYPT_EAL_PkeySetParaById(pkey, optPara->pkeyParaId) != CRYPT_SUCCESS) {
AppPrintError("genpkey: Failed to set ML-DSA parameters (param ID: %u).\n", optPara->pkeyParaId);
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
if (CRYPT_EAL_PkeyGen(pkey) != CRYPT_SUCCESS) {
AppPrintError("genpkey: Failed to generate the ML-DSA private key.\n");
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
return pkey;
}
static int32_t GetRsaKeygenBits(const char *algorithm, const char *pkeyOptArg, uint32_t *bits)
{
uint32_t numBits = 0;
if ((strcasecmp(algorithm, "RSA") != 0) || (strlen(pkeyOptArg) <= RSA_KEYGEN_BITS_STR_LEN) ||
(HITLS_APP_OptGetUint32(pkeyOptArg + RSA_KEYGEN_BITS_STR_LEN, &numBits) != HITLS_APP_SUCCESS)) {
(void)AppPrintError("genpkey: The %s algorithm parameter %s is incorrect.\n", algorithm, pkeyOptArg);
return HITLS_APP_INVALID_ARG;
}
static const uint32_t numBitsArray[] = {1024, 2048, 3072, 4096};
for (size_t i = 0; i < sizeof(numBitsArray) / sizeof(numBitsArray[0]); i++) {
if (numBits == numBitsArray[i]) {
*bits = numBits;
return HITLS_APP_SUCCESS;
}
}
AppPrintError("genpkey: The RSA key length is error, supporting 1024、2048、3072、4096.\n");
return HITLS_APP_INVALID_ARG;
}
static int32_t GetParamGenCurve(const char *algorithm, const char *pkeyOptArg, uint32_t *pkeyParaId)
{
if ((strcasecmp(algorithm, "EC") != 0) || (strlen(pkeyOptArg) <= EC_PARAMGEN_CURVE_LEN)) {
(void)AppPrintError("genpkey: The %s algorithm parameter %s is incorrect.\n", algorithm, pkeyOptArg);
return HITLS_APP_INVALID_ARG;
}
const char *curesName = pkeyOptArg + EC_PARAMGEN_CURVE_LEN;
int32_t cid = HITLS_APP_GetCidByName(curesName, HITLS_APP_LIST_OPT_CURVES);
if (cid == CRYPT_PKEY_PARAID_MAX) {
(void)AppPrintError("genpkey: The %s algorithm parameter %s is incorrect, Use the [list -all-curves] command "
"to view supported curves.\n",
algorithm, pkeyOptArg);
return HITLS_APP_INVALID_ARG;
}
*pkeyParaId = cid;
return HITLS_APP_SUCCESS;
}
static int32_t GetMlDsaParam(const char *algorithm, const char *pkeyOptArg, uint32_t *pkeyParaId)
{
// Validate input parameters
if (algorithm == NULL || pkeyOptArg == NULL || pkeyParaId == NULL) {
(void)AppPrintError("genpkey: Internal error - NULL parameter passed to GetMlDsaParam.\n");
return HITLS_APP_INVALID_ARG;
}
// Validate algorithm type
if (strcasecmp(algorithm, "ML-DSA") != 0) {
(void)AppPrintError("genpkey: Algorithm mismatch - expected ML-DSA, got %s.\n", algorithm);
return HITLS_APP_INVALID_ARG;
}
// Validate parameter format
if (strlen(pkeyOptArg) <= MLDSA_PARAM_LEN) {
(void)AppPrintError("genpkey: ML-DSA parameter string too short: %s\n", pkeyOptArg);
(void)AppPrintError("Expected format: mldsa_param:ML-DSA-XX\n");
return HITLS_APP_INVALID_ARG;
}
// Validate parameter prefix
if (strncmp(pkeyOptArg, MLDSA_PARAM_STR, MLDSA_PARAM_LEN) != 0) {
(void)AppPrintError("genpkey: ML-DSA parameter must start with 'mldsa_param:'\n");
return HITLS_APP_INVALID_ARG;
}
const char *paramName = pkeyOptArg + MLDSA_PARAM_LEN;
// Validate parameter name is not empty
if (strlen(paramName) == 0) {
(void)AppPrintError("genpkey: ML-DSA parameter name is empty.\n"
"Supported parameters: ML-DSA-44, ML-DSA-65, ML-DSA-87\n");
return HITLS_APP_INVALID_ARG;
}
// Parse and validate ML-DSA variant
if (strcasecmp(paramName, "ML-DSA-44") == 0) {
*pkeyParaId = CRYPT_MLDSA_TYPE_MLDSA_44;
} else if (strcasecmp(paramName, "ML-DSA-65") == 0) {
*pkeyParaId = CRYPT_MLDSA_TYPE_MLDSA_65;
} else if (strcasecmp(paramName, "ML-DSA-87") == 0) {
*pkeyParaId = CRYPT_MLDSA_TYPE_MLDSA_87;
} else {
(void)AppPrintError("genpkey: ML-DSA parameter '%s' is not supported.\n", paramName);
(void)AppPrintError("Supported parameters: ML-DSA-44, ML-DSA-65, ML-DSA-87\n");
return HITLS_APP_INVALID_ARG;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetPkeyPara(GenPkeyOptCtx *optCtx)
{
if (optCtx->genPkeyCtxFunc == NULL) {
(void)AppPrintError("genpkey: Algorithm not specified.\n");
return HITLS_APP_INVALID_ARG;
}
for (uint32_t i = 0; i < optCtx->inPara.pkeyOptArgNum; ++i) {
if (optCtx->inPara.pkeyOptArg[i] == NULL) {
return HITLS_APP_INVALID_ARG;
}
char *algorithm = optCtx->inPara.algorithm;
char *pkeyOptArg = optCtx->inPara.pkeyOptArg[i];
// rsa_keygen_bits:numbits
if (strncmp(pkeyOptArg, RSA_KEYGEN_BITS_STR, RSA_KEYGEN_BITS_STR_LEN) == 0) {
return GetRsaKeygenBits(algorithm, pkeyOptArg, &optCtx->genPkeyOptPara.bits);
} else if (strncmp(pkeyOptArg, EC_PARAMGEN_CURVE_STR, EC_PARAMGEN_CURVE_LEN) == 0) {
// ec_paramgen_curve:curve
return GetParamGenCurve(algorithm, pkeyOptArg, &optCtx->genPkeyOptPara.pkeyParaId);
} else if (strncmp(pkeyOptArg, MLDSA_PARAM_STR, MLDSA_PARAM_LEN) == 0) {
// mldsa_param:ML-DSA-44/ML-DSA-65/ML-DSA-87
return GetMlDsaParam(algorithm, pkeyOptArg, &optCtx->genPkeyOptPara.pkeyParaId);
} else {
(void)AppPrintError("genpkey: The %s algorithm parameter %s is incorrect.\n", algorithm, pkeyOptArg);
return HITLS_APP_INVALID_ARG;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t GenPkeyOptAlgorithm(GenPkeyOptCtx *optCtx)
{
optCtx->inPara.algorithm = HITLS_APP_OptGetValueStr();
if (strcasecmp(optCtx->inPara.algorithm, "RSA") == 0) {
optCtx->genPkeyCtxFunc = GenRsaPkeyCtx;
} else if (strcasecmp(optCtx->inPara.algorithm, "EC") == 0) {
optCtx->genPkeyCtxFunc = GenEcPkeyCtx;
} else if (strcasecmp(optCtx->inPara.algorithm, "ML-DSA") == 0) {
optCtx->genPkeyCtxFunc = GenMlDsaPkeyCtx;
} else {
(void)AppPrintError("genpkey: The %s algorithm is not supported.\n"
"Supported algorithms: RSA, EC, ML-DSA\n", optCtx->inPara.algorithm);
return HITLS_APP_INVALID_ARG;
}
return HITLS_APP_SUCCESS;
}
static int32_t GenPkeyOpt(GenPkeyOptCtx *optCtx)
{
if (optCtx->inPara.pkeyOptArgNum >= MAX_PKEY_OPT_ARG) {
return HITLS_APP_INVALID_ARG;
}
optCtx->inPara.pkeyOptArg[optCtx->inPara.pkeyOptArgNum] = HITLS_APP_OptGetValueStr();
++(optCtx->inPara.pkeyOptArgNum);
return HITLS_APP_SUCCESS;
}
static int32_t GenPkeyOptCipher(GenPkeyOptCtx *optCtx)
{
const char *name = HITLS_APP_OptGetUnKownOptName();
return HITLS_APP_GetAndCheckCipherOpt(name, &optCtx->cipherAlgCid);
}
static int32_t GenPkeyOptPassout(GenPkeyOptCtx *optCtx)
{
optCtx->outPara.passOutArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t GenPkeyOptOut(GenPkeyOptCtx *optCtx)
{
optCtx->outPara.outFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t GenPkeyOptPubOut(GenPkeyOptCtx *optCtx)
{
optCtx->outPara.pubOut = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t GenPkeyOptOutForm(GenPkeyOptCtx *optCtx)
{
char *format = HITLS_APP_OptGetValueStr();
if (strcasecmp(format, "PEM") == 0) {
optCtx->outPara.outFormat = BSL_FORMAT_PEM;
} else if (strcasecmp(format, "DER") == 0) {
optCtx->outPara.outFormat = BSL_FORMAT_ASN1;
} else {
(void)AppPrintError("genpkey: Invalid output format %s. Supported formats: PEM, DER\n", format);
return HITLS_APP_INVALID_ARG;
}
return HITLS_APP_SUCCESS;
}
static const GenPkeyOptHandleTable g_genPkeyOptHandleTable[] = {
{HITLS_APP_OPT_ERR, GenPkeyOptErr},
{HITLS_APP_OPT_HELP, GenPkeyOptHelp},
{HITLS_APP_OPT_ALGORITHM, GenPkeyOptAlgorithm},
{HITLS_APP_OPT_PKEYOPT, GenPkeyOpt},
{HITLS_APP_OPT_CIPHER_ALG, GenPkeyOptCipher},
{HITLS_APP_OPT_PASS, GenPkeyOptPassout},
{HITLS_APP_OPT_PUBOUT, GenPkeyOptPubOut},
{HITLS_APP_OPT_OUT, GenPkeyOptOut},
{HITLS_APP_OPT_OUTFORM, GenPkeyOptOutForm},
};
static int32_t ParseGenPkeyOpt(GenPkeyOptCtx *optCtx)
{
int32_t ret = HITLS_APP_SUCCESS;
int optType = HITLS_APP_OPT_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF)) {
for (size_t i = 0; i < (sizeof(g_genPkeyOptHandleTable) / sizeof(g_genPkeyOptHandleTable[0])); ++i) {
if (optType == g_genPkeyOptHandleTable[i].optType) {
ret = g_genPkeyOptHandleTable[i].func(optCtx);
break;
}
}
}
// Obtain the number of parameters that cannot be parsed in the current version,
// and print the error inFormation and help list.
if ((ret == HITLS_APP_SUCCESS) && (HITLS_APP_GetRestOptNum() != 0)) {
AppPrintError("Extra arguments given.\n");
AppPrintError("genpkey: Use -help for summary.\n");
ret = HITLS_APP_OPT_UNKOWN;
}
return ret;
}
static int32_t HandleGenPkeyOpt(GenPkeyOptCtx *optCtx)
{
int32_t ret = ParseGenPkeyOpt(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// 1. SetPkeyPara
if (SetPkeyPara(optCtx) != HITLS_APP_SUCCESS) {
return HITLS_APP_INVALID_ARG;
}
// 2. Read Password
if (HITLS_APP_ParsePasswd(optCtx->outPara.passOutArg, &optCtx->passout) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
// 3. Gen private key
optCtx->pkey = optCtx->genPkeyCtxFunc(&optCtx->genPkeyOptPara);
if (optCtx->pkey == NULL) {
return HITLS_APP_LOAD_KEY_FAIL;
}
if (optCtx->outPara.pubOut != NULL) {
ret = HITLS_APP_PrintPubKey(optCtx->pkey, optCtx->outPara.pubOut, optCtx->outPara.outFormat);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
}
// 4. Output the private key.
return HITLS_APP_PrintPrvKey(optCtx->pkey, optCtx->outPara.outFilePath, optCtx->outPara.outFormat,
optCtx->cipherAlgCid, &optCtx->passout);
}
static void InitGenPkeyOptCtx(GenPkeyOptCtx *optCtx)
{
optCtx->pkey = NULL;
optCtx->genPkeyCtxFunc = NULL;
optCtx->genPkeyOptPara.bits = DEFAULT_RSA_KEYGEN_BITS;
optCtx->genPkeyOptPara.pkeyParaId = CRYPT_PKEY_PARAID_MAX;
optCtx->passout = NULL;
optCtx->cipherAlgCid = CRYPT_CIPHER_MAX;
optCtx->inPara.algorithm = NULL;
memset_s(optCtx->inPara.pkeyOptArg, MAX_PKEY_OPT_ARG, 0, MAX_PKEY_OPT_ARG);
optCtx->inPara.pkeyOptArgNum = 0;
optCtx->outPara.outFilePath = NULL;
optCtx->outPara.passOutArg = NULL;
optCtx->outPara.pubOut = NULL;
optCtx->outPara.outFormat = BSL_FORMAT_PEM; // Default to PEM format
}
static void UnInitGenPkeyOptCtx(GenPkeyOptCtx *optCtx)
{
CRYPT_EAL_PkeyFreeCtx(optCtx->pkey);
optCtx->pkey = NULL;
if (optCtx->passout != NULL) {
BSL_SAL_ClearFree(optCtx->passout, strlen(optCtx->passout));
}
}
// genpkey main function
int32_t HITLS_GenPkeyMain(int argc, char *argv[])
{
GenPkeyOptCtx optCtx = {};
InitGenPkeyOptCtx(&optCtx);
int32_t ret = HITLS_APP_SUCCESS;
do {
ret = HITLS_APP_OptBegin(argc, argv, g_genPkeyOpts);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
break;
}
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR,
"provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) {
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = HandleGenPkeyOpt(&optCtx);
} while (false);
CRYPT_EAL_RandDeinitEx(NULL);
HITLS_APP_OptEnd();
UnInitGenPkeyOptCtx(&optCtx);
return ret;
} | 2401_83913325/openHiTLS_1 | apps/src/app_genpkey.c | C | unknown | 17,314 |
/*
* 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 "app_genrsa.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <termios.h>
#include <unistd.h>
#include <securec.h>
#include <limits.h>
#include "bsl_ui.h"
#include "bsl_uio.h"
#include "app_utils.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_errno.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_algid.h"
#include "crypt_types.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_pkey.h"
#include "crypt_util_rand.h"
#include "crypt_eal_codecs.h"
typedef enum {
HITLS_APP_OPT_NUMBITS = 0,
HITLS_APP_OPT_CIPHER = 2,
HITLS_APP_OPT_OUT_FILE,
} HITLSOptType;
typedef struct {
char *outFile;
long numBits; // Indicates the length of the private key entered by the user.
int32_t cipherId; // Indicates the symmetric encryption algorithm ID entered by the user.
} GenrsaInOpt;
const HITLS_CmdOption g_genrsaOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"cipher", HITLS_APP_OPT_CIPHER, HITLS_APP_OPT_VALUETYPE_STRING, "Secret key cryptography"},
{"out", HITLS_APP_OPT_OUT_FILE, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output the rsa key to specified file"},
{"numbits", HITLS_APP_OPT_NUMBITS, HITLS_APP_OPT_VALUETYPE_PARAMTERS, "RSA key length, command line tail value"},
{NULL, 0, 0, NULL}
};
uint8_t g_e[] = {0x01, 0x00, 0x01}; // Default E value
const uint32_t g_numBitsArray[] = {1024, 2048, 3072, 4096};
const HITLS_APPAlgList g_IdList[] = {
{CRYPT_CIPHER_AES128_CBC, "aes128-cbc"},
{CRYPT_CIPHER_AES192_CBC, "aes192-cbc"},
{CRYPT_CIPHER_AES256_CBC, "aes256-cbc"},
{CRYPT_CIPHER_AES128_XTS, "aes128-xts"},
{CRYPT_CIPHER_AES256_XTS, "aes256-xts"},
{CRYPT_CIPHER_SM4_XTS, "sm4-xts"},
{CRYPT_CIPHER_SM4_CBC, "sm4-cbc"},
{CRYPT_CIPHER_SM4_CTR, "sm4-ctr"},
{CRYPT_CIPHER_SM4_CFB, "sm4-cfb"},
{CRYPT_CIPHER_SM4_OFB, "sm4-ofb"},
{CRYPT_CIPHER_AES128_CFB, "aes128-cfb"},
{CRYPT_CIPHER_AES192_CFB, "aes192-cfb"},
{CRYPT_CIPHER_AES256_CFB, "aes256-cfb"},
{CRYPT_CIPHER_AES128_OFB, "aes128-ofb"},
{CRYPT_CIPHER_AES192_OFB, "aes192-ofb"},
{CRYPT_CIPHER_AES256_OFB, "aes256-ofb"},
};
static void PrintAlgList(void)
{
AppPrintError("The current version supports only the following Pkey algorithms:\n");
for (size_t i = 0; i < sizeof(g_IdList) / sizeof(g_IdList[0]); i++) {
AppPrintError("%-19s", g_IdList[i].algName);
// Four algorithm names are displayed in each row.
if ((i + 1) % REC_ALG_NUM_EACHLINE == 0 && i != sizeof(g_IdList) - 1) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return;
}
static int32_t GetAlgId(const char *name)
{
for (size_t i = 0; i < sizeof(g_IdList) / sizeof(g_IdList[0]); i++) {
if (strcmp(g_IdList[i].algName, name) == 0) {
return g_IdList[i].id;
}
}
(void)PrintAlgList();
return -1;
}
int32_t HITLS_APP_Passwd(char *buf, int32_t bufMaxLen, int32_t flag, void *userdata)
{
int32_t errLen = -1;
if (buf == NULL) {
return errLen;
}
int32_t cbRet = HITLS_APP_SUCCESS;
uint32_t bufLen = bufMaxLen;
BSL_UI_ReadPwdParam param = {"password", NULL, flag};
if (userdata == NULL) {
cbRet = BSL_UI_ReadPwdUtil(¶m, buf, &bufLen, HITLS_APP_DefaultPassCB, NULL);
if (cbRet == BSL_UI_READ_BUFF_TOO_LONG || cbRet == BSL_UI_READ_LEN_TOO_SHORT) {
(void)memset_s(buf, bufMaxLen, 0, bufMaxLen);
HITLS_APP_PrintPassErrlog();
return errLen;
}
if (cbRet != BSL_SUCCESS) {
(void)memset_s(buf, bufMaxLen, 0, bufMaxLen);
return errLen;
}
bufLen -= 1;
buf[bufLen] = '\0';
cbRet = HITLS_APP_CheckPasswd((uint8_t *)buf, bufLen);
if (cbRet != HITLS_APP_SUCCESS) {
(void)memset_s(buf, bufMaxLen, 0, bufMaxLen);
return errLen;
}
} else if (userdata != NULL) {
if (strlen(userdata) > APP_MAX_PASS_LENGTH) {
HITLS_APP_PrintPassErrlog();
return errLen;
}
cbRet = HITLS_APP_CheckPasswd((uint8_t *)userdata, strlen(userdata));
if (cbRet != HITLS_APP_SUCCESS) {
return errLen;
}
if (strncpy_s(buf, bufMaxLen, (char *)userdata, strlen(userdata)) != EOK) {
(void)memset_s(buf, bufMaxLen, 0, bufMaxLen);
return errLen;
}
bufLen = strlen(buf);
}
return bufLen;
}
static int32_t HandleOpt(GenrsaInOpt *opt)
{
int32_t optType;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
switch (optType) {
case HITLS_APP_OPT_EOF:
break;
case HITLS_APP_OPT_ERR:
AppPrintError("genrsa: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_OPT_HELP:
HITLS_APP_OptHelpPrint(g_genrsaOpts);
return HITLS_APP_HELP;
case HITLS_APP_OPT_CIPHER:
if ((opt->cipherId = GetAlgId(HITLS_APP_OptGetValueStr())) == -1) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_OUT_FILE:
opt->outFile = HITLS_APP_OptGetValueStr();
break;
default:
break;
}
}
// Obtains the value of the last digit numbits.
int32_t restOptNum = HITLS_APP_GetRestOptNum();
if (restOptNum == 1) {
char **numbits = HITLS_APP_GetRestOpt();
if (HITLS_APP_OptGetLong(numbits[0], &opt->numBits) != HITLS_APP_SUCCESS) {
return HITLS_APP_OPT_VALUE_INVALID;
}
} else {
if (restOptNum > 1) {
(void)AppPrintError("Extra arguments given.\n");
} else {
(void)AppPrintError("The command is incorrectly used.\n");
}
AppPrintError("genrsa: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
static bool IsNumBitsValid(long num)
{
for (size_t i = 0; i < sizeof(g_numBitsArray) / sizeof(g_numBitsArray[0]); i++) {
if (num == g_numBitsArray[i]) {
return true;
}
}
return false;
}
static int32_t CheckPara(GenrsaInOpt *opt, BSL_UIO *outUio)
{
if (opt->cipherId == -1) {
AppPrintError("The command is incorrectly used.\n");
AppPrintError("genrsa: Use -help for summary.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
// Check whether the RSA key length (in bits) of the private key complies with the specifications.
// The length must be greater than or equal to 1024.
if (!IsNumBitsValid(opt->numBits)) {
AppPrintError("Your RSA key length is %ld.\n", opt->numBits);
AppPrintError("The RSA key length is error, supporting 1024、2048、3072、4096.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
// Obtains the post-value of the OUT option. If there is no post-value or this option, stdout.
if (opt->outFile == NULL) {
if (BSL_UIO_Ctrl(outUio, BSL_UIO_FILE_PTR, 0, (void *)stdout) != BSL_SUCCESS) {
AppPrintError("Failed to set stdout mode.\n");
return HITLS_APP_UIO_FAIL;
}
} else {
// User input file path, which is bound to the output file.
if (strlen(opt->outFile) >= PATH_MAX || strlen(opt->outFile) == 0) {
AppPrintError("The length of outfile error, range is (0, 4096].\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (BSL_UIO_Ctrl(outUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_WRITE, opt->outFile) != BSL_SUCCESS) {
AppPrintError("Failed to set outfile mode.\n");
return HITLS_APP_UIO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
static CRYPT_EAL_PkeyPara *PkeyNewRsaPara(uint8_t *e, uint32_t eLen, uint32_t bits)
{
CRYPT_EAL_PkeyPara *para = BSL_SAL_Calloc(1, sizeof(CRYPT_EAL_PkeyPara));
if (para == NULL) {
return NULL;
}
para->id = CRYPT_PKEY_RSA;
para->para.rsaPara.bits = bits;
para->para.rsaPara.e = e;
para->para.rsaPara.eLen = eLen;
return para;
}
static int32_t HandlePkey(GenrsaInOpt *opt, char *resBuf, uint32_t bufLen)
{
int32_t ret = HITLS_APP_SUCCESS;
// Setting the Entropy Source
(void)CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default", NULL, 0, NULL);
CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_RSA,
CRYPT_EAL_PKEY_UNKNOWN_OPERATE, "provider=default");
if (pkey == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_PkeyPara *pkeyParam = NULL;
pkeyParam = PkeyNewRsaPara(g_e, sizeof(g_e), opt->numBits);
if (pkeyParam == NULL) {
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto hpEnd;
}
if (CRYPT_EAL_PkeySetPara(pkey, pkeyParam) != CRYPT_SUCCESS) {
ret = HITLS_APP_CRYPTO_FAIL;
goto hpEnd;
}
if (CRYPT_EAL_PkeyGen(pkey) != CRYPT_SUCCESS) {
ret = HITLS_APP_CRYPTO_FAIL;
goto hpEnd;
}
char pwd[APP_MAX_PASS_LENGTH + 1] = {0};
int32_t pwdLen = HITLS_APP_Passwd(pwd, APP_MAX_PASS_LENGTH + 1, 1, NULL);
if (pwdLen == -1) {
ret = HITLS_APP_PASSWD_FAIL;
goto hpEnd;
}
CRYPT_Pbkdf2Param pbkdfParam = {BSL_CID_PBES2, BSL_CID_PBKDF2, CRYPT_MAC_HMAC_SHA1,
opt->cipherId, 16, (uint8_t *)pwd, pwdLen, 2048};
CRYPT_EncodeParam encodeParam = {CRYPT_DERIVE_PBKDF2, &pbkdfParam};
BSL_Buffer encode = {0};
ret = CRYPT_EAL_EncodeBuffKey(pkey, &encodeParam, BSL_FORMAT_PEM, CRYPT_PRIKEY_PKCS8_ENCRYPT, &encode);
(void)memset_s(pwd, APP_MAX_PASS_LENGTH, 0, APP_MAX_PASS_LENGTH);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("Encode failed.\n");
ret = HITLS_APP_ENCODE_FAIL;
goto hpEnd;
}
if (memcpy_s(resBuf, bufLen, encode.data, encode.dataLen) != EOK) {
ret = HITLS_APP_SECUREC_FAIL;
}
BSL_SAL_FREE(encode.data);
hpEnd:
CRYPT_EAL_RandDeinitEx(NULL);
BSL_SAL_ClearFree(pkeyParam, sizeof(CRYPT_EAL_PkeyPara));
CRYPT_EAL_PkeyFreeCtx(pkey);
return ret;
}
int32_t HITLS_GenRSAMain(int argc, char *argv[])
{
GenrsaInOpt opt = {NULL, -1, -1};
BSL_UIO *outUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (outUio == NULL) {
AppPrintError("Failed to create the output UIO.\n");
return HITLS_APP_UIO_FAIL;
}
int32_t ret = HITLS_APP_SUCCESS;
if ((ret = HITLS_APP_OptBegin(argc, argv, g_genrsaOpts)) != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
goto GenRsaEnd;
}
if ((ret = HandleOpt(&opt)) != HITLS_APP_SUCCESS) {
goto GenRsaEnd;
}
if ((ret = CheckPara(&opt, outUio)) != HITLS_APP_SUCCESS) {
goto GenRsaEnd;
}
char resBuf[REC_MAX_PEM_FILELEN] = {0};
uint32_t bufLen = sizeof(resBuf);
uint32_t writeLen = 0;
if ((ret = HandlePkey(&opt, resBuf, bufLen)) != HITLS_APP_SUCCESS) {
goto GenRsaEnd;
}
if (BSL_UIO_Write(outUio, resBuf, strlen(resBuf), &writeLen) != BSL_SUCCESS || writeLen == 0) {
ret = HITLS_APP_UIO_FAIL;
goto GenRsaEnd;
}
ret = HITLS_APP_SUCCESS;
GenRsaEnd:
if (opt.outFile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(outUio, true);
}
BSL_UIO_Free(outUio);
HITLS_APP_OptEnd();
return ret;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_genrsa.c | C | unknown | 12,036 |
/*
* 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 "app_help.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_function.h"
HITLS_CmdOption g_helpOptions[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Usage: help [options]"},
{NULL, 0, 0, NULL}
};
int HITLS_HelpMain(int argc, char *argv[])
{
if (argc == 1) {
AppPrintFuncList();
return HITLS_APP_SUCCESS;
}
HITLS_OptChoice oc;
int32_t ret = HITLS_APP_OptBegin(argc, argv, g_helpOptions);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
HITLS_APP_OptEnd();
return ret;
}
while ((oc = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
switch (oc) {
case HITLS_APP_OPT_ERR:
AppPrintError("help: Use -help for summary.\n");
HITLS_APP_OptEnd();
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_OPT_HELP:
HITLS_APP_OptHelpPrint(g_helpOptions);
HITLS_APP_OptEnd();
return HITLS_APP_SUCCESS;
default:
AppPrintError("help: Use -help for summary.\n");
HITLS_APP_OptEnd();
return HITLS_APP_OPT_UNKOWN;
}
}
if (HITLS_APP_GetRestOptNum() != 1) {
AppPrintError("Please enter help to obtain the support list.\n");
HITLS_APP_OptEnd();
return HITLS_APP_OPT_VALUE_INVALID;
}
HITLS_CmdFunc func = { 0 };
char *proName = HITLS_APP_GetRestOpt()[0];
HITLS_APP_OptEnd();
ret = AppGetProgFunc(proName, &func);
if (ret != 0) {
AppPrintError("Please enter help to obtain the support list.\n");
return ret;
}
char *newArgv[3] = {proName, "--help", NULL};
int newArgc = 2;
return func.main(newArgc, newArgv);
} | 2401_83913325/openHiTLS_1 | apps/src/app_help.c | C | unknown | 2,370 |
/*
* 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 "app_kdf.h"
#include <limits.h>
#include "string.h"
#include "securec.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_eal_kdf.h"
#include "crypt_params_key.h"
#include "bsl_errno.h"
#include "bsl_params.h"
#include "app_opt.h"
#include "app_function.h"
#include "app_list.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_provider.h"
#include "app_sm.h"
#include "app_utils.h"
typedef enum OptionChoice {
HITLS_APP_OPT_KDF_ERR = -1,
HITLS_APP_OPT_KDF_EOF = 0,
HITLS_APP_OPT_KDF_ALG = HITLS_APP_OPT_KDF_EOF,
HITLS_APP_OPT_KDF_HELP = 1, // The value of the help type of each opt option is 1. The following can be customized.
HITLS_APP_OPT_KDF_KEYLEN,
HITLS_APP_OPT_KDF_MAC_ALG,
HITLS_APP_OPT_KDF_OUT,
HITLS_APP_OPT_KDF_PASS,
HITLS_APP_OPT_KDF_HEXPASS,
HITLS_APP_OPT_KDF_SALT,
HITLS_APP_OPT_KDF_HEXSALT,
HITLS_APP_OPT_KDF_ITER,
HITLS_APP_OPT_KDF_BINARY,
HITLS_APP_PROV_ENUM,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS_ENUM,
#endif
} HITLSOptType;
const HITLS_CmdOption g_kdfOpts[] = {
{"help", HITLS_APP_OPT_KDF_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Show usage information for KDF command."},
{"mac", HITLS_APP_OPT_KDF_MAC_ALG, HITLS_APP_OPT_VALUETYPE_STRING,
"Specify MAC algorithm used in KDF (e.g.: hmac-sha256)."},
{"out", HITLS_APP_OPT_KDF_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE,
"Set output file for derived key (default: stdout, hex format)."},
{"binary", HITLS_APP_OPT_KDF_BINARY, HITLS_APP_OPT_VALUETYPE_NO_VALUE,
"Output derived key in binary format."},
{"keylen", HITLS_APP_OPT_KDF_KEYLEN, HITLS_APP_OPT_VALUETYPE_UINT, "Length of derived key in bytes."},
{"pass", HITLS_APP_OPT_KDF_PASS, HITLS_APP_OPT_VALUETYPE_STRING, "Input password as a string."},
{"hexpass", HITLS_APP_OPT_KDF_HEXPASS, HITLS_APP_OPT_VALUETYPE_STRING,
"Input password in hexadecimal format (e.g.: 0x1234ABCD)."},
{"salt", HITLS_APP_OPT_KDF_SALT, HITLS_APP_OPT_VALUETYPE_STRING, "Input salt as a string."},
{"hexsalt", HITLS_APP_OPT_KDF_HEXSALT, HITLS_APP_OPT_VALUETYPE_STRING,
"Input salt in hexadecimal format (e.g.: 0xAABBCCDD)."},
{"iter", HITLS_APP_OPT_KDF_ITER, HITLS_APP_OPT_VALUETYPE_UINT, "Number of iterations for KDF computation."},
HITLS_APP_PROV_OPTIONS,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS,
#endif
{"kdfalg...", HITLS_APP_OPT_KDF_ALG, HITLS_APP_OPT_VALUETYPE_PARAMTERS, "Specify KDF algorithm (e.g.: pbkdf2)."},
{NULL, 0, 0, NULL}};
typedef struct {
int32_t macId;
char *kdfName;
int32_t kdfId;
uint32_t keyLen;
char *outFile;
char *pass;
char *hexPass;
char *salt;
char *hexSalt;
uint32_t iter;
AppProvider *provider;
uint32_t isBinary;
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param *smParam;
#endif
} KdfOpt;
typedef int32_t (*KdfOptHandleFunc)(KdfOpt *);
typedef struct {
int optType;
KdfOptHandleFunc func;
} KdfOptHandleFuncMap;
static int32_t HandleKdfErr(KdfOpt *kdfOpt)
{
(void)kdfOpt;
AppPrintError("kdf: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t HandleKdfHelp(KdfOpt *kdfOpt)
{
(void)kdfOpt;
HITLS_APP_OptHelpPrint(g_kdfOpts);
return HITLS_APP_HELP;
}
static int32_t HandleKdfOut(KdfOpt *kdfOpt)
{
kdfOpt->outFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfPass(KdfOpt *kdfOpt)
{
kdfOpt->pass = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfHexPass(KdfOpt *kdfOpt)
{
kdfOpt->hexPass = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfSalt(KdfOpt *kdfOpt)
{
kdfOpt->salt = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfHexSalt(KdfOpt *kdfOpt)
{
kdfOpt->hexSalt = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfIter(KdfOpt *kdfOpt)
{
int32_t ret = HITLS_APP_OptGetUint32(HITLS_APP_OptGetValueStr(), &(kdfOpt->iter));
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("kdf: Invalid iter value.\n");
}
return ret;
}
static int32_t HandleKdfKeyLen(KdfOpt *kdfOpt)
{
int32_t ret = HITLS_APP_OptGetUint32(HITLS_APP_OptGetValueStr(), &(kdfOpt->keyLen));
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("kdf: Invalid keylen value.\n");
}
return ret;
}
static int32_t HandleKdfBinary(KdfOpt *kdfOpt)
{
kdfOpt->isBinary = 1;
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfMacAlg(KdfOpt *kdfOpt)
{
char *macName = HITLS_APP_OptGetValueStr();
if (macName == NULL) {
AppPrintError("kdf: MAC algorithm is NULL.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
kdfOpt->macId = HITLS_APP_GetCidByName(macName, HITLS_APP_LIST_OPT_MAC_ALG);
if (kdfOpt->macId == BSL_CID_UNKNOWN) {
AppPrintError("kdf: Unsupported MAC algorithm: %s\n", macName);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static const KdfOptHandleFuncMap g_kdfOptHandleFuncMap[] = {
{HITLS_APP_OPT_KDF_ERR, HandleKdfErr},
{HITLS_APP_OPT_KDF_HELP, HandleKdfHelp},
{HITLS_APP_OPT_KDF_OUT, HandleKdfOut},
{HITLS_APP_OPT_KDF_PASS, HandleKdfPass},
{HITLS_APP_OPT_KDF_HEXPASS, HandleKdfHexPass},
{HITLS_APP_OPT_KDF_SALT, HandleKdfSalt},
{HITLS_APP_OPT_KDF_HEXSALT, HandleKdfHexSalt},
{HITLS_APP_OPT_KDF_ITER, HandleKdfIter},
{HITLS_APP_OPT_KDF_KEYLEN, HandleKdfKeyLen},
{HITLS_APP_OPT_KDF_MAC_ALG, HandleKdfMacAlg},
{HITLS_APP_OPT_KDF_BINARY, HandleKdfBinary},
};
static int32_t ParseKdfOpt(KdfOpt *kdfOpt)
{
int ret = HITLS_APP_SUCCESS;
int optType = HITLS_APP_OPT_KDF_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_KDF_EOF)) {
for (size_t i = 0; i < (sizeof(g_kdfOptHandleFuncMap) / sizeof(g_kdfOptHandleFuncMap[0])); ++i) {
if (optType == g_kdfOptHandleFuncMap[i].optType) {
ret = g_kdfOptHandleFuncMap[i].func(kdfOpt);
break;
}
}
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
HITLS_APP_PROV_CASES(optType, kdfOpt->provider)
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_CASES(optType, kdfOpt->smParam);
#endif
}
return HITLS_APP_SUCCESS;
}
static int32_t GetKdfAlg(KdfOpt *kdfOpt)
{
int32_t argc = HITLS_APP_GetRestOptNum();
char **argv = HITLS_APP_GetRestOpt();
if (argc == 0) {
AppPrintError("Please input KDF algorithm.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
kdfOpt->kdfName = argv[0];
kdfOpt->kdfId = HITLS_APP_GetCidByName(kdfOpt->kdfName, HITLS_APP_LIST_OPT_KDF_ALG);
if (kdfOpt->kdfId == BSL_CID_UNKNOWN) {
AppPrintError("Not support KDF algorithm.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (argc - 1 != 0) {
AppPrintError("Extra arguments given.\n");
AppPrintError("kdf: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckSmParam(KdfOpt *kdfOpt)
{
#ifdef HITLS_APP_SM_MODE
if (kdfOpt->smParam->smTag == 1 && kdfOpt->smParam->workPath == NULL) {
AppPrintError("kdf: The workpath is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
#else
(void)kdfOpt;
#endif
return HITLS_APP_SUCCESS;
}
static int32_t CheckParam(KdfOpt *kdfOpt)
{
int32_t ret = CheckSmParam(kdfOpt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (kdfOpt->kdfId == CRYPT_KDF_PBKDF2) {
if (kdfOpt->pass == NULL && kdfOpt->hexPass == NULL) {
AppPrintError("kdf: No pass entered.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (kdfOpt->pass != NULL && kdfOpt->hexPass != NULL) {
AppPrintError("kdf: Cannot specify both pass and hexpass.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (kdfOpt->salt == NULL && kdfOpt->hexSalt == NULL) {
AppPrintError("kdf: No salt entered.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (kdfOpt->salt != NULL && kdfOpt->hexSalt != NULL) {
AppPrintError("kdf: Cannot specify both salt and hexsalt.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
}
if (kdfOpt->keyLen == 0) {
AppPrintError("kdf: Input keylen is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (kdfOpt->iter == 0) {
AppPrintError("kdf: Input iter is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (kdfOpt->outFile != NULL && strlen((const char*)kdfOpt->outFile) > PATH_MAX) {
AppPrintError("kdf: The output file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static CRYPT_EAL_KdfCTX *InitAlgKdf(KdfOpt *kdfOpt)
{
CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_ProviderKdfNewCtx(APP_GetCurrent_LibCtx(), kdfOpt->kdfId,
kdfOpt->provider->providerAttr);
if (ctx == NULL) {
(void)AppPrintError("Failed to create the algorithm(%s) context\n", kdfOpt->kdfName);
}
return ctx;
}
static int32_t KdfParsePass(KdfOpt *kdfOpt, uint8_t **pass, uint32_t *passLen)
{
size_t len;
if (kdfOpt->pass != NULL) {
len = strlen((const char *)kdfOpt->pass);
} else {
len = strlen((const char *)kdfOpt->hexPass);
}
if (len > UINT32_MAX) {
AppPrintError("kdf: pass length overflow.\n");
return HITLS_APP_INVALID_ARG;
}
if (kdfOpt->pass != NULL) {
*passLen = (uint32_t)len;
*pass = (uint8_t *)kdfOpt->pass;
} else {
int32_t ret = HITLS_APP_HexToByte(kdfOpt->hexPass, pass, passLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("kdf:Invalid pass: %s.\n", kdfOpt->hexPass);
return ret;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t KdfParseSalt(KdfOpt *kdfOpt, uint8_t **salt, uint32_t *saltLen)
{
size_t len;
if (kdfOpt->salt != NULL) {
len = strlen((const char *)kdfOpt->salt);
} else {
len = strlen((const char *)kdfOpt->hexSalt);
}
if (len > UINT32_MAX) {
AppPrintError("kdf: salt length overflow.\n");
return HITLS_APP_INVALID_ARG;
}
if (kdfOpt->salt != NULL) {
*saltLen = (uint32_t)len;
*salt = (uint8_t *)kdfOpt->salt;
} else {
int32_t ret = HITLS_APP_HexToByte(kdfOpt->hexSalt, salt, saltLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("kdf:Invalid salt: %s.\n", kdfOpt->hexSalt);
return ret;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t Pbkdf2Params(CRYPT_EAL_KdfCTX *ctx, BSL_Param *params, KdfOpt *kdfOpt)
{
uint32_t index = 0;
uint8_t *pass = NULL;
uint32_t passLen = 0;
uint8_t *salt = NULL;
uint32_t saltLen = 0;
int32_t ret = HITLS_APP_SUCCESS;
do {
ret = KdfParsePass(kdfOpt, &pass, &passLen);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = KdfParseSalt(kdfOpt, &salt, &saltLen);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32,
&(kdfOpt->macId), sizeof(kdfOpt->macId));
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("kdf:Init macId failed. ERROR:%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, pass, passLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("kdf:Init pass failed. ERROR:%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("kdf:Init salt failed. ERROR:%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32,
&kdfOpt->iter, sizeof(kdfOpt->iter));
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("kdf:Init iter failed. ERROR:%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = CRYPT_EAL_KdfSetParam(ctx, params);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("kdf:KdfSetParam failed. ERROR:%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
}
} while (0);
if (kdfOpt->salt == NULL) {
BSL_SAL_FREE(salt);
}
if (kdfOpt->pass == NULL) {
BSL_SAL_ClearFree(pass, passLen);
}
return ret;
}
static int32_t PbkdfParamSet(CRYPT_EAL_KdfCTX *ctx, KdfOpt *kdfOpt)
{
if (kdfOpt->kdfId == CRYPT_KDF_PBKDF2) {
BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END};
return Pbkdf2Params(ctx, params, kdfOpt);
}
(void)AppPrintError("kdf: Unsupported KDF algorithm: %s\n", kdfOpt->kdfName);
return HITLS_APP_OPT_VALUE_INVALID;
}
static int32_t KdfResult(CRYPT_EAL_KdfCTX *ctx, KdfOpt *kdfOpt)
{
uint8_t *out = NULL;
uint32_t outLen = kdfOpt->keyLen;
int32_t ret = PbkdfParamSet(ctx, kdfOpt);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("PbkdfParamSet failed. \n");
return ret;
}
#ifdef HITLS_APP_SM_MODE
kdfOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
#endif
out = BSL_SAL_Malloc(outLen);
if (out == NULL) {
(void)AppPrintError("kdf: Allocate memory failed. \n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
ret = CRYPT_EAL_KdfDerive(ctx, out, outLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("KdfDeriv failed. ERROR:%d\n", ret);
BSL_SAL_ClearFree(out, outLen);
return HITLS_APP_CRYPTO_FAIL;
}
BSL_UIO *fileOutUio = HITLS_APP_UioOpen(kdfOpt->outFile, 'w', 0);
if (fileOutUio == NULL) {
BSL_SAL_ClearFree(out, outLen);
(void)AppPrintError("kdf:UioOpen failed\n");
return HITLS_APP_UIO_FAIL;
}
if (kdfOpt->outFile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(fileOutUio, true);
}
ret = HITLS_APP_OptWriteUio(fileOutUio, out, outLen,
kdfOpt->isBinary == 1 ? HITLS_APP_FORMAT_TEXT: HITLS_APP_FORMAT_HEX);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("kdf:Failed to output the content to the screen\n");
}
BSL_UIO_Free(fileOutUio);
BSL_SAL_ClearFree(out, outLen);
return ret;
}
int32_t HITLS_KdfMain(int argc, char *argv[])
{
int32_t mainRet = HITLS_APP_SUCCESS;
AppProvider appProvider = {NULL, NULL, NULL};
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param smParam = {NULL, 0, NULL, NULL, 0, HITLS_APP_SM_STATUS_OPEN};
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider, &smParam};
KdfOpt kdfOpt = {CRYPT_MAC_HMAC_SM3, NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, 1024, &appProvider, 0, &smParam};
#else
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider};
KdfOpt kdfOpt = {CRYPT_MAC_HMAC_SHA256, NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, 1000, &appProvider, 0};
#endif
CRYPT_EAL_KdfCTX *ctx = NULL;
do {
mainRet = HITLS_APP_OptBegin(argc, argv, g_kdfOpts);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("error in opt begin.\n");
break;
}
mainRet = ParseKdfOpt(&kdfOpt);
if (mainRet != HITLS_APP_SUCCESS) {
break;
}
mainRet = GetKdfAlg(&kdfOpt);
if (mainRet != HITLS_APP_SUCCESS) {
break;
}
mainRet = CheckParam(&kdfOpt);
if (mainRet != HITLS_APP_SUCCESS) {
break;
}
mainRet = HITLS_APP_Init(&initParam);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("kdf: Failed to init, errCode: 0x%x.\n", mainRet);
break;
}
ctx = InitAlgKdf(&kdfOpt);
if (ctx == NULL) {
mainRet = HITLS_APP_CRYPTO_FAIL;
break;
}
mainRet = KdfResult(ctx, &kdfOpt);
} while (0);
CRYPT_EAL_KdfFreeCtx(ctx);
HITLS_APP_Deinit(&initParam, mainRet);
HITLS_APP_OptEnd();
return mainRet;
} | 2401_83913325/openHiTLS_1 | apps/src/app_kdf.c | C | unknown | 16,986 |
/*
* 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 "app_keymgmt.h"
#include <stddef.h>
#include <stdbool.h>
#include <dirent.h>
#include <limits.h>
#include "securec.h"
#include "bsl_uio.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_cipher.h"
#include "crypt_params_key.h"
#include "crypt_eal_cmvp.h"
#include "bsl_base64.h"
#include "crypt_errno.h"
#include "bsl_errno.h"
#include "bsl_sal.h"
#include "app_opt.h"
#include "app_utils.h"
#include "app_print.h"
#include "app_errno.h"
#include "app_function.h"
#include "app_sm.h"
#include "hitls_pki_pkcs12.h"
#include "hitls_pki_errno.h"
#include "bsl_bytes.h"
#ifdef HITLS_APP_SM_MODE
// include cipher key, mac key and asym key.
#define APP_KEYMGMT_MAX_KEY_LEN 128
#define APP_KEYMGMT_HMAC_KEY_LEN 64
#define APP_KEYMGMT_CBC_MAC_SM4_KEY_LEN 16
#define APP_KEYMGMT_MAX_KEY_COUNT 1024
#define APP_KEYMGMT_PBKDF2_IT_CNT_MIN 1024
#define APP_KEYMGMT_PBKDF2_IT_DEFAULT_CNT 10000
#define APP_KEYMGMT_PBKDF2_SALT_LEN_MIN 8
#define APP_KEYMGMT_PBKDF2_SALT_DEFAULT_LEN 16
#define APP_KEYMGMT_UUID_STR_LEN (2 * (HITLS_APP_UUID_LEN) + 1)
#define APP_KEYMGMT_KEY_EXPIRE_TIME (180 * 24 * 60 * 60) /* 180 days */
#define APP_KEYMGMT_KEY_VERSION 1
#define APP_KEYMGMT_SYNC_DATA_VERSION 1
typedef enum OptionChoice {
HITLS_APP_OPT_KEYMGMT_ERR = -1,
HITLS_APP_OPT_KEYMGMT_ROF = 0,
HITLS_APP_OPT_KEYMGMT_HELP = 1,
HITLS_APP_OPT_KEYMGMT_CREATE,
HITLS_APP_OPT_KEYMGMT_DEL,
HITLS_APP_OPT_KEYMGMT_ERASEKEY,
HITLS_APP_OPT_KEYMGMT_ALGID,
HITLS_APP_OPT_KEYMGMT_ITER,
HITLS_APP_OPT_KEYMGMT_SALTLEN,
HITLS_APP_OPT_KEYMGMT_GETVERSION,
HITLS_APP_OPT_KEYMGMT_GETSTATUS,
HITLS_APP_OPT_KEYMGMT_GETPUB,
HITLS_APP_OPT_KEYMGMT_SELFTEST,
HITLS_APP_PROV_ENUM,
HITLS_SM_OPTIONS_ENUM,
} HITLSOptType;
typedef struct {
uint32_t version;
int32_t algId; // key will be used for algorithm.
int32_t createTag; // to create a key.
int32_t deleteTag; // to delete a key.
int32_t eraseTag; // to erase all keys.
int32_t getVersionTag; // to get version.
int32_t getStatusTag; // to get status.
int32_t selfTestTag; // to do self test.
int32_t getPubTag; // to get public key.
int32_t iter; // iteration count for generating p12 file.
int32_t saltLen; // salt length for generating p12 file.
AppProvider *provider;
HITLS_APP_SM_Param *smParam;
} KeyMgmtCmdOpt;
typedef struct {
HITLS_APP_KeyAttr attr;
uint32_t keyLen;
uint8_t key[APP_KEYMGMT_MAX_KEY_LEN];
} HITLS_SyncKeyInfo;
static int32_t GetAlgId(const char *name);
static void FreeKeyInfo(HITLS_APP_KeyInfo *keyInfo);
static int32_t CheckAlgMatchForFind(int32_t requestAlgId, int32_t storedAlgId);
static int32_t ReadAsymKey(AppProvider *provider, HITLS_APP_SM_Param *smParam, HITLS_APP_KeyInfo *keyInfo);
static const HITLS_CmdOption g_keyMgmtOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"create", HITLS_APP_OPT_KEYMGMT_CREATE, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Create a key"},
{"delete", HITLS_APP_OPT_KEYMGMT_DEL, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Delete a key"},
{"erasekey", HITLS_APP_OPT_KEYMGMT_ERASEKEY, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Erase all keys"},
{"getversion", HITLS_APP_OPT_KEYMGMT_GETVERSION, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Get version"},
{"getstatus", HITLS_APP_OPT_KEYMGMT_GETSTATUS, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Get status"},
{"getpub", HITLS_APP_OPT_KEYMGMT_GETPUB, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Get public key"},
{"selftest", HITLS_APP_OPT_KEYMGMT_SELFTEST, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Self test"},
{"algid", HITLS_APP_OPT_KEYMGMT_ALGID, HITLS_APP_OPT_VALUETYPE_STRING, "Key usage algorithm"},
{"iter", HITLS_APP_OPT_KEYMGMT_ITER, HITLS_APP_OPT_VALUETYPE_POSITIVE_INT,
"Iteration count for generating p12 file."},
{"saltlen", HITLS_APP_OPT_KEYMGMT_SALTLEN, HITLS_APP_OPT_VALUETYPE_POSITIVE_INT,
"Salt length for generating p12 file"},
HITLS_APP_PROV_OPTIONS,
HITLS_SM_OPTIONS,
{NULL, 0, 0, NULL}
};
static void KeyAttrOrderCvt(HITLS_APP_KeyAttr *attr, bool toByte)
{
if (toByte) {
BSL_Uint32ToByte(attr->version, (uint8_t *)&attr->version);
BSL_Uint32ToByte(attr->algId, (uint8_t *)&attr->algId);
BSL_Uint64ToByte(attr->createTime, (uint8_t *)&attr->createTime);
BSL_Uint64ToByte(attr->expireTime, (uint8_t *)&attr->expireTime);
} else {
attr->version = BSL_ByteToUint32((uint8_t *)&attr->version);
attr->algId = BSL_ByteToUint32((uint8_t *)&attr->algId);
attr->createTime = BSL_ByteToUint64((uint8_t *)&attr->createTime);
attr->expireTime = BSL_ByteToUint64((uint8_t *)&attr->expireTime);
}
}
static char *GetKeyFullPath(const char *workPath, const char *uuid, const char *suffix)
{
char *path = BSL_SAL_Malloc(APP_MAX_PATH_LEN);
if (path == NULL) {
AppPrintError("keymgmt: Failed to allocate memory.\n");
return NULL;
}
int32_t ret = sprintf_s(path, APP_MAX_PATH_LEN, "%s/%s%s", workPath, uuid, suffix);
if (ret < 0) {
BSL_SAL_Free(path);
AppPrintError("keymgmt: Failed to get key full path, ret: %d.\n", ret);
return NULL;
}
return path;
}
static char *GetKeyFilePath(const char *workPath, const char *uuid)
{
return GetKeyFullPath(workPath, uuid, ".p12");
}
static char *GetPubKeyFilePath(const char *workPath, const char *uuid)
{
return GetKeyFullPath(workPath, uuid, "-pub.pem");
}
static int32_t WriteKeyFile(KeyMgmtCmdOpt *keyMgmtOpt, const char *uuid, HITLS_PKCS12 *p12)
{
CRYPT_Pbkdf2Param pbkdf2Param = {0};
pbkdf2Param.pbesId = BSL_CID_PBES2;
pbkdf2Param.pbkdfId = CRYPT_KDF_PBKDF2;
pbkdf2Param.hmacId = CRYPT_MAC_HMAC_SM3;
pbkdf2Param.symId = CRYPT_CIPHER_SM4_CBC;
pbkdf2Param.saltLen = keyMgmtOpt->saltLen;
pbkdf2Param.pwd = keyMgmtOpt->smParam->password;
pbkdf2Param.pwdLen = keyMgmtOpt->smParam->passwordLen;
pbkdf2Param.itCnt = keyMgmtOpt->iter;
CRYPT_EncodeParam encParam = {0};
encParam.deriveMode = CRYPT_DERIVE_PBKDF2;
encParam.param = &pbkdf2Param;
HITLS_PKCS12_KdfParam kdfParam = {0};
kdfParam.saltLen = keyMgmtOpt->saltLen;
kdfParam.itCnt = keyMgmtOpt->iter;
kdfParam.macId = CRYPT_MD_SM3;
kdfParam.pwd = keyMgmtOpt->smParam->password;
kdfParam.pwdLen = keyMgmtOpt->smParam->passwordLen;
HITLS_PKCS12_MacParam macParam = {0};
macParam.algId = BSL_CID_PKCS12KDF;
macParam.para = &kdfParam;
HITLS_PKCS12_EncodeParam encodeParam = {0};
encodeParam.encParam = encParam;
encodeParam.macParam = macParam;
char *path = GetKeyFilePath(keyMgmtOpt->smParam->workPath, uuid);
if (path == NULL) {
(void)AppPrintError("keymgmt: Failed to get key full path.\n");
return HITLS_APP_INVALID_ARG;
}
int32_t ret = HITLS_PKCS12_GenFile(BSL_FORMAT_ASN1, p12, &encodeParam, true, path);
BSL_SAL_Free(path);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("keymgmt: Failed to generate pkcs12 key file, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t AddAttrToBag(HITLS_PKCS12_Bag *bag, HITLS_APP_KeyInfo *keyInfo)
{
HITLS_APP_KeyAttr attr = keyInfo->attr;
KeyAttrOrderCvt(&attr, true);
char attrValue[2 * sizeof(attr) + 1] = {0}; // 2: one byte to two hex chars.
int32_t ret = HITLS_APP_OptToHex((uint8_t *)&attr, sizeof(attr), attrValue, sizeof(attrValue));
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Failed to convert attr to hex, errCode: 0x%x.\n", ret);
return ret;
}
BSL_Buffer attrValueBuf = {0};
attrValueBuf.data = (uint8_t *)attrValue;
attrValueBuf.dataLen = strlen(attrValue) + 1;
ret = HITLS_PKCS12_BagCtrl(bag, HITLS_PKCS12_BAG_ADD_ATTR, &attrValueBuf, BSL_CID_FRIENDLYNAME);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("keymgmt: Failed to add attr to bag, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t AddCipherKeyToP12(HITLS_PKCS12 *p12, HITLS_APP_KeyInfo *keyInfo)
{
BSL_Buffer value = {0};
value.data = keyInfo->key;
value.dataLen = keyInfo->keyLen;
HITLS_PKCS12_Bag *bag = HITLS_PKCS12_BagNew(BSL_CID_SECRETBAG, BSL_CID_CE_KEYUSAGE, &value);
if (bag == NULL) {
AppPrintError("keymgmt: Failed to create the secret bag.\n");
return HITLS_APP_X509_FAIL;
}
int32_t ret = AddAttrToBag(bag, keyInfo);
if (ret != HITLS_APP_SUCCESS) {
HITLS_PKCS12_BagFree(bag);
return ret;
}
ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_SECRETBAG, bag, 0);
HITLS_PKCS12_BagFree(bag);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("keymgmt: Failed to add the secret bag, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t AddAsymKeyToP12(HITLS_PKCS12 *p12, HITLS_APP_KeyInfo *keyInfo)
{
HITLS_PKCS12_Bag *bag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, keyInfo->pkeyCtx);
if (bag == NULL) {
AppPrintError("keymgmt: Failed to create the PKCS8ShroudedKeyBag.\n");
return HITLS_APP_X509_FAIL;
}
int32_t ret = AddAttrToBag(bag, keyInfo);
if (ret != HITLS_APP_SUCCESS) {
HITLS_PKCS12_BagFree(bag);
return ret;
}
ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_KEYBAG, bag, 0);
HITLS_PKCS12_BagFree(bag);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("keymgmt: Failed to set the private key bag, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return ret;
}
static int32_t HITLS_APP_WriteKey(KeyMgmtCmdOpt *keyMgmtOpt, HITLS_APP_KeyInfo *keyInfo, const char *uuid)
{
HITLS_PKCS12 *p12 = HITLS_PKCS12_ProviderNew(APP_GetCurrent_LibCtx(), keyMgmtOpt->provider->providerAttr);
if (p12 == NULL) {
AppPrintError("keymgmt: Failed to create the pkcs12 context.\n");
return HITLS_APP_X509_FAIL;
}
int32_t ret = 0;
if (keyInfo->attr.algId == CRYPT_PKEY_SM2) {
ret = AddAsymKeyToP12(p12, keyInfo);
} else {
ret = AddCipherKeyToP12(p12, keyInfo);
}
if (ret != HITLS_APP_SUCCESS) {
HITLS_PKCS12_Free(p12);
return ret;
}
ret = WriteKeyFile(keyMgmtOpt, uuid, p12);
HITLS_PKCS12_Free(p12);
return ret;
}
static int32_t GenerateKeyAttr(int32_t algId, HITLS_APP_KeyAttr *attr,
char **uuid)
{
char *uuidStr = NULL;
int32_t ret = CRYPT_EAL_RandbytesEx(APP_GetCurrent_LibCtx(), attr->uuid, sizeof(attr->uuid));
if (ret != CRYPT_SUCCESS) {
AppPrintError("keymgmt: Failed to generate the uuid, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
ret = HITLS_APP_GetTime(&attr->createTime);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
attr->expireTime = attr->createTime + APP_KEYMGMT_KEY_EXPIRE_TIME;
attr->version = APP_KEYMGMT_KEY_VERSION;
attr->algId = algId;
uuidStr = (char *)BSL_SAL_Malloc(APP_KEYMGMT_UUID_STR_LEN);
if (uuidStr == NULL) {
AppPrintError("keymgmt: Failed to allocate memory.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
ret = HITLS_APP_OptToHex(attr->uuid, sizeof(attr->uuid), uuidStr, APP_KEYMGMT_UUID_STR_LEN);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_Free(uuidStr);
AppPrintError("keymgmt: Failed to convert uuid to hex, errCode: 0x%x.\n", ret);
return ret;
}
*uuid = uuidStr;
return HITLS_APP_SUCCESS;
}
static int32_t CreateCipherKey(KeyMgmtCmdOpt *keyMgmtOpt, int32_t algId, HITLS_APP_KeyInfo *keyInfo)
{
if (algId == CRYPT_MAC_HMAC_SM3) {
keyInfo->keyLen = APP_KEYMGMT_HMAC_KEY_LEN;
} else if (algId == CRYPT_MAC_CBC_MAC_SM4) {
keyInfo->keyLen = APP_KEYMGMT_CBC_MAC_SM4_KEY_LEN;
} else {
int32_t ret = CRYPT_EAL_CipherGetInfo(algId, CRYPT_INFO_KEY_LEN, &keyInfo->keyLen);
if (ret != CRYPT_SUCCESS) {
AppPrintError("keymgmt: Failed to get the key length, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
}
keyMgmtOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
int32_t ret = CRYPT_EAL_RandbytesEx(APP_GetCurrent_LibCtx(), keyInfo->key, keyInfo->keyLen);
if (ret != CRYPT_SUCCESS) {
AppPrintError("keymgmt: Failed to generate the key, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t CreateAsymKey(KeyMgmtCmdOpt *keyMgmtOpt, int32_t algId, HITLS_APP_KeyInfo *keyInfo)
{
CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(APP_GetCurrent_LibCtx(), algId, 0,
keyMgmtOpt->provider->providerAttr);
if (pkeyCtx == NULL) {
AppPrintError("keymgmt: Failed to create the asym pkey context.\n");
return HITLS_APP_CRYPTO_FAIL;
}
keyMgmtOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
int32_t ret = CRYPT_EAL_PkeyGen(pkeyCtx);
if (ret != CRYPT_SUCCESS) {
HITLS_APP_SM_PrintLog(ret);
CRYPT_EAL_PkeyFreeCtx(pkeyCtx);
AppPrintError("keymgmt: Failed to generate the asym key, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
keyInfo->pkeyCtx = pkeyCtx;
return HITLS_APP_SUCCESS;
}
static int32_t HITLS_APP_CreateKey(KeyMgmtCmdOpt *keyMgmtOpt, int32_t algId, char **uuid)
{
HITLS_APP_KeyInfo keyInfo = {0};
char *uuidStr = NULL;
int32_t ret = HITLS_APP_SUCCESS;
switch (algId) {
case CRYPT_CIPHER_SM4_XTS:
case CRYPT_CIPHER_SM4_CBC:
case CRYPT_CIPHER_SM4_ECB:
case CRYPT_CIPHER_SM4_CTR:
case CRYPT_CIPHER_SM4_GCM:
case CRYPT_CIPHER_SM4_CFB:
case CRYPT_CIPHER_SM4_OFB:
case CRYPT_MAC_HMAC_SM3:
case CRYPT_MAC_CBC_MAC_SM4:
ret = CreateCipherKey(keyMgmtOpt, algId, &keyInfo);
break;
case CRYPT_PKEY_SM2:
ret = CreateAsymKey(keyMgmtOpt, algId, &keyInfo);
break;
default:
AppPrintError("keymgmt: Invalid algorithm id: %d.\n", algId);
ret = HITLS_APP_INVALID_ARG;
break;
}
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = GenerateKeyAttr(algId, &keyInfo.attr, &uuidStr);
if (ret != HITLS_APP_SUCCESS) {
FreeKeyInfo(&keyInfo);
return ret;
}
ret = HITLS_APP_WriteKey(keyMgmtOpt, &keyInfo, uuidStr);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_Free(uuidStr);
FreeKeyInfo(&keyInfo);
return ret;
}
FreeKeyInfo(&keyInfo);
*uuid = uuidStr;
return HITLS_APP_SUCCESS;
}
static int32_t EraseKeyFile(char *path)
{
size_t fileLen = 0;
int32_t ret = BSL_SAL_FileLength(path, &fileLen);
if (ret != BSL_SUCCESS) {
AppPrintError("keymgmt: Failed to get file size: %s, errCode = 0x%x.\n", path, ret);
return HITLS_APP_BSL_FAIL;
}
if (fileLen > APP_FILE_MAX_SIZE) {
AppPrintError("keymgmt: File size exceed limit: %zu, fileLen:%zu, path:%s.\n",
APP_FILE_MAX_SIZE, fileLen, path);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO *uio = BSL_UIO_New(BSL_UIO_FileMethod());
if (uio == NULL) {
AppPrintError("keymgmt: Failed to create uio.\n");
return HITLS_APP_UIO_FAIL;
}
ret = BSL_UIO_Ctrl(uio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_WRITE, path);
if (ret != BSL_SUCCESS) {
AppPrintError("keymgmt: Failed to open key file, errCode: 0x%x.\n", ret);
BSL_UIO_Free(uio);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(uio, true);
uint32_t writeLen = 0;
uint8_t *data = BSL_SAL_Calloc(fileLen, 1);
if (data == NULL) {
BSL_UIO_Free(uio);
AppPrintError("keymgmt: Failed to allocate memory.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
ret = BSL_UIO_Write(uio, data, fileLen, &writeLen);
if (ret != BSL_SUCCESS || writeLen != fileLen) {
BSL_UIO_Free(uio);
BSL_SAL_Free(data);
AppPrintError("keymgmt: Failed to erase key file, errCode: 0x%x, writeLen: %u.\n", ret, writeLen);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_Free(uio);
BSL_SAL_Free(data);
return HITLS_APP_SUCCESS;
}
static int32_t HITLS_APP_RmvKey(KeyMgmtCmdOpt *keyMgmtOpt, const char *uuid)
{
char *path = GetKeyFilePath(keyMgmtOpt->smParam->workPath, uuid);
if (path == NULL) {
return HITLS_APP_INVALID_ARG;
}
keyMgmtOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
int32_t ret = EraseKeyFile(path);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_Free(path);
return ret;
}
if (remove(path) != 0) {
AppPrintError("keymgmt: Failed to remove key file, path: %s.\n", path);
BSL_SAL_Free(path);
return HITLS_APP_INVALID_ARG;
}
BSL_SAL_Free(path);
return HITLS_APP_SUCCESS;
}
static void FreeKeyInfo(HITLS_APP_KeyInfo *keyInfo)
{
if (keyInfo == NULL) {
return;
}
if (keyInfo->keyLen != 0) {
(void)BSL_SAL_CleanseData(keyInfo->key, keyInfo->keyLen);
}
keyInfo->keyLen = 0;
if (keyInfo->pkeyCtx != NULL) {
CRYPT_EAL_PkeyFreeCtx(keyInfo->pkeyCtx);
}
keyInfo->pkeyCtx = NULL;
}
static void HandleSomeOpt(KeyMgmtCmdOpt *keyMgmtOpt, HITLSOptType optType)
{
switch (optType) {
case HITLS_APP_OPT_KEYMGMT_CREATE:
keyMgmtOpt->createTag = 1;
break;
case HITLS_APP_OPT_KEYMGMT_DEL:
keyMgmtOpt->deleteTag = 1;
break;
case HITLS_APP_OPT_KEYMGMT_ERASEKEY:
keyMgmtOpt->eraseTag = 1;
break;
case HITLS_APP_OPT_KEYMGMT_GETVERSION:
keyMgmtOpt->getVersionTag = 1;
break;
case HITLS_APP_OPT_KEYMGMT_GETSTATUS:
keyMgmtOpt->getStatusTag = 1;
break;
case HITLS_APP_OPT_KEYMGMT_GETPUB:
keyMgmtOpt->getPubTag = 1;
break;
case HITLS_APP_OPT_KEYMGMT_SELFTEST:
keyMgmtOpt->selfTestTag = 1;
break;
default:
break;
}
return;
}
static int32_t HandleOpt(KeyMgmtCmdOpt *keyMgmtOpt)
{
int32_t ret;
int32_t optType;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
HITLS_APP_PROV_CASES(optType, keyMgmtOpt->provider);
HITLS_APP_SM_CASES(optType, keyMgmtOpt->smParam);
switch (optType) {
case HITLS_APP_OPT_ERR:
AppPrintError("keymgmt: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_OPT_HELP:
HITLS_APP_OptHelpPrint(g_keyMgmtOpts);
return HITLS_APP_HELP;
case HITLS_APP_OPT_KEYMGMT_ALGID:
if ((keyMgmtOpt->algId = GetAlgId(HITLS_APP_OptGetValueStr())) == -1) {
AppPrintError("keymgmt: Invalid algorithm id: %s.\n", HITLS_APP_OptGetValueStr());
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_KEYMGMT_ITER:
ret = HITLS_APP_OptGetInt(HITLS_APP_OptGetValueStr(), (int32_t *)&keyMgmtOpt->iter);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
break;
case HITLS_APP_OPT_KEYMGMT_SALTLEN:
ret = HITLS_APP_OptGetInt(HITLS_APP_OptGetValueStr(), (int32_t *)&keyMgmtOpt->saltLen);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
break;
default:
break;
}
HandleSomeOpt(keyMgmtOpt, optType);
}
if (HITLS_APP_GetRestOptNum() != 0) {
AppPrintError("keymgmt: Extra arguments given.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckActionTag(KeyMgmtCmdOpt *keyMgmtOpt)
{
int32_t count = 0;
count += keyMgmtOpt->createTag;
count += keyMgmtOpt->deleteTag;
count += keyMgmtOpt->eraseTag;
count += keyMgmtOpt->getVersionTag;
count += keyMgmtOpt->getStatusTag;
count += keyMgmtOpt->selfTestTag;
count += keyMgmtOpt->getPubTag;
if (count != 1) {
AppPrintError("keymgmt: Only one action is allowed: -create, -delete, -erasekey, -getversion, -getstatus or " \
"-selftest, -getpub.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckOptParam(KeyMgmtCmdOpt *keyMgmtOpt)
{
int32_t ret = CheckActionTag(keyMgmtOpt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (keyMgmtOpt->smParam->smTag != 1) {
AppPrintError("keymgmt: The sm is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (keyMgmtOpt->smParam->workPath == NULL) {
AppPrintError("keymgmt: The workpath is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (keyMgmtOpt->eraseTag == 1 || keyMgmtOpt->getVersionTag == 1 || keyMgmtOpt->getStatusTag == 1 ||
keyMgmtOpt->selfTestTag == 1) {
return HITLS_APP_SUCCESS;
}
if (keyMgmtOpt->deleteTag == 1 || keyMgmtOpt->getPubTag == 1) {
if (keyMgmtOpt->smParam->uuid == NULL) {
AppPrintError("keymgmt: The uuid is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
if (keyMgmtOpt->algId < 0) {
AppPrintError("keymgmt: The algorithm is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (keyMgmtOpt->iter == -1) {
keyMgmtOpt->iter = APP_KEYMGMT_PBKDF2_IT_DEFAULT_CNT;
}
if (keyMgmtOpt->iter < APP_KEYMGMT_PBKDF2_IT_CNT_MIN) {
AppPrintError("keymgmt: The number of iterations is invalid, iter: %d, min: %d.\n", keyMgmtOpt->iter,
APP_KEYMGMT_PBKDF2_IT_CNT_MIN);
return HITLS_APP_OPT_VALUE_INVALID;
}
if (keyMgmtOpt->saltLen == -1) {
keyMgmtOpt->saltLen = APP_KEYMGMT_PBKDF2_SALT_DEFAULT_LEN;
}
if (keyMgmtOpt->saltLen < APP_KEYMGMT_PBKDF2_SALT_LEN_MIN) {
AppPrintError("keymgmt: The salt length is invalid, saltLen: %d, min: %d.\n", keyMgmtOpt->saltLen,
APP_KEYMGMT_PBKDF2_SALT_LEN_MIN);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t CreateKey(KeyMgmtCmdOpt *keyMgmtOpt)
{
char *uuid = NULL;
int32_t ret = HITLS_APP_CreateKey(keyMgmtOpt, keyMgmtOpt->algId, &uuid);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Failed to create key, errCode: 0x%x.\n", ret);
return ret;
}
AppPrintError("keymgmt: uuid: %s\n", uuid);
BSL_SAL_Free(uuid);
return HITLS_APP_SUCCESS;
}
static int32_t SplitUuidString(const char *uuid, BslList **uuidList)
{
char *src = BSL_SAL_Dump(uuid, strlen(uuid) + 1);
if (src == NULL) {
AppPrintError("keymgmt: Failed to dump uuid string.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
BslList *list = BSL_LIST_New(sizeof(char *));
if (list == NULL) {
BSL_SAL_FREE(src);
AppPrintError("keymgmt: Failed to create list.\n");
return HITLS_APP_SAL_FAIL;
}
char sep[] = ",";
char *nextTmp = NULL;
char *tmp = strtok_s(src, sep, &nextTmp);
while (tmp != NULL) {
char *singleUuid = BSL_SAL_Dump(tmp, strlen(tmp) + 1);
if (singleUuid == NULL) {
BSL_SAL_FREE(src);
BSL_LIST_FREE(list, BSL_SAL_Free);
AppPrintError("keymgmt: Failed to dump single uuid string.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
int32_t ret = BSL_LIST_AddElement(list, singleUuid, BSL_LIST_POS_END);
if (ret != BSL_SUCCESS) {
BSL_SAL_FREE(singleUuid);
BSL_SAL_FREE(src);
BSL_LIST_FREE(list, BSL_SAL_Free);
AppPrintError("keymgmt: Failed to add single uuid to list.\n");
return HITLS_APP_SAL_FAIL;
}
tmp = strtok_s(NULL, sep, &nextTmp);
}
BSL_SAL_FREE(src);
*uuidList = list;
return HITLS_APP_SUCCESS;
}
static int32_t DeleteKeyByUuidList(KeyMgmtCmdOpt *keyMgmtOpt, BslList *uuidList)
{
int32_t ret = HITLS_APP_SUCCESS;
const char *oneUuid = BSL_LIST_GET_FIRST(uuidList);
while (oneUuid != NULL) {
ret = HITLS_APP_RmvKey(keyMgmtOpt, oneUuid);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
oneUuid = BSL_LIST_GET_NEXT(uuidList);
}
return HITLS_APP_SUCCESS;
}
static int32_t DeleteKey(KeyMgmtCmdOpt *keyMgmtOpt)
{
BslList *uuidList = NULL;
int32_t ret = SplitUuidString(keyMgmtOpt->smParam->uuid, &uuidList);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = DeleteKeyByUuidList(keyMgmtOpt, uuidList);
BSL_LIST_FREE(uuidList, BSL_SAL_Free);
return ret;
}
static bool IsP12File(const char *file)
{
const char *suffix = ".p12";
size_t fileLen = strlen(file);
if (fileLen != 2 * HITLS_APP_UUID_LEN + strlen(suffix)) { // 2: one byte to two hex chars.
return false;
}
return strcmp(file + fileLen - strlen(suffix), suffix) == 0;
}
static int32_t GetAllKeyUuids(const char *workPath, BslList **fileList)
{
char *uuid = NULL;
int32_t ret = HITLS_APP_SUCCESS;
DIR *dir = opendir(workPath);
if (dir == NULL) {
AppPrintError("keymgmt: Failed to open directory.\n");
return HITLS_APP_INVALID_ARG;
}
BslList *list = BSL_LIST_New(sizeof(char *));
if (list == NULL) {
closedir(dir);
AppPrintError("keymgmt: Failed to create list.\n");
return HITLS_APP_SAL_FAIL;
}
struct dirent *dp = NULL;
for (dp = readdir(dir); dp != NULL; dp = readdir(dir)) {
if (dp->d_type == DT_REG && IsP12File(dp->d_name)) {
uuid = BSL_SAL_Dump(dp->d_name, APP_KEYMGMT_UUID_STR_LEN);
if (uuid == NULL) {
closedir(dir);
BSL_LIST_FREE(list, BSL_SAL_Free);
AppPrintError("keymgmt: Failed to dump single uuid string.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
uuid[APP_KEYMGMT_UUID_STR_LEN - 1] = '\0';
ret = BSL_LIST_AddElement(list, uuid, BSL_LIST_POS_END);
if (ret != BSL_SUCCESS) {
closedir(dir);
BSL_LIST_FREE(list, BSL_SAL_Free);
BSL_SAL_FREE(uuid);
AppPrintError("keymgmt: Failed to add single uuid to list.\n");
return HITLS_APP_SAL_FAIL;
}
}
}
closedir(dir);
*fileList = list;
return HITLS_APP_SUCCESS;
}
static int32_t EraseAllKeys(KeyMgmtCmdOpt *keyMgmtOpt)
{
BslList *uuidList = NULL;
int32_t ret = GetAllKeyUuids(keyMgmtOpt->smParam->workPath, &uuidList);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = DeleteKeyByUuidList(keyMgmtOpt, uuidList);
BSL_LIST_FREE(uuidList, BSL_SAL_Free);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Failed to erase all keys, errCode: 0x%x.\n", ret);
return ret;
}
AppPrintError("keymgmt: All keys deleted successfully.\n");
return HITLS_APP_SUCCESS;
}
static int32_t GetVersion(KeyMgmtCmdOpt *keyMgmtOpt)
{
CRYPT_SelftestCtx *selftestCtx = NULL;
selftestCtx = CRYPT_CMVP_SelftestNewCtx(APP_GetCurrent_LibCtx(), keyMgmtOpt->provider->providerAttr);
if (selftestCtx == NULL) {
AppPrintError("keymgmt: Failed to get version, selftestCtx is NULL.\n");
return HITLS_APP_CRYPTO_FAIL;
}
keyMgmtOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
const char *version = CRYPT_CMVP_GetVersion(selftestCtx);
if (version == NULL) {
CRYPT_CMVP_SelftestFreeCtx(selftestCtx);
AppPrintError("keymgmt: Failed to get version, version is NULL.\n");
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_CMVP_SelftestFreeCtx(selftestCtx);
AppPrintError("%s\n", version);
return HITLS_APP_SUCCESS;
}
static int32_t GetStatus(KeyMgmtCmdOpt *keyMgmtOpt)
{
keyMgmtOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
AppPrintError("keymgmt: status: %d\n", keyMgmtOpt->smParam->status);
return HITLS_APP_SUCCESS;
}
static int32_t SelfTest(KeyMgmtCmdOpt *keyMgmtOpt)
{
CRYPT_SelftestCtx *selftestCtx = NULL;
selftestCtx = CRYPT_CMVP_SelftestNewCtx(APP_GetCurrent_LibCtx(), keyMgmtOpt->provider->providerAttr);
if (selftestCtx == NULL) {
AppPrintError("keymgmt: Failed to self test, selftestCtx is NULL.\n");
return HITLS_APP_CRYPTO_FAIL;
}
keyMgmtOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
BSL_Param params[] = {{0}, BSL_PARAM_END};
int32_t type = CRYPT_CMVP_KAT_TEST;
BSL_PARAM_InitValue(¶ms[0], CRYPT_PARAM_CMVP_SELFTEST_TYPE, BSL_PARAM_TYPE_INT32, &type, sizeof(type));
int32_t ret = CRYPT_CMVP_Selftest(selftestCtx, params);
if (ret != CRYPT_SUCCESS) {
HITLS_APP_SM_PrintLog(ret);
AppPrintError("keymgmt: Failed to self test, errCode: 0x%x.\n", ret);
CRYPT_CMVP_SelftestFreeCtx(selftestCtx);
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_CMVP_SelftestFreeCtx(selftestCtx);
AppPrintError("keymgmt: Self test passed.\n");
return HITLS_APP_SUCCESS;
}
static int32_t GetPub(KeyMgmtCmdOpt *keyMgmtOpt)
{
HITLS_APP_KeyInfo keyInfo = {0};
int32_t ret = ReadAsymKey(keyMgmtOpt->provider, keyMgmtOpt->smParam, &keyInfo);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
char *path = GetPubKeyFilePath(keyMgmtOpt->smParam->workPath, keyMgmtOpt->smParam->uuid);
if (path == NULL) {
AppPrintError("keymgmt: Failed to get public key full path.\n");
FreeKeyInfo(&keyInfo);
return HITLS_APP_INVALID_ARG;
}
ret = HITLS_APP_PrintPubKey(keyInfo.pkeyCtx, path, BSL_FORMAT_PEM);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Failed to write public key, errCode: 0x%x.\n", ret);
FreeKeyInfo(&keyInfo);
BSL_SAL_Free(path);
return ret;
}
AppPrintError("keymgmt: Public key written successfully.\n");
FreeKeyInfo(&keyInfo);
BSL_SAL_Free(path);
return HITLS_APP_SUCCESS;
}
static int32_t ProcessOptions(KeyMgmtCmdOpt *keyMgmtOpt)
{
if (keyMgmtOpt->eraseTag == 1) {
return EraseAllKeys(keyMgmtOpt);
}
if (keyMgmtOpt->getVersionTag == 1) {
return GetVersion(keyMgmtOpt);
}
if (keyMgmtOpt->getStatusTag == 1) {
return GetStatus(keyMgmtOpt);
}
if (keyMgmtOpt->getPubTag == 1) {
return GetPub(keyMgmtOpt);
}
if (keyMgmtOpt->selfTestTag == 1) {
return SelfTest(keyMgmtOpt);
}
if (keyMgmtOpt->createTag == 1) {
return CreateKey(keyMgmtOpt);
}
if (keyMgmtOpt->deleteTag == 1) {
return DeleteKey(keyMgmtOpt);
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_KeyMgmtMain(int argc, char *argv[])
{
int32_t ret;
AppProvider appProvider = {NULL, NULL, NULL};
HITLS_APP_SM_Param smParam = {NULL, 0, NULL, NULL, 0, HITLS_APP_SM_STATUS_OPEN};
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider, &smParam};
KeyMgmtCmdOpt keyMgmtOpt = {1, -1, 0, 0, 0, 0, 0, 0, 0, -1, -1, &appProvider, &smParam};
if ((ret = HITLS_APP_OptBegin(argc, argv, g_keyMgmtOpts)) != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Error in opt begin.\n");
goto End;
}
if ((ret = HandleOpt(&keyMgmtOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
if ((ret = CheckOptParam(&keyMgmtOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
if ((ret = HITLS_APP_Init(&initParam)) != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Failed to init, errCode: 0x%x.\n", ret);
goto End;
}
ret = ProcessOptions(&keyMgmtOpt);
End:
HITLS_APP_Deinit(&initParam, ret);
return ret;
}
static int32_t ReadKeyFile(AppProvider *provider, HITLS_APP_SM_Param *smParam, HITLS_PKCS12 **p12)
{
char *path = GetKeyFilePath(smParam->workPath, smParam->uuid);
if (path == NULL) {
AppPrintError("keymgmt: Failed to get key full path.\n");
return HITLS_APP_INVALID_ARG;
}
BSL_Buffer encPwd = {0};
encPwd.data = smParam->password;
encPwd.dataLen = smParam->passwordLen;
HITLS_PKCS12_PwdParam pwdParam = {0};
pwdParam.encPwd = &encPwd;
pwdParam.macPwd = &encPwd;
int32_t ret = HITLS_PKCS12_ProviderParseFile(APP_GetCurrent_LibCtx(), provider->providerAttr, "ASN1", path,
&pwdParam, p12, true);
BSL_SAL_Free(path);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("keymgmt: Failed to read key file, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t GetKeyAttr(HITLS_PKCS12_Bag *bag, HITLS_APP_KeyAttr *attr)
{
char attrValue[2 * sizeof(*attr) + 1] = {0}; // 2: one byte to two hex chars.
BSL_Buffer attrValueBuf = {0};
attrValueBuf.data = (uint8_t *)attrValue;
attrValueBuf.dataLen = sizeof(attrValue);
int32_t ret = HITLS_PKCS12_BagCtrl(bag, HITLS_PKCS12_BAG_GET_ATTR, &attrValueBuf, BSL_CID_FRIENDLYNAME);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("keymgmt: Failed to get key attr, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
uint32_t attrLen = sizeof(HITLS_APP_KeyAttr);
ret = HITLS_APP_StrToHex(attrValue, (uint8_t *)attr, &attrLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Failed to convert attr to hex, errCode: 0x%x.\n", ret);
return ret;
}
if (attrLen != sizeof(HITLS_APP_KeyAttr)) {
AppPrintError("keymgmt: Attr len not match, attrLen: %u.\n", attrLen);
return HITLS_APP_INFO_CMP_FAIL;
}
KeyAttrOrderCvt(attr, false);
return HITLS_APP_SUCCESS;
}
static int32_t ReadCipherKey(AppProvider *provider, HITLS_APP_SM_Param *smParam, HITLS_APP_KeyInfo *keyInfo)
{
HITLS_PKCS12 *p12 = NULL;
int32_t ret = ReadKeyFile(provider, smParam, &p12);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Failed to read cipher key, errCode: 0x%x.\n", ret);
return ret;
}
HITLS_PKCS12_Bag *tmpBag = NULL;
BslList *secretBags = NULL;
ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GET_SECRETBAGS, &secretBags, 0);
if (ret != HITLS_PKI_SUCCESS) {
HITLS_PKCS12_Free(p12);
AppPrintError("keymgmt: Failed to get secret bags, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
tmpBag = BSL_LIST_GET_FIRST(secretBags);
ret = GetKeyAttr(tmpBag, &keyInfo->attr);
if (ret != HITLS_APP_SUCCESS) {
HITLS_PKCS12_Free(p12);
return ret;
}
BSL_Buffer value = {keyInfo->key, sizeof(keyInfo->key)};
ret = HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_VALUE, &value, 0);
HITLS_PKCS12_Free(p12);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("keymgmt: Failed to get key value, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
keyInfo->keyLen = value.dataLen;
return HITLS_APP_SUCCESS;
}
static int32_t ReadAsymKey(AppProvider *provider, HITLS_APP_SM_Param *smParam, HITLS_APP_KeyInfo *keyInfo)
{
HITLS_PKCS12 *p12 = NULL;
int32_t ret = ReadKeyFile(provider, smParam, &p12);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Failed to read asym key, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
HITLS_PKCS12_Bag *tmpBag = NULL;
ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GET_ENTITY_KEYBAG, &tmpBag, 0);
if (ret != HITLS_PKI_SUCCESS) {
HITLS_PKCS12_Free(p12);
AppPrintError("keymgmt: Failed to get entity key bag, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = GetKeyAttr(tmpBag, &keyInfo->attr);
if (ret != HITLS_APP_SUCCESS) {
HITLS_PKCS12_BagFree(tmpBag);
HITLS_PKCS12_Free(p12);
return ret;
}
ret = HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_VALUE, &keyInfo->pkeyCtx, 0);
HITLS_PKCS12_BagFree(tmpBag);
HITLS_PKCS12_Free(p12);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("keymgmt: Failed to get pkeyCtx, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_FindKey(AppProvider *provider, HITLS_APP_SM_Param *smParam, int32_t algId,
HITLS_APP_KeyInfo *keyInfo)
{
if (provider == NULL || smParam == NULL || smParam->uuid == NULL || smParam->password == NULL ||
smParam->passwordLen == 0 || smParam->workPath == NULL || keyInfo == NULL) {
AppPrintError("keymgmt: Invalid argument to find key.\n");
return HITLS_APP_INVALID_ARG;
}
int32_t ret;
HITLS_APP_KeyInfo readKeyInfo = {0};
switch (algId) {
case CRYPT_CIPHER_SM4_XTS:
case CRYPT_CIPHER_SM4_CBC:
case CRYPT_CIPHER_SM4_ECB:
case CRYPT_CIPHER_SM4_CTR:
case CRYPT_CIPHER_SM4_GCM:
case CRYPT_CIPHER_SM4_CFB:
case CRYPT_CIPHER_SM4_OFB:
case CRYPT_MAC_HMAC_SM3:
case CRYPT_MAC_CBC_MAC_SM4:
ret = ReadCipherKey(provider, smParam, &readKeyInfo);
break;
case CRYPT_PKEY_SM2:
ret = ReadAsymKey(provider, smParam, &readKeyInfo);
break;
default:
AppPrintError("keymgmt: Invalid algorithm id: %d.\n", algId);
return HITLS_APP_INVALID_ARG;
}
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Failed to read key, errCode: 0x%x.\n", ret);
return ret;
}
ret = CheckAlgMatchForFind(algId, readKeyInfo.attr.algId);
if (ret != HITLS_APP_SUCCESS) {
FreeKeyInfo(&readKeyInfo);
return ret;
}
(void)memcpy_s(keyInfo, sizeof(*keyInfo), &readKeyInfo, sizeof(readKeyInfo));
(void)BSL_SAL_CleanseData(readKeyInfo.key, readKeyInfo.keyLen);
return HITLS_APP_SUCCESS;
}
static int32_t GetSm2Raw(const CRYPT_EAL_PkeyCtx *pkey, uint8_t *prv, uint32_t *prvLen, uint8_t *pub, uint32_t *pubLen)
{
BSL_Param pubParam[2] = {{CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, pub, *pubLen, 0}, BSL_PARAM_END};
BSL_Param prvParam[2] = {{CRYPT_PARAM_EC_PRVKEY, BSL_PARAM_TYPE_OCTETS, prv, *prvLen, 0}, BSL_PARAM_END};
int32_t ret = CRYPT_EAL_PkeyGetPubEx(pkey, pubParam);
if (ret != CRYPT_SUCCESS) {
AppPrintError("keymgmt: Failed to get pub, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
*pubLen = pubParam[0].useLen;
ret = CRYPT_EAL_PkeyGetPrvEx(pkey, prvParam);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_CleanseData(pub, *pubLen);
AppPrintError("keymgmt: Failed to get prv, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
*prvLen = prvParam[0].useLen;
return HITLS_APP_SUCCESS;
}
static int32_t FillSyncKeyInfoFromSm2(const HITLS_APP_KeyInfo *keyInfo, HITLS_SyncKeyInfo *info)
{
HITLS_APP_KeyAttr attr = keyInfo->attr;
KeyAttrOrderCvt(&attr, true);
(void)memcpy_s(&info->attr, sizeof(info->attr), &attr, sizeof(attr));
uint8_t prv[APP_KEYMGMT_MAX_KEY_LEN] = {0};
uint8_t pub[APP_KEYMGMT_MAX_KEY_LEN] = {0};
uint32_t prvLen = sizeof(prv);
uint32_t pubLen = sizeof(pub);
int32_t ret = GetSm2Raw(keyInfo->pkeyCtx, prv, &prvLen, pub, &pubLen);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (pubLen + prvLen + sizeof(pubLen) + sizeof(prvLen) > sizeof(info->key)) {
AppPrintError("keymgmt: Invalid pubLen(%u) and prvLen(%u).\n", pubLen, prvLen);
BSL_SAL_CleanseData(prv, prvLen);
BSL_SAL_CleanseData(pub, pubLen);
return HITLS_APP_INVALID_ARG;
}
uint32_t used = 0;
uint32_t len = 0;
BSL_Uint32ToByte(pubLen, (uint8_t *)&len);
(void)memcpy_s(info->key + used, sizeof(info->key) - used, &len, sizeof(len));
used += sizeof(len);
(void)memcpy_s(info->key + used, sizeof(info->key) - used, pub, pubLen);
used += pubLen;
BSL_Uint32ToByte(prvLen, (uint8_t *)&len);
(void)memcpy_s(info->key + used, sizeof(info->key) - used, &len, sizeof(len));
used += sizeof(len);
(void)memcpy_s(info->key + used, sizeof(info->key) - used, prv, prvLen);
used += prvLen;
BSL_Uint32ToByte(used, (uint8_t *)&info->keyLen);
BSL_SAL_CleanseData(prv, prvLen);
BSL_SAL_CleanseData(pub, pubLen);
return ret;
}
static int32_t FillSyncKeyInfoFromCipher(const HITLS_APP_KeyInfo *keyInfo, HITLS_SyncKeyInfo *info)
{
HITLS_APP_KeyAttr attr = keyInfo->attr;
KeyAttrOrderCvt(&attr, true);
(void)memcpy_s(&info->attr, sizeof(info->attr), &attr, sizeof(attr));
(void)memcpy_s(info->key, sizeof(info->key), keyInfo->key, keyInfo->keyLen);
BSL_Uint32ToByte(keyInfo->keyLen, (uint8_t *)&info->keyLen);
return HITLS_APP_SUCCESS;
}
// try read key info (cipher or asym) by uuid without knowing algId
static int32_t ReadCipherOrAsymKey(AppProvider *provider, HITLS_APP_SM_Param *smParam, HITLS_APP_KeyInfo *keyInfo)
{
HITLS_PKCS12 *p12 = NULL;
int32_t ret = ReadKeyFile(provider, smParam, &p12);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Failed to read key, errCode: 0x%x.\n", ret);
return ret;
}
// try asym first
HITLS_PKCS12_Bag *keyBag = NULL;
ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GET_ENTITY_KEYBAG, &keyBag, 0);
if (ret == HITLS_PKI_SUCCESS && keyBag != NULL) {
ret = GetKeyAttr(keyBag, &keyInfo->attr);
if (ret != HITLS_APP_SUCCESS) {
HITLS_PKCS12_BagFree(keyBag);
HITLS_PKCS12_Free(p12);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_GET_VALUE, &keyInfo->pkeyCtx, 0);
HITLS_PKCS12_BagFree(keyBag);
HITLS_PKCS12_Free(p12);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("keymgmt: Failed to get pkeyCtx, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
// else secret bag
BslList *secretBags = NULL;
ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GET_SECRETBAGS, &secretBags, 0);
if (ret != HITLS_PKI_SUCCESS) {
HITLS_PKCS12_Free(p12);
AppPrintError("keymgmt: Failed to get secret bags, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
HITLS_PKCS12_Bag *tmpBag = BSL_LIST_GET_FIRST(secretBags);
ret = GetKeyAttr(tmpBag, &keyInfo->attr);
if (ret != HITLS_APP_SUCCESS) {
HITLS_PKCS12_Free(p12);
return ret;
}
BSL_Buffer value = {keyInfo->key, sizeof(keyInfo->key)};
ret = HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_VALUE, &value, 0);
HITLS_PKCS12_Free(p12);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("keymgmt: Failed to get key value, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
keyInfo->keyLen = value.dataLen;
return HITLS_APP_SUCCESS;
}
static int32_t PrepareOneKey(AppProvider *provider, HITLS_APP_SM_Param *smParam, uint8_t *buf, size_t *index)
{
HITLS_APP_KeyInfo keyInfo = {0};
int32_t ret = ReadCipherOrAsymKey(provider, smParam, &keyInfo);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
HITLS_SyncKeyInfo info = {0};
if (keyInfo.attr.algId == CRYPT_PKEY_SM2) {
ret = FillSyncKeyInfoFromSm2(&keyInfo, &info);
} else {
ret = FillSyncKeyInfoFromCipher(&keyInfo, &info);
}
FreeKeyInfo(&keyInfo);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
(void)memcpy_s(buf + *index, sizeof(HITLS_SyncKeyInfo), &info, sizeof(HITLS_SyncKeyInfo));
*index += sizeof(HITLS_SyncKeyInfo);
BSL_SAL_CleanseData(info.key, sizeof(info.key));
return HITLS_APP_SUCCESS;
}
static void PreparHeaderInfo(uint32_t n, uint8_t *buf, size_t *index)
{
uint32_t version = APP_KEYMGMT_SYNC_DATA_VERSION;
BSL_Uint32ToByte(version, (uint8_t *)&version);
(void)memcpy_s(buf, sizeof(uint32_t), &version, sizeof(uint32_t));
*index += sizeof(uint32_t);
BSL_Uint32ToByte(n, (uint8_t *)&n);
(void)memcpy_s(buf + *index, sizeof(uint32_t), &n, sizeof(uint32_t));
*index += sizeof(uint32_t);
}
int32_t HITLS_APP_SendKey(AppProvider *provider, HITLS_APP_SM_Param *smParam, HITLS_APP_SendFunc sendFunc, void *ctx)
{
if (provider == NULL || smParam == NULL || smParam->uuid == NULL || smParam->password == NULL ||
smParam->passwordLen == 0 || smParam->workPath == NULL || sendFunc == NULL) {
AppPrintError("keymgmt: Invalid argument to send key.\n");
return HITLS_APP_INVALID_ARG;
}
char *uuid = smParam->uuid;
BslList *uuidList = NULL;
int32_t ret = SplitUuidString(uuid, &uuidList);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
uint32_t n = BSL_LIST_COUNT(uuidList);
if (n == 0 || n > APP_KEYMGMT_MAX_KEY_COUNT) {
BSL_LIST_FREE(uuidList, BSL_SAL_Free);
AppPrintError("keymgmt: Invalid key count: %u.\n", n);
return HITLS_APP_INVALID_ARG;
}
size_t total = sizeof(uint32_t) + sizeof(uint32_t) + n * sizeof(HITLS_SyncKeyInfo);
uint8_t *buf = (uint8_t *)BSL_SAL_Malloc(total);
if (buf == NULL) {
BSL_LIST_FREE(uuidList, BSL_SAL_Free);
AppPrintError("keymgmt: Failed to allocate memory, len: %zu.\n", total);
return HITLS_APP_MEM_ALLOC_FAIL;
}
size_t index = 0;
PreparHeaderInfo(n, buf, &index);
smParam->uuid = BSL_LIST_GET_FIRST(uuidList);
for (uint32_t i = 0; i < n; i++) {
ret = PrepareOneKey(provider, smParam, buf, &index);
if (ret != HITLS_APP_SUCCESS) {
break;
}
smParam->uuid = BSL_LIST_GET_NEXT(uuidList);
}
smParam->uuid = uuid;
BSL_LIST_FREE(uuidList, BSL_SAL_Free);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_ClearFree(buf, index);
return ret;
}
ret = sendFunc(ctx, buf, index);
BSL_SAL_ClearFree(buf, index);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: TLCP send failed, errCode = 0x%x.\n", ret);
return ret;
}
return HITLS_APP_SUCCESS;
}
static int32_t CreateCipherKeyFromSyncInfo(const HITLS_SyncKeyInfo *info, HITLS_APP_KeyInfo *outKeyInfo)
{
if (info->keyLen > sizeof(outKeyInfo->key)) {
AppPrintError("keymgmt: Invalid keyLen: %d.\n", info->keyLen);
return HITLS_APP_INVALID_ARG;
}
(void)memcpy_s(outKeyInfo->key, sizeof(outKeyInfo->key), info->key, info->keyLen);
outKeyInfo->keyLen = info->keyLen;
return HITLS_APP_SUCCESS;
}
static int32_t CreateAndCheckAsymKey(AppProvider *provider, uint8_t *prv, uint32_t prvLen, uint8_t *pub,
uint32_t pubLen, CRYPT_EAL_PkeyCtx **pkey)
{
CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(APP_GetCurrent_LibCtx(), CRYPT_PKEY_SM2, 0,
provider->providerAttr);
if (pkeyCtx == NULL) {
AppPrintError("keymgmt: Failed to create the pkeyCtx.\n");
return HITLS_APP_CRYPTO_FAIL;
}
BSL_Param prvParam[] = {{0}, BSL_PARAM_END};
BSL_Param pubParam[] = {{0}, BSL_PARAM_END};
(void)BSL_PARAM_InitValue(&prvParam[0], CRYPT_PARAM_EC_PRVKEY, BSL_PARAM_TYPE_OCTETS, prv, prvLen);
(void)BSL_PARAM_InitValue(&pubParam[0], CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, pub, pubLen);
int32_t ret = CRYPT_EAL_PkeySetPrvEx(pkeyCtx, prvParam);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pkeyCtx);
AppPrintError("keymgmt: Failed to set prv key, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
ret = CRYPT_EAL_PkeySetPubEx(pkeyCtx, pubParam);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pkeyCtx);
AppPrintError("keymgmt: Failed to set pub key, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
ret = CRYPT_EAL_PkeyPairCheck(pkeyCtx, pkeyCtx);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pkeyCtx);
HITLS_APP_SM_PrintLog(ret);
AppPrintError("keymgmt: Check asymmetric key pairwise failed, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
*pkey = pkeyCtx;
return HITLS_APP_SUCCESS;
}
static int32_t CreateAsymKeyFromSyncInfo(AppProvider *provider, HITLS_SyncKeyInfo *info, HITLS_APP_KeyInfo *outKeyInfo)
{
if (info->keyLen < sizeof(uint32_t)) {
AppPrintError("keymgmt: Invalid keyLen: %d.\n", info->keyLen);
return HITLS_APP_INVALID_ARG;
}
uint32_t pubLen = 0;
(void)memcpy_s(&pubLen, sizeof(pubLen), info->key, sizeof(uint32_t));
pubLen = BSL_ByteToUint32((uint8_t *)&pubLen);
uint32_t pos = sizeof(uint32_t);
if (pubLen > info->keyLen - pos) {
AppPrintError("keymgmt: Invalid pubLen: %d.\n", pubLen);
return HITLS_APP_INVALID_ARG;
}
uint8_t *pub = info->key + pos;
pos += pubLen;
if (info->keyLen - pos < sizeof(uint32_t)) {
AppPrintError("keymgmt: Invalid keyLen: %d.\n", info->keyLen);
return HITLS_APP_INVALID_ARG;
}
uint32_t prvLen = 0;
(void)memcpy_s(&prvLen, sizeof(prvLen), info->key + pos, sizeof(uint32_t));
prvLen = BSL_ByteToUint32((uint8_t *)&prvLen);
pos += sizeof(uint32_t);
if (prvLen != info->keyLen - pos) {
AppPrintError("keymgmt: Invalid prvLen(%d) or keyLen(%d).\n", prvLen, info->keyLen);
return HITLS_APP_INVALID_ARG;
}
uint8_t *prv = info->key + pos;
return CreateAndCheckAsymKey(provider, prv, prvLen, pub, pubLen, &outKeyInfo->pkeyCtx);
}
static int32_t ParseAndWriteKeyFile(KeyMgmtCmdOpt *keyMgmtOpt, HITLS_SyncKeyInfo *info)
{
info->keyLen = BSL_ByteToUint32((uint8_t *)&info->keyLen);
if (info->keyLen > sizeof(info->key)) {
AppPrintError("keymgmt: Invalid keyLen: %d.\n", info->keyLen);
return HITLS_APP_INVALID_ARG;
}
KeyAttrOrderCvt(&info->attr, false);
HITLS_APP_KeyInfo keyInfo = {0};
(void)memcpy_s(&keyInfo.attr, sizeof(keyInfo.attr), &info->attr, sizeof(info->attr));
int32_t ret;
if (keyInfo.attr.algId == CRYPT_PKEY_SM2) {
ret = CreateAsymKeyFromSyncInfo(keyMgmtOpt->provider, info, &keyInfo);
} else {
ret = CreateCipherKeyFromSyncInfo(info, &keyInfo);
}
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
char uuidStr[APP_KEYMGMT_UUID_STR_LEN];
ret = HITLS_APP_OptToHex(keyInfo.attr.uuid, sizeof(keyInfo.attr.uuid), uuidStr, sizeof(uuidStr));
if (ret != HITLS_APP_SUCCESS) {
FreeKeyInfo(&keyInfo);
AppPrintError("keymgmt: Failed to convert uuid to hex, errCode: 0x%x.\n", ret);
return ret;
}
ret = HITLS_APP_WriteKey(keyMgmtOpt, &keyInfo, uuidStr);
FreeKeyInfo(&keyInfo);
return ret;
}
static int32_t CheckAndSetKdfParam(KeyMgmtCmdOpt *keyMgmtOpt, HITLS_APP_SM_Param *smParam, int32_t iter,
int32_t saltLen)
{
if (smParam == NULL || smParam->password == NULL || smParam->passwordLen == 0 ||
smParam->workPath == NULL) {
AppPrintError("keymgmt: The password is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
keyMgmtOpt->smParam = smParam;
keyMgmtOpt->iter = iter == -1 ? APP_KEYMGMT_PBKDF2_IT_DEFAULT_CNT : iter;
keyMgmtOpt->saltLen = saltLen == -1 ? APP_KEYMGMT_PBKDF2_SALT_DEFAULT_LEN : saltLen;
if (keyMgmtOpt->iter < APP_KEYMGMT_PBKDF2_IT_CNT_MIN) {
AppPrintError("keymgmt: The number of iterations is invalid, iter: %d.\n", keyMgmtOpt->iter);
return HITLS_APP_OPT_VALUE_INVALID;
}
if (keyMgmtOpt->saltLen < APP_KEYMGMT_PBKDF2_SALT_LEN_MIN) {
AppPrintError("keymgmt: The salt length is invalid, saltLen: %d.\n", keyMgmtOpt->saltLen);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_ReceiveKey(AppProvider *provider, HITLS_APP_SM_Param *smParam, int32_t iter, int32_t saltLen,
HITLS_APP_RecvFunc recvFunc, void *ctx)
{
uint32_t version = 0;
KeyMgmtCmdOpt keyMgmtOpt = {0};
keyMgmtOpt.provider = provider;
int32_t ret = CheckAndSetKdfParam(&keyMgmtOpt, smParam, iter, saltLen);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (recvFunc == NULL) {
AppPrintError("keymgmt: The recvFunc is invalid.\n");
return HITLS_APP_INVALID_ARG;
}
ret = recvFunc(ctx, &version, sizeof(uint32_t));
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: TLCP receive failed, errCode: 0x%x.\n", ret);
return ret;
}
version = BSL_ByteToUint32((uint8_t *)&version);
if (version != APP_KEYMGMT_SYNC_DATA_VERSION) {
AppPrintError("keymgmt: Version mismatch, version: %d, expected: %d.\n", version,
APP_KEYMGMT_SYNC_DATA_VERSION);
return HITLS_APP_INVALID_ARG;
}
uint32_t n = 0;
ret = recvFunc(ctx, &n, sizeof(uint32_t));
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: TLCP receive failed, errCode: 0x%x.\n", ret);
return ret;
}
n = BSL_ByteToUint32((uint8_t *)&n);
if (n == 0 || n > APP_KEYMGMT_MAX_KEY_COUNT) {
AppPrintError("keymgmt: Invalid n: %d.\n", n);
return HITLS_APP_INVALID_ARG;
}
HITLS_SyncKeyInfo keyInfo = {0};
for (uint32_t i = 0; i < n; i++) {
ret = recvFunc(ctx, &keyInfo, sizeof(HITLS_SyncKeyInfo));
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: TLCP receive failed, errCode: 0x%x.\n", ret);
return ret;
}
ret = ParseAndWriteKeyFile(&keyMgmtOpt, &keyInfo);
BSL_SAL_CleanseData(keyInfo.key, sizeof(keyInfo.key));
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("keymgmt: Failed to parse and write key file, errCode: 0x%x.\n", ret);
return ret;
}
}
return HITLS_APP_SUCCESS;
}
typedef struct {
const int cipherId;
const char *cipherAlgName;
} KeyMgmtAlgList;
static const KeyMgmtAlgList g_algIdList[] = {
// For SM4, only expose "sm4" (normal 16-byte key) and "sm4_xts" (32-byte key)
// Map "sm4" to SM4_CBC internally to reuse existing creation logic.
{CRYPT_CIPHER_SM4_CBC, "sm4"},
{CRYPT_CIPHER_SM4_XTS, "sm4_xts"},
{CRYPT_MAC_HMAC_SM3, "hmac-sm3"},
{CRYPT_MAC_CBC_MAC_SM4, "sm4-cbc-mac"},
{CRYPT_PKEY_SM2, "sm2"},
};
static void PrintAlgList(void)
{
AppPrintError("The current version supports only the following algorithms:\n");
for (size_t i = 0; i < sizeof(g_algIdList) / sizeof(g_algIdList[0]); i++) {
AppPrintError("%-19s", g_algIdList[i].cipherAlgName);
// 4 algorithm names are displayed in each row
if ((i + 1) % 4 == 0 && i != sizeof(g_algIdList) - 1) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return;
}
static int32_t GetAlgId(const char *name)
{
for (size_t i = 0; i < sizeof(g_algIdList) / sizeof(g_algIdList[0]); i++) {
if (strcmp(g_algIdList[i].cipherAlgName, name) == 0) {
return g_algIdList[i].cipherId;
}
}
PrintAlgList();
return -1;
}
// Determine whether an algorithm ID is an SM4 non-XTS mode
static bool IsSm4NormalAlg(int32_t algId)
{
switch (algId) {
case CRYPT_CIPHER_SM4_CBC:
case CRYPT_CIPHER_SM4_ECB:
case CRYPT_CIPHER_SM4_CTR:
case CRYPT_CIPHER_SM4_GCM:
case CRYPT_CIPHER_SM4_CFB:
case CRYPT_CIPHER_SM4_OFB:
return true;
default:
return false;
}
}
// Check whether the stored key algorithm matches the requested algorithm for FindKey
// For SM4, treat non-XTS modes as equivalent; XTS is distinct.
static int32_t CheckAlgMatchForFind(int32_t requestAlgId, int32_t storedAlgId)
{
if (IsSm4NormalAlg(requestAlgId)) {
if (!IsSm4NormalAlg(storedAlgId)) {
AppPrintError(
"keymgmt: The key file algorithm(%d) is not equal to the algorithm(%d) specified by the user.\n",
storedAlgId, requestAlgId);
return HITLS_APP_INVALID_ARG;
}
return HITLS_APP_SUCCESS;
}
if (storedAlgId != requestAlgId) {
AppPrintError("keymgmt: The key file algorithm(%d) is not equal to the algorithm(%d) specified by the user.\n",
storedAlgId, requestAlgId);
return HITLS_APP_INVALID_ARG;
}
return HITLS_APP_SUCCESS;
}
#endif
| 2401_83913325/openHiTLS_1 | apps/src/app_keymgmt.c | C | unknown | 56,860 |
/*
* 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 <string.h>
#include <stddef.h>
#include <securec.h>
#include "hitls_error.h"
#include "bsl_errno.h"
#include "bsl_uio.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_opt.h"
#include "crypt_algid.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_mac.h"
#include "crypt_eal_pkey.h"
#include "crypt_eal_md.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_kdf.h"
#include "app_list.h"
const HITLS_CmdOption g_listOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"all-algorithms", HITLS_APP_LIST_OPT_ALL_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported all algorthms"},
{"digest-algorithms", HITLS_APP_LIST_OPT_DGST_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE,
"List supported digest algorthms"},
{"cipher-algorithms", HITLS_APP_LIST_OPT_CIPHER_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE,
"List supported cipher algorthms"},
{"asym-algorithms", HITLS_APP_LIST_OPT_ASYM_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported asym algorthms"},
{"mac-algorithms", HITLS_APP_LIST_OPT_MAC_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported mac algorthms"},
{"rand-algorithms", HITLS_APP_LIST_OPT_RAND_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported rand algorthms"},
{"kdf-algorithms", HITLS_APP_LIST_OPT_KDF_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported kdf algorthms"},
{"all-curves", HITLS_APP_LIST_OPT_CURVES, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported curves"},
{NULL, 0, 0, NULL}};
typedef struct {
int32_t cid;
const char *name;
} CidInfo;
static const CidInfo g_allCipherAlgInfo [] = {
{CRYPT_CIPHER_AES128_CBC, "aes128-cbc"},
{CRYPT_CIPHER_AES128_CCM, "aes128-ccm"},
{CRYPT_CIPHER_AES128_CFB, "aes128-cfb"},
{CRYPT_CIPHER_AES128_CTR, "aes128-ctr"},
{CRYPT_CIPHER_AES128_ECB, "aes128-ecb"},
{CRYPT_CIPHER_AES128_GCM, "aes128-gcm"},
{CRYPT_CIPHER_AES128_OFB, "aes128-ofb"},
{CRYPT_CIPHER_AES128_XTS, "aes128-xts"},
{CRYPT_CIPHER_AES192_CBC, "aes192-cbc"},
{CRYPT_CIPHER_AES192_CCM, "aes192-ccm"},
{CRYPT_CIPHER_AES192_CFB, "aes192-cfb"},
{CRYPT_CIPHER_AES192_CTR, "aes192-ctr"},
{CRYPT_CIPHER_AES192_ECB, "aes192-ecb"},
{CRYPT_CIPHER_AES192_GCM, "aes192-gcm"},
{CRYPT_CIPHER_AES192_OFB, "aes192-ofb"},
{CRYPT_CIPHER_AES256_CBC, "aes256-cbc"},
{CRYPT_CIPHER_AES256_CCM, "aes256-ccm"},
{CRYPT_CIPHER_AES256_CFB, "aes256-cfb"},
{CRYPT_CIPHER_AES256_CTR, "aes256-ctr"},
{CRYPT_CIPHER_AES256_ECB, "aes256-ecb"},
{CRYPT_CIPHER_AES256_GCM, "aes256-gcm"},
{CRYPT_CIPHER_AES256_OFB, "aes256-ofb"},
{CRYPT_CIPHER_AES256_XTS, "aes256-xts"},
{CRYPT_CIPHER_CHACHA20_POLY1305, "chacha20-poly1305"},
{CRYPT_CIPHER_SM4_CBC, "sm4-cbc"},
{CRYPT_CIPHER_SM4_CFB, "sm4-cfb"},
{CRYPT_CIPHER_SM4_CTR, "sm4-ctr"},
{CRYPT_CIPHER_SM4_ECB, "sm4-ecb"},
{CRYPT_CIPHER_SM4_GCM, "sm4-gcm"},
{CRYPT_CIPHER_SM4_OFB, "sm4-ofb"},
{CRYPT_CIPHER_SM4_XTS, "sm4-xts"},
};
#define CIPHER_ALG_CNT (sizeof(g_allCipherAlgInfo) / sizeof(CidInfo))
static const CidInfo g_allMdAlgInfo[] = {
{CRYPT_MD_MD5, "md5"},
{CRYPT_MD_SHA1, "sha1"},
{CRYPT_MD_SHA224, "sha224"},
{CRYPT_MD_SHA256, "sha256"},
{CRYPT_MD_SHA384, "sha384"},
{CRYPT_MD_SHA512, "sha512"},
{CRYPT_MD_SHA3_224, "sha3-224"},
{CRYPT_MD_SHA3_256, "sha3-256"},
{CRYPT_MD_SHA3_384, "sha3-384"},
{CRYPT_MD_SHA3_512, "sha3-512"},
{CRYPT_MD_SHAKE128, "shake128"},
{CRYPT_MD_SHAKE256, "shake256"},
{CRYPT_MD_SM3, "sm3"},
};
#define MD_ALG_CNT (sizeof(g_allMdAlgInfo) / sizeof(CidInfo))
static const CidInfo g_allPkeyAlgInfo[] = {
{CRYPT_PKEY_ECDH, "ecdh"},
{CRYPT_PKEY_ECDSA, "ecdsa"},
{CRYPT_PKEY_ED25519, "ed25519"},
{CRYPT_PKEY_DH, "dh"},
{CRYPT_PKEY_DSA, "dsa"},
{CRYPT_PKEY_RSA, "rsa"},
{CRYPT_PKEY_SM2, "sm2"},
{CRYPT_PKEY_X25519, "x25519"},
};
#define PKEY_ALG_CNT (sizeof(g_allPkeyAlgInfo) / sizeof(CidInfo))
static const CidInfo g_allMacAlgInfo[] = {
{CRYPT_MAC_HMAC_MD5, "hmac-md5"},
{CRYPT_MAC_HMAC_SHA1, "hmac-sha1"},
{CRYPT_MAC_HMAC_SHA224, "hmac-sha224"},
{CRYPT_MAC_HMAC_SHA256, "hmac-sha256"},
{CRYPT_MAC_HMAC_SHA384, "hmac-sha384"},
{CRYPT_MAC_HMAC_SHA512, "hmac-sha512"},
{CRYPT_MAC_HMAC_SHA3_224, "hmac-sha3-224"},
{CRYPT_MAC_HMAC_SHA3_256, "hmac-sha3-256"},
{CRYPT_MAC_HMAC_SHA3_384, "hmac-sha3-384"},
{CRYPT_MAC_HMAC_SHA3_512, "hmac-sha3-512"},
{CRYPT_MAC_HMAC_SM3, "hmac-sm3"},
{CRYPT_MAC_CMAC_AES128, "cmac-aes128"},
{CRYPT_MAC_CMAC_AES192, "cmac-aes192"},
{CRYPT_MAC_CMAC_AES256, "cmac-aes256"},
{CRYPT_MAC_GMAC_AES128, "gmac-aes128"},
{CRYPT_MAC_GMAC_AES192, "gmac-aes192"},
{CRYPT_MAC_GMAC_AES256, "gmac-aes256"},
{CRYPT_MAC_SIPHASH64, "siphash64"},
{CRYPT_MAC_SIPHASH128, "siphash128"},
{CRYPT_MAC_CBC_MAC_SM4, "sm4-cbc-mac"},
};
#define MAC_ALG_CNT (sizeof(g_allMacAlgInfo) / sizeof(CidInfo))
static const CidInfo g_allRandAlgInfo[] = {
{CRYPT_RAND_SHA1, "sha1"},
{CRYPT_RAND_SHA224, "sha224"},
{CRYPT_RAND_SHA256, "sha256"},
{CRYPT_RAND_SHA384, "sha384"},
{CRYPT_RAND_SHA512, "sha512"},
{CRYPT_RAND_SM3, "sm3"},
{CRYPT_RAND_HMAC_SHA1, "hmac-sha1"},
{CRYPT_RAND_HMAC_SHA224, "hmac-sha224"},
{CRYPT_RAND_HMAC_SHA256, "hmac-sha256"},
{CRYPT_RAND_HMAC_SHA384, "hmac-sha384"},
{CRYPT_RAND_HMAC_SHA512, "hmac-sha512"},
{CRYPT_RAND_AES128_CTR, "aes128-ctr"},
{CRYPT_RAND_AES192_CTR, "aes192-ctr"},
{CRYPT_RAND_AES256_CTR, "aes256-ctr"},
{CRYPT_RAND_AES128_CTR_DF, "aes128-ctr-df"},
{CRYPT_RAND_AES192_CTR_DF, "aes192-ctr-df"},
{CRYPT_RAND_AES256_CTR_DF, "aes256-ctr-df"},
{CRYPT_RAND_SM4_CTR_DF, "sm4-ctr-df"},
};
#define RAND_ALG_CNT (sizeof(g_allRandAlgInfo) / sizeof(CidInfo))
static const CidInfo g_allKdfAlgInfo[] = {
{CRYPT_MAC_HMAC_MD5, "hmac-md5"},
{CRYPT_MAC_HMAC_SHA1, "hmac-sha1"},
{CRYPT_MAC_HMAC_SHA224, "hmac-sha224"},
{CRYPT_MAC_HMAC_SHA256, "hmac-sha256"},
{CRYPT_MAC_HMAC_SHA384, "hmac-sha384"},
{CRYPT_MAC_HMAC_SHA512, "hmac-sha512"},
{CRYPT_MAC_HMAC_SHA3_224, "hmac-sha3-224"},
{CRYPT_MAC_HMAC_SHA3_256, "hmac-sha3-256"},
{CRYPT_MAC_HMAC_SHA3_384, "hmac-sha3-384"},
{CRYPT_MAC_HMAC_SHA3_512, "hmac-sha3-512"},
{CRYPT_MAC_HMAC_SM3, "hmac-sm3"},
{CRYPT_KDF_PBKDF2, "pbkdf2"},
};
#define KDF_ALG_CNT (sizeof(g_allKdfAlgInfo) / sizeof(CidInfo))
static CidInfo g_allCurves[] = {
{CRYPT_ECC_NISTP224, "P-224"},
{CRYPT_ECC_NISTP256, "P-256"},
{CRYPT_ECC_NISTP384, "P-384"},
{CRYPT_ECC_NISTP521, "P-521"},
{CRYPT_ECC_NISTP224, "prime224v1"},
{CRYPT_ECC_NISTP256, "prime256v1"},
{CRYPT_ECC_NISTP384, "secp384r1"},
{CRYPT_ECC_NISTP521, "secp521r1"},
{CRYPT_ECC_BRAINPOOLP256R1, "brainpoolp256r1"},
{CRYPT_ECC_BRAINPOOLP384R1, "brainpoolp384r1"},
{CRYPT_ECC_BRAINPOOLP512R1, "brainpoolp512r1"},
{CRYPT_ECC_SM2, "sm2"},
};
#define CURVES_SPLIT_LINE 6
#define CURVES_CNT (sizeof(g_allCurves) / sizeof(CidInfo))
typedef void (*PrintAlgFunc)(void);
PrintAlgFunc g_printAlgFuncList[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
#define PRINT_ALG_FUNC_LIST_CNT (sizeof(g_printAlgFuncList) / sizeof(PrintAlgFunc))
static void AppPushPrintFunc(PrintAlgFunc func)
{
for (size_t i = 0; i < PRINT_ALG_FUNC_LIST_CNT; ++i) {
if ((g_printAlgFuncList[i] == NULL) || (g_printAlgFuncList[i] == func)) {
g_printAlgFuncList[i] = func;
return;
}
}
}
static void AppPrintList(void)
{
for (size_t i = 0; i < PRINT_ALG_FUNC_LIST_CNT; ++i) {
if ((g_printAlgFuncList[i] != NULL)) {
g_printAlgFuncList[i]();
}
}
}
static void ResetPrintAlgFuncList(void)
{
for (size_t i = 0; i < PRINT_ALG_FUNC_LIST_CNT; ++i) {
g_printAlgFuncList[i] = NULL;
}
}
static BSL_UIO *g_stdout = NULL;
static int32_t AppPrintStdoutUioInit(void)
{
g_stdout = BSL_UIO_New(BSL_UIO_FileMethod());
if (BSL_UIO_Ctrl(g_stdout, BSL_UIO_FILE_PTR, 0, (void *)stdout) != BSL_SUCCESS) {
AppPrintError("Failed to set stdout mode.\n");
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static void AppPrintStdoutUioUnInit(void)
{
BSL_UIO_Free(g_stdout);
}
static void PrintCipherAlg(void)
{
AppPrint(g_stdout, "List Cipher Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < CIPHER_ALG_CNT; ++i) {
if (!CRYPT_EAL_CipherIsValidAlgId(g_allCipherAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allCipherAlgInfo[i].name, g_allCipherAlgInfo[i].cid);
}
}
static void PrintMdAlg(void)
{
AppPrint(g_stdout, "List Digest Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < MD_ALG_CNT; ++i) {
if (!CRYPT_EAL_MdIsValidAlgId(g_allMdAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allMdAlgInfo[i].name, g_allMdAlgInfo[i].cid);
}
}
static void PrintPkeyAlg(void)
{
AppPrint(g_stdout, "List Asym Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < PKEY_ALG_CNT; ++i) {
if (!CRYPT_EAL_PkeyIsValidAlgId(g_allPkeyAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allPkeyAlgInfo[i].name, g_allPkeyAlgInfo[i].cid);
}
}
static void PrintMacAlg(void)
{
AppPrint(g_stdout, "List Mac Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < MAC_ALG_CNT; ++i) {
if (!CRYPT_EAL_MacIsValidAlgId(g_allMacAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allMacAlgInfo[i].name, g_allMacAlgInfo[i].cid);
}
}
static void PrintRandAlg(void)
{
AppPrint(g_stdout, "List Rand Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < RAND_ALG_CNT; ++i) {
if (!CRYPT_EAL_RandIsValidAlgId(g_allRandAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allRandAlgInfo[i].name, g_allRandAlgInfo[i].cid);
}
}
static void PrintHkdfAlg(void)
{
AppPrint(g_stdout, "List Hkdf Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < KDF_ALG_CNT; ++i) {
if (!CRYPT_EAL_KdfIsValidAlgId(g_allKdfAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allKdfAlgInfo[i].name, g_allKdfAlgInfo[i].cid);
}
}
static void PrintPbkdf2Alg(void)
{
AppPrint(g_stdout, "List Pbkdf2 Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < KDF_ALG_CNT; ++i) {
if (!CRYPT_EAL_KdfIsValidAlgId(g_allKdfAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allKdfAlgInfo[i].name, g_allKdfAlgInfo[i].cid);
}
}
static void PrintKdftls12Alg(void)
{
AppPrint(g_stdout, "List Kdftls12 Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < KDF_ALG_CNT; ++i) {
if (!CRYPT_EAL_KdfIsValidAlgId(g_allKdfAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allKdfAlgInfo[i].name, g_allKdfAlgInfo[i].cid);
}
}
static void PrintKdfAlg(void)
{
PrintHkdfAlg();
AppPrint(g_stdout, "\n");
PrintPbkdf2Alg();
AppPrint(g_stdout, "\n");
PrintKdftls12Alg();
}
static void PrintAllAlg(void)
{
PrintCipherAlg();
AppPrint(g_stdout, "\n");
PrintMdAlg();
AppPrint(g_stdout, "\n");
PrintPkeyAlg();
AppPrint(g_stdout, "\n");
PrintMacAlg();
AppPrint(g_stdout, "\n");
PrintRandAlg();
AppPrint(g_stdout, "\n");
PrintKdfAlg();
}
static void PrintCurves(void)
{
AppPrint(g_stdout, "List Curves:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < CURVES_CNT; ++i) {
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allCurves[i].name, g_allCurves[i].cid);
}
}
static int32_t ParseListOpt(void)
{
bool isEmptyOpt = true;
int optType = HITLS_APP_OPT_ERR;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
isEmptyOpt = false;
switch (optType) {
case HITLS_APP_OPT_HELP:
HITLS_APP_OptHelpPrint(g_listOpts);
return HITLS_APP_HELP;
case HITLS_APP_OPT_ERR:
AppPrintError("list: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_LIST_OPT_ALL_ALG:
AppPushPrintFunc(PrintAllAlg);
break;
case HITLS_APP_LIST_OPT_DGST_ALG:
AppPushPrintFunc(PrintMdAlg);
break;
case HITLS_APP_LIST_OPT_CIPHER_ALG:
AppPushPrintFunc(PrintCipherAlg);
break;
case HITLS_APP_LIST_OPT_ASYM_ALG:
AppPushPrintFunc(PrintPkeyAlg);
break;
case HITLS_APP_LIST_OPT_MAC_ALG:
AppPushPrintFunc(PrintMacAlg);
break;
case HITLS_APP_LIST_OPT_RAND_ALG:
AppPushPrintFunc(PrintRandAlg);
break;
case HITLS_APP_LIST_OPT_KDF_ALG:
AppPushPrintFunc(PrintKdfAlg);
break;
case HITLS_APP_LIST_OPT_CURVES:
AppPushPrintFunc(PrintCurves);
break;
default:
break;
}
}
// Get the number of parameters that cannot be parsed in the current version
// and print the error information and help list.
if ((HITLS_APP_GetRestOptNum() != 0) || isEmptyOpt) {
AppPrintError("Extra arguments given.\n");
AppPrintError("list: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
// List main function
int32_t HITLS_ListMain(int argc, char *argv[])
{
ResetPrintAlgFuncList();
int32_t ret = HITLS_APP_SUCCESS;
do {
ret = AppPrintStdoutUioInit();
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = HITLS_APP_OptBegin(argc, argv, g_listOpts);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
break;
}
ret = ParseListOpt();
if (ret != HITLS_APP_SUCCESS) {
break;
}
AppPrintList();
} while (false);
HITLS_APP_OptEnd();
AppPrintStdoutUioUnInit();
return ret;
}
static int32_t GetInfoByType(int32_t type, const CidInfo **cidInfos, uint32_t *cnt, char **typeName)
{
switch (type) {
case HITLS_APP_LIST_OPT_DGST_ALG:
*cidInfos = g_allMdAlgInfo;
*cnt = MD_ALG_CNT;
*typeName = "dgst";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_CIPHER_ALG:
*cidInfos = g_allCipherAlgInfo;
*cnt = CIPHER_ALG_CNT;
*typeName = "cipher";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_ASYM_ALG:
*cidInfos = g_allPkeyAlgInfo;
*cnt = PKEY_ALG_CNT;
*typeName = "asym";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_MAC_ALG:
*cidInfos = g_allMacAlgInfo;
*cnt = MAC_ALG_CNT;
*typeName = "mac";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_RAND_ALG:
*cidInfos = g_allRandAlgInfo;
*cnt = RAND_ALG_CNT;
*typeName = "rand";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_KDF_ALG:
*cidInfos = g_allKdfAlgInfo;
*cnt = KDF_ALG_CNT;
*typeName = "kdf";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_CURVES:
*cidInfos = g_allCurves;
*cnt = CURVES_CNT;
*typeName = "curves";
return HITLS_APP_SUCCESS;
default:
return HITLS_APP_INVALID_ARG;
}
}
int32_t HITLS_APP_GetCidByName(const char *name, int32_t type)
{
if (name == NULL) {
return BSL_CID_UNKNOWN;
}
const CidInfo *cidInfos = NULL;
uint32_t cnt = 0;
char *typeName;
int32_t ret = GetInfoByType(type, &cidInfos, &cnt, &typeName);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Get cid info by name failed, name: %s\n", name);
return BSL_CID_UNKNOWN;
}
for (size_t i = 0; i < cnt; ++i) {
if (strcmp(name, cidInfos[i].name) == 0) {
return (BslCid)cidInfos[i].cid;
}
}
AppPrintError("Unsupport %s: %s\n", typeName, name);
return BSL_CID_UNKNOWN;
}
const char *HITLS_APP_GetNameByCid(int32_t cid, int32_t type)
{
const CidInfo *cidInfos = NULL;
uint32_t cnt = 0;
char *typeName;
int32_t ret = GetInfoByType(type, &cidInfos, &cnt, &typeName);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Get cid info by cid failed, cid: %d\n", cid);
return NULL;
}
for (size_t i = 0; i < cnt; ++i) {
if (cid == cidInfos[i].cid) {
return cidInfos[i].name;
}
}
AppPrintError("Unsupport %s: %d\n", typeName, cid);
return NULL;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_list.c | C | unknown | 17,979 |
/*
* 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 "app_mac.h"
#include <limits.h>
#include "string.h"
#include "securec.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_eal_mac.h"
#include "bsl_errno.h"
#include "app_opt.h"
#include "app_function.h"
#include "app_list.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_provider.h"
#include "app_utils.h"
#include "app_sm.h"
#include "app_keymgmt.h"
#define MAX_BUFSIZE (1024 * 8) // Indicates the length of a single mac during mac calculation.
#define IS_SUPPORT_GET_EOF 1
#define MAC_MAX_KEY_LEN 64
typedef enum OptionChoice {
HITLS_APP_OPT_MAC_ERR = -1,
HITLS_APP_OPT_MAC_EOF = 0,
HITLS_APP_OPT_MAC_HELP = 1, // The value of the help type of each opt option is 1. The following can be customized.
HITLS_APP_OPT_MAC_ALG,
HITLS_APP_OPT_MAC_IN,
HITLS_APP_OPT_MAC_OUT,
HITLS_APP_OPT_MAC_BINARY,
HITLS_APP_OPT_MAC_KEY,
HITLS_APP_OPT_MAC_HEXKEY,
HITLS_APP_PROV_ENUM,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS_ENUM,
#endif
} HITLSOptType;
const HITLS_CmdOption g_macOpts[] = {
{"help", HITLS_APP_OPT_MAC_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Show usage information for MAC command."},
{"name", HITLS_APP_OPT_MAC_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Specify MAC algorithm (e.g., hmac-sha256)."},
{"in", HITLS_APP_OPT_MAC_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE,
"Set input file for MAC computation (default: stdin)."},
{"out", HITLS_APP_OPT_MAC_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE,
"Set output file for MAC result (default: stdout)."},
{"binary", HITLS_APP_OPT_MAC_BINARY, HITLS_APP_OPT_VALUETYPE_NO_VALUE,
"Output MAC result in binary format."},
{"key", HITLS_APP_OPT_MAC_KEY, HITLS_APP_OPT_VALUETYPE_STRING,
"Input encryption key as a string."},
{"hexkey", HITLS_APP_OPT_MAC_HEXKEY, HITLS_APP_OPT_VALUETYPE_STRING,
"Input encryption key in hexadecimal format (e.g., 0x1234ABCD)."},
HITLS_APP_PROV_OPTIONS,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS,
#endif
{NULL, 0, 0, NULL}};
typedef struct {
int32_t algId;
uint32_t macSize;
uint32_t isBinary;
char *inFile;
uint8_t readBuf[MAX_BUFSIZE];
uint32_t readLen;
char *outFile;
char *key;
char *hexKey;
uint32_t keyLen;
AppProvider *provider;
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param *smParam;
#endif
} MacOpt;
typedef int32_t (*MacOptHandleFunc)(MacOpt *);
typedef struct {
int32_t optType;
MacOptHandleFunc func;
} MacOptHandleFuncMap;
static int32_t MacOptErr(MacOpt *macOpt)
{
(void)macOpt;
AppPrintError("mac: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t MacOptHelp(MacOpt *macOpt)
{
(void)macOpt;
HITLS_APP_OptHelpPrint(g_macOpts);
return HITLS_APP_HELP;
}
static int32_t MacOptIn(MacOpt *macOpt)
{
macOpt->inFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t MacOptOut(MacOpt *macOpt)
{
macOpt->outFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t MacOptKey(MacOpt *macOpt)
{
macOpt->key = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t MacOptHexKey(MacOpt *macOpt)
{
macOpt->hexKey = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t MacOptBinary(MacOpt *macOpt)
{
macOpt->isBinary = 1;
return HITLS_APP_SUCCESS;
}
static int32_t MacOptAlg(MacOpt *macOpt)
{
char *algName = HITLS_APP_OptGetValueStr();
if (algName == NULL) {
return HITLS_APP_OPT_VALUE_INVALID;
}
macOpt->algId = HITLS_APP_GetCidByName(algName, HITLS_APP_LIST_OPT_MAC_ALG);
if (macOpt->algId == BSL_CID_UNKNOWN) {
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static const MacOptHandleFuncMap g_macOptHandleFuncMap[] = {
{HITLS_APP_OPT_MAC_ERR, MacOptErr},
{HITLS_APP_OPT_MAC_HELP, MacOptHelp},
{HITLS_APP_OPT_MAC_IN, MacOptIn},
{HITLS_APP_OPT_MAC_OUT, MacOptOut},
{HITLS_APP_OPT_MAC_KEY, MacOptKey},
{HITLS_APP_OPT_MAC_HEXKEY, MacOptHexKey},
{HITLS_APP_OPT_MAC_BINARY, MacOptBinary},
{HITLS_APP_OPT_MAC_ALG, MacOptAlg},
};
static int32_t ParseMacOpt(MacOpt *macOpt)
{
int ret = HITLS_APP_SUCCESS;
int optType = HITLS_APP_OPT_MAC_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_MAC_EOF)) {
for (size_t i = 0; i < sizeof(g_macOptHandleFuncMap) / sizeof(g_macOptHandleFuncMap[0]); ++i) {
if (optType == g_macOptHandleFuncMap[i].optType) {
ret = g_macOptHandleFuncMap[i].func(macOpt);
break;
}
}
HITLS_APP_PROV_CASES(optType, macOpt->provider);
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_CASES(optType, macOpt->smParam);
#endif
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
}
if (HITLS_APP_GetRestOptNum() != 0) {
AppPrintError("Extra arguments given.\n");
AppPrintError("mac: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckKeyParam(MacOpt *macOpt)
{
#ifdef HITLS_APP_SM_MODE
if (macOpt->smParam->smTag == 1) {
if (macOpt->smParam->uuid == NULL) {
AppPrintError("mac: The uuid is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (macOpt->smParam->workPath == NULL) {
AppPrintError("mac: The workpath is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
#endif
if (macOpt->key == NULL && macOpt->hexKey == NULL) {
AppPrintError("mac: No key entered.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (macOpt->key != NULL && macOpt->hexKey != NULL) {
AppPrintError("mac: Cannot specify both key and hexkey.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckParam(MacOpt *macOpt)
{
int32_t ret = CheckKeyParam(macOpt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (macOpt->inFile != NULL && strlen((const char*)macOpt->inFile) > PATH_MAX) {
AppPrintError("mac: The input file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (macOpt->outFile != NULL && strlen((const char*)macOpt->outFile) > PATH_MAX) {
AppPrintError("mac: The output file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
#ifdef HITLS_APP_SM_MODE
static int32_t GetKeyFromP12(MacOpt *macOpt, uint8_t **key, uint32_t *keyLen)
{
HITLS_APP_KeyInfo keyInfo = {0};
int32_t ret = HITLS_APP_FindKey(macOpt->provider, macOpt->smParam, macOpt->algId, &keyInfo);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("mac: Failed to find key, errCode: 0x%x.\n", ret);
return ret;
}
*key = (uint8_t*)BSL_SAL_Dump(keyInfo.key, keyInfo.keyLen);
if (*key == NULL) {
(void)BSL_SAL_CleanseData(keyInfo.key, keyInfo.keyLen);
AppPrintError("mac: Failed to dump key, keyLen: %u.\n", keyInfo.keyLen);
return HITLS_APP_MEM_ALLOC_FAIL;
}
*keyLen = keyInfo.keyLen;
(void)BSL_SAL_CleanseData(keyInfo.key, keyInfo.keyLen);
return HITLS_APP_SUCCESS;
}
#endif
static int32_t GetMacKey(MacOpt *macOpt, uint8_t **key, uint32_t *keyLen)
{
#ifdef HITLS_APP_SM_MODE
if (macOpt->smParam->smTag == 1) {
return GetKeyFromP12(macOpt, key, keyLen);
}
#endif
size_t len;
if (macOpt->key != NULL) {
len = strlen((const char *)macOpt->key);
} else {
len = strlen((const char *)macOpt->hexKey);
}
if (len > UINT32_MAX) {
AppPrintError("mac: key length overflow.\n");
return HITLS_APP_INVALID_ARG;
}
if (macOpt->key != NULL) {
*key = (uint8_t *)BSL_SAL_Dump(macOpt->key, strlen(macOpt->key));
if (*key == NULL) {
AppPrintError("mac: Failed to dump key, keyLen: %u.\n", strlen(macOpt->key));
return HITLS_APP_MEM_ALLOC_FAIL;
}
*keyLen = strlen(macOpt->key);
return HITLS_APP_SUCCESS;
} else if (macOpt->hexKey != NULL) {
int32_t ret = HITLS_APP_HexToByte(macOpt->hexKey, key, keyLen);
if (ret == HITLS_APP_OPT_VALUE_INVALID) {
AppPrintError("mac: Get key from hexkey failed, errCode: 0x%x.\n", ret);
return ret;
}
return HITLS_APP_SUCCESS;
}
return HITLS_APP_OPT_VALUE_INVALID;
}
static CRYPT_EAL_MacCtx *InitAlgMac(MacOpt *macOpt)
{
uint8_t *key = NULL;
uint32_t keyLen = 0;
int32_t ret = GetMacKey(macOpt, &key, &keyLen);
if (ret != HITLS_APP_SUCCESS) {
return NULL;
}
CRYPT_EAL_MacCtx *ctx = NULL;
do {
ctx = CRYPT_EAL_ProviderMacNewCtx(APP_GetCurrent_LibCtx(), macOpt->algId,
macOpt->provider->providerAttr); // creating an MAC Context
if (ctx == NULL) {
(void)AppPrintError("mac:Failed to create the algorithm(%d) context\n", macOpt->algId);
break;
}
ret = CRYPT_EAL_MacInit(ctx, key, keyLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("mac:Summary context creation failed, ret=%d\n", ret);
CRYPT_EAL_MacFreeCtx(ctx);
ctx = NULL;
break;
}
} while (0);
BSL_SAL_ClearFree(key, keyLen);
return ctx;
}
static int32_t MacParamSet(CRYPT_EAL_MacCtx *ctx, MacOpt *macOpt)
{
int32_t ret = HITLS_APP_SUCCESS;
uint32_t padding = CRYPT_PADDING_ZEROS;
if (macOpt->algId == CRYPT_MAC_CBC_MAC_SM4) {
ret = CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padding, sizeof(CRYPT_PaddingType));
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("mac:Failed to set CBC MAC padding, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
}
}
return ret;
}
static int32_t GetReadBuf(CRYPT_EAL_MacCtx *ctx, MacOpt *macOpt)
{
int32_t ret;
bool isEof = false;
uint32_t readLen = 0;
uint64_t readFileLen = 0;
uint8_t *tmpBuf = (uint8_t *)BSL_SAL_Calloc(MAX_BUFSIZE, sizeof(uint8_t));
if (tmpBuf == NULL) {
AppPrintError("mac: Failed to allocate read buffer.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
BSL_UIO *readUio = HITLS_APP_UioOpen(macOpt->inFile, 'r', 0);
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
if (readUio == NULL) {
if (macOpt->inFile == NULL) {
AppPrintError("mac: Failed to open stdin\n");
} else {
AppPrintError("mac: Failed to open the file <%s>, No such file or directory\n", macOpt->inFile);
}
BSL_SAL_FREE(tmpBuf);
return HITLS_APP_UIO_FAIL;
}
if (macOpt->inFile == NULL) {
while (BSL_UIO_Ctrl(readUio, BSL_UIO_FILE_GET_EOF, IS_SUPPORT_GET_EOF, &isEof) == BSL_SUCCESS && !isEof) {
if (BSL_UIO_Read(readUio, tmpBuf, MAX_BUFSIZE, &readLen) != BSL_SUCCESS) {
BSL_SAL_FREE(tmpBuf);
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to obtain the content from the STDIN\n");
return HITLS_APP_STDIN_FAIL;
}
if (readLen == 0) {
break;
}
ret = CRYPT_EAL_MacUpdate(ctx, tmpBuf, readLen);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(tmpBuf);
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to continuously summarize the STDIN content\n");
return HITLS_APP_CRYPTO_FAIL;
}
}
} else {
ret = BSL_UIO_Ctrl(readUio, BSL_UIO_PENDING, sizeof(readFileLen), &readFileLen);
if (ret != BSL_SUCCESS) {
BSL_SAL_FREE(tmpBuf);
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to obtain the content length\n");
return HITLS_APP_UIO_FAIL;
}
while (readFileLen > 0) {
uint32_t bufLen = (readFileLen > MAX_BUFSIZE) ? MAX_BUFSIZE : (uint32_t)readFileLen;
ret = BSL_UIO_Read(readUio, tmpBuf, bufLen, &readLen); // read content to memory
if (ret != BSL_SUCCESS || bufLen != readLen) {
BSL_SAL_FREE(tmpBuf);
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to read the input content\n");
return HITLS_APP_UIO_FAIL;
}
ret = CRYPT_EAL_MacUpdate(ctx, tmpBuf, bufLen); // continuously enter summary content
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(tmpBuf);
BSL_UIO_Free(readUio);
(void)AppPrintError("mac: Failed to update MAC with file content, error code: %d\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
readFileLen -= bufLen;
}
}
BSL_UIO_Free(readUio);
BSL_SAL_FREE(tmpBuf);
return HITLS_APP_SUCCESS;
}
static int32_t MacResult(CRYPT_EAL_MacCtx *ctx, MacOpt *macOpt)
{
uint8_t *outBuf = NULL;
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(macOpt->outFile, 'w', 0); // overwrite the original content
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
if (fileWriteUio == NULL) {
(void)AppPrintError("Failed to open the outfile\n");
return HITLS_APP_UIO_FAIL;
}
uint32_t macSize = CRYPT_EAL_GetMacLen(ctx);
if (macSize <= 0) {
AppPrintError("mac: Invalid MAC size: %u\n", macSize);
BSL_UIO_Free(fileWriteUio);
return HITLS_APP_CRYPTO_FAIL;
}
outBuf = (uint8_t *)BSL_SAL_Calloc(macSize, sizeof(uint8_t));
if (outBuf == NULL) {
AppPrintError("mac: Failed to allocate MAC buffer.\n");
BSL_UIO_Free(fileWriteUio);
return HITLS_APP_MEM_ALLOC_FAIL;
}
uint32_t macBufLen = macSize;
int32_t ret = CRYPT_EAL_MacFinal(ctx, outBuf, &macBufLen);
if (ret != CRYPT_SUCCESS || macBufLen < macSize) {
BSL_SAL_FREE(outBuf);
(void)AppPrintError("mac: Failed to complete the final summary. ERR:%d\n", ret);
BSL_UIO_Free(fileWriteUio);
return HITLS_APP_CRYPTO_FAIL;
}
ret = HITLS_APP_OptWriteUio(fileWriteUio, outBuf, macBufLen,
macOpt->isBinary == 1 ? HITLS_APP_FORMAT_TEXT: HITLS_APP_FORMAT_HEX);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("mac:Failed to export data to the outfile path\n");
}
BSL_UIO_Free(fileWriteUio);
BSL_SAL_FREE(outBuf);
return ret;
}
static int32_t HandleMac(MacOpt *macOpt)
{
CRYPT_EAL_MacCtx *ctx = NULL;
int32_t ret = HITLS_APP_SUCCESS;
do {
ctx = InitAlgMac(macOpt);
if (ctx == NULL) {
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = MacParamSet(ctx, macOpt);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("mac: Failed to set mac params, errCode: 0x%x.\n", ret);
break;
}
#ifdef HITLS_APP_SM_MODE
if (macOpt->smParam->smTag == 1) {
macOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
}
#endif
ret = GetReadBuf(ctx, macOpt);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = MacResult(ctx, macOpt);
} while (0);
CRYPT_EAL_MacFreeCtx(ctx);
return ret;
}
int32_t HITLS_MacMain(int argc, char *argv[])
{
int32_t mainRet = HITLS_APP_SUCCESS;
AppProvider appProvider = {NULL, NULL, NULL};
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param smParam = {NULL, 0, NULL, NULL, 0, HITLS_APP_SM_STATUS_OPEN};
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider, &smParam};
MacOpt macOpt = {CRYPT_MAC_HMAC_SM3, 0, 0, NULL, {0}, 0, NULL, NULL, NULL, 0, &appProvider, &smParam};
#else
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider};
MacOpt macOpt = {CRYPT_MAC_HMAC_SHA256, 0, 0, NULL, {0}, 0, NULL, NULL, NULL, 0, &appProvider};
#endif
do {
mainRet = HITLS_APP_OptBegin(argc, argv, g_macOpts);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("error in opt begin.\n");
break;
}
mainRet = ParseMacOpt(&macOpt);
if (mainRet != HITLS_APP_SUCCESS) {
break;
}
mainRet = CheckParam(&macOpt);
if (mainRet != HITLS_APP_SUCCESS) {
break;
}
mainRet = HITLS_APP_Init(&initParam);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("mac: Failed to init, errCode: 0x%x.\n", mainRet);
break;
}
mainRet = HandleMac(&macOpt);
} while (0);
HITLS_APP_Deinit(&initParam, mainRet);
HITLS_APP_OptEnd();
return mainRet;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_mac.c | C | unknown | 17,300 |
/*
* 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 "app_opt.h"
#include <stdint.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <errno.h>
#include <libgen.h>
#include <sys/stat.h>
#include <stdbool.h>
#include "securec.h"
#include "app_errno.h"
#include "bsl_sal.h"
#include "app_print.h"
#include "bsl_uio.h"
#include "bsl_errno.h"
#include "bsl_base64.h"
#define MAX_HITLS_APP_OPT_NAME_WIDTH 40
#define MAX_HITLS_APP_OPT_LINE_WIDTH 80
typedef struct {
int32_t optIndex;
int32_t argc;
char *valueStr;
char progName[128];
char **argv;
const HITLS_CmdOption *opts;
} HITLS_CmdOptState;
static HITLS_CmdOptState g_cmdOptState = {0};
static const HITLS_CmdOption *g_unKnownOpt = NULL;
static char *g_unKownName = NULL;
const char *HITLS_APP_OptGetUnKownOptName(void)
{
return g_unKownName;
}
static void GetProgName(const char *filePath)
{
const char *p = NULL;
for (p = filePath + strlen(filePath); --p > filePath;) {
if (*p == '/') {
p++;
break;
}
}
// Avoid consistency between source and destination addresses.
if (p != g_cmdOptState.progName) {
(void)strncpy_s(
g_cmdOptState.progName, sizeof(g_cmdOptState.progName) - 1, p, sizeof(g_cmdOptState.progName) - 1);
}
g_cmdOptState.progName[sizeof(g_cmdOptState.progName) - 1] = '\0';
}
static void CmdOptStateInit(int32_t index, int32_t argc, char **argv, const HITLS_CmdOption *opts)
{
g_cmdOptState.optIndex = index;
g_cmdOptState.argc = argc;
g_cmdOptState.argv = argv;
g_cmdOptState.opts = opts;
(void)memset_s(g_cmdOptState.progName, sizeof(g_cmdOptState.progName), 0, sizeof(g_cmdOptState.progName));
}
static void CmdOptStateClear(void)
{
g_cmdOptState.optIndex = 0;
g_cmdOptState.argc = 0;
g_cmdOptState.argv = NULL;
g_cmdOptState.opts = NULL;
(void)memset_s(g_cmdOptState.progName, sizeof(g_cmdOptState.progName), 0, sizeof(g_cmdOptState.progName));
}
char *HITLS_APP_GetProgName(void)
{
return g_cmdOptState.progName;
}
int32_t HITLS_APP_OptBegin(int32_t argc, char **argv, const HITLS_CmdOption *opts)
{
if (argc == 0 || argv == NULL || opts == NULL) {
(void)AppPrintError("incorrect command \n");
return HITLS_APP_OPT_UNKOWN;
}
// init cmd option state
CmdOptStateInit(1, argc, argv, opts);
GetProgName(argv[0]);
g_unKnownOpt = NULL;
const HITLS_CmdOption *opt = opts;
// Check all opts before using them
for (; opt->name != NULL; ++opt) {
if ((strlen(opt->name) == 0) && (opt->valueType == HITLS_APP_OPT_VALUETYPE_NO_VALUE)) {
g_unKnownOpt = opt;
} else if ((strlen(opt->name) == 0) || (opt->name[0] == '-')) {
(void)AppPrintError("Invalid optname %s \n", opt->name);
return HITLS_APP_OPT_NAME_INVALID;
}
if (opt->valueType <= HITLS_APP_OPT_VALUETYPE_NONE || opt->valueType >= HITLS_APP_OPT_VALUETYPE_MAX) {
return HITLS_APP_OPT_VALUETYPE_INVALID;
}
if (opt->valueType == HITLS_APP_OPT_VALUETYPE_PARAMTERS && opt->optType != HITLS_APP_OPT_PARAM) {
return HITLS_APP_OPT_TYPE_INVALID;
}
for (const HITLS_CmdOption *nextOpt = opt + 1; nextOpt->name != NULL; ++nextOpt) {
if (strcmp(opt->name, nextOpt->name) == 0) {
(void)AppPrintError("Invalid duplicate name : %s\n", opt->name);
return HITLS_APP_OPT_NAME_INVALID;
}
}
}
return HITLS_APP_SUCCESS;
}
char *HITLS_APP_OptGetValueStr(void)
{
return g_cmdOptState.valueStr;
}
static int32_t IsDir(const char *path)
{
struct stat st = {0};
if (path == NULL) {
return HITLS_APP_OPT_VALUE_INVALID;
}
if (stat(path, &st) != 0) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
if (S_ISDIR(st.st_mode)) {
return HITLS_APP_SUCCESS;
}
return HITLS_APP_OPT_VALUE_INVALID;
}
int32_t HITLS_APP_OptGetLong(const char *valueS, long *valueL)
{
char *endPtr = NULL;
errno = 0;
long l = strtol(valueS, &endPtr, 0);
if (strlen(endPtr) > 0 || endPtr == valueS || (l == LONG_MAX || l == LONG_MIN) || errno == ERANGE ||
(l == 0 && errno != 0)) {
(void)AppPrintError("The parameter: %s is not a number or out of range\n", valueS);
return HITLS_APP_OPT_VALUE_INVALID;
}
*valueL = l;
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptGetInt(const char *valueS, int32_t *valueI)
{
long valueL = 0;
if (HITLS_APP_OptGetLong(valueS, &valueL) != HITLS_APP_SUCCESS) {
return HITLS_APP_OPT_VALUE_INVALID;
}
*valueI = (int32_t)valueL;
// value outside integer range
if ((long)(*valueI) != valueL) {
(void)AppPrintError("The number %ld out the int bound \n", valueL);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptGetUint32(const char *valueS, uint32_t *valueU)
{
long valueL = 0;
if (HITLS_APP_OptGetLong(valueS, &valueL) != HITLS_APP_SUCCESS) {
return HITLS_APP_OPT_VALUE_INVALID;
}
*valueU = (uint32_t)valueL;
// value outside integer range
if ((long)(*valueU) != valueL) {
(void)AppPrintError("The number %ld out the int bound \n", valueL);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptGetFormatType(const char *valueS, HITLS_ValueType type, BSL_ParseFormat *formatType)
{
if (type != HITLS_APP_OPT_VALUETYPE_FMT_PEMDER && type != HITLS_APP_OPT_VALUETYPE_FMT_ANY) {
(void)AppPrintError("Invalid Format Type\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (strcasecmp(valueS, "DER") == 0) {
*formatType = BSL_FORMAT_ASN1;
return HITLS_APP_SUCCESS;
} else if (strcasecmp(valueS, "PEM") == 0) {
*formatType = BSL_FORMAT_PEM;
return HITLS_APP_SUCCESS;
}
(void)AppPrintError("Invalid format \"%s\".\n", valueS);
return HITLS_APP_OPT_VALUE_INVALID;
}
int32_t HITLS_APP_GetRestOptNum(void)
{
return g_cmdOptState.argc - g_cmdOptState.optIndex;
}
char **HITLS_APP_GetRestOpt(void)
{
return &g_cmdOptState.argv[g_cmdOptState.optIndex];
}
static int32_t ClassifyByValue(HITLS_ValueType value)
{
switch (value) {
case HITLS_APP_OPT_VALUETYPE_IN_FILE:
case HITLS_APP_OPT_VALUETYPE_OUT_FILE:
case HITLS_APP_OPT_VALUETYPE_STRING:
case HITLS_APP_OPT_VALUETYPE_PARAMTERS:
return HITLS_APP_OPT_VALUECLASS_STR;
case HITLS_APP_OPT_VALUETYPE_DIR:
return HITLS_APP_OPT_VALUECLASS_DIR;
case HITLS_APP_OPT_VALUETYPE_INT:
case HITLS_APP_OPT_VALUETYPE_UINT:
case HITLS_APP_OPT_VALUETYPE_POSITIVE_INT:
return HITLS_APP_OPT_VALUECLASS_INT;
case HITLS_APP_OPT_VALUETYPE_LONG:
case HITLS_APP_OPT_VALUETYPE_ULONG:
return HITLS_APP_OPT_VALUECLASS_LONG;
case HITLS_APP_OPT_VALUETYPE_FMT_PEMDER:
case HITLS_APP_OPT_VALUETYPE_FMT_ANY:
return HITLS_APP_OPT_VALUECLASS_FMT;
default:
return HITLS_APP_OPT_VALUECLASS_NO_VALUE;
}
return HITLS_APP_OPT_VALUECLASS_NONE;
}
static int32_t CheckOptValueType(const HITLS_CmdOption *opt, const char *valStr)
{
int32_t valueClass = ClassifyByValue(opt->valueType);
switch (valueClass) {
case HITLS_APP_OPT_VALUECLASS_STR:
break;
case HITLS_APP_OPT_VALUECLASS_DIR: {
if (IsDir(valStr) != HITLS_APP_SUCCESS) {
AppPrintError("%s: Invalid dir \"%s\" for -%s\n", g_cmdOptState.progName, valStr, opt->name);
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
}
case HITLS_APP_OPT_VALUECLASS_INT: {
int32_t valueI = 0;
if (HITLS_APP_OptGetInt(valStr, &valueI) != HITLS_APP_SUCCESS ||
(opt->valueType == HITLS_APP_OPT_VALUETYPE_UINT && valueI < 0) ||
(opt->valueType == HITLS_APP_OPT_VALUETYPE_POSITIVE_INT && valueI < 0)) {
AppPrintError("%s: Invalid number \"%s\" for -%s\n", g_cmdOptState.progName, valStr, opt->name);
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
}
case HITLS_APP_OPT_VALUECLASS_LONG: {
long valueL = 0;
if (HITLS_APP_OptGetLong(valStr, &valueL) != HITLS_APP_SUCCESS ||
(opt->valueType == HITLS_APP_OPT_VALUETYPE_LONG && valueL < 0)) {
AppPrintError("%s: Invalid number \"%s\" for -%s\n", g_cmdOptState.progName, valStr, opt->name);
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
}
case HITLS_APP_OPT_VALUECLASS_FMT: {
BSL_ParseFormat formatType = 0;
if (HITLS_APP_OptGetFormatType(valStr, opt->valueType, &formatType) != HITLS_APP_SUCCESS) {
AppPrintError("%s: Invalid format \"%s\" for -%s\n", g_cmdOptState.progName, valStr, opt->name);
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
}
default:
AppPrintError("%s: Invalid arg \"%s\" for -%s\n", g_cmdOptState.progName, valStr, opt->name);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptNext(void)
{
if (g_cmdOptState.optIndex > g_cmdOptState.argc) {
return HITLS_APP_OPT_EOF;
}
char *optName = g_cmdOptState.argv[g_cmdOptState.optIndex];
if (optName == NULL || *optName != '-') {
return HITLS_APP_OPT_EOF;
}
g_cmdOptState.optIndex++;
// optName only contain '-' or '--'
if (strcmp(optName, "-") == 0 || strcmp(optName, "--") == 0) {
return HITLS_APP_OPT_ERR;
}
if (*(++optName) == '-') {
optName++;
}
// case: key=value do not support
g_cmdOptState.valueStr = strchr(optName, '=');
if (g_cmdOptState.valueStr != NULL) {
return HITLS_APP_OPT_ERR;
}
for (const HITLS_CmdOption *opt = g_cmdOptState.opts; opt->name; ++opt) {
if (strcmp(optName, opt->name) != 0) {
continue;
}
// case: opt doesn't have value
if (opt->valueType == HITLS_APP_OPT_VALUETYPE_NO_VALUE) {
if (g_cmdOptState.valueStr != NULL) {
AppPrintError("%s does not take a value\n", opt->name);
return HITLS_APP_OPT_ERR;
}
return opt->optType;
}
// case: opt should has value
if (g_cmdOptState.valueStr == NULL) {
if (g_cmdOptState.optIndex > g_cmdOptState.argc || g_cmdOptState.argv[g_cmdOptState.optIndex] == NULL) {
AppPrintError("%s needs a value\n", opt->name);
return HITLS_APP_OPT_ERR;
}
g_cmdOptState.valueStr = g_cmdOptState.argv[g_cmdOptState.optIndex];
g_cmdOptState.optIndex++;
}
if (CheckOptValueType(opt, g_cmdOptState.valueStr) != HITLS_APP_SUCCESS) {
return HITLS_APP_OPT_ERR;
}
return opt->optType;
}
if (g_unKnownOpt != NULL) {
g_unKownName = optName;
return g_unKnownOpt->optType;
}
AppPrintError("%s: Unknown option: -%s\n", g_cmdOptState.progName, optName);
return HITLS_APP_OPT_ERR;
}
struct {
HITLS_ValueType type;
char *param;
} g_valTypeParam[] = {
{HITLS_APP_OPT_VALUETYPE_IN_FILE, "infile"},
{HITLS_APP_OPT_VALUETYPE_OUT_FILE, "outfile"},
{HITLS_APP_OPT_VALUETYPE_STRING, "val"},
{HITLS_APP_OPT_VALUETYPE_PARAMTERS, ""},
{HITLS_APP_OPT_VALUETYPE_DIR, "dir"},
{HITLS_APP_OPT_VALUETYPE_INT, "int"},
{HITLS_APP_OPT_VALUETYPE_UINT, "uint"},
{HITLS_APP_OPT_VALUETYPE_POSITIVE_INT, "uint(>0)"},
{HITLS_APP_OPT_VALUETYPE_LONG, "long"},
{HITLS_APP_OPT_VALUETYPE_ULONG, "ulong"},
{HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "PEM|DER"},
{HITLS_APP_OPT_VALUETYPE_FMT_ANY, "format"}
};
/* Return a string describing the parameter type. */
static const char *ValueType2Param(HITLS_ValueType type)
{
for (int i = 0; i <= (int)sizeof(g_valTypeParam); i++) {
if (type == g_valTypeParam[i].type)
return g_valTypeParam[i].param;
}
return "";
}
static void OptPrint(const HITLS_CmdOption *opt, int width)
{
const char *help = opt->help ? opt->help : "";
char start[MAX_HITLS_APP_OPT_LINE_WIDTH + 1] = {0};
(void)memset_s(start, sizeof(start) - 1, ' ', sizeof(start) - 1);
start[sizeof(start) - 1] = '\0';
int pos = 0;
start[pos++] = ' ';
if (opt->valueType != HITLS_APP_OPT_VALUETYPE_PARAMTERS) {
start[pos++] = '-';
} else {
start[pos++] = '[';
}
if (strlen(opt->name) > 0) {
if (EOK == strncpy_s(&start[pos], sizeof(start) - pos - 1, opt->name, strlen(opt->name))) {
pos += strlen(opt->name);
}
(void)memset_s(&start[pos + 1], sizeof(start) - 1 - pos - 1, ' ', sizeof(start) - 1 - pos - 1);
} else {
start[pos++] = '*';
}
if (opt->valueType == HITLS_APP_OPT_VALUETYPE_PARAMTERS) {
start[pos++] = ']';
}
if (opt->valueType != HITLS_APP_OPT_VALUETYPE_NO_VALUE) {
start[pos++] = ' ';
const char *param = ValueType2Param(opt->valueType);
if (strncpy_s(&start[pos], sizeof(start) - pos - 1, param, strlen(param)) == EOK) {
pos += strlen(param);
}
(void)memset_s(&start[pos + 1], sizeof(start) - 1 - pos - 1, ' ', sizeof(start) - 1 - pos - 1);
}
start[pos++] = ' ';
if (pos >= MAX_HITLS_APP_OPT_NAME_WIDTH) {
start[pos] = '\0';
(void)AppPrintError("%s\n", start);
(void)memset_s(start, sizeof(start) - 1, ' ', sizeof(start) - 1);
}
start[width] = '\0';
(void)AppPrintError("%s %s\n", start, help);
}
void HITLS_APP_OptHelpPrint(const HITLS_CmdOption *opts)
{
int width = 5;
int len = 0;
const HITLS_CmdOption *opt;
for (opt = opts; opt->name != NULL; opt++) {
len = 1 + (int)strlen(opt->name) + 1; // '-' + name + space
if (opt->valueType != HITLS_APP_OPT_VALUETYPE_NO_VALUE) {
len += 1 + strlen(ValueType2Param(opt->valueType));
}
if (len < MAX_HITLS_APP_OPT_NAME_WIDTH && len > width) {
width = len;
}
}
(void)AppPrintError("Usage: %s \n", g_cmdOptState.progName);
for (opt = opts; opt->name != NULL; opt++) {
(void)OptPrint(opt, width);
}
}
void HITLS_APP_OptEnd(void)
{
CmdOptStateClear();
}
BSL_UIO *HITLS_APP_UioOpen(const char *filename, char mode, int32_t flag)
{
if (mode != 'w' && mode != 'r' && mode != 'a') {
(void)AppPrintError("Invalid mode, only support a/w/r\n");
return NULL;
}
BSL_UIO *uio = BSL_UIO_New(BSL_UIO_FileMethod());
if (uio == NULL) {
return uio;
}
int32_t cmd = 0;
int32_t larg = 0;
void *parg = NULL;
if (filename == NULL) {
cmd = BSL_UIO_FILE_PTR;
larg = flag;
switch (mode) {
case 'w': parg = (void *)stdout;
break;
case 'r': parg = (void *)stdin;
break;
default:
BSL_UIO_Free(uio);
(void)AppPrintError("Only standard I/O is supported\n");
return NULL;
}
} else {
parg = (void *)(uintptr_t)filename;
cmd = BSL_UIO_FILE_OPEN;
switch (mode) {
case 'w': larg = BSL_UIO_FILE_WRITE;
break;
case 'r': larg = BSL_UIO_FILE_READ;
break;
case 'a': larg = BSL_UIO_FILE_APPEND;
break;
default:
BSL_UIO_Free(uio);
(void)AppPrintError("Only standard I/O is supported\n");
return NULL;
}
}
int32_t ctrlRet = BSL_UIO_Ctrl(uio, cmd, larg, parg);
if (ctrlRet != BSL_SUCCESS) {
(void)AppPrintError("Failed to bind the filepath\n");
BSL_UIO_Free(uio);
uio = NULL;
}
return uio;
}
int32_t HITLS_APP_OptToBase64(uint8_t *inBuf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen)
{
if (inBuf == NULL || outBuf == NULL || inBufLen == 0 || outBufLen == 0) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
// encode conversion
int32_t encodeRet = BSL_BASE64_Encode(inBuf, inBufLen, outBuf, &outBufLen);
if (encodeRet != BSL_SUCCESS) {
(void)AppPrintError("Failed to convert to Base64 format\n");
return HITLS_APP_ENCODE_FAIL;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptToHex(uint8_t *inBuf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen)
{
// One byte is encoded into hex and becomes 2 bytes.
int32_t hexCharSize = 2;
if (inBuf == NULL || outBuf == NULL || inBufLen == 0 || outBufLen < hexCharSize * inBufLen + 1) {
(void)AppPrintError("opt: Invalid input buffer or output buffer.\n");
return HITLS_APP_INTERNAL_EXCEPTION;
}
const char *hexChars = "0123456789abcdef";
size_t pos = 0;
for (size_t i = 0; i < inBufLen; ++i) {
outBuf[pos++] = hexChars[(inBuf[i] >> 4) & 0xF]; // high 4 bits.
outBuf[pos++] = hexChars[inBuf[i] & 0xF]; // low 4 bits.
}
outBuf[pos] = '\0';
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptWriteUio(BSL_UIO *uio, uint8_t *buf, uint32_t bufLen, int32_t format)
{
if (buf == NULL || uio == NULL || bufLen == 0) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
uint32_t outBufLen = 0;
uint32_t writeLen = 0;
switch (format) {
case HITLS_APP_FORMAT_BASE64:
/* In the Base64 format, three 8-bit bytes are converted into four 6-bit bytes. Therefore, the length
of the data in the Base64 format must be at least (Length of the original data + 2)/3 x 4 + 1.
The original data length plus 2 is used to ensure that
the remainder of buflen divided by 3 after rounding down is not lost. */
outBufLen = (bufLen + 2) / 3 * 4 + 1;
break;
// One byte is encoded into hex and becomes 2 bytes.
case HITLS_APP_FORMAT_HEX:
outBufLen = bufLen * 2 + 1; // The length of the encoded data is 2 times the length of the original data.
break;
default: // The original length of bufLen is used by the default type.
outBufLen = bufLen;
}
char *outBuf = (char *)BSL_SAL_Calloc(outBufLen, sizeof(char));
if (outBuf == NULL) {
(void)AppPrintError("Failed to read the UIO content to calloc space\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
int32_t outRet = HITLS_APP_SUCCESS;
switch (format) {
case HITLS_APP_FORMAT_BASE64:
outRet = HITLS_APP_OptToBase64(buf, bufLen, outBuf, outBufLen);
break;
case HITLS_APP_FORMAT_HEX:
outRet = HITLS_APP_OptToHex(buf, bufLen, outBuf, outBufLen);
outBufLen = strlen(outBuf);
break;
default:
outRet = memcpy_s(outBuf, outBufLen, buf, bufLen);
}
if (outRet != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(outBuf);
return outRet;
}
int32_t writeRet = BSL_UIO_Write(uio, outBuf, outBufLen, &writeLen);
BSL_SAL_FREE(outBuf);
if (writeRet != BSL_SUCCESS || outBufLen != writeLen) {
(void)AppPrintError("Failed to output the content.\n");
return HITLS_APP_UIO_FAIL;
}
(void)BSL_UIO_Ctrl(uio, BSL_UIO_FLUSH, 0, NULL);
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptReadUio(BSL_UIO *uio, uint8_t **readBuf, uint64_t *readBufLen, uint64_t maxBufLen)
{
if (uio == NULL) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
int32_t readRet = BSL_UIO_Ctrl(uio, BSL_UIO_PENDING, sizeof(*readBufLen), readBufLen);
if (readRet != BSL_SUCCESS) {
(void)AppPrintError("Failed to obtain the content length\n");
return HITLS_APP_UIO_FAIL;
}
if (*readBufLen == 0 || *readBufLen > maxBufLen) {
(void)AppPrintError("Invalid content length\n");
return HITLS_APP_UIO_FAIL;
}
// obtain the length of the UIO content, the pointer of the input parameter points to the allocated memory
uint8_t *buf = (uint8_t *)BSL_SAL_Calloc(*readBufLen + 1, sizeof(uint8_t));
if (buf == NULL) {
(void)AppPrintError("Failed to create the space.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
uint32_t readLen = 0;
readRet = BSL_UIO_Read(uio, buf, *readBufLen, &readLen); // read content to memory
if (readRet != BSL_SUCCESS || *readBufLen != readLen) {
BSL_SAL_FREE(buf);
(void)AppPrintError("Failed to read UIO content.\n");
return HITLS_APP_UIO_FAIL;
}
buf[*readBufLen] = '\0';
*readBuf = buf;
return HITLS_APP_SUCCESS;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_opt.c | C | unknown | 21,395 |
/*
* 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 "app_passwd.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <termios.h>
#include <unistd.h>
#include <securec.h>
#include <limits.h>
#include "bsl_ui.h"
#include "bsl_uio.h"
#include "bsl_sal.h"
#include "bsl_errno.h"
#include "app_opt.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_utils.h"
#include "crypt_eal_rand.h"
#include "crypt_errno.h"
#include "crypt_eal_md.h"
typedef enum {
HITLS_APP_OPT_PASSWD_ERR = -1,
HITLS_APP_OPT_PASSWD_EOF = 0,
HITLS_APP_OPT_PASSWD_HELP = 1,
HITLS_APP_OPT_PASSWD_OUTFILE = 2,
HITLS_APP_OPT_PASSWD_SHA512,
} HITLSOptType;
const HITLS_CmdOption g_passwdOpts[] = {
{"help", HITLS_APP_OPT_PASSWD_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"out", HITLS_APP_OPT_PASSWD_OUTFILE, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Outfile"},
{"sha512", HITLS_APP_OPT_PASSWD_SHA512, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "SHA512-based password algorithm"},
{NULL, 0, 0, NULL}
};
typedef struct {
char *outFile;
int32_t algTag; // 6 indicates sha512, 5 indicates sha256, and 1 indicates md5.
uint8_t *salt;
int32_t saltLen;
char *pass;
uint32_t passwdLen;
long iter;
} PasswdOpt;
typedef struct {
uint8_t *buf;
size_t bufLen;
} BufLen;
// List of visible characters also B64 coding table
static const char g_b64Table[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static int32_t HandleOpt(PasswdOpt *opt);
static int32_t CheckPara(PasswdOpt *opt, BSL_UIO *outUio);
static int32_t GetSalt(PasswdOpt *opt);
static int32_t GetPasswd(PasswdOpt *opt);
static int32_t Sha512Crypt(PasswdOpt *opt, char *resBuf, uint32_t bufMaxLen);
static int32_t OutputResult(BSL_UIO *outUio, char *resBuf, uint32_t bufLen);
static bool IsSaltValid(char *salt);
static bool IsSaltArgValid(PasswdOpt *opt);
static bool IsDigit(char *str);
static long StrToDigit(char *str);
static bool ParseSalt(PasswdOpt *opt);
static char *SubStr(const char* srcStr, int32_t startPos, int32_t cutLen);
static CRYPT_EAL_MdCTX *InitSha512Ctx(void);
static int32_t B64EncToBuf(char *resBuf, uint32_t bufLen, uint32_t offset, uint8_t *hashBuf, uint32_t hashBufLen);
static int32_t ResToBuf(PasswdOpt *opt, char *resBuf, uint32_t bufMaxLen, uint8_t *hashBuf, uint32_t hashBufLen);
static int32_t Sha512Md2Hash(CRYPT_EAL_MdCTX *md2, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen);
static int32_t Sha512Md1HashWithMd2(CRYPT_EAL_MdCTX *md1, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen);
static int32_t Sha512MdPHash(CRYPT_EAL_MdCTX *mdP, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen);
static int32_t Sha512MdSHash(CRYPT_EAL_MdCTX *mdS, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen, uint8_t nForMdS);
static int32_t Sha512GetMdPBuf(PasswdOpt *opt, uint8_t *mdPBuf, uint32_t mdPBufLen);
static int32_t Sha512GetMdSBuf(PasswdOpt *opt, uint8_t *mdSBuf, uint32_t mdSBufLen, uint8_t nForMdS);
static int32_t Sha512IterHash(long rounds, BufLen *md1HashRes, BufLen *mdPBuf, BufLen *mdSBuf);
static int32_t Sha512MdCrypt(PasswdOpt *opt, char *resBuf, uint32_t bufLen);
int32_t HITLS_PasswdMain(int argc, char *argv[])
{
PasswdOpt opt = {NULL, -1, NULL, -1, NULL, 0, -1};
int32_t ret = HITLS_APP_SUCCESS;
BSL_UIO *outUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (outUio == NULL) {
AppPrintError("Failed to create the output UIO.\n");
return HITLS_APP_UIO_FAIL;
}
if ((ret = HITLS_APP_OptBegin(argc, argv, g_passwdOpts)) != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
goto passwdEnd;
}
if ((ret = HandleOpt(&opt)) != HITLS_APP_SUCCESS) {
goto passwdEnd;
}
if ((ret = CheckPara(&opt, outUio)) != HITLS_APP_SUCCESS) {
goto passwdEnd;
}
char res[REC_MAX_ARRAY_LEN] = {0};
if ((ret = Sha512Crypt(&opt, res, REC_MAX_ARRAY_LEN)) != HITLS_APP_SUCCESS) {
goto passwdEnd;
}
uint32_t resBufLen = strlen(res);
if ((ret = OutputResult(outUio, res, resBufLen)) != HITLS_APP_SUCCESS) {
goto passwdEnd;
}
passwdEnd:
BSL_SAL_FREE(opt.salt);
if (opt.pass != NULL && opt.passwdLen > 0) {
(void)memset_s(opt.pass, opt.passwdLen, 0, opt.passwdLen);
}
BSL_SAL_FREE(opt.pass);
if (opt.outFile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(outUio, true);
}
BSL_UIO_Free(outUio);
return ret;
}
static int32_t HandleOpt(PasswdOpt *opt)
{
int32_t optType;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_PASSWD_EOF) {
switch (optType) {
case HITLS_APP_OPT_PASSWD_EOF:
break;
case HITLS_APP_OPT_PASSWD_ERR:
AppPrintError("passwd: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_OPT_PASSWD_HELP:
HITLS_APP_OptHelpPrint(g_passwdOpts);
return HITLS_APP_HELP;
case HITLS_APP_OPT_PASSWD_OUTFILE:
opt->outFile = HITLS_APP_OptGetValueStr();
break;
case HITLS_APP_OPT_PASSWD_SHA512:
opt->algTag = REC_SHA512_ALGTAG;
opt->saltLen = REC_SHA512_SALTLEN;
break;
default:
break;
}
}
// Obtains the value of the last digit numbits.
int32_t restOptNum = HITLS_APP_GetRestOptNum();
if (restOptNum != 0) {
(void)AppPrintError("Extra arguments given.\n");
AppPrintError("passwd: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
static int32_t GetSalt(PasswdOpt *opt)
{
if (opt->salt == NULL && opt->saltLen != -1) {
uint8_t *tmpSalt = (uint8_t *)BSL_SAL_Calloc(opt->saltLen + 1, sizeof(uint8_t));
if (tmpSalt == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
opt->salt = tmpSalt;
// Generate a salt value
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default",
NULL, 0, NULL) != CRYPT_SUCCESS ||
CRYPT_EAL_RandbytesEx(NULL, opt->salt, opt->saltLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to generate the salt value.\n");
BSL_SAL_FREE(opt->salt);
CRYPT_EAL_RandDeinitEx(NULL);
return HITLS_APP_CRYPTO_FAIL;
}
// Convert salt value to visible code
int32_t count = 0;
for (; count < opt->saltLen; count++) {
if ((opt->salt[count] & 0x3f) < strlen(g_b64Table)) {
opt->salt[count] = g_b64Table[opt->salt[count] & 0x3f];
}
}
opt->salt[count] = '\0';
CRYPT_EAL_RandDeinitEx(NULL);
}
return HITLS_APP_SUCCESS;
}
static int32_t GetPasswd(PasswdOpt *opt)
{
uint32_t bufLen = APP_MAX_PASS_LENGTH + 1;
BSL_UI_ReadPwdParam param = {"password", NULL, true};
if (opt->pass == NULL) {
char *tmpPasswd = (char *)BSL_SAL_Calloc(APP_MAX_PASS_LENGTH + 1, sizeof(char));
if (tmpPasswd == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
int32_t readPassRet = BSL_UI_ReadPwdUtil(¶m, tmpPasswd, &bufLen, HITLS_APP_DefaultPassCB, NULL);
if (readPassRet == BSL_UI_READ_BUFF_TOO_LONG || readPassRet == BSL_UI_READ_LEN_TOO_SHORT) {
HITLS_APP_PrintPassErrlog();
BSL_SAL_FREE(tmpPasswd);
return HITLS_APP_PASSWD_FAIL;
}
if (readPassRet != BSL_SUCCESS) {
BSL_SAL_FREE(tmpPasswd);
return HITLS_APP_PASSWD_FAIL;
}
bufLen -= 1; // The interface also reads the Enter, so the last digit needs to be replaced with the '\0'.
tmpPasswd[bufLen] = '\0';
opt->pass = tmpPasswd;
} else {
bufLen = strlen(opt->pass);
}
opt->passwdLen = bufLen;
if (HITLS_APP_CheckPasswd((uint8_t *)opt->pass, opt->passwdLen) != HITLS_APP_SUCCESS) {
opt->passwdLen = 0;
return HITLS_APP_PASSWD_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckPara(PasswdOpt *passwdOpt, BSL_UIO *outUio)
{
if (passwdOpt->algTag == -1 || passwdOpt->saltLen == -1) {
AppPrintError("The hash algorithm is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (passwdOpt->iter != -1) {
if (passwdOpt->iter < REC_MIN_ITER_TIMES || passwdOpt->iter > REC_MAX_ITER_TIMES) {
AppPrintError("Invalid iterations number, valid range[1000, 999999999].\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
}
int32_t checkRet = HITLS_APP_SUCCESS;
if ((checkRet = GetSalt(passwdOpt)) != HITLS_APP_SUCCESS) {
return checkRet;
}
if ((checkRet = GetPasswd(passwdOpt)) != HITLS_APP_SUCCESS) {
return checkRet;
}
// Obtains the post-value of the OUT option. If there is no post-value or this option, stdout.
if (passwdOpt->outFile == NULL) {
if (BSL_UIO_Ctrl(outUio, BSL_UIO_FILE_PTR, 0, (void *)stdout) != BSL_SUCCESS) {
AppPrintError("Failed to set stdout mode.\n");
return HITLS_APP_UIO_FAIL;
}
} else {
// User input file path, which is bound to the output file.
if (strlen(passwdOpt->outFile) >= PATH_MAX || strlen(passwdOpt->outFile) == 0) {
AppPrintError("The length of outfile error, range is (0, 4096].\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (BSL_UIO_Ctrl(outUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_WRITE, passwdOpt->outFile) != BSL_SUCCESS) {
AppPrintError("Failed to set outfile mode.\n");
return HITLS_APP_UIO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
static bool IsDigit(char *str)
{
for (size_t i = 0; i < strlen(str); i++) {
if (str[i] < '0' || str[i] > '9') {
return false;
}
}
return true;
}
static long StrToDigit(char *str)
{
long res = 0;
for (size_t i = 0; i < strlen(str); i++) {
res = res * REC_TEN + (str[i] - '0');
}
return res;
}
static char *SubStr(const char* srcStr, int32_t startPos, int32_t cutLen)
{
if (srcStr == NULL || (size_t)startPos < 0 || cutLen < 0) {
return NULL;
}
if (strlen(srcStr) < (size_t)startPos || strlen(srcStr) < (size_t)cutLen) {
return NULL;
}
int32_t index = 0;
static char destStr[REC_MAX_ARRAY_LEN] = {0};
srcStr = srcStr + startPos;
while (srcStr != NULL && index < cutLen) {
destStr[index] = *srcStr++;
if (*srcStr == '\0') {
break;
}
index++;
}
return destStr;
}
// Parse the user salt value in the special format and obtain the core salt value.
// For example, "$6$rounds=100000$/q1Z/N8SXhnbS5p5$cipherText" or "$6$/q1Z/N8SXhnbS5p5$cipherText"
// This function parses a string and extracts a valid salt value as "/q1Z/N8SXhnbS5p5"
static bool ParseSalt(PasswdOpt *opt)
{
if (strncmp((char *)opt->salt, "$6$", REC_PRE_TAG_LEN) != 0) {
return false;
}
// cutting salt value head
if (strlen((char *)opt->salt) < REC_PRE_TAG_LEN + 1) {
return false;
}
uint8_t *restSalt = opt->salt + REC_PRE_TAG_LEN;
// Check whether this part is the information about the number of iterations.
if (strncmp((char *)restSalt, "rounds=", REC_PRE_ITER_LEN - 1) == 0) {
// Check whether the number of iterations is valid and assign the value.
if (strlen((char *)restSalt) < REC_PRE_ITER_LEN) {
return false;
}
restSalt = restSalt + REC_PRE_ITER_LEN - 1;
char *context = NULL;
char *iterStr = strtok_s((char *)restSalt, "$", &context);
if (iterStr == NULL || !IsDigit(iterStr)) {
return false;
}
if (opt->iter != -1) {
if (opt->iter != StrToDigit(iterStr)) {
AppPrintError("Input iterations does not match the information in the salt string.\n");
return false;
}
} else {
long tmpIter = StrToDigit(iterStr);
if (tmpIter < REC_MIN_ITER_TIMES || tmpIter > REC_MAX_ITER_TIMES) {
AppPrintError("Invalid input iterations number, valid range[1000, 999999999].\n");
return false;
}
opt->iter = tmpIter;
}
char *cipherText = NULL;
char *tmpSalt = strtok_s(context, "$", &cipherText);
if (tmpSalt == NULL || !IsSaltValid(tmpSalt)) {
return false;
}
opt->salt = (uint8_t *)tmpSalt;
} else {
char *cipherText = NULL;
char *tmpSalt = strtok_s((char *)restSalt, "$", &cipherText);
if (tmpSalt == NULL || !IsSaltValid(tmpSalt)) {
return false;
}
opt->salt = (uint8_t *)tmpSalt;
}
if (strlen((char *)opt->salt) > REC_MAX_SALTLEN) {
opt->salt = (uint8_t *)SubStr((char *)opt->salt, 0, REC_MAX_SALTLEN);
}
return true;
}
static bool IsSaltValid(char *salt)
{
if (salt == NULL || strlen(salt) == 0) {
return false;
}
for (size_t i = 1; i < strlen(salt); i++) {
if (salt[i] == '$') {
return false;
}
}
return true;
}
static bool IsSaltArgValid(PasswdOpt *opt)
{
if (opt->salt[0] != '$') {
// Salt value in non-encrypted format
return IsSaltValid((char *)opt->salt);
} else {
// Salt value of the encryption format.
return ParseSalt(opt);
}
return true;
}
static CRYPT_EAL_MdCTX *InitSha512Ctx(void)
{
// Creating an MD Context
CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_ProviderMdNewCtx(NULL, CRYPT_MD_SHA512, "provider=default");
if (ctx == NULL) {
return NULL;
}
if (CRYPT_EAL_MdInit(ctx) != CRYPT_SUCCESS) {
CRYPT_EAL_MdFreeCtx(ctx);
return NULL;
}
return ctx;
}
static int32_t B64EncToBuf(char *resBuf, uint32_t bufLen, uint32_t offset, uint8_t *hashBuf, uint32_t hashBufLen)
{
if (resBuf == NULL || bufLen == 0 || hashBuf == NULL || hashBufLen < REC_HASH_BUF_LEN || offset > bufLen) {
return HITLS_APP_INVALID_ARG;
}
#define B64_FROM_24BIT(B3, B2, B1, N) \
do { \
uint32_t w = ((B3) << 16) | ((B2) << 8) | (B1); \
int32_t n = (N); \
while (n-- > 0 && bufLen > 0) { \
*(resBuf + offset++) = g_b64Table[w & 0x3f]; \
--bufLen; \
w >>= 6; \
} \
} while (0)
B64_FROM_24BIT (hashBuf[0], hashBuf[21], hashBuf[42], 4);
B64_FROM_24BIT (hashBuf[22], hashBuf[43], hashBuf[1], 4);
B64_FROM_24BIT (hashBuf[44], hashBuf[2], hashBuf[23], 4);
B64_FROM_24BIT (hashBuf[3], hashBuf[24], hashBuf[45], 4);
B64_FROM_24BIT (hashBuf[25], hashBuf[46], hashBuf[4], 4);
B64_FROM_24BIT (hashBuf[47], hashBuf[5], hashBuf[26], 4);
B64_FROM_24BIT (hashBuf[6], hashBuf[27], hashBuf[48], 4);
B64_FROM_24BIT (hashBuf[28], hashBuf[49], hashBuf[7], 4);
B64_FROM_24BIT (hashBuf[50], hashBuf[8], hashBuf[29], 4);
B64_FROM_24BIT (hashBuf[9], hashBuf[30], hashBuf[51], 4);
B64_FROM_24BIT (hashBuf[31], hashBuf[52], hashBuf[10], 4);
B64_FROM_24BIT (hashBuf[53], hashBuf[11], hashBuf[32], 4);
B64_FROM_24BIT (hashBuf[12], hashBuf[33], hashBuf[54], 4);
B64_FROM_24BIT (hashBuf[34], hashBuf[55], hashBuf[13], 4);
B64_FROM_24BIT (hashBuf[56], hashBuf[14], hashBuf[35], 4);
B64_FROM_24BIT (hashBuf[15], hashBuf[36], hashBuf[57], 4);
B64_FROM_24BIT (hashBuf[37], hashBuf[58], hashBuf[16], 4);
B64_FROM_24BIT (hashBuf[59], hashBuf[17], hashBuf[38], 4);
B64_FROM_24BIT (hashBuf[18], hashBuf[39], hashBuf[60], 4);
B64_FROM_24BIT (hashBuf[40], hashBuf[61], hashBuf[19], 4);
B64_FROM_24BIT (hashBuf[62], hashBuf[20], hashBuf[41], 4);
B64_FROM_24BIT (0, 0, hashBuf[63], 2);
if (bufLen <= 0) {
return HITLS_APP_ENCODE_FAIL;
} else {
*(resBuf + offset) = '\0';
}
return CRYPT_SUCCESS;
}
static int32_t ResToBuf(PasswdOpt *opt, char *resBuf, uint32_t bufMaxLen, uint8_t *hashBuf, uint32_t hashBufLen)
{
// construct the result string
if (resBuf == NULL || bufMaxLen < REC_MIN_PREFIX_LEN) {
return HITLS_APP_INVALID_ARG;
}
uint32_t bufLen = bufMaxLen; // Remaining buffer size
uint32_t offset = 0; // Number of characters in the prefix
// algorithm identifier
if (snprintf_s((char *)resBuf, bufLen, REC_PRE_TAG_LEN, "$%d$", opt->algTag) == -1) {
return HITLS_APP_SECUREC_FAIL;
}
bufLen -= REC_PRE_TAG_LEN;
offset += REC_PRE_TAG_LEN;
// Determine whether to add the iteration times flag.
if (opt->iter != -1) {
uint32_t iterBit = 0;
long tmpIter = opt->iter;
while (tmpIter != 0) {
tmpIter /= REC_TEN;
iterBit++;
}
uint32_t totalLen = iterBit + REC_PRE_ITER_LEN;
if (snprintf_s(resBuf + offset, bufLen, totalLen, "rounds=%ld$", opt->algTag) == -1) {
return HITLS_APP_SECUREC_FAIL;
}
bufLen -= totalLen;
offset += totalLen;
}
// Add Salt Value
if (snprintf_s(resBuf + offset, bufLen, opt->saltLen + 1, "%s$", opt->salt) == -1) {
return HITLS_APP_SECUREC_FAIL;
}
bufLen -= (opt->saltLen + 1);
offset += (opt->saltLen + 1);
if (B64EncToBuf(resBuf, bufLen, offset, hashBuf, hashBufLen) != CRYPT_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t Sha512Md2Hash(CRYPT_EAL_MdCTX *md2, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen)
{
if (CRYPT_EAL_MdUpdate(md2, (uint8_t *)opt->pass, opt->passwdLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (CRYPT_EAL_MdUpdate(md2, opt->salt, opt->saltLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (CRYPT_EAL_MdUpdate(md2, (uint8_t *)opt->pass, opt->passwdLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (CRYPT_EAL_MdFinal(md2, resBuf, bufLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512Md1HashWithMd2(CRYPT_EAL_MdCTX *md1, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen)
{
if (CRYPT_EAL_MdUpdate(md1, (uint8_t *)opt->pass, opt->passwdLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (CRYPT_EAL_MdUpdate(md1, opt->salt, opt->saltLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_MdCTX *md2 = InitSha512Ctx();
if (md2 == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
uint8_t md2_hash_res[REC_MAX_ARRAY_LEN] = {0};
uint32_t md2_hash_len = REC_MAX_ARRAY_LEN;
if (Sha512Md2Hash(md2, opt, md2_hash_res, &md2_hash_len) != CRYPT_SUCCESS) {
CRYPT_EAL_MdFreeCtx(md2);
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_MdFreeCtx(md2);
uint32_t times = opt->passwdLen / REC_SHA512_BLOCKSIZE;
uint32_t restDataLen = opt->passwdLen % REC_SHA512_BLOCKSIZE;
for (uint32_t i = 0; i < times; i++) {
if (CRYPT_EAL_MdUpdate(md1, md2_hash_res, md2_hash_len) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
if (restDataLen != 0) {
if (CRYPT_EAL_MdUpdate(md1, md2_hash_res, restDataLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
for (uint32_t count = opt->passwdLen; count > 0; count >>= 1) {
if ((count & 1) != 0) {
if (CRYPT_EAL_MdUpdate(md1, md2_hash_res, md2_hash_len) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
} else {
if (CRYPT_EAL_MdUpdate(md1, (uint8_t *)opt->pass, opt->passwdLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
}
if (CRYPT_EAL_MdFinal(md1, resBuf, bufLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512MdPHash(CRYPT_EAL_MdCTX *mdP, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen)
{
for (uint32_t i = opt->passwdLen; i > 0; i--) {
if (CRYPT_EAL_MdUpdate(mdP, (uint8_t *)opt->pass, opt->passwdLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
if (CRYPT_EAL_MdFinal(mdP, resBuf, bufLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512MdSHash(CRYPT_EAL_MdCTX *mdS, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen, uint8_t nForMdS)
{
for (int32_t count = 16 + nForMdS; count > 0; count--) {
if (CRYPT_EAL_MdUpdate(mdS, opt->salt, opt->saltLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
if (CRYPT_EAL_MdFinal(mdS, resBuf, bufLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512GetMdPBuf(PasswdOpt *opt, uint8_t *mdPBuf, uint32_t mdPBufLen)
{
CRYPT_EAL_MdCTX *mdP = InitSha512Ctx();
if (mdP == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t mdPBufMaxLen = REC_MAX_ARRAY_LEN;
uint8_t mdP_hash_res[REC_MAX_ARRAY_LEN] = {0};
uint32_t mdP_hash_len = REC_MAX_ARRAY_LEN; // The generated length is 64 characters.
if (Sha512MdPHash(mdP, opt, mdP_hash_res, &mdP_hash_len) != CRYPT_SUCCESS) {
CRYPT_EAL_MdFreeCtx(mdP);
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_MdFreeCtx(mdP);
uint32_t cpyLen = 0;
for (; mdPBufLen > REC_SHA512_BLOCKSIZE; mdPBufLen -= REC_SHA512_BLOCKSIZE) {
if (strncpy_s((char *)(mdPBuf + cpyLen), mdPBufMaxLen, (char *)mdP_hash_res, mdP_hash_len) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
cpyLen += mdP_hash_len;
mdPBufMaxLen -= mdP_hash_len;
}
if (strncpy_s((char *)(mdPBuf + cpyLen), mdPBufMaxLen, (char *)mdP_hash_res, mdPBufLen) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512GetMdSBuf(PasswdOpt *opt, uint8_t *mdSBuf, uint32_t mdSBufLen, uint8_t nForMdS)
{
CRYPT_EAL_MdCTX *mdS = InitSha512Ctx();
if (mdS == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t mdSBufMaxLen = REC_MAX_ARRAY_LEN;
uint8_t mdS_hash_res[REC_MAX_ARRAY_LEN] = {0};
uint32_t mdS_hash_len = REC_MAX_ARRAY_LEN; // The generated length is 64 characters.
if (Sha512MdSHash(mdS, opt, mdS_hash_res, &mdS_hash_len, nForMdS) != CRYPT_SUCCESS) {
CRYPT_EAL_MdFreeCtx(mdS);
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_MdFreeCtx(mdS);
uint32_t cpyLen = 0;
for (; mdSBufLen > REC_SHA512_BLOCKSIZE; mdSBufLen -= REC_SHA512_BLOCKSIZE) {
if (strncpy_s((char *)(mdSBuf + cpyLen), mdSBufMaxLen, (char *)mdS_hash_res, mdS_hash_len) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
cpyLen += mdS_hash_len;
mdSBufMaxLen -= mdS_hash_len;
}
if (strncpy_s((char *)(mdSBuf + cpyLen), mdSBufMaxLen, (char *)mdS_hash_res, mdSBufLen) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
mdSBufLen = opt->saltLen;
return CRYPT_SUCCESS;
}
static int32_t Sha512IterHash(long rounds, BufLen *md1HashRes, BufLen *mdPBuf, BufLen *mdSBuf)
{
uint32_t md1HashLen = md1HashRes->bufLen;
uint32_t mdPBufLen = mdPBuf->bufLen;
uint32_t mdSBufLen = mdSBuf->bufLen;
for (long round = 0; round < rounds; round++) {
CRYPT_EAL_MdCTX *md_r = InitSha512Ctx();
if (md_r == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t ret = CRYPT_SUCCESS;
if (round % REC_TWO != 0) {
if ((ret = CRYPT_EAL_MdUpdate(md_r, mdPBuf->buf, mdPBufLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
} else {
if ((ret = CRYPT_EAL_MdUpdate(md_r, md1HashRes->buf, md1HashLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
}
if (round % REC_THREE != 0) {
if ((ret = CRYPT_EAL_MdUpdate(md_r, mdSBuf->buf, mdSBufLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
}
if (round % REC_SEVEN != 0) {
if ((ret = CRYPT_EAL_MdUpdate(md_r, mdPBuf->buf, mdPBufLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
}
if (round % REC_TWO != 0) {
if ((ret = CRYPT_EAL_MdUpdate(md_r, md1HashRes->buf, md1HashLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
} else {
if ((ret = CRYPT_EAL_MdUpdate(md_r, mdPBuf->buf, mdPBufLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
}
ret = CRYPT_EAL_MdFinal(md_r, md1HashRes->buf, &md1HashLen);
iterEnd:
CRYPT_EAL_MdFreeCtx(md_r);
if (ret != CRYPT_SUCCESS) {
return ret;
}
}
return CRYPT_SUCCESS;
}
static int32_t Sha512MdCrypt(PasswdOpt *opt, char *resBuf, uint32_t bufLen)
{
CRYPT_EAL_MdCTX *md1 = InitSha512Ctx();
if (md1 == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
uint8_t md1_hash_res[REC_MAX_ARRAY_LEN] = {0};
uint32_t md1_hash_len = REC_MAX_ARRAY_LEN; // The generated length is 64 characters.
if (Sha512Md1HashWithMd2(md1, opt, md1_hash_res, &md1_hash_len) != CRYPT_SUCCESS) {
CRYPT_EAL_MdFreeCtx(md1);
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_MdFreeCtx(md1);
uint8_t mdP_buf[REC_MAX_ARRAY_LEN] = {0};
uint32_t mdP_buf_len = opt->passwdLen;
if (Sha512GetMdPBuf(opt, mdP_buf, mdP_buf_len) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
uint8_t mdS_buf[REC_MAX_ARRAY_LEN] = {0};
uint32_t mdS_buf_len = opt->saltLen;
if (Sha512GetMdSBuf(opt, mdS_buf, mdS_buf_len, md1_hash_res[0]) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
long rounds = (opt->iter == -1) ? 5000 : opt->iter;
BufLen md1HasnResBuf = {.buf = md1_hash_res, .bufLen = md1_hash_len};
BufLen mdPBuf = {.buf = mdP_buf, .bufLen = mdP_buf_len};
BufLen mdSBuf = {.buf = mdS_buf, .bufLen = mdS_buf_len};
if (Sha512IterHash(rounds, &md1HasnResBuf, &mdPBuf, &mdSBuf) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (ResToBuf(opt, resBuf, bufLen, md1_hash_res, md1_hash_len) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512Crypt(PasswdOpt *opt, char *resBuf, uint32_t bufMaxLen)
{
if (opt->pass == NULL || opt->salt == NULL) {
return HITLS_APP_INVALID_ARG;
}
if (opt->algTag != REC_SHA512_ALGTAG && opt->algTag != REC_SHA256_ALGTAG && opt->algTag != REC_MD5_ALGTAG) {
return HITLS_APP_INVALID_ARG;
}
if (!IsSaltArgValid(opt)) {
return HITLS_APP_INVALID_ARG;
}
int32_t shaRet = HITLS_APP_SUCCESS;
if ((shaRet = Sha512MdCrypt(opt, resBuf, bufMaxLen)) != HITLS_APP_SUCCESS) {
return shaRet;
}
return shaRet;
}
static int32_t OutputResult(BSL_UIO *outUio, char *resBuf, uint32_t bufLen)
{
uint32_t writeLen = 0;
if (BSL_UIO_Write(outUio, resBuf, bufLen, &writeLen) != BSL_SUCCESS || writeLen == 0) {
return HITLS_APP_UIO_FAIL;
}
if (BSL_UIO_Write(outUio, "\n", 1, &writeLen) != BSL_SUCCESS || writeLen == 0) {
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_passwd.c | C | unknown | 28,134 |
/*
* 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 "app_pkcs12.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <securec.h>
#include <limits.h>
#include "app_errno.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_utils.h"
#include "crypt_algid.h"
#include "crypt_errno.h"
#include "bsl_err.h"
#include "bsl_uio.h"
#include "bsl_ui.h"
#include "bsl_obj.h"
#include "bsl_errno.h"
#include "crypt_eal_rand.h"
#include "hitls_cert_local.h"
#include "hitls_pkcs12_local.h"
#include "hitls_pki_errno.h"
#define CA_NAME_NUM (APP_FILE_MAX_SIZE_KB / 1) // Calculated based on the average value of 1K for each certificate.
typedef enum {
HITLS_APP_OPT_IN_FILE = 2,
HITLS_APP_OPT_OUT_FILE,
HITLS_APP_OPT_PASS_IN,
HITLS_APP_OPT_PASS_OUT,
HITLS_APP_OPT_IN_KEY,
HITLS_APP_OPT_EXPORT,
HITLS_APP_OPT_CLCERTS,
HITLS_APP_OPT_KEY_PBE,
HITLS_APP_OPT_CERT_PBE,
HITLS_APP_OPT_MAC_ALG,
HITLS_APP_OPT_CHAIN,
HITLS_APP_OPT_CANAME,
HITLS_APP_OPT_NAME,
HITLS_APP_OPT_CA_FILE,
HITLS_APP_OPT_CIPHER_ALG,
} HITLSOptType;
typedef struct {
char *inFile;
char *outFile;
char *passInArg;
char *passOutArg;
} GeneralOptions;
typedef struct {
bool clcerts;
const char *cipherAlgName;
} ImportOptions;
typedef struct {
char *inKey;
char *name;
char *caName[CA_NAME_NUM];
uint32_t caNameSize;
char *caFile;
char *macAlgArg;
char *certPbeArg;
char *keyPbeArg;
bool chain;
bool export;
} OutputOptions;
typedef struct {
GeneralOptions genOpt;
ImportOptions importOpt;
OutputOptions outPutOpt;
CRYPT_EAL_PkeyCtx *pkey;
char *passin;
char *passout;
int32_t cipherAlgCid;
int32_t macAlg;
int32_t certPbe;
int32_t keyPbe;
HITLS_PKCS12 *p12;
HITLS_X509_StoreCtx *store;
HITLS_X509_StoreCtx *dupStore;
HITLS_X509_List *certList;
HITLS_X509_List *caCertList;
HITLS_X509_List *outCertChainList;
HITLS_X509_Cert *userCert;
BSL_UIO *wUio;
} Pkcs12OptCtx;
typedef struct {
const uint32_t id;
const char *name;
} AlgList;
typedef int32_t (*OptHandleFunc)(Pkcs12OptCtx *);
typedef struct {
int optType;
OptHandleFunc func;
} OptHandleTable;
#define MIN_NAME_LEN 1U
#define MAX_NAME_LEN 1024U
static const HITLS_CmdOption OPTS[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"in", HITLS_APP_OPT_IN_FILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file"},
{"out", HITLS_APP_OPT_OUT_FILE, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"passin", HITLS_APP_OPT_PASS_IN, HITLS_APP_OPT_VALUETYPE_STRING, "Input file pass phrase source"},
{"passout", HITLS_APP_OPT_PASS_OUT, HITLS_APP_OPT_VALUETYPE_STRING, "Output file pass phrase source"},
{"inkey", HITLS_APP_OPT_IN_KEY, HITLS_APP_OPT_VALUETYPE_STRING, "Private key if not infile"},
{"export", HITLS_APP_OPT_EXPORT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Output PKCS12 file"},
{"clcerts", HITLS_APP_OPT_CLCERTS, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "output client certs"},
{"keypbe", HITLS_APP_OPT_KEY_PBE, HITLS_APP_OPT_VALUETYPE_STRING, "Private key PBE algorithm (default PBES2)"},
{"certpbe", HITLS_APP_OPT_CERT_PBE, HITLS_APP_OPT_VALUETYPE_STRING, "Certificate PBE algorithm (default PBES2)"},
{"macalg", HITLS_APP_OPT_MAC_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Digest algorithm used in MAC (default SHA256)"},
{"chain", HITLS_APP_OPT_CHAIN, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Add certificate chain"},
{"caname", HITLS_APP_OPT_CANAME, HITLS_APP_OPT_VALUETYPE_STRING, "Input friendly ca name"},
{"name", HITLS_APP_OPT_NAME, HITLS_APP_OPT_VALUETYPE_STRING, "Use name as friendly name"},
{"CAfile", HITLS_APP_OPT_CA_FILE, HITLS_APP_OPT_VALUETYPE_STRING, "PEM-format file of CA's"},
{"", HITLS_APP_OPT_CIPHER_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Any supported cipher"},
{NULL, 0, 0, NULL}
};
static const AlgList MAC_ALG_LIST[] = {
{CRYPT_MD_SHA224, "sha224"},
{CRYPT_MD_SHA256, "sha256"},
{CRYPT_MD_SHA384, "sha384"},
{CRYPT_MD_SHA512, "sha512"}
};
static const AlgList CERT_PBE_LIST[] = {
{BSL_CID_PBES2, "PBES2"}
};
static const AlgList KEY_PBE_LIST[] = {
{BSL_CID_PBES2, "PBES2"}
};
static int32_t DisplayHelp(Pkcs12OptCtx *opt)
{
(void)opt;
HITLS_APP_OptHelpPrint(OPTS);
return HITLS_APP_HELP;
}
static int32_t HandleOptErr(Pkcs12OptCtx *opt)
{
(void)opt;
AppPrintError("pkcs12: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t ParseInFile(Pkcs12OptCtx *opt)
{
opt->genOpt.inFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParseOutFile(Pkcs12OptCtx *opt)
{
opt->genOpt.outFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParsePassIn(Pkcs12OptCtx *opt)
{
opt->genOpt.passInArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParsePassOut(Pkcs12OptCtx *opt)
{
opt->genOpt.passOutArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParseInKey(Pkcs12OptCtx *opt)
{
opt->outPutOpt.inKey = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParseExport(Pkcs12OptCtx *opt)
{
opt->outPutOpt.export = true;
return HITLS_APP_SUCCESS;
}
static int32_t ParseClcerts(Pkcs12OptCtx *opt)
{
opt->importOpt.clcerts = true;
return HITLS_APP_SUCCESS;
}
static int32_t ParseKeyPbe(Pkcs12OptCtx *opt)
{
opt->outPutOpt.keyPbeArg = HITLS_APP_OptGetValueStr();
bool find = false;
for (size_t i = 0; i < sizeof(KEY_PBE_LIST) / sizeof(KEY_PBE_LIST[0]); i++) {
if (strcmp(KEY_PBE_LIST[i].name, opt->outPutOpt.keyPbeArg) == 0) {
find = true;
opt->keyPbe = KEY_PBE_LIST[i].id;
break;
}
}
// If the supported algorithm list is not found, print the supported algorithm list and return an error.
if (!find) {
AppPrintError("pkcs12: The current private key PBE algorithm supports only the following algorithms:\n");
for (size_t i = 0; i < sizeof(KEY_PBE_LIST) / sizeof(KEY_PBE_LIST[0]); i++) {
AppPrintError("%-19s", KEY_PBE_LIST[i].name);
// 4 algorithm names are displayed in each row.
if ((i + 1) % 4 == 0 && i != ((sizeof(KEY_PBE_LIST) / sizeof(KEY_PBE_LIST[0])) - 1)) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t ParseCertPbe(Pkcs12OptCtx *opt)
{
opt->outPutOpt.certPbeArg = HITLS_APP_OptGetValueStr();
bool find = false;
for (size_t i = 0; i < sizeof(CERT_PBE_LIST) / sizeof(CERT_PBE_LIST[0]); i++) {
if (strcmp(CERT_PBE_LIST[i].name, opt->outPutOpt.certPbeArg) == 0) {
find = true;
opt->certPbe = CERT_PBE_LIST[i].id;
break;
}
}
// If the supported algorithm list is not found, print the supported algorithm list and return an error.
if (!find) {
AppPrintError("pkcs12: The current certificate PBE algorithm supports only the following algorithms:\n");
for (size_t i = 0; i < sizeof(CERT_PBE_LIST) / sizeof(CERT_PBE_LIST[0]); i++) {
AppPrintError("%-19s", CERT_PBE_LIST[i].name);
// 4 algorithm names are displayed in each row.
if ((i + 1) % 4 == 0 && i != ((sizeof(CERT_PBE_LIST) / sizeof(CERT_PBE_LIST[0])) - 1)) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t ParseMacAlg(Pkcs12OptCtx *opt)
{
opt->outPutOpt.macAlgArg = HITLS_APP_OptGetValueStr();
bool find = false;
for (size_t i = 0; i < sizeof(MAC_ALG_LIST) / sizeof(MAC_ALG_LIST[0]); i++) {
if (strcmp(MAC_ALG_LIST[i].name, opt->outPutOpt.macAlgArg) == 0) {
find = true;
opt->macAlg = MAC_ALG_LIST[i].id;
break;
}
}
// If the supported algorithm list is not found, print the supported algorithm list and return an error.
if (!find) {
AppPrintError("pkcs12: The current digest algorithm supports only the following algorithms:\n");
for (size_t i = 0; i < sizeof(MAC_ALG_LIST) / sizeof(MAC_ALG_LIST[0]); i++) {
AppPrintError("%-19s", MAC_ALG_LIST[i].name);
// 4 algorithm names are displayed in each row.
if ((i + 1) % 4 == 0 && i != ((sizeof(MAC_ALG_LIST) / sizeof(MAC_ALG_LIST[0])) - 1)) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t ParseChain(Pkcs12OptCtx *opt)
{
opt->outPutOpt.chain = true;
return HITLS_APP_SUCCESS;
}
static int32_t ParseName(Pkcs12OptCtx *opt)
{
opt->outPutOpt.name = HITLS_APP_OptGetValueStr();
if (strlen(opt->outPutOpt.name) > MAX_NAME_LEN) {
AppPrintError("pkcs12: The name length is incorrect. It should be in the range of %u to %u.\n", MIN_NAME_LEN,
MAX_NAME_LEN);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t ParseCaName(Pkcs12OptCtx *opt)
{
char *caName = HITLS_APP_OptGetValueStr();
if (strlen(caName) > MAX_NAME_LEN) {
AppPrintError("pkcs12: The name length is incorrect. It should be in the range of %u to %u.\n", MIN_NAME_LEN,
MAX_NAME_LEN);
return HITLS_APP_OPT_VALUE_INVALID;
}
uint32_t index = opt->outPutOpt.caNameSize;
if (index >= CA_NAME_NUM) {
AppPrintError("pkcs12: The maximum number of canames is %u.\n", CA_NAME_NUM);
return HITLS_APP_OPT_VALUE_INVALID;
}
opt->outPutOpt.caName[index] = caName;
++(opt->outPutOpt.caNameSize);
return HITLS_APP_SUCCESS;
}
static int32_t ParseCaFile(Pkcs12OptCtx *opt)
{
opt->outPutOpt.caFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParseCipher(Pkcs12OptCtx *opt)
{
opt->importOpt.cipherAlgName = HITLS_APP_OptGetUnKownOptName();
return HITLS_APP_GetAndCheckCipherOpt(opt->importOpt.cipherAlgName, &opt->cipherAlgCid);
}
static const OptHandleTable OPT_HANDLE_TABLE[] = {
{HITLS_APP_OPT_ERR, HandleOptErr},
{HITLS_APP_OPT_HELP, DisplayHelp},
{HITLS_APP_OPT_IN_FILE, ParseInFile},
{HITLS_APP_OPT_OUT_FILE, ParseOutFile},
{HITLS_APP_OPT_PASS_IN, ParsePassIn},
{HITLS_APP_OPT_PASS_OUT, ParsePassOut},
{HITLS_APP_OPT_IN_KEY, ParseInKey},
{HITLS_APP_OPT_EXPORT, ParseExport},
{HITLS_APP_OPT_CLCERTS, ParseClcerts},
{HITLS_APP_OPT_KEY_PBE, ParseKeyPbe},
{HITLS_APP_OPT_CERT_PBE, ParseCertPbe},
{HITLS_APP_OPT_MAC_ALG, ParseMacAlg},
{HITLS_APP_OPT_CHAIN, ParseChain},
{HITLS_APP_OPT_CANAME, ParseCaName},
{HITLS_APP_OPT_NAME, ParseName},
{HITLS_APP_OPT_CA_FILE, ParseCaFile},
{HITLS_APP_OPT_CIPHER_ALG, ParseCipher}
};
static int32_t ParseOpt(int argc, char *argv[], Pkcs12OptCtx *opt)
{
int32_t ret = HITLS_APP_OptBegin(argc, argv, OPTS);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkcs12: error in opt begin.\n");
return ret;
}
int optType = HITLS_APP_OPT_ERR;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
for (size_t i = 0; i < (sizeof(OPT_HANDLE_TABLE) / sizeof(OPT_HANDLE_TABLE[0])); i++) {
if (optType != OPT_HANDLE_TABLE[i].optType) {
continue;
}
ret = OPT_HANDLE_TABLE[i].func(opt);
if (ret != HITLS_APP_SUCCESS) { // If any option fails to be parsed, an error is returned.
return ret;
}
break; // If the parsing is successful, exit the current loop and parse the next option.
}
}
// Obtain the number of parameters that cannot be parsed in the current version,
// and print the error information and help list.
if (HITLS_APP_GetRestOptNum() != 0) {
AppPrintError("pkcs12: Extra arguments given.\n");
AppPrintError("pkcs12: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return ret;
}
static int32_t CheckInFile(const char *inFile, const char *fileType)
{
if (inFile == NULL) {
AppPrintError("pkcs12: The %s is not specified.\n", fileType);
return HITLS_APP_OPT_UNKOWN;
}
if ((strnlen(inFile, PATH_MAX + 1) >= PATH_MAX) || (strlen(inFile) == 0)) {
AppPrintError("pkcs12: The length of %s error, range is (0, %d).\n", fileType, PATH_MAX);
return HITLS_APP_OPT_VALUE_INVALID;
}
size_t fileLen = 0;
int32_t ret = BSL_SAL_FileLength(inFile, &fileLen);
if (ret != BSL_SUCCESS) {
AppPrintError("pkcs12: Failed to get file size: %s, errCode = 0x%x.\n", fileType, ret);
return HITLS_APP_BSL_FAIL;
}
if (fileLen > APP_FILE_MAX_SIZE) {
AppPrintError("pkcs12: File size exceed limit %zukb: %s.\n", APP_FILE_MAX_SIZE_KB, fileType);
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckOutFile(const char *outFile)
{
// If outfile is transferred, the length cannot exceed PATH_MAX.
if ((outFile != NULL) && ((strnlen(outFile, PATH_MAX + 1) >= PATH_MAX) || (strlen(outFile) == 0))) {
AppPrintError("pkcs12: The length of out file error, range is (0, %d).\n", PATH_MAX);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t LoadCertList(const char *certFile, HITLS_X509_List **outCertList)
{
HITLS_X509_List *certlist = NULL;
int32_t ret = HITLS_X509_CertParseBundleFile(BSL_FORMAT_PEM, certFile, &certlist);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to read cert from %s. errCode = 0x%x.\n", certFile, ret);
return HITLS_APP_X509_FAIL;
}
*outCertList = certlist;
return HITLS_APP_SUCCESS;
}
static int32_t CheckCertListWithPriKey(HITLS_X509_List *certList, CRYPT_EAL_PkeyCtx *prvKey, HITLS_X509_Cert **userCert)
{
HITLS_X509_Cert *pstCert = BSL_LIST_GET_FIRST(certList);
while (pstCert != NULL) {
CRYPT_EAL_PkeyCtx *pubKey = NULL;
int32_t ret = HITLS_X509_CertCtrl(pstCert, HITLS_X509_GET_PUBKEY, &pubKey, 0);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Get pubKey from certificate failed, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = CRYPT_EAL_PkeyCmp(pubKey, prvKey);
CRYPT_EAL_PkeyFreeCtx(pubKey);
if (ret == CRYPT_SUCCESS) {
// If an error occurs, the memory applied here will be uniformly freed through the release of caList
*userCert = HITLS_X509_CertDup(pstCert);
if (*userCert == NULL) {
AppPrintError("pkcs12: Failed to duplicate the certificate.\n");
return HITLS_APP_X509_FAIL;
}
BSL_LIST_DeleteCurrent(certList, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
return HITLS_APP_SUCCESS;
}
pstCert = BSL_LIST_GET_NEXT(certList);
}
AppPrintError("pkcs12: No certificate matches private key.\n");
return HITLS_APP_X509_FAIL;
}
static int32_t AddCertToList(HITLS_X509_Cert *cert, HITLS_X509_List *certList)
{
HITLS_X509_Cert *tmpCert = HITLS_X509_CertDup(cert);
if (tmpCert == NULL) {
AppPrintError("pkcs12: Failed to duplicate the certificate.\n");
return HITLS_APP_X509_FAIL;
}
int32_t ret = BSL_LIST_AddElement(certList, tmpCert, BSL_LIST_POS_AFTER);
if (ret != BSL_SUCCESS) {
AppPrintError("pkcs12: Failed to add cert list, errCode = 0x%x.\n", ret);
HITLS_X509_CertFree(tmpCert);
return HITLS_APP_BSL_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t AddCertChain(Pkcs12OptCtx *opt)
{
// if the issuer certificate for input certificate is not found in the trust store, then only input
// certificate will be considered in the output chain.
if (BSL_LIST_COUNT(opt->outCertChainList) <= 1) {
AppPrintError("pkcs12: Failed to get local issuer certificate.\n");
return HITLS_APP_X509_FAIL;
}
// Mark duplicate CA certificate
opt->dupStore = HITLS_X509_StoreCtxNew();
if (opt->dupStore == NULL) {
AppPrintError("pkcs12: Failed to create the dup store context.\n");
return HITLS_APP_X509_FAIL;
}
HITLS_X509_Cert *cert = BSL_LIST_GET_FIRST(opt->certList);
while (cert != NULL) {
(void)HITLS_X509_StoreCtxCtrl(opt->dupStore, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, cert,
sizeof(HITLS_X509_Cert));
cert = BSL_LIST_GET_NEXT(opt->certList);
}
// The first element in the output certificate chain is the input certificate, skip it.
HITLS_X509_Cert *pstCert = BSL_LIST_GET_FIRST(opt->outCertChainList);
pstCert = BSL_LIST_GET_NEXT(opt->outCertChainList);
while (pstCert != NULL) {
if (HITLS_X509_StoreCtxCtrl(opt->dupStore, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, pstCert,
sizeof(HITLS_X509_Cert)) == HITLS_X509_ERR_CERT_EXIST) {
pstCert = BSL_LIST_GET_NEXT(opt->outCertChainList);
continue;
}
int32_t ret = AddCertToList(pstCert, opt->certList);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
pstCert = BSL_LIST_GET_NEXT(opt->outCertChainList);
}
return HITLS_APP_SUCCESS;
}
static int32_t ParseAndAddCertChain(Pkcs12OptCtx *opt)
{
opt->store = HITLS_X509_StoreCtxNew();
if (opt->store == NULL) {
AppPrintError("pkcs12: Failed to create the store context.\n");
return HITLS_APP_X509_FAIL;
}
int32_t ret = HITLS_X509_CertParseBundleFile(BSL_FORMAT_PEM, opt->outPutOpt.caFile, &opt->caCertList);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to parse certificate %s, errCode = 0x%x.\n", opt->outPutOpt.caFile, ret);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_Cert *cert = BSL_LIST_GET_FIRST(opt->caCertList);
while (cert != NULL) {
ret = HITLS_X509_StoreCtxCtrl(opt->store, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, cert, sizeof(HITLS_X509_Cert));
if (ret == HITLS_X509_ERR_CERT_EXIST) {
cert = BSL_LIST_GET_NEXT(opt->caCertList);
continue;
}
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to add the certificate %s to the trust store, errCode = 0x%0x.\n",
opt->outPutOpt.caFile, ret);
return HITLS_APP_X509_FAIL;
}
cert = BSL_LIST_GET_NEXT(opt->caCertList);
}
ret = HITLS_X509_CertChainBuild(opt->store, true, opt->userCert, &opt->outCertChainList);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed get cert chain by cert, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return AddCertChain(opt);
}
static int32_t AddKeyBagToP12(char *name, CRYPT_EAL_PkeyCtx *pkey, HITLS_PKCS12 *p12)
{
// new a key Bag
HITLS_PKCS12_Bag *pkeyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, pkey);
if (pkeyBag == NULL) {
AppPrintError("pkcs12: Failed to create the private key bag.\n");
return HITLS_APP_X509_FAIL;
}
if (name != NULL) {
BSL_Buffer attribute = { (uint8_t *)name, strlen(name) };
int32_t ret = HITLS_PKCS12_BagAddAttr(pkeyBag, BSL_CID_FRIENDLYNAME, &attribute);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to add the private key friendlyname, errCode = 0x%x.\n", ret);
HITLS_PKCS12_BagFree(pkeyBag);
return HITLS_APP_X509_FAIL;
}
}
// Set entity-key to p12
int32_t ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_KEYBAG, pkeyBag, 0);
HITLS_PKCS12_BagFree(pkeyBag);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to set the private key bag, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t AddUserCertBagToP12(char *name, HITLS_X509_Cert *cert, HITLS_PKCS12 *p12)
{
// new a cert Bag
HITLS_PKCS12_Bag *certBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, cert);
if (certBag == NULL) {
AppPrintError("pkcs12: Failed to create the user cert bag.\n");
return HITLS_APP_X509_FAIL;
}
if (name != NULL) {
BSL_Buffer attribute = { (uint8_t *)name, strlen(name) };
int32_t ret = HITLS_PKCS12_BagAddAttr(certBag, BSL_CID_FRIENDLYNAME, &attribute);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to add the user cert friendlyname, errCode = 0x%x.\n", ret);
HITLS_PKCS12_BagFree(certBag);
return HITLS_APP_X509_FAIL;
}
}
// Set entity-cert to p12
int32_t ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_CERTBAG, certBag, 0);
HITLS_PKCS12_BagFree(certBag);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to set the user cert bag, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t AddOtherCertListBagToP12(char **caName, uint32_t caNameSize, HITLS_X509_List *certList,
HITLS_PKCS12 *p12)
{
int32_t ret = HITLS_APP_SUCCESS;
HITLS_X509_Cert *pstCert = BSL_LIST_GET_FIRST(certList);
uint32_t index = 0;
while (pstCert != NULL) {
HITLS_PKCS12_Bag *otherCertBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, pstCert);
if (otherCertBag == NULL) {
AppPrintError("pkcs12: Failed to create the other cert bag.\n");
return HITLS_APP_X509_FAIL;
}
if ((index < caNameSize) && (caName[index] != NULL)) {
BSL_Buffer caAttribute = { (uint8_t *)caName[index], strlen(caName[index]) };
ret = HITLS_PKCS12_BagAddAttr(otherCertBag, BSL_CID_FRIENDLYNAME, &caAttribute);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to add the other cert friendlyname, errCode = 0x%x.\n", ret);
HITLS_PKCS12_BagFree(otherCertBag);
return HITLS_APP_X509_FAIL;
}
++index;
}
ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_CERTBAG, otherCertBag, 0);
HITLS_PKCS12_BagFree(otherCertBag);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to add the other cert bag, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
pstCert = BSL_LIST_GET_NEXT(certList);
}
if (index < caNameSize) {
AppPrintError("pkcs12: Warning: Redundant %zu -caname options.\n", caNameSize - index);
}
return HITLS_APP_SUCCESS;
}
static int32_t PrintPkcs12(Pkcs12OptCtx *opt)
{
int32_t ret = HITLS_APP_SUCCESS;
uint8_t *passOutBuf = NULL;
uint32_t passOutBufLen = 0;
BSL_UI_ReadPwdParam passParam = { "Export passwd", opt->genOpt.outFile, true };
if (HITLS_APP_GetPasswd(&passParam, &opt->passout, &passOutBuf, &passOutBufLen) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
HITLS_PKCS12_EncodeParam encodeParam = { 0 };
CRYPT_Pbkdf2Param certPbParam = { 0 };
certPbParam.pbesId = opt->certPbe;
certPbParam.pbkdfId = BSL_CID_PBKDF2;
certPbParam.hmacId = CRYPT_MAC_HMAC_SHA256;
certPbParam.symId = CRYPT_CIPHER_AES256_CBC;
certPbParam.saltLen = DEFAULT_SALTLEN;
certPbParam.pwd = passOutBuf;
certPbParam.pwdLen = passOutBufLen;
certPbParam.itCnt = DEFAULT_ITCNT;
CRYPT_EncodeParam certEncParam = { CRYPT_DERIVE_PBKDF2, &certPbParam };
HITLS_PKCS12_KdfParam hmacParam = { 0 };
hmacParam.macId = opt->macAlg;
hmacParam.saltLen = DEFAULT_SALTLEN;
hmacParam.pwd = passOutBuf;
hmacParam.pwdLen = passOutBufLen;
hmacParam.itCnt = DEFAULT_ITCNT;
HITLS_PKCS12_MacParam macParam = { .para = &hmacParam, .algId = BSL_CID_PKCS12KDF };
encodeParam.macParam = macParam;
encodeParam.encParam = certEncParam;
BSL_Buffer p12Buff = { 0 };
ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, opt->p12, &encodeParam, true, &p12Buff);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to generate pkcs12, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_APP_OptWriteUio(opt->wUio, p12Buff.data, p12Buff.dataLen, HITLS_APP_FORMAT_ASN1);
BSL_SAL_FREE(p12Buff.data);
return ret;
}
static int32_t MakePfxAndOutput(Pkcs12OptCtx *opt)
{
// Create pkcs12 info
opt->p12 = HITLS_PKCS12_New();
if (opt->p12 == NULL) {
AppPrintError("pkcs12: Failed to create pkcs12 info.\n");
return HITLS_APP_X509_FAIL;
}
// add key to p12
int32_t ret = AddKeyBagToP12(opt->outPutOpt.name, opt->pkey, opt->p12);
if (ret != HITLS_PKI_SUCCESS) {
return ret;
}
// add user cert to p12
ret = AddUserCertBagToP12(opt->outPutOpt.name, opt->userCert, opt->p12);
if (ret != HITLS_PKI_SUCCESS) {
return ret;
}
// add other cert to p12
ret = AddOtherCertListBagToP12(opt->outPutOpt.caName, opt->outPutOpt.caNameSize, opt->certList, opt->p12);
if (ret != HITLS_PKI_SUCCESS) {
return ret;
}
// Cal localKeyId to p12
int32_t mdId = CRYPT_MD_SHA1;
ret = HITLS_PKCS12_Ctrl(opt->p12, HITLS_PKCS12_GEN_LOCALKEYID, &mdId, sizeof(CRYPT_MD_AlgId));
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to set the local keyid, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return PrintPkcs12(opt);
}
static int32_t CreatePkcs12File(Pkcs12OptCtx *opt)
{
int32_t ret = LoadCertList(opt->genOpt.inFile, &opt->certList);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkcs12: Failed to load cert list.\n");
return ret;
}
opt->pkey = HITLS_APP_LoadPrvKey(opt->outPutOpt.inKey, BSL_FORMAT_PEM, &opt->passin);
if (opt->pkey == NULL) {
AppPrintError("pkcs12: Load key failed.\n");
return HITLS_APP_LOAD_KEY_FAIL;
}
ret = CheckCertListWithPriKey(opt->certList, opt->pkey, &opt->userCert);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (opt->outPutOpt.chain) {
ret = ParseAndAddCertChain(opt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
}
return MakePfxAndOutput(opt);
}
static int32_t OutPutCert(const char *certType, BSL_UIO *wUio, HITLS_X509_Cert *cert)
{
BSL_Buffer encodeCert = {};
int32_t ret = HITLS_X509_CertGenBuff(BSL_FORMAT_PEM, cert, &encodeCert);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: encode %s failed, errCode = 0x%0x.\n", certType, ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_APP_OptWriteUio(wUio, encodeCert.data, encodeCert.dataLen, HITLS_APP_FORMAT_PEM);
BSL_SAL_Free(encodeCert.data);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkcs12: Failed to print the cert\n");
return ret;
}
return HITLS_APP_SUCCESS;
}
static int32_t OutPutCerts(Pkcs12OptCtx *opt)
{
// Output the user cert.
int32_t ret = HITLS_PKCS12_Ctrl(opt->p12, HITLS_PKCS12_GET_ENTITY_CERT, &opt->userCert, 0);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to get user cert, errCode = 0x%0x.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = OutPutCert("user cert", opt->wUio, opt->userCert);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// only output user cert
if (opt->importOpt.clcerts) {
return HITLS_APP_SUCCESS;
}
// Output other cert and cert chain
HITLS_PKCS12_Bag *pstCertBag = BSL_LIST_GET_FIRST(opt->p12->certList);
while (pstCertBag != NULL) {
ret = OutPutCert("cert chain", opt->wUio, pstCertBag->value.cert);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
pstCertBag = BSL_LIST_GET_NEXT(opt->p12->certList);
}
return HITLS_APP_SUCCESS;
}
static int32_t OutPutKey(Pkcs12OptCtx *opt)
{
// Output private key
int32_t ret = HITLS_PKCS12_Ctrl(opt->p12, HITLS_PKCS12_GET_ENTITY_KEY, &opt->pkey, 0);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to get private key, errCode = 0x%0x.\n", ret);
return HITLS_APP_X509_FAIL;
}
AppKeyPrintParam param = { opt->genOpt.outFile, BSL_FORMAT_PEM, opt->cipherAlgCid, false, false};
return HITLS_APP_PrintPrvKeyByUio(opt->wUio, opt->pkey, ¶m, &opt->passout);
}
static int32_t OutPutCertsAndKey(Pkcs12OptCtx *opt)
{
int32_t ret = OutPutCerts(opt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return OutPutKey(opt);
}
static int32_t ParsePkcs12File(Pkcs12OptCtx *opt)
{
BSL_UI_ReadPwdParam passParam = { "Import passwd", NULL, false };
BSL_Buffer encPwd = { (uint8_t *)"", 0 };
if (HITLS_APP_GetPasswd(&passParam, &opt->passin, &encPwd.data, &encPwd.dataLen) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
HITLS_PKCS12_PwdParam param = {
.encPwd = &encPwd,
.macPwd = &encPwd,
};
int32_t ret = HITLS_PKCS12_ParseFile(BSL_FORMAT_ASN1, opt->genOpt.inFile, ¶m, &opt->p12, true);
(void)memset_s(encPwd.data, encPwd.dataLen, 0, encPwd.dataLen);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to parse the %s pkcs12 file, errCode = 0x%x.\n", opt->genOpt.inFile, ret);
return HITLS_APP_X509_FAIL;
}
return OutPutCertsAndKey(opt);
}
static int32_t CheckParam(Pkcs12OptCtx *opt)
{
// In all cases, the infile must exist.
int32_t ret = CheckInFile(opt->genOpt.inFile, "in file");
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (opt->outPutOpt.export) {
// In the export cases, the private key must be available.
ret = CheckInFile(opt->outPutOpt.inKey, "private key");
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (opt->importOpt.clcerts) {
AppPrintError("pkcs12: Warning: -clcerts option ignored with -export\n");
}
if (opt->importOpt.cipherAlgName != NULL) {
AppPrintError("pkcs12: Warning: output encryption option -%s ignored with -export\n",
opt->importOpt.cipherAlgName);
}
// When adding a certificate chain, caFile must be exist.
if (opt->outPutOpt.chain) {
ret = CheckInFile(opt->outPutOpt.caFile, "ca file");
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
} else if (opt->outPutOpt.caFile != NULL) {
AppPrintError("pkcs12: Warning: ignoring -CAfile since -chain is not given\n");
}
} else {
if (opt->outPutOpt.chain) {
AppPrintError("pkcs12: Warning: ignoring -chain since -export is not given\n");
}
if (opt->outPutOpt.caFile != NULL) {
AppPrintError("pkcs12: Warning: ignoring -CAfile since -export is not given\n");
}
if (opt->outPutOpt.keyPbeArg != NULL) {
AppPrintError("pkcs12: Warning: ignoring -keypbe since -export is not given\n");
}
if (opt->outPutOpt.certPbeArg != NULL) {
AppPrintError("pkcs12: Warning: ignoring -certpbe since -export is not given\n");
}
if (opt->outPutOpt.macAlgArg != NULL) {
AppPrintError("pkcs12: Warning: ignoring -macalg since -export is not given\n");
}
if (opt->outPutOpt.name != NULL) {
AppPrintError("pkcs12: Warning: ignoring -name since -export is not given\n");
}
if (opt->outPutOpt.caNameSize != 0) {
AppPrintError("pkcs12: Warning: ignoring -caname since -export is not given\n");
}
}
return CheckOutFile(opt->genOpt.outFile);
}
static void InitPkcs12OptCtx(Pkcs12OptCtx *optCtx)
{
optCtx->pkey = NULL;
optCtx->passin = NULL;
optCtx->passout = NULL;
optCtx->cipherAlgCid = CRYPT_CIPHER_AES256_CBC;
optCtx->macAlg = BSL_CID_SHA256;
optCtx->certPbe = BSL_CID_PBES2;
optCtx->keyPbe = BSL_CID_PBES2;
optCtx->p12 = NULL;
optCtx->store = NULL;
optCtx->certList = NULL;
optCtx->caCertList = NULL;
optCtx->outCertChainList = NULL;
optCtx->userCert = NULL;
optCtx->wUio = NULL;
optCtx->genOpt.inFile = NULL;
optCtx->genOpt.outFile = NULL;
optCtx->genOpt.passInArg = NULL;
optCtx->genOpt.passOutArg = NULL;
optCtx->importOpt.clcerts = false;
optCtx->importOpt.cipherAlgName = NULL;
optCtx->outPutOpt.inKey = NULL;
optCtx->outPutOpt.name = NULL;
optCtx->outPutOpt.caNameSize = 0;
optCtx->outPutOpt.caFile = NULL;
optCtx->outPutOpt.macAlgArg = NULL;
optCtx->outPutOpt.certPbeArg = NULL;
optCtx->outPutOpt.keyPbeArg = NULL;
optCtx->outPutOpt.chain = false;
optCtx->outPutOpt.export = false;
}
static void UnInitPkcs12OptCtx(Pkcs12OptCtx *optCtx)
{
CRYPT_EAL_PkeyFreeCtx(optCtx->pkey);
optCtx->pkey = NULL;
if (optCtx->passin != NULL) {
BSL_SAL_ClearFree(optCtx->passin, strlen(optCtx->passin));
}
if (optCtx->passout != NULL) {
BSL_SAL_ClearFree(optCtx->passout, strlen(optCtx->passout));
}
HITLS_PKCS12_Free(optCtx->p12);
optCtx->p12 = NULL;
HITLS_X509_StoreCtxFree(optCtx->store);
optCtx->store = NULL;
HITLS_X509_StoreCtxFree(optCtx->dupStore);
optCtx->dupStore = NULL;
BSL_LIST_FREE(optCtx->caCertList, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
BSL_LIST_FREE(optCtx->outCertChainList, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
BSL_LIST_FREE(optCtx->certList, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
HITLS_X509_CertFree(optCtx->userCert);
optCtx->userCert = NULL;
BSL_UIO_Free(optCtx->wUio);
optCtx->wUio = NULL;
BSL_SAL_FREE(optCtx);
}
static int32_t HandlePKCS12Opt(Pkcs12OptCtx *opt)
{
// 1.Read and Parse pass arg
if ((HITLS_APP_ParsePasswd(opt->genOpt.passInArg, &opt->passin) != HITLS_APP_SUCCESS) ||
(HITLS_APP_ParsePasswd(opt->genOpt.passOutArg, &opt->passout) != HITLS_APP_SUCCESS)) {
return HITLS_APP_PASSWD_FAIL;
}
// 2.Create output uio
opt->wUio = HITLS_APP_UioOpen(opt->genOpt.outFile, 'w', 0);
if (opt->wUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(opt->wUio, true);
return opt->outPutOpt.export ? CreatePkcs12File(opt) : ParsePkcs12File(opt);
}
// pkcs12 main function
int32_t HITLS_PKCS12Main(int argc, char *argv[])
{
Pkcs12OptCtx *opt = BSL_SAL_Calloc(1, sizeof(Pkcs12OptCtx));
if (opt == NULL) {
AppPrintError("pkcs12: Failed to create pkcs12 ctx.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
InitPkcs12OptCtx(opt);
int32_t ret = HITLS_APP_SUCCESS;
do {
ret = ParseOpt(argc, argv, opt);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = CheckParam(opt);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR, "provider=default", NULL, 0, NULL);
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkcs12: Failed to initialize the random number, errCode = 0x%x.\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = HandlePKCS12Opt(opt);
} while (false);
UnInitPkcs12OptCtx(opt);
CRYPT_EAL_RandDeinitEx(NULL);
return ret;
} | 2401_83913325/openHiTLS_1 | apps/src/app_pkcs12.c | C | unknown | 36,255 |
/*
* 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 "app_pkey.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <securec.h>
#include <limits.h>
#include "app_errno.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_list.h"
#include "app_utils.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_rand.h"
typedef enum {
HITLS_APP_OPT_IN = 2,
HITLS_APP_OPT_PASSIN,
HITLS_APP_OPT_OUT,
HITLS_APP_OPT_PUBOUT,
HITLS_APP_OPT_CIPHER_ALG,
HITLS_APP_OPT_PASSOUT,
HITLS_APP_OPT_TEXT,
HITLS_APP_OPT_NOOUT,
} HITLSOptType;
const HITLS_CmdOption g_pKeyOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"in", HITLS_APP_OPT_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input key"},
{"passin", HITLS_APP_OPT_PASSIN, HITLS_APP_OPT_VALUETYPE_STRING, "Input file pass phrase source"},
{"out", HITLS_APP_OPT_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"pubout", HITLS_APP_OPT_PUBOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Output public key, not private"},
{"", HITLS_APP_OPT_CIPHER_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Any supported cipher"},
{"passout", HITLS_APP_OPT_PASSOUT, HITLS_APP_OPT_VALUETYPE_STRING, "Output file pass phrase source"},
{"text", HITLS_APP_OPT_TEXT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print key in text(only RSA is supported)"},
{"noout", HITLS_APP_OPT_NOOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Do not output the key in encoded form"},
{NULL, 0, 0, NULL},
};
typedef struct {
char *inFilePath;
BSL_ParseFormat inFormat;
char *passInArg;
bool pubin;
} InputKeyPara;
typedef struct {
char *outFilePath;
BSL_ParseFormat outFormat;
char *passOutArg;
bool pubout;
bool text;
bool noout;
} OutPutKeyPara;
typedef struct {
CRYPT_EAL_PkeyCtx *pkey;
char *passin;
char *passout;
BSL_UIO *wUio;
int32_t cipherAlgCid;
InputKeyPara inPara;
OutPutKeyPara outPara;
} PkeyOptCtx;
typedef int32_t (*PkeyOptHandleFunc)(PkeyOptCtx *);
typedef struct {
int optType;
PkeyOptHandleFunc func;
} PkeyOptHandleTable;
static int32_t PkeyOptErr(PkeyOptCtx *optCtx)
{
(void)optCtx;
AppPrintError("pkey: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t PkeyOptHelp(PkeyOptCtx *optCtx)
{
(void)optCtx;
HITLS_APP_OptHelpPrint(g_pKeyOpts);
return HITLS_APP_HELP;
}
static int32_t PkeyOptIn(PkeyOptCtx *optCtx)
{
optCtx->inPara.inFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptPassin(PkeyOptCtx *optCtx)
{
optCtx->inPara.passInArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptOut(PkeyOptCtx *optCtx)
{
optCtx->outPara.outFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptPubout(PkeyOptCtx *optCtx)
{
optCtx->outPara.pubout = true;
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptCipher(PkeyOptCtx *optCtx)
{
const char *name = HITLS_APP_OptGetUnKownOptName();
return HITLS_APP_GetAndCheckCipherOpt(name, &optCtx->cipherAlgCid);
}
static int32_t PkeyOptPassout(PkeyOptCtx *optCtx)
{
optCtx->outPara.passOutArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptText(PkeyOptCtx *optCtx)
{
optCtx->outPara.text = true;
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptNoout(PkeyOptCtx *optCtx)
{
optCtx->outPara.noout = true;
return HITLS_APP_SUCCESS;
}
static const PkeyOptHandleTable g_pkeyOptHandleTable[] = {
{HITLS_APP_OPT_ERR, PkeyOptErr},
{HITLS_APP_OPT_HELP, PkeyOptHelp},
{HITLS_APP_OPT_IN, PkeyOptIn},
{HITLS_APP_OPT_PASSIN, PkeyOptPassin},
{HITLS_APP_OPT_OUT, PkeyOptOut},
{HITLS_APP_OPT_PUBOUT, PkeyOptPubout},
{HITLS_APP_OPT_CIPHER_ALG, PkeyOptCipher},
{HITLS_APP_OPT_PASSOUT, PkeyOptPassout},
{HITLS_APP_OPT_TEXT, PkeyOptText},
{HITLS_APP_OPT_NOOUT, PkeyOptNoout},
};
static int32_t ParsePkeyOpt(int argc, char *argv[], PkeyOptCtx *optCtx)
{
int32_t ret = HITLS_APP_OptBegin(argc, argv, g_pKeyOpts);
if (ret != HITLS_APP_SUCCESS) {
HITLS_APP_OptEnd();
AppPrintError("error in opt begin.\n");
return ret;
}
int optType = HITLS_APP_OPT_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF)) {
for (size_t i = 0; i < (sizeof(g_pkeyOptHandleTable) / sizeof(g_pkeyOptHandleTable[0])); ++i) {
if (optType == g_pkeyOptHandleTable[i].optType) {
ret = g_pkeyOptHandleTable[i].func(optCtx);
break;
}
}
}
// Obtain the number of parameters that cannot be parsed in the current version,
// and print the error inFormation and help list.
if ((ret == HITLS_APP_SUCCESS) && (HITLS_APP_GetRestOptNum() != 0)) {
AppPrintError("Extra arguments given.\n");
AppPrintError("pkey: Use -help for summary.\n");
ret = HITLS_APP_OPT_UNKOWN;
}
HITLS_APP_OptEnd();
return ret;
}
static int32_t HandlePkeyOpt(int argc, char *argv[], PkeyOptCtx *optCtx)
{
int32_t ret = ParsePkeyOpt(argc, argv, optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// 1. Read Password
if ((optCtx->cipherAlgCid == CRYPT_CIPHER_MAX) && (optCtx->outPara.passOutArg != NULL)) {
AppPrintError("Warning: The -passout option is ignored without a cipher option.\n");
}
if ((HITLS_APP_ParsePasswd(optCtx->inPara.passInArg, &optCtx->passin) != HITLS_APP_SUCCESS) ||
(HITLS_APP_ParsePasswd(optCtx->outPara.passOutArg, &optCtx->passout) != HITLS_APP_SUCCESS)) {
return HITLS_APP_PASSWD_FAIL;
}
// 2. Load the public or private key
if (optCtx->inPara.pubin) {
optCtx->pkey = HITLS_APP_LoadPubKey(optCtx->inPara.inFilePath, optCtx->inPara.inFormat);
} else {
optCtx->pkey = HITLS_APP_LoadPrvKey(optCtx->inPara.inFilePath, optCtx->inPara.inFormat, &optCtx->passin);
}
if (optCtx->pkey == NULL) {
return HITLS_APP_LOAD_KEY_FAIL;
}
// 3. Output the public or private key.
if (optCtx->outPara.pubout) {
return HITLS_APP_PrintPubKey(optCtx->pkey, optCtx->outPara.outFilePath, optCtx->outPara.outFormat);
}
optCtx->wUio = HITLS_APP_UioOpen(optCtx->outPara.outFilePath, 'w', 0);
if (optCtx->wUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(optCtx->wUio, true);
AppKeyPrintParam param = { optCtx->outPara.outFilePath, BSL_FORMAT_PEM, optCtx->cipherAlgCid,
optCtx->outPara.text, optCtx->outPara.noout};
return HITLS_APP_PrintPrvKeyByUio(optCtx->wUio, optCtx->pkey, ¶m, &optCtx->passout);
}
static void InitPkeyOptCtx(PkeyOptCtx *optCtx)
{
optCtx->pkey = NULL;
optCtx->passin = NULL;
optCtx->passout = NULL;
optCtx->cipherAlgCid = CRYPT_CIPHER_MAX;
optCtx->inPara.inFilePath = NULL;
optCtx->inPara.inFormat = BSL_FORMAT_PEM;
optCtx->inPara.passInArg = NULL;
optCtx->inPara.pubin = false;
optCtx->outPara.outFilePath = NULL;
optCtx->outPara.outFormat = BSL_FORMAT_PEM;
optCtx->outPara.passOutArg = NULL;
optCtx->outPara.pubout = false;
optCtx->outPara.text = false;
optCtx->outPara.noout = false;
}
static void UnInitPkeyOptCtx(PkeyOptCtx *optCtx)
{
CRYPT_EAL_PkeyFreeCtx(optCtx->pkey);
optCtx->pkey = NULL;
if (optCtx->passin != NULL) {
BSL_SAL_ClearFree(optCtx->passin, strlen(optCtx->passin));
}
if (optCtx->passout != NULL) {
BSL_SAL_ClearFree(optCtx->passout, strlen(optCtx->passout));
}
BSL_UIO_Free(optCtx->wUio);
optCtx->wUio = NULL;
}
// pkey main function
int32_t HITLS_PkeyMain(int argc, char *argv[])
{
PkeyOptCtx optCtx = {};
InitPkeyOptCtx(&optCtx);
int32_t ret = HITLS_APP_SUCCESS;
do {
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR,
"provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) {
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = HandlePkeyOpt(argc, argv, &optCtx);
} while (false);
CRYPT_EAL_RandDeinitEx(NULL);
UnInitPkeyOptCtx(&optCtx);
return ret;
} | 2401_83913325/openHiTLS_1 | apps/src/app_pkey.c | C | unknown | 8,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.
*/
#include "app_pkeyutl.h"
#include <limits.h>
#include "string.h"
#include "securec.h"
#include "bsl_sal.h"
#include "crypt_types.h"
#include "crypt_errno.h"
#include "crypt_params_key.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_codecs.h"
#include "bsl_errno.h"
#include "bsl_params.h"
#include "hitls_pki_errno.h"
#include "app_opt.h"
#include "app_function.h"
#include "app_list.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_provider.h"
#include "app_utils.h"
#include "app_sm.h"
#include "app_keymgmt.h"
#define SM2_PUBKEY_LEN 65
#define SM2_PRVKEY_LEN 33
#define CIPHER_TEXT_BASE_LEN 112
#define MAX_CERT_KEY_SIZE (256 * 1024)
#define APP_PKEYUTL_PBKDF2_IT_CNT_MIN 1024
#define APP_PKEYUTL_PBKDF2_SALT_LEN_MIN 8
#define APP_PKEYUTL_SM2_EXCH_TEMP_KEY_LEN 32 // SM3_MD_SIZE
typedef enum OptionChoice {
HITLS_APP_OPT_PKEYUTL_ERR = -1,
HITLS_APP_OPT_PKEYUTL_EOF = 0,
HITLS_APP_OPT_PKEYUTL_HELP = 1,
HITLS_APP_OPT_PKEYUTL_ENCRYPT,
HITLS_APP_OPT_PKEYUTL_DECRYPT,
HITLS_APP_OPT_PKEYUTL_DERIVE,
HITLS_APP_OPT_PKEYUTL_OUTR,
HITLS_APP_OPT_PKEYUTL_OUTRAND,
HITLS_APP_OPT_PKEYUTL_INR,
HITLS_APP_OPT_PKEYUTL_SELFR,
HITLS_APP_OPT_PKEYUTL_PUBIN,
HITLS_APP_OPT_PKEYUTL_PRVIN,
HITLS_APP_OPT_PKEYUTL_IN,
HITLS_APP_OPT_PKEYUTL_OUT,
HITLS_APP_OPT_PKEYUTL_INKEY,
HITLS_APP_OPT_PKEYUTL_PEERKEY,
HITLS_APP_OPT_PKEYUTL_USERID,
HITLS_APP_OPT_PKEYUTL_RPASS,
HITLS_APP_PROV_ENUM,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS_ENUM,
#endif
} HITLSOptType;
const HITLS_CmdOption g_pkeyUtlOpts[] = {
{"help", HITLS_APP_OPT_PKEYUTL_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Show usage information for command."},
{"encrypt", HITLS_APP_OPT_PKEYUTL_ENCRYPT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Public key encryption."},
{"decrypt", HITLS_APP_OPT_PKEYUTL_DECRYPT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Private key decryption."},
{"derive", HITLS_APP_OPT_PKEYUTL_DERIVE, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Key exchange."},
{"outR", HITLS_APP_OPT_PKEYUTL_OUTR, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Key exchange output R."},
{"outr", HITLS_APP_OPT_PKEYUTL_OUTRAND, HITLS_APP_OPT_VALUETYPE_OUT_FILE,
"Key exchange output self r."},
{"inR", HITLS_APP_OPT_PKEYUTL_INR, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Key exchange input R."},
{"inr", HITLS_APP_OPT_PKEYUTL_SELFR, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Key exchange input r."},
{"pubin", HITLS_APP_OPT_PKEYUTL_PUBIN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file for public key."},
{"prvin", HITLS_APP_OPT_PKEYUTL_PRVIN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file for private key."},
{"in", HITLS_APP_OPT_PKEYUTL_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file for data to be processed."},
{"out", HITLS_APP_OPT_PKEYUTL_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file for result."},
{"inkey", HITLS_APP_OPT_PKEYUTL_INKEY, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Key for this side in key exchange."},
{"peerkey", HITLS_APP_OPT_PKEYUTL_PEERKEY, HITLS_APP_OPT_VALUETYPE_IN_FILE,
"Key for the other side in key exchange."},
{"userid", HITLS_APP_OPT_PKEYUTL_USERID, HITLS_APP_OPT_VALUETYPE_STRING, "User ID for SM2."},
{"rpass", HITLS_APP_OPT_PKEYUTL_RPASS, HITLS_APP_OPT_VALUETYPE_STRING,
"Password to encrypt or decrypt sm2 temp key when key exchange."},
HITLS_APP_PROV_OPTIONS,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS,
#endif
{NULL, 0, 0, NULL}};
typedef struct {
int32_t optEncrypt; // Flag for encrypt
int32_t optDecrypt; // Flag for decrypt
int32_t optDerive; // Flag for derive
char *outRFile; // Output file for R
char *outRandFile; // Output file for self r
char *inRFile; // Input file for R
char *inRandFile; // Input file for self r
char *pubinFile; // Input file for public key
char *prvinFile; // Input file for private key
char *inFile; // Input file for data to be processed
char *outFile; // Output file for result
char *inkeyFile; // Key for this side in key exchange
char *peerkeyFile; // Key for the other side in key exchange
char *rpass;
char *userid;
AppProvider *provider;
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param *smParam;
#endif
} PkeyUtlOpt;
typedef int32_t (*PkeyUtlOptHandleFunc)(PkeyUtlOpt *);
typedef struct {
int optType;
PkeyUtlOptHandleFunc func;
} PkeyUtlOptHandleFuncMap;
static int32_t HandlePkeyUtlErr(PkeyUtlOpt *opt)
{
(void)opt;
AppPrintError("pkeyutl: Invalid option or error occurred.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t HandlePkeyUtlHelp(PkeyUtlOpt *opt)
{
(void)opt;
HITLS_APP_OptHelpPrint(g_pkeyUtlOpts);
return HITLS_APP_HELP;
}
static int32_t HandlePkeyUtlEncrypt(PkeyUtlOpt *opt)
{
opt->optEncrypt = 1;
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlDecrypt(PkeyUtlOpt *opt)
{
opt->optDecrypt = 1;
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlDerive(PkeyUtlOpt *opt)
{
opt->optDerive = 1;
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlPubin(PkeyUtlOpt *opt)
{
opt->pubinFile = HITLS_APP_OptGetValueStr();
if (opt->pubinFile == NULL) {
AppPrintError("pkeyutl: Invalid public key file.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlPrvin(PkeyUtlOpt *opt)
{
opt->prvinFile = HITLS_APP_OptGetValueStr();
if (opt->prvinFile == NULL) {
AppPrintError("pkeyutl: Invalid private key file.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlIn(PkeyUtlOpt *opt)
{
opt->inFile = HITLS_APP_OptGetValueStr();
if (opt->inFile == NULL) {
AppPrintError("pkeyutl: Invalid input file.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlOut(PkeyUtlOpt *opt)
{
opt->outFile = HITLS_APP_OptGetValueStr();
if (opt->outFile == NULL) {
AppPrintError("pkeyutl: Invalid output file.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlInkey(PkeyUtlOpt *opt)
{
opt->inkeyFile = HITLS_APP_OptGetValueStr();
if (opt->inkeyFile == NULL) {
AppPrintError("pkeyutl: Invalid inkey file.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlPeerkey(PkeyUtlOpt *opt)
{
opt->peerkeyFile = HITLS_APP_OptGetValueStr();
if (opt->peerkeyFile == NULL) {
AppPrintError("pkeyutl: Invalid peerkey file.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlR(PkeyUtlOpt *opt)
{
opt->outRFile = HITLS_APP_OptGetValueStr();
if (opt->outRFile == NULL) {
AppPrintError("pkeyutl: Invalid outR file.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlSelfOutr(PkeyUtlOpt *opt)
{
opt->outRandFile = HITLS_APP_OptGetValueStr();
if (opt->outRandFile == NULL) {
AppPrintError("pkeyutl: Invalid out r file.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlInR(PkeyUtlOpt *opt)
{
opt->inRFile = HITLS_APP_OptGetValueStr();
if (opt->inRFile == NULL) {
AppPrintError("pkeyutl: Invalid inR file.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlSelfr(PkeyUtlOpt *opt)
{
opt->inRandFile = HITLS_APP_OptGetValueStr();
if (opt->inRandFile == NULL) {
AppPrintError("pkeyutl: Invalid in r file.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlUserid(PkeyUtlOpt *opt)
{
opt->userid = HITLS_APP_OptGetValueStr();
if (opt->userid == NULL) {
AppPrintError("pkeyutl: Invalid user ID.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandlePkeyUtlrPass(PkeyUtlOpt *opt)
{
opt->rpass = HITLS_APP_OptGetValueStr();
if (opt->rpass == NULL) {
AppPrintError("pkeyutl: Invalid rpass.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static const PkeyUtlOptHandleFuncMap g_ecOptHandleFuncMap[] = {
{HITLS_APP_OPT_PKEYUTL_ERR, HandlePkeyUtlErr},
{HITLS_APP_OPT_PKEYUTL_HELP, HandlePkeyUtlHelp},
{HITLS_APP_OPT_PKEYUTL_ENCRYPT, HandlePkeyUtlEncrypt},
{HITLS_APP_OPT_PKEYUTL_DECRYPT, HandlePkeyUtlDecrypt},
{HITLS_APP_OPT_PKEYUTL_DERIVE, HandlePkeyUtlDerive},
{HITLS_APP_OPT_PKEYUTL_OUTR, HandlePkeyUtlR},
{HITLS_APP_OPT_PKEYUTL_OUTRAND, HandlePkeyUtlSelfOutr},
{HITLS_APP_OPT_PKEYUTL_INR, HandlePkeyUtlInR},
{HITLS_APP_OPT_PKEYUTL_SELFR, HandlePkeyUtlSelfr},
{HITLS_APP_OPT_PKEYUTL_PUBIN, HandlePkeyUtlPubin},
{HITLS_APP_OPT_PKEYUTL_PRVIN, HandlePkeyUtlPrvin},
{HITLS_APP_OPT_PKEYUTL_IN, HandlePkeyUtlIn},
{HITLS_APP_OPT_PKEYUTL_OUT, HandlePkeyUtlOut},
{HITLS_APP_OPT_PKEYUTL_INKEY, HandlePkeyUtlInkey},
{HITLS_APP_OPT_PKEYUTL_PEERKEY, HandlePkeyUtlPeerkey},
{HITLS_APP_OPT_PKEYUTL_USERID, HandlePkeyUtlUserid},
{HITLS_APP_OPT_PKEYUTL_RPASS, HandlePkeyUtlrPass},
};
static int32_t ParsepkeyUtlOpt(PkeyUtlOpt *pkeyUtlOpt)
{
int ret = HITLS_APP_SUCCESS;
int optType = HITLS_APP_OPT_PKEYUTL_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_PKEYUTL_EOF)) {
for (size_t i = 0; i < (sizeof(g_ecOptHandleFuncMap) / sizeof(g_ecOptHandleFuncMap[0])); ++i) {
if (optType == g_ecOptHandleFuncMap[i].optType) {
ret = g_ecOptHandleFuncMap[i].func(pkeyUtlOpt);
break;
}
}
HITLS_APP_PROV_CASES(optType, pkeyUtlOpt->provider)
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_CASES(optType, pkeyUtlOpt->smParam);
#endif
}
if (HITLS_APP_GetRestOptNum() != 0) {
AppPrintError("Extra arguments given.\n");
AppPrintError("pkeyutl: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return ret;
}
static int32_t GetReadBuf(uint8_t **buf, uint64_t *bufLen, char *inFile, uint32_t maxSize)
{
if (buf == NULL || bufLen == NULL) {
AppPrintError("pkeyutl: Invalid parameters for GetReadBuf\n");
return HITLS_APP_INVALID_ARG;
}
BSL_UIO *readUio = HITLS_APP_UioOpen(inFile, 'r', 0);
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
if (readUio == NULL) {
if (inFile == NULL) {
AppPrintError("pkeyutl: Failed to open stdin\n");
} else {
AppPrintError("pkeyutl: Failed to open the file <%s>, No such file or directory\n", inFile);
}
return HITLS_APP_UIO_FAIL;
}
int32_t ret = HITLS_APP_OptReadUio(readUio, buf, bufLen, maxSize);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("pkeyutl: Failed to read the content from the file <%s>\n", inFile);
}
BSL_UIO_Free(readUio);
return ret;
}
static int32_t CheckFilePathLength(const PkeyUtlOpt *opt)
{
// Check all file path length
if (opt->inFile != NULL && strlen(opt->inFile) > PATH_MAX) {
AppPrintError("pkeyutl: The input file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (opt->outFile != NULL && strlen(opt->outFile) > PATH_MAX) {
AppPrintError("pkeyutl: The output file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (opt->pubinFile != NULL && strlen(opt->pubinFile) > PATH_MAX) {
AppPrintError("pkeyutl: The public key file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (opt->prvinFile != NULL && strlen(opt->prvinFile) > PATH_MAX) {
AppPrintError("pkeyutl: The private key file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (opt->inkeyFile != NULL && strlen(opt->inkeyFile) > PATH_MAX) {
AppPrintError("pkeyutl: The inkey file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (opt->peerkeyFile != NULL && strlen(opt->peerkeyFile) > PATH_MAX) {
AppPrintError("pkeyutl: The peerkey file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (opt->outRFile != NULL && strlen(opt->outRFile) > PATH_MAX) {
AppPrintError("pkeyutl: The outR file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (opt->inRFile != NULL && strlen(opt->inRFile) > PATH_MAX) {
AppPrintError("pkeyutl: The inR file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (opt->inRandFile != NULL && strlen(opt->inRandFile) > PATH_MAX) {
AppPrintError("pkeyutl: The r file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (opt->outRandFile != NULL && strlen(opt->outRandFile) > PATH_MAX) {
AppPrintError("pkeyutl: The out r file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t GetrPass(PkeyUtlOpt *opt, char **pass)
{
char *tmpPass = NULL;
int32_t ret = HITLS_APP_ParsePasswd(opt->rpass == NULL ? "stdin" : opt->rpass, &tmpPass);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to parse the rpass, errCode: 0x%08x.\n", ret);
return HITLS_APP_PASSWD_FAIL;
}
*pass = tmpPass;
return HITLS_APP_SUCCESS;
}
static int32_t CheckParam(const PkeyUtlOpt *opt)
{
int32_t count = opt->optEncrypt + opt->optDecrypt + opt->optDerive;
if (count != 1) {
AppPrintError("Must choose exactly one operation: encrypt, decrypt, or derive.\n");
return HITLS_APP_INVALID_ARG;
}
if (opt->outFile == NULL && opt->optDerive == 0) {
AppPrintError("Output file not specified.\n");
return HITLS_APP_INVALID_ARG;
}
if (opt->optEncrypt == 1) {
if (opt->inFile == NULL || opt->pubinFile == NULL) {
AppPrintError("Encrypt: input file or public key file not specified.\n");
return HITLS_APP_INVALID_ARG;
}
}
if (opt->optDecrypt == 1) {
if (opt->inFile == NULL || opt->prvinFile == NULL) {
AppPrintError("Decrypt: input file or inkey file not specified.\n");
return HITLS_APP_INVALID_ARG;
}
}
if (opt->optDerive == 1) {
if (opt->inkeyFile == NULL) {
AppPrintError("Derive: inkey file or peerkey file not specified.\n");
return HITLS_APP_INVALID_ARG;
}
}
#ifdef HITLS_APP_SM_MODE
if (opt->smParam->smTag == 1 && opt->smParam->workPath == NULL) {
AppPrintError(" The workpath is not specified.\n");
return HITLS_APP_INVALID_ARG;
}
#endif
return CheckFilePathLength(opt);
}
#ifdef HITLS_APP_SM_MODE
static int32_t GetPkeyCtxFromUuid(PkeyUtlOpt *pkeyUtlOpt, char *uuid, CRYPT_EAL_PkeyCtx **ctx)
{
HITLS_APP_KeyInfo keyInfo = {0};
pkeyUtlOpt->smParam->uuid = uuid;
int32_t ret = HITLS_APP_FindKey(pkeyUtlOpt->provider, pkeyUtlOpt->smParam, CRYPT_PKEY_SM2, &keyInfo);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to find key, ret: 0x%08x\n", ret);
return ret;
}
*ctx = keyInfo.pkeyCtx;
return HITLS_APP_SUCCESS;
}
#endif
static int32_t GetPubKeyCtx(PkeyUtlOpt *pkeyUtlOpt, CRYPT_EAL_PkeyCtx **ctx)
{
int32_t ret = HITLS_APP_SUCCESS;
uint8_t *pubBuf = NULL;
uint64_t bufLen = 0;
BSL_Buffer pub = {0};
CRYPT_EAL_PkeyCtx *pkeyCtx = NULL;
#ifdef HITLS_APP_SM_MODE
if (pkeyUtlOpt->smParam->smTag == 1) {
ret = GetPkeyCtxFromUuid(pkeyUtlOpt, pkeyUtlOpt->pubinFile, &pkeyCtx);
if (ret == HITLS_APP_SUCCESS) {
*ctx = pkeyCtx;
return HITLS_APP_SUCCESS;
}
}
#endif
ret = GetReadBuf(&pubBuf, &bufLen, pkeyUtlOpt->pubinFile, MAX_CERT_KEY_SIZE);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("pkeyutl: Failed to read the public key file\n");
return ret;
}
pub.data = pubBuf;
pub.dataLen = bufLen;
ret = CRYPT_EAL_ProviderDecodeBuffKey(APP_GetCurrent_LibCtx(), pkeyUtlOpt->provider->providerAttr,
BSL_CID_UNKNOWN, "PEM", "PRIKEY_PKCS8_UNENCRYPT", &pub, NULL, &pkeyCtx);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("pkeyutl: Failed to decode the private key, ret=%d\n", ret);
BSL_SAL_ClearFree(pubBuf, bufLen);
return HITLS_APP_CRYPTO_FAIL;
}
BSL_SAL_ClearFree(pubBuf, bufLen);
*ctx = pkeyCtx;
(void)AppPrintError("pkeyutl: Get pub key ctx success!\n");
return HITLS_APP_SUCCESS;
}
static int32_t PkeyEncrypt(PkeyUtlOpt *pkeyUtlOpt)
{
int32_t ret = HITLS_APP_SUCCESS;
uint8_t *plainText = NULL;
uint64_t plainTextLen = 0;
uint8_t *cipherText = NULL;
uint32_t outLen = CIPHER_TEXT_BASE_LEN;
CRYPT_EAL_PkeyCtx *ctx = NULL;
do {
ret = GetPubKeyCtx(pkeyUtlOpt, &ctx);
if (ret != HITLS_APP_SUCCESS) {
break;
}
#ifdef HITLS_APP_SM_MODE
if (pkeyUtlOpt->smParam->smTag == 1) {
pkeyUtlOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
}
#endif
ret = GetReadBuf(&plainText, &plainTextLen, pkeyUtlOpt->inFile, MAX_CERT_KEY_SIZE);
if (ret != HITLS_APP_SUCCESS) {
break;
}
outLen += plainTextLen;
cipherText = BSL_SAL_Malloc(outLen);
if (cipherText == NULL) {
(void)AppPrintError("Failed to allocate memory for ciphertext\n");
ret = HITLS_APP_MEM_ALLOC_FAIL;
break;
}
ret = CRYPT_EAL_PkeyEncrypt(ctx, plainText, plainTextLen, cipherText, &outLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("Failed to encrypt the plaintext, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(pkeyUtlOpt->outFile, 'w', 0); // overwrite the original content
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
if (fileWriteUio == NULL) {
(void)AppPrintError("Failed to open the outfile\n");
ret = HITLS_APP_UIO_FAIL;
break;
}
ret = HITLS_APP_OptWriteUio(fileWriteUio, cipherText, outLen, HITLS_APP_FORMAT_HEX);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("dgst:Failed to export data to the outfile path\n");
}
BSL_UIO_Free(fileWriteUio);
} while (0);
BSL_SAL_FREE(cipherText);
BSL_SAL_FREE(plainText);
CRYPT_EAL_PkeyFreeCtx(ctx);
return ret;
}
static int32_t PkeyDecrypt(PkeyUtlOpt *pkeyUtlOpt)
{
int32_t ret = HITLS_APP_SUCCESS;
uint8_t *priBuf = NULL;
uint64_t priLen = 0;
uint8_t *cipherText = NULL;
uint64_t cipherLen = 0;
uint8_t *plainText = NULL;
uint32_t outLen = 0;
BSL_Buffer prv = {0};
uint8_t *hexBuf = NULL;
uint32_t hexLen;
CRYPT_EAL_PkeyCtx *ctx = NULL;
do {
#ifdef HITLS_APP_SM_MODE
if (pkeyUtlOpt->smParam->smTag == 1) {
ret = GetPkeyCtxFromUuid(pkeyUtlOpt, pkeyUtlOpt->prvinFile, &ctx);
if (ret != HITLS_APP_SUCCESS) {
break;
}
} else {
#endif
ret = GetReadBuf(&priBuf, &priLen, pkeyUtlOpt->prvinFile, MAX_CERT_KEY_SIZE);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to read private key file for decryption.\n");
break;
}
prv.data = priBuf;
prv.dataLen = priLen;
ret = CRYPT_EAL_ProviderDecodeBuffKey(APP_GetCurrent_LibCtx(), pkeyUtlOpt->provider->providerAttr,
BSL_CID_UNKNOWN, "PEM", "PRIKEY_PKCS8_UNENCRYPT", &prv, NULL, &ctx);
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: Failed to decode the private key, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
#ifdef HITLS_APP_SM_MODE
}
if (pkeyUtlOpt->smParam->smTag == 1) {
pkeyUtlOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
}
#endif
ret = GetReadBuf(&cipherText, &cipherLen, pkeyUtlOpt->inFile, UINT32_MAX);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to read input ciphertext file.\n");
break;
}
hexBuf = BSL_SAL_Malloc(cipherLen * 2 + 1);
hexLen = cipherLen * 2;
ret = HITLS_APP_StrToHex((const char *)cipherText, hexBuf, &hexLen);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("pkeyutl: Failed to convert signature to hex.");
break;
}
outLen = cipherLen;
plainText = BSL_SAL_Malloc(outLen);
if (plainText == NULL) {
AppPrintError("Failed to allocate memory for plaintext\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
ret = CRYPT_EAL_PkeyDecrypt(ctx, hexBuf, hexLen, plainText, &outLen);
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: SM2 decryption failed, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(pkeyUtlOpt->outFile, 'w', 0);
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
if (fileWriteUio == NULL) {
AppPrintError("pkeyutl: Failed to open the output file for plaintext.\n");
ret = HITLS_APP_UIO_FAIL;
break;
}
ret = HITLS_APP_OptWriteUio(fileWriteUio, plainText, outLen, HITLS_APP_FORMAT_TEXT);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to export plaintext to the output file.\n");
}
BSL_UIO_Free(fileWriteUio);
} while (0);
BSL_SAL_ClearFree(prv.data, prv.dataLen);
BSL_SAL_FREE(hexBuf);
BSL_SAL_FREE(cipherText);
BSL_SAL_FREE(plainText);
CRYPT_EAL_PkeyFreeCtx(ctx);
return ret;
}
static int32_t GetPeerCtx(CRYPT_EAL_PkeyCtx **peerCtx, PkeyUtlOpt *pkeyUtlOpt)
{
int32_t ret = HITLS_APP_SUCCESS;
uint8_t *pubBuf = NULL;
uint64_t pubLen = 0;
uint8_t *inRBuf = NULL;
uint64_t inRLen = 0;
uint8_t *hexBuf = NULL;
uint32_t hexLen;
BSL_Buffer pub = {0};
do {
ret = GetReadBuf(&pubBuf, &pubLen, pkeyUtlOpt->peerkeyFile, MAX_CERT_KEY_SIZE);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to read peer public key file for exchange.\n");
break;
}
pub.data = pubBuf;
pub.dataLen = pubLen;
ret = CRYPT_EAL_ProviderDecodeBuffKey(APP_GetCurrent_LibCtx(), pkeyUtlOpt->provider->providerAttr,
BSL_CID_UNKNOWN, "PEM", "PRIKEY_PKCS8_UNENCRYPT", &pub, NULL, peerCtx);
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: Failed to decode the peer public key, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = GetReadBuf(&inRBuf, &inRLen, pkeyUtlOpt->inRFile, MAX_CERT_KEY_SIZE);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to read R file for exchange.\n");
break;
}
hexBuf = BSL_SAL_Malloc(inRLen * 2 + 1);
hexLen = inRLen * 2;
ret = HITLS_APP_StrToHex((const char *)inRBuf, hexBuf, &hexLen);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("pkeyutl: Failed to convert R to hex.");
break;
}
ret = CRYPT_EAL_PkeyCtrl(*peerCtx, CRYPT_CTRL_SET_SM2_USER_ID, pkeyUtlOpt->userid, strlen(pkeyUtlOpt->userid));
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: Failed to set SM2 user ID, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
if (pkeyUtlOpt->inRFile != NULL) {
ret = CRYPT_EAL_PkeyCtrl(*peerCtx, CRYPT_CTRL_SET_SM2_SERVER, &(int32_t){0}, sizeof(int32_t));
} else {
ret = CRYPT_EAL_PkeyCtrl(*peerCtx, CRYPT_CTRL_SET_SM2_SERVER, &(int32_t){1}, sizeof(int32_t));
}
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: Failed to set SM2 server/client, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = CRYPT_EAL_PkeyCtrl(*peerCtx, CRYPT_CTRL_SET_SM2_R, hexBuf, hexLen);
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: Failed to generate SM2 R, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
}
} while (0);
BSL_SAL_FREE(hexBuf);
BSL_SAL_FREE(inRBuf);
BSL_SAL_ClearFree(pub.data, pub.dataLen);
return ret;
}
static int32_t GetDataFromP12(AppProvider *provider, const char *file, uint8_t *password, uint32_t passwordLen,
uint8_t *data, uint32_t *dataLen)
{
HITLS_PKCS12 *p12 = NULL;
BSL_Buffer encPwd = {0};
HITLS_PKCS12_PwdParam pwdParam = {0};
encPwd.data = password;
encPwd.dataLen = passwordLen;
pwdParam.encPwd = &encPwd;
pwdParam.macPwd = &encPwd;
int32_t ret = HITLS_PKCS12_ProviderParseFile(APP_GetCurrent_LibCtx(), provider->providerAttr, "ASN1", file,
&pwdParam, &p12, true);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkeyutl: Failed to read p12 file, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
BslList *bagList = NULL;
ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GET_SECRETBAGS, &bagList, 0);
if (ret != HITLS_PKI_SUCCESS) {
HITLS_PKCS12_Free(p12);
AppPrintError("pkeyutl: Failed to get secret bags, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
HITLS_PKCS12_Bag *bag = BSL_LIST_GET_FIRST(bagList);
BSL_Buffer value = {data, *dataLen};
ret = HITLS_PKCS12_BagCtrl(bag, HITLS_PKCS12_BAG_GET_VALUE, &value, 0);
HITLS_PKCS12_Free(p12);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkeyutl: Failed to get bag value, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
*dataLen = value.dataLen;
return HITLS_APP_SUCCESS;
}
static int32_t GenP12File(AppProvider *provider, const char *file, HITLS_PKCS12_EncodeParam *encodeParam,
uint8_t *data, uint32_t dataLen)
{
HITLS_PKCS12 *p12 = HITLS_PKCS12_ProviderNew(APP_GetCurrent_LibCtx(), provider->providerAttr);
if (p12 == NULL) {
AppPrintError("pkeyutl: Failed to create the p12 ctx.\n");
return HITLS_APP_X509_FAIL;
}
BSL_Buffer value = {0};
value.data = data;
value.dataLen = dataLen;
HITLS_PKCS12_Bag *bag = HITLS_PKCS12_BagNew(BSL_CID_SECRETBAG, BSL_CID_CE_KEYUSAGE, &value);
if (bag == NULL) {
AppPrintError("pkeyutl: Failed to create the secret bag.\n");
HITLS_PKCS12_Free(p12);
return HITLS_APP_X509_FAIL;
}
int32_t ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_SECRETBAG, bag, 0);
HITLS_PKCS12_BagFree(bag);
if (ret != HITLS_PKI_SUCCESS) {
HITLS_PKCS12_Free(p12);
AppPrintError("pkeyutl: Failed to add the secret bag to p12, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_PKCS12_GenFile(BSL_FORMAT_ASN1, p12, encodeParam, true, file);
HITLS_PKCS12_Free(p12);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkeyutl: Failed to generate p12 file, errCode: 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t AddDataToP12(AppProvider *provider, const char *file, uint8_t *password, uint32_t passwordLen,
uint8_t *data, uint32_t dataLen)
{
CRYPT_Pbkdf2Param pbkdf2Param = {0};
pbkdf2Param.pbesId = BSL_CID_PBES2;
pbkdf2Param.pbkdfId = CRYPT_KDF_PBKDF2;
pbkdf2Param.hmacId = CRYPT_MAC_HMAC_SM3;
pbkdf2Param.symId = CRYPT_CIPHER_SM4_CBC;
pbkdf2Param.saltLen = APP_PKEYUTL_PBKDF2_SALT_LEN_MIN;
pbkdf2Param.pwd = password;
pbkdf2Param.pwdLen = passwordLen;
pbkdf2Param.itCnt = APP_PKEYUTL_PBKDF2_IT_CNT_MIN;
CRYPT_EncodeParam encParam = {0};
encParam.deriveMode = CRYPT_DERIVE_PBKDF2;
encParam.param = &pbkdf2Param;
HITLS_PKCS12_KdfParam kdfParam = {0};
kdfParam.saltLen = APP_PKEYUTL_PBKDF2_SALT_LEN_MIN;
kdfParam.itCnt = APP_PKEYUTL_PBKDF2_IT_CNT_MIN;
kdfParam.macId = CRYPT_MD_SM3;
kdfParam.pwd = password;
kdfParam.pwdLen = passwordLen;
HITLS_PKCS12_MacParam macParam = {0};
macParam.algId = BSL_CID_PKCS12KDF;
macParam.para = &kdfParam;
HITLS_PKCS12_EncodeParam encodeParam = {0};
encodeParam.encParam = encParam;
encodeParam.macParam = macParam;
return GenP12File(provider, file, &encodeParam, data, dataLen);
}
static int32_t GetTempKeyFromP12(PkeyUtlOpt *pkeyUtlOpt, CRYPT_EAL_PkeyCtx *ctx)
{
char *pass = NULL;
int32_t ret = GetrPass(pkeyUtlOpt, &pass);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to get rpass, errCode: 0x%x.\n", ret);
return ret;
}
uint8_t r[APP_PKEYUTL_SM2_EXCH_TEMP_KEY_LEN] = {0};
uint32_t rLen = sizeof(r);
ret = GetDataFromP12(pkeyUtlOpt->provider, pkeyUtlOpt->inRandFile, (uint8_t *)pass, strlen(pass), r, &rLen);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_ClearFree(pass, strlen(pass));
AppPrintError("pkeyutl: Failed to get SM2 r from p12, errCode: 0x%x.\n", ret);
return ret;
}
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_RANDOM, r, rLen);
BSL_SAL_CleanseData(r, rLen);
BSL_SAL_ClearFree(pass, strlen(pass));
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: Failed to set SM2 r, ret=%d\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t WriteTempKeyToP12(PkeyUtlOpt *pkeyUtlOpt, CRYPT_EAL_PkeyCtx *ctx)
{
char *pass = NULL;
int32_t ret = GetrPass(pkeyUtlOpt, &pass);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to get rpass, errCode: 0x%x.\n", ret);
return ret;
}
uint8_t r[APP_PKEYUTL_SM2_EXCH_TEMP_KEY_LEN] = {0};
uint32_t rLen = sizeof(r);
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_SM2_RANDOM, r, rLen);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_ClearFree(pass, strlen(pass));
AppPrintError("pkeyutl: Failed to get SM2 r, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
ret = AddDataToP12(pkeyUtlOpt->provider, pkeyUtlOpt->outRandFile, (uint8_t *)pass, strlen(pass), r, rLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to add SM2 r to p12, errCode: 0x%x.\n", ret);
}
BSL_SAL_ClearFree(pass, strlen(pass));
BSL_SAL_CleanseData(r, sizeof(r));
return ret;
}
static int32_t PkeyDerive(PkeyUtlOpt *pkeyUtlOpt)
{
int32_t ret = HITLS_APP_SUCCESS;
uint8_t *priBuf = NULL;
uint64_t priLen = 0;
uint8_t localR[65];
CRYPT_EAL_PkeyCtx *ctx = NULL;
CRYPT_EAL_PkeyCtx *peerCtx = NULL;
uint8_t out[64];
uint32_t outLen = sizeof(out);
BSL_Buffer prv = {0};
do {
#ifdef HITLS_APP_SM_MODE
if (pkeyUtlOpt->smParam->smTag == 1) {
ret = GetPkeyCtxFromUuid(pkeyUtlOpt, pkeyUtlOpt->inkeyFile, &ctx);
if (ret != HITLS_APP_SUCCESS) {
break;
}
} else {
#endif
ret = GetReadBuf(&priBuf, &priLen, pkeyUtlOpt->inkeyFile, MAX_CERT_KEY_SIZE);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to read private key file for exchange.\n");
break;
}
prv.data = priBuf;
prv.dataLen = priLen;
ret = CRYPT_EAL_ProviderDecodeBuffKey(APP_GetCurrent_LibCtx(), pkeyUtlOpt->provider->providerAttr,
BSL_CID_UNKNOWN, "PEM", "PRIKEY_PKCS8_UNENCRYPT", &prv, NULL, &ctx);
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: Failed to decode the private key, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
#ifdef HITLS_APP_SM_MODE
}
#endif
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, pkeyUtlOpt->userid, strlen(pkeyUtlOpt->userid));
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: Failed to set SM2 user ID, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
if (pkeyUtlOpt->inRandFile == NULL) {
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_SERVER, &(int32_t){1}, sizeof(int32_t));
} else {
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_SERVER, &(int32_t){0}, sizeof(int32_t));
}
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: Failed to set SM2 server/client, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
if (pkeyUtlOpt->inRandFile == NULL) {
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR));
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: Failed to generate SM2 R, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
} else {
ret = GetTempKeyFromP12(pkeyUtlOpt, ctx);
if (ret != HITLS_APP_SUCCESS) {
break;
}
}
if (pkeyUtlOpt->outRFile != NULL) {
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(pkeyUtlOpt->outRFile, 'w', 0);
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
if (fileWriteUio == NULL) {
AppPrintError("pkeyutl: Failed to open the output file for R.\n");
ret = HITLS_APP_UIO_FAIL;
break;
}
ret = HITLS_APP_OptWriteUio(fileWriteUio, localR, sizeof(localR), HITLS_APP_FORMAT_HEX);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to export R to the output file.\n");
}
BSL_UIO_Free(fileWriteUio);
}
if (pkeyUtlOpt->outRandFile != NULL) {
ret = WriteTempKeyToP12(pkeyUtlOpt, ctx);
if (ret != HITLS_APP_SUCCESS) {
break;
}
}
if (pkeyUtlOpt->inRFile != NULL && pkeyUtlOpt->peerkeyFile != NULL) {
ret = GetPeerCtx(&peerCtx, pkeyUtlOpt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to get peer context, ret=%d\n", ret);
break;
}
#ifdef HITLS_APP_SM_MODE
if (pkeyUtlOpt->smParam->smTag == 1) {
pkeyUtlOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
}
#endif
ret = CRYPT_EAL_PkeyComputeShareKey(ctx, peerCtx, out, &outLen);
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkeyutl: Failed to compute shared key, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
BSL_UIO *shareFileUio = HITLS_APP_UioOpen(pkeyUtlOpt->outFile, 'w', 0);
BSL_UIO_SetIsUnderlyingClosedByUio(shareFileUio, true);
if (shareFileUio == NULL) {
AppPrintError("pkeyutl: Failed to open the output file for plaintext.\n");
ret = HITLS_APP_UIO_FAIL;
break;
}
ret = HITLS_APP_OptWriteUio(shareFileUio, out, outLen, HITLS_APP_FORMAT_TEXT);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: Failed to export plaintext to the output file.\n");
}
BSL_UIO_Free(shareFileUio);
}
} while (0);
pkeyUtlOpt->inRFile = NULL;
BSL_SAL_ClearFree(prv.data, prv.dataLen);
BSL_SAL_CleanseData(out, outLen);
CRYPT_EAL_PkeyFreeCtx(ctx);
CRYPT_EAL_PkeyFreeCtx(peerCtx);
return ret;
}
int32_t HITLS_PkeyUtlMain(int argc, char *argv[])
{
AppProvider appProvider = {NULL, NULL, NULL};
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param smParam = {NULL, 0, NULL, NULL, 0, HITLS_APP_SM_STATUS_OPEN};
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider, &smParam};
PkeyUtlOpt pkeyUtlOpt = {0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
"1234567812345678", &appProvider, &smParam};
#else
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider};
PkeyUtlOpt pkeyUtlOpt = {0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
"1234567812345678", &appProvider};
#endif
int32_t ret = HITLS_APP_SUCCESS;
do {
ret = HITLS_APP_OptBegin(argc, argv, g_pkeyUtlOpts);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkeyutl: error in opt begin.\n");
break;
}
ret = ParsepkeyUtlOpt(&pkeyUtlOpt);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = CheckParam(&pkeyUtlOpt);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = HITLS_APP_Init(&initParam);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("pkeyutl: Failed to init app, errCode: 0x%x.\n", ret);
break;
}
if (pkeyUtlOpt.optEncrypt) {
ret = PkeyEncrypt(&pkeyUtlOpt);
} else if (pkeyUtlOpt.optDecrypt) {
ret = PkeyDecrypt(&pkeyUtlOpt);
} else {
ret = PkeyDerive(&pkeyUtlOpt);
}
} while (false);
HITLS_APP_Deinit(&initParam, ret);
HITLS_APP_OptEnd();
return ret;
} | 2401_83913325/openHiTLS_1 | apps/src/app_pkeyutl.c | C | unknown | 39,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.
*/
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include "securec.h"
#include "bsl_uio.h"
#include "bsl_errno.h"
#include "bsl_sal.h"
#include "app_errno.h"
#define X509_PRINT_MAX_LAYER 10
#define X509_PRINT_LAYER_INDENT 4
#define X509_PRINT_MAX_INDENT (X509_PRINT_MAX_LAYER * X509_PRINT_LAYER_INDENT)
#define LOG_BUFFER_LEN 2048
static BSL_UIO *g_errorUIO = NULL;
int32_t AppUioVPrint(BSL_UIO *uio, const char *format, va_list args)
{
int32_t ret = 0;
if (uio == NULL) {
return HITLS_APP_INVALID_ARG;
}
uint32_t writeLen = 0;
char *buf = (char *)BSL_SAL_Calloc(LOG_BUFFER_LEN + 1, sizeof(char));
if (buf == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
ret = vsnprintf_s(buf, LOG_BUFFER_LEN + 1, LOG_BUFFER_LEN, format, args);
if (ret < EOK) {
BSL_SAL_FREE(buf);
return HITLS_APP_SECUREC_FAIL;
}
ret = BSL_UIO_Write(uio, buf, ret, &writeLen);
BSL_SAL_FREE(buf);
return ret;
}
int32_t AppPrint(BSL_UIO *uio, const char *format, ...)
{
if (uio == NULL) {
return HITLS_APP_INVALID_ARG;
}
va_list args;
va_start(args, format);
int32_t ret = AppUioVPrint(uio, format, args);
va_end(args);
return ret;
}
void AppPrintError(const char *format, ...)
{
if (g_errorUIO == NULL) {
return;
}
va_list args;
va_start(args, format);
(void)AppUioVPrint(g_errorUIO, format, args);
va_end(args);
return;
}
int32_t AppPrintErrorUioInit(FILE *fp)
{
if (fp == NULL) {
return HITLS_APP_INVALID_ARG;
}
if (g_errorUIO != NULL) {
return HITLS_APP_SUCCESS;
}
g_errorUIO = BSL_UIO_New(BSL_UIO_FileMethod());
if (g_errorUIO == NULL) {
return BSL_UIO_MEM_ALLOC_FAIL;
}
return BSL_UIO_Ctrl(g_errorUIO, BSL_UIO_FILE_PTR, 0, (void *)fp);
}
void AppPrintErrorUioUnInit(void)
{
if (g_errorUIO != NULL) {
BSL_UIO_Free(g_errorUIO);
g_errorUIO = NULL;
}
} | 2401_83913325/openHiTLS_1 | apps/src/app_print.c | C | unknown | 2,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.
*/
#ifdef HITLS_CRYPTO_PROVIDER
#include "app_provider.h"
#include <limits.h>
#include "string.h"
#include "securec.h"
#include "app_errno.h"
#include "app_print.h"
#include "bsl_sal.h"
#include "bsl_errno.h"
#include "crypt_errno.h"
#include "crypt_eal_provider.h"
static CRYPT_EAL_LibCtx *g_libCtx = NULL;
CRYPT_EAL_LibCtx *APP_GetCurrent_LibCtx(void)
{
return g_libCtx;
}
CRYPT_EAL_LibCtx *APP_Create_LibCtx(void)
{
if (g_libCtx == NULL) {
g_libCtx = CRYPT_EAL_LibCtxNew();
}
return g_libCtx;
}
int32_t HITLS_APP_LoadProvider(const char *searchPath, const char *providerName)
{
CRYPT_EAL_LibCtx *ctx = g_libCtx;
int32_t ret = HITLS_APP_SUCCESS;
if (ctx == NULL) {
(void)AppPrintError("Lib not initialized\n");
return HITLS_APP_INVALID_ARG;
}
if (searchPath != NULL) {
ret = CRYPT_EAL_ProviderSetLoadPath(ctx, searchPath);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("Load SetSearchPath failed. ERR:%d\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
}
if (providerName != NULL) {
ret = CRYPT_EAL_ProviderLoad(ctx, BSL_SAL_LIB_FMT_OFF, providerName, NULL, NULL);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("Load provider failed. ERR:%d\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
void HITLS_APP_FreeLibCtx(void)
{
if (g_libCtx != NULL) {
CRYPT_EAL_LibCtxFree(g_libCtx);
g_libCtx = NULL;
}
}
#endif // HITLS_CRYPTO_PROVIDER
| 2401_83913325/openHiTLS_1 | apps/src/app_provider.c | C | unknown | 2,107 |
/*
* 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 "app_rand.h"
#include <stddef.h>
#include <limits.h>
#include "securec.h"
#include "bsl_uio.h"
#include "crypt_eal_rand.h"
#include "bsl_base64.h"
#include "crypt_errno.h"
#include "bsl_errno.h"
#include "bsl_sal.h"
#include "app_opt.h"
#include "app_print.h"
#include "app_errno.h"
#include "app_function.h"
#include "app_provider.h"
#include "app_sm.h"
#include "app_list.h"
#include "app_utils.h"
#define MAX_RANDOM_LEN 4096
typedef enum OptionChoice {
HITLS_APP_OPT_RAND_ERR = -1,
HITLS_APP_OPT_RAND_EOF = 0,
HITLS_APP_OPT_RAND_NUMBITS = HITLS_APP_OPT_RAND_EOF,
HITLS_APP_OPT_RAND_HELP = 1, // The value of help type of each opt is 1. The following options can be customized.
HITLS_APP_OPT_RAND_HEX = 2,
HITLS_APP_OPT_RAND_BASE64,
HITLS_APP_OPT_RAND_OUT,
HITLS_APP_OPT_RAND_ALGORITHM,
HITLS_APP_PROV_ENUM,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS_ENUM,
#endif
} HITLSOptType;
typedef struct {
int32_t randNumLen;
char *outFile;
int32_t format;
int32_t algId;
AppProvider *provider;
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param *smParam;
#endif
} RandCmdOpt;
HITLS_CmdOption g_randOpts[] = {
{"help", HITLS_APP_OPT_RAND_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"hex", HITLS_APP_OPT_RAND_HEX, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Hex-encoded output"},
{"base64", HITLS_APP_OPT_RAND_BASE64, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Base64-encoded output"},
{"out", HITLS_APP_OPT_RAND_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"numbytes", HITLS_APP_OPT_RAND_NUMBITS, HITLS_APP_OPT_VALUETYPE_PARAMTERS, "Random byte length"},
{"algorithm", HITLS_APP_OPT_RAND_ALGORITHM, HITLS_APP_OPT_VALUETYPE_STRING, "Random algorithm"},
HITLS_APP_PROV_OPTIONS,
#ifdef HITLS_APP_SM_MODE
HITLS_SM_OPTIONS,
#endif
{NULL, 0, 0, NULL}};
static int32_t OptParse(RandCmdOpt *randCmdOpt);
static int32_t RandNumOut(RandCmdOpt *randCmdOpt);
static int32_t GetRandNumLen(int32_t *randNumLen)
{
int unParseParamNum = HITLS_APP_GetRestOptNum();
char** unParseParam = HITLS_APP_GetRestOpt();
if (unParseParamNum != 1) {
(void)AppPrintError("rand: Extra arguments given.\n");
return HITLS_APP_OPT_UNKOWN;
}
int32_t ret = HITLS_APP_OptGetInt(unParseParam[0], randNumLen);
if (ret != HITLS_APP_SUCCESS || *randNumLen <= 0) {
(void)AppPrintError("rand: Valid Range[1, 2147483647]\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_RandMain(int argc, char **argv)
{
int32_t mainRet = HITLS_APP_SUCCESS; // return value of the main function
AppProvider appProvider = {NULL, NULL, NULL};
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param smParam = {NULL, 0, NULL, NULL, 0, HITLS_APP_SM_STATUS_OPEN};
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider, &smParam};
RandCmdOpt randCmdOpt = {0, NULL, HITLS_APP_FORMAT_BINARY, CRYPT_RAND_SHA256, &appProvider, &smParam};
#else
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider};
RandCmdOpt randCmdOpt = {0, NULL, HITLS_APP_FORMAT_BINARY, CRYPT_RAND_SHA256, &appProvider};
#endif
mainRet = HITLS_APP_OptBegin(argc, argv, g_randOpts);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
mainRet = OptParse(&randCmdOpt);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
initParam.randAlgId = randCmdOpt.algId;
// GET the length of the random number to be generated.
mainRet = GetRandNumLen(&randCmdOpt.randNumLen);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
mainRet = HITLS_APP_Init(&initParam);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("rand: Failed to init, errCode: 0x%x.\n", mainRet);
goto end;
}
mainRet = RandNumOut(&randCmdOpt);
end:
HITLS_APP_Deinit(&initParam, mainRet);
HITLS_APP_OptEnd();
return mainRet;
}
static int32_t OptParse(RandCmdOpt *randCmdOpt)
{
HITLSOptType optType;
int ret = HITLS_APP_SUCCESS;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_RAND_EOF) {
switch (optType) {
case HITLS_APP_OPT_RAND_EOF:
case HITLS_APP_OPT_RAND_ERR:
ret = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("rand: Use -help for summary.\n");
return ret;
case HITLS_APP_OPT_RAND_HELP:
ret = HITLS_APP_HELP;
(void)HITLS_APP_OptHelpPrint(g_randOpts);
return ret;
case HITLS_APP_OPT_RAND_OUT:
randCmdOpt->outFile = HITLS_APP_OptGetValueStr();
if (randCmdOpt->outFile == NULL || strlen(randCmdOpt->outFile) >= PATH_MAX) {
AppPrintError("rand: The length of outfile error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_RAND_BASE64:
randCmdOpt->format = HITLS_APP_FORMAT_BASE64;
break;
case HITLS_APP_OPT_RAND_HEX:
randCmdOpt->format = HITLS_APP_FORMAT_HEX;
break;
case HITLS_APP_OPT_RAND_ALGORITHM:
randCmdOpt->algId = HITLS_APP_GetCidByName(HITLS_APP_OptGetValueStr(), HITLS_APP_LIST_OPT_RAND_ALG);
if (randCmdOpt->algId == BSL_CID_UNKNOWN) {
AppPrintError("rand: The algorithm is not supported.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
default:
break;
}
HITLS_APP_PROV_CASES(optType, randCmdOpt->provider);
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_CASES(optType, randCmdOpt->smParam);
#endif
}
#ifdef HITLS_APP_SM_MODE
if (randCmdOpt->smParam->smTag == 1 && randCmdOpt->smParam->workPath == NULL) {
AppPrintError("rand: The workpath is not specified.\n");
return HITLS_APP_INVALID_ARG;
}
#endif
return HITLS_APP_SUCCESS;
}
static int32_t RandNumOut(RandCmdOpt *randCmdOpt)
{
#ifdef HITLS_APP_SM_MODE
if (randCmdOpt->smParam->smTag == 1) {
randCmdOpt->smParam->status = HITLS_APP_SM_STATUS_APPORVED;
}
#endif
int ret = HITLS_APP_SUCCESS;
BSL_UIO *uio;
uio = HITLS_APP_UioOpen(randCmdOpt->outFile, 'w', 0);
if (uio == NULL) {
return HITLS_APP_UIO_FAIL;
}
if (randCmdOpt->outFile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(uio, true);
}
int32_t randNumLen = randCmdOpt->randNumLen;
uint8_t outBuf[MAX_RANDOM_LEN] = {0};
uint32_t outLen = 0;
while (randNumLen > 0) {
outLen = randNumLen > MAX_RANDOM_LEN ? MAX_RANDOM_LEN : randNumLen;
int32_t randRet = CRYPT_EAL_RandbytesEx(APP_GetCurrent_LibCtx(), outBuf, outLen);
if (randRet != CRYPT_SUCCESS) {
BSL_UIO_Free(uio);
BSL_SAL_CleanseData(outBuf, sizeof(outBuf));
(void)AppPrintError("rand: Failed to generate random number, randRet: 0x%x\n", randRet);
return HITLS_APP_CRYPTO_FAIL;
}
ret = HITLS_APP_OptWriteUio(uio, outBuf, outLen, randCmdOpt->format);
if (ret != HITLS_APP_SUCCESS) {
BSL_UIO_Free(uio);
BSL_SAL_CleanseData(outBuf, outLen);
return ret;
}
randNumLen -= outLen;
if (randCmdOpt->format != HITLS_APP_FORMAT_BINARY && randNumLen == 0) {
char buf[1] = {'\n'}; // Enter a newline character at the end.
uint32_t bufLen = 1;
uint32_t writeLen = 0;
ret = BSL_UIO_Write(uio, buf, bufLen, &writeLen);
if (ret != BSL_SUCCESS) {
BSL_UIO_Free(uio);
BSL_SAL_CleanseData(outBuf, outLen);
(void)AppPrintError("rand: Failed to enter the newline character, errCode: 0x%x.\n", ret);
return HITLS_APP_UIO_FAIL;
}
}
}
BSL_UIO_Free(uio);
BSL_SAL_CleanseData(outBuf, outLen);
return HITLS_APP_SUCCESS;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_rand.c | C | unknown | 8,625 |
/*
* 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 "app_req.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <securec.h>
#include <limits.h>
#include "app_errno.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_utils.h"
#include "bsl_sal.h"
#include "bsl_errno.h"
#include "crypt_errno.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_rand.h"
#include "hitls_pki_errno.h"
#define HITLS_APP_REQ_SECTION "req"
#define HITLS_APP_REQ_EXTENSION_SECTION "req_extensions"
typedef enum {
HITLS_REQ_APP_OPT_NEW = 2,
HITLS_REQ_APP_OPT_VERIFY,
HITLS_REQ_APP_OPT_MDALG,
HITLS_REQ_APP_OPT_SUBJ,
HITLS_REQ_APP_OPT_KEY,
HITLS_REQ_APP_OPT_KEYFORM,
HITLS_REQ_APP_OPT_PASSIN,
HITLS_REQ_APP_OPT_PASSOUT,
HITLS_REQ_APP_OPT_NOOUT,
HITLS_REQ_APP_OPT_TEXT,
HITLS_REQ_APP_OPT_CONFIG,
HITLS_REQ_APP_OPT_IN,
HITLS_REQ_APP_OPT_INFORM,
HITLS_REQ_APP_OPT_OUT,
HITLS_REQ_APP_OPT_OUTFORM,
} HITLSOptType;
const HITLS_CmdOption g_reqOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"new", HITLS_REQ_APP_OPT_NEW, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "New request"},
{"verify", HITLS_REQ_APP_OPT_VERIFY, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Verify self-signature on the request"},
{"mdalg", HITLS_REQ_APP_OPT_MDALG, HITLS_APP_OPT_VALUETYPE_STRING, "Any supported digest"},
{"subj", HITLS_REQ_APP_OPT_SUBJ, HITLS_APP_OPT_VALUETYPE_STRING, "Set or modify subject of request or cert"},
{"key", HITLS_REQ_APP_OPT_KEY, HITLS_APP_OPT_VALUETYPE_STRING, "Key for signing, and to include unless -in given"},
{"keyform", HITLS_REQ_APP_OPT_KEYFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Input format - DER or PEM"},
{"passin", HITLS_REQ_APP_OPT_PASSIN, HITLS_APP_OPT_VALUETYPE_STRING, "Private key and certificate password source"},
{"passout", HITLS_REQ_APP_OPT_PASSOUT, HITLS_APP_OPT_VALUETYPE_STRING, "Output file pass phrase source"},
{"noout", HITLS_REQ_APP_OPT_NOOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Do not output REQ"},
{"text", HITLS_REQ_APP_OPT_TEXT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Text form of request"},
{"config", HITLS_REQ_APP_OPT_CONFIG, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Request template file"},
{"in", HITLS_REQ_APP_OPT_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "X.509 request input file (default stdin)"},
{"inform", HITLS_REQ_APP_OPT_INFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Input format - DER or PEM"},
{"out", HITLS_REQ_APP_OPT_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"outform", HITLS_REQ_APP_OPT_OUTFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Output format - DER or PEM"},
{NULL, 0, 0, NULL},
};
typedef struct {
char *inFilePath;
BSL_ParseFormat inFormat;
bool verify;
} ReqGeneralOptions;
typedef struct {
bool new;
char *configFilePath;
bool text;
char *subj;
} ReqCertOptions;
typedef struct {
char *keyFilePath;
BSL_ParseFormat keyFormat;
char *passInArg;
char *passOutArg;
int32_t mdalgId;
} ReqKeysAndSignOptions;
typedef struct {
char *outFilePath;
BSL_ParseFormat outFormat;
bool noout;
} ReqOutputOptions;
typedef struct {
ReqGeneralOptions genOpt;
ReqCertOptions certOpt;
ReqKeysAndSignOptions keyAndSignOpt;
ReqOutputOptions outPutOpt;
char *passin;
char *passout;
HITLS_X509_Csr *csr;
CRYPT_EAL_PkeyCtx *pkey;
BSL_UIO *wUio;
BSL_Buffer encode;
HITLS_X509_Ext *ext;
BSL_CONF *conf;
} ReqOptCtx;
typedef int32_t (*ReqOptHandleFunc)(ReqOptCtx *);
typedef struct {
int optType;
ReqOptHandleFunc func;
} ReqOptHandleTable;
static int32_t ReqOptErr(ReqOptCtx *optCtx)
{
(void)optCtx;
AppPrintError("req: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t ReqOptHelp(ReqOptCtx *optCtx)
{
(void)optCtx;
HITLS_APP_OptHelpPrint(g_reqOpts);
return HITLS_APP_HELP;
}
static int32_t ReqOptNew(ReqOptCtx *optCtx)
{
optCtx->certOpt.new = true;
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptVerify(ReqOptCtx *optCtx)
{
optCtx->genOpt.verify = true;
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptMdAlg(ReqOptCtx *optCtx)
{
return HITLS_APP_GetAndCheckHashOpt(HITLS_APP_OptGetValueStr(), &optCtx->keyAndSignOpt.mdalgId);
}
static int32_t ReqOptSubj(ReqOptCtx *optCtx)
{
optCtx->certOpt.subj = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptKey(ReqOptCtx *optCtx)
{
optCtx->keyAndSignOpt.keyFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptKeyFormat(ReqOptCtx *optCtx)
{
return HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_ANY,
&optCtx->keyAndSignOpt.keyFormat);
}
static int32_t ReqOptPassin(ReqOptCtx *optCtx)
{
optCtx->keyAndSignOpt.passInArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptPassout(ReqOptCtx *optCtx)
{
optCtx->keyAndSignOpt.passOutArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptNoout(ReqOptCtx *optCtx)
{
optCtx->outPutOpt.noout = true;
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptText(ReqOptCtx *optCtx)
{
optCtx->certOpt.text = true;
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptConfig(ReqOptCtx *optCtx)
{
optCtx->certOpt.configFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptIn(ReqOptCtx *optCtx)
{
optCtx->genOpt.inFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptInFormat(ReqOptCtx *optCtx)
{
return HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_PEMDER,
&optCtx->genOpt.inFormat);
}
static int32_t ReqOptOut(ReqOptCtx *optCtx)
{
optCtx->outPutOpt.outFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptOutFormat(ReqOptCtx *optCtx)
{
return HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_PEMDER,
&optCtx->outPutOpt.outFormat);
}
static const ReqOptHandleTable g_reqOptHandleTable[] = {
{HITLS_APP_OPT_ERR, ReqOptErr},
{HITLS_APP_OPT_HELP, ReqOptHelp},
{HITLS_REQ_APP_OPT_NEW, ReqOptNew},
{HITLS_REQ_APP_OPT_VERIFY, ReqOptVerify},
{HITLS_REQ_APP_OPT_MDALG, ReqOptMdAlg},
{HITLS_REQ_APP_OPT_SUBJ, ReqOptSubj},
{HITLS_REQ_APP_OPT_KEY, ReqOptKey},
{HITLS_REQ_APP_OPT_KEYFORM, ReqOptKeyFormat},
{HITLS_REQ_APP_OPT_PASSIN, ReqOptPassin},
{HITLS_REQ_APP_OPT_PASSOUT, ReqOptPassout},
{HITLS_REQ_APP_OPT_NOOUT, ReqOptNoout},
{HITLS_REQ_APP_OPT_TEXT, ReqOptText},
{HITLS_REQ_APP_OPT_CONFIG, ReqOptConfig},
{HITLS_REQ_APP_OPT_IN, ReqOptIn},
{HITLS_REQ_APP_OPT_INFORM, ReqOptInFormat},
{HITLS_REQ_APP_OPT_OUT, ReqOptOut},
{HITLS_REQ_APP_OPT_OUTFORM, ReqOptOutFormat},
};
static int32_t ParseReqOpt(ReqOptCtx *optCtx)
{
int32_t ret = HITLS_APP_SUCCESS;
int optType = HITLS_APP_OPT_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF)) {
for (size_t i = 0; i < (sizeof(g_reqOptHandleTable) / sizeof(g_reqOptHandleTable[0])); ++i) {
if (optType == g_reqOptHandleTable[i].optType) {
ret = g_reqOptHandleTable[i].func(optCtx);
break;
}
}
}
// Obtain the number of parameters that cannot be parsed in the current version,
// and print the error inFormation and help list.
if ((ret == HITLS_APP_SUCCESS) && (HITLS_APP_GetRestOptNum() != 0)) {
AppPrintError("Extra arguments given.\n");
AppPrintError("req: Use -help for summary.\n");
ret = HITLS_APP_OPT_UNKOWN;
}
if ((HITLS_APP_ParsePasswd(optCtx->keyAndSignOpt.passInArg, &optCtx->passin) != HITLS_APP_SUCCESS) ||
(HITLS_APP_ParsePasswd(optCtx->keyAndSignOpt.passOutArg, &optCtx->passout) != HITLS_APP_SUCCESS)) {
return HITLS_APP_PASSWD_FAIL;
}
return ret;
}
static int32_t ReqLoadPrvKey(ReqOptCtx *optCtx)
{
if (optCtx->keyAndSignOpt.keyFilePath == NULL) {
optCtx->pkey = HITLS_APP_GenRsaPkeyCtx(2048); // default 2048
if (optCtx->pkey == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
// default write to private.pem
int32_t ret = HITLS_APP_PrintPrvKey(
optCtx->pkey, "private.pem", BSL_FORMAT_PEM, CRYPT_CIPHER_AES256_CBC, &optCtx->passout);
return ret;
}
optCtx->pkey =
HITLS_APP_LoadPrvKey(optCtx->keyAndSignOpt.keyFilePath, optCtx->keyAndSignOpt.keyFormat, &optCtx->passin);
if (optCtx->pkey == NULL) {
return HITLS_APP_LOAD_KEY_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetRequestedExt(ReqOptCtx *optCtx)
{
if (optCtx->ext == NULL) {
return HITLS_APP_SUCCESS;
}
BslList *attrList = NULL;
int32_t ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_CSR_GET_ATTRIBUTES, &attrList, sizeof(BslList *));
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to get attr the csr, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_Attrs *attrs = NULL;
ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_CSR_GET_ATTRIBUTES, &attrs, sizeof(HITLS_X509_Attrs *));
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to get attrs from the csr, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_AttrCtrl(attrs, HITLS_X509_ATTR_SET_REQUESTED_EXTENSIONS, optCtx->ext, 0);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to set attr the csr, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t GetSignMdId(ReqOptCtx *optCtx)
{
CRYPT_PKEY_AlgId id = CRYPT_EAL_PkeyGetId(optCtx->pkey);
int32_t mdalgId = optCtx->keyAndSignOpt.mdalgId;
if (mdalgId == CRYPT_MD_MAX) {
if (id == CRYPT_PKEY_ED25519) {
mdalgId = CRYPT_MD_SHA512;
} else if (id == CRYPT_PKEY_SM2) {
mdalgId = CRYPT_MD_SM3;
} else {
mdalgId = CRYPT_MD_SHA256;
}
}
return mdalgId;
}
static int32_t ProcSanExt(BslCid cid, void *val, void *ctx)
{
HITLS_X509_Ext *ext = ctx;
switch (cid) {
case BSL_CID_CE_SUBJECTALTNAME:
return HITLS_X509_ExtCtrl(ext, HITLS_X509_EXT_SET_SAN, val, sizeof(HITLS_X509_ExtSan));
default:
return HITLS_APP_CONF_FAIL;
}
}
static int32_t ParseConf(ReqOptCtx *optCtx)
{
if (!optCtx->certOpt.new || (optCtx->certOpt.configFilePath == NULL)) {
return HITLS_APP_SUCCESS;
}
optCtx->ext = HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CSR);
if (optCtx->ext == NULL) {
(void)AppPrintError("req: Failed to create the ext context.\n");
return HITLS_APP_X509_FAIL;
}
optCtx->conf = BSL_CONF_New(BSL_CONF_DefaultMethod());
if (optCtx->conf == NULL) {
(void)AppPrintError("req: Failed to create profile context.\n");
return HITLS_APP_CONF_FAIL;
}
char extSectionStr[BSL_CONF_SEC_SIZE + 1] = {0};
uint32_t extSectionStrLen = sizeof(extSectionStr);
int32_t ret = BSL_CONF_Load(optCtx->conf, optCtx->certOpt.configFilePath);
if (ret != BSL_SUCCESS) {
(void)AppPrintError("req: Failed to load the config file %s.\n", optCtx->certOpt.configFilePath);
return HITLS_APP_CONF_FAIL;
}
ret = BSL_CONF_GetString(optCtx->conf, HITLS_APP_REQ_SECTION, HITLS_APP_REQ_EXTENSION_SECTION,
extSectionStr, &extSectionStrLen);
if (ret == BSL_CONF_VALUE_NOT_FOUND) {
return HITLS_APP_SUCCESS;
} else if (ret != BSL_SUCCESS) {
(void)AppPrintError("req: Failed to get req_extensions, config file %s.\n", optCtx->certOpt.configFilePath);
return HITLS_APP_CONF_FAIL;
}
ret = HITLS_APP_CONF_ProcExt(optCtx->conf, extSectionStr, ProcSanExt, optCtx->ext);
if (ret == HITLS_APP_NO_EXT) {
return HITLS_APP_SUCCESS;
} else if (ret != BSL_SUCCESS) {
(void)AppPrintError("req: Failed to parse SAN from config file %s.\n", optCtx->certOpt.configFilePath);
return HITLS_APP_CONF_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t ReqGen(ReqOptCtx *optCtx)
{
if (optCtx->certOpt.subj == NULL) {
AppPrintError("req: -subj must be included when -new is used.\n");
return HITLS_APP_INVALID_ARG;
}
if (optCtx->genOpt.inFilePath != NULL) {
AppPrintError("req: ignore -in option when generating csr.\n");
}
int32_t ret = ReqLoadPrvKey(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
optCtx->csr = HITLS_X509_CsrNew();
if (optCtx->csr == NULL) {
(void)AppPrintError("req: Failed to create the csr context.\n");
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_SET_PUBKEY, optCtx->pkey, sizeof(CRYPT_EAL_PkeyCtx *));
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to set public the csr, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
if (ParseConf(optCtx) != HITLS_APP_SUCCESS) {
return HITLS_APP_CONF_FAIL;
}
ret = HITLS_APP_CFG_ProcDnName(optCtx->certOpt.subj, HiTLS_AddSubjDnNameToCsr, optCtx->csr);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to set subject name the csr, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = SetRequestedExt(optCtx);
if (ret != HITLS_PKI_SUCCESS) {
return ret;
}
ret = HITLS_X509_CsrSign(GetSignMdId(optCtx), optCtx->pkey, NULL, optCtx->csr);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to sign the csr, errCode = %x.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CsrGenBuff(optCtx->outPutOpt.outFormat, optCtx->csr, &optCtx->encode);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to generate the csr, errCode = %x.\n", ret);
}
return ret;
}
static int32_t ReqLoad(ReqOptCtx *optCtx)
{
optCtx->csr = HITLS_APP_LoadCsr(optCtx->genOpt.inFilePath, optCtx->genOpt.inFormat);
if (optCtx->csr == NULL) {
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static void ReqVerify(ReqOptCtx *optCtx)
{
int32_t ret = HITLS_X509_CsrVerify(optCtx->csr);
if (ret == HITLS_PKI_SUCCESS) {
(void)AppPrintError("req: verify ok.\n");
} else {
(void)AppPrintError("req: verify failure, errCode = %d.\n", ret);
}
}
static int32_t ReqOutput(ReqOptCtx *optCtx)
{
if (optCtx->outPutOpt.noout && !optCtx->certOpt.text) {
return HITLS_APP_SUCCESS;
}
optCtx->wUio = HITLS_APP_UioOpen(optCtx->outPutOpt.outFilePath, 'w', 0);
if (optCtx->wUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(optCtx->wUio, true);
int32_t ret;
if (optCtx->certOpt.text) {
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_CSR, optCtx->csr, sizeof(HITLS_X509_Csr *), optCtx->wUio);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("x509: print csr failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
if (optCtx->outPutOpt.noout) {
return HITLS_APP_SUCCESS;
}
if (optCtx->encode.data == NULL) {
ret = HITLS_X509_CsrGenBuff(optCtx->outPutOpt.outFormat, optCtx->csr, &optCtx->encode);
if (ret != 0) {
AppPrintError("x509: encode csr failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
uint32_t writeLen = 0;
ret = BSL_UIO_Write(optCtx->wUio, optCtx->encode.data, optCtx->encode.dataLen, &writeLen);
if (ret != 0 || writeLen != optCtx->encode.dataLen) {
AppPrintError("req: write csr failed, errCode = %d, writeLen = %u.\n", ret, writeLen);
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static void InitReqOptCtx(ReqOptCtx *optCtx)
{
optCtx->genOpt.inFormat = BSL_FORMAT_PEM;
optCtx->keyAndSignOpt.keyFormat = BSL_FORMAT_UNKNOWN;
optCtx->outPutOpt.outFormat = BSL_FORMAT_PEM;
}
static void UnInitReqOptCtx(ReqOptCtx *optCtx)
{
if (optCtx->passin != NULL) {
BSL_SAL_ClearFree(optCtx->passin, strlen(optCtx->passin));
}
if (optCtx->passout != NULL) {
BSL_SAL_ClearFree(optCtx->passout, strlen(optCtx->passout));
}
HITLS_X509_CsrFree(optCtx->csr);
CRYPT_EAL_PkeyFreeCtx(optCtx->pkey);
BSL_UIO_Free(optCtx->wUio);
BSL_SAL_FREE(optCtx->encode.data);
HITLS_X509_ExtFree(optCtx->ext);
BSL_CONF_Free(optCtx->conf);
}
// req main function
int32_t HITLS_ReqMain(int argc, char *argv[])
{
ReqOptCtx optCtx = {0};
InitReqOptCtx(&optCtx);
int32_t ret = HITLS_APP_SUCCESS;
do {
ret = HITLS_APP_OptBegin(argc, argv, g_reqOpts);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("req: error in opt begin.\n");
break;
}
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR,
"provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) {
AppPrintError("req: failed to init rand.\n");
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = ParseReqOpt(&optCtx);
if (ret != HITLS_APP_SUCCESS) {
break;
}
if (optCtx.certOpt.new) {
ret = ReqGen(&optCtx);
} else {
ret = ReqLoad(&optCtx);
}
if (ret != HITLS_APP_SUCCESS) {
break;
}
if (optCtx.genOpt.verify) {
ReqVerify(&optCtx);
}
ret = ReqOutput(&optCtx);
} while (false);
CRYPT_EAL_RandDeinitEx(NULL);
UnInitReqOptCtx(&optCtx);
HITLS_APP_OptEnd();
return ret;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_req.c | C | unknown | 18,482 |
/*
* 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 "app_rsa.h"
#include <stddef.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <limits.h>
#include "securec.h"
#include "bsl_uio.h"
#include "bsl_ui.h"
#include "app_errno.h"
#include "app_function.h"
#include "bsl_sal.h"
#include "app_utils.h"
#include "app_opt.h"
#include "app_utils.h"
#include "app_print.h"
#include "crypt_eal_codecs.h"
#include "crypt_codecskey.h"
#include "crypt_errno.h"
#define RSA_MIN_LEN 256
#define RSA_MAX_LEN 4096
#define DEFAULT_RSA_SIZE 512U
typedef enum OptionChoice {
HITLS_APP_OPT_RSA_ERR = -1,
HITLS_APP_OPT_RSA_ROF = 0,
HITLS_APP_OPT_RSA_HELP = 1, // first opt of each option is help = 1, following opt can be customized.
HITLS_APP_OPT_RSA_IN,
HITLS_APP_OPT_RSA_OUT,
HITLS_APP_OPT_RSA_NOOUT,
HITLS_APP_OPT_RSA_TEXT,
} HITLSOptType;
typedef struct {
int32_t outformat;
bool text;
bool noout;
char *outfile;
} OutputInfo;
HITLS_CmdOption g_rsaOpts[] = {
{"help", HITLS_APP_OPT_RSA_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"in", HITLS_APP_OPT_RSA_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file"},
{"out", HITLS_APP_OPT_RSA_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"noout", HITLS_APP_OPT_RSA_NOOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "No RSA output "},
{"text", HITLS_APP_OPT_RSA_TEXT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print RSA key in text"},
{NULL, 0, 0, NULL}};
static int32_t OutPemFormat(BSL_UIO *uio, void *encode)
{
BSL_Buffer *outBuf = encode; // Encode data into the PEM format.
(void)AppPrintError("writing RSA key\n");
int32_t writeRet = HITLS_APP_OptWriteUio(uio, outBuf->data, outBuf->dataLen, HITLS_APP_FORMAT_PEM);
if (writeRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("Failed to export data in PEM format\n");
}
return writeRet;
}
static int32_t BufWriteToUio(void *pkey, OutputInfo outInfo)
{
int32_t writeRet = HITLS_APP_SUCCESS;
BSL_UIO *uio = HITLS_APP_UioOpen(outInfo.outfile, 'w', 0); // Open the file and overwrite the file content.
if (uio == NULL) {
(void)AppPrintError("Failed to open the file <%s> \n", outInfo.outfile);
return HITLS_APP_UIO_FAIL;
}
if (outInfo.text == true) {
writeRet = CRYPT_EAL_PrintPrikey(0, pkey, uio);
if (writeRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("Failed to export data in text format to a file <%s> \n", outInfo.outfile);
goto end;
}
}
if (outInfo.noout != true) {
BSL_Buffer encodeBuffer = {0};
writeRet = CRYPT_EAL_EncodeBuffKey(pkey, NULL, BSL_FORMAT_PEM, CRYPT_PRIKEY_RSA, &encodeBuffer);
if (writeRet != CRYPT_SUCCESS) {
(void)AppPrintError("Failed to encode pem format data\n");
goto end;
}
writeRet = OutPemFormat(uio, &encodeBuffer);
BSL_SAL_FREE(encodeBuffer.data);
if (writeRet != CRYPT_SUCCESS) {
(void)AppPrintError("Failed to export data in pem format to a file <%s> \n", outInfo.outfile);
}
}
end:
BSL_UIO_SetIsUnderlyingClosedByUio(uio, true);
BSL_UIO_Free(uio);
return writeRet;
}
static int32_t GetRsaByStd(uint8_t **readBuf, uint64_t *readBufLen)
{
(void)AppPrintError("Please enter the key content\n");
size_t rsaDataCapacity = DEFAULT_RSA_SIZE;
void *rsaData = BSL_SAL_Calloc(rsaDataCapacity, sizeof(uint8_t));
if (rsaData == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
size_t rsaDataSize = 0;
bool isMatchRsaData = false;
uint32_t i = 0;
char *header[] = {"-----BEGIN RSA PRIVATE KEY-----\n",
"-----BEGIN PRIVATE KEY-----\n", "-----BEGIN ENCRYPTED PRIVATE KEY-----\n"};
char *tail[] = {"-----END RSA PRIVATE KEY-----\n",
"-----END PRIVATE KEY-----\n", "-----END ENCRYPTED PRIVATE KEY-----\n"};
uint32_t num = (uint32_t)sizeof(header) / sizeof(header[0]);
while (true) {
char *buf = NULL;
size_t bufLen = 0;
ssize_t readLen = getline(&buf, &bufLen, stdin);
if (readLen <= 0) {
BSL_SAL_FREE(buf);
(void)AppPrintError("Failed to obtain the standard input.\n");
break;
}
if ((rsaDataSize + readLen) > rsaDataCapacity) {
// If the space is insufficient, expand the capacity by twice.
size_t newRsaDataCapacity = rsaDataCapacity << 1;
/* If the space is insufficient for two times of capacity expansion,
expand the capacity based on the actual length. */
if ((rsaDataSize + readLen) > newRsaDataCapacity) {
newRsaDataCapacity = rsaDataSize + readLen;
}
rsaData = ExpandingMem(rsaData, newRsaDataCapacity, rsaDataCapacity);
rsaDataCapacity = newRsaDataCapacity;
}
if (memcpy_s(rsaData + rsaDataSize, rsaDataCapacity - rsaDataSize, buf, readLen) != 0) {
BSL_SAL_FREE(buf);
BSL_SAL_FREE(rsaData);
return HITLS_APP_SECUREC_FAIL;
}
rsaDataSize += readLen;
i *= (uint32_t)isMatchRsaData; // reset 0 if false.
while (!isMatchRsaData && (i < num)) {
if (strcmp(buf, header[i]) == 0) {
isMatchRsaData = true;
break;
}
i++;
}
if (isMatchRsaData && (strcmp(buf, tail[i]) == 0)) {
BSL_SAL_FREE(buf);
break;
}
BSL_SAL_FREE(buf);
}
*readBuf = rsaData;
*readBufLen = rsaDataSize;
return (rsaDataSize > 0) ? HITLS_APP_SUCCESS : HITLS_APP_STDIN_FAIL;
}
static int32_t UioReadToBuf(uint8_t **readBuf, uint64_t *readBufLen, const char *infile, int32_t flag)
{
int32_t readRet = HITLS_APP_SUCCESS;
if (infile == NULL) {
readRet = GetRsaByStd(readBuf, readBufLen);
} else {
BSL_UIO *uio = HITLS_APP_UioOpen(infile, 'r', flag);
if (uio == NULL) {
AppPrintError("Failed to open the file <%s>, No such file or directory\n", infile);
return HITLS_APP_UIO_FAIL;
}
readRet = HITLS_APP_OptReadUio(uio, readBuf, readBufLen, RSA_MAX_LEN);
BSL_UIO_SetIsUnderlyingClosedByUio(uio, true);
BSL_UIO_Free(uio);
if (readRet != HITLS_APP_SUCCESS) {
AppPrintError("Failed to read the file: <%s>\n", infile);
}
}
return readRet;
}
static int32_t OptParse(char **infile, OutputInfo *outInfo)
{
HITLSOptType optType;
int ret = HITLS_APP_SUCCESS;
outInfo->outformat = HITLS_APP_FORMAT_PEM;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_RSA_ROF) {
switch (optType) {
case HITLS_APP_OPT_RSA_ROF:
case HITLS_APP_OPT_RSA_ERR:
ret = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("rsa: Use -help for summary.\n");
return ret;
case HITLS_APP_OPT_RSA_HELP:
ret = HITLS_APP_HELP;
(void)HITLS_APP_OptHelpPrint(g_rsaOpts);
return ret;
case HITLS_APP_OPT_RSA_IN:
*infile = HITLS_APP_OptGetValueStr();
if (*infile == NULL || strlen(*infile) >= PATH_MAX) {
AppPrintError("The length of infile error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_RSA_OUT:
outInfo->outfile = HITLS_APP_OptGetValueStr();
if (outInfo->outfile == NULL || strlen(outInfo->outfile) >= PATH_MAX) {
AppPrintError("The length of out file error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_RSA_NOOUT:
outInfo->noout = true;
break;
case HITLS_APP_OPT_RSA_TEXT:
outInfo->text = true;
break;
default:
ret = HITLS_APP_OPT_UNKOWN;
return ret;
}
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_RsaMain(int argc, char *argv[])
{
char *infile = NULL;
uint64_t readBufLen = 0;
uint8_t *readBuf = NULL;
int32_t mainRet = HITLS_APP_SUCCESS;
OutputInfo outInfo = {HITLS_APP_FORMAT_PEM, false, false, NULL};
CRYPT_EAL_PkeyCtx *ealPKey = NULL;
mainRet = HITLS_APP_OptBegin(argc, argv, g_rsaOpts);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
mainRet = OptParse(&infile, &outInfo);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
int unParseParamNum = HITLS_APP_GetRestOptNum();
if (unParseParamNum != 0) { // The input parameters are not completely parsed.
(void)AppPrintError("Extra arguments given.\n");
(void)AppPrintError("rsa: Use -help for summary.\n");
mainRet = HITLS_APP_OPT_UNKOWN;
goto end;
}
mainRet = UioReadToBuf(
&readBuf, &readBufLen, infile, 0); // Read the content of the input file from the file to the buffer.
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
BSL_Buffer read = {readBuf, readBufLen};
mainRet = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, CRYPT_PRIKEY_RSA, &read, NULL, 0, &ealPKey);
if (mainRet == BSL_PEM_SYMBOL_NOT_FOUND) {
mainRet = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, CRYPT_PRIKEY_PKCS8_UNENCRYPT, &read, NULL, 0, &ealPKey);
}
if (mainRet == BSL_PEM_SYMBOL_NOT_FOUND || mainRet == BSL_PEM_NO_PWD) {
char pwd[APP_MAX_PASS_LENGTH + 1] = {0};
int32_t pwdLen = HITLS_APP_Passwd(pwd, APP_MAX_PASS_LENGTH + 1, 0, NULL);
if (pwdLen == -1) {
mainRet = HITLS_APP_PASSWD_FAIL;
goto end;
}
if (mainRet == BSL_PEM_SYMBOL_NOT_FOUND) {
mainRet = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, CRYPT_PRIKEY_PKCS8_ENCRYPT,
&read, (uint8_t *)pwd, pwdLen, &ealPKey);
} else {
mainRet = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, CRYPT_PRIKEY_RSA,
&read, (uint8_t *)pwd, pwdLen, &ealPKey);
}
(void)memset_s(pwd, APP_MAX_PASS_LENGTH, 0, APP_MAX_PASS_LENGTH);
}
if (mainRet != CRYPT_SUCCESS) {
(void)AppPrintError("Decode failed.\n");
mainRet = HITLS_APP_DECODE_FAIL;
goto end;
}
mainRet = BufWriteToUio(ealPKey, outInfo); // Selective output based on command line parameters.
end:
CRYPT_EAL_PkeyFreeCtx(ealPKey);
BSL_SAL_FREE(readBuf);
HITLS_APP_OptEnd();
return mainRet;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_rsa.c | C | unknown | 11,205 |
/*
* 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 "app_server.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include "securec.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_provider.h"
#include "app_sm.h"
#include "app_keymgmt.h"
#include "app_utils.h"
#include "app_tls_common.h"
#include "hitls.h"
#include "hitls_cert_init.h"
#include "hitls_crypt_init.h"
#include "hitls_session.h"
#include "crypt_errno.h"
#include "bsl_uio.h"
#include "crypt_eal_init.h"
#include "crypt_eal_rand.h"
#include "bsl_sal.h"
#include "bsl_err.h"
#include "bsl_log.h"
#define HTTP_BUF_MAXLEN (18 * 1024) /* 18KB */
#define DEFAULT_DTLCP_TIMEOUT 5
static volatile bool g_loopFlag = true;
static int ServerMainLoop(HITLS_Config *config, int listenFd, HITLS_ServerParams *params);
/* Thread server parameters structure */
typedef struct {
HITLS_Config *config;
int listenFd;
HITLS_ServerParams *params;
int ret;
} ThreadServerArgs;
static void *ThreadServerMainLoop(void *arg)
{
ThreadServerArgs *threadArgs = (ThreadServerArgs *)arg;
threadArgs->ret = ServerMainLoop(threadArgs->config, threadArgs->listenFd, threadArgs->params);
g_loopFlag = false;
return NULL;
}
#ifdef HITLS_APP_SM_MODE
static int32_t HeartBeatLoop(HITLS_Config *config, int listenFd, HITLS_ServerParams *params);
static void *ThreadHeartBeatLoop(void *arg)
{
ThreadServerArgs *threadArgs = (ThreadServerArgs *)arg;
threadArgs->ret = HeartBeatLoop(threadArgs->config, threadArgs->listenFd, threadArgs->params);
return NULL;
}
#endif
/* Server option types */
typedef enum {
HITLS_SERVER_OPT_ACCEPT = 2,
HITLS_SERVER_OPT_PORT,
/* Protocol options */
HITLS_SERVER_OPT_TLS,
HITLS_SERVER_OPT_TLCP,
HITLS_SERVER_OPT_DTLCP,
HITLS_SERVER_OPT_CIPHER,
/* Certificate options */
HITLS_SERVER_OPT_CAFILE,
HITLS_SERVER_OPT_CHAINCAFILE,
/* TLCP options */
HITLS_SERVER_OPT_TLCP_ENC_CERT,
HITLS_SERVER_OPT_TLCP_ENC_KEY,
HITLS_SERVER_OPT_TLCP_SIGN_CERT,
HITLS_SERVER_OPT_TLCP_SIGN_KEY,
/* Service options */
HITLS_SERVER_OPT_ACCEPT_ONCE,
/* Output options */
HITLS_SERVER_OPT_QUIET,
HITLS_SERVER_OPT_STATE,
/* Format options */
HITLS_SERVER_OPT_CERTFORM,
HITLS_SERVER_OPT_KEYFORM,
HITLS_APP_PROV_ENUM,
#ifdef HITLS_APP_SM_MODE
/* SM mode options */
HITLS_SM_OPTIONS_ENUM,
#endif
HITLS_SERVER_OPT_MAX,
} HITLS_ServerOptType;
/* Command line options for s_server */
static const HITLS_CmdOption g_serverOptions[] = {
/* Listen options */
{"accept", HITLS_SERVER_OPT_ACCEPT, HITLS_APP_OPT_VALUETYPE_STRING, "Listen on host:port"},
{"port", HITLS_SERVER_OPT_PORT, HITLS_APP_OPT_VALUETYPE_UINT, "Listen port (default 4433)"},
/* Protocol options */
{"tls", HITLS_SERVER_OPT_TLS, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Use TLS protocol (default)"},
{"tlcp", HITLS_SERVER_OPT_TLCP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Use TLCP protocol"},
{"dtlcp", HITLS_SERVER_OPT_DTLCP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Use DTLCP protocol"},
{"cipher", HITLS_SERVER_OPT_CIPHER, HITLS_APP_OPT_VALUETYPE_STRING, "Specify cipher suites"},
/* Certificate options */
{"CAfile", HITLS_SERVER_OPT_CAFILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "CA certificate file"},
{"chainCAfile", HITLS_SERVER_OPT_CHAINCAFILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "CA file for certificate chain"},
/* TLCP options */
{"tlcp_enc_cert", HITLS_SERVER_OPT_TLCP_ENC_CERT, HITLS_APP_OPT_VALUETYPE_IN_FILE, "TLCP encryption certificate"},
{"tlcp_enc_key", HITLS_SERVER_OPT_TLCP_ENC_KEY, HITLS_APP_OPT_VALUETYPE_IN_FILE, "TLCP encryption private key"},
{"tlcp_sign_cert", HITLS_SERVER_OPT_TLCP_SIGN_CERT, HITLS_APP_OPT_VALUETYPE_IN_FILE, "TLCP signature certificate"},
{"tlcp_sign_key", HITLS_SERVER_OPT_TLCP_SIGN_KEY, HITLS_APP_OPT_VALUETYPE_IN_FILE, "TLCP signature private key"},
/* Service options */
{"accept_once", HITLS_SERVER_OPT_ACCEPT_ONCE, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Accept only one connection"},
/* Output options */
{"quiet", HITLS_SERVER_OPT_QUIET, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Quiet mode"},
{"state", HITLS_SERVER_OPT_STATE, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Show handshake state"},
/* Format options */
{"certform", HITLS_SERVER_OPT_CERTFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Certificate format (PEM|DER)"},
{"keyform", HITLS_SERVER_OPT_KEYFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Private key format (PEM|DER)"},
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Show help"},
HITLS_APP_PROV_OPTIONS,
#ifdef HITLS_APP_SM_MODE
/* SM mode options */
HITLS_SM_OPTIONS,
#endif
{NULL, 0, 0, NULL}
};
typedef int (*ServerOptHandleFunc)(HITLS_ServerParams *);
typedef struct {
int optType;
ServerOptHandleFunc func;
} ServerOptHandleFuncMap;
static void InitServerParams(HITLS_ServerParams *params, AppProvider *provider)
{
if (params == NULL || provider == NULL) {
return;
}
/* Set default values */
params->port = 4433;
params->backlog = 5;
params->protocol = NULL;
params->verifyDepth = 9;
params->certFormat = BSL_FORMAT_PEM;
params->keyFormat = BSL_FORMAT_PEM;
params->maxConnections = 0; /* No limit */
params->provider = provider;
params->verifyClient = true;
}
static int HandleServerAccept(HITLS_ServerParams *params)
{
APP_NetworkAddr addr = {0};
if (ParseConnectString(HITLS_APP_OptGetValueStr(), &addr) == HITLS_APP_SUCCESS) {
params->bindAddr = addr.host;
params->port = addr.port;
}
return HITLS_APP_SUCCESS;
}
static int HandleServerPort(HITLS_ServerParams *params)
{
HITLS_APP_OptGetUint32(HITLS_APP_OptGetValueStr(), (uint32_t*)¶ms->port);
return HITLS_APP_SUCCESS;
}
static int HandleServerTLS(HITLS_ServerParams *params)
{
params->protocol = "tls";
return HITLS_APP_SUCCESS;
}
static int HandleServerTLCP(HITLS_ServerParams *params)
{
params->protocol = "tlcp";
return HITLS_APP_SUCCESS;
}
static int HandleServerDTLCP(HITLS_ServerParams *params)
{
params->protocol = "dtlcp";
return HITLS_APP_SUCCESS;
}
static int HandleServerCipher(HITLS_ServerParams *params)
{
params->cipherSuites = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleServerCAFile(HITLS_ServerParams *params)
{
params->caFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleServerChainCAFile(HITLS_ServerParams *params)
{
params->caChain = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleServerTLCPEncCert(HITLS_ServerParams *params)
{
params->tlcpEncCert = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleServerTLCPEncKey(HITLS_ServerParams *params)
{
params->tlcpEncKey = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleServerTLCPSignCert(HITLS_ServerParams *params)
{
params->tlcpSignCert = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleServerTLCPSignKey(HITLS_ServerParams *params)
{
params->tlcpSignKey = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int HandleServerAcceptOnce(HITLS_ServerParams *params)
{
params->acceptOnce = true;
return HITLS_APP_SUCCESS;
}
static int HandleServerQuiet(HITLS_ServerParams *params)
{
params->quiet = true;
return HITLS_APP_SUCCESS;
}
static int HandleServerState(HITLS_ServerParams *params)
{
params->state = true;
return HITLS_APP_SUCCESS;
}
static int HandleServerCertForm(HITLS_ServerParams *params)
{
HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, ¶ms->certFormat);
return HITLS_APP_SUCCESS;
}
static int HandleServerKeyForm(HITLS_ServerParams *params)
{
HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, ¶ms->keyFormat);
return HITLS_APP_SUCCESS;
}
static int HandleServerHelp(HITLS_ServerParams *params)
{
(void)params;
HITLS_APP_OptHelpPrint(g_serverOptions);
return HITLS_APP_HELP;
}
// 映射表
static const ServerOptHandleFuncMap g_serverOptHandleFuncMap[] = {
{HITLS_SERVER_OPT_ACCEPT, HandleServerAccept},
{HITLS_SERVER_OPT_PORT, HandleServerPort},
{HITLS_SERVER_OPT_TLS, HandleServerTLS},
{HITLS_SERVER_OPT_TLCP, HandleServerTLCP},
{HITLS_SERVER_OPT_DTLCP, HandleServerDTLCP},
{HITLS_SERVER_OPT_CIPHER, HandleServerCipher},
{HITLS_SERVER_OPT_CAFILE, HandleServerCAFile},
{HITLS_SERVER_OPT_CHAINCAFILE, HandleServerChainCAFile},
{HITLS_SERVER_OPT_TLCP_ENC_CERT, HandleServerTLCPEncCert},
{HITLS_SERVER_OPT_TLCP_ENC_KEY, HandleServerTLCPEncKey},
{HITLS_SERVER_OPT_TLCP_SIGN_CERT, HandleServerTLCPSignCert},
{HITLS_SERVER_OPT_TLCP_SIGN_KEY, HandleServerTLCPSignKey},
{HITLS_SERVER_OPT_ACCEPT_ONCE, HandleServerAcceptOnce},
{HITLS_SERVER_OPT_QUIET, HandleServerQuiet},
{HITLS_SERVER_OPT_STATE, HandleServerState},
{HITLS_SERVER_OPT_CERTFORM, HandleServerCertForm},
{HITLS_SERVER_OPT_KEYFORM, HandleServerKeyForm},
{HITLS_APP_OPT_HELP, HandleServerHelp},
};
static int ParseServerOptLoop(HITLS_ServerParams *params)
{
int ret = HITLS_APP_SUCCESS;
int optType = HITLS_APP_OPT_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF)) {
for (size_t i = 0; i < sizeof(g_serverOptHandleFuncMap)/sizeof(g_serverOptHandleFuncMap[0]); ++i) {
if (optType == g_serverOptHandleFuncMap[i].optType) {
ret = g_serverOptHandleFuncMap[i].func(params);
break;
}
}
HITLS_APP_PROV_CASES(optType, params->provider)
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_CASES(optType, params->smParam);
#endif
}
if (HITLS_APP_GetRestOptNum() != 0) {
AppPrintError("Extra arguments given.\n");
AppPrintError("pkeyutl: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return ret;
}
static int32_t CheckSmParam(HITLS_ServerParams *params)
{
#ifdef HITLS_APP_SM_MODE
if (params->smParam->smTag == 1 && params->smParam->workPath == NULL) {
AppPrintError("server: The workpath is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
#else
(void) params;
#endif
return HITLS_APP_SUCCESS;
}
static int ParseServerOptions(int argc, char *argv[], HITLS_ServerParams *params, AppProvider *provider)
{
int ret = HITLS_APP_SUCCESS;
if (params == NULL || provider == NULL) {
return HITLS_APP_INVALID_ARG;
}
InitServerParams(params, provider);
int opt = HITLS_APP_OptBegin(argc, argv, g_serverOptions);
if (opt != HITLS_APP_SUCCESS) {
AppPrintError("Failed to initialize option parser\n");
return opt;
}
ret = ParseServerOptLoop(params);
if (ret != HITLS_APP_SUCCESS) {
if (ret != HITLS_APP_HELP) {
AppPrintError("Failed to parse server options: 0x%x\n", ret);
}
return ret;
}
HITLS_APP_OptEnd();
ret = CheckSmParam(params);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return HITLS_APP_SUCCESS;
}
static HITLS_Config *CreateServerConfig(HITLS_ServerParams *params)
{
if (params == NULL) {
return NULL;
}
/* Determine protocol type */
APP_ProtocolType protocol = ParseProtocolType(params->protocol);
/* Create base configuration */
HITLS_Config *config = CreateProtocolConfig(protocol, params->provider);
if (config == NULL) {
return NULL;
}
int ret = HITLS_SUCCESS;
/* Configure cipher suites */
if (params->cipherSuites) {
ret = ConfigureCipherSuites(config, params->cipherSuites, protocol);
if (ret != HITLS_APP_SUCCESS) {
HITLS_CFG_FreeConfig(config);
return NULL;
}
}
/* Configure certificate verification */
APP_CertConfig certConfig = {
.caFile = params->caFile,
.caChain = params->caChain,
.certFormat = params->certFormat,
.keyFormat = params->keyFormat,
.tlcpEncCert = params->tlcpEncCert,
.tlcpEncKey = params->tlcpEncKey,
.tlcpSignCert = params->tlcpSignCert,
.tlcpSignKey = params->tlcpSignKey,
.provider = params->provider,
#ifdef HITLS_APP_SM_MODE
.smParam = params->smParam,
#endif
};
ret = ConfCertVerification(config, &certConfig, params->verifyClient, params->verifyDepth);
if (ret != HITLS_APP_SUCCESS) {
HITLS_CFG_FreeConfig(config);
return NULL;
}
ret = ConfigureTLCPCertificates(config, &certConfig);
if (ret != HITLS_APP_SUCCESS) {
HITLS_CFG_FreeConfig(config);
return NULL;
}
return config;
}
static int CreateListenSocket(HITLS_ServerParams *params)
{
if (params == NULL) {
return -1;
}
APP_NetworkAddr addr = {
.host = params->bindAddr,
.port = params->port,
};
int listenFd = -1;
/* Create listen socket based on protocol */
APP_ProtocolType protocol = ParseProtocolType(params->protocol);
if (protocol == APP_PROTOCOL_DTLCP) {
listenFd = CreateUDPListenSocket(&addr, DEFAULT_DTLCP_TIMEOUT);
} else {
listenFd = CreateTCPListenSocket(&addr, params->backlog);
}
if (listenFd < 0) {
return -1;
}
if (!params->quiet) {
AppPrintInfo("Listening on %s:%d (%s)\n", addr.host ? addr.host : "0.0.0.0", params->port,
protocol == APP_PROTOCOL_DTLCP ? "UDP" : "TCP");
}
return listenFd;
}
static BSL_UIO *CreateServerUIO(int clientFd, HITLS_ServerParams *params)
{
BSL_UIO *uio = NULL;
APP_ProtocolType protocol = ParseProtocolType(params->protocol);
if (protocol == APP_PROTOCOL_DTLCP) {
uio = BSL_UIO_New(BSL_UIO_UdpMethod());
} else {
uio = BSL_UIO_New(BSL_UIO_TcpMethod());
}
int ret = BSL_UIO_Ctrl(uio, BSL_UIO_SET_FD, sizeof(clientFd), &clientFd);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to set socket to UIO: 0x%x\n", ret);
BSL_UIO_Free(uio);
return NULL;
}
return uio;
}
#ifdef HITLS_APP_SM_MODE
static int32_t ReceiveKeyCallback(void *ctx, void *buf, uint32_t len)
{
uint32_t readLen = 0;
int32_t ret = HITLS_Read(ctx, buf, len, &readLen);
if (ret != HITLS_SUCCESS) {
return ret;
}
if (readLen != len) {
return HITLS_APP_ERR_SEND_DATA;
}
return HITLS_APP_SUCCESS;
}
static int32_t HandleSm(HITLS_Ctx *ctx, HITLS_ServerParams *params)
{
int32_t ret = HITLS_APP_ReceiveKey(params->provider, params->smParam, -1, -1, ReceiveKeyCallback, ctx);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("server: Failed to receive key: 0x%x\n", ret);
return ret;
}
AppPrintError("server: Received key from client successfully!\n");
/* Send response */
const char *response = "Received key successfully!";
uint32_t written = 0;
ret = HITLS_Write(ctx, (const uint8_t *)response, strlen(response), &written);
if (ret == HITLS_SUCCESS) {
if (!params->quiet) {
AppPrintError("server: Sent %u bytes response to client\n", written);
}
} else {
AppPrintError("server: Failed to send response: 0x%x\n", ret);
}
return HITLS_APP_SUCCESS;
}
#endif
static int HandleClientConnection(HITLS_Ctx *ctx, HITLS_ServerParams *params)
{
if (ctx == NULL || params == NULL) {
return HITLS_APP_INVALID_ARG;
}
int ret = HITLS_APP_SUCCESS;
if (!params->quiet) {
AppPrintInfo("Starting TLS handshake with client...\n");
}
/* Perform handshake */
do {
if (!g_loopFlag) {
return HITLS_APP_SUCCESS;
}
ret = HITLS_Accept(ctx);
if (ret == HITLS_SUCCESS) {
break;
}
if (ret != HITLS_REC_NORMAL_RECV_BUF_EMPTY && ret != HITLS_REC_NORMAL_IO_BUSY) {
AppPrintInfo("TLS handshake failed: 0x%x\n", ret);
return HITLS_APP_ERR_HANDSHAKE;
}
/* Non-blocking I/O, retry */
usleep(10000); /* Sleep 10000us. */
} while (ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY || ret == HITLS_REC_NORMAL_IO_BUSY);
if (!params->quiet) {
AppPrintInfo("TLS handshake completed successfully\n");
/* Print connection information */
PrintConnectionInfo(ctx, params->state);
}
#ifdef HITLS_APP_SM_MODE
if (params->smParam->smTag == 1) {
return HandleSm(ctx, params);
}
#endif
/* Handle data exchange */
uint8_t buffer[HTTP_BUF_MAXLEN];
uint32_t read_len = 0;
/* Read client data */
ret = HITLS_Read(ctx, buffer, sizeof(buffer) - 1, &read_len);
if (ret == HITLS_SUCCESS && read_len > 0) {
buffer[read_len] = '\0';
if (!params->quiet) {
AppPrintInfo("Received %u bytes from client:\n%s\n", read_len, buffer);
}
/* Send response */
const char *response = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World!";
uint32_t written = 0;
ret = HITLS_Write(ctx, (const uint8_t *)response, strlen(response), &written);
if (ret == HITLS_SUCCESS) {
if (!params->quiet) {
AppPrintInfo("Sent %u bytes response to client\n", written);
}
} else {
AppPrintError("Failed to send response: 0x%x\n", ret);
}
} else if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to read client data: 0x%x\n", ret);
}
return HITLS_APP_SUCCESS;
}
static void CleanupConnection(HITLS_Ctx *ctx, BSL_UIO *uio, int clientFd)
{
if (ctx) {
HITLS_Close(ctx); // send close
HITLS_Close(ctx); // read close
HITLS_Free(ctx);
}
if (uio) {
BSL_UIO_Free(uio);
}
if (clientFd >= 0) {
BSL_SAL_SockClose(clientFd);
}
}
static int ServerMainLoop(HITLS_Config *config, int listenFd, HITLS_ServerParams *params)
{
if (config == NULL || listenFd < 0 || params == NULL) {
return HITLS_APP_INVALID_ARG;
}
int connections = 0;
APP_ProtocolType protocol = ParseProtocolType(params->protocol);
if (!params->quiet) {
AppPrintInfo("Server started, waiting for connections...\n");
}
while (g_loopFlag) {
int clientFd = -1;
BSL_UIO *uio = NULL;
HITLS_Ctx *ctx = NULL;
if (protocol == APP_PROTOCOL_DTLCP) {
/* For DTLS, we use the same socket for communication */
clientFd = listenFd;
} else {
clientFd = AcceptTCPConnection(listenFd);
if (clientFd < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
usleep(10000); /* Sleep 10000us. */
continue;
}
if (clientFd < 0) {
AppPrintError("Failed to accept connection: %s\n", strerror(errno));
break;
}
}
/* Create UIO and TLS context */
uio = CreateServerUIO(clientFd, params);
ctx = HITLS_New(config);
if (uio == NULL || ctx == NULL) {
AppPrintError("Failed to create UIO or TLS context\n");
CleanupConnection(ctx, uio, (protocol != APP_PROTOCOL_DTLCP) ? clientFd : -1);
continue;
}
int ret = HITLS_SetUio(ctx, uio);
if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to set UIO: 0x%x\n", ret);
CleanupConnection(ctx, uio, (protocol != APP_PROTOCOL_DTLCP) ? clientFd : -1);
continue;
}
/* Handle client connection */
ret = HandleClientConnection(ctx, params);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to handle client connection\n");
}
CleanupConnection(ctx, uio, (protocol != APP_PROTOCOL_DTLCP) ? clientFd : -1);
connections++;
if (!params->quiet) {
AppPrintInfo("Connection %d completed\n", connections);
}
/* Check if we should exit */
if (params->acceptOnce ||
(params->maxConnections > 0 && connections >= params->maxConnections)) {
if (!params->quiet) {
AppPrintInfo("Reached connection limit, exiting\n");
}
break;
}
}
return HITLS_APP_SUCCESS;
}
static void CleanupServerResources(HITLS_Config *config, int listenFd)
{
if (config) {
HITLS_CFG_FreeConfig(config);
}
if (listenFd >= 0) {
BSL_SAL_SockClose(listenFd);
}
}
static void SignalHandler(int sig)
{
(void)sig;
g_loopFlag = false;
}
#ifdef HITLS_APP_SM_MODE
static void *ThreadPeriodicTask(void *arg)
{
int i = 0;
int seconds = 0;
struct timeval delay;
AppProvider *provider = (AppProvider *)arg;
if (provider == NULL) {
return NULL;
}
while (g_loopFlag) {
if (seconds == 0) {
(void)HITLS_APP_SM_PeriodicRandomCheck(provider);
}
for (i = 0; i < 1000; i++) { /* Sleep 1000 times, total 1s. */
if (!g_loopFlag) {
return NULL;
}
delay.tv_sec = 0;
delay.tv_usec = 1000; /* Sleep 1000us. */
select(0, NULL, NULL, NULL, &delay);
}
seconds++;
if (seconds == 86400) { /* 86400: 24 hours */
seconds = 0;
}
}
return NULL;
}
#endif
static int32_t CreateConfigAndListenSocket(HITLS_ServerParams *params, HITLS_Config **config, int *listenFd)
{
/* Create TLS configuration */
HITLS_Config *configTmp = CreateServerConfig(params);
if (configTmp == NULL) {
AppPrintError("Failed to create TLS configuration\n");
return HITLS_APP_INVALID_ARG;
}
/* Create listening socket */
int fd = CreateListenSocket(params);
if (fd < 0) {
AppPrintError("Failed to create listening socket\n");
HITLS_CFG_FreeConfig(configTmp);
return HITLS_APP_ERR_LISTEN;
}
*config = configTmp;
*listenFd = fd;
return HITLS_APP_SUCCESS;
}
static void RegisterSignal(void)
{
(void)signal(SIGCHLD, SIG_IGN);
(void)signal(SIGINT, SignalHandler);
(void)signal(SIGTERM, SignalHandler);
}
static int32_t CreateServerThread(ThreadServerArgs *threadArgs1, ThreadServerArgs *threadArgs2,
AppProvider *appProvider)
{
(void)threadArgs2;
(void)appProvider;
int ret = HITLS_APP_SUCCESS;
BSL_SAL_ThreadId thread1 = NULL;
#ifdef HITLS_APP_SM_MODE
BSL_SAL_ThreadId thread2 = NULL;
BSL_SAL_ThreadId thread3 = NULL;
#endif
do {
/* Start first thread for TLCP server */
ret = BSL_SAL_ThreadCreate(&thread1, ThreadServerMainLoop, threadArgs1);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to create tlcp server thread\n");
ret = HITLS_APP_SAL_FAIL;
break;
}
#ifdef HITLS_APP_SM_MODE
if (threadArgs1->params->smParam->smTag != 1) {
break;
}
/* Start second thread for DTLCP server */
ret = BSL_SAL_ThreadCreate(&thread2, ThreadHeartBeatLoop, threadArgs2);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to create dtlcp server thread\n");
ret = HITLS_APP_SAL_FAIL;
break;
}
/* Start third thread for periodic task */
ret = BSL_SAL_ThreadCreate(&thread3, ThreadPeriodicTask, appProvider);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to create periodic task thread\n");
ret = HITLS_APP_SAL_FAIL;
break;
}
#endif
} while (0);
if (ret != HITLS_APP_SUCCESS) {
g_loopFlag = false;
}
while (g_loopFlag) {
usleep(500000); /* 500000us */
}
BSL_SAL_ThreadClose(thread1);
#ifdef HITLS_APP_SM_MODE
BSL_SAL_ThreadClose(thread2);
BSL_SAL_ThreadClose(thread3);
#endif
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
/* Check return values from both threads */
if (threadArgs1->ret != HITLS_APP_SUCCESS) {
AppPrintError("server: tlcp server thread failed with error: 0x%x\n", threadArgs1->ret);
return threadArgs1->ret;
}
#ifdef HITLS_APP_SM_MODE
if (threadArgs1->params->smParam->smTag == 1 && threadArgs2->ret != HITLS_APP_SUCCESS) {
AppPrintError("server: dtlcp server thread failed with error: 0x%x\n", threadArgs2->ret);
return threadArgs2->ret;
}
#endif
return HITLS_APP_SUCCESS;
}
int HITLS_ServerMain(int argc, char *argv[])
{
AppProvider appProvider = {NULL, NULL, NULL};
HITLS_ServerParams params = {0};
#ifdef HITLS_APP_SM_MODE
HITLS_APP_SM_Param smParam = {0};
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider, &smParam};
params.smParam = &smParam;
#else
AppInitParam initParam = {CRYPT_RAND_SHA256, &appProvider};
#endif
HITLS_Config *config = NULL;
int listenFd = -1;
HITLS_Config *dtlcpConfig = NULL;
int dtlcpListenFd = -1;
HITLS_ServerParams dtlcpParams = {0};
int ret = HITLS_APP_SUCCESS;
/* Initialize library */
/* BSL memory callbacks are already set up in BSL module */
BSL_ERR_Init();
/* Initialize print UIO for error and info output */
ret = AppPrintErrorUioInit(stderr);
if (ret != HITLS_APP_SUCCESS) {
return HITLS_APP_INIT_FAILED;
}
ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL);
if (ret != CRYPT_SUCCESS) {
AppPrintError("Failed to initialize crypto library: 0x%x\n", ret);
return HITLS_APP_INIT_FAILED;
}
HITLS_CertMethodInit();
HITLS_CryptMethodInit();
/* Parse command line options */
ret = ParseServerOptions(argc, argv, ¶ms, &appProvider);
if (ret != HITLS_APP_SUCCESS) {
goto cleanup;
}
ret = HITLS_APP_Init(&initParam);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to initialize app, ret: %d.\n", ret);
goto cleanup;
}
ret = CreateConfigAndListenSocket(¶ms, &config, &listenFd);
if (ret != HITLS_APP_SUCCESS) {
goto cleanup;
}
#ifdef HITLS_APP_SM_MODE
if (params.smParam->smTag == 1) {
(void)memcpy_s(&dtlcpParams, sizeof(dtlcpParams), ¶ms, sizeof(params));
dtlcpParams.protocol = "dtlcp";
dtlcpParams.port = DEFAULT_DTLCP_PORT;
ret = CreateConfigAndListenSocket(&dtlcpParams, &dtlcpConfig, &dtlcpListenFd);
if (ret != HITLS_APP_SUCCESS) {
goto cleanup;
}
}
#endif
/* Handle SIGCHLD for child processes */
RegisterSignal();
ThreadServerArgs threadArgs1 = {config, listenFd, ¶ms, HITLS_APP_SUCCESS};
ThreadServerArgs threadArgs2 = {dtlcpConfig, dtlcpListenFd, &dtlcpParams, HITLS_APP_SUCCESS};
ret = CreateServerThread(&threadArgs1, &threadArgs2, &appProvider);
if (ret != HITLS_APP_SUCCESS) {
goto cleanup;
}
cleanup:
CleanupServerResources(config, listenFd);
CleanupServerResources(dtlcpConfig, dtlcpListenFd);
if (!params.quiet && ret == HITLS_APP_SUCCESS) {
AppPrintInfo("Server completed successfully\n");
}
BSL_SAL_FREE(params.bindAddr);
HITLS_APP_Deinit(&initParam, ret);
/* Cleanup print UIO */
AppPrintErrorUioUnInit();
return ret;
}
#ifdef HITLS_APP_SM_MODE
static int32_t HandleHeartBeat(HITLS_Ctx *ctx)
{
int ret = HITLS_APP_SUCCESS;
do {
if (!g_loopFlag) {
return HITLS_APP_SUCCESS;
}
ret = HITLS_Accept(ctx);
if (ret == HITLS_SUCCESS) {
break;
}
if (ret != HITLS_REC_NORMAL_RECV_BUF_EMPTY && ret != HITLS_REC_NORMAL_IO_BUSY) {
AppPrintError("server: TLS handshake failed, errCode: 0x%x.\n", ret);
return HITLS_APP_ERR_HANDSHAKE;
}
/* Non-blocking I/O, retry */
usleep(10000); /* Sleep 10000us. */
} while (ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY || ret == HITLS_REC_NORMAL_IO_BUSY);
uint8_t buffer[APP_HEARTBEAT_LEN];
uint32_t readLen = 0;
while (g_loopFlag) {
ret = HITLS_Read(ctx, buffer, sizeof(buffer), &readLen);
if (ret == HITLS_CM_LINK_CLOSED) {
break;
}
if (ret != HITLS_SUCCESS || readLen != APP_HEARTBEAT_LEN) {
AppPrintError("server: Failed to read heartbeat data, errCode: 0x%x, readLen: %u.\n", ret, readLen);
return ret;
}
ret = ParseHeartBeat(buffer, readLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("server: Failed to parse heartbeat, errCode: 0x%x.\n", ret);
return ret;
}
readLen = sizeof(buffer);
ret = GetHeartBeat(buffer, &readLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to get heartbeat: 0x%x\n", ret);
return ret;
}
uint32_t written = 0;
ret = HITLS_Write(ctx, (const uint8_t *)buffer, readLen, &written);
if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to send heartbeat, errCode: 0x%x\n", ret);
return ret;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t HeartBeatLoop(HITLS_Config *config, int listenFd, HITLS_ServerParams *params)
{
int ret = HITLS_APP_SUCCESS;
while (g_loopFlag) {
BSL_UIO *uio = NULL;
HITLS_Ctx *ctx = NULL;
int clientFd = listenFd;
/* Create UIO and TLS context */
uio = CreateServerUIO(clientFd, params);
ctx = HITLS_New(config);
if (uio == NULL || ctx == NULL) {
AppPrintError("server: Failed to create UIO or TLS context.\n");
CleanupConnection(ctx, uio, -1);
ret = HITLS_APP_ERR_CREATE_CTX;
break;
}
ret = HITLS_SetUio(ctx, uio);
if (ret != HITLS_SUCCESS) {
AppPrintError("server: Failed to set UIO, errCode: 0x%x.\n", ret);
CleanupConnection(ctx, uio, -1);
ret = HITLS_APP_UIO_FAIL;
break;
}
/* Handle client connection */
ret = HandleHeartBeat(ctx);
CleanupConnection(ctx, uio, -1);
}
g_loopFlag = false;
return ret;
}
#endif
| 2401_83913325/openHiTLS_1 | apps/src/app_server.c | C | unknown | 32,451 |
/*
* 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 "app_sm.h"
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#ifdef HITLS_APP_SM_MODE
#include <unistd.h>
#endif
#include <securec.h>
#include "bsl_bytes.h"
#include "bsl_ui.h"
#include "bsl_sal.h"
#include "bsl_params.h"
#include "sal_file.h"
#include "app_errno.h"
#include "app_opt.h"
#include "app_print.h"
#include "app_utils.h"
#include "crypt_eal_kdf.h"
#include "crypt_eal_mac.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_cmvp.h"
#include "crypt_params_key.h"
#include "crypt_errno.h"
#include "crypt_algid.h"
#include "crypt_cmvp_selftest.h"
#ifdef HITLS_APP_SM_MODE
#define HITLS_APP_SM_USER_FILE_NAME "openhitls_user"
#define HITLS_APP_SM_VERSION 1
#define HITLS_APP_SM_DERIVE_MAC_ID CRYPT_MAC_HMAC_SM3
#define HITLS_APP_SM_INTEGRITY_MAC_ID CRYPT_MAC_HMAC_SM3
#define HITLS_APP_SM_ITER 1024
#define HITLS_APP_SM_SALT_MAX_LEN 64
#define HITLS_APP_SM_SALT_LEN 8
#define HITLS_APP_SM_DKEY_LEN 32
#define HITLS_APP_SM_HMAC_LEN 32
#define HITLS_APP_SM_MAX_PARAM_NUM 5
#ifndef CMVP_INTEGRITYKEY
#define CMVP_INTEGRITYKEY ""
#endif
#define HITLS_APP_SM_SM4_SELFTEST_FAILED "SM4 selftest failed.\n"
#define HITLS_APP_SM_SM3_SELFTEST_FAILED "SM3 selftest failed.\n"
#define HITLS_APP_SM_MAC_SELFTEST_FAILED "Mac selftest failed.\n"
#define HITLS_APP_SM_DRBG_SELFTEST_FAILED "Drbg selftest failed.\n"
#define HITLS_APP_SM_KDF_SELFTEST_FAILED "Pbkdf2-hmac-sm3 selftest failed.\n"
#define HITLS_APP_SM_SM2_SELFTEST_FAILED "SM2 selftest failed.\n"
#define HITLS_APP_SM_INTEGRITY_SELFTEST_FAILED "Integrity selftest failed.\n"
#define HITLS_APP_SM_RANDOMNESS_SELFTEST_FAILED "Randomness selftest failed.\n"
#define HITLS_APP_SM_PAIRWISETEST_SELFTEST_FAILED "SM2 key pairwise test failed.\n"
typedef struct {
int32_t version;
int32_t deriveMacId;
int32_t integrityMacId;
int32_t iter;
uint8_t salt[HITLS_APP_SM_SALT_MAX_LEN];
uint32_t saltLen;
uint8_t dKey[HITLS_APP_SM_DKEY_LEN];
uint32_t dKeyLen;
} UserParam;
typedef struct {
UserParam userParam;
uint8_t hmac[HITLS_APP_SM_HMAC_LEN];
uint32_t hmacLen;
} UserInfo;
static void UserParamOrderCvt(UserParam *userParam, bool toByte)
{
if (toByte) {
BSL_Uint32ToByte(userParam->version, (uint8_t *)&userParam->version);
BSL_Uint32ToByte(userParam->deriveMacId, (uint8_t *)&userParam->deriveMacId);
BSL_Uint32ToByte(userParam->integrityMacId, (uint8_t *)&userParam->integrityMacId);
BSL_Uint32ToByte(userParam->iter, (uint8_t *)&userParam->iter);
BSL_Uint32ToByte(userParam->saltLen, (uint8_t *)&userParam->saltLen);
BSL_Uint32ToByte(userParam->dKeyLen, (uint8_t *)&userParam->dKeyLen);
} else {
userParam->version = BSL_ByteToUint32((uint8_t *)&userParam->version);
userParam->deriveMacId = BSL_ByteToUint32((uint8_t *)&userParam->deriveMacId);
userParam->integrityMacId = BSL_ByteToUint32((uint8_t *)&userParam->integrityMacId);
userParam->iter = BSL_ByteToUint32((uint8_t *)&userParam->iter);
userParam->saltLen = BSL_ByteToUint32((uint8_t *)&userParam->saltLen);
userParam->dKeyLen = BSL_ByteToUint32((uint8_t *)&userParam->dKeyLen);
}
}
static void UserInfoOrderCvt(UserInfo *userInfo, bool toByte)
{
UserParamOrderCvt(&userInfo->userParam, toByte);
if (toByte) {
BSL_Uint32ToByte(userInfo->hmacLen, (uint8_t *)&userInfo->hmacLen);
} else {
userInfo->hmacLen = BSL_ByteToUint32((uint8_t *)&userInfo->hmacLen);
}
}
int32_t HITLS_APP_SM_RootUserCheck(void)
{
if (getuid() == 0) {
AppPrintError("Root selftest failed.\n");
return HITLS_APP_ROOT_CHECK_FAIL;
}
return HITLS_APP_SUCCESS;
}
static bool CheckFileExists(const char *filename)
{
return access(filename, F_OK) == 0;
}
static int32_t CheckPassword(const uint8_t *password, const uint32_t passwordLen)
{
const char specialStr[] = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
uint32_t hasLowercase = 0;
uint32_t hasUppercase = 0;
uint32_t hasDigit = 0;
uint32_t hasSpecial = 0;
if (passwordLen < 8) { // 8: minimum length of password
AppPrintError("The password must be at least 8 characters long.\n");
return HITLS_APP_PASSWD_FAIL;
}
for (uint32_t i = 0; i < passwordLen; i++) {
if (password[i] < '!' || password[i] > '~') {
AppPrintError("The password can contain only the following characters:\n");
AppPrintError("a~z A~Z 0~9 ! \" # $ %% & ' ( ) * + , - . / : ; < = > ? @ [ \\ ] ^ _ ` { | } ~\n");
return HITLS_APP_PASSWD_FAIL;
}
if (password[i] >= 'a' && password[i] <= 'z') {
hasLowercase = 1;
}
if (password[i] >= 'A' && password[i] <= 'Z') {
hasUppercase = 1;
}
if (password[i] >= '0' && password[i] <= '9') {
hasDigit = 1;
}
if (strchr(specialStr, password[i]) != NULL) {
hasSpecial = 1;
}
}
if (hasLowercase + hasUppercase + hasDigit + hasSpecial < 2) { // 2: minimum number of different characters
AppPrintError("The password must contain at least two of the following characters: lowercase letter, uppercase "
"letter, digit, or special character.\n");
return HITLS_APP_PASSWD_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t GetPassword(char **password)
{
char buf[APP_MAX_PASS_LENGTH + 1] = {0};
uint32_t bufLen = APP_MAX_PASS_LENGTH + 1;
BSL_UI_ReadPwdParam param = {"passwd", NULL, true};
int32_t ret = BSL_UI_ReadPwdUtil(¶m, buf, &bufLen, HITLS_APP_DefaultPassCB, NULL);
if (ret == BSL_UI_READ_BUFF_TOO_LONG || ret == BSL_UI_READ_LEN_TOO_SHORT) {
HITLS_APP_PrintPassErrlog();
return HITLS_APP_PASSWD_FAIL;
}
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to read passwd from stdin.\n");
return HITLS_APP_PASSWD_FAIL;
}
buf[bufLen - 1] = '\0';
ret = CheckPassword((const uint8_t *)buf, bufLen - 1);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_CleanseData(buf, bufLen);
return ret;
}
*password = (char *)BSL_SAL_Dump(buf, bufLen);
BSL_SAL_CleanseData(buf, bufLen);
if (*password == NULL) {
AppPrintError("Failed to allocate memory, bufLen: %u.\n", bufLen);
return HITLS_APP_MEM_ALLOC_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t DeriveKeyFromPassword(AppProvider *provider, char *password, UserParam *userParam, uint8_t *dKey,
uint32_t dKeyLen)
{
CRYPT_EAL_KdfCTX *kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(APP_GetCurrent_LibCtx(), CRYPT_KDF_PBKDF2,
provider->providerAttr);
if (kdfCtx == NULL) {
AppPrintError("Failed to create kdf context.\n");
return HITLS_APP_CRYPTO_FAIL;
}
int index = 0;
BSL_Param params[HITLS_APP_SM_MAX_PARAM_NUM] = {{0}, {0}, {0}, {0}, BSL_PARAM_END};
(void)BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &userParam->deriveMacId,
sizeof(userParam->deriveMacId));
(void)BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, (uint8_t *)password,
strlen(password));
(void)BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, userParam->salt,
userParam->saltLen);
(void)BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &userParam->iter,
sizeof(userParam->iter));
int32_t ret = CRYPT_EAL_KdfSetParam(kdfCtx, params);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_KdfFreeCtx(kdfCtx);
AppPrintError("Failed to set kdf params, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
ret = CRYPT_EAL_KdfDerive(kdfCtx, dKey, dKeyLen);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_KdfFreeCtx(kdfCtx);
AppPrintError("Failed to derive key, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_KdfFreeCtx(kdfCtx);
return HITLS_APP_SUCCESS;
}
const char *GetIntegrityKey(void)
{
return CMVP_INTEGRITYKEY;
}
static int32_t CalculateHMAC(AppProvider *provider, int32_t macId, const uint8_t *data, uint32_t dataLen, uint8_t *hmac,
uint32_t *hmacLen)
{
CRYPT_EAL_MacCtx *macCtx = CRYPT_EAL_ProviderMacNewCtx(APP_GetCurrent_LibCtx(), macId, provider->providerAttr);
if (macCtx == NULL) {
AppPrintError("Failed to create mac context, macId: %d.\n", macId);
return HITLS_APP_CRYPTO_FAIL;
}
int32_t ret = CRYPT_EAL_MacInit(macCtx, (const uint8_t *)GetIntegrityKey(), (uint32_t)strlen(GetIntegrityKey()));
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_MacFreeCtx(macCtx);
AppPrintError("Failed to init mac context, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
ret = CRYPT_EAL_MacUpdate(macCtx, data, dataLen);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_MacFreeCtx(macCtx);
AppPrintError("Failed to update mac context, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
ret = CRYPT_EAL_MacFinal(macCtx, hmac, hmacLen);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_MacFreeCtx(macCtx);
AppPrintError("Failed to final mac context, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_MacFreeCtx(macCtx);
return HITLS_APP_SUCCESS;
}
static int32_t VerifyHMAC(AppProvider *provider, int32_t macId, const uint8_t *data, uint32_t dataLen,
const uint8_t *hmac, uint32_t hmacLen)
{
uint8_t calculatedHmac[HITLS_APP_SM_HMAC_LEN];
uint32_t calcHmacLen = sizeof(calculatedHmac);
int32_t ret = CalculateHMAC(provider, macId, data, dataLen, calculatedHmac, &calcHmacLen);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (calcHmacLen != hmacLen || memcmp(calculatedHmac, hmac, hmacLen) != 0) {
AppPrintError("HMAC verify failed.\n");
return HITLS_APP_INTEGRITY_VERIFY_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t WriteUserFile(char *userFile, UserInfo *userInfo)
{
BSL_UIO *uio = BSL_UIO_New(BSL_UIO_FileMethod());
if (uio == NULL) {
AppPrintError("Failed to create uio.\n");
return HITLS_APP_UIO_FAIL;
}
int32_t ret = BSL_UIO_Ctrl(uio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_WRITE, userFile);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to open userFile, errCode: 0x%x.\n", ret);
BSL_UIO_Free(uio);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(uio, true);
UserInfoOrderCvt(userInfo, true);
uint32_t writeLen = 0;
ret = BSL_UIO_Write(uio, userInfo, sizeof(UserInfo), &writeLen);
if (ret != BSL_SUCCESS || writeLen != sizeof(UserInfo)) {
BSL_UIO_Free(uio);
AppPrintError("Failed to write userFile, errCode: 0x%x, writeLen: %u.\n", ret, writeLen);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_Free(uio);
return HITLS_APP_SUCCESS;
}
static int32_t ReadUserFile(char *userFile, UserInfo *userInfo)
{
BSL_UIO *uio = BSL_UIO_New(BSL_UIO_FileMethod());
if (uio == NULL) {
AppPrintError("Failed to create uio.\n");
return HITLS_APP_UIO_FAIL;
}
int32_t ret = BSL_UIO_Ctrl(uio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_READ, userFile);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to open userFile, errCode: 0x%x.\n", ret);
BSL_UIO_Free(uio);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(uio, true);
uint32_t readLen = 0;
ret = BSL_UIO_Read(uio, userInfo, sizeof(UserInfo), &readLen);
if (ret != BSL_SUCCESS || readLen != sizeof(UserInfo)) {
BSL_UIO_Free(uio);
AppPrintError("Failed to read userFile, errCode: 0x%x, readLen: %u.\n", ret, readLen);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_Free(uio);
UserInfoOrderCvt(userInfo, false);
// check userInfo
if (userInfo->userParam.version != HITLS_APP_SM_VERSION ||
userInfo->userParam.saltLen > sizeof(userInfo->userParam.salt) ||
userInfo->userParam.dKeyLen > sizeof(userInfo->userParam.dKey) ||
userInfo->hmacLen > sizeof(userInfo->hmac)) {
AppPrintError("User info check failed.\n");
return HITLS_APP_INFO_CMP_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetUserInfo(AppProvider *provider, UserInfo *userInfo, char *password)
{
userInfo->userParam.version = HITLS_APP_SM_VERSION;
userInfo->userParam.deriveMacId = HITLS_APP_SM_DERIVE_MAC_ID;
userInfo->userParam.integrityMacId = HITLS_APP_SM_INTEGRITY_MAC_ID;
userInfo->userParam.iter = HITLS_APP_SM_ITER;
userInfo->userParam.saltLen = HITLS_APP_SM_SALT_LEN;
userInfo->userParam.dKeyLen = HITLS_APP_SM_DKEY_LEN;
int32_t ret = CRYPT_EAL_RandbytesEx(APP_GetCurrent_LibCtx(), userInfo->userParam.salt, userInfo->userParam.saltLen);
if (ret != CRYPT_SUCCESS) {
AppPrintError("Failed to generate the salt value, ret: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
return DeriveKeyFromPassword(provider, password, &userInfo->userParam, userInfo->userParam.dKey,
userInfo->userParam.dKeyLen);
}
static int32_t FirstTimeLogin(AppProvider *provider, char *userFile, char **pwd)
{
char *password = NULL;
UserInfo userInfo = {0};
userInfo.hmacLen = sizeof(userInfo.hmac);
AppPrintError("This is your first login, please set your password.\n");
int32_t ret = GetPassword(&password);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = SetUserInfo(provider, &userInfo, password);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_ClearFree(password, strlen(password));
return ret;
}
int32_t macId = userInfo.userParam.integrityMacId;
UserParamOrderCvt(&userInfo.userParam, true);
ret = CalculateHMAC(provider, macId, (const uint8_t *)&userInfo.userParam, sizeof(UserParam), userInfo.hmac,
&userInfo.hmacLen);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_ClearFree(password, strlen(password));
return ret;
}
UserParamOrderCvt(&userInfo.userParam, false);
ret = WriteUserFile(userFile, &userInfo);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_ClearFree(password, strlen(password));
return ret;
}
*pwd = password;
return HITLS_APP_SUCCESS;
}
static int32_t VerifyPassword(AppProvider *provider, UserInfo *userInfo, char *password)
{
uint8_t derivedKey[HITLS_APP_SM_DKEY_LEN];
int32_t ret = DeriveKeyFromPassword(provider, password, &userInfo->userParam, derivedKey, sizeof(derivedKey));
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (userInfo->userParam.dKeyLen != sizeof(derivedKey)) {
AppPrintError("Admin verification failed.\n");
return HITLS_APP_INFO_CMP_FAIL;
}
if (memcmp(derivedKey, userInfo->userParam.dKey, userInfo->userParam.dKeyLen) != 0) {
AppPrintError("Admin verification failed.\n");
return HITLS_APP_PASSWD_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t ExistingUserLogin(AppProvider *provider, char *userFile, char **pwd)
{
char *password = NULL;
UserInfo userInfo = {0};
int32_t ret;
ret = ReadUserFile(userFile, &userInfo);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
int32_t macId = userInfo.userParam.integrityMacId;
UserParamOrderCvt(&userInfo.userParam, true);
ret = VerifyHMAC(provider, macId, (const uint8_t *)&userInfo.userParam, sizeof(UserParam),
userInfo.hmac, userInfo.hmacLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("User file integrity check failed, errCode: 0x%x.\n", ret);
return ret;
}
UserParamOrderCvt(&userInfo.userParam, false);
ret = GetPassword(&password);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = VerifyPassword(provider, &userInfo, password);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_ClearFree(password, strlen(password));
return ret;
}
*pwd = password;
return HITLS_APP_SUCCESS;
}
static char *GetUserFilePath(const char *workPath)
{
char *path = BSL_SAL_Malloc(APP_MAX_PATH_LEN);
if (path == NULL) {
AppPrintError("Failed to allocate memory.\n");
return NULL;
}
int32_t ret = sprintf_s(path, APP_MAX_PATH_LEN, "%s/%s", workPath, HITLS_APP_SM_USER_FILE_NAME);
if (ret < 0) {
AppPrintError("WorkPath is invalid.\n");
BSL_SAL_Free(path);
return NULL;
}
return path;
}
int32_t HITLS_APP_SM_Init(AppProvider *provider, const char *workPath, char **password, int32_t *status)
{
if (provider == NULL || workPath == NULL || password == NULL || status == NULL) {
return HITLS_APP_INVALID_ARG;
}
*status = HITLS_APP_SM_STATUS_SELFTEST;
int32_t ret = HITLS_APP_SM_RootUserCheck();
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = HITLS_APP_SM_IntegrityCheck(provider);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
*status = HITLS_APP_SM_STATUS_MANAGER;
char *path = GetUserFilePath(workPath);
if (path == NULL) {
AppPrintError("Failed to get user file path.\n");
return HITLS_APP_INVALID_ARG;
}
ret = CheckFileExists(path) ? ExistingUserLogin(provider, path, password) :
FirstTimeLogin(provider, path, password);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_Free(path);
return ret;
}
BSL_SAL_Free(path);
return HITLS_APP_SUCCESS;
}
char *HITLS_APP_GetAppPath(void)
{
char *tempPath = BSL_SAL_Malloc(APP_MAX_PATH_LEN);
if (tempPath == NULL) {
(void)AppPrintError("Failed to allocate memory.\n");
return NULL;
}
ssize_t count = readlink("/proc/self/exe", tempPath, APP_MAX_PATH_LEN);
if (count < 0 || (size_t)count >= APP_MAX_PATH_LEN) {
BSL_SAL_Free(tempPath);
AppPrintError("Failed to readlink.\n");
return NULL;
}
tempPath[count] = '\0';
// realpath() need to use PATH_MAX.
char *path = BSL_SAL_Malloc(PATH_MAX);
if (path == NULL) {
BSL_SAL_Free(tempPath);
AppPrintError("Failed to allocate app path memory.\n");
return NULL;
}
if (realpath(tempPath, path) == NULL) {
BSL_SAL_Free(path);
BSL_SAL_Free(tempPath);
AppPrintError("Failed to get realpath.\n");
return NULL;
}
BSL_SAL_Free(tempPath);
return path;
}
static int32_t GetAppExpectHmac(const char *appPath, uint8_t *hmac, uint32_t *hmacLen)
{
char *hmacPath = BSL_SAL_Malloc(APP_MAX_PATH_LEN);
if (hmacPath == NULL) {
AppPrintError("Failed to allocate memory.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
int32_t ret = sprintf_s(hmacPath, APP_MAX_PATH_LEN, "%s.hmac", appPath);
if (ret < 0) {
AppPrintError("AppPath is too long, ret: %d.\n", ret);
BSL_SAL_Free(hmacPath);
return HITLS_APP_SECUREC_FAIL;
}
BSL_Buffer data = { 0 };
ret = BSL_SAL_ReadFile(hmacPath, &data.data, &data.dataLen);
if (ret != BSL_SUCCESS) {
AppPrintError("Read file failed: %s, errCode: 0x%x.\n", hmacPath, ret);
BSL_SAL_Free(hmacPath);
return HITLS_APP_SAL_FAIL;
}
BSL_SAL_FREE(hmacPath);
char seps[] = " \n";
char *tmp = NULL;
char *nextTmp = NULL;
do {
tmp = strtok_s((char *)data.data, seps, &nextTmp);
if (tmp == NULL) {
AppPrintError("Invalid hmac.\n");
ret = HITLS_APP_INVALID_ARG;
break;
}
tmp = strtok_s(NULL, seps, &nextTmp);
if (tmp == NULL) {
AppPrintError("Invalid hmac.\n");
ret = HITLS_APP_INVALID_ARG;
break;
}
ret = HITLS_APP_StrToHex(tmp, hmac, hmacLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to convert hmac, errCode: 0x%x.\n", ret);
break;
}
} while (0);
BSL_SAL_Free(data.data);
return ret;
}
static int32_t VerifyAppHmac(AppProvider *provider, const char *appPath, const uint8_t *expectHmac,
uint32_t expectHmacLen)
{
BSL_Buffer data = {0};
int32_t ret = BSL_SAL_ReadFile(appPath, &data.data, &data.dataLen);
if (ret != BSL_SUCCESS) {
AppPrintError("Read file failed, appPath: %s, errCode: 0x%x.\n", appPath, ret);
return HITLS_APP_SAL_FAIL;
}
ret = VerifyHMAC(provider, CRYPT_MAC_HMAC_SM3, data.data, data.dataLen, expectHmac, expectHmacLen);
BSL_SAL_Free(data.data);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Calculate integrity hmac failed, appPath: %s, errCode: 0x%x.\n", appPath, ret);
return ret;
}
return ret;
}
int32_t HITLS_APP_SM_IntegrityCheck(AppProvider *provider)
{
if (provider == NULL) {
return HITLS_APP_INVALID_ARG;
}
char *appPath = HITLS_APP_GetAppPath();
if (appPath == NULL) {
AppPrintError("Failed to get app path.\n");
return HITLS_APP_INVALID_ARG;
}
uint8_t expectHmac[HITLS_APP_SM_HMAC_LEN];
uint32_t expectHmacLen = sizeof(expectHmac);
int32_t ret = GetAppExpectHmac(appPath, expectHmac, &expectHmacLen);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_Free(appPath);
return ret;
}
ret = VerifyAppHmac(provider, appPath, expectHmac, expectHmacLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError(HITLS_APP_SM_INTEGRITY_SELFTEST_FAILED);
BSL_SAL_Free(appPath);
return ret;
}
BSL_SAL_Free(appPath);
return HITLS_APP_SUCCESS;
}
static int32_t RandomnessTest(CRYPT_SelftestCtx *selftestCtx, uint8_t *data, uint32_t len)
{
BSL_Param params[] = {{0}, {0}, BSL_PARAM_END};
int32_t type = CRYPT_CMVP_RANDOMNESS_TEST;
(void)BSL_PARAM_InitValue(¶ms[0], CRYPT_PARAM_CMVP_SELFTEST_TYPE, BSL_PARAM_TYPE_INT32, &type, sizeof(type));
(void)BSL_PARAM_InitValue(¶ms[1], CRYPT_PARAM_CMVP_RANDOM, BSL_PARAM_TYPE_OCTETS, data, len);
int32_t ret = CRYPT_CMVP_Selftest(selftestCtx, params);
if (ret != CRYPT_SUCCESS) {
AppPrintError("Random number randomness check failed, errCode: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t RandomSelftest(AppProvider *provider, uint32_t groups, uint32_t bitsPerGroup, uint32_t retry,
uint32_t threshold)
{
const uint32_t bytesPerGroup = (bitsPerGroup + 7) >> 3;
const uint32_t totalLen = groups * bytesPerGroup;
uint8_t *data = BSL_SAL_Malloc(totalLen);
if (data == NULL) {
AppPrintError("Failed to allocate memory.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
CRYPT_SelftestCtx *selftestCtx = CRYPT_CMVP_SelftestNewCtx(APP_GetCurrent_LibCtx(), provider->providerAttr);
if (selftestCtx == NULL) {
AppPrintError("Randomness test failed, selftestCtx is NULL.\n");
BSL_SAL_Free(data);
return HITLS_APP_CRYPTO_FAIL;
}
bool isSuccess = false;
for (uint32_t attempt = 0; attempt < retry; attempt++) {
int32_t ret = CRYPT_EAL_RandbytesEx(APP_GetCurrent_LibCtx(), data, totalLen);
if (ret != CRYPT_SUCCESS) {
AppPrintError("Failed to generate random data, errCode: 0x%x.\n", ret);
continue;
}
uint32_t failCnt = 0;
for (uint32_t i = 0; i < groups; i++) {
ret = RandomnessTest(selftestCtx, data + i * bytesPerGroup, bytesPerGroup);
if (ret == HITLS_APP_SUCCESS) {
continue;
}
failCnt++;
if (failCnt >= threshold) {
break;
}
}
if (failCnt < threshold) {
isSuccess = true;
break;
}
}
BSL_SAL_Free(data);
CRYPT_CMVP_SelftestFreeCtx(selftestCtx);
return isSuccess ? HITLS_APP_SUCCESS : HITLS_APP_CRYPTO_FAIL;
}
int32_t HITLS_APP_SM_PeriodicRandomCheck(AppProvider *provider)
{
if (provider == NULL) {
return HITLS_APP_INVALID_ARG;
}
/* GM/T 0062-2018:
* Periodic random self-check (requirements a–d):
* a) Test amount: 5 groups × 10^4 bits per group (total 5 × 10^4 bits).
* b) Test item: Poker test, m = 2 (via CMVP selftest under the hood).
* c) Decision: fail if ≥1 group fails; allow one repeat of collection and test.
* To allow one retry, set 'retry' to 2 (attempts). Default below is 1 (no retry).
* d) Detection period: configurable; recommended interval ≤ 24 hours between checks.
* Invoke this API on a schedule according to product requirements.
*/
uint32_t groups = 5;
uint32_t bitsPerGroup = 10000;
uint32_t retry = 2;
uint32_t threshold = 1;
return RandomSelftest(provider, groups, bitsPerGroup, retry, threshold);
}
void HITLS_APP_SM_PrintLog(int32_t ret)
{
switch (ret) {
case CRYPT_CMVP_ERR_CIPHER_SELFTEST:
AppPrintError(HITLS_APP_SM_SM4_SELFTEST_FAILED);
return;
case CRYPT_CMVP_ERR_MD_SELFTEST:
AppPrintError(HITLS_APP_SM_SM3_SELFTEST_FAILED);
return;
case CRYPT_CMVP_ERR_MAC_SELFTEST:
AppPrintError(HITLS_APP_SM_MAC_SELFTEST_FAILED);
return;
case CRYPT_CMVP_ERR_DRBG_SELFTEST:
AppPrintError(HITLS_APP_SM_DRBG_SELFTEST_FAILED);
return;
case CRYPT_CMVP_ERR_KDF_SELFTEST:
AppPrintError(HITLS_APP_SM_KDF_SELFTEST_FAILED);
return;
case CRYPT_CMVP_ERR_PKEY_SELFTEST:
AppPrintError(HITLS_APP_SM_SM2_SELFTEST_FAILED);
return;
case CRYPT_CMVP_ERR_INTEGRITY:
AppPrintError(HITLS_APP_SM_INTEGRITY_SELFTEST_FAILED);
return;
case CRYPT_CMVP_RANDOMNESS_ERR:
AppPrintError(HITLS_APP_SM_RANDOMNESS_SELFTEST_FAILED);
return;
case CRYPT_CMVP_ERR_PAIRWISETEST:
AppPrintError(HITLS_APP_SM_PAIRWISETEST_SELFTEST_FAILED);
return;
default:
return;
}
}
#endif
| 2401_83913325/openHiTLS_1 | apps/src/app_sm.c | C | unknown | 26,613 |
/*
* Shandong University — School of Cyber Science and Technology
* Cryptography Engineering Course (2025)
*
* Course Project Contribution
* Contributor: ShaoYan Zhang, XiaoKai Gong, YiMing Zhou, HeYang Ding
* Instructor: Weijia Wang
*
* Description:
* This code is part of the official output of the 2025 Cryptography Engineering
* course at the School of Cyber Science and Technology, Shandong University.
* It reflects the project work and research conducted by the contributor(s)
* under the supervision of the instructor.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <termios.h>
#include <unistd.h>
#include <sys/stat.h>
#include <securec.h>
#include <pthread.h>
#include <sys/time.h>
#include "bsl_uio.h"
#include "app_utils.h"
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_provider.h"
#include "app_sm.h"
#include "bsl_sal.h"
#include "sal_file.h"
#include "ui_type.h"
#include "bsl_ui.h"
#include "bsl_errno.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_kdf.h"
#include "crypt_algid.h"
#include "crypt_errno.h"
#include "crypt_params_key.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_mac.h"
#include "app_speed.h"
// Supported cipher algorithm list
static const HITLS_CipherList g_cIdList[] = {
{CRYPT_CIPHER_AES128_CBC, "aes-128-cbc"},
{CRYPT_CIPHER_AES192_CBC, "aes-192-cbc"},
{CRYPT_CIPHER_AES256_CBC, "aes-256-cbc"},
{CRYPT_CIPHER_AES128_CTR, "aes-128-ctr"},
{CRYPT_CIPHER_AES192_CTR, "aes-192-ctr"},
{CRYPT_CIPHER_AES256_CTR, "aes-256-ctr"},
{CRYPT_CIPHER_AES128_ECB, "aes-128-ecb"},
{CRYPT_CIPHER_AES192_ECB, "aes-192-ecb"},
{CRYPT_CIPHER_AES256_ECB, "aes-256-ecb"},
{CRYPT_CIPHER_AES128_GCM, "aes-128-gcm"},
{CRYPT_CIPHER_AES192_GCM, "aes-192-gcm"},
{CRYPT_CIPHER_AES256_GCM, "aes-256-gcm"},
{CRYPT_CIPHER_AES128_CFB, "aes-128-cfb"},
{CRYPT_CIPHER_AES192_CFB, "aes-192-cfb"},
{CRYPT_CIPHER_AES256_CFB, "aes-256-cfb"},
{CRYPT_CIPHER_AES128_OFB, "aes-128-ofb"},
{CRYPT_CIPHER_AES192_OFB, "aes-192-ofb"},
{CRYPT_CIPHER_AES256_OFB, "aes-256-ofb"},
{CRYPT_CIPHER_SM4_CBC, "sm4-cbc"},
{CRYPT_CIPHER_SM4_ECB, "sm4-ecb"},
{CRYPT_CIPHER_SM4_CTR, "sm4-ctr"},
{CRYPT_CIPHER_SM4_GCM, "sm4-gcm"},
{CRYPT_CIPHER_SM4_CFB, "sm4-cfb"},
{CRYPT_CIPHER_SM4_OFB, "sm4-ofb"},
};
// Supported MAC algorithm list
static const HITLS_MacList g_mIdList[] = {
{CRYPT_MAC_HMAC_MD5, "md5"},
{CRYPT_MAC_HMAC_SM3, "sm3"},
{CRYPT_MAC_HMAC_SHA1, "sha1"},
{CRYPT_MAC_HMAC_SHA224, "sha224"},
{CRYPT_MAC_HMAC_SHA256, "sha256"},
{CRYPT_MAC_HMAC_SHA384, "sha384"},
{CRYPT_MAC_HMAC_SHA512, "sha512"},
{CRYPT_MAC_HMAC_SHA3_224, "sha3-224"},
{CRYPT_MAC_HMAC_SHA3_256, "sha3-256"},
{CRYPT_MAC_HMAC_SHA3_384, "sha3-384"},
{CRYPT_MAC_HMAC_SHA3_512, "sha3-512"},
};
// Command line option enumeration
typedef enum {
HITLS_APP_OPT_CIPHER_ALG = 2,
HITLS_APP_OPT_MAC,
HITLS_APP_OPT_ENC,
HITLS_APP_OPT_DEC,
HITLS_APP_OPT_SECONDS,
HITLS_APP_OPT_BYTES,
HITLS_APP_OPT_AUTO_BLOCK,
HITLS_APP_OPT_THREADS,
} HITLS_OptType;
// Algorithm test command option structure
typedef struct {
uint32_t version;
int32_t cipherId;
int32_t macId;
int32_t encTag;
int32_t seconds;
int32_t bytes;
bool autoBlock;
int32_t threads;
} SpeedCmdOpt;
// Thread resource structure
typedef struct {
const SpeedCmdOpt* opt;
int blockSize;
int threadId;
uint64_t threadOps;
size_t threadTotalBytes;
double threadElapsed;
unsigned char key[MAX_KEY_LEN];
unsigned char iv[IV_LENGTH];
unsigned char* in;
unsigned char* out;
CRYPT_EAL_CipherCtx* cipherCtx;
unsigned char mac[MAX_MAC_LEN];
unsigned char* data;
CRYPT_EAL_MacCtx* macCtx;
} ThreadResource;
// Command line option definition
static const HITLS_CmdOption g_speedOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"cipher", HITLS_APP_OPT_CIPHER_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Cipher algorithm (e.g., aes-128-cbc)"},
{"mac", HITLS_APP_OPT_MAC, HITLS_APP_OPT_VALUETYPE_STRING, "MAC algorithm (e.g., sha256)"},
{"enc", HITLS_APP_OPT_ENC, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Encryption operation"},
{"dec", HITLS_APP_OPT_DEC, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Decryption operation"},
{"seconds", HITLS_APP_OPT_SECONDS, HITLS_APP_OPT_VALUETYPE_UINT, "Run benchmarks for N seconds (default: 3)"},
{"bytes", HITLS_APP_OPT_BYTES, HITLS_APP_OPT_VALUETYPE_UINT, "Custom block size in bytes (e.g., 1024)"},
{"auto-block", HITLS_APP_OPT_AUTO_BLOCK, HITLS_APP_OPT_VALUETYPE_NO_VALUE,
"Auto test multiple block sizes (16/64/256/1024/8192/16384 bytes)"},
{"threads", HITLS_APP_OPT_THREADS, HITLS_APP_OPT_VALUETYPE_UINT,
"Number of threads for parallel test (default: 1)"},
{NULL}
};
// Global variables
static struct timeval g_startTimeval;
double throughputs[TEST_BLOCK_SIZES_LEN] = {0.0};
// Function declarations
static int32_t HandleOpt(SpeedCmdOpt* speedOpt);
static void ValidateThreadsParam(SpeedCmdOpt* speedOpt, const char* val);
static int32_t ParseSpeedOpts(SpeedCmdOpt* speedOpt);
static int32_t ValidateSpeedOpts(SpeedCmdOpt* speedOpt);
static void RunCipherBenchmark(const SpeedCmdOpt* opt);
static void RunCipherSingleBlockTest(const SpeedCmdOpt* opt, int blockSize, int index);
static void RunCipherAutoBlockTest(const SpeedCmdOpt* opt);
static int InitCipherResources(ThreadResource* res);
static int GetCipherKeyLen(int32_t cipherId);
static void FreeCipherResources(ThreadResource* res);
static void* CipherThreadWork(void* arg);
static void RunMacBenchmark(const SpeedCmdOpt* opt);
static void RunMacSingleBlockTest(const SpeedCmdOpt* opt, int blockSize, int index);
static void RunMacAutoBlockTest(const SpeedCmdOpt* opt);
static int InitMacResources(ThreadResource* res);
static uint32_t GetMacKeyLen(int32_t macId);
static void FreeMacResources(ThreadResource* res);
static void* MacThreadWork(void* arg);
static void AggregateThreadResults(const SpeedCmdOpt* opt, ThreadResource* res,
double* totalSpeed, uint64_t* totalOps, double* totalElapsed);
static int32_t GetCipherId(const char* name);
static int32_t GetHMacId(const char* mdName);
static const char* GetCipherName(int32_t cipherId);
static const char* GetMacName(int32_t macId);
static void PrintCipherAlgList(void);
static void PrintHMacAlgList(void);
static void TimeF(int mode);
static bool CheckBlockSize(int cipherId, int blockSize);
// Main function
int32_t HITLS_SpeedMain(int argc, char* argv[])
{
int32_t speedret = -1;
SpeedCmdOpt speedOpt = {1, 0, 0, 1, 0, 0, false, 1};
speedret = HITLS_APP_OptBegin(argc, argv, g_speedOpts);
if (speedret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to init option parser\n");
goto EXIT;
}
if ((speedret = HandleOpt(&speedOpt)) != HITLS_APP_SUCCESS) {
goto EXIT;
}
if (speedOpt.seconds <= 0) {
AppPrintError("Invalid seconds: %d (must be positive)\n", speedOpt.seconds);
speedret = HITLS_APP_OPT_VALUE_INVALID;
goto EXIT;
}
if (speedOpt.threads < 1 || speedOpt.threads > MAX_THREADS) {
AppPrintError("Invalid thread count: %d (must be 1-%d)\n", speedOpt.threads, MAX_THREADS);
speedret = HITLS_APP_OPT_VALUE_INVALID;
goto EXIT;
}
if (speedOpt.bytes > 0 && speedOpt.cipherId != 0 && !CheckBlockSize(speedOpt.cipherId, speedOpt.bytes)) {
AppPrintError("Block size %d is invalid for cipher %s\n", speedOpt.bytes, GetCipherName(speedOpt.cipherId));
speedret = HITLS_APP_OPT_VALUE_INVALID;
goto EXIT;
}
if (speedOpt.cipherId != 0) {
if (speedOpt.autoBlock || speedOpt.bytes == 0) {
RunCipherAutoBlockTest(&speedOpt);
} else {
RunCipherBenchmark(&speedOpt);
}
}
if (speedOpt.macId != 0) {
if (speedOpt.autoBlock || speedOpt.bytes == 0) {
RunMacAutoBlockTest(&speedOpt);
} else {
RunMacBenchmark(&speedOpt);
}
}
EXIT:
return speedret;
}
// Command line option processing entry
static int32_t HandleOpt(SpeedCmdOpt* speedOpt)
{
int32_t ret = ParseSpeedOpts(speedOpt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return ValidateSpeedOpts(speedOpt);
}
// Parse command line options
static int32_t ParseSpeedOpts(SpeedCmdOpt* speedOpt)
{
int32_t optType;
const char* val;
speedOpt->seconds = SECONDS;
speedOpt->threads = 1;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
switch (optType) {
case HITLS_APP_OPT_EOF: break;
case HITLS_APP_OPT_ERR:
AppPrintError("speed: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_OPT_HELP:
HITLS_APP_OptHelpPrint(g_speedOpts);
return HITLS_APP_HELP;
case HITLS_APP_OPT_ENC:
speedOpt->encTag = 1; break;
case HITLS_APP_OPT_DEC:
speedOpt->encTag = 0; break;
case HITLS_APP_OPT_CIPHER_ALG:
if ((speedOpt->cipherId = GetCipherId(HITLS_APP_OptGetValueStr())) == -1)
{return HITLS_APP_OPT_VALUE_INVALID;} break;
case HITLS_APP_OPT_MAC:
if ((speedOpt->macId = GetHMacId(HITLS_APP_OptGetValueStr())) == -1)
{return HITLS_APP_OPT_VALUE_INVALID;} break;
case HITLS_APP_OPT_SECONDS:
val = HITLS_APP_OptGetValueStr();
if (val != NULL) {speedOpt->seconds = atoi(val);}
break;
case HITLS_APP_OPT_BYTES:
val = HITLS_APP_OptGetValueStr();
if (val != NULL) {speedOpt->bytes = atoi(val);}
break;
case HITLS_APP_OPT_AUTO_BLOCK:
speedOpt->autoBlock = true;
break;
case HITLS_APP_OPT_THREADS:
val = HITLS_APP_OptGetValueStr();
ValidateThreadsParam(speedOpt, val);
break;
default:
AppPrintError("Unknown option type: %d\n", optType);
return HITLS_APP_OPT_UNKOWN;
}
}
return HITLS_APP_SUCCESS;
}
// Handle the validation of the threads parameter
static void ValidateThreadsParam(SpeedCmdOpt* speedOpt, const char* val)
{
if (val == NULL) {
return;
}
speedOpt->threads = atoi(val);
if (speedOpt->threads < 1) {
speedOpt->threads = 1;
}
if (speedOpt->threads > MAX_THREADS) {
speedOpt->threads = MAX_THREADS;
}
}
// Validate command line option validity
static int32_t ValidateSpeedOpts(SpeedCmdOpt* speedOpt)
{
if (HITLS_APP_GetRestOptNum() != 0) {
AppPrintError("Extra arguments given.\n");
AppPrintError("enc: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
if (speedOpt->cipherId == 0 && speedOpt->macId == 0) {
AppPrintError("Please specify either --cipher or --mac algorithm\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (speedOpt->seconds <= 0) {
speedOpt->seconds = SECONDS;
}
return HITLS_APP_SUCCESS;
}
// Cipher algorithm benchmark test entry (custom block size)
static void RunCipherBenchmark(const SpeedCmdOpt* opt)
{
printf("=== Cipher Custom Block Test: %s ===\n", GetCipherName(opt->cipherId));
RunCipherSingleBlockTest(opt, opt->bytes, 0);
}
// Single block size cipher benchmark test
static void RunCipherSingleBlockTest(const SpeedCmdOpt* opt, int blockSize, int index)
{
double duration = (opt->seconds > 0) ? opt->seconds : SECONDS;
bool isEnc = (opt->encTag == 1);
const char* algName = GetCipherName(opt->cipherId);
pthread_t* threads = (pthread_t*)malloc(sizeof(pthread_t) * opt->threads);
ThreadResource* threadRes = (ThreadResource*)malloc(sizeof(ThreadResource) * opt->threads);
if (threads == NULL || threadRes == NULL) {
AppPrintError("Failed to allocate memory for threads\n");
free(threads);
free(threadRes);
throughputs[index] = 0.0;
return;
}
for (int i = 0; i < opt->threads; i++) {
threadRes[i].opt = opt;
threadRes[i].blockSize = blockSize;
threadRes[i].threadId = i;
threadRes[i].threadOps = 0;
threadRes[i].threadTotalBytes = 0;
threadRes[i].threadElapsed = 0.0;
threadRes[i].in = threadRes[i].out = NULL;
threadRes[i].cipherCtx = NULL;
}
TimeF(0);
for (int i = 0; i < opt->threads; i++) {
if (pthread_create(&threads[i], NULL, CipherThreadWork, (void*)&threadRes[i]) != 0) {
AppPrintError("Failed to create cipher thread %d\n", i);
for (int j = 0; j < i; j++) {
pthread_join(threads[j], NULL);
}
free(threads);
free(threadRes);
throughputs[index] = 0.0;
return;
}
}
for (int i = 0; i < opt->threads; i++) {
pthread_join(threads[i], NULL);
}
double totalSpeed = 0.0;
uint64_t totalOps = 0;
double totalElapsed = 0.0;
AggregateThreadResults(opt, threadRes, &totalSpeed, &totalOps, &totalElapsed);
printf("Doing %s %s for %.1fs on %d size blocks: %llu %s's in %.2fs ", isEnc ? "Encryption" : "Decryption",
algName, duration, blockSize, (unsigned long long)totalOps, algName, totalElapsed);
printf("speed=%.2f KB/s (%.2f MB/s)\n", totalSpeed, totalSpeed / KB_TO_MB_FACTOR);
throughputs[index] = totalSpeed;
free(threads);
free(threadRes);
}
// Automatic multi-block size cipher benchmark test
static void RunCipherAutoBlockTest(const SpeedCmdOpt* opt)
{
printf("=== Cipher Auto Block Test: %s ===\n", GetCipherName(opt->cipherId));
for (int i = 0; i < TEST_BLOCK_SIZES_LEN; i++) {
int blockSize = TEST_BLOCK_SIZES[i];
RunCipherSingleBlockTest(opt, blockSize, i);
}
printf("=== Cipher Performance Summary (units: KB/s) ===\n");
printf("%-15s", "Algorithm");
for (int i = 0; i < TEST_BLOCK_SIZES_LEN; i++) {
printf("%-15d", TEST_BLOCK_SIZES[i]);
}
printf("\n%-15s", GetCipherName(opt->cipherId));
for (int i = 0; i < TEST_BLOCK_SIZES_LEN; i++) {
printf("%-15.2f", throughputs[i]);
}
printf("\n");
}
// Get cipher algorithm key length
static int GetCipherKeyLen(int32_t cipherId)
{
switch (cipherId) {
case CRYPT_CIPHER_AES192_CBC: case CRYPT_CIPHER_AES192_CTR:
case CRYPT_CIPHER_AES192_ECB: case CRYPT_CIPHER_AES192_GCM:
case CRYPT_CIPHER_AES192_CFB: case CRYPT_CIPHER_AES192_OFB:
return AES192_KEY_LENGTH;
case CRYPT_CIPHER_AES256_CBC: case CRYPT_CIPHER_AES256_CTR:
case CRYPT_CIPHER_AES256_ECB: case CRYPT_CIPHER_AES256_GCM:
case CRYPT_CIPHER_AES256_CFB: case CRYPT_CIPHER_AES256_OFB:
return AES256_KEY_LENGTH;
default:
return AES128_KEY_LENGTH;
}
}
// Initialize cipher resources
static int InitCipherResources(ThreadResource* res)
{
const SpeedCmdOpt* opt = res->opt;
int threadId = res->threadId;
int blockSize = res->blockSize;
bool isEnc = (opt->encTag == 1);
memset_s(res->key, MAX_KEY_LEN, 0, MAX_KEY_LEN);
memset_s(res->iv, IV_LENGTH, 0, IV_LENGTH);
res->in = (unsigned char*)malloc(blockSize);
res->out = (unsigned char*)malloc(blockSize + ENCRYPT_EXTRA_BUFFER_LEN);
if (res->in == NULL || res->out == NULL) {
AppPrintError("Thread %d: Failed to allocate memory\n", threadId);
free(res->in);
free(res->out);
res->in = res->out = NULL;
return CRYPT_FAILURE;
}
memset_s(res->in, blockSize, 0xAA, blockSize);
res->cipherCtx = CRYPT_EAL_CipherNewCtx(opt->cipherId);
if (res->cipherCtx == NULL) {
AppPrintError("Thread %d: Failed to create cipher ctx\n", threadId);
free(res->in);
free(res->out);
res->in = res->out = NULL;
return CRYPT_FAILURE;
}
int keyLen = GetCipherKeyLen(opt->cipherId);
if (CRYPT_EAL_CipherInit(res->cipherCtx, res->key, keyLen, res->iv, IV_LENGTH, isEnc) != CRYPT_SUCCESS) {
AppPrintError("Thread %d: Cipher init failed (alg: %s, keyLen: %d)\n",
threadId, GetCipherName(opt->cipherId), keyLen);
FreeCipherResources(res);
return CRYPT_FAILURE;
}
return CRYPT_SUCCESS;
}
// Free cipher resources
static void FreeCipherResources(ThreadResource* res)
{
memset_s(res->key, MAX_KEY_LEN, 0, MAX_KEY_LEN);
memset_s(res->iv, IV_LENGTH, 0, IV_LENGTH);
if (res->cipherCtx != NULL) {
CRYPT_EAL_CipherFreeCtx(res->cipherCtx);
res->cipherCtx = NULL;
}
if (res->in != NULL) {
free(res->in);
res->in = NULL;
}
if (res->out != NULL) {
free(res->out);
res->out = NULL;
}
}
// Cipher thread work function
static void* CipherThreadWork(void* arg)
{
ThreadResource* res = (ThreadResource*)arg;
const SpeedCmdOpt* opt = res->opt;
int blockSize = res->blockSize;
int duration = (opt->seconds > 0) ? opt->seconds : SECONDS;
if (InitCipherResources(res) != CRYPT_SUCCESS) {
goto EXIT;
}
struct timeval threadStart;
gettimeofday(&threadStart, NULL);
uint64_t threadOps = 0;
size_t threadTotalBytes = 0;
while (1) {
struct timeval current;
gettimeofday(¤t, NULL);
double elapsed = (current.tv_sec - threadStart.tv_sec) +
(current.tv_usec - threadStart.tv_usec) / USEC_TO_SEC_FACTOR;
if (elapsed >= duration) {break;}
uint32_t outlen = blockSize + ENCRYPT_EXTRA_BUFFER_LEN;
if (CRYPT_EAL_CipherUpdate(res->cipherCtx, res->in, blockSize, res->out, &outlen) != CRYPT_SUCCESS) {
AppPrintError("Thread %d: Cipher update failed (block size: %d)\n", res->threadId, blockSize);
break;
}
threadOps++;
threadTotalBytes += blockSize;
}
struct timeval threadEnd;
gettimeofday(&threadEnd, NULL);
res->threadOps = threadOps;
res->threadTotalBytes = threadTotalBytes;
res->threadElapsed = (threadEnd.tv_sec - threadStart.tv_sec) +
(threadEnd.tv_usec - threadStart.tv_usec) / USEC_TO_SEC_FACTOR;
EXIT:
FreeCipherResources(res);
return NULL;
}
// MAC algorithm benchmark test entry (custom block size)
static void RunMacBenchmark(const SpeedCmdOpt* opt)
{
printf("=== MAC Custom Block Test: %s ===\n", GetMacName(opt->macId));
RunMacSingleBlockTest(opt, opt->bytes, 0);
}
// Single block size MAC benchmark test
static void RunMacSingleBlockTest(const SpeedCmdOpt* opt, int blockSize, int index)
{
double duration = (opt->seconds > 0) ? opt->seconds : SECONDS;
const char* algName = GetMacName(opt->macId);
pthread_t* threads = (pthread_t*)malloc(sizeof(pthread_t) * opt->threads);
ThreadResource* threadRes = (ThreadResource*)malloc(sizeof(ThreadResource) * opt->threads);
if (threads == NULL || threadRes == NULL) {
AppPrintError("Failed to allocate memory for threads\n");
free(threads);
free(threadRes);
throughputs[index] = 0.0;
return;
}
for (int i = 0; i < opt->threads; i++) {
threadRes[i].opt = opt;
threadRes[i].blockSize = blockSize;
threadRes[i].threadId = i;
threadRes[i].threadOps = 0;
threadRes[i].threadTotalBytes = 0;
threadRes[i].threadElapsed = 0.0;
threadRes[i].data = NULL;
threadRes[i].macCtx = NULL;
}
TimeF(0);
for (int i = 0; i < opt->threads; i++) {
if (pthread_create(&threads[i], NULL, MacThreadWork, (void*)&threadRes[i]) != 0) {
AppPrintError("Failed to create MAC thread %d\n", i);
for (int j = 0; j < i; j++) {
pthread_join(threads[j], NULL);
}
free(threads);
free(threadRes);
throughputs[index] = 0.0;
return;
}
}
for (int i = 0; i < opt->threads; i++) {
pthread_join(threads[i], NULL);
}
double totalSpeed = 0.0;
uint64_t totalOps = 0;
double totalElapsed = 0.0;
AggregateThreadResults(opt, threadRes, &totalSpeed, &totalOps, &totalElapsed);
printf("Doing %s for %.1fs on %d size blocks: %llu %s's in %.2fs ",
algName, duration, blockSize, (unsigned long long)totalOps, algName, totalElapsed);
printf("speed=%.2f KB/s (%.2f MB/s)\n", totalSpeed, totalSpeed / KB_TO_MB_FACTOR);
throughputs[index] = totalSpeed;
free(threads);
free(threadRes);
}
// Automatic multi-block size MAC benchmark test
static void RunMacAutoBlockTest(const SpeedCmdOpt* opt)
{
printf("=== MAC Auto Block Test: %s ===\n", GetMacName(opt->macId));
for (int i = 0; i < TEST_BLOCK_SIZES_LEN; i++) {
int blockSize = TEST_BLOCK_SIZES[i];
RunMacSingleBlockTest(opt, blockSize, i);
}
printf("=== MAC Performance Summary (units: KB/s) ===\n");
printf("%-15s", "Algorithm");
for (int i = 0; i < TEST_BLOCK_SIZES_LEN; i++) {
printf("%-15d", TEST_BLOCK_SIZES[i]);
}
printf("\n%-15s", GetMacName(opt->macId));
for (int i = 0; i < TEST_BLOCK_SIZES_LEN; i++) {
printf("%-15.2f", throughputs[i]);
}
printf("\n");
}
// Get MAC algorithm key length
static uint32_t GetMacKeyLen(int32_t macId)
{
switch (macId) {
case CRYPT_MAC_HMAC_SHA384:
case CRYPT_MAC_HMAC_SHA512:
return HMAC_SHA512_KEY_LENGTH;
default:
return DEFAULT_HMAC_KEY_LENGTH;
}
}
// Initialize MAC resources
static int InitMacResources(ThreadResource* res)
{
const SpeedCmdOpt* opt = res->opt;
int threadId = res->threadId;
int blockSize = res->blockSize;
memset_s(res->key, MAX_KEY_LEN, 0, MAX_KEY_LEN);
memset_s(res->mac, MAX_MAC_LEN, 0, MAX_MAC_LEN);
res->data = (unsigned char*)malloc(blockSize);
if (res->data == NULL) {
AppPrintError("Thread %d: Failed to allocate memory for MAC test\n", threadId);
return CRYPT_FAILURE;
}
memset_s(res->data, blockSize, 0xAA, blockSize);
res->macCtx = CRYPT_EAL_MacNewCtx(opt->macId);
if (res->macCtx == NULL) {
AppPrintError("Thread %d: Failed to create MAC ctx\n", threadId);
free(res->data);
res->data = NULL;
return CRYPT_FAILURE;
}
uint32_t keyLen = GetMacKeyLen(opt->macId);
if (CRYPT_EAL_MacInit(res->macCtx, res->key, keyLen) != CRYPT_SUCCESS) {
AppPrintError("Thread %d: MAC init failed\n", threadId);
FreeMacResources(res);
return CRYPT_FAILURE;
}
return CRYPT_SUCCESS;
}
// Free MAC resources
static void FreeMacResources(ThreadResource* res)
{
memset_s(res->key, MAX_KEY_LEN, 0, MAX_KEY_LEN);
memset_s(res->mac, MAX_MAC_LEN, 0, MAX_MAC_LEN);
if (res->macCtx != NULL) {
CRYPT_EAL_MacFreeCtx(res->macCtx);
res->macCtx = NULL;
}
if (res->data != NULL) {
free(res->data);
res->data = NULL;
}
}
// MAC thread work function
static void* MacThreadWork(void* arg)
{
ThreadResource* res = (ThreadResource*)arg;
const SpeedCmdOpt* opt = res->opt;
int blockSize = res->blockSize;
int duration = (opt->seconds > 0) ? opt->seconds : SECONDS;
if (InitMacResources(res) != CRYPT_SUCCESS) {
goto EXIT;
}
struct timeval threadStart;
gettimeofday(&threadStart, NULL);
uint64_t threadOps = 0;
size_t threadTotalBytes = 0;
while (1) {
struct timeval current;
gettimeofday(¤t, NULL);
double elapsed = (current.tv_sec - threadStart.tv_sec) +
(current.tv_usec - threadStart.tv_usec) / USEC_TO_SEC_FACTOR;
if (elapsed >= duration) {
break;
}
if (CRYPT_EAL_MacUpdate(res->macCtx, res->data, blockSize) != CRYPT_SUCCESS) {
AppPrintError("Thread %d: MAC update failed\n", res->threadId);
break;
}
threadOps++;
threadTotalBytes += blockSize;
}
uint32_t macLen = sizeof(res->mac);
if (CRYPT_EAL_MacFinal(res->macCtx, res->mac, &macLen) != CRYPT_SUCCESS) {
AppPrintError("Thread %d: MAC final failed\n", res->threadId);
goto EXIT;
}
struct timeval threadEnd;
gettimeofday(&threadEnd, NULL);
res->threadOps = threadOps;
res->threadTotalBytes = threadTotalBytes;
res->threadElapsed = (threadEnd.tv_sec - threadStart.tv_sec) +
(threadEnd.tv_usec - threadStart.tv_usec) / USEC_TO_SEC_FACTOR;
EXIT:
FreeMacResources(res);
return NULL;
}
// Aggregate thread results
static void AggregateThreadResults(const SpeedCmdOpt* opt, ThreadResource* res,
double* totalSpeed, uint64_t* totalOps, double* totalElapsed)
{
*totalOps = 0;
size_t totalBytes = 0;
*totalElapsed = 0.0;
for (int i = 0; i < opt->threads; i++) {
*totalOps += res[i].threadOps;
totalBytes += res[i].threadTotalBytes;
if (res[i].threadElapsed > *totalElapsed) {
*totalElapsed = res[i].threadElapsed;
}
}
if (*totalElapsed <= MIN_ELAPSED_THRESHOLD) {
*totalElapsed = MIN_ELAPSED_THRESHOLD;
}
*totalSpeed = (totalBytes / KB_TO_MB_FACTOR) / *totalElapsed;
}
// Get cipher algorithm ID by name
static int32_t GetCipherId(const char* name)
{
for (size_t i = 0; i < sizeof(g_cIdList) / sizeof(g_cIdList[0]); i++) {
if (strcmp(g_cIdList[i].cipherAlgName, name) == 0) {
return g_cIdList[i].cipherId;
}
}
PrintCipherAlgList();
return -1;
}
// Get MAC algorithm ID by name
static int32_t GetHMacId(const char* mdName)
{
for (size_t i = 0; i < sizeof(g_mIdList) / sizeof(g_mIdList[0]); i++) {
if (strcmp(g_mIdList[i].macAlgName, mdName) == 0) {
return g_mIdList[i].macId;
}
}
PrintHMacAlgList();
return -1;
}
// Get cipher algorithm name by ID
static const char* GetCipherName(int32_t cipherId)
{
for (size_t i = 0; i < sizeof(g_cIdList) / sizeof(g_cIdList[0]); i++) {
if (g_cIdList[i].cipherId == cipherId) {
return g_cIdList[i].cipherAlgName;
}
}
return "unknown_cipher";
}
// Get MAC algorithm name by ID
static const char* GetMacName(int32_t macId)
{
for (size_t i = 0; i < sizeof(g_mIdList) / sizeof(g_mIdList[0]); i++) {
if (g_mIdList[i].macId == macId) {
return g_mIdList[i].macAlgName;
}
}
return "unknown_mac";
}
// Print supported cipher algorithm list
static void PrintCipherAlgList(void)
{
AppPrintError("The current version supports only the following cipher algorithms:\n");
for (size_t i = 0; i < sizeof(g_cIdList) / sizeof(g_cIdList[0]); i++) {
AppPrintError("%-19s", g_cIdList[i].cipherAlgName);
if ((i + 1) % CIPHER_ALG_PER_LINE == 0 && i != sizeof(g_cIdList) / sizeof(g_cIdList[0]) - 1) {
AppPrintError("\n");
}
}
AppPrintError("\n");
}
// Print supported MAC algorithm list
static void PrintHMacAlgList(void)
{
AppPrintError("The current version supports only the following digest algorithms:\n");
for (size_t i = 0; i < sizeof(g_mIdList) / sizeof(g_mIdList[0]); i++) {
AppPrintError("%-19s", g_mIdList[i].macAlgName);
if ((i + 1) % CIPHER_ALG_PER_LINE == 0 && i != sizeof(g_mIdList) / sizeof(g_mIdList[0]) - 1) {
AppPrintError("\n");
}
}
AppPrintError("\n");
}
// Time recording function
static void TimeF(int mode)
{
if (mode == 0) {
gettimeofday(&g_startTimeval, NULL);
}
}
// Block size validity check
static bool CheckBlockSize(int cipherId, int blockSize)
{
switch (cipherId) {
case CRYPT_CIPHER_AES128_CBC: case CRYPT_CIPHER_AES192_CBC:
case CRYPT_CIPHER_AES256_CBC: case CRYPT_CIPHER_SM4_CBC:
case CRYPT_CIPHER_AES128_ECB: case CRYPT_CIPHER_SM4_ECB:
return (blockSize % IV_LENGTH) == 0;
default:
return blockSize > 0;
}
}
| 2401_83913325/openHiTLS_1 | apps/src/app_speed.c | C | unknown | 29,279 |
/*
* 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 "app_tls_common.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <fcntl.h>
#include "securec.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_utils.h"
#include "app_provider.h"
#include "app_keymgmt.h"
#include "app_utils.h"
#include "hitls_config.h"
#include "hitls_cert.h"
#include "hitls_pki_cert.h"
#include "hitls_type.h"
#include "cipher_suite.h"
#include "hitls_session.h"
#include "hitls_cert_type.h"
#include "bsl_bytes.h"
#include "bsl_sal.h"
#include "bsl_err.h"
#include "sal_file.h"
#define HEARTBEAT_STR "heartbeat"
APP_ProtocolType ParseProtocolType(const char *protocolStr)
{
if (protocolStr == NULL) {
return APP_PROTOCOL_TLS; // Default to TLS protocol
}
if (strcmp(protocolStr, "tls") == 0) {
return APP_PROTOCOL_TLS;
} else if (strcmp(protocolStr, "tlcp") == 0) {
return APP_PROTOCOL_TLCP;
} else if (strcmp(protocolStr, "dtlcp") == 0) {
return APP_PROTOCOL_DTLCP;
}
return APP_PROTOCOL_TLS; /* Default fallback */
}
HITLS_Config *CreateProtocolConfig(APP_ProtocolType protocol, AppProvider *provider)
{
HITLS_Config *config = NULL;
switch (protocol) {
case APP_PROTOCOL_TLS:
config = HITLS_CFG_ProviderNewTLSConfig(APP_GetCurrent_LibCtx(), provider->providerAttr);
break;
case APP_PROTOCOL_TLCP:
config = HITLS_CFG_ProviderNewTLCPConfig(APP_GetCurrent_LibCtx(), provider->providerAttr);
break;
case APP_PROTOCOL_DTLCP:
config = HITLS_CFG_ProviderNewDTLCPConfig(APP_GetCurrent_LibCtx(), provider->providerAttr);
break;
default:
AppPrintError("Unsupported protocol type: %d\n", protocol);
return NULL;
}
if (config == NULL) {
AppPrintError("Failed to create protocol configuration\n");
}
#ifdef HITLS_APP_SM_MODE
int32_t ret = HITLS_CFG_SetSessionTicketSupport(config, false);
if (ret != HITLS_SUCCESS) {
HITLS_CFG_FreeConfig(config);
AppPrintError("Failed to set session ticket support, errCode: 0x%x.\n", ret);
return NULL;
}
#endif
return config;
}
int ConfigureCipherSuites(HITLS_Config *config, const char *cipherStr, APP_ProtocolType protocol)
{
if (config == NULL || cipherStr == NULL) {
return HITLS_APP_INVALID_ARG;
}
int32_t ret;
uint32_t protocolVersion = 0;
bool needVersionCheck = false;
// Only check version for TLCP/DTLCP, TLS does not need version check
if (protocol == APP_PROTOCOL_DTLCP || protocol == APP_PROTOCOL_TLCP) {
protocolVersion = HITLS_VERSION_TLCP_DTLCP11;
needVersionCheck = true;
}
// Support multiple cipher suites separated by colon
// Example: "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"
char *cipherStrCopy = BSL_SAL_Malloc(strlen(cipherStr) + 1);
if (cipherStrCopy == NULL) {
AppPrintError("Failed to allocate memory for cipher string\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
strcpy_s(cipherStrCopy, strlen(cipherStr) + 1, cipherStr);
// Count number of cipher suites (based on colon count)
uint32_t cipherCount = 1;
for (const char *p = cipherStr; *p != '\0'; p++) {
if (*p == ':') {
cipherCount++;
}
}
// Allocate cipher suite array
uint16_t *cipherSuites = BSL_SAL_Malloc(sizeof(uint16_t) * cipherCount);
if (cipherSuites == NULL) {
BSL_SAL_Free(cipherStrCopy);
AppPrintError("Failed to allocate memory for cipher suites\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
// Parse each cipher suite
uint32_t index = 0;
char *token = strtok(cipherStrCopy, ":");
while (token != NULL && index < cipherCount) {
const HITLS_Cipher *cipher = HITLS_CFG_GetCipherSuiteByStdName((const uint8_t *)token);
if (cipher == NULL) {
AppPrintError("Invalid cipher suite: %s\n", token);
BSL_SAL_Free(cipherStrCopy);
BSL_SAL_Free(cipherSuites);
return HITLS_APP_ERR_SET_CIPHER;
}
// Only check version range for TLCP/DTLCP
if (needVersionCheck) {
if (protocolVersion < cipher->minVersion || protocolVersion > cipher->maxVersion) {
AppPrintError("Protocol (%d) not in cipher suite version range [%d, %d]!\n",
protocolVersion, cipher->minVersion, cipher->maxVersion);
BSL_SAL_Free(cipherStrCopy);
BSL_SAL_Free(cipherSuites);
return HITLS_APP_ERR_SET_CIPHER;
}
}
ret = HITLS_CFG_GetCipherSuite(cipher, &cipherSuites[index]);
if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to get cipher suite for %s: 0x%x\n", token, ret);
BSL_SAL_Free(cipherStrCopy);
BSL_SAL_Free(cipherSuites);
return HITLS_APP_ERR_SET_CIPHER;
}
index++;
token = strtok(NULL, ":");
}
// Set cipher suite array
ret = HITLS_CFG_SetCipherSuites(config, cipherSuites, index);
if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to set cipher suites: 0x%x\n", ret);
BSL_SAL_Free(cipherStrCopy);
BSL_SAL_Free(cipherSuites);
return HITLS_APP_ERR_SET_CIPHER;
}
BSL_SAL_Free(cipherStrCopy);
BSL_SAL_Free(cipherSuites);
return HITLS_APP_SUCCESS;
}
typedef struct {
const char *name;
BSL_ParseFormat format;
} FormatMapEntry;
static const FormatMapEntry FORMAT_MAP[] = {
{"ASN1", BSL_FORMAT_ASN1},
{"PEM", BSL_FORMAT_PEM},
};
const char *GetFormatName(BSL_ParseFormat format)
{
for (size_t i = 0; i < sizeof(FORMAT_MAP)/sizeof(FORMAT_MAP[0]); ++i) {
if (FORMAT_MAP[i].format == format) {
return FORMAT_MAP[i].name;
}
}
return NULL;
}
HITLS_X509_Cert *LoadCertFromFile(const char *certFile, BSL_ParseFormat format, AppProvider *provider)
{
if (certFile == NULL) {
return NULL;
}
const char *formatName = GetFormatName(format);
uint8_t *data = NULL;
uint32_t dataLen = 0;
HITLS_X509_Cert *cert = NULL;
int32_t ret = BSL_SAL_ReadFile(certFile, &data, &dataLen);
if (ret != BSL_SUCCESS) {
return NULL;
}
BSL_Buffer encode = {data, dataLen};
ret = HITLS_X509_ProviderCertParseBuff(APP_GetCurrent_LibCtx(), provider->providerAttr, formatName, &encode, &cert);
if (ret != HITLS_SUCCESS) {
BSL_SAL_Free(data);
AppPrintError("Failed to load certificate from %s: 0x%x\n", certFile, ret);
return NULL;
}
BSL_SAL_Free(data);
return cert;
}
#ifdef HITLS_APP_SM_MODE
static int32_t GetPkeyCtxFromUuid(AppProvider *provider, HITLS_APP_SM_Param *smParam, char *uuid,
CRYPT_EAL_PkeyCtx **ctx)
{
HITLS_APP_KeyInfo keyInfo = {0};
HITLS_APP_SM_Param param = {0};
(void)memcpy_s(¶m, sizeof(HITLS_APP_SM_Param), smParam, sizeof(HITLS_APP_SM_Param));
param.uuid = uuid;
int32_t ret = HITLS_APP_FindKey(provider, ¶m, CRYPT_PKEY_SM2, &keyInfo);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to find key, errCode: 0x%x\n", ret);
return ret;
}
*ctx = keyInfo.pkeyCtx;
return HITLS_APP_SUCCESS;
}
#endif
static CRYPT_EAL_PkeyCtx *LoadKeyFromFile(APP_CertConfig *certConfig, bool isSignKey)
{
char *keyFile = isSignKey ? certConfig->tlcpSignKey : certConfig->tlcpEncKey;
BSL_ParseFormat format = certConfig->keyFormat;
const char *password = certConfig->keyPass;
AppProvider *provider = certConfig->provider;
if (keyFile == NULL) {
return NULL;
}
CRYPT_EAL_PkeyCtx *pkey = NULL;
#ifdef HITLS_APP_SM_MODE
if (isSignKey && certConfig->smParam->smTag == 1) {
int32_t ret = GetPkeyCtxFromUuid(provider, certConfig->smParam, keyFile, &pkey);
if (ret == HITLS_APP_SUCCESS) {
return pkey;
}
}
#endif
/* Load private key using the existing utility function */
char *pass = NULL;
if (password != NULL) {
size_t len = strlen(password) + 1;
pass = BSL_SAL_Malloc(len);
if (pass != NULL) {
strcpy_s(pass, len, password);
}
}
pkey = HITLS_APP_ProviderLoadPrvKey(APP_GetCurrent_LibCtx(), provider->providerAttr, keyFile, format, &pass);
if (pkey == NULL) {
AppPrintError("Failed to load private key from %s\n", keyFile);
}
if (pass != NULL) {
BSL_SAL_ClearFree(pass, strlen(pass));
}
return pkey;
}
int ConfCertVerification(HITLS_Config *config, APP_CertConfig *certConfig,
bool verifyPeer, int verifyDepth)
{
if (config == NULL) {
return HITLS_APP_INVALID_ARG;
}
int ret = HITLS_SUCCESS;
bool hasLoadedCA = false;
/* Load CA certificates */
if (certConfig && certConfig->caFile) {
HITLS_X509_Cert *ca_cert = LoadCertFromFile(certConfig->caFile, certConfig->certFormat, certConfig->provider);
if (ca_cert != NULL) {
ret = HITLS_CFG_AddCertToStore(config, ca_cert, TLS_CERT_STORE_TYPE_DEFAULT, true);
if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to add CA certificate to store: 0x%x\n", ret);
HITLS_X509_CertFree(ca_cert);
return HITLS_APP_ERR_LOAD_CA;
}
HITLS_X509_CertFree(ca_cert);
hasLoadedCA = true;
}
}
if (certConfig && certConfig->caChain) {
HITLS_X509_List *certlist = NULL;
ret = HITLS_X509_CertParseBundleFile(certConfig->certFormat, certConfig->caChain, &certlist);
if (ret != BSL_SUCCESS) {
(void)AppPrintError("Failed to parse certificate <%s>, errCode = %d.\n", certConfig->caChain, ret);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_Cert **cert = BSL_LIST_First(certlist);
while (cert != NULL) {
ret = HITLS_CFG_AddCertToStore(config, *cert, TLS_CERT_STORE_TYPE_DEFAULT, true);
if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to add CA-chain certificate to store: 0x%x\n", ret);
ret = HITLS_APP_ERR_LOAD_CA;
break;
}
cert = BSL_LIST_Next(certlist);
}
BSL_LIST_FREE(certlist, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
hasLoadedCA = true;
}
/* If no CA certificate is configured, load default CA path */
if (!hasLoadedCA) {
ret = HITLS_CFG_LoadDefaultCAPath(config);
if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to load default CA path: 0x%x\n", ret);
// Don't return error, just log warning - allow to continue without CA if needed
}
}
ret = HITLS_CFG_SetVerifyNoneSupport(config, !verifyPeer);
if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to disable server verification: 0x%x\n", ret);
return HITLS_APP_ERR_SET_VERIFY;
}
ret = HITLS_CFG_SetClientVerifySupport(config, verifyPeer);
if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to set client verification: 0x%x\n", ret);
return HITLS_APP_ERR_SET_VERIFY;
}
/* Set verification depth */
if (verifyDepth > 0) {
ret = HITLS_CFG_SetVerifyDepth(config, verifyDepth);
if (ret != HITLS_SUCCESS) {
AppPrintError("Failed to set verification depth: 0x%x\n", ret);
return HITLS_APP_ERR_SET_VERIFY;
}
}
return HITLS_APP_SUCCESS;
}
int ConfigureTLCPCertificates(HITLS_Config *config, APP_CertConfig *certConfig)
{
if (config == NULL || certConfig == NULL) {
return HITLS_APP_INVALID_ARG;
}
int ret = HITLS_SUCCESS;
/* Configure signature certificate */
if (certConfig->tlcpSignCert && certConfig->tlcpSignKey) {
HITLS_X509_Cert *sign_cert = LoadCertFromFile(certConfig->tlcpSignCert, certConfig->certFormat,
certConfig->provider);
CRYPT_EAL_PkeyCtx *sign_key = LoadKeyFromFile(certConfig, true);
if (sign_cert && sign_key) {
ret = HITLS_CFG_SetTlcpCertificate(config, sign_cert, false, false); /* Signature cert */
if (ret != HITLS_SUCCESS) {
HITLS_X509_CertFree(sign_cert);
CRYPT_EAL_PkeyFreeCtx(sign_key);
AppPrintError("Failed to set TLCP signature certificate: 0x%x\n", ret);
return HITLS_APP_ERR_SET_TLCP_CERT;
}
ret = HITLS_CFG_SetTlcpPrivateKey(config, sign_key, false, false);
if (ret != HITLS_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(sign_key);
AppPrintError("Failed to set TLCP signature private key: 0x%x\n", ret);
return HITLS_APP_ERR_SET_TLCP_CERT;
}
} else {
HITLS_X509_CertFree(sign_cert);
CRYPT_EAL_PkeyFreeCtx(sign_key);
return HITLS_APP_ERR_SET_TLCP_CERT;
}
}
/* Configure encryption certificate */
if (certConfig->tlcpEncCert && certConfig->tlcpEncKey) {
HITLS_X509_Cert *enc_cert = LoadCertFromFile(certConfig->tlcpEncCert, certConfig->certFormat,
certConfig->provider);
CRYPT_EAL_PkeyCtx *enc_key = LoadKeyFromFile(certConfig, false);
if (enc_cert && enc_key) {
ret = HITLS_CFG_SetTlcpCertificate(config, enc_cert, false, true); /* Encryption cert */
if (ret != HITLS_SUCCESS) {
HITLS_X509_CertFree(enc_cert);
CRYPT_EAL_PkeyFreeCtx(enc_key);
AppPrintError("Failed to set TLCP encryption certificate: 0x%x\n", ret);
return HITLS_APP_ERR_SET_TLCP_CERT;
}
ret = HITLS_CFG_SetTlcpPrivateKey(config, enc_key, false, true);
if (ret != HITLS_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(enc_key);
AppPrintError("Failed to set TLCP encryption private key: 0x%x\n", ret);
return HITLS_APP_ERR_SET_TLCP_CERT;
}
} else {
HITLS_X509_CertFree(enc_cert);
CRYPT_EAL_PkeyFreeCtx(enc_key);
return HITLS_APP_ERR_SET_TLCP_CERT;
}
}
return HITLS_APP_SUCCESS;
}
int CreateTCPSocket(APP_NetworkAddr *addr, int timeout)
{
if (addr == NULL || addr->host == NULL) {
return -1;
}
int sockfd = BSL_SAL_Socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
AppPrintError("Failed to create socket: %s\n", strerror(errno));
return -1;
}
/* Set socket timeout if specified */
if (timeout > 0) {
struct timeval tv;
tv.tv_sec = timeout;
tv.tv_usec = 0;
BSL_SAL_SetSockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
BSL_SAL_SetSockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
}
/* Connect to server */
struct sockaddr_in serverAdd;
memset_s(&serverAdd, sizeof(serverAdd), 0, sizeof(serverAdd));
serverAdd.sin_family = AF_INET;
serverAdd.sin_port = htons(addr->port);
if (inet_pton(AF_INET, addr->host, &serverAdd.sin_addr) <= 0) {
/* Try to resolve hostname */
struct hostent *hostEntry = gethostbyname(addr->host);
if (hostEntry == NULL) {
AppPrintError("Failed to resolve hostname: %s\n", addr->host);
BSL_SAL_SockClose(sockfd);
return -1;
}
memcpy_s(&serverAdd.sin_addr, sizeof(serverAdd.sin_addr), hostEntry->h_addr_list[0], hostEntry->h_length);
}
if (BSL_SAL_SockConnect(sockfd, (BSL_SAL_SockAddr)&serverAdd, sizeof(serverAdd)) < 0) {
AppPrintError("Failed to connect to %s:%d: %s\n", addr->host, addr->port, strerror(errno));
BSL_SAL_SockClose(sockfd);
return -1;
}
return sockfd;
}
int CreateUDPSocket(APP_NetworkAddr *addr, int timeout)
{
(void)timeout; /* Suppress unused parameter warning */
if (addr == NULL || addr->host == NULL) {
return -1;
}
int sockfd = BSL_SAL_Socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
AppPrintError("Failed to create UDP socket: %s\n", strerror(errno));
return -1;
}
/* Connect UDP socket to server */
struct sockaddr_in serverAdd;
memset_s(&serverAdd, sizeof(serverAdd), 0, sizeof(serverAdd));
serverAdd.sin_family = AF_INET;
serverAdd.sin_port = htons(addr->port);
if (inet_pton(AF_INET, addr->host, &serverAdd.sin_addr) <= 0) {
/* Try to resolve hostname */
struct hostent *hostEntry = gethostbyname(addr->host);
if (hostEntry == NULL) {
AppPrintError("Failed to resolve hostname: %s\n", addr->host);
BSL_SAL_SockClose(sockfd);
return -1;
}
memcpy_s(&serverAdd.sin_addr, sizeof(serverAdd.sin_addr), hostEntry->h_addr_list[0], hostEntry->h_length);
}
if (BSL_SAL_SockConnect(sockfd, (BSL_SAL_SockAddr)&serverAdd, sizeof(serverAdd)) < 0) {
AppPrintError("Failed to connect UDP socket to %s:%d: %s\n", addr->host, addr->port, strerror(errno));
BSL_SAL_SockClose(sockfd);
return -1;
}
return sockfd;
}
int CreateTCPListenSocket(APP_NetworkAddr *addr, int backlog)
{
int sockfd = BSL_SAL_Socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
AppPrintError("Failed to create listen socket: %s\n", strerror(errno));
return -1;
}
/* Set socket options */
int opt = 1;
BSL_SAL_SetSockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
/* Bind to address */
struct sockaddr_in bindAddr;
memset_s(&bindAddr, sizeof(bindAddr), 0, sizeof(bindAddr));
bindAddr.sin_family = AF_INET;
bindAddr.sin_port = htons(addr->port);
if (addr->host && strcmp(addr->host, "0.0.0.0") != 0) {
if (inet_pton(AF_INET, addr->host, &bindAddr.sin_addr) <= 0) {
AppPrintError("Invalid bind address: %s\n", addr->host);
BSL_SAL_SockClose(sockfd);
return -1;
}
} else {
bindAddr.sin_addr.s_addr = INADDR_ANY;
}
if (BSL_SAL_SockBind(sockfd, (BSL_SAL_SockAddr)&bindAddr, sizeof(bindAddr)) < 0) {
AppPrintError("Failed to bind to %s:%d: %s\n",
addr->host ? addr->host : "0.0.0.0", addr->port, strerror(errno));
BSL_SAL_SockClose(sockfd);
return -1;
}
if (BSL_SAL_SockListen(sockfd, backlog) < 0) {
AppPrintError("Failed to listen: %s\n", strerror(errno));
BSL_SAL_SockClose(sockfd);
return -1;
}
return sockfd;
}
int CreateUDPListenSocket(APP_NetworkAddr *addr, int timeout)
{
int sockfd = BSL_SAL_Socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
AppPrintError("Failed to create UDP listen socket: %s\n", strerror(errno));
return -1;
}
if (timeout > 0) {
struct timeval tv;
tv.tv_sec = timeout;
tv.tv_usec = 0;
BSL_SAL_SetSockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
BSL_SAL_SetSockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
}
/* Bind to address */
struct sockaddr_in bindAddr;
memset_s(&bindAddr, sizeof(bindAddr), 0, sizeof(bindAddr));
bindAddr.sin_family = AF_INET;
bindAddr.sin_port = htons(addr->port);
if (addr->host && strcmp(addr->host, "0.0.0.0") != 0) {
if (inet_pton(AF_INET, addr->host, &bindAddr.sin_addr) <= 0) {
AppPrintError("Invalid bind address: %s\n", addr->host);
BSL_SAL_SockClose(sockfd);
return -1;
}
} else {
bindAddr.sin_addr.s_addr = INADDR_ANY;
}
if (BSL_SAL_SockBind(sockfd, (BSL_SAL_SockAddr)&bindAddr, sizeof(bindAddr)) < 0) {
AppPrintError("Failed to bind UDP to %s:%d: %s\n",
addr->host ? addr->host : "0.0.0.0", addr->port, strerror(errno));
BSL_SAL_SockClose(sockfd);
return -1;
}
return sockfd;
}
int AcceptTCPConnection(int listenFd)
{
struct sockaddr_in clientAddr;
socklen_t addrLen = sizeof(clientAddr);
int flags = fcntl(listenFd, F_GETFL, 0);
fcntl(listenFd, F_SETFL, flags | O_NONBLOCK);
int clientFd = accept(listenFd, (struct sockaddr *)&clientAddr, &addrLen);
if (clientFd < 0) {
return -1;
}
/* Print client information */
char clientIp[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &clientAddr.sin_addr, clientIp, INET_ADDRSTRLEN);
AppPrintInfo("Accepted connection from %s:%d\n", clientIp, ntohs(clientAddr.sin_port));
return clientFd;
}
void PrintConnectionInfo(HITLS_Ctx *ctx, bool showState)
{
if (ctx == NULL) {
return;
}
/* Print protocol version */
uint16_t version;
if (HITLS_GetNegotiatedVersion(ctx, &version) == HITLS_SUCCESS) {
AppPrintInfo("Protocol version: ");
switch (version) {
case HITLS_VERSION_TLS12:
AppPrintInfo("TLSv1.2\n");
break;
case HITLS_VERSION_TLS13:
AppPrintInfo("TLSv1.3\n");
break;
case HITLS_VERSION_DTLS12:
AppPrintInfo("DTLSv1.2\n");
break;
case HITLS_VERSION_TLCP_DTLCP11:
AppPrintInfo("TLCP v1.1\n");
break;
default:
AppPrintInfo("Unknown (0x%04x)\n", version);
break;
}
}
/* Print cipher suite */
const HITLS_Cipher *cipher = HITLS_GetCurrentCipher(ctx);
if (cipher != NULL) {
AppPrintError("Cipher: %p\n", (const void*)cipher);
}
if (showState) {
PrintHandshakeState(ctx);
}
}
void PrintHandshakeState(HITLS_Ctx *ctx)
{
if (ctx == NULL) {
return;
}
uint32_t state;
if (HITLS_GetHandShakeState(ctx, &state) == HITLS_SUCCESS) {
const char *stateStr = HITLS_GetStateString(state);
AppPrintInfo("Handshake state: %s\n", stateStr ? stateStr : "Unknown");
}
}
int ParseConnectString(const char *connectStr, APP_NetworkAddr *addr)
{
if (connectStr == NULL || addr == NULL) {
return HITLS_APP_INVALID_ARG;
}
size_t len = strlen(connectStr) + 1;
char *strCopy = BSL_SAL_Malloc(len);
if (strCopy == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
strcpy_s(strCopy, len, connectStr);
char *colon_pos = strrchr(strCopy, ':');
if (colon_pos == NULL) {
/* No port specified, use default */
addr->host = strCopy;
addr->port = 443; /* Default HTTPS port */
return HITLS_APP_SUCCESS;
}
*colon_pos = '\0';
size_t host_len = strlen(strCopy) + 1;
addr->host = BSL_SAL_Malloc(host_len);
if (addr->host != NULL) {
strcpy_s(addr->host, host_len, strCopy);
}
addr->port = atoi(colon_pos + 1);
BSL_SAL_Free(strCopy);
if (addr->port <= 0 || addr->port > 65535) {
BSL_SAL_Free(addr->host);
addr->host = NULL;
return HITLS_APP_INVALID_ARG;
}
return HITLS_APP_SUCCESS;
}
#ifdef HITLS_APP_SM_MODE
int32_t GetHeartBeat(uint8_t *buffer, uint32_t *len)
{
if (buffer == NULL || len == NULL || *len < APP_HEARTBEAT_LEN) {
AppPrintError("Invalid buffer or length.\n");
return HITLS_APP_INVALID_ARG;
}
int64_t time = 0;
int ret = HITLS_APP_GetTime(&time);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to get time, errCode: 0x%x.\n", ret);
return ret;
}
BSL_Uint64ToByte(time, (uint8_t *)&time);
const char *heartBeat = HEARTBEAT_STR;
(void)memcpy_s(buffer, APP_HEARTBEAT_LEN, heartBeat, strlen(heartBeat));
(void)memcpy_s(buffer + strlen(heartBeat), APP_HEARTBEAT_LEN - strlen(heartBeat), &time, sizeof(time));
*len = APP_HEARTBEAT_LEN;
return HITLS_APP_SUCCESS;
}
int32_t ParseHeartBeat(uint8_t *buffer, uint32_t len)
{
if (buffer == NULL || len != APP_HEARTBEAT_LEN) {
AppPrintError("Invalid buffer or length.\n");
return HITLS_APP_INVALID_ARG;
}
int ret = strncmp((const char *)buffer, HEARTBEAT_STR, strlen(HEARTBEAT_STR));
if (ret != 0) {
AppPrintError("Invalid heartbeat string.\n");
return HITLS_APP_INVALID_ARG;
}
int64_t time = 0;
(void)memcpy_s(&time, sizeof(time), buffer + strlen(HEARTBEAT_STR), sizeof(time));
time = BSL_ByteToUint64((uint8_t *)&time);
return HITLS_APP_SUCCESS;
}
#endif
| 2401_83913325/openHiTLS_1 | apps/src/app_tls_common.c | C | unknown | 25,981 |
/*
* 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 "app_utils.h"
#include <stdio.h>
#include <securec.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include "bsl_sal.h"
#include "bsl_ui.h"
#include "bsl_errno.h"
#include "bsl_buffer.h"
#include "bsl_pem_internal.h"
#include "sal_file.h"
#include "crypt_errno.h"
#include "crypt_eal_codecs.h"
#include "crypt_eal_pkey.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_md.h"
#include "crypt_eal_rand.h"
#include "crypt_codecskey.h"
#include "app_print.h"
#include "app_errno.h"
#include "app_opt.h"
#include "app_list.h"
#include "app_sm.h"
#define DEFAULT_PEM_FILE_SIZE 1024U
#define RSA_PRV_CTX_LEN 8
#define HEX_TO_BYTE 2
#define APP_HEX_HEAD "0x"
#define APP_LINESIZE 255
#define PEM_BEGIN_STR "-----BEGIN "
#define PEM_END_STR "-----END "
#define PEM_TAIL_STR "-----\n"
#define PEM_TAIL_KEY_STR "KEY-----\n"
#define PEM_BEGIN_STR_LEN ((int)(sizeof(PEM_BEGIN_STR) - 1))
#define PEM_END_STR_LEN ((int)(sizeof(PEM_END_STR) - 1))
#define PEM_TAIL_STR_LEN ((int)(sizeof(PEM_TAIL_STR) - 1))
#define PEM_TAIL_KEY_STR_LEN ((int)(sizeof(PEM_TAIL_KEY_STR) - 1))
#define PEM_RSA_PRIVATEKEY_STR "RSA PRIVATE KEY"
#define PEM_RSA_PUBLIC_STR "RSA PUBLIC KEY"
#define PEM_EC_PRIVATEKEY_STR "EC PRIVATE KEY"
#define PEM_PKCS8_PRIVATEKEY_STR "PRIVATE KEY"
#define PEM_PKCS8_PUBLIC_STR "PUBLIC KEY"
#define PEM_ENCRYPTED_PKCS8_PRIVATEKEY_STR "ENCRYPTED PRIVATE KEY"
#define PEM_PROC_TYPE_STR "Proc-Type:"
#define PEM_PROC_TYPE_NUM_STR "4,"
#define PEM_ENCRYPTED_STR "ENCRYPTED"
#define APP_PASS_ARG_STR "pass:"
#define APP_PASS_ARG_STR_LEN ((int)(sizeof(APP_PASS_ARG_STR) - 1))
#define APP_PASS_STDIN_STR "stdin"
#define APP_PASS_STDIN_STR_LEN ((int)(sizeof(APP_PASS_STDIN_STR) - 1))
#define APP_PASS_FILE_STR "file:"
#define APP_PASS_FILE_STR_LEN ((int)(sizeof(APP_PASS_FILE_STR) - 1))
#ifdef HITLS_APP_SM_MODE
#ifndef HITLS_PROVIDER_LIB_NAME
#error "HITLS_PROVIDER_LIB_NAME must be defined by build system"
#endif
#define APP_SM_PROVIDER_NAME HITLS_PROVIDER_LIB_NAME
#define APP_SM_PROVIDER_ATTR "provider=sm"
#endif
#define APP_DEFAULT_PROVIDER_NAME "default"
#define APP_DEFAULT_PROVIDER_ATTR "provider=default"
typedef struct defaultPassCBData {
uint32_t maxLen;
uint32_t minLen;
} APP_DefaultPassCBData;
static int32_t ReadData(const char *path, BSL_PEM_Symbol *symbol, char *fileName, BSL_Buffer *data);
void *ExpandingMem(void *oldPtr, size_t newSize, size_t oldSize)
{
if (newSize <= 0) {
return oldPtr;
}
void *newPtr = BSL_SAL_Calloc(newSize, sizeof(uint8_t));
if (newPtr == NULL) {
return oldPtr;
}
if (oldPtr != NULL) {
if (memcpy_s(newPtr, newSize, oldPtr, oldSize) != 0) {
BSL_SAL_FREE(newPtr);
return oldPtr;
}
BSL_SAL_FREE(oldPtr);
}
return newPtr;
}
int32_t HITLS_APP_CheckPasswd(const uint8_t *password, const uint32_t passwordLen)
{
for (uint32_t i = 0; i < passwordLen; ++i) {
if (password[i] < '!' || password[i] > '~') {
AppPrintError("The password can contain only the following characters:\n");
AppPrintError("a~z A~Z 0~9 ! \" # $ %% & ' ( ) * + , - . / : ; < = > ? @ [ \\ ] ^ _ ` { | } ~\n");
return HITLS_APP_PASSWD_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_DefaultPassCB(BSL_UI *ui, char *buff, uint32_t buffLen, void *callBackData)
{
if (ui == NULL || buff == NULL || buffLen == 1) {
(void)AppPrintError("You have not entered a password.\n");
return BSL_UI_INVALID_DATA_ARG;
}
uint32_t passLen = buffLen - 1;
uint32_t maxLength = 0;
if (callBackData == NULL) {
maxLength = APP_MAX_PASS_LENGTH;
} else {
APP_DefaultPassCBData *data = callBackData;
maxLength = data->maxLen;
}
if (passLen > maxLength) {
HITLS_APP_PrintPassErrlog();
return BSL_UI_INVALID_DATA_RESULT;
}
return BSL_SUCCESS;
}
static int32_t CheckFileSizeByPath(const char *inFilePath, uint32_t *fileSize)
{
size_t getFileSize = 0;
int32_t ret = BSL_SAL_FileLength(inFilePath, &getFileSize);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to get the file size: %d.\n", ret);
return HITLS_APP_UIO_FAIL;
}
if (getFileSize > APP_FILE_MAX_SIZE) {
AppPrintError("File size exceed limit %zukb.\n", APP_FILE_MAX_SIZE_KB);
return HITLS_APP_UIO_FAIL;
}
if (fileSize != NULL) {
*fileSize = (uint32_t)getFileSize;
}
return ret;
}
static char *GetPemKeyFileName(const char *buf, size_t readLen)
{
// -----BEGIN *** KEY-----
if ((strncmp(buf, PEM_BEGIN_STR, PEM_BEGIN_STR_LEN) != 0) || (readLen < PEM_TAIL_KEY_STR_LEN) ||
(strncmp(buf + readLen - PEM_TAIL_KEY_STR_LEN, PEM_TAIL_KEY_STR, PEM_TAIL_KEY_STR_LEN) != 0)) {
return NULL;
}
int32_t len = readLen - PEM_BEGIN_STR_LEN - PEM_TAIL_STR_LEN;
char *name = BSL_SAL_Calloc(len + 1, sizeof(char));
if (name == NULL) {
return name;
}
memcpy_s(name, len, buf + PEM_BEGIN_STR_LEN, len);
name[len] = '\0';
return name;
}
static bool IsNeedEncryped(const char *name, const char *header, uint32_t headerLen)
{
// PKCS8
if (strcmp(name, PEM_ENCRYPTED_PKCS8_PRIVATEKEY_STR) == 0) {
return true;
}
// PKCS1
// Proc-Type: 4, ENCRYPTED
uint32_t offset = 0;
uint32_t len = strlen(PEM_PROC_TYPE_STR);
if (strncmp(header + offset, PEM_PROC_TYPE_STR, len) != 0) {
return false;
}
offset += len + strspn(header + offset + len, " \t");
len = strlen(PEM_PROC_TYPE_NUM_STR);
if ((offset >= headerLen) || (strncmp(header + offset, PEM_PROC_TYPE_NUM_STR, len) != 0)) {
return false;
}
offset += len + strspn(header + offset + len, " \t");
len = strlen(PEM_ENCRYPTED_STR);
if ((offset >= headerLen) || (strncmp(header + offset, PEM_ENCRYPTED_STR, len) != 0)) {
return false;
}
offset += len + strspn(header + offset + len, " \t");
if ((offset >= headerLen) || header[offset] != '\n') {
return false;
}
return true;
}
static void PrintFileOrStdinError(const char *filePath, const char *errStr)
{
if (filePath == NULL) {
AppPrintError("%s.\n", errStr);
} else {
AppPrintError("%s from \"%s\".\n", errStr, filePath);
}
}
static int32_t ReadPemKeyFile(const char *inFilePath, uint8_t **inData, uint32_t *inDataSize, char **name,
bool *isEncrypted)
{
if ((inData == NULL) || (inDataSize == NULL) || (name == NULL)) {
return HITLS_APP_INVALID_ARG;
}
// End after reading the following two strings in sequence:
// -----BEGIN XXX-----
// -----END XXX-----
bool isParseHeader = false;
BSL_Buffer dataBuff = {0};
BSL_PEM_Symbol symbol = {PEM_BEGIN_STR, PEM_END_STR};
int32_t ret = ReadData(inFilePath, &symbol, "key", &dataBuff);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
uint32_t fileSize = dataBuff.dataLen;
char *tmp = (char *)dataBuff.data;
uint32_t readLen = 0;
while (readLen < fileSize) {
uint32_t remain = fileSize - readLen;
char *nextline = memchr(tmp, '\n', remain);
uint32_t curLineLen = (nextline != NULL) ? (uint32_t)(nextline - tmp + 1) : remain;
if (*name == NULL) {
*name = GetPemKeyFileName(tmp, curLineLen);
} else if (curLineLen < PEM_END_STR_LEN && strncmp(tmp, PEM_END_STR, PEM_END_STR_LEN) == 0) {
break; // Read the end of the pem.
} else if (!isParseHeader) {
*isEncrypted = IsNeedEncryped(*name, tmp, curLineLen);
isParseHeader = true;
}
tmp += curLineLen;
readLen += curLineLen;
}
if (readLen == 0 || *name == NULL) {
AppPrintError("Failed to read the pem file.\n");
BSL_SAL_FREE(dataBuff.data);
BSL_SAL_FREE(*name);
return HITLS_APP_STDIN_FAIL;
}
*inData = dataBuff.data;
*inDataSize = readLen;
return HITLS_APP_SUCCESS;
}
static int32_t GetPasswdByFile(const char *passwdArg, size_t passwdArgLen, char **pass)
{
if (passwdArgLen <= APP_PASS_FILE_STR_LEN) {
AppPrintError("Failed to read passwd from file.\n");
return HITLS_APP_INVALID_ARG;
}
// Apply for a new memory and copy the unprocessed character string.
char filePath[PATH_MAX] = {0};
if (strcpy_s(filePath, PATH_MAX - 1, passwdArg + APP_PASS_FILE_STR_LEN) != EOK) {
AppPrintError("Failed to read passwd from file.\n");
return HITLS_APP_SECUREC_FAIL;
}
// Binding the password file UIO.
BSL_UIO *passUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (passUio == NULL) {
AppPrintError("Failed to read passwd from file.\n");
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(passUio, true);
if (BSL_UIO_Ctrl(passUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_READ, filePath) != BSL_SUCCESS) {
AppPrintError("Failed to set infile mode for passwd.\n");
BSL_UIO_Free(passUio);
return HITLS_APP_UIO_FAIL;
}
char *passBuf = (char *)BSL_SAL_Calloc(APP_MAX_PASS_LENGTH + 1 + 1, sizeof(char));
if (passBuf == NULL) {
BSL_UIO_Free(passUio);
AppPrintError("Failed to read passwd from file.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
// When the number of bytes exceeds 1024 bytes, only one more bit is read.
uint32_t passLen = APP_MAX_PASS_LENGTH + 1 + 1;
if (BSL_UIO_Gets(passUio, passBuf, &passLen) != BSL_SUCCESS) {
AppPrintError("Failed to read passwd from file.\n");
BSL_UIO_Free(passUio);
BSL_SAL_FREE(passBuf);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_Free(passUio);
if (passLen <= 0) {
passBuf[0] = '\0';
} else if (passBuf[passLen - 1] == '\n') {
passBuf[passLen - 1] = '\0';
}
*pass = passBuf;
return HITLS_APP_SUCCESS;
}
static char *GetPasswdByStdin(BSL_UI_ReadPwdParam *param)
{
char *pass = (char *)BSL_SAL_Calloc(APP_MAX_PASS_LENGTH + 1, sizeof(char));
if (pass == NULL) {
return NULL;
}
uint32_t passLen = APP_MAX_PASS_LENGTH + 1;
int32_t ret = BSL_UI_ReadPwdUtil(param, pass, &passLen, NULL, NULL);
if (ret != BSL_SUCCESS) {
pass[0] = '\0';
return pass;
}
pass[passLen - 1] = '\0';
return pass;
}
static char *GetStrAfterPreFix(const char *inputArg, uint32_t inputArgLen, uint32_t prefixLen)
{
if (prefixLen > inputArgLen) {
return NULL;
}
uint32_t len = inputArgLen - prefixLen;
char *str = (char *)BSL_SAL_Calloc(len + 1, sizeof(char));
if (str == NULL) {
return NULL;
}
memcpy_s(str, len, inputArg + prefixLen, len);
str[len] = '\0';
return str;
}
int32_t HITLS_APP_ParsePasswd(const char *passArg, char **pass)
{
if (passArg == NULL) {
return HITLS_APP_SUCCESS;
}
if (strncmp(passArg, APP_PASS_ARG_STR, APP_PASS_ARG_STR_LEN) == 0) {
*pass = GetStrAfterPreFix(passArg, strlen(passArg), APP_PASS_ARG_STR_LEN);
} else if (strncmp(passArg, APP_PASS_STDIN_STR, APP_PASS_STDIN_STR_LEN) == 0) {
BSL_UI_ReadPwdParam passParam = { "passwd", NULL, false };
*pass = GetPasswdByStdin(&passParam);
} else if (strncmp(passArg, APP_PASS_FILE_STR, APP_PASS_FILE_STR_LEN) == 0) {
return GetPasswdByFile(passArg, strlen(passArg), pass);
} else {
AppPrintError("The %s password parameter is not supported.\n", passArg);
return HITLS_APP_PASSWD_FAIL;
}
return HITLS_APP_SUCCESS;
}
static CRYPT_EAL_PkeyCtx *ReadPemPrvKey(BSL_Buffer *encode, const char *name, uint8_t *pass, uint32_t passLen)
{
int32_t type = CRYPT_ENCDEC_UNKNOW;
if (strcmp(name, PEM_RSA_PRIVATEKEY_STR) == 0) {
type = CRYPT_PRIKEY_RSA;
} else if (strcmp(name, PEM_EC_PRIVATEKEY_STR) == 0) {
type = CRYPT_PRIKEY_ECC;
} else if (strcmp(name, PEM_PKCS8_PRIVATEKEY_STR) == 0) {
type = CRYPT_PRIKEY_PKCS8_UNENCRYPT;
} else if (strcmp(name, PEM_ENCRYPTED_PKCS8_PRIVATEKEY_STR) == 0) {
type = CRYPT_PRIKEY_PKCS8_ENCRYPT;
}
CRYPT_EAL_PkeyCtx *pkey = NULL;
if (CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, type, encode, pass, passLen, &pkey) != CRYPT_SUCCESS) {
return NULL;
}
return pkey;
}
static CRYPT_EAL_PkeyCtx *ReadPemPubKey(BSL_Buffer *encode, const char *name)
{
int32_t type = CRYPT_ENCDEC_UNKNOW;
if (strcmp(name, PEM_RSA_PUBLIC_STR) == 0) {
type = CRYPT_PUBKEY_RSA;
} else if (strcmp(name, PEM_PKCS8_PUBLIC_STR) == 0) {
type = CRYPT_PUBKEY_SUBKEY;
}
CRYPT_EAL_PkeyCtx *pkey = NULL;
if (CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, type, encode, NULL, 0, &pkey) != CRYPT_SUCCESS) {
return NULL;
}
return pkey;
}
int32_t HITLS_APP_GetPasswd(BSL_UI_ReadPwdParam *param, char **passin, uint8_t **pass, uint32_t *passLen)
{
if (*passin == NULL) {
*passin = GetPasswdByStdin(param);
}
if ((*passin == NULL) || (strlen(*passin) > APP_MAX_PASS_LENGTH) || (strlen(*passin) < APP_MIN_PASS_LENGTH)) {
HITLS_APP_PrintPassErrlog();
return HITLS_APP_PASSWD_FAIL;
}
*pass = (uint8_t *)*passin;
*passLen = strlen(*passin);
return HITLS_APP_SUCCESS;
}
static bool CheckFilePath(const char *filePath)
{
if (filePath == NULL) {
return true;
}
if (strlen(filePath) > PATH_MAX) {
AppPrintError("The maximum length of the file path is %d.\n", PATH_MAX);
return false;
}
return true;
}
static CRYPT_EAL_PkeyCtx *LoadPrvDerKey(const char *inFilePath)
{
static CRYPT_ENCDEC_TYPE encodeType[] = {CRYPT_PRIKEY_ECC, CRYPT_PRIKEY_RSA, CRYPT_PRIKEY_PKCS8_UNENCRYPT};
CRYPT_EAL_PkeyCtx *pkey = NULL;
for (uint32_t i = 0; i < sizeof(encodeType) / sizeof(CRYPT_ENCDEC_TYPE); ++i) {
if (CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, encodeType[i], inFilePath, NULL, 0, &pkey) == CRYPT_SUCCESS) {
break;
}
}
if (pkey == NULL) {
AppPrintError("Failed to read the private key from \"%s\".\n", inFilePath);
return NULL;
}
return pkey;
}
static CRYPT_EAL_PkeyCtx *ProviderLoadPrvDerKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, const char *inFilePath)
{
static CRYPT_PKEY_AlgId encodeType[] = {CRYPT_PKEY_SM2, CRYPT_PKEY_RSA};
const char *encodeTypeStr[] = {"PRIKEY_ECC", "PRIKEY_RSA"};
CRYPT_EAL_PkeyCtx *pkey = NULL;
for (uint32_t i = 0; i < sizeof(encodeType) / sizeof(CRYPT_ENCDEC_TYPE); ++i) {
if (CRYPT_EAL_ProviderDecodeFileKey(libCtx, attrName, encodeType[i], "ASN1", encodeTypeStr[i], inFilePath,
NULL, &pkey) == CRYPT_SUCCESS) {
break;
}
}
if (pkey == NULL) {
AppPrintError("Failed to read the private key from \"%s\".\n", inFilePath);
return NULL;
}
return pkey;
}
static CRYPT_EAL_PkeyCtx *ProviderReadPemPrvKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *encode,
uint8_t *pass, uint32_t passLen)
{
CRYPT_EAL_PkeyCtx *pkey = NULL;
BSL_Buffer passBuf = { pass, passLen };
if (CRYPT_EAL_ProviderDecodeBuffKey(libCtx, attrName, BSL_CID_UNKNOWN, "PEM", NULL,
encode, &passBuf, &pkey) != CRYPT_SUCCESS) {
return NULL;
}
return pkey;
}
CRYPT_EAL_PkeyCtx *HITLS_APP_ProviderLoadPrvKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName,
const char *inFilePath, BSL_ParseFormat informat, char **passin)
{
if (inFilePath == NULL && informat == BSL_FORMAT_ASN1) {
AppPrintError("The \"-inform DER or -keyform DER\" requires using the \"-in\" option.\n");
return NULL;
}
if (!CheckFilePath(inFilePath)) {
return NULL;
}
if (informat == BSL_FORMAT_ASN1) {
return ProviderLoadPrvDerKey(libCtx, attrName, inFilePath);
}
char *prvkeyName = NULL;
bool isEncrypted = false;
uint8_t *data = NULL;
uint32_t dataLen = 0;
if (ReadPemKeyFile(inFilePath, &data, &dataLen, &prvkeyName, &isEncrypted) != HITLS_APP_SUCCESS) {
PrintFileOrStdinError(inFilePath, "Failed to read the private key");
return NULL;
}
uint8_t *pass = NULL;
uint32_t passLen = 0;
BSL_UI_ReadPwdParam passParam = { "passwd", inFilePath, false };
if (isEncrypted && (HITLS_APP_GetPasswd(&passParam, passin, &pass, &passLen) != HITLS_APP_SUCCESS)) {
BSL_SAL_FREE(data);
BSL_SAL_FREE(prvkeyName);
return NULL;
}
BSL_Buffer encode = { data, dataLen };
CRYPT_EAL_PkeyCtx *pkey = ProviderReadPemPrvKey(libCtx, attrName, &encode, pass, passLen);
if (pkey == NULL) {
PrintFileOrStdinError(inFilePath, "Failed to read the private key");
}
(void)memset_s(pass, passLen, 0, passLen);
BSL_SAL_FREE(data);
BSL_SAL_FREE(prvkeyName);
return pkey;
}
CRYPT_EAL_PkeyCtx *HITLS_APP_LoadPrvKey(const char *inFilePath, BSL_ParseFormat informat, char **passin)
{
if (inFilePath == NULL && informat == BSL_FORMAT_ASN1) {
AppPrintError("The \"-inform DER or -keyform DER\" requires using the \"-in\" option.\n");
return NULL;
}
if (!CheckFilePath(inFilePath)) {
return NULL;
}
if (informat == BSL_FORMAT_ASN1) {
return LoadPrvDerKey(inFilePath);
}
char *prvkeyName = NULL;
bool isEncrypted = false;
uint8_t *data = NULL;
uint32_t dataLen = 0;
if (ReadPemKeyFile(inFilePath, &data, &dataLen, &prvkeyName, &isEncrypted) != HITLS_APP_SUCCESS) {
PrintFileOrStdinError(inFilePath, "Failed to read the private key");
return NULL;
}
uint8_t *pass = NULL;
uint32_t passLen = 0;
BSL_UI_ReadPwdParam passParam = { "passwd", inFilePath, false };
if (isEncrypted && (HITLS_APP_GetPasswd(&passParam, passin, &pass, &passLen) != HITLS_APP_SUCCESS)) {
BSL_SAL_FREE(data);
BSL_SAL_FREE(prvkeyName);
return NULL;
}
BSL_Buffer encode = { data, dataLen };
CRYPT_EAL_PkeyCtx *pkey = ReadPemPrvKey(&encode, prvkeyName, pass, passLen);
if (pkey == NULL) {
PrintFileOrStdinError(inFilePath, "Failed to read the private key");
}
(void)memset_s(pass, passLen, 0, passLen);
BSL_SAL_FREE(data);
BSL_SAL_FREE(prvkeyName);
return pkey;
}
CRYPT_EAL_PkeyCtx *HITLS_APP_LoadPubKey(const char *inFilePath, BSL_ParseFormat informat)
{
if (informat != BSL_FORMAT_PEM) {
AppPrintError("Reading public key from non-PEM files is not supported.\n");
return NULL;
}
char *pubKeyName = NULL;
uint8_t *data = NULL;
uint32_t dataLen = 0;
bool isEncrypted = false;
if (!CheckFilePath(inFilePath) ||
(ReadPemKeyFile(inFilePath, &data, &dataLen, &pubKeyName, &isEncrypted) != HITLS_APP_SUCCESS)) {
PrintFileOrStdinError(inFilePath, "Failed to read the public key");
return NULL;
}
BSL_Buffer encode = { data, dataLen };
CRYPT_EAL_PkeyCtx *pkey = ReadPemPubKey(&encode, pubKeyName);
if (pkey == NULL) {
PrintFileOrStdinError(inFilePath, "Failed to read the public key");
}
BSL_SAL_FREE(data);
BSL_SAL_FREE(pubKeyName);
return pkey;
}
int32_t HITLS_APP_PrintPubKey(CRYPT_EAL_PkeyCtx *pkey, const char *outFilePath, BSL_ParseFormat outformat)
{
if (!CheckFilePath(outFilePath)) {
return HITLS_APP_INVALID_ARG;
}
BSL_Buffer pubKeyBuf = { 0 };
if (CRYPT_EAL_EncodeBuffKey(pkey, NULL, outformat, CRYPT_PUBKEY_SUBKEY, &pubKeyBuf) != CRYPT_SUCCESS) {
AppPrintError("Failed to export the public key.\n");
return HITLS_APP_ENCODE_KEY_FAIL;
}
BSL_UIO *wPubKeyUio = HITLS_APP_UioOpen(outFilePath, 'w', 0);
if (wPubKeyUio == NULL) {
BSL_SAL_FREE(pubKeyBuf.data);
return HITLS_APP_UIO_FAIL;
}
int32_t ret = HITLS_APP_OptWriteUio(wPubKeyUio, pubKeyBuf.data, pubKeyBuf.dataLen, HITLS_APP_FORMAT_PEM);
BSL_SAL_FREE(pubKeyBuf.data);
BSL_UIO_SetIsUnderlyingClosedByUio(wPubKeyUio, true);
BSL_UIO_Free(wPubKeyUio);
return ret;
}
int32_t HITLS_APP_PrintPrvKey(CRYPT_EAL_PkeyCtx *pkey, const char *outFilePath, BSL_ParseFormat outformat,
int32_t cipherAlgCid, char **passout)
{
if (!CheckFilePath(outFilePath)) {
return HITLS_APP_INVALID_ARG;
}
BSL_UIO *wPrvUio = HITLS_APP_UioOpen(outFilePath, 'w', 0);
if (wPrvUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
AppKeyPrintParam param = { outFilePath, outformat, cipherAlgCid, false, false};
int32_t ret = HITLS_APP_PrintPrvKeyByUio(wPrvUio, pkey, ¶m, passout);
BSL_UIO_SetIsUnderlyingClosedByUio(wPrvUio, true);
BSL_UIO_Free(wPrvUio);
return ret;
}
int32_t HITLS_APP_PrintPrvKeyByUio(BSL_UIO *uio, CRYPT_EAL_PkeyCtx *pkey, AppKeyPrintParam *printKeyParam,
char **passout)
{
int32_t ret = printKeyParam->text ? CRYPT_EAL_PrintPrikey(0, pkey, uio) : HITLS_APP_SUCCESS;
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to print the private key text, errCode = 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
if (printKeyParam->noout) {
return HITLS_APP_SUCCESS;
}
int32_t type =
printKeyParam->cipherAlgCid != CRYPT_CIPHER_MAX ? CRYPT_PRIKEY_PKCS8_ENCRYPT : CRYPT_PRIKEY_PKCS8_UNENCRYPT;
uint8_t *pass = NULL;
uint32_t passLen = 0;
BSL_UI_ReadPwdParam passParam = { "passwd", printKeyParam->name, true };
if ((type == CRYPT_PRIKEY_PKCS8_ENCRYPT) &&
(HITLS_APP_GetPasswd(&passParam, passout, &pass, &passLen) != HITLS_APP_SUCCESS)) {
return HITLS_APP_PASSWD_FAIL;
}
CRYPT_Pbkdf2Param param = { 0 };
param.pbesId = BSL_CID_PBES2;
param.pbkdfId = BSL_CID_PBKDF2;
param.hmacId = CRYPT_MAC_HMAC_SHA256;
param.symId = printKeyParam->cipherAlgCid;
param.pwd = pass;
param.saltLen = DEFAULT_SALTLEN;
param.pwdLen = passLen;
param.itCnt = DEFAULT_ITCNT;
CRYPT_EncodeParam paramEx = { CRYPT_DERIVE_PBKDF2, ¶m };
BSL_Buffer prvKeyBuf = { 0 };
if (CRYPT_EAL_EncodeBuffKey(pkey, ¶mEx, printKeyParam->outformat, type, &prvKeyBuf) != CRYPT_SUCCESS) {
AppPrintError("Failed to export the private key.\n");
return HITLS_APP_ENCODE_KEY_FAIL;
}
ret = HITLS_APP_OptWriteUio(uio, prvKeyBuf.data, prvKeyBuf.dataLen, HITLS_APP_FORMAT_PEM);
BSL_SAL_FREE(prvKeyBuf.data);
return ret;
}
int32_t HITLS_APP_GetAndCheckCipherOpt(const char *name, int32_t *symId)
{
if (symId == NULL) {
return HITLS_APP_INVALID_ARG;
}
uint32_t cid = (uint32_t)HITLS_APP_GetCidByName(name, HITLS_APP_LIST_OPT_CIPHER_ALG);
if (cid == CRYPT_CIPHER_MAX) {
(void)AppPrintError("%s: Use the [list -cipher-algorithms] command to view supported encryption algorithms.\n",
HITLS_APP_GetProgName());
return HITLS_APP_OPT_UNKOWN;
}
if (!CRYPT_EAL_CipherIsValidAlgId(cid)) {
AppPrintError("%s: %s ciphers not supported.\n", HITLS_APP_GetProgName(), name);
return HITLS_APP_OPT_UNKOWN;
}
uint32_t isAeadId = 1;
if (CRYPT_EAL_CipherGetInfo((CRYPT_CIPHER_AlgId)cid, CRYPT_INFO_IS_AEAD, &isAeadId) != CRYPT_SUCCESS) {
AppPrintError("%s: The encryption algorithm is not supported\n", HITLS_APP_GetProgName());
return HITLS_APP_INVALID_ARG;
}
if (isAeadId == 1) {
AppPrintError("%s: The AEAD encryption algorithm is not supported\n", HITLS_APP_GetProgName());
return HITLS_APP_INVALID_ARG;
}
*symId = cid;
return HITLS_APP_SUCCESS;
}
static int32_t ReadPemByUioSymbol(BSL_UIO *memUio, BSL_UIO *rUio, BSL_PEM_Symbol *symbol)
{
int32_t ret = HITLS_APP_UIO_FAIL;
char buf[APP_LINESIZE + 1];
uint32_t lineLen;
bool hasHead = false;
uint32_t writeMemLen;
int64_t dataLen = 0;
while (true) {
lineLen = APP_LINESIZE + 1;
(void)memset_s(buf, lineLen, 0, lineLen);
// Reads a row of data.
if ((BSL_UIO_Gets(rUio, buf, &lineLen) != BSL_SUCCESS) || (lineLen == 0)) {
break;
}
ret = BSL_UIO_Ctrl(rUio, BSL_UIO_GET_READ_NUM, sizeof(int64_t), &dataLen);
if (ret != BSL_SUCCESS || dataLen > APP_FILE_MAX_SIZE) {
AppPrintError("The maximum file size is %zukb.\n", APP_FILE_MAX_SIZE_KB);
ret = HITLS_APP_UIO_FAIL;
break;
}
if (!hasHead) {
// Check whether it is the head.
if (strncmp(buf, symbol->head, strlen(symbol->head)) != 0) {
continue;
}
if (BSL_UIO_Puts(memUio, (const char *)buf, &writeMemLen) != BSL_SUCCESS || writeMemLen != lineLen) {
break;
}
hasHead = true;
continue;
}
// Copy the intermediate content.
if (BSL_UIO_Puts(memUio, (const char *)buf, &writeMemLen) != BSL_SUCCESS || writeMemLen != lineLen) {
break;
}
// Check whether it is the tail.
if (strncmp(buf, symbol->tail, strlen(symbol->tail)) == 0) {
ret = HITLS_APP_SUCCESS;
break;
}
}
return ret;
}
static int32_t ReadPemFromStdin(BSL_BufMem **data, BSL_PEM_Symbol *symbol)
{
int32_t ret = HITLS_APP_UIO_FAIL;
BSL_UIO *memUio = BSL_UIO_New(BSL_UIO_MemMethod());
if (memUio == NULL) {
return ret;
}
// Read from stdin or file.
BSL_UIO *rUio = HITLS_APP_UioOpen(NULL, 'r', 1);
if (rUio == NULL) {
BSL_UIO_Free(memUio);
return ret;
}
BSL_UIO_SetIsUnderlyingClosedByUio(rUio, true);
ret = ReadPemByUioSymbol(memUio, rUio, symbol);
BSL_UIO_Free(rUio);
if (ret == HITLS_APP_SUCCESS) {
if (BSL_UIO_Ctrl(memUio, BSL_UIO_MEM_GET_PTR, sizeof(BSL_BufMem *), data) == BSL_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(memUio, false);
BSL_SAL_Free(BSL_UIO_GetCtx(memUio));
BSL_UIO_SetCtx(memUio, NULL);
} else {
ret = HITLS_APP_UIO_FAIL;
}
}
BSL_UIO_Free(memUio);
return ret;
}
static int32_t ReadFileData(const char *path, BSL_Buffer *data)
{
int32_t ret = CheckFileSizeByPath(path, NULL);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = BSL_SAL_ReadFile(path, &data->data, &data->dataLen);
if (ret != BSL_SUCCESS) {
AppPrintError("Read file failed: %s.\n", path);
}
return ret;
}
static int32_t ReadData(const char *path, BSL_PEM_Symbol *symbol, char *fileName, BSL_Buffer *data)
{
if (path == NULL) {
BSL_BufMem *buf = NULL;
if (ReadPemFromStdin(&buf, symbol) != HITLS_APP_SUCCESS) {
AppPrintError("Failed to read %s from stdin.\n", fileName);
return HITLS_APP_UIO_FAIL;
}
data->data = (uint8_t *)buf->data;
data->dataLen = buf->length;
BSL_SAL_Free(buf);
return HITLS_APP_SUCCESS;
} else {
return ReadFileData(path, data);
}
}
HITLS_X509_Cert *HITLS_APP_LoadCert(const char *inPath, BSL_ParseFormat inform)
{
if (inPath == NULL && inform == BSL_FORMAT_ASN1) {
AppPrintError("Reading DER files from stdin is not supported.\n");
return NULL;
}
if (!CheckFilePath(inPath)) {
AppPrintError("Invalid cert path: \"%s\".", inPath == NULL ? "" : inPath);
return NULL;
}
BSL_Buffer data = { 0 };
BSL_PEM_Symbol symbol = { BSL_PEM_CERT_BEGIN_STR, BSL_PEM_CERT_END_STR };
int32_t ret = ReadData(inPath, &symbol, "cert", &data);
if (ret != HITLS_APP_SUCCESS) {
return NULL;
}
HITLS_X509_Cert *cert = NULL;
if (HITLS_X509_CertParseBuff(inform, &data, &cert) != 0) {
AppPrintError("Failed to parse cert: \"%s\".\n", inPath == NULL ? "stdin" : inPath);
BSL_SAL_Free(data.data);
return NULL;
}
BSL_SAL_Free(data.data);
return cert;
}
HITLS_X509_Csr *HITLS_APP_LoadCsr(const char *inPath, BSL_ParseFormat inform)
{
if (inPath == NULL && inform == BSL_FORMAT_ASN1) {
AppPrintError("Reading DER files from stdin is not supported.\n");
return NULL;
}
if (!CheckFilePath(inPath)) {
AppPrintError("Invalid csr path: \"%s\".", inPath == NULL ? "" : inPath);
return NULL;
}
BSL_Buffer data = { 0 };
BSL_PEM_Symbol symbol = { BSL_PEM_CERT_REQ_BEGIN_STR, BSL_PEM_CERT_REQ_END_STR };
int32_t ret = ReadData(inPath, &symbol, "csr", &data);
if (ret != HITLS_APP_SUCCESS) {
return NULL;
}
HITLS_X509_Csr *csr = NULL;
if (HITLS_X509_CsrParseBuff(inform, &data, &csr) != 0) {
AppPrintError("Failed to parse csr: \"%s\".\n", inPath == NULL ? "stdin" : inPath);
BSL_SAL_Free(data.data);
return NULL;
}
BSL_SAL_Free(data.data);
return csr;
}
int32_t HITLS_APP_GetAndCheckHashOpt(const char *name, int32_t *hashId)
{
if (hashId == NULL) {
return HITLS_APP_INVALID_ARG;
}
uint32_t cid = (uint32_t)HITLS_APP_GetCidByName(name, HITLS_APP_LIST_OPT_DGST_ALG);
if (cid == BSL_CID_UNKNOWN) {
(void)AppPrintError("%s: Use the [list -digest-algorithms] command to view supported digest algorithms.\n",
HITLS_APP_GetProgName());
return HITLS_APP_OPT_UNKOWN;
}
if (!CRYPT_EAL_MdIsValidAlgId(cid)) {
AppPrintError("%s: %s digest not supported.\n", HITLS_APP_GetProgName(), name);
return HITLS_APP_OPT_UNKOWN;
}
*hashId = cid;
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_PrintText(const BSL_Buffer *csrBuf, const char *outFileName)
{
BSL_UIO *wCsrUio = HITLS_APP_UioOpen(outFileName, 'w', 0);
if (wCsrUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
int32_t ret = HITLS_APP_OptWriteUio(wCsrUio, csrBuf->data, csrBuf->dataLen, HITLS_APP_FORMAT_TEXT);
BSL_UIO_SetIsUnderlyingClosedByUio(wCsrUio, true);
BSL_UIO_Free(wCsrUio);
return ret;
}
CRYPT_EAL_PkeyCtx *HITLS_APP_GenRsaPkeyCtx(uint32_t bits)
{
CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_RSA,
CRYPT_EAL_PKEY_UNKNOWN_OPERATE, "provider=default");
if (pkey == NULL) {
AppPrintError("%s: Failed to initialize the RSA private key.\n", HITLS_APP_GetProgName());
return NULL;
}
CRYPT_EAL_PkeyPara *para = BSL_SAL_Calloc(sizeof(CRYPT_EAL_PkeyPara), 1);
if (para == NULL) {
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
static uint8_t e[] = {0x01, 0x00, 0x01}; // Default E value
para->id = CRYPT_PKEY_RSA;
para->para.rsaPara.bits = bits;
para->para.rsaPara.e = e;
para->para.rsaPara.eLen = sizeof(e);
if (CRYPT_EAL_PkeySetPara(pkey, para) != CRYPT_SUCCESS) {
AppPrintError("%s: Failed to set RSA parameters.\n", HITLS_APP_GetProgName());
BSL_SAL_FREE(para);
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
BSL_SAL_FREE(para);
if (CRYPT_EAL_PkeyGen(pkey) != CRYPT_SUCCESS) {
AppPrintError("%s: Failed to generate the RSA private key.\n", HITLS_APP_GetProgName());
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
int32_t padType = CRYPT_EMSA_PKCSV15;
if (CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_PADDING, &padType, sizeof(padType)) != CRYPT_SUCCESS) {
AppPrintError("%s: Failed to set rsa padding.\n", HITLS_APP_GetProgName());
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
return pkey;
}
void HITLS_APP_PrintPassErrlog(void)
{
AppPrintError("The password length is incorrect. It should be in the range of %d to %d.\n", APP_MIN_PASS_LENGTH,
APP_MAX_PASS_LENGTH);
}
int32_t HITLS_APP_HexToByte(const char *hex, uint8_t **bin, uint32_t *len)
{
uint32_t prefixLen = strlen(APP_HEX_HEAD);
if (strncmp(hex, APP_HEX_HEAD, prefixLen) != 0 || strlen(hex) <= prefixLen) {
AppPrintError("Invalid hex value, should start with '0x'.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
const char *num = hex + prefixLen;
uint32_t hexLen = strlen(num);
// Skip the preceding zeros.
for (uint32_t i = 0; i < hexLen; ++i) {
if (num[i] != '0' && (i + 1) != hexLen) {
num += i;
hexLen -= i;
break;
}
}
*len = (hexLen + 1) / HEX_TO_BYTE;
uint8_t *res = BSL_SAL_Malloc(*len);
if (res == NULL) {
AppPrintError("Allocate memory failed.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
int32_t ret = HITLS_APP_SUCCESS;
if (hexLen % HEX_TO_BYTE == 1) {
char *tmp = BSL_SAL_Malloc(hexLen + 2); // 2: '0' + '\0'
if (tmp == NULL) {
AppPrintError("Allocate memory failed.\n");
BSL_SAL_Free(res);
return HITLS_APP_MEM_ALLOC_FAIL;
}
tmp[0] = '0';
(void)memcpy_s(tmp + 1, hexLen, num, hexLen);
tmp[hexLen + 1] = '\0';
ret = HITLS_APP_StrToHex(tmp, res, len);
BSL_SAL_Free(tmp);
} else {
ret = HITLS_APP_StrToHex(num, res, len);
}
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_Free(res);
return ret;
}
*bin = res;
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_StrToHex(const char *str, uint8_t *hex, uint32_t *hexLen)
{
if (str == NULL || hex == NULL || hexLen == NULL) {
AppPrintError("Invalid input buffer or output buffer.\n");
return HITLS_APP_INVALID_ARG;
}
size_t inLen = strlen(str);
if (inLen == 0 || inLen % 2 != 0 || *hexLen < inLen / 2) { // 2: one byte to two hex chars.
return HITLS_APP_INVALID_ARG;
}
// A group of 2 bytes
for (size_t i = 0; i < inLen; i += 2) {
if (!((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'f') ||
(str[i] >= 'A' && str[i] <= 'F'))) {
AppPrintError("Input string is not a valid hex string.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (!((str[i + 1] >= '0' && str[i + 1] <= '9') || (str[i + 1] >= 'a' && str[i + 1] <= 'f') ||
(str[i + 1] >= 'A' && str[i + 1] <= 'F'))) {
AppPrintError("Input string is not a valid hex string.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
// Formula for converting hex to int: (Hex% 32 + 9)% 25 = int, hexadecimal, 16: high 4 bits.
hex[i / 2] = ((uint8_t)str[i] % 32 + 9) % 25 * 16 + ((uint8_t)str[i + 1] % 32 + 9) % 25;
}
*hexLen = inLen / 2; // 2: one byte to two hex chars.
return HITLS_APP_SUCCESS;
}
static int32_t InitRand(AppInitParam *param)
{
#ifdef HITLS_APP_SM_MODE
pid_t pid = getpid();
char str[32] = {0};
int32_t len = sprintf_s(str, sizeof(str), "%d", pid);
if (len < 0) {
AppPrintError("Failed to set pid, pid = %d.\n", pid);
return HITLS_APP_INVALID_ARG;
}
if (param->smParam->smTag == 1 && param->randAlgId == CRYPT_RAND_SHA256) {
param->randAlgId = CRYPT_RAND_SM4_CTR_DF;
}
int32_t ret = CRYPT_EAL_ProviderRandInitCtx(APP_GetCurrent_LibCtx(), param->randAlgId,
param->provider->providerAttr, (const uint8_t *)str, len, NULL);
#else
int32_t ret = CRYPT_EAL_ProviderRandInitCtx(APP_GetCurrent_LibCtx(), param->randAlgId,
param->provider->providerAttr, NULL, 0, NULL);
#endif
if (ret != CRYPT_SUCCESS) {
AppPrintError("Failed to init rand ctx, ret: 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
return HITLS_APP_SUCCESS;
}
#ifdef HITLS_APP_SM_MODE
static char *g_smProviderPath = NULL;
static int32_t GetSmProviderPath(void)
{
char *path = HITLS_APP_GetAppPath();
if (path == NULL) {
return HITLS_APP_INVALID_ARG;
}
char *lastSlash = strrchr(path, '/');
if (lastSlash == NULL) {
BSL_SAL_Free(path);
return HITLS_APP_INVALID_ARG;
}
lastSlash[0] = '\0';
g_smProviderPath = path;
return HITLS_APP_SUCCESS;
}
#endif
static int32_t GetProviderParam(AppInitParam *param)
{
if (param->provider->providerName != NULL || param->provider->providerAttr != NULL ||
param->provider->providerPath != NULL) {
return HITLS_APP_SUCCESS;
}
#ifdef HITLS_APP_SM_MODE
if (param->smParam->smTag == 1) {
int32_t ret = GetSmProviderPath();
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
param->provider->providerName = APP_SM_PROVIDER_NAME;
param->provider->providerPath = g_smProviderPath;
param->provider->providerAttr = APP_SM_PROVIDER_ATTR;
return HITLS_APP_SUCCESS;
}
#endif
param->provider->providerName = APP_DEFAULT_PROVIDER_NAME;
param->provider->providerPath = NULL;
param->provider->providerAttr = APP_DEFAULT_PROVIDER_ATTR;
return HITLS_APP_SUCCESS;
}
static void PrintSelfTestErrlog(AppInitParam *param, int32_t ret)
{
#ifdef HITLS_APP_SM_MODE
if (param->smParam->smTag == 1) {
HITLS_APP_SM_PrintLog(ret);
}
#else
(void)param;
(void)ret;
#endif
}
int32_t HITLS_APP_Init(AppInitParam *param)
{
if (param == NULL) {
return HITLS_APP_INVALID_ARG;
}
#ifdef HITLS_APP_SM_MODE
if (param->smParam->smTag == 1) {
param->smParam->status = HITLS_APP_SM_STATUS_INIT;
}
#endif
int32_t ret = GetProviderParam(param);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = HITLS_APP_LoadProvider(param->provider->providerPath, param->provider->providerName);
if (ret != HITLS_APP_SUCCESS) {
PrintSelfTestErrlog(param, ret);
return ret;
}
ret = InitRand(param);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
#ifdef HITLS_APP_SM_MODE
if (param->smParam->smTag == 1) {
ret = HITLS_APP_SM_Init(param->provider, param->smParam->workPath, (char **)¶m->smParam->password,
¶m->smParam->status);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to init sm, errCode: 0x%x.\n", ret);
CRYPT_EAL_RandDeinitEx(APP_GetCurrent_LibCtx());
return ret;
}
param->smParam->passwordLen = strlen((const char *)param->smParam->password);
param->smParam->status = HITLS_APP_SM_STATUS_KEY_PARAMETER_INPUT;
if (g_smProviderPath != NULL) {
BSL_SAL_FREE(g_smProviderPath);
param->provider->providerPath = NULL;
}
}
#endif
return HITLS_APP_SUCCESS;
}
void HITLS_APP_Deinit(AppInitParam *param, int32_t ret)
{
#ifdef HITLS_APP_SM_MODE
if (param != NULL && param->smParam != NULL && param->smParam->smTag == 1) {
if (ret != HITLS_APP_SUCCESS) {
param->smParam->status = HITLS_APP_SM_STATUS_ERROR;
}
if (param->smParam->password != NULL) {
BSL_SAL_ClearFree(param->smParam->password, param->smParam->passwordLen);
param->smParam->password = NULL;
param->smParam->passwordLen = 0;
}
param->smParam->status = HITLS_APP_SM_STATUS_CLOSE;
}
#else
(void)param;
(void)ret;
#endif
CRYPT_EAL_RandDeinitEx(APP_GetCurrent_LibCtx());
}
int32_t HITLS_APP_GetTime(int64_t *time)
{
if (time == NULL) {
AppPrintError("Invalid time pointer.\n");
return HITLS_APP_INVALID_ARG;
}
BSL_TIME sysTime = {0};
int32_t ret = BSL_SAL_SysTimeGet(&sysTime);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to get system time, errCode: 0x%x.\n", ret);
return HITLS_APP_SAL_FAIL;
}
int64_t utcTime = 0;
ret = BSL_SAL_DateToUtcTimeConvert(&sysTime, &utcTime);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to convert system time to utc time, errCode: 0x%x.\n", ret);
return HITLS_APP_SAL_FAIL;
}
*time = utcTime;
return HITLS_APP_SUCCESS;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_utils.c | C | unknown | 40,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 "app_verify.h"
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include "string.h"
#include "securec.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "app_function.h"
#include "bsl_list.h"
#include "app_errno.h"
#include "app_opt.h"
#include "app_print.h"
#include "app_conf.h"
#include "app_utils.h"
#include "crypt_eal_rand.h"
#include "hitls_pki_errno.h"
typedef enum OptionChoice {
HITLS_APP_OPT_VERIFY_ERR = -1,
HITLS_APP_OPT_VERIFY_EOF = 0,
HITLS_APP_OPT_VERIFY_CERTS = HITLS_APP_OPT_VERIFY_EOF,
HITLS_APP_OPT_VERIFY_HELP = 1,
HITLS_APP_OPT_VERIFY_CAFILE,
HITLS_APP_OPT_VERIFY_VERBOSE,
HITLS_APP_OPT_VERIFY_NOKEYUSAGE
} HITLSOptType;
const HITLS_CmdOption g_verifyOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"nokeyusage", HITLS_APP_OPT_VERIFY_NOKEYUSAGE, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Set not to verify keyUsage"},
{"CAfile", HITLS_APP_OPT_VERIFY_CAFILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input ca file"},
{"verbose", HITLS_APP_OPT_VERIFY_VERBOSE, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print extra information"},
{"certs", HITLS_APP_OPT_VERIFY_CERTS, HITLS_APP_OPT_VALUETYPE_PARAMTERS, "Input certs"},
{NULL, 0, 0, NULL}
};
static bool g_verbose = false;
static bool g_noVerifyKeyUsage = false;
void PrintCertErr(HITLS_X509_Cert *cert)
{
if (!g_verbose) {
return;
}
BSL_Buffer subjectName = { NULL, 0 };
if (HITLS_X509_CertCtrl(cert, HITLS_X509_GET_SUBJECT_DN_STR, &subjectName, sizeof(BSL_Buffer)) ==
HITLS_PKI_SUCCESS) {
(void)AppPrintError("%s\n", subjectName.data);
BSL_SAL_FREE(subjectName.data);
}
}
bool CheckCertKeyUsage(HITLS_X509_Cert *cert, const char *certfile, uint32_t usage)
{
if (g_noVerifyKeyUsage) {
return true;
}
uint32_t keyUsage = 0;
int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_GET_KUSAGE, &keyUsage, sizeof(keyUsage));
if (ret != HITLS_PKI_SUCCESS) {
(void)AppPrintError("Failed to get the key usage of file %s, errCode = %d.\n", certfile, ret);
return false;
}
// Check only if the keyusage extension is present.
if (keyUsage == HITLS_X509_EXT_KU_NONE) {
return true;
}
if ((keyUsage & usage) == 0) {
PrintCertErr(cert);
(void)AppPrintError("Failed to check the key usage of file %s.\n", certfile);
return false;
}
return true;
}
int32_t InitVerify(HITLS_X509_StoreCtx *store, const char *cafile)
{
int32_t depth = 20; // HITLS_X509_STORECTX_SET_PARAM_DEPTH can be set to a maximum of 20
int32_t ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_PARAM_DEPTH, &depth, sizeof(int32_t));
if (ret != HITLS_PKI_SUCCESS) {
(void)AppPrintError("Failed to set the maximum depth of the certificate chain, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
int64_t timeval = BSL_SAL_CurrentSysTimeGet();
ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_TIME, &timeval, sizeof(timeval));
if (ret != HITLS_PKI_SUCCESS) {
(void)AppPrintError("Failed to set time of the certificate chain, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_List *certlist = NULL;
ret = HITLS_X509_CertParseBundleFile(BSL_FORMAT_PEM, cafile, &certlist);
if (ret != HITLS_PKI_SUCCESS) {
(void)AppPrintError("Failed to parse certificate <%s>, errCode = %d.\n", cafile, ret);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_Cert **cert = BSL_LIST_First(certlist);
while (cert != NULL) {
if (!CheckCertKeyUsage(*cert, cafile, HITLS_X509_EXT_KU_KEY_CERT_SIGN)) {
ret = HITLS_APP_X509_FAIL;
break;
}
ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, *cert, sizeof(HITLS_X509_Cert *));
if (ret != HITLS_PKI_SUCCESS) {
PrintCertErr(*cert);
ret = HITLS_APP_X509_FAIL;
(void)AppPrintError("Failed to add the certificate <%s> to the trust store, errCode = %d.\n", cafile, ret);
break;
}
cert = BSL_LIST_Next(certlist);
}
BSL_LIST_FREE(certlist, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
return ret;
}
static int32_t 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) {
return ret;
}
return ret;
}
static int32_t VerifyCert(HITLS_X509_StoreCtx *storeCtx, const char *fileName)
{
HITLS_X509_Cert *cert = HITLS_APP_LoadCert(fileName, BSL_FORMAT_PEM);
if (cert == NULL) {
return HITLS_APP_X509_FAIL;
}
const char *errStr = fileName == NULL ? "stdin" : fileName;
if (!CheckCertKeyUsage(cert, errStr, HITLS_X509_EXT_KU_KEY_ENCIPHERMENT)) {
HITLS_X509_CertFree(cert);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_List *chain = BSL_LIST_New(sizeof(HITLS_X509_Cert *));
if (chain == NULL) {
AppPrintError("Failed to create the certificate chain from %s.\n", errStr);
HITLS_X509_CertFree(cert);
return HITLS_APP_X509_FAIL;
}
int32_t ret = AddCertToChain(chain, cert);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to add the chain from %s, errCode = %d.\n", errStr, ret);
HITLS_X509_CertFree(cert);
BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CertVerify(storeCtx, chain);
if (ret != HITLS_PKI_SUCCESS) {
PrintCertErr(cert);
HITLS_X509_CertFree(cert);
BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
(void)AppPrintError("error %s: verification failed, errCode = %d.\n", errStr, ret);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_CertFree(cert);
BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
(void)AppPrintError("%s: OK\n", errStr);
return HITLS_APP_SUCCESS;
}
static int32_t VerifyCerts(HITLS_X509_StoreCtx *storeCtx, int argc, char **argv)
{
int32_t ret = HITLS_APP_SUCCESS;
if (argc == 0) {
return VerifyCert(storeCtx, NULL);
} else {
for (int i = 0; i < argc; ++i) {
ret = VerifyCert(storeCtx, argv[i]);
if (ret != HITLS_APP_SUCCESS) {
return HITLS_APP_X509_FAIL;
}
}
}
return ret;
}
static int32_t OptParse(char **cafile)
{
HITLSOptType optType;
int ret = HITLS_APP_SUCCESS;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_VERIFY_EOF) {
switch (optType) {
case HITLS_APP_OPT_VERIFY_EOF:
case HITLS_APP_OPT_VERIFY_ERR:
ret = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("verify: Use -help for summary.\n");
return ret;
case HITLS_APP_OPT_VERIFY_HELP:
ret = HITLS_APP_HELP;
(void)HITLS_APP_OptHelpPrint(g_verifyOpts);
return ret;
case HITLS_APP_OPT_VERIFY_CAFILE:
*cafile = HITLS_APP_OptGetValueStr();
if (*cafile == NULL || strlen(*cafile) >= PATH_MAX) {
AppPrintError("The length of CA file error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_VERIFY_VERBOSE:
g_verbose = true;
break;
case HITLS_APP_OPT_VERIFY_NOKEYUSAGE:
g_noVerifyKeyUsage = true;
break;
default:
return HITLS_APP_OPT_UNKOWN;
}
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_VerifyMain(int argc, char *argv[])
{
HITLS_X509_StoreCtx *store = NULL;
char *cafile = NULL;
int32_t mainRet = HITLS_APP_SUCCESS;
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR,
"provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) {
mainRet = HITLS_APP_CRYPTO_FAIL;
goto end;
}
mainRet = HITLS_APP_OptBegin(argc, argv, g_verifyOpts);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("error in opt begin.\n");
goto end;
}
mainRet = OptParse(&cafile);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
if (cafile == NULL) {
mainRet = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("Failed to complete the verification because the CAfile file is not obtained\n");
goto end;
}
store = HITLS_X509_StoreCtxNew();
if (store == NULL) {
mainRet = HITLS_APP_X509_FAIL;
(void)AppPrintError("Failed to create the store context.\n");
goto end;
}
mainRet = InitVerify(store, cafile);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
int unParseParamNum = HITLS_APP_GetRestOptNum();
char **unParseParam = HITLS_APP_GetRestOpt();
mainRet = VerifyCerts(store, unParseParamNum, unParseParam);
end:
HITLS_X509_StoreCtxFree(store);
HITLS_APP_OptEnd();
CRYPT_EAL_RandDeinitEx(NULL);
return mainRet;
} | 2401_83913325/openHiTLS_1 | apps/src/app_verify.c | C | unknown | 9,921 |
/*
* 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 "app_x509.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <securec.h>
#include <limits.h>
#include "bsl_list.h"
#include "bsl_print.h"
#include "bsl_conf_def.h"
#include "crypt_errno.h"
#include "crypt_eal_rand.h"
#include "crypt_codecskey.h"
#include "crypt_eal_codecs.h"
#include "crypt_eal_md.h"
#include "hitls_pki_errno.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_conf.h"
#include "app_opt.h"
#include "app_utils.h"
#include "app_list.h"
#define X509_DEFAULT_CERT_DAYS 30
#define X509_DEFAULT_SERIAL_SIZE 20
#define X509_DAY_SECONDS (24 * 60 * 60)
#define X509_SET_SERIAL_PREFIX "0x"
#define X509_MAX_MD_LEN 64
typedef enum {
HITLS_APP_OPT_IN = 2,
HITLS_APP_OPT_INFORM,
HITLS_APP_OPT_REQ,
HITLS_APP_OPT_OUT,
HITLS_APP_OPT_OUTFORM,
HITLS_APP_OPT_NOOUT,
HITLS_APP_OPT_TEXT,
HITLS_APP_OPT_ISSUER,
HITLS_APP_OPT_SUBJECT,
HITLS_APP_OPT_NAMEOPT,
HITLS_APP_OPT_SUBJECT_HASH,
HITLS_APP_OPT_FINGERPRINT,
HITLS_APP_OPT_PUBKEY,
HITLS_APP_OPT_DAYS,
HITLS_APP_OPT_SET_SERIAL,
HITLS_APP_OPT_EXT_FILE,
HITLS_APP_OPT_EXT_SECTION,
HITLS_APP_OPT_MD_ALG,
HITLS_APP_OPT_SIGN_KEY,
HITLS_APP_OPT_PASSIN,
HITLS_APP_OPT_CA,
HITLS_APP_OPT_CA_KEY,
HITLS_APP_OPT_USERID,
} HITLSOptType;
const HITLS_CmdOption g_x509Opts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
/* General opts */
{"in", HITLS_APP_OPT_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file"},
{"inform", HITLS_APP_OPT_INFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Input format"},
{"req", HITLS_APP_OPT_REQ, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Input is a csr, sign and output"},
{"out", HITLS_APP_OPT_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"outform", HITLS_APP_OPT_OUTFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Output format"},
{"noout", HITLS_APP_OPT_NOOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "No Cert output "},
/* Print opts */
{"nameopt", HITLS_APP_OPT_NAMEOPT, HITLS_APP_OPT_VALUETYPE_STRING,
"Cert name options: oneline|multiline|rfc2253 - def oneline"},
{"issuer", HITLS_APP_OPT_ISSUER, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print issuer DN"},
{"subject", HITLS_APP_OPT_SUBJECT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print subject DN"},
{"hash", HITLS_APP_OPT_SUBJECT_HASH, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print subject DN hash"},
{"fingerprint", HITLS_APP_OPT_FINGERPRINT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print fingerprint"},
{"pubkey", HITLS_APP_OPT_PUBKEY, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Output the pubkey"},
{"text", HITLS_APP_OPT_TEXT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print x509 cert in text"},
/* Certificate output opts */
{"days", HITLS_APP_OPT_DAYS, HITLS_APP_OPT_VALUETYPE_POSITIVE_INT,
"How long before the certificate expires - def 30 days"},
{"set_serial", HITLS_APP_OPT_SET_SERIAL, HITLS_APP_OPT_VALUETYPE_STRING, "Cer serial number"},
{"extfile", HITLS_APP_OPT_EXT_FILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "File with x509v3 extension to add"},
{"extensions", HITLS_APP_OPT_EXT_SECTION, HITLS_APP_OPT_VALUETYPE_STRING, "Section from config file to use"},
{"md", HITLS_APP_OPT_MD_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Any supported digest algorithm."},
{"signkey", HITLS_APP_OPT_SIGN_KEY, HITLS_APP_OPT_VALUETYPE_IN_FILE,
"Privkey file for self sign cert, must be PEM format"},
{"passin", HITLS_APP_OPT_PASSIN, HITLS_APP_OPT_VALUETYPE_STRING, "Private key and cert file pass-phrase source"},
{"CA", HITLS_APP_OPT_CA, HITLS_APP_OPT_VALUETYPE_IN_FILE, "CA certificate, must be PEM format"},
{"CAkey", HITLS_APP_OPT_CA_KEY, HITLS_APP_OPT_VALUETYPE_IN_FILE, "CA key, must be PEM format"},
{"userId", HITLS_APP_OPT_USERID, HITLS_APP_OPT_VALUETYPE_STRING, "sm2 userId, default is null"},
{NULL, 0, 0, NULL},
};
typedef struct {
bool req;
char *inPath;
BSL_ParseFormat inForm;
char *outPath;
BSL_ParseFormat outForm;
bool noout;
char *passInArg;
} X509GeneralOpts;
typedef struct {
int32_t nameOpt;
bool issuer;
bool subject;
bool subjectHash;
bool text;
int32_t mdId;
bool fingerprint;
bool pubKey;
} X509PrintOpts;
typedef struct {
int32_t mdId;
int64_t days; // default to 30.
uint8_t *serial; // If this parameter is not specified, the value is generated randomly.
uint32_t serialLen;
char *extFile;
char *extSection;
char *signKeyPath;
char *caPath;
char *caKeyPath;
} X509CertOpts;
typedef struct {
X509GeneralOpts generalOpts;
X509PrintOpts printOpts;
X509CertOpts certOpts;
BSL_UIO *outUio;
BSL_CONF *conf;
HITLS_X509_Cert *cert;
HITLS_X509_Cert *ca;
HITLS_X509_Csr *csr;
HITLS_X509_Ext *certExt;
CRYPT_EAL_PkeyCtx *privKey;
char *passin; // pass of privkey
BSL_Buffer encodeCert;
char *userId;
} X509OptCtx;
typedef int32_t (*X509OptHandleFunc)(X509OptCtx *);
typedef struct {
int optType;
X509OptHandleFunc func;
} X509OptHandleFuncMap;
typedef int32_t (*ExtConfHandleFunc)(char *cnfValue, X509OptCtx *optCtx);
typedef struct {
char *extName;
ExtConfHandleFunc func;
} X509ExtHandleFuncMap;
typedef struct {
const char *nameopt;
int32_t printFlag;
} X509NamePrintFlag;
typedef int32_t (*PrintX509Func)(const X509OptCtx *);
/**
* 6 types of data printing:
* 1. issuer
* 2. subject
* 3. hash
* 4. fingerprint
* 5. pubKey
* 6. cert
*/
PrintX509Func g_printX509FuncList[] = {NULL, NULL, NULL, NULL, NULL, NULL};
#define PRINT_X509_FUNC_LIST_CNT (sizeof(g_printX509FuncList) / sizeof(PrintX509Func))
static void AppPushPrintX509Func(PrintX509Func func)
{
for (size_t i = 0; i < PRINT_X509_FUNC_LIST_CNT; ++i) {
if ((g_printX509FuncList[i] == NULL) || (g_printX509FuncList[i] == func)) {
g_printX509FuncList[i] = func;
return;
}
}
}
static int32_t AppPrintX509(const X509OptCtx *optCtx)
{
int32_t ret = HITLS_APP_SUCCESS;
for (size_t i = 0; i < PRINT_X509_FUNC_LIST_CNT; ++i) {
if ((g_printX509FuncList[i] != NULL)) {
ret = g_printX509FuncList[i](optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
}
}
return ret;
}
static void ResetPrintX509FuncList(void)
{
for (size_t i = 0; i < PRINT_X509_FUNC_LIST_CNT; ++i) {
g_printX509FuncList[i] = NULL;
}
}
static int32_t PrintIssuer(const X509OptCtx *optCtx)
{
BslList *issuer = NULL;
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_GET_ISSUER_DN, &issuer, sizeof(BslList *));
if (ret != 0) {
AppPrintError("x509: Get issuer name failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = BSL_PRINT_Fmt(0, optCtx->outUio,
optCtx->printOpts.nameOpt == HITLS_PKI_PRINT_DN_MULTILINE ? "Issuer=\n" : "Issuer=");
if (ret != 0) {
AppPrintError("x509: Print issuer name failed, errCode=%d.\n", ret);
return HITLS_APP_BSL_FAIL;
}
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_DNNAME, issuer, sizeof(BslList), optCtx->outUio);
if (ret != 0) {
AppPrintError("x509: Print issuer failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t PrintSubject(const X509OptCtx *optCtx)
{
BslList *subject = NULL;
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_GET_SUBJECT_DN, &subject, sizeof(BslList *));
if (ret != 0) {
AppPrintError("x509: Get subject name failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = BSL_PRINT_Fmt(0, optCtx->outUio,
optCtx->printOpts.nameOpt == HITLS_PKI_PRINT_DN_MULTILINE ? "Subject=\n" : "Subject=");
if (ret != 0) {
AppPrintError("x509: Print subject name failed, errCode=%d.\n", ret);
return HITLS_APP_BSL_FAIL;
}
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_DNNAME, subject, sizeof(BslList), optCtx->outUio);
if (ret != 0) {
AppPrintError("x509: Print subject failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t PrintSubjectHash(const X509OptCtx *optCtx)
{
BslList *subject = NULL;
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_GET_SUBJECT_DN, &subject, sizeof(BslList *));
if (ret != 0) {
AppPrintError("x509: Get subject name for hash failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_DNNAME_HASH, subject, sizeof(BslList), optCtx->outUio);
if (ret != 0) {
AppPrintError("x509: Print subject hash failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t PrintFingerPrint(const X509OptCtx *optCtx)
{
uint8_t md[X509_MAX_MD_LEN] = {0};
uint32_t mdLen = X509_MAX_MD_LEN;
if (optCtx->printOpts.mdId == CRYPT_MD_SHAKE128) {
mdLen = HITLS_APP_SHAKE128_SIZE;
} else if (optCtx->printOpts.mdId == CRYPT_MD_SHAKE256) {
mdLen = HITLS_APP_SHAKE256_SIZE;
}
int32_t ret = HITLS_X509_CertDigest(optCtx->cert, optCtx->printOpts.mdId, md, &mdLen);
if (ret != 0) {
AppPrintError("x509: Get cert digest failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = BSL_PRINT_Fmt(0, optCtx->outUio, "%s Fingerprint=",
HITLS_APP_GetNameByCid(optCtx->printOpts.mdId, HITLS_APP_LIST_OPT_DGST_ALG));
if (ret != 0) {
AppPrintError("x509: Print fingerprint failed, errCode=%d.\n", ret);
return HITLS_APP_BSL_FAIL;
}
ret = BSL_PRINT_Hex(0, true, md, mdLen, optCtx->outUio);
if (ret != 0) {
AppPrintError("x509: Print fingerprint failed, errCode=%d.\n", ret);
return HITLS_APP_BSL_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t PrintCert(const X509OptCtx *optCtx)
{
int32_t ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_CERT, optCtx->cert, sizeof(HITLS_X509_Cert *), optCtx->outUio);
if (ret != 0) {
AppPrintError("x509: Print cert failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509OptErr(X509OptCtx *optCtx)
{
(void)optCtx;
AppPrintError("x509: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t X509OptHelp(X509OptCtx *optCtx)
{
(void)optCtx;
HITLS_APP_OptHelpPrint(g_x509Opts);
return HITLS_APP_HELP;
}
static int32_t X509OptIn(X509OptCtx *optCtx)
{
optCtx->generalOpts.inPath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptOut(X509OptCtx *optCtx)
{
optCtx->generalOpts.outPath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptInForm(X509OptCtx *optCtx)
{
char *str = HITLS_APP_OptGetValueStr();
int32_t ret =
HITLS_APP_OptGetFormatType(str, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, (uint32_t *)&optCtx->generalOpts.inForm);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("x509: Invalid format \"%s\" for -inform.\nx509: Use -help for summary.\n", str);
}
return ret;
}
static int32_t X509OptOutForm(X509OptCtx *optCtx)
{
char *str = HITLS_APP_OptGetValueStr();
int32_t ret =
HITLS_APP_OptGetFormatType(str, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, (uint32_t *)&optCtx->generalOpts.outForm);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("x509: Invalid format \"%s\" for -outform.\nx509: Use -help for summary.\n", str);
}
return ret;
}
static int32_t X509OptReq(X509OptCtx *optCtx)
{
optCtx->generalOpts.req = true;
return HITLS_APP_SUCCESS;
}
static int32_t X509OptNoout(X509OptCtx *optCtx)
{
optCtx->generalOpts.noout = true;
return HITLS_APP_SUCCESS;
}
static int32_t X509OptIssuer(X509OptCtx *optCtx)
{
optCtx->printOpts.issuer = true;
AppPushPrintX509Func(PrintIssuer);
return HITLS_APP_SUCCESS;
}
static int32_t X509OptSubject(X509OptCtx *optCtx)
{
optCtx->printOpts.subject = true;
AppPushPrintX509Func(PrintSubject);
return HITLS_APP_SUCCESS;
}
static int32_t X509OptNameOpt(X509OptCtx *optCtx)
{
static const X509NamePrintFlag printFlags[] = {
{"oneline", HITLS_PKI_PRINT_DN_ONELINE},
{"multiline", HITLS_PKI_PRINT_DN_MULTILINE},
{"rfc2253", HITLS_PKI_PRINT_DN_RFC2253},
};
char *str = HITLS_APP_OptGetValueStr();
for (size_t i = 0; i < (sizeof(printFlags) / sizeof(X509NamePrintFlag)); ++i) {
if (strcmp(printFlags[i].nameopt, str) == 0) {
optCtx->printOpts.nameOpt = printFlags[i].printFlag;
return HITLS_APP_SUCCESS;
}
}
AppPrintError("x509: Invalid nameopt %s.\nx509: Use -help for summary.\n", str);
return HITLS_APP_OPT_VALUE_INVALID;
}
static int32_t X509OptSubjectHash(X509OptCtx *optCtx)
{
(void)optCtx;
AppPushPrintX509Func(PrintSubjectHash);
return HITLS_APP_SUCCESS;
}
static int32_t X509OptFingerprint(X509OptCtx *optCtx)
{
(void)optCtx;
AppPushPrintX509Func(PrintFingerPrint);
return HITLS_APP_SUCCESS;
}
static int32_t X509OptText(X509OptCtx *optCtx)
{
optCtx->printOpts.text = true;
AppPushPrintX509Func(PrintCert);
return HITLS_APP_SUCCESS;
}
static int32_t X509OptPubkey(X509OptCtx *optCtx)
{
(void)optCtx;
optCtx->printOpts.pubKey = true;
return HITLS_APP_SUCCESS;
}
static int32_t X509OptMdId(X509OptCtx *optCtx)
{
optCtx->certOpts.mdId = HITLS_APP_GetCidByName(HITLS_APP_OptGetValueStr(), HITLS_APP_LIST_OPT_DGST_ALG);
optCtx->printOpts.mdId = optCtx->certOpts.mdId;
return optCtx->certOpts.mdId == BSL_CID_UNKNOWN ? HITLS_APP_OPT_VALUE_INVALID : HITLS_APP_SUCCESS;
}
static int32_t X509OptDays(X509OptCtx *optCtx)
{
int32_t ret = HITLS_APP_OptGetUint32(HITLS_APP_OptGetValueStr(), (uint32_t *)&optCtx->certOpts.days);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("x509: Invalid days.\nx509: Use -help for summary.\n");
}
return ret;
}
static int32_t X509OptSetSerial(X509OptCtx *optCtx)
{
char *str = HITLS_APP_OptGetValueStr();
int32_t ret = HITLS_APP_HexToByte(str, &optCtx->certOpts.serial, &optCtx->certOpts.serialLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("x509: Invalid serial: %s.\n", str);
}
return ret;
}
static int32_t X509OptExtFile(X509OptCtx *optCtx)
{
optCtx->certOpts.extFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptExtSection(X509OptCtx *optCtx)
{
optCtx->certOpts.extSection = HITLS_APP_OptGetValueStr();
if (strlen(optCtx->certOpts.extSection) > BSL_CONF_SEC_SIZE) {
AppPrintError("x509: Invalid extensions, size should less than %d.\n", BSL_CONF_SEC_SIZE);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509OptSignKey(X509OptCtx *optCtx)
{
optCtx->certOpts.signKeyPath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptPassin(X509OptCtx *optCtx)
{
optCtx->generalOpts.passInArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptCa(X509OptCtx *optCtx)
{
optCtx->certOpts.caPath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptCaKey(X509OptCtx *optCtx)
{
optCtx->certOpts.caKeyPath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509UserId(X509OptCtx *optCtx)
{
optCtx->userId = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static const X509OptHandleFuncMap g_x509OptHandleFuncMap[] = {
{HITLS_APP_OPT_ERR, X509OptErr},
{HITLS_APP_OPT_HELP, X509OptHelp},
{HITLS_APP_OPT_IN, X509OptIn},
{HITLS_APP_OPT_INFORM, X509OptInForm},
{HITLS_APP_OPT_REQ, X509OptReq},
{HITLS_APP_OPT_OUT, X509OptOut},
{HITLS_APP_OPT_OUTFORM, X509OptOutForm},
{HITLS_APP_OPT_NOOUT, X509OptNoout},
{HITLS_APP_OPT_ISSUER, X509OptIssuer},
{HITLS_APP_OPT_SUBJECT, X509OptSubject},
{HITLS_APP_OPT_NAMEOPT, X509OptNameOpt},
{HITLS_APP_OPT_SUBJECT_HASH, X509OptSubjectHash},
{HITLS_APP_OPT_FINGERPRINT, X509OptFingerprint},
{HITLS_APP_OPT_PUBKEY, X509OptPubkey},
{HITLS_APP_OPT_TEXT, X509OptText},
{HITLS_APP_OPT_MD_ALG, X509OptMdId},
{HITLS_APP_OPT_DAYS, X509OptDays},
{HITLS_APP_OPT_SET_SERIAL, X509OptSetSerial},
{HITLS_APP_OPT_EXT_FILE, X509OptExtFile},
{HITLS_APP_OPT_EXT_SECTION, X509OptExtSection},
{HITLS_APP_OPT_SIGN_KEY, X509OptSignKey},
{HITLS_APP_OPT_PASSIN, X509OptPassin},
{HITLS_APP_OPT_CA, X509OptCa},
{HITLS_APP_OPT_CA_KEY, X509OptCaKey},
{HITLS_APP_OPT_USERID, X509UserId},
};
static int32_t ParseX509Opt(int argc, char *argv[], X509OptCtx *optCtx)
{
int32_t ret = HITLS_APP_OptBegin(argc, argv, g_x509Opts);
if (ret != HITLS_APP_SUCCESS) {
HITLS_APP_OptEnd();
AppPrintError("error in opt begin.\n");
return ret;
}
int optType = HITLS_APP_OPT_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF)) {
for (size_t i = 0; i < (sizeof(g_x509OptHandleFuncMap) / sizeof(g_x509OptHandleFuncMap[0])); ++i) {
if (optType == g_x509OptHandleFuncMap[i].optType) {
ret = g_x509OptHandleFuncMap[i].func(optCtx);
break;
}
}
}
// Obtain the number of parameters that cannot be parsed in the current version,
// and print the error information and help list.
if ((ret == HITLS_APP_SUCCESS) && (HITLS_APP_GetRestOptNum() != 0)) {
AppPrintError("x509: Extra arguments given.\nx509: Use -help for summary.\n");
ret = HITLS_APP_OPT_UNKOWN;
}
HITLS_APP_OptEnd();
return ret;
}
static int32_t GetCertPubkeyEncodeBuff(
HITLS_X509_Cert *cert, BSL_ParseFormat format, bool isComplete, BSL_Buffer *encode)
{
CRYPT_EAL_PkeyCtx *pubKey = NULL;
int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_PUBKEY, &pubKey, 0);
if (ret != 0) {
AppPrintError("x509: Get pubKey from cert failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = CRYPT_EAL_EncodePubKeyBuffInternal(pubKey, format, CRYPT_PUBKEY_SUBKEY, isComplete, encode);
CRYPT_EAL_PkeyFreeCtx(pubKey);
if (ret != CRYPT_SUCCESS) {
AppPrintError("x509: Encode pubKey failed, errCode = %d.\n", ret);
return HITLS_APP_ENCODE_KEY_FAIL;
}
return HITLS_APP_SUCCESS;
}
/**
* RFC 5280:
* section 4.1
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING
* }
* AlgorithmIdentifier ::= SEQUENCE { ... }
*
* section 4.2.1.2
* (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the value of the
* BIT STRING subjectPublicKey (excluding the tag, length, and number of unused bits).
*/
static int32_t GetCertKid(HITLS_X509_Cert *cert, BSL_ParseFormat format, BSL_Buffer *buff)
{
// 1. Get the encode value of algotithm and subjectPublicKey.
BSL_Buffer info = {0};
int32_t ret = GetCertPubkeyEncodeBuff(cert, format, false, &info);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// 2. Skip the algorithm
uint8_t *enc = info.data;
uint32_t encLen = info.dataLen;
uint32_t vLen = 0;
ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, &enc, &encLen, &vLen);
if (ret != 0) {
AppPrintError("x509: Decode pubKey failed, errCode = %d.\n", ret);
ret = HITLS_APP_DECODE_FAIL;
goto EXIT;
}
enc += vLen;
encLen -= vLen;
// 3. Skip the tag, length and unusedBits of bitstring
ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_BITSTRING, &enc, &encLen, &vLen);
if (ret != 0) {
AppPrintError("x509: Decode pubKey failed, errCode = %d.\n", ret);
ret = HITLS_APP_DECODE_FAIL;
goto EXIT;
}
enc += 1; // 1: skip the unusedBits of bitstring
encLen -= 1;
// 4. sha1
buff->data = BSL_SAL_Malloc(20); // 20: CRYPT_SHA1_DIGESTSIZE
if (buff->data == NULL) {
AppPrintError("x509: Allocate memory for kid failed.\n");
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
buff->dataLen = 20; // 20: CRYPT_SHA1_DIGESTSIZE
ret = CRYPT_EAL_Md(CRYPT_MD_SHA1, enc, encLen, buff->data, &buff->dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(buff->data);
buff->dataLen = 0;
AppPrintError("x509: Failed to calculate the kid, errCode = %d.\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
goto EXIT;
}
ret = HITLS_APP_SUCCESS;
EXIT:
BSL_SAL_Free(info.data);
return ret;
}
static int32_t LoadConf(X509OptCtx *optCtx)
{
if (optCtx->certOpts.extFile == NULL || optCtx->certOpts.extSection == NULL) {
return HITLS_APP_SUCCESS;
}
optCtx->conf = BSL_CONF_New(BSL_CONF_DefaultMethod());
if (optCtx->conf == NULL) {
AppPrintError("x509: New conf failed.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
int32_t ret = BSL_CONF_Load(optCtx->conf, optCtx->certOpts.extFile);
if (ret != 0) {
BSL_CONF_Free(optCtx->conf);
optCtx->conf = NULL;
AppPrintError("x509: Load extfile %s failed, errCode = %d.\n", optCtx->certOpts.extFile, ret);
return HITLS_APP_CONF_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t LoadRelatedFiles(X509OptCtx *optCtx)
{
// Load and verify csr
optCtx->csr = HITLS_APP_LoadCsr(optCtx->generalOpts.inPath, optCtx->generalOpts.inForm);
if (optCtx->csr == NULL) {
AppPrintError("x509: Load csr failed\n");
return HITLS_APP_LOAD_CSR_FAIL;
}
int32_t ret;
if (optCtx->userId != NULL) {
ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_SET_VFY_SM2_USER_ID, optCtx->userId, strlen(optCtx->userId));
if (ret != 0) {
AppPrintError("x509: set userId failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
ret = HITLS_X509_CsrVerify(optCtx->csr);
if (ret != 0) {
AppPrintError("x509: Verify csr failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
if (HITLS_APP_ParsePasswd(optCtx->generalOpts.passInArg, &optCtx->passin) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
// Load private key
if (optCtx->certOpts.signKeyPath != NULL) {
optCtx->privKey = HITLS_APP_LoadPrvKey(optCtx->certOpts.signKeyPath, BSL_FORMAT_PEM, &optCtx->passin);
} else if (optCtx->certOpts.caKeyPath != NULL) {
optCtx->privKey = HITLS_APP_LoadPrvKey(optCtx->certOpts.caKeyPath, BSL_FORMAT_PEM, &optCtx->passin);
}
if (optCtx->privKey == NULL) {
AppPrintError("x509: Load signkey or cakey failed.\n");
return HITLS_APP_LOAD_KEY_FAIL;
}
if (optCtx->userId != NULL) {
ret = CRYPT_EAL_PkeyCtrl(optCtx->privKey, CRYPT_CTRL_SET_SM2_USER_ID, optCtx->userId, strlen(optCtx->userId));
if (ret != 0) {
AppPrintError("x509: set userId failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
// Load ca
if (optCtx->certOpts.caPath != NULL) {
optCtx->ca = HITLS_APP_LoadCert(optCtx->certOpts.caPath, BSL_FORMAT_PEM);
if (optCtx->ca == NULL) {
AppPrintError("x509: Load ca failed\n");
return HITLS_APP_LOAD_CERT_FAIL;
}
CRYPT_EAL_PkeyCtx *pubKey = NULL;
ret = HITLS_X509_CertCtrl(optCtx->ca, HITLS_X509_GET_PUBKEY, &pubKey, 0);
if (ret != 0) {
AppPrintError("x509: Get pubKey from ca failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = CRYPT_EAL_PkeyPairCheck(pubKey, optCtx->privKey);
CRYPT_EAL_PkeyFreeCtx(pubKey);
if (ret != 0) {
AppPrintError("x509: CA public key and CA private key do not match, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
return LoadConf(optCtx);
}
static int32_t SetSerial(X509OptCtx *optCtx)
{
int32_t ret;
if (optCtx->certOpts.serial == NULL) {
optCtx->certOpts.serial = BSL_SAL_Malloc(X509_DEFAULT_SERIAL_SIZE);
if (optCtx->certOpts.serial == NULL) {
AppPrintError("x509: Allocate serial memory failed.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
optCtx->certOpts.serialLen = X509_DEFAULT_SERIAL_SIZE;
if ((ret = CRYPT_EAL_RandbytesEx(NULL, optCtx->certOpts.serial, optCtx->certOpts.serialLen)) != 0) {
BSL_SAL_FREE(optCtx->certOpts.serial);
AppPrintError("x509: Generate serial number failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
ret = HITLS_X509_CertCtrl(
optCtx->cert, HITLS_X509_SET_SERIALNUM, optCtx->certOpts.serial, optCtx->certOpts.serialLen);
if (ret != 0) {
AppPrintError("x509: Set serial number failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetValidity(X509OptCtx *optCtx)
{
int64_t startTime = BSL_SAL_CurrentSysTimeGet();
if (startTime == 0) {
AppPrintError("x509: Get system time failed.\n");
return HITLS_APP_SAL_FAIL;
}
if (optCtx->certOpts.days > (INT64_MAX - startTime) / X509_DAY_SECONDS) {
AppPrintError("x509: The sum of the current time and -days %lld outside integer range.\n", optCtx->certOpts.days);
return HITLS_APP_SAL_FAIL;
}
int64_t endTime = startTime + optCtx->certOpts.days * X509_DAY_SECONDS;
if (endTime >= 253402272000) { // 253402272000: utctime of 10000-01-01 00:00:00
AppPrintError("x509: The end time of cert is greatter than 9999 years.\n");
return HITLS_APP_INVALID_ARG;
}
BSL_TIME start = {0};
BSL_TIME end = {0};
if (BSL_SAL_UtcTimeToDateConvert(startTime, &start) != 0 || BSL_SAL_UtcTimeToDateConvert(endTime, &end) != 0) {
AppPrintError("x509: Time convert failed.\n");
return HITLS_APP_SAL_FAIL;
}
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_BEFORE_TIME, &start, sizeof(BSL_TIME));
if (ret != 0) {
AppPrintError("x509: Set start time failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_AFTER_TIME, &end, sizeof(BSL_TIME));
if (ret != 0) {
AppPrintError("x509: Set end time failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetCertDn(X509OptCtx *optCtx)
{
BslList *subject = NULL;
int32_t ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_GET_SUBJECT_DN, &subject, sizeof(BslList *));
if (ret != 0) {
AppPrintError("x509: Get subject from csr failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_SUBJECT_DN, subject, sizeof(BslList));
if (ret != 0) {
AppPrintError("x509: Set subject failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
BslList *issuer = subject;
if (optCtx->ca != NULL) {
ret = HITLS_X509_CertCtrl(optCtx->ca, HITLS_X509_GET_SUBJECT_DN, &issuer, sizeof(BslList *));
if (ret != 0) {
AppPrintError("x509: Get subject from ca failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_ISSUER_DN, issuer, sizeof(BslList));
if (ret != 0) {
AppPrintError("x509: Set issuer failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t CopyExtensionsFromCsr(X509OptCtx *optCtx)
{
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_CSR_EXT, optCtx->csr, 0);
if (ret == HITLS_X509_ERR_ATTR_NOT_FOUND) {
return HITLS_APP_SUCCESS;
}
if (ret != 0) {
AppPrintError("x509: Copy csr extensions failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
int32_t version = HITLS_X509_VERSION_3;
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_VERSION, &version, sizeof(version));
if (ret != 0) {
AppPrintError("x509: Set cert version failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509SetBasicConstraints(HITLS_X509_ExtBCons *bCons, X509OptCtx *optCtx)
{
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_SET_BCONS, bCons, sizeof(HITLS_X509_ExtBCons));
if (ret != 0) {
AppPrintError("x509: Set basicConstraints failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509SetKeyUsage(HITLS_X509_ExtKeyUsage *ku, X509OptCtx *optCtx)
{
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_SET_KUSAGE, ku, sizeof(HITLS_X509_ExtKeyUsage));
if (ret != 0) {
AppPrintError("x509: Set keyUsage failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509SetExtendKeyUsage(HITLS_X509_ExtExKeyUsage *exku, X509OptCtx *optCtx)
{
int32_t ret =
HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_SET_EXKUSAGE, exku, sizeof(HITLS_X509_ExtExKeyUsage));
if (ret != 0) {
AppPrintError("x509: Set extendKeyUsage failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509SetSubjectAltName(HITLS_X509_ExtSan *san, X509OptCtx *optCtx)
{
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_SET_SAN, san, sizeof(HITLS_X509_ExtSan));
if (ret != 0) {
AppPrintError("x509: Set subjectAltName failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509SetSubjectKeyIdentifier(HITLS_X509_ExtSki *ski, HITLS_X509_Cert *cert, bool needFree)
{
int32_t ret = GetCertKid(cert, BSL_FORMAT_ASN1, &ski->kid);
if (ret != 0) {
return ret;
}
ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SKI, ski, sizeof(HITLS_X509_ExtSki));
if (needFree) {
BSL_SAL_FREE(ski->kid.data);
}
if (ret != 0) {
AppPrintError("x509: Set subjectKeyIdentifier failed, errCode = %d.\n", ret);
BSL_SAL_FREE(ski->kid.data);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetSelfSignedCertAki(HITLS_CFG_ExtAki *cfgAki, HITLS_X509_Cert *cert)
{
// [keyid] set ski, kid is from csr or self-generated
// [keyid:always] set ski and aki, aki = ski
bool isSkiExist;
HITLS_X509_ExtAki aki = cfgAki->aki;
HITLS_X509_ExtSki ski = {0};
int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_CHECK_SKI, &isSkiExist, sizeof(bool));
if (ret != 0) {
AppPrintError("x509: Check cert subjectKeyIdentifier failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
if (isSkiExist && (cfgAki->flag & HITLS_CFG_X509_EXT_AKI_KID_ALWAYS) == 0) {
// Ski has been set and the cnf does not contain 'always'.
return HITLS_APP_SUCCESS;
}
if (isSkiExist) {
// get ski from cert
ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_GET_SKI, &ski, sizeof(HITLS_X509_ExtSki));
if (ret != 0) {
AppPrintError("x509: Get cert subjectKeyIdentifier failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
} else {
// generate ski and set ski
ret = X509SetSubjectKeyIdentifier(&ski, cert, false);
if (ret != 0) {
return ret;
}
if ((cfgAki->flag & HITLS_CFG_X509_EXT_AKI_KID_ALWAYS) == 0) {
BSL_SAL_Free(ski.kid.data);
return ret;
}
}
aki.kid = ski.kid;
ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_AKI, &aki, sizeof(HITLS_X509_ExtAki));
if (!isSkiExist) {
BSL_SAL_Free(ski.kid.data);
}
if (ret != 0) {
AppPrintError("x509: Set cert authorityKeyIdentifier failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetNonSelfSignedCertAki(HITLS_CFG_ExtAki *cfgAki, X509OptCtx *optCtx)
{
// [keyid] set ski and aki, aki.kid is from issuer cert
HITLS_X509_ExtSki caSki = {0};
HITLS_X509_ExtAki aki = cfgAki->aki;
bool isSkiExist;
int32_t ret = HITLS_X509_CertCtrl(optCtx->ca, HITLS_X509_EXT_GET_SKI, &caSki, sizeof(HITLS_X509_ExtSki));
if (ret != 0) {
AppPrintError("x509: Get issuer keyId failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
aki.kid = caSki.kid;
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_SET_AKI, &aki, sizeof(HITLS_X509_ExtAki));
if (ret != 0) {
AppPrintError("x509: Set non-self-signed cert authorityKeyIdentifier failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_CHECK_SKI, &isSkiExist, sizeof(bool));
if (ret != 0) {
AppPrintError("x509: Check cert subjectKeyIdentifier failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
if (isSkiExist) {
return HITLS_APP_SUCCESS;
}
return X509SetSubjectKeyIdentifier(&caSki, optCtx->cert, true);
}
static int32_t X509SetAuthKeyIdentifier(HITLS_CFG_ExtAki *cfgAki, X509OptCtx *optCtx)
{
if (optCtx->ca == NULL) {
return SetSelfSignedCertAki(cfgAki, optCtx->cert);
} else {
return SetNonSelfSignedCertAki(cfgAki, optCtx);
}
}
static int32_t X509ProcExt(BslCid cid, void *val, X509OptCtx *optCtx)
{
if (val == NULL) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
switch (cid) {
case BSL_CID_CE_BASICCONSTRAINTS:
return X509SetBasicConstraints(val, optCtx);
case BSL_CID_CE_KEYUSAGE:
return X509SetKeyUsage(val, optCtx);
case BSL_CID_CE_EXTKEYUSAGE:
return X509SetExtendKeyUsage(val, optCtx);
case BSL_CID_CE_AUTHORITYKEYIDENTIFIER:
return X509SetAuthKeyIdentifier(val, optCtx);
case BSL_CID_CE_SUBJECTKEYIDENTIFIER:
return X509SetSubjectKeyIdentifier(val, optCtx->cert, true);
case BSL_CID_CE_SUBJECTALTNAME:
return X509SetSubjectAltName(val, optCtx);
default:
AppPrintError("x509: Unsupported extension: %d.\n", (int32_t)cid);
return HITLS_APP_X509_FAIL;
}
}
static int32_t SetCertExtensionsByConf(X509OptCtx *optCtx)
{
if (optCtx->conf == NULL) {
return HITLS_APP_SUCCESS;
}
int32_t ret =
HITLS_APP_CONF_ProcExt(optCtx->conf, optCtx->certOpts.extSection, (ProcExtCallBack)X509ProcExt, optCtx);
if (ret != HITLS_APP_SUCCESS && ret != HITLS_APP_NO_EXT) {
return ret;
}
if (ret == HITLS_APP_NO_EXT) {
return HITLS_APP_SUCCESS;
}
int32_t version = HITLS_X509_VERSION_3;
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_VERSION, &version, sizeof(version));
if (ret != 0) {
AppPrintError("x509: Set cert version failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetPubKey(X509OptCtx *optCtx)
{
int32_t ret;
CRYPT_EAL_PkeyCtx *pubKey = NULL;
if (optCtx->ca == NULL) {
// self-signed cert
pubKey = optCtx->privKey;
} else {
// non self-signed cert
ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_GET_PUBKEY, &pubKey, 0);
if (ret != 0) {
AppPrintError("x509: Get pubKey from csr failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_PUBKEY, pubKey, 0);
if (optCtx->ca != NULL) {
CRYPT_EAL_PkeyFreeCtx(pubKey);
}
if (ret != 0) {
AppPrintError("x509: Set public key failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetCertCont(X509OptCtx *optCtx)
{
// Pubkey must be set first, which will be used in set extensions
int32_t ret = SetPubKey(optCtx);
if (ret != 0) {
return ret;
}
ret = CopyExtensionsFromCsr(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = SetCertExtensionsByConf(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = SetSerial(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = SetValidity(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return SetCertDn(optCtx);
}
static int32_t GenCert(X509OptCtx *optCtx)
{
int32_t ret = LoadRelatedFiles(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
optCtx->cert = HITLS_X509_CertNew();
if (optCtx->cert == NULL) {
AppPrintError("x509: Failed to new a cert.\n");
return HITLS_APP_X509_FAIL;
}
ret = SetCertCont(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = HITLS_X509_CertSign(optCtx->certOpts.mdId, optCtx->privKey, NULL, optCtx->cert);
if (ret != 0) {
AppPrintError("x509: sign cert failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CertGenBuff(optCtx->generalOpts.outForm, optCtx->cert, &optCtx->encodeCert);
if (ret != 0) {
AppPrintError("x509: encode cert failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t LoadCert(X509OptCtx *optCtx)
{
optCtx->cert = HITLS_APP_LoadCert(optCtx->generalOpts.inPath, optCtx->generalOpts.inForm);
if (optCtx->cert == NULL) {
return HITLS_APP_LOAD_CERT_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t OutputPubkey(X509OptCtx *optCtx)
{
if (!optCtx->printOpts.pubKey) {
return HITLS_APP_SUCCESS;
}
BSL_Buffer encodePubkey = {0};
int32_t ret = GetCertPubkeyEncodeBuff(optCtx->cert, BSL_FORMAT_PEM, true, &encodePubkey);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
uint32_t writeLen = 0;
ret = BSL_UIO_Write(optCtx->outUio, encodePubkey.data, encodePubkey.dataLen, &writeLen);
BSL_SAL_Free(encodePubkey.data);
if (ret != 0 || writeLen != encodePubkey.dataLen) {
AppPrintError("x509: write pubKey failed, errCode = %d, writeLen = %u.\n", ret, writeLen);
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509Output(X509OptCtx *optCtx)
{
int32_t ret;
optCtx->outUio = HITLS_APP_UioOpen(optCtx->generalOpts.outPath, 'w', 0);
if (optCtx->outUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(optCtx->outUio, true);
// Output cert info
if (optCtx->printOpts.issuer || optCtx->printOpts.subject || optCtx->printOpts.text) {
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_SET_PRINT_FLAG, (void *)&optCtx->printOpts.nameOpt, sizeof(int32_t), NULL);
if (ret != 0) {
AppPrintError("x509: Set DN print flag failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
ret = AppPrintX509(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// Output pubKey
ret = OutputPubkey(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// Output cert der/pem
if (optCtx->generalOpts.noout) {
return HITLS_APP_SUCCESS;
}
if (optCtx->encodeCert.data == NULL) {
ret = HITLS_X509_CertGenBuff(optCtx->generalOpts.outForm, optCtx->cert, &optCtx->encodeCert);
if (ret != 0) {
AppPrintError("x509: encode cert failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
uint32_t writeLen = 0;
ret = BSL_UIO_Write(optCtx->outUio, optCtx->encodeCert.data, optCtx->encodeCert.dataLen, &writeLen);
if (ret != 0 || writeLen != optCtx->encodeCert.dataLen) {
AppPrintError("x509: write cert failed, errCode = %d, writeLen = %u.\n", ret, writeLen);
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static bool CheckGenCertOpt(X509OptCtx *optCtx)
{
if (optCtx->certOpts.caPath != NULL) {
if (optCtx->certOpts.signKeyPath != NULL) {
AppPrintError("x509: Cannot use both -signkey and -CA.\n");
return false;
}
} else {
if (optCtx->certOpts.caKeyPath != NULL) {
if (optCtx->certOpts.signKeyPath != NULL) {
AppPrintError("x509: Cannot use both -CAkey and -signkey.\n");
return false;
} else {
AppPrintError("x509: Should use both -CA and -CAkey.\n");
return false;
}
}
}
if (optCtx->certOpts.signKeyPath == NULL && optCtx->certOpts.caKeyPath == NULL) {
AppPrintError("x509: We need a private key to genetate cert, use -signkey or -CAkey.\n");
return false;
}
if (optCtx->certOpts.extFile != NULL && optCtx->certOpts.extSection == NULL) {
AppPrintError("x509: Warning: ignoring -extFile since -extensions is not given.\n");
optCtx->certOpts.extFile = NULL;
}
if (optCtx->certOpts.extFile == NULL && optCtx->certOpts.extSection != NULL) {
AppPrintError("x509: Warning: ignoring -extensions since -extFile is not given.\n");
optCtx->certOpts.extSection = NULL;
}
return true;
}
static bool CheckOpt(X509OptCtx *optCtx)
{
if (optCtx->generalOpts.req) { // new cert
return CheckGenCertOpt(optCtx);
} else {
if (optCtx->certOpts.signKeyPath != NULL || optCtx->certOpts.caKeyPath != NULL ||
optCtx->certOpts.caPath != NULL) {
AppPrintError("x509: Warning: ignoring -signkey, -CA, -CAkey since -req is not given.\n");
optCtx->certOpts.caKeyPath = NULL;
optCtx->certOpts.signKeyPath = NULL;
optCtx->certOpts.caPath = NULL;
}
if (optCtx->certOpts.serialLen != 0) {
AppPrintError("x509: Warning: ignoring -set_serial since -req is not given.\n");
BSL_SAL_FREE(optCtx->certOpts.serial);
optCtx->certOpts.serialLen = 0;
}
if (optCtx->certOpts.extFile != NULL || optCtx->certOpts.extSection != NULL) {
AppPrintError("x509: Warning: ignoring -extfile or -extensions since -req is not given.\n");
optCtx->certOpts.extFile = NULL;
optCtx->certOpts.extSection = NULL;
}
}
return true;
}
int32_t HandleX509Opt(int argc, char *argv[], X509OptCtx *optCtx)
{
int32_t ret = ParseX509Opt(argc, argv, optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (!CheckOpt(optCtx)) {
return HITLS_APP_OPT_TYPE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static void InitX509OptCtx(X509OptCtx *optCtx)
{
optCtx->generalOpts.inForm = BSL_FORMAT_PEM;
optCtx->generalOpts.outForm = BSL_FORMAT_PEM;
optCtx->generalOpts.req = false;
optCtx->generalOpts.noout = false;
optCtx->printOpts.nameOpt = HITLS_PKI_PRINT_DN_ONELINE;
optCtx->certOpts.days = X509_DEFAULT_CERT_DAYS;
optCtx->certOpts.mdId = CRYPT_MD_SHA256;
optCtx->printOpts.mdId = CRYPT_MD_SHA1;
}
static void UnInitX509OptCtx(X509OptCtx *optCtx)
{
BSL_UIO_Free(optCtx->outUio);
optCtx->outUio = NULL;
BSL_CONF_Free(optCtx->conf);
optCtx->conf = NULL;
HITLS_X509_CertFree(optCtx->cert);
optCtx->cert = NULL;
HITLS_X509_CertFree(optCtx->ca);
optCtx->ca = NULL;
HITLS_X509_CsrFree(optCtx->csr);
optCtx->csr = NULL;
CRYPT_EAL_PkeyFreeCtx(optCtx->privKey);
optCtx->privKey = NULL;
BSL_SAL_FREE(optCtx->certOpts.serial);
BSL_SAL_FREE(optCtx->encodeCert.data);
if (optCtx->passin != NULL) {
BSL_SAL_ClearFree(optCtx->passin, strlen(optCtx->passin));
}
}
// x509 main function
int32_t HITLS_X509Main(int argc, char *argv[])
{
ResetPrintX509FuncList();
X509OptCtx optCtx = {0};
InitX509OptCtx(&optCtx);
int32_t ret = HITLS_APP_SUCCESS;
do {
// Init rand: Generate a serial number or signature certificate.
ret = HandleX509Opt(argc, argv, &optCtx);
if (ret != HITLS_APP_SUCCESS) {
break;
}
if (optCtx.generalOpts.req) {
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR,
"provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) {
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = GenCert(&optCtx);
} else {
ret = LoadCert(&optCtx);
}
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = X509Output(&optCtx);
} while (false);
UnInitX509OptCtx(&optCtx);
CRYPT_EAL_RandDeinitEx(NULL);
return ret;
}
| 2401_83913325/openHiTLS_1 | apps/src/app_x509.c | C | unknown | 45,824 |
/*
* 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 "securec.h"
#include "app_errno.h"
#include "bsl_sal.h"
#include "bsl_errno.h"
#include "app_function.h"
#include "app_print.h"
#include "app_help.h"
#include "app_provider.h"
static int AppInit(void)
{
int32_t ret = AppPrintErrorUioInit(stderr);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return HITLS_APP_SUCCESS;
}
static void AppUninit(void)
{
AppPrintErrorUioUnInit();
return;
}
static void FreeNewArgv(char **newargv, int argc)
{
if (newargv != NULL) {
for (int i = 0; i < argc; i++) {
BSL_SAL_FREE(newargv[i]);
}
}
BSL_SAL_FREE(newargv);
}
static char **CopyArgs(int argc, char **argv, int *newArgc)
{
char **newargv = BSL_SAL_Calloc(argc + 1, sizeof(*newargv));
if (newargv == NULL) {
AppPrintError("SAL malloc failed.\n");
return NULL;
}
int i = 0;
for (i = 0; i < argc; i++) {
newargv[i] = (char *)BSL_SAL_Calloc(strlen(argv[i]) + 1, sizeof(char));
if (newargv[i] == NULL) {
AppPrintError("SAL malloc failed.\n");
goto EXIT;
}
if (strcpy_s(newargv[i], strlen(argv[i]) + 1, argv[i]) != EOK) {
AppPrintError("Failed to copy argv.\n");
goto EXIT;
}
}
newargv[i] = NULL;
*newArgc = i;
return newargv;
EXIT:
FreeNewArgv(newargv, i);
return NULL;
}
int main(int argc, char *argv[])
{
int ret = AppInit();
if (ret != HITLS_APP_SUCCESS) {
return HITLS_APP_INIT_FAILED;
}
if (argc == 1) {
AppPrintError("There is only one input parameter. Please enter help to obtain the support list.\n");
return HITLS_APP_INVALID_ARG;
}
int paramNum = argc;
char** paramVal = argv;
--paramNum;
++paramVal;
int newArgc = 0;
char **newArgv = CopyArgs(paramNum, paramVal, &newArgc);
if (newArgv == NULL) {
AppPrintError("Copy args failed.\n");
ret = HITLS_APP_COPY_ARGS_FAILED;
goto end;
}
HITLS_CmdFunc func = { 0 };
char *proName = newArgv[0];
ret = AppGetProgFunc(proName, &func);
if (ret != 0) {
AppPrintError("Please enter help to obtain the support list.\n");
FreeNewArgv(newArgv, newArgc);
goto end;
}
if (APP_GetCurrent_LibCtx() == NULL) {
if (APP_Create_LibCtx() == NULL) {
(void)AppPrintError("Create g_libCtx failed\n");
ret = HITLS_APP_INVALID_ARG;
goto end;
}
}
ret = func.main(newArgc, newArgv);
FreeNewArgv(newArgv, newArgc);
end:
HITLS_APP_FreeLibCtx();
AppUninit();
return ret;
}
| 2401_83913325/openHiTLS_1 | apps/src/hitls.c | C | unknown | 3,206 |
/*
* 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 OTP_H
#define OTP_H
#include <stdint.h>
#include "bsl_sal.h"
#include "bsl_types.h"
#include "auth_params.h"
#include "auth_otp.h"
#ifdef __cplusplus
extern "C" {
#endif
#define OTP_DEFAULT_DIGITS 6
#define OTP_MIN_DIGITS 6
#define OTP_MAX_DIGITS 8
#define OTP_TOTP_DEFAULT_TIME_STEP_SIZE 30
#define OTP_TOTP_DEFAULT_START_OFFSET 0
#define OTP_TOTP_DEFAULT_VALID_WINDOW 1
typedef struct {
HITLS_AUTH_OtpHmac hmac;
HITLS_AUTH_OtpRandom random;
} OtpCryptCb;
typedef struct {
uint32_t timeStepSize;
BslUnixTime startOffset;
uint32_t validWindow;
} TotpCtx;
/* Main context structure for OTP operations */
struct Otp_Ctx {
CRYPT_EAL_LibCtx *libCtx; // Provider context
const char *attrName; // Provider attribute name
int32_t protocolType;
BSL_Buffer key;
uint32_t digits;
int32_t hashAlgId;
void *ctx; // Protocol-specific fields
OtpCryptCb method; // Cryptographic callbacks
};
/**
* @brief Get the default cryptographic callback functions.
* @retval OtpCryptCb structure containing default callbacks.
*/
OtpCryptCb OtpCryptDefaultCb(void);
#ifdef __cplusplus
}
#endif
#endif // OTP_H | 2401_83913325/openHiTLS_1 | auth/otp/include/otp.h | C | unknown | 1,753 |
/*
* 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 "securec.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "bsl_bytes.h"
#include "auth_errno.h"
#include "auth_params.h"
#include "auth_otp.h"
#include "crypt_errno.h"
#include "otp.h"
int32_t HITLS_AUTH_OtpInit(HITLS_AUTH_OtpCtx *ctx, uint8_t *key, uint32_t keyLen)
{
if (ctx == NULL || keyLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
if (ctx->key.data != NULL) {
BSL_SAL_Free(ctx->key.data);
}
ctx->key.dataLen = keyLen;
ctx->key.data = (uint8_t *)BSL_SAL_Malloc(ctx->key.dataLen);
if (ctx->key.data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
if (key == NULL) {
int32_t ret = ctx->method.random(ctx->key.data, ctx->key.dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(ctx->key.data);
ctx->key.data = NULL;
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
} else {
(void)memcpy_s(ctx->key.data, ctx->key.dataLen, key, keyLen);
}
return HITLS_AUTH_SUCCESS;
}
typedef enum {
OTP_HMAC_SHA1SIZE = 20,
OTP_HMAC_SHA256SIZE = 32,
OTP_HMAC_SHA512SIZE = 64,
} OTP_HmacSize;
int32_t GenericOtpGen(HITLS_AUTH_OtpCtx *ctx, uint64_t movingFactor, char *otp, uint32_t *otpLen)
{
// Put movingFactor value into byte array
uint8_t counter[sizeof(movingFactor)];
for (uint32_t i = 0; i < sizeof(movingFactor); i++) {
counter[sizeof(movingFactor) - 1 - i] = (movingFactor >> (8 * i)) & 0xFF; // 8: the number of bits in a byte.
}
// Compute HMAC hash
uint8_t hmac[OTP_HMAC_SHA512SIZE];
uint32_t hmacLen;
switch (ctx->hashAlgId) {
case HITLS_AUTH_OTP_CRYPTO_SHA1:
hmacLen = OTP_HMAC_SHA1SIZE;
break;
case HITLS_AUTH_OTP_CRYPTO_SHA256:
hmacLen = OTP_HMAC_SHA256SIZE;
break;
case HITLS_AUTH_OTP_CRYPTO_SHA512:
hmacLen = OTP_HMAC_SHA512SIZE;
break;
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
uint32_t ret = ctx->method.hmac(ctx->libCtx, ctx->attrName, ctx->hashAlgId, ctx->key.data, ctx->key.dataLen,
(uint8_t *)&counter, sizeof(counter), hmac, &hmacLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// Dynamic truncation
uint8_t offset = hmac[hmacLen - 1] & 0x0F;
uint32_t binOtp = BSL_ByteToUint32(&hmac[offset]) & 0x7FFFFFFF;
// Stringify
for (uint32_t i = 0, div = 10, mod = 1; i < ctx->digits; i++, div *= 10, mod *= 10) { // 10: decimal number
otp[ctx->digits - i - 1] = '0' + binOtp % div / mod;
}
*otpLen = ctx->digits;
return HITLS_AUTH_SUCCESS;
}
int32_t HotpGen(HITLS_AUTH_OtpCtx *ctx, const BSL_Param *param, char *otp, uint32_t *otpLen, uint64_t *movingFactorOut)
{
uint64_t movingFactor = 0;
uint32_t movingFactorLen = (uint32_t)sizeof(movingFactor);
const BSL_Param *tmpParam = BSL_PARAM_FindConstParam(param, AUTH_PARAM_OTP_HOTP_COUNTER);
if (tmpParam == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_NO_COUNTER);
return HITLS_AUTH_OTP_NO_COUNTER;
}
int32_t ret = BSL_PARAM_GetValue(tmpParam, AUTH_PARAM_OTP_HOTP_COUNTER, BSL_PARAM_TYPE_OCTETS, &movingFactor,
&movingFactorLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (movingFactorOut != NULL) {
*movingFactorOut = movingFactor;
}
return GenericOtpGen(ctx, movingFactor, otp, otpLen);
}
int32_t TotpGen(HITLS_AUTH_OtpCtx *ctx, const BSL_Param *param, const int32_t offset, char *otp, uint32_t *otpLen,
uint64_t *movingFactorOut)
{
uint64_t curTime = 0;
uint32_t curTimeLen = (uint32_t)sizeof(curTime);
const BSL_Param *tmpParam = BSL_PARAM_FindConstParam(param, AUTH_PARAM_OTP_TOTP_CURTIME);
if (tmpParam == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_NO_CURTIME);
return HITLS_AUTH_OTP_NO_CURTIME;
}
int32_t ret =
BSL_PARAM_GetValue(tmpParam, AUTH_PARAM_OTP_TOTP_CURTIME, BSL_PARAM_TYPE_OCTETS, &curTime, &curTimeLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
TotpCtx *totpCtx = (TotpCtx *)ctx->ctx;
uint64_t movingFactor = ((curTime - totpCtx->startOffset) / totpCtx->timeStepSize) + offset;
if (movingFactorOut != NULL) {
*movingFactorOut = movingFactor;
}
return GenericOtpGen(ctx, movingFactor, otp, otpLen);
}
int32_t HITLS_AUTH_OtpGen(HITLS_AUTH_OtpCtx *ctx, const BSL_Param *param, char *otp, uint32_t *otpLen)
{
if (ctx == NULL || ctx->key.data == NULL || param == NULL || otp == NULL || otpLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
if (*otpLen < ctx->digits) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
switch (ctx->protocolType) {
case HITLS_AUTH_OTP_HOTP:
return HotpGen(ctx, param, otp, otpLen, NULL);
case HITLS_AUTH_OTP_TOTP:
return TotpGen(ctx, param, 0, otp, otpLen, NULL);
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_PROTOCOL_TYPE);
return HITLS_AUTH_OTP_INVALID_PROTOCOL_TYPE;
}
}
int32_t HotpValidate(HITLS_AUTH_OtpCtx *ctx, const BSL_Param *param, const char *otp, const uint32_t otpLen,
uint64_t *matched)
{
char targetOtp[OTP_MAX_DIGITS];
uint32_t targetOtpLen = sizeof(targetOtp);
uint64_t movingFactor;
int32_t ret = HotpGen(ctx, param, targetOtp, &targetOtpLen, &movingFactor);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (strncmp(otp, targetOtp, otpLen) != 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_VALIDATE_MISMATCH);
return HITLS_AUTH_OTP_VALIDATE_MISMATCH;
}
if (matched != NULL) {
*matched = movingFactor;
}
return HITLS_AUTH_SUCCESS;
}
int32_t TotpValidate(HITLS_AUTH_OtpCtx *ctx, const BSL_Param *param, const char *otp, const uint32_t otpLen,
uint64_t *matched)
{
int32_t ret;
char targetOtp[OTP_MAX_DIGITS];
uint32_t targetOtpLen = sizeof(targetOtp);
uint32_t validWindow = ((TotpCtx *)ctx->ctx)->validWindow;
uint64_t movingFactor;
for (int64_t offset = -(int64_t)validWindow; offset < (int64_t)validWindow + 1; offset++) {
ret = TotpGen(ctx, param, offset, targetOtp, &targetOtpLen, &movingFactor);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (strncmp(otp, targetOtp, otpLen) == 0) {
if (matched != NULL) {
*matched = movingFactor;
}
return HITLS_AUTH_SUCCESS;
}
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_VALIDATE_MISMATCH);
return HITLS_AUTH_OTP_VALIDATE_MISMATCH;
}
int32_t HITLS_AUTH_OtpValidate(HITLS_AUTH_OtpCtx *ctx, const BSL_Param *param, const char *otp, const uint32_t otpLen,
uint64_t *matched)
{
if (ctx == NULL || ctx->key.data == NULL || param == NULL || otp == NULL || otpLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
if (otpLen != ctx->digits) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_VALIDATE_MISMATCH);
return HITLS_AUTH_OTP_VALIDATE_MISMATCH;
}
switch (ctx->protocolType) {
case HITLS_AUTH_OTP_HOTP:
return HotpValidate(ctx, param, otp, otpLen, matched);
case HITLS_AUTH_OTP_TOTP:
return TotpValidate(ctx, param, otp, otpLen, matched);
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_PROTOCOL_TYPE);
return HITLS_AUTH_OTP_INVALID_PROTOCOL_TYPE;
}
} | 2401_83913325/openHiTLS_1 | auth/otp/src/otp.c | C | unknown | 8,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 <stdint.h>
#include "securec.h"
#include "auth_errno.h"
#include "auth_otp.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "otp.h"
int32_t OtpSetCtxContent(HITLS_AUTH_OtpCtx *ctx, int32_t cmd, void *param)
{
int32_t ret;
uint32_t valueLen;
BSL_Param *input;
switch (cmd) {
case HITLS_AUTH_OTP_SET_CTX_DIGITS:
input = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_DIGITS);
if (input == NULL || input->valueType != BSL_PARAM_TYPE_UINT32) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
uint32_t digits;
valueLen = sizeof(digits);
ret = BSL_PARAM_GetValue(input, AUTH_PARAM_OTP_CTX_DIGITS, BSL_PARAM_TYPE_UINT32, &digits, &valueLen);
if (ret != BSL_SUCCESS) {
return ret;
}
if (digits < OTP_MIN_DIGITS || digits > OTP_MAX_DIGITS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
ctx->digits = digits;
return HITLS_AUTH_SUCCESS;
case HITLS_AUTH_OTP_SET_CTX_HASHALGID:
input = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_HASHALGID);
if (input == NULL || input->valueType != BSL_PARAM_TYPE_OCTETS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
int32_t hashAlgId;
valueLen = sizeof(hashAlgId);
ret = BSL_PARAM_GetValue(input, AUTH_PARAM_OTP_CTX_HASHALGID, BSL_PARAM_TYPE_OCTETS, &hashAlgId, &valueLen);
if (ret != BSL_SUCCESS) {
return ret;
}
if (hashAlgId != HITLS_AUTH_OTP_CRYPTO_SHA1 && hashAlgId != HITLS_AUTH_OTP_CRYPTO_SHA256 &&
hashAlgId != HITLS_AUTH_OTP_CRYPTO_SHA512) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
ctx->hashAlgId = hashAlgId;
return HITLS_AUTH_SUCCESS;
case HITLS_AUTH_OTP_SET_CTX_TOTP_TIMESTEPSIZE:
input = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_TOTP_TIMESTEPSIZE);
if (input == NULL || input->valueType != BSL_PARAM_TYPE_UINT32) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
uint32_t timeStepSize;
valueLen = sizeof(timeStepSize);
ret = BSL_PARAM_GetValue(input, AUTH_PARAM_OTP_CTX_TOTP_TIMESTEPSIZE, BSL_PARAM_TYPE_UINT32, &timeStepSize,
&valueLen);
if (ret != BSL_SUCCESS) {
return ret;
}
if (timeStepSize == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
((TotpCtx *)(ctx->ctx))->timeStepSize = timeStepSize;
return HITLS_AUTH_SUCCESS;
case HITLS_AUTH_OTP_SET_CTX_TOTP_STARTOFFSET:
input = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_TOTP_STARTOFFSET);
if (input == NULL || input->valueType != BSL_PARAM_TYPE_OCTETS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
valueLen = sizeof(((TotpCtx *)(ctx->ctx))->startOffset);
return BSL_PARAM_GetValue(input, AUTH_PARAM_OTP_CTX_TOTP_STARTOFFSET, BSL_PARAM_TYPE_OCTETS,
&((TotpCtx *)(ctx->ctx))->startOffset, &valueLen);
case HITLS_AUTH_OTP_SET_CTX_TOTP_VALIDWINDOW:
input = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_TOTP_VALIDWINDOW);
if (input == NULL || input->valueType != BSL_PARAM_TYPE_UINT32) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
valueLen = sizeof(((TotpCtx *)(ctx->ctx))->validWindow);
return BSL_PARAM_GetValue(input, AUTH_PARAM_OTP_CTX_TOTP_VALIDWINDOW, BSL_PARAM_TYPE_UINT32,
&((TotpCtx *)(ctx->ctx))->validWindow, &valueLen);
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_CMD);
return HITLS_AUTH_OTP_INVALID_CMD;
}
}
static int32_t OtpGetCtxContent(HITLS_AUTH_OtpCtx *ctx, int32_t cmd, void *param)
{
BSL_Param *output;
switch (cmd) {
case HITLS_AUTH_OTP_GET_CTX_PROTOCOLTYPE:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_PROTOCOLTYPE);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
return BSL_PARAM_SetValue(output, AUTH_PARAM_OTP_CTX_PROTOCOLTYPE, BSL_PARAM_TYPE_OCTETS,
&ctx->protocolType, sizeof(ctx->protocolType));
case HITLS_AUTH_OTP_GET_CTX_KEY:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_KEY);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
if (output->valueLen < ctx->key.dataLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_OTP_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, ctx->key.data, ctx->key.dataLen);
output->useLen = ctx->key.dataLen;
return HITLS_AUTH_SUCCESS;
case HITLS_AUTH_OTP_GET_CTX_DIGITS:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_DIGITS);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_UINT32) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
return BSL_PARAM_SetValue(output, AUTH_PARAM_OTP_CTX_DIGITS, BSL_PARAM_TYPE_UINT32, &ctx->digits,
sizeof(ctx->digits));
case HITLS_AUTH_OTP_GET_CTX_HASHALGID:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_HASHALGID);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
return BSL_PARAM_SetValue(output, AUTH_PARAM_OTP_CTX_HASHALGID, BSL_PARAM_TYPE_OCTETS, &ctx->hashAlgId,
sizeof(ctx->hashAlgId));
case HITLS_AUTH_OTP_GET_CTX_TOTP_TIMESTEPSIZE:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_TOTP_TIMESTEPSIZE);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_UINT32) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
return BSL_PARAM_SetValue(output, AUTH_PARAM_OTP_CTX_TOTP_TIMESTEPSIZE, BSL_PARAM_TYPE_UINT32,
&((TotpCtx *)(ctx->ctx))->timeStepSize,
sizeof(((TotpCtx *)(ctx->ctx))->timeStepSize));
case HITLS_AUTH_OTP_GET_CTX_TOTP_STARTOFFSET:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_TOTP_STARTOFFSET);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
return BSL_PARAM_SetValue(output, AUTH_PARAM_OTP_CTX_TOTP_STARTOFFSET, BSL_PARAM_TYPE_OCTETS,
&((TotpCtx *)(ctx->ctx))->startOffset,
sizeof(((TotpCtx *)(ctx->ctx))->startOffset));
case HITLS_AUTH_OTP_GET_CTX_TOTP_VALIDWINDOW:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_OTP_CTX_TOTP_VALIDWINDOW);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_UINT32) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
return BSL_PARAM_SetValue(output, AUTH_PARAM_OTP_CTX_TOTP_VALIDWINDOW, BSL_PARAM_TYPE_UINT32,
&((TotpCtx *)(ctx->ctx))->validWindow,
sizeof(((TotpCtx *)(ctx->ctx))->validWindow));
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_CMD);
return HITLS_AUTH_OTP_INVALID_CMD;
}
}
int32_t HITLS_AUTH_OtpCtxCtrl(HITLS_AUTH_OtpCtx *ctx, int32_t cmd, void *param, uint32_t paramLen)
{
(void)paramLen;
switch (cmd) {
case HITLS_AUTH_OTP_SET_CTX_DIGITS:
case HITLS_AUTH_OTP_SET_CTX_HASHALGID:
return OtpSetCtxContent(ctx, cmd, param);
case HITLS_AUTH_OTP_SET_CTX_TOTP_TIMESTEPSIZE:
case HITLS_AUTH_OTP_SET_CTX_TOTP_STARTOFFSET:
case HITLS_AUTH_OTP_SET_CTX_TOTP_VALIDWINDOW:
if (ctx->protocolType != HITLS_AUTH_OTP_TOTP) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
return OtpSetCtxContent(ctx, cmd, param);
case HITLS_AUTH_OTP_GET_CTX_PROTOCOLTYPE:
case HITLS_AUTH_OTP_GET_CTX_DIGITS:
case HITLS_AUTH_OTP_GET_CTX_KEY:
case HITLS_AUTH_OTP_GET_CTX_HASHALGID:
return OtpGetCtxContent(ctx, cmd, param);
case HITLS_AUTH_OTP_GET_CTX_TOTP_TIMESTEPSIZE:
case HITLS_AUTH_OTP_GET_CTX_TOTP_STARTOFFSET:
case HITLS_AUTH_OTP_GET_CTX_TOTP_VALIDWINDOW:
if (ctx->protocolType != HITLS_AUTH_OTP_TOTP) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
return OtpGetCtxContent(ctx, cmd, param);
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_CMD);
return HITLS_AUTH_OTP_INVALID_CMD;
}
}
TotpCtx *OtpNewTotpCtx()
{
TotpCtx *ctx = (TotpCtx *)BSL_SAL_Calloc(1u, sizeof(TotpCtx));
if (ctx == NULL) {
return NULL;
}
ctx->timeStepSize = OTP_TOTP_DEFAULT_TIME_STEP_SIZE;
ctx->startOffset = OTP_TOTP_DEFAULT_START_OFFSET;
ctx->validWindow = OTP_TOTP_DEFAULT_VALID_WINDOW;
return ctx;
}
HITLS_AUTH_OtpCtx *HITLS_AUTH_OtpNewCtx(int32_t protocolType) {
return HITLS_AUTH_ProviderOtpNewCtx(NULL, protocolType, NULL);
}
HITLS_AUTH_OtpCtx *HITLS_AUTH_ProviderOtpNewCtx(CRYPT_EAL_LibCtx *libCtx, int32_t protocolType, const char *attrName)
{
if (protocolType != HITLS_AUTH_OTP_HOTP && protocolType != HITLS_AUTH_OTP_TOTP) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_PROTOCOL_TYPE);
return NULL;
}
HITLS_AUTH_OtpCtx *ctx = (HITLS_AUTH_OtpCtx *)BSL_SAL_Calloc(1u, sizeof(HITLS_AUTH_OtpCtx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
ctx->libCtx = libCtx;
ctx->attrName = attrName;
ctx->protocolType = protocolType;
ctx->digits = OTP_DEFAULT_DIGITS;
switch (protocolType) {
case HITLS_AUTH_OTP_HOTP:
case HITLS_AUTH_OTP_TOTP:
ctx->hashAlgId = HITLS_AUTH_OTP_CRYPTO_SHA1;
break;
default:
break;
}
switch (protocolType) {
case HITLS_AUTH_OTP_TOTP: {
TotpCtx *totpCtx = OtpNewTotpCtx();
if (totpCtx == NULL) {
BSL_SAL_Free(ctx);
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
ctx->ctx = (void *)totpCtx;
break;
}
case HITLS_AUTH_OTP_HOTP:
default:
break;
}
ctx->method = OtpCryptDefaultCb();
return ctx;
}
void OtpFreeTotpCtx(TotpCtx *ctx)
{
if (ctx == NULL) {
return;
}
BSL_SAL_Free(ctx);
}
void HITLS_AUTH_OtpFreeCtx(HITLS_AUTH_OtpCtx *ctx)
{
if (ctx == NULL) {
return;
}
BSL_SAL_ClearFree((void *)ctx->key.data, ctx->key.dataLen);
switch (ctx->protocolType) {
case HITLS_AUTH_OTP_TOTP:
OtpFreeTotpCtx(ctx->ctx);
break;
case HITLS_AUTH_OTP_HOTP:
default:
break;
}
BSL_SAL_Free(ctx);
}
int32_t HITLS_AUTH_OtpSetCryptCb(HITLS_AUTH_OtpCtx *ctx, int32_t cbType, void *cryptCb)
{
if (ctx == NULL || cryptCb == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
switch (cbType) {
case HITLS_AUTH_OTP_RANDOM_CB:
ctx->method.random = (HITLS_AUTH_OtpRandom)cryptCb;
break;
case HITLS_AUTH_OTP_HMAC_CB:
ctx->method.hmac = (HITLS_AUTH_OtpHmac)cryptCb;
break;
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_CRYPTO_CALLBACK_TYPE);
return HITLS_AUTH_OTP_INVALID_CRYPTO_CALLBACK_TYPE;
}
return HITLS_AUTH_SUCCESS;
} | 2401_83913325/openHiTLS_1 | auth/otp/src/otp_util.c | C | unknown | 13,869 |
/*
* 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 "auth_errno.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "crypt_eal_mac.h"
#include "crypt_eal_rand.h"
#include "crypt_errno.h"
#include "auth_otp.h"
#include "otp.h"
#include "bsl_sal.h"
int32_t OtpHmac(void *libCtx, const char *attrName, int32_t algId, const uint8_t *key, uint32_t keyLen,
const uint8_t *input, uint32_t inputLen, uint8_t *digest, uint32_t *digestLen)
{
(void)libCtx;
(void)attrName;
if (key == NULL || keyLen == 0 || input == NULL || inputLen == 0 || digest == NULL || digestLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId);
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
uint32_t hmacSize = CRYPT_EAL_GetMacLen(ctx);
if (hmacSize == 0 || *digestLen < hmacSize) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
CRYPT_EAL_MacFreeCtx(ctx);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
int32_t ret = CRYPT_EAL_MacInit(ctx, key, keyLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_EAL_MacFreeCtx(ctx);
return ret;
}
ret = CRYPT_EAL_MacUpdate(ctx, input, inputLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_EAL_MacFreeCtx(ctx);
return ret;
}
ret = CRYPT_EAL_MacFinal(ctx, digest, digestLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_EAL_MacFreeCtx(ctx);
return ret;
}
CRYPT_EAL_MacFreeCtx(ctx);
return CRYPT_SUCCESS;
}
int32_t OtpRandom(uint8_t *buffer, uint32_t bufferLen)
{
if (buffer == NULL || bufferLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_OTP_INVALID_INPUT);
return HITLS_AUTH_OTP_INVALID_INPUT;
}
return CRYPT_EAL_RandbytesEx(NULL, buffer, bufferLen);
}
OtpCryptCb OtpCryptDefaultCb(void)
{
OtpCryptCb method = {
.hmac = OtpHmac,
.random = OtpRandom,
};
return method;
} | 2401_83913325/openHiTLS_1 | auth/otp/src/otp_wrapper.c | C | unknown | 2,649 |
/*
* 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"
#include "auth_pake.h"
#include "spake2plus.h"
#include "auth_errno.h"
#include "crypt_errno.h"
#include "bsl_errno.h"
#include "bsl_params.h"
#include "securec.h"
#include "crypt_params_key.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
typedef struct HITLS_AUTH_PakeCtx {
CRYPT_EAL_LibCtx *libCtx;
const char *attrName;
HITLS_AUTH_PAKE_Type type;
HITLS_AUTH_PAKE_Role role;
BSL_Buffer password;
BSL_Buffer prover;
BSL_Buffer verifier;
BSL_Buffer context;
HITLS_AUTH_PAKE_CipherSuite cipherSuite;
void *ctx;
} HITLS_AUTH_PakeCtx;
void HITLS_AUTH_PakeFreeCtx(HITLS_AUTH_PakeCtx *ctx)
{
if (ctx == NULL) {
return;
}
BSL_SAL_ClearFree(ctx->password.data, ctx->password.dataLen);
BSL_SAL_ClearFree(ctx->prover.data, ctx->prover.dataLen);
BSL_SAL_ClearFree(ctx->verifier.data, ctx->verifier.dataLen);
BSL_SAL_ClearFree(ctx->context.data, ctx->context.dataLen);
switch (ctx->type) {
case HITLS_AUTH_PAKE_SPAKE2PLUS:
if (ctx->ctx != NULL) {
Spake2PlusFreeCtx(ctx->ctx);
}
break;
case HITLS_AUTH_PAKE_INVALID:
default:
break;
}
BSL_SAL_ClearFree(ctx, sizeof(HITLS_AUTH_PakeCtx));
}
HITLS_AUTH_PakeCtx *HITLS_AUTH_PakeNewCtx(CRYPT_EAL_LibCtx *libCtx, const char *attrName,
HITLS_AUTH_PAKE_Type type, HITLS_AUTH_PAKE_Role role,
HITLS_AUTH_PAKE_CipherSuite cipherSuite, BSL_Buffer password, BSL_Buffer prover,
BSL_Buffer verifier, BSL_Buffer context )
{
int32_t ret = HITLS_AUTH_SUCCESS;
if (type == HITLS_AUTH_PAKE_INVALID) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_PARAM);
return NULL;
}
if (role != HITLS_AUTH_PAKE_REQ && role != HITLS_AUTH_PAKE_RESP) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_PARAM);
return NULL;
}
HITLS_AUTH_PakeCtx *ctx = (HITLS_AUTH_PakeCtx *)BSL_SAL_Calloc(1, sizeof(HITLS_AUTH_PakeCtx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
return NULL;
}
ctx->libCtx = libCtx;
ctx->attrName = attrName;
ctx->type = type;
ctx->role = role;
ctx->cipherSuite = cipherSuite;
switch (cipherSuite.type) {
case HITLS_AUTH_PAKE_SPAKE2PLUS:
ctx->ctx = Spake2PlusNewCtx(cipherSuite.params.spake2plus.curve);
ret = Spake2PlusInitCipherSuite(ctx->ctx, &cipherSuite);
if (ctx->ctx == NULL|| ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
HITLS_AUTH_PakeFreeCtx(ctx);
return NULL;
}
break;
case HITLS_AUTH_PAKE_INVALID:
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_ALG_TYPE);
HITLS_AUTH_PakeFreeCtx(ctx);
return NULL;
}
ctx->password = (BSL_Buffer){.data = BSL_SAL_Malloc(password.dataLen), .dataLen = password.dataLen};
ctx->prover = (BSL_Buffer){.data = BSL_SAL_Malloc(prover.dataLen), .dataLen = prover.dataLen};
ctx->verifier = (BSL_Buffer){.data = BSL_SAL_Malloc(verifier.dataLen), .dataLen = verifier.dataLen};
ctx->context = (BSL_Buffer){.data = BSL_SAL_Malloc(context.dataLen), .dataLen = context.dataLen};
if (ctx->prover.data == NULL || ctx->verifier.data == NULL || ctx->context.data == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
HITLS_AUTH_PakeFreeCtx(ctx);
return NULL;
}
memcpy_s(ctx->password.data, ctx->password.dataLen, password.data, password.dataLen);
memcpy_s(ctx->prover.data, ctx->prover.dataLen, prover.data, prover.dataLen);
memcpy_s(ctx->verifier.data, ctx->verifier.dataLen, verifier.data, verifier.dataLen);
memcpy_s(ctx->context.data, ctx->context.dataLen, context.data, context.dataLen);
return ctx;
}
static int32_t HITLS_AUTH_PakeReqRegister(HITLS_AUTH_PakeCtx *ctx, CRYPT_EAL_KdfCTX* kdfctx,
BSL_Buffer in0, BSL_Buffer in1, BSL_Buffer in2)
{
if (ctx == NULL || kdfctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
if (ctx->role != HITLS_AUTH_PAKE_REQ) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_ROLE);
return HITLS_AUTH_PAKE_INVALID_ROLE;
}
int32_t ret = HITLS_AUTH_SUCCESS;
switch (ctx->type) {
case HITLS_AUTH_PAKE_SPAKE2PLUS:
ret=HITLS_AUTH_Spake2plusReqRegister(ctx, kdfctx, in0, in1, in2);
break;
default:
ret=HITLS_AUTH_INVALID_ARG;
break;
}
return ret;
}
static int32_t HITLS_AUTH_PakeRespRegister(HITLS_AUTH_PakeCtx *ctx, CRYPT_EAL_KdfCTX *kdfctx,
BSL_Buffer in0, BSL_Buffer in1, BSL_Buffer in2)
{
(void)kdfctx;
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
if (ctx->role != HITLS_AUTH_PAKE_RESP) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_ROLE);
return HITLS_AUTH_PAKE_INVALID_ROLE;
}
int32_t ret = HITLS_AUTH_SUCCESS;
switch (ctx->type) {
case HITLS_AUTH_PAKE_SPAKE2PLUS:
ret = HITLS_AUTH_Spake2plusRespRegister(ctx, in0, in1, in2);
break;
default:
ret=HITLS_AUTH_INVALID_ARG;
break;
}
return ret;
}
int32_t HITLS_AUTH_Pake_Ctrl(HITLS_AUTH_PakeCtx *ctx, HITLS_AUTH_PAKE_CtrlCmd cmd, CRYPT_EAL_KdfCTX *kdfctx,
BSL_Buffer in0, BSL_Buffer in1, BSL_Buffer in2)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
int32_t ret = HITLS_AUTH_SUCCESS;
switch (cmd) {
case HITLS_AUTH_PAKE_REQ_REGISTER:
if (ctx->role != HITLS_AUTH_PAKE_REQ) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_ROLE);
return HITLS_AUTH_PAKE_INVALID_ROLE;
}
ret=HITLS_AUTH_PakeReqRegister(ctx, kdfctx, in0, in1, in2);
break;
case HITLS_AUTH_PAKE_RESP_REGISTER:
if (ctx->role != HITLS_AUTH_PAKE_RESP) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_ROLE);
return HITLS_AUTH_PAKE_INVALID_ROLE;
}
ret = HITLS_AUTH_PakeRespRegister(ctx, kdfctx, in0, in1, in2);
break;
default:
ret = HITLS_AUTH_INVALID_ARG;
break;
}
return ret;
}
int32_t HITLS_AUTH_PakeReqSetup(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer in, BSL_Buffer *out)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
if (ctx->role != HITLS_AUTH_PAKE_REQ) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_ROLE);
return HITLS_AUTH_PAKE_INVALID_ROLE;
}
int32_t ret = HITLS_AUTH_SUCCESS;
switch (ctx->type) {
case HITLS_AUTH_PAKE_SPAKE2PLUS:
ret = HITLS_AUTH_Spake2plusReqSetup(ctx, in, out);
break;
default:
ret = HITLS_AUTH_INVALID_ARG;
break;
}
return ret;
}
int32_t HITLS_AUTH_PakeRespSetup(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer in0, BSL_Buffer in1,
BSL_Buffer *out0, BSL_Buffer *out1)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
if (ctx->role != HITLS_AUTH_PAKE_RESP) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_ROLE);
return HITLS_AUTH_PAKE_INVALID_ROLE;
}
int32_t ret = HITLS_AUTH_SUCCESS;
switch (ctx->type) {
case HITLS_AUTH_PAKE_SPAKE2PLUS:
ret = HITLS_AUTH_Spake2plusRespSetup(ctx, in0, in1, out0, out1);
break;
case HITLS_AUTH_PAKE_INVALID:
default:
ret=HITLS_AUTH_INVALID_ARG;
break;
}
return ret;
}
int32_t HITLS_AUTH_PakeReqDerive(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer in0, BSL_Buffer in1,
BSL_Buffer *out0, BSL_Buffer *out1)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
if (ctx->role != HITLS_AUTH_PAKE_REQ) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_ROLE);
return HITLS_AUTH_PAKE_INVALID_ROLE;
}
int32_t ret = HITLS_AUTH_SUCCESS;
switch (ctx->type) {
case HITLS_AUTH_PAKE_SPAKE2PLUS:
ret=HITLS_AUTH_Spake2plusReqDerive(ctx, in0, in1, out0, out1);
break;
case HITLS_AUTH_PAKE_INVALID:
default:
ret = HITLS_AUTH_INVALID_ARG;
break;
}
return ret;
}
int32_t HITLS_AUTH_PakeRespDerive(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer in0, BSL_Buffer *out0)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
if (ctx->role != HITLS_AUTH_PAKE_RESP) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_ROLE);
return HITLS_AUTH_PAKE_INVALID_ROLE;
}
int32_t ret = HITLS_AUTH_SUCCESS;
switch (ctx->type) {
case HITLS_AUTH_PAKE_SPAKE2PLUS:
ret = HITLS_AUTH_Spake2plusRespDerive(ctx, in0, out0);
break;
case HITLS_AUTH_PAKE_INVALID:
default:
ret = HITLS_AUTH_INVALID_ARG;
break;
}
return ret;
}
CRYPT_EAL_KdfCTX* HITLS_AUTH_PakeGetKdfCtx(HITLS_AUTH_PakeCtx* ctx, HITLS_AUTH_PAKE_KDF kdf)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return NULL;
}
switch (kdf.algId) {
case CRYPT_KDF_PBKDF2: {
uint32_t totalLen = ctx->password.dataLen + ctx->prover.dataLen + ctx->verifier.dataLen;
uint8_t *buffer = BSL_SAL_Malloc(totalLen);
if (buffer == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
return NULL;
}
CRYPT_MAC_AlgId algId = kdf.param.pbkdf2.mac;
uint32_t it = kdf.param.pbkdf2.iteration;
uint32_t saltLen = kdf.param.pbkdf2.salt.dataLen;
uint8_t *salt = kdf.param.pbkdf2.salt.data;
int32_t ret = HITLS_AUTH_SUCCESS;
(void)memcpy_s(buffer, ctx->password.dataLen, ctx->password.data, ctx->password.dataLen);
(void)memcpy_s(buffer + ctx->password.dataLen, ctx->prover.dataLen, ctx->prover.data, ctx->prover.dataLen);
(void)memcpy_s(buffer + ctx->password.dataLen + ctx->prover.dataLen, ctx->verifier.dataLen,
ctx->verifier.data, ctx->verifier.dataLen);
CRYPT_EAL_KdfCTX *kdfCtx = CRYPT_EAL_KdfNewCtx(kdf.algId);
if (kdfCtx == NULL) {
BSL_SAL_Free(buffer);
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
return NULL;
}
BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END};
ret = BSL_PARAM_InitValue(¶ms[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId));
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BSL_PARAM_InitValue(¶ms[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, buffer, totalLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BSL_PARAM_InitValue(¶ms[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen);
if (ret!=HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BSL_PARAM_InitValue(¶ms[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &it, sizeof(it));
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = CRYPT_EAL_KdfSetParam(kdfCtx, params);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
BSL_SAL_Free(buffer);
return kdfCtx;
ERR:
BSL_SAL_Free(buffer);
CRYPT_EAL_KdfFreeCtx(kdfCtx);
return NULL;
}
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_ALG_TYPE);
return NULL;
}
}
void *HITLS_AUTH_PakeGetInternalCtx(HITLS_AUTH_PakeCtx *ctx)
{
if (ctx == NULL)
return NULL;
return ctx->ctx;
}
BSL_Buffer HITLS_AUTH_PakeGetPassword(HITLS_AUTH_PakeCtx *ctx)
{
if (ctx == NULL)
return (BSL_Buffer){0};
return ctx->password;
}
BSL_Buffer HITLS_AUTH_PakeGetProver(HITLS_AUTH_PakeCtx *ctx)
{
if (ctx == NULL)
return (BSL_Buffer){0};
return ctx->prover;
}
BSL_Buffer HITLS_AUTH_PakeGetVerifier(HITLS_AUTH_PakeCtx *ctx)
{
if (ctx == NULL)
return (BSL_Buffer){0};
return ctx->verifier;
}
HITLS_AUTH_PAKE_CipherSuite HITLS_AUTH_PakeGetCipherSuite(HITLS_AUTH_PakeCtx *ctx)
{
if (ctx == NULL)
return (HITLS_AUTH_PAKE_CipherSuite){0};
return ctx->cipherSuite;
}
BSL_Buffer HITLS_AUTH_PakeGetContext(HITLS_AUTH_PakeCtx *ctx)
{
if (ctx == NULL)
return (BSL_Buffer){0};
return ctx->context;
}
| 2401_83913325/openHiTLS_1 | auth/pake/pake.c | C | unknown | 13,581 |
/*
* 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 SPAKE2PLUS_H
#define SPAKE2PLUS_H
/**
* @defgroup spake2plus
* @ingroup pake
* @brief spake2+ of pake module
*/
#include "hitls_build.h"
#include <stdint.h>
#include "bsl_types.h"
#include "auth_pake.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct HITLS_AUTH_PakeCtx HITLS_AUTH_PakeCtx;
typedef struct Spake2plusCtx Spake2plusCtx;
/**
* @ingroup spake2plus
* @brief Create a new SPAKE2+ context
*
* @param curve [IN] Elliptic curve parameter identifier
*
* @retval Spake2plusCtx pointer if successful, NULL if failed
*/
Spake2plusCtx* Spake2PlusNewCtx(CRYPT_PKEY_ParaId curve);
/**
* @ingroup spake2plus
* @brief Free SPAKE2+ context and associated resources
*
* @param ctx [IN] SPAKE2+ context to free
*/
void Spake2PlusFreeCtx(Spake2plusCtx* ctx);
/**
* @ingroup spake2plus
* @brief Initialize the cipher suite for SPAKE2+ context
*
* @param ctx [IN] SPAKE2+ context
* @param ciphersuite [IN] Cipher suite configuration containing cryptographic algorithms
*
* @retval #HITLS_AUTH_SUCCESS if successful
* Other error codes defined in hitls_errno.h if an error occurs
*/
int32_t Spake2PlusInitCipherSuite(Spake2plusCtx* ctx, HITLS_AUTH_PAKE_CipherSuite* ciphersuite);
/**
* @ingroup spake2plus
* @brief Register pre-computed parameters for SPAKE2+ requester
*
* @param ctx [IN] PAKE context
* @param kdfCtx [IN] KDF context
* @param exist_w0 [IN] Pre-computed w0 parameter which can be null
* @param exist_w1 [IN] Pre-computed w1 parameter which can be null
* @param exist_l [IN] Pre-computed L point which can be null
*
* @retval #HITLS_AUTH_SUCCESS if successful
* Other error codes defined in hitls_errno.h if an error occurs
*/
int32_t HITLS_AUTH_Spake2plusReqRegister(HITLS_AUTH_PakeCtx* ctx, CRYPT_EAL_KdfCTX* kdfCtx,
BSL_Buffer exist_w0, BSL_Buffer exist_w1, BSL_Buffer exist_l);
/**
* @ingroup spake2plus
* @brief Register pre-computed parameters for SPAKE2+ responder
*
* @param ctx [IN] PAKE context
* @param exist_w0 [IN] Pre-computed w0 parameter
* @param exist_w1 [IN] Pre-computed w1 parameter
* @param exist_l [IN] Pre-computed L point
*
* @retval #HITLS_AUTH_SUCCESS if successful
* Other error codes defined in hitls_errno.h if an error occurs
*/
int32_t HITLS_AUTH_Spake2plusRespRegister(HITLS_AUTH_PakeCtx* ctx,
BSL_Buffer exist_w0, BSL_Buffer exist_w1, BSL_Buffer exist_l);
/**
* @ingroup spake2plus
* @brief Perform SPAKE2+ requester setup phase
*
* @param ctx [IN] PAKE context
* @param x [IN] random number for key generation which can be null
* @param shareP [OUT] Output public share point to be sent to responder
*
* @retval #HITLS_AUTH_SUCCESS Setup successful
* Other error codes defined in hitls_errno.h if an error occurs
*/
int32_t HITLS_AUTH_Spake2plusReqSetup(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer x, BSL_Buffer *shareP);
/**
* @ingroup spake2plus
* @brief Perform SPAKE2+ responder setup phase
*
* @param ctx [IN] PAKE context
* @param y [IN] Input scalar for key generation which can be null
* @param shareP [IN] Public share point received from requester
* @param shareV [OUT] Output public share point to be sent to requester
* @param confirmV [OUT] Output confirmation value for initial verification
*
* @retval #HITLS_AUTH_SUCCESS Setup successful
* Other error codes defined in hitls_errno.h if an error occurs
*/
int32_t HITLS_AUTH_Spake2plusRespSetup(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer y,
BSL_Buffer shareP, BSL_Buffer *shareV, BSL_Buffer *confirmV);
/**
* @ingroup spake2plus
* @brief Derive session keys for SPAKE2+ requester
*
* @param ctx [IN] PAKE context
* @param shareV [IN] Public share point received from responder
* @param confirmV [IN] Confirmation value received from responder
* @param confirmP [OUT] Output confirmation value for responder verification
* @param out [OUT] Output derived key material
*
* @retval #HITLS_AUTH_SUCCESS Key derivation successful
* Other error codes defined in hitls_errno.h if an error occurs
*/
int32_t HITLS_AUTH_Spake2plusReqDerive(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer shareV,
BSL_Buffer confirmV, BSL_Buffer *confirmP, BSL_Buffer *out);
/**
* @ingroup spake2plus
* @brief Derive session keys for SPAKE2+ responder
*
* @param ctx [IN] PAKE context
* @param confirmP [IN] Confirmation value received from requester
* @param out [OUT] Output derived key material
*
* @retval #HITLS_AUTH_SUCCESS Key derivation successful
* Other error codes defined in hitls_errno.h if an error occurs
*/
int32_t HITLS_AUTH_Spake2plusRespDerive(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer confirmP, BSL_Buffer *out);
/**
* @ingroup spake2plus
* @brief Get internal context from PAKE context
*
* @param ctx [IN] PAKE context
*
* @retval non-NULL Internal SPAKE2+ context pointer
* NULL Invalid context
*/
void* HITLS_AUTH_PakeGetInternalCtx(HITLS_AUTH_PakeCtx *ctx);
/**
* @ingroup spake2plus
* @brief Get password from PAKE context
*
* @param ctx [IN] PAKE context
*
* @retval BSL_Buffer containing the authentication password
*/
BSL_Buffer HITLS_AUTH_PakeGetPassword(HITLS_AUTH_PakeCtx *ctx);
/**
* @ingroup spake2plus
* @brief Get prover from PAKE context
*
* @param ctx [IN] PAKE context
*
* @retval BSL_Buffer containing the prover information
*/
BSL_Buffer HITLS_AUTH_PakeGetProver(HITLS_AUTH_PakeCtx *ctx);
/**
* @ingroup spake2plus
* @brief Get verifier identity from PAKE context
*
* @param ctx [IN] PAKE context
*
* @retval BSL_Buffer containing verifier identity information
*/
BSL_Buffer HITLS_AUTH_PakeGetVerifier(HITLS_AUTH_PakeCtx *ctx);
/**
* @ingroup spake2plus
* @brief Get context data from PAKE context
*
* @param ctx [IN] PAKE context
*
* @retval BSL_Buffer containing additional protocol context data
*/
BSL_Buffer HITLS_AUTH_PakeGetContext(HITLS_AUTH_PakeCtx *ctx);
#ifdef __cplusplus
}
#endif
#endif // SPAKE2PLUS_H | 2401_83913325/openHiTLS_1 | auth/pake/spake2plus/include/spake2plus.h | C | unknown | 6,494 |
/*
* 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 SPAKE2PLUS_ECC_H
#define SPAKE2PLUS_ECC_H
#include "hitls_build.h"
uint8_t ECC_NISTP256_M[] = {
0x02, 0x88, 0x6e, 0x2f, 0x97, 0xac, 0xe4, 0x6e, 0x55, 0xba, 0x9d, 0xd7, 0x24, 0x25, 0x79, 0xf2, 0x99, 0x3b, 0x64,
0xe1, 0x6e, 0xf3, 0xdc, 0xab, 0x95, 0xaf, 0xd4, 0x97, 0x33, 0x3d, 0x8f, 0xa1, 0x2f
};
uint8_t ECC_NISTP256_N[] = {
0x03, 0xd8, 0xbb, 0xd6, 0xc6, 0x39, 0xc6, 0x29, 0x37, 0xb0, 0x4d, 0x99, 0x7f, 0x38, 0xc3, 0x77, 0x07, 0x19, 0xc6,
0x29, 0xd7, 0x01, 0x4d, 0x49, 0xa2, 0x4b, 0x4f, 0x98, 0xba, 0xa1, 0x29, 0x2b, 0x49
};
uint8_t ECC_NISTP384_M[] = {
0x03, 0x0f, 0xf0, 0x89, 0x5a, 0xe5, 0xeb, 0xf6, 0x18, 0x70, 0x80, 0xa8, 0x2d, 0x82, 0xb4, 0x2e, 0x27, 0x65, 0xe3,
0xb2, 0xf8, 0x74, 0x9c, 0x7e, 0x05, 0xeb, 0xa3, 0x66, 0x43, 0x4b, 0x36, 0x3d, 0x3d, 0xc3, 0x6f, 0x15, 0x31, 0x47,
0x39, 0x07, 0x4d, 0x2e, 0xb8, 0x61, 0x3f, 0xce, 0xec, 0x28, 0x53
};
uint8_t ECC_NISTP384_N[] = {
0x02, 0xc7, 0x2c, 0xf2, 0xe3, 0x90, 0x85, 0x3a, 0x1c, 0x1c, 0x4a, 0xd8, 0x16, 0xa6, 0x2f, 0xd1, 0x58, 0x24, 0xf5,
0x60, 0x78, 0x91, 0x8f, 0x43, 0xf9, 0x22, 0xca, 0x21, 0x51, 0x8f, 0x9c, 0x54, 0x3b, 0xb2, 0x52, 0xc5, 0x49, 0x02,
0x14, 0xcf, 0x9a, 0xa3, 0xf0, 0xba, 0xab, 0x4b, 0x66, 0x5c, 0x10
};
uint8_t ECC_NISTP521_M[] = {
0x02, 0x00, 0x3f, 0x06, 0xf3, 0x81, 0x31, 0xb2, 0xba, 0x26, 0x00, 0x79, 0x1e, 0x82, 0x48, 0x8e, 0x8d, 0x20, 0xab,
0x88, 0x9a, 0xf7, 0x53, 0xa4, 0x18, 0x06, 0xc5, 0xdb, 0x18, 0xd3, 0x7d, 0x85, 0x60, 0x8c, 0xfa, 0xe0, 0x6b, 0x82,
0xe4, 0xa7, 0x2c, 0xd7, 0x44, 0xc7, 0x19, 0x19, 0x35, 0x62, 0xa6, 0x53, 0xea, 0x1f, 0x11, 0x9e, 0xef, 0x93, 0x56,
0x90, 0x7e, 0xdc, 0x9b, 0x56, 0x97, 0x99, 0x62, 0xd7, 0xaa
};
uint8_t ECC_NISTP521_N[] = {
0x02, 0x00, 0xc7, 0x92, 0x4b, 0x9e, 0xc0, 0x17, 0xf3, 0x09, 0x45, 0x62, 0x89, 0x43, 0x36, 0xa5, 0x3c, 0x50, 0x16,
0x7b, 0xa8, 0xc5, 0x96, 0x38, 0x76, 0x88, 0x05, 0x42, 0xbc, 0x66, 0x9e, 0x49, 0x4b, 0x25, 0x32, 0xd7, 0x6c, 0x5b,
0x53, 0xdf, 0xb3, 0x49, 0xfd, 0xf6, 0x91, 0x54, 0xb9, 0xe0, 0x04, 0x8c, 0x58, 0xa4, 0x2e, 0x8e, 0xd0, 0x4c, 0xef,
0x05, 0x2a, 0x3b, 0xc3, 0x49, 0xd9, 0x55, 0x75, 0xcd, 0x25
};
#ifdef __cplusplus
}
#endif
#endif // SPAKE2PLUS_ECC_H | 2401_83913325/openHiTLS_1 | auth/pake/spake2plus/include/spake2plus_ecc.h | C | unknown | 2,726 |
/*
* 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"
#include <string.h>
#include <stdbool.h>
#include "auth_pake.h"
#include "crypt_ecc.h"
#include "spake2plus_ecc.h"
#include "auth_errno.h"
#include "securec.h"
#include "crypt_bn.h"
#include "crypt_eal_md.h"
#include "crypt_eal_kdf.h"
#include "crypt_eal_mac.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_pkey.h"
#include "crypt_params_key.h"
#include "crypt_errno.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "spake2plus.h"
#define SPAKE2PLUS_INVALID_ALG_INDEX 0xFF
#define MAX_ECC_PARAM_LEN 66 // Maximum length of elliptic curve parameters (in bytes)
#define MAX_ECC_KEY_LEN 133 // Maximum length of elliptic curve public key (in bytes)
#define LITTLE_BYTEORDER_LEN 8 // Length for little-endian byte order representation of 64-bit values
#define MAX_KEY_LEN 64
typedef struct Spake2plusCtx {
uint8_t index;
BSL_Buffer w0;
BSL_Buffer w1;
BSL_Buffer l;
BSL_Buffer x;
BSL_Buffer share;
BSL_Buffer key_shared;
BSL_Buffer confirmP;
BSL_Buffer confirmV;
BSL_Buffer m;
BSL_Buffer n;
} Spake2plusCtx;
typedef enum {
ECC_PARAM_P,
ECC_PARAM_N
} EccParamType;
typedef struct {
CRYPT_PKEY_ParaId curveId;
CRYPT_MD_AlgId hashId;
CRYPT_KDF_HKDF_AlgId kdfId;
CRYPT_MAC_AlgId macId;
uint16_t hashKeyLen;
uint16_t macKeyLen;
} Spake2Plus_AlgInfo;
static Spake2Plus_AlgInfo g_spake2PlusAlgInfo[] = {
{CRYPT_ECC_NISTP256, CRYPT_MD_SHA256, CRYPT_HKDF_SHA256, CRYPT_MAC_HMAC_SHA256, 32, 32},
{CRYPT_ECC_NISTP256, CRYPT_MD_SHA512, CRYPT_HKDF_SHA512, CRYPT_MAC_HMAC_SHA512, 64, 64},
{CRYPT_ECC_NISTP384, CRYPT_MD_SHA256, CRYPT_HKDF_SHA256, CRYPT_MAC_HMAC_SHA256, 32, 32},
{CRYPT_ECC_NISTP384, CRYPT_MD_SHA512, CRYPT_HKDF_SHA512, CRYPT_MAC_HMAC_SHA512, 64, 64},
{CRYPT_ECC_NISTP521, CRYPT_MD_SHA512, CRYPT_HKDF_SHA512, CRYPT_MAC_HMAC_SHA512, 64, 64},
{CRYPT_ECC_NISTP256, CRYPT_MD_SHA256, CRYPT_HKDF_SHA256, CRYPT_MAC_CMAC_AES128, 32, 16},
{CRYPT_ECC_NISTP256, CRYPT_MD_SHA512, CRYPT_HKDF_SHA512, CRYPT_MAC_CMAC_AES128, 64, 16},
};
void Spake2PlusFreeCtx(Spake2plusCtx *ctx)
{
if (ctx == NULL) {
return;
}
BSL_SAL_ClearFree(ctx->w0.data, ctx->w0.dataLen);
BSL_SAL_ClearFree(ctx->w1.data, ctx->w1.dataLen);
BSL_SAL_ClearFree(ctx->l.data, ctx->l.dataLen);
BSL_SAL_ClearFree(ctx->x.data, ctx->x.dataLen);
BSL_SAL_ClearFree(ctx->share.data, ctx->share.dataLen);
BSL_SAL_ClearFree(ctx->key_shared.data, ctx->key_shared.dataLen);
BSL_SAL_ClearFree(ctx->confirmP.data, ctx->confirmP.dataLen);
BSL_SAL_ClearFree(ctx->confirmV.data, ctx->confirmV.dataLen);
BSL_SAL_ClearFree(ctx, sizeof(Spake2plusCtx));
}
int32_t Spake2PlusInitCipherSuite(Spake2plusCtx* ctx, HITLS_AUTH_PAKE_CipherSuite* ciphersuite)
{
uint8_t position = SPAKE2PLUS_INVALID_ALG_INDEX;
if (ciphersuite == NULL || ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
for (uint8_t i = 0; i < sizeof(g_spake2PlusAlgInfo) / sizeof(Spake2Plus_AlgInfo); i++) {
if (ciphersuite->params.spake2plus.curve == g_spake2PlusAlgInfo[i].curveId &&
ciphersuite->params.spake2plus.hash == g_spake2PlusAlgInfo[i].hashId &&
ciphersuite->params.spake2plus.kdf == g_spake2PlusAlgInfo[i].kdfId &&
ciphersuite->params.spake2plus.mac == g_spake2PlusAlgInfo[i].macId) {
position = i;
break;
}
}
if (position == SPAKE2PLUS_INVALID_ALG_INDEX) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
ctx->index = position;
return HITLS_AUTH_SUCCESS;
}
Spake2plusCtx* Spake2PlusNewCtx(CRYPT_PKEY_ParaId curve)
{
Spake2plusCtx *ctx = (Spake2plusCtx*)BSL_SAL_Calloc(1, sizeof(Spake2plusCtx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return NULL;
}
ctx->w0 = (BSL_Buffer){.data = BSL_SAL_Malloc(MAX_ECC_PARAM_LEN), .dataLen = MAX_ECC_PARAM_LEN};
ctx->w1 = (BSL_Buffer){.data = BSL_SAL_Malloc(MAX_ECC_PARAM_LEN), .dataLen = MAX_ECC_PARAM_LEN};
ctx->l = (BSL_Buffer){.data = BSL_SAL_Malloc(MAX_ECC_KEY_LEN), .dataLen = MAX_ECC_KEY_LEN};
ctx->x = (BSL_Buffer){.data = BSL_SAL_Malloc(MAX_ECC_PARAM_LEN), .dataLen = MAX_ECC_PARAM_LEN};
ctx->share = (BSL_Buffer){.data = BSL_SAL_Malloc(MAX_ECC_KEY_LEN), .dataLen = MAX_ECC_KEY_LEN};
ctx->key_shared = (BSL_Buffer){.data = BSL_SAL_Malloc(MAX_KEY_LEN), .dataLen = MAX_KEY_LEN};
ctx->confirmP = (BSL_Buffer){.data = BSL_SAL_Malloc(MAX_KEY_LEN), .dataLen = MAX_KEY_LEN};
ctx->confirmV = (BSL_Buffer){.data = BSL_SAL_Malloc(MAX_KEY_LEN), .dataLen = MAX_KEY_LEN};
if (ctx->w0.data == NULL || ctx->w1.data == NULL || ctx->l.data == NULL || ctx->x.data == NULL ||
ctx->key_shared.data == NULL || ctx->confirmP.data == NULL || ctx->confirmV.data == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_MEM_ALLOC_FAIL);
goto err;
}
if (curve == CRYPT_ECC_NISTP256) {
ctx->m = (BSL_Buffer){.data = ECC_NISTP256_M, .dataLen = sizeof(ECC_NISTP256_M)};
ctx->n = (BSL_Buffer){.data = ECC_NISTP256_N, .dataLen= sizeof(ECC_NISTP256_N)};
}
if (curve == CRYPT_ECC_NISTP384) {
ctx->m = (BSL_Buffer){.data = ECC_NISTP384_M, .dataLen = sizeof(ECC_NISTP384_M)};
ctx->n = (BSL_Buffer){.data = ECC_NISTP384_N, .dataLen = sizeof(ECC_NISTP384_N)};
}
if (curve==CRYPT_ECC_NISTP521) {
ctx->m = (BSL_Buffer){.data = ECC_NISTP521_M, .dataLen = sizeof(ECC_NISTP521_M)};
ctx->n = (BSL_Buffer){.data = ECC_NISTP521_N, .dataLen = sizeof(ECC_NISTP521_N)};
}
return ctx;
err:
Spake2PlusFreeCtx(ctx);
return NULL;
}
static int32_t GetPubKeyData(CRYPT_EAL_PkeyCtx *pkey, uint8_t *out, uint32_t *outLen)
{
CRYPT_EAL_PkeyPub ephemPub = { 0 };
ephemPub.id = CRYPT_EAL_PkeyGetId(pkey);
ephemPub.key.eccPub.data = out;
ephemPub.key.eccPub.len = *outLen;
int32_t ret = CRYPT_EAL_PkeyGetPub(pkey, &ephemPub);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
*outLen = ephemPub.key.eccPub.len;
return HITLS_AUTH_SUCCESS;
}
static int32_t Spake2PlusGetEcc(CRYPT_EAL_PkeyCtx *pkey, EccParamType type, uint8_t *out, uint32_t *outLen)
{
uint8_t ecP[MAX_ECC_PARAM_LEN];
uint8_t ecA[MAX_ECC_PARAM_LEN];
uint8_t ecB[MAX_ECC_PARAM_LEN];
uint8_t ecN[MAX_ECC_PARAM_LEN];
uint8_t ecH[MAX_ECC_PARAM_LEN];
uint8_t ecX[MAX_ECC_PARAM_LEN];
uint8_t ecY[MAX_ECC_PARAM_LEN];
CRYPT_EAL_PkeyPara para = {0};
para.id = CRYPT_EAL_PkeyGetId(pkey);
para.para.eccPara.p = ecP;
para.para.eccPara.a = ecA;
para.para.eccPara.b = ecB;
para.para.eccPara.n = ecN;
para.para.eccPara.h = ecH;
para.para.eccPara.x = ecX;
para.para.eccPara.y = ecY;
para.para.eccPara.pLen = MAX_ECC_PARAM_LEN;
para.para.eccPara.aLen = MAX_ECC_PARAM_LEN;
para.para.eccPara.bLen = MAX_ECC_PARAM_LEN;
para.para.eccPara.nLen = MAX_ECC_PARAM_LEN;
para.para.eccPara.hLen = MAX_ECC_PARAM_LEN;
para.para.eccPara.xLen = MAX_ECC_PARAM_LEN;
para.para.eccPara.yLen = MAX_ECC_PARAM_LEN;
int32_t ret = CRYPT_EAL_PkeyGetPara(pkey, ¶);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
switch (type) {
case ECC_PARAM_P:
(void)memcpy_s(out, para.para.eccPara.pLen, para.para.eccPara.p, para.para.eccPara.pLen);
*outLen = para.para.eccPara.pLen;
break;
case ECC_PARAM_N:
(void)memcpy_s(out, para.para.eccPara.nLen, para.para.eccPara.n, para.para.eccPara.nLen);
*outLen = para.para.eccPara.nLen;
break;
default:
return HITLS_AUTH_INVALID_ARG;
}
return HITLS_AUTH_SUCCESS;
}
int32_t HITLS_AUTH_Spake2plusReqRegister(HITLS_AUTH_PakeCtx* ctx, CRYPT_EAL_KdfCTX* kdfCtx, BSL_Buffer exist_w0,
BSL_Buffer exist_w1, BSL_Buffer exist_l)
{
bool allNull = (exist_w0.data == NULL && exist_w1.data == NULL && exist_l.data == NULL);
bool allNotNull = (exist_w0.data != NULL && exist_w1.data != NULL && exist_l.data != NULL);
if (!allNull && !allNotNull) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
Spake2plusCtx *spakeCtx = (Spake2plusCtx *)HITLS_AUTH_PakeGetInternalCtx(ctx);
if (spakeCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_CONTEXT);
return HITLS_AUTH_PAKE_INVALID_CONTEXT;
}
if (allNotNull) {
spakeCtx->w0.dataLen = exist_w0.dataLen;
spakeCtx->w1.dataLen = exist_w1.dataLen;
spakeCtx->l.dataLen = exist_l.dataLen;
(void)memcpy_s(spakeCtx->w0.data, exist_w0.dataLen, exist_w0.data, exist_w0.dataLen);
(void)memcpy_s(spakeCtx->w1.data, exist_w1.dataLen, exist_w1.data, exist_w1.dataLen);
(void)memcpy_s(spakeCtx->l.data, exist_l.dataLen, exist_l.data, exist_l.dataLen);
return HITLS_AUTH_SUCCESS;
}
// data from rfc9383 section 3.2, length>=2*ceil(log2(p))+64 bits
uint32_t outLen = 0;
if (g_spake2PlusAlgInfo[spakeCtx->index].curveId == CRYPT_ECC_NISTP256) {
outLen = 80;
} else if (g_spake2PlusAlgInfo[spakeCtx->index].curveId == CRYPT_ECC_NISTP384) {
outLen = 112;
} else if (g_spake2PlusAlgInfo[spakeCtx->index].curveId == CRYPT_ECC_NISTP521) {
outLen = 148;
} else {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
uint8_t out[outLen];
uint8_t w0s[outLen/2];
uint32_t w0sLen = outLen/2;
uint8_t w1s[outLen/2];
uint32_t w1sLen = outLen/2;
uint8_t p[MAX_ECC_PARAM_LEN];
uint32_t pLen = MAX_ECC_PARAM_LEN;
uint8_t w0_data[outLen/2];
uint32_t w0_dataLen = outLen/2;
uint8_t w1_data[outLen/2];
uint32_t w1_dataLen = outLen/2;
uint8_t l_data[MAX_ECC_KEY_LEN];
uint32_t l_dataLen = MAX_ECC_KEY_LEN;
int32_t ret = HITLS_AUTH_SUCCESS;
BN_BigNum* w0s0 = BN_Create(w0sLen*8);
BN_BigNum* w1s0 = BN_Create(w1sLen*8);
BN_BigNum* p0 = BN_Create(pLen*8);
BN_BigNum *result = BN_Create(pLen*8);
ECC_Para *para = ECC_NewPara(g_spake2PlusAlgInfo[spakeCtx->index].curveId);
ECC_Point* L = ECC_NewPoint(para);
CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH);
BN_Optimizer *opt = BN_OptimizerCreate();
if (opt == NULL || w0s0 == NULL || w1s0 == NULL || p0 == NULL || result == NULL || para == NULL ||
L == NULL || pkeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_MEM_ALLOC_FAIL);
ret = HITLS_AUTH_MEM_ALLOC_FAIL;
goto ERR;
}
ret = CRYPT_EAL_KdfDerive(kdfCtx, out, outLen);
if (ret!=HITLS_AUTH_SUCCESS) {
goto ERR;
}
(void)memcpy_s(w0s, sizeof(w0s), out, w0sLen);
(void)memcpy_s(w1s, sizeof(w1s), out + w0sLen, outLen - w0sLen);
ret = BN_Bin2Bn(w0s0, w0s, w0sLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Bin2Bn(w1s0, w1s, w1sLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = CRYPT_EAL_PkeySetParaById(pkeyCtx, g_spake2PlusAlgInfo[spakeCtx->index].curveId);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = Spake2PlusGetEcc(pkeyCtx, ECC_PARAM_P, p, &pLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Bin2Bn(p0, p, pLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Mod(result, w0s0, p0, opt);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Bn2Bin(result, w0_data, &w0_dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Mod(result, w1s0, p0, opt);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Bn2Bin(result, w1_data, &w1_dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_PointMul(para, L, result, NULL);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_EncodePoint(para, L, l_data, &l_dataLen, CRYPT_POINT_UNCOMPRESSED);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
spakeCtx->w0.dataLen = w0_dataLen;
spakeCtx->w1.dataLen = w1_dataLen;
spakeCtx->l.dataLen = l_dataLen;
(void)memcpy_s(spakeCtx->w0.data, w0_dataLen, w0_data, w0_dataLen);
(void)memcpy_s(spakeCtx->w1.data, w1_dataLen, w1_data, w1_dataLen);
(void)memcpy_s(spakeCtx->l.data, l_dataLen, l_data, l_dataLen);
ERR:
BN_Destroy(w0s0);
BN_Destroy(w1s0);
BN_Destroy(p0);
BN_Destroy(result);
BN_OptimizerDestroy(opt);
CRYPT_EAL_PkeyFreeCtx(pkeyCtx);
ECC_FreePoint(L);
ECC_FreePara(para);
if (ret != HITLS_AUTH_SUCCESS) {
Spake2PlusFreeCtx(spakeCtx);
}
return ret;
}
int32_t HITLS_AUTH_Spake2plusRespRegister(HITLS_AUTH_PakeCtx* ctx, BSL_Buffer exist_w0,
BSL_Buffer exist_w1, BSL_Buffer exist_l)
{
Spake2plusCtx *spakeCtx = (Spake2plusCtx *)HITLS_AUTH_PakeGetInternalCtx(ctx);
if (spakeCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
if (exist_w0.data != NULL && exist_w1.data != NULL && exist_l.data != NULL) {
spakeCtx->w0.dataLen = exist_w0.dataLen;
spakeCtx->w1.dataLen = exist_w1.dataLen;
spakeCtx->l.dataLen = exist_l.dataLen;
(void)memcpy_s(spakeCtx->w0.data, exist_w0.dataLen, exist_w0.data, exist_w0.dataLen);
(void)memcpy_s(spakeCtx->w1.data, exist_w1.dataLen, exist_w1.data, exist_w1.dataLen);
(void)memcpy_s(spakeCtx->l.data, exist_l.dataLen, exist_l.data, exist_l.dataLen);
return HITLS_AUTH_SUCCESS;
}
Spake2PlusFreeCtx(spakeCtx);
return HITLS_AUTH_PAKE_INVALID_PARAM;
}
static int32_t Spake2PlusCreatePkeyCtx(uint8_t index, CRYPT_EAL_PkeyCtx **pkeyCtx)
{
CRYPT_EAL_PkeyCtx *pkey = NULL;
pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH);
if (pkey == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
return HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
}
CRYPT_PKEY_ParaId curveId = g_spake2PlusAlgInfo[index].curveId;
int32_t ret = CRYPT_EAL_PkeySetParaById(pkey, curveId);
if (ret != HITLS_AUTH_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pkey);
return ret;
}
*pkeyCtx = pkey;
return HITLS_AUTH_SUCCESS;
}
static int32_t Spake2PlusCreatePubKey(Spake2plusCtx* ctx, uint8_t *pubKey, uint32_t pubKeyLen, CRYPT_EAL_PkeyCtx **pkey)
{
CRYPT_EAL_PkeyCtx *tmpKey = NULL;
int32_t ret = Spake2PlusCreatePkeyCtx(ctx->index, &tmpKey);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
CRYPT_EAL_PkeyPub pub = {0};
pub.id = CRYPT_EAL_PkeyGetId(tmpKey);
pub.key.eccPub.data = pubKey;
pub.key.eccPub.len = pubKeyLen;
ret = CRYPT_EAL_PkeySetPub(tmpKey, &pub);
if (ret != HITLS_AUTH_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(tmpKey);
return ret;
}
*pkey = tmpKey;
return HITLS_AUTH_SUCCESS;
}
static int32_t Spake2PlusGenerateRandNum(uint8_t *num, uint8_t *p, uint32_t pLen)
{
BN_BigNum *p0 = BN_Create(pLen*8);
BN_BigNum *x0 = BN_Create(pLen*8);
if (p0 == NULL || x0 == NULL) {
BN_Destroy(p0);
BN_Destroy(x0);
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
return HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
}
int32_t ret = HITLS_AUTH_SUCCESS;
ret = BN_Bin2Bn(p0, p, pLen);
if (ret != HITLS_AUTH_SUCCESS) {
BN_Destroy(p0);
BN_Destroy(x0);
return ret;
}
uint8_t *x = BSL_SAL_Malloc(pLen);
if (x == NULL) {
BN_Destroy(p0);
BN_Destroy(x0);
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
return HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
}
(void)memset_s(x, pLen, 0, pLen);
uint32_t retryCount = 0;
const uint32_t MAX_RETRIES = 1000;
bool success = false;
while (retryCount < MAX_RETRIES) {
ret = CRYPT_EAL_RandbytesEx(NULL, x, pLen);
if (ret != HITLS_AUTH_SUCCESS) {
break;
}
ret = BN_Bin2Bn(x0, x, pLen);
if (ret != HITLS_AUTH_SUCCESS) {
break;
}
if (BN_Cmp(x0, p0) == -1) {
success = true;
break;
}
++retryCount;
}
if (ret != HITLS_AUTH_SUCCESS) {
ret = CRYPT_NO_REGIST_RAND;
} else if (!success) {
ret = CRYPT_NO_REGIST_RAND;
} else {
(void)memcpy_s(num, pLen, x, pLen);
ret = HITLS_AUTH_SUCCESS;
}
BSL_SAL_Free(x);
BN_Destroy(p0);
BN_Destroy(x0);
return ret;
}
static int32_t Spake2PlusInit(Spake2plusCtx *ctx, uint8_t *randnum, uint32_t *randnumLen)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
uint8_t p[MAX_ECC_PARAM_LEN];
uint32_t pLen = MAX_ECC_PARAM_LEN;
CRYPT_EAL_PkeyCtx* mKey = NULL;
int32_t ret = Spake2PlusCreatePubKey(ctx, ctx->m.data, ctx->m.dataLen, &mKey);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = Spake2PlusGetEcc(mKey, ECC_PARAM_P, p, &pLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = Spake2PlusGenerateRandNum(randnum, p, pLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
*randnumLen = pLen;
ERR:
if (mKey != NULL) {
CRYPT_EAL_PkeyFreeCtx(mKey);
}
return ret;
}
static int32_t Spake2PlusProverComputeX(Spake2plusCtx* ctx, uint8_t *x, uint32_t xLen,
uint8_t *shareP, uint32_t *sharePLen)
{
if (ctx == NULL || x == NULL || xLen <= 0 || shareP == NULL || sharePLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
ECC_Para *para = ECC_NewPara(g_spake2PlusAlgInfo[ctx->index].curveId);
ECC_Point *X = ECC_NewPoint(para);
ECC_Point *m = ECC_NewPoint(para);
BN_BigNum *x0 = BN_Create(xLen * 8);
BN_BigNum *w0 = BN_Create(ctx->w0.dataLen * 8);
int32_t ret = HITLS_AUTH_SUCCESS;
if (para == NULL || X == NULL || m == NULL || x0 == NULL || w0 == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
ret = HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
goto EXIT;
}
ret = BN_Bin2Bn(x0, x, xLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto EXIT;
}
ret = BN_Bin2Bn(w0, ctx->w0.data, ctx->w0.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto EXIT;
}
ret = ECC_DecodePoint(para, m, ctx->m.data, ctx->m.dataLen);
if (ret !=HITLS_AUTH_SUCCESS || ECC_PointCheck(m) != HITLS_AUTH_SUCCESS) {
goto EXIT;
}
// shareP(X)=x*G+w0*m
ret = ECC_PointMulAdd(para, X, x0, w0, m);
if (ret != HITLS_AUTH_SUCCESS) {
goto EXIT;
}
ret = ECC_EncodePoint(para, X, shareP, sharePLen, CRYPT_POINT_UNCOMPRESSED);
if (ret != HITLS_AUTH_SUCCESS) {
goto EXIT;
}
EXIT:
BN_Destroy(x0);
BN_Destroy(w0);
ECC_FreePoint(X);
ECC_FreePoint(m);
ECC_FreePara(para);
return ret;
}
static int32_t Spake2PlusVerifierComputeY(Spake2plusCtx* ctx, uint8_t *y, uint32_t yLen,
uint8_t *shareV, uint32_t *shareVLen)
{
if (ctx == NULL || y == NULL || yLen <= 0 || shareV == NULL || shareVLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
ECC_Para *para = ECC_NewPara(g_spake2PlusAlgInfo[ctx->index].curveId);
ECC_Point *Y = ECC_NewPoint(para);
ECC_Point *n = ECC_NewPoint(para);
BN_BigNum *y0 = BN_Create(yLen * 8);
BN_BigNum *w0 = BN_Create(ctx->w0.dataLen * 8);
int32_t ret = HITLS_AUTH_SUCCESS;
if (para == NULL || Y == NULL || n == NULL || y0 == NULL || w0 == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
ret = HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
goto EXIT;
}
ret = BN_Bin2Bn(y0, y, yLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto EXIT;
}
ret = BN_Bin2Bn(w0, ctx->w0.data, ctx->w0.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto EXIT;
}
ret = ECC_DecodePoint(para, n, ctx->n.data, ctx->n.dataLen);
if (ret!=HITLS_AUTH_SUCCESS || ECC_PointCheck(n) != HITLS_AUTH_SUCCESS) {
goto EXIT;
}
// shareV(Y)=y*G+w0*n
ret = ECC_PointMulAdd(para, Y, y0, w0, n);
if (ret != HITLS_AUTH_SUCCESS) {
goto EXIT;
}
ret = ECC_EncodePoint(para, Y, shareV, shareVLen, CRYPT_POINT_UNCOMPRESSED);
if (ret != HITLS_AUTH_SUCCESS) {
goto EXIT;
}
EXIT:
BN_Destroy(y0);
BN_Destroy(w0);
ECC_FreePoint(Y);
ECC_FreePoint(n);
ECC_FreePara(para);
return ret;
}
static int32_t Spake2PlusProverFinish(Spake2plusCtx *ctx, BSL_Buffer x, BSL_Buffer shareV,
BSL_Buffer *z, BSL_Buffer *v)
{
if (ctx == NULL || x.data == NULL || x.dataLen <= 0 || shareV.data == NULL || shareV.dataLen <= 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
BN_BigNum *w0 = BN_Create(ctx->w0.dataLen * 8);
BN_BigNum *w1 = BN_Create(ctx->w1.dataLen * 8);
BN_BigNum *w2 = BN_Create(ctx->w0.dataLen * 8);
BN_BigNum *n0 = BN_Create(ctx->w0.dataLen * 8);
BN_BigNum *x0 = BN_Create(x.dataLen * 8);
ECC_Para *para = ECC_NewPara(g_spake2PlusAlgInfo[ctx->index].curveId);
ECC_Point *Z = ECC_NewPoint(para);
ECC_Point *N = ECC_NewPoint(para);
ECC_Point *Y = ECC_NewPoint(para);
ECC_Point *Z0 = ECC_NewPoint(para);
ECC_Point *V0 = ECC_NewPoint(para);
CRYPT_EAL_PkeyCtx* shareVKey = NULL;
int32_t ret = HITLS_AUTH_SUCCESS;
if (para == NULL || Z == NULL || N == NULL || Y == NULL || Z0 == NULL || V0 == NULL ||
w0 == NULL || w1 == NULL || w2 == NULL || n0 == NULL || x0 == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
ret = HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
goto ERR;
}
ret = BN_Bin2Bn(w0, ctx->w0.data, ctx->w0.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Bin2Bn(w1, ctx->w1.data, ctx->w1.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Bin2Bn(x0, x.data, x.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
uint8_t n[MAX_ECC_PARAM_LEN];
uint32_t nLen = MAX_ECC_PARAM_LEN;
ret = Spake2PlusCreatePubKey(ctx, shareV.data, shareV.dataLen, &shareVKey);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = Spake2PlusGetEcc(shareVKey, ECC_PARAM_N, n, &nLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Bin2Bn(n0, n, nLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Sub(w2, n0, w0);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_DecodePoint(para, N, ctx->n.data, ctx->n.dataLen);
if (ret != HITLS_AUTH_SUCCESS || ECC_PointCheck(N) != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_PointMul(para, Z, w2, N);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_DecodePoint(para, Y, shareV.data, shareV.dataLen);
if (ret != HITLS_AUTH_SUCCESS || ECC_PointCheck(Y) != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_PointAddAffine(para, Z, Z, Y);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_PointMul(para, Z0, x0, Z);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_EncodePoint(para, Z0, z->data, &(z->dataLen), CRYPT_POINT_UNCOMPRESSED);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_PointMul(para, V0, w1, Z);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_EncodePoint(para, V0, v->data, &(v->dataLen), CRYPT_POINT_UNCOMPRESSED);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ERR:
BN_Destroy(w0);
BN_Destroy(w1);
BN_Destroy(w2);
BN_Destroy(n0);
BN_Destroy(x0);
ECC_FreePoint(Z);
ECC_FreePoint(N);
ECC_FreePoint(Y);
ECC_FreePoint(Z0);
ECC_FreePoint(V0);
ECC_FreePara(para);
CRYPT_EAL_PkeyFreeCtx(shareVKey);
return ret;
}
static int32_t Spake2PlusVerifierFinish(Spake2plusCtx *ctx, BSL_Buffer y, BSL_Buffer shareP,
BSL_Buffer *z, BSL_Buffer *v)
{
if (ctx == NULL || y.data == NULL || y.dataLen <= 0 || shareP.data == NULL || shareP.dataLen <= 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
BN_BigNum *w0 = BN_Create(ctx->w0.dataLen * 8);
BN_BigNum *n0 = BN_Create(ctx->w0.dataLen * 8);
BN_BigNum *w2 = BN_Create(ctx->w0.dataLen * 8);
BN_BigNum *y0 = BN_Create(y.dataLen * 8);
ECC_Para *para = ECC_NewPara(g_spake2PlusAlgInfo[ctx->index].curveId);
ECC_Point *Z = ECC_NewPoint(para);
ECC_Point *M = ECC_NewPoint(para);
ECC_Point *X = ECC_NewPoint(para);
ECC_Point *Z0 = ECC_NewPoint(para);
ECC_Point *V0 = ECC_NewPoint(para);
ECC_Point *L = ECC_NewPoint(para);
CRYPT_EAL_PkeyCtx* sharePKey = NULL;
int32_t ret = HITLS_AUTH_SUCCESS;
if (para == NULL || Z == NULL || M == NULL || X == NULL || Z0 == NULL || V0 == NULL ||
L == NULL || w0 == NULL || w2 == NULL || n0 == NULL || y0 == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
ret = HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
goto ERR;
}
uint8_t n[MAX_ECC_PARAM_LEN];
uint32_t nLen = MAX_ECC_PARAM_LEN;
ret = BN_Bin2Bn(w0, ctx->w0.data, ctx->w0.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Bin2Bn(y0, y.data, y.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = Spake2PlusCreatePubKey(ctx, shareP.data, shareP.dataLen, &sharePKey);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = Spake2PlusGetEcc(sharePKey, ECC_PARAM_N, n, &nLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Bin2Bn(n0, n, nLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BN_Sub(w2, n0, w0);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_DecodePoint(para, M, ctx->m.data, ctx->m.dataLen);
if (ret != HITLS_AUTH_SUCCESS || ECC_PointCheck(M) != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_PointMul(para, Z, w2, M);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_DecodePoint(para, X, shareP.data, shareP.dataLen);
if (ret != HITLS_AUTH_SUCCESS || ECC_PointCheck(X) != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_PointAddAffine(para, Z, Z, X);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_PointMul(para, Z0, y0, Z);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_EncodePoint(para, Z0, z->data, &(z->dataLen), CRYPT_POINT_UNCOMPRESSED);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_DecodePoint(para, L, ctx->l.data, ctx->l.dataLen);
if (ret != HITLS_AUTH_SUCCESS || ECC_PointCheck(L) != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_PointMul(para, V0, y0, L);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = ECC_EncodePoint(para, V0, v->data, &(v->dataLen), CRYPT_POINT_UNCOMPRESSED);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ERR:
BN_Destroy(w0);
BN_Destroy(w2);
BN_Destroy(n0);
BN_Destroy(y0);
ECC_FreePoint(Z);
ECC_FreePoint(M);
ECC_FreePoint(X);
ECC_FreePoint(L);
ECC_FreePoint(Z0);
ECC_FreePoint(V0);
ECC_FreePara(para);
CRYPT_EAL_PkeyFreeCtx(sharePKey);
return ret;
}
static void uint32_to_le_bytes(uint32_t len, uint8_t out[8])
{
out[0] = (uint8_t)(len & 0xFF);
out[1] = (uint8_t)((len >> 8) & 0xFF);
out[2] = (uint8_t)((len >> 16) & 0xFF);
out[3] = (uint8_t)((len >> 24) & 0xFF);
out[4] = out[5] = out[6] = out[7] = 0;
}
#define APPEND_FIELD(data, len) ({ \
int32_t __ret = HITLS_AUTH_SUCCESS; \
uint8_t len_bytes[8]; \
uint32_to_le_bytes(len, len_bytes); \
if (remaining < 8 + len) { \
__ret = CRYPT_MEM_ALLOC_FAIL; \
} else { \
(void)memcpy_s(pos, 8, len_bytes, 8); \
pos += 8; remaining -= 8; \
(void)memcpy_s(pos, len, data, len); \
pos += len; remaining -= len; \
} \
__ret; \
})
static int32_t Spake2PlusComputeTranscript(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer shareP, BSL_Buffer shareV,
BSL_Buffer z, BSL_Buffer v, BSL_Buffer *tt, uint32_t *totalSize)
{
if (ctx == NULL || shareP.data == NULL || shareP.dataLen <= 0 || shareV.data == NULL || shareV.dataLen <= 0 ||
z.data == NULL || z.dataLen <= 0 || v.data == NULL || v.dataLen <= 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
uint8_t *pos = tt ? tt->data : NULL;
size_t remaining = tt ? tt->dataLen : 0;
CRYPT_EAL_PkeyCtx* mKey = NULL;
CRYPT_EAL_PkeyCtx* nKey = NULL;
Spake2plusCtx *spakeCtx = (Spake2plusCtx *)HITLS_AUTH_PakeGetInternalCtx(ctx);
if (spakeCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_CONTEXT);
return HITLS_AUTH_PAKE_INVALID_CONTEXT;
}
uint8_t m[MAX_ECC_KEY_LEN];
uint32_t mLen = MAX_ECC_KEY_LEN;
uint8_t n[MAX_ECC_KEY_LEN];
uint32_t nLen = MAX_ECC_KEY_LEN;
BSL_Buffer prover = HITLS_AUTH_PakeGetProver(ctx);
BSL_Buffer verifier = HITLS_AUTH_PakeGetVerifier(ctx);
BSL_Buffer context = HITLS_AUTH_PakeGetContext(ctx);
int32_t ret = HITLS_AUTH_SUCCESS;
ret = Spake2PlusCreatePubKey(spakeCtx, spakeCtx->m.data, spakeCtx->m.dataLen, &mKey);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = GetPubKeyData(mKey, m, &mLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = Spake2PlusCreatePubKey(spakeCtx, spakeCtx->n.data, spakeCtx->n.dataLen, &nKey);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = GetPubKeyData(nKey, n, &nLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
if (totalSize) {
*totalSize = 8 + context.dataLen + 8 + prover.dataLen + 8 + verifier.dataLen + 8 + mLen + 8 + nLen +
8 + shareP.dataLen + 8 + shareV.dataLen + 8 + z.dataLen + 8 + v.dataLen + 8 + spakeCtx->w0.dataLen;
}
if (tt) {
ret = APPEND_FIELD(context.data, context.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = APPEND_FIELD(prover.data, prover.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = APPEND_FIELD(verifier.data, verifier.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = APPEND_FIELD(m, mLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = APPEND_FIELD(n, nLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = APPEND_FIELD(shareP.data, shareP.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = APPEND_FIELD(shareV.data, shareV.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = APPEND_FIELD(z.data, z.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = APPEND_FIELD(v.data, v.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = APPEND_FIELD(spakeCtx->w0.data, spakeCtx->w0.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
tt->dataLen = pos - tt->data;
}
ERR:
CRYPT_EAL_PkeyFreeCtx(mKey);
CRYPT_EAL_PkeyFreeCtx(nKey);
if (ret != HITLS_AUTH_SUCCESS) {
Spake2PlusFreeCtx(spakeCtx);
}
return ret;
}
static int32_t Spake2PlusComputeKeySchedule(Spake2plusCtx *ctx, BSL_Buffer tt, BSL_Buffer *kConfirmP,
BSL_Buffer *kConfirmV, BSL_Buffer *kShared)
{
if (ctx == NULL || tt.data == NULL || tt.dataLen <= 0 || kConfirmP->data == NULL ||
kConfirmV->data == NULL || kShared->data == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
uint8_t kMain[g_spake2PlusAlgInfo[ctx->index].hashKeyLen];
uint32_t kMainLen = g_spake2PlusAlgInfo[ctx->index].hashKeyLen;
int32_t ret = CRYPT_EAL_Md(g_spake2PlusAlgInfo[ctx->index].hashId, tt.data, tt.dataLen, kMain, &kMainLen);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
CRYPT_MAC_AlgId macId;
if (g_spake2PlusAlgInfo[ctx->index].kdfId == CRYPT_HKDF_SHA256) {
macId=CRYPT_MAC_HMAC_SHA256;
}
if (g_spake2PlusAlgInfo[ctx->index].kdfId == CRYPT_HKDF_SHA512) {
macId=CRYPT_MAC_HMAC_SHA512;
}
CRYPT_EAL_KdfCTX *kdfCtx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_HKDF);
if (kdfCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
return HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
}
CRYPT_HKDF_MODE mode = CRYPT_KDF_HKDF_MODE_FULL;
uint8_t *salt = NULL;
uint32_t saltLen = 0;
uint8_t *info = (uint8_t*)"ConfirmationKeys"; // data from rfc 9383, section 3.4
uint32_t infoLen = strlen("ConfirmationKeys");
uint8_t out[g_spake2PlusAlgInfo[ctx->index].macKeyLen * 2];
uint32_t outLen = g_spake2PlusAlgInfo[ctx->index].macKeyLen * 2;
uint8_t out0[g_spake2PlusAlgInfo[ctx->index].hashKeyLen];
uint32_t out0Len = g_spake2PlusAlgInfo[ctx->index].hashKeyLen;
BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END};
ret = BSL_PARAM_InitValue(¶ms[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macId, sizeof(macId));
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BSL_PARAM_InitValue(¶ms[1], CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, &mode, sizeof(mode));
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BSL_PARAM_InitValue(¶ms[2], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, kMain, kMainLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BSL_PARAM_InitValue(¶ms[3], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = BSL_PARAM_InitValue(¶ms[4], CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, info, infoLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = CRYPT_EAL_KdfSetParam(kdfCtx, params);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = CRYPT_EAL_KdfDerive(kdfCtx, out, outLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
(void)memcpy_s(kConfirmP->data, g_spake2PlusAlgInfo[ctx->index].macKeyLen,
out, g_spake2PlusAlgInfo[ctx->index].macKeyLen);
(void)memcpy_s(kConfirmV->data, g_spake2PlusAlgInfo[ctx->index].macKeyLen,
out + g_spake2PlusAlgInfo[ctx->index].macKeyLen, g_spake2PlusAlgInfo[ctx->index].macKeyLen);
kConfirmP->dataLen = g_spake2PlusAlgInfo[ctx->index].macKeyLen;
kConfirmV->dataLen = g_spake2PlusAlgInfo[ctx->index].macKeyLen;
uint8_t *info0 = (uint8_t*)"SharedKey"; // data from rfc 9383, section 3.4
uint32_t info0Len = strlen("SharedKey");
ret = BSL_PARAM_InitValue(¶ms[4], CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, info0, info0Len);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = CRYPT_EAL_KdfSetParam(kdfCtx, params);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = CRYPT_EAL_KdfDerive(kdfCtx, out0, out0Len);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
(void)memcpy_s(kShared->data, out0Len, out0, out0Len);
kShared->dataLen = out0Len;
(void)memset_s(kMain, sizeof(kMain), 0, sizeof(kMain));
(void)memset_s(out, sizeof(out), 0, sizeof(out));
(void)memset_s(out0, sizeof(out0), 0, sizeof(out0));
ERR:
CRYPT_EAL_KdfFreeCtx(kdfCtx);
return ret;
}
static int32_t Spake2PlusComputeExpectedConfirm(Spake2plusCtx *ctx, BSL_Buffer kConfirm, BSL_Buffer share,
BSL_Buffer *outHmac)
{
if (ctx == NULL || kConfirm.data == NULL || kConfirm.dataLen <= 0 ||
share.data == NULL || share.dataLen <= 0 || outHmac->data == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_INVALID_ARG);
return HITLS_AUTH_INVALID_ARG;
}
CRYPT_EAL_MacCtx *MacCtx = CRYPT_EAL_MacNewCtx(g_spake2PlusAlgInfo[ctx->index].macId);
if (MacCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
return HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
}
int32_t ret = HITLS_AUTH_SUCCESS;
if (MacCtx == NULL) {
ret = HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
return ret;
}
ret = CRYPT_EAL_MacInit(MacCtx, kConfirm.data, kConfirm.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ret = CRYPT_EAL_MacUpdate(MacCtx, share.data, share.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
outHmac->dataLen = g_spake2PlusAlgInfo[ctx->index].macKeyLen;
ret = CRYPT_EAL_MacFinal(MacCtx, outHmac->data, &(outHmac->dataLen));
if (ret != HITLS_AUTH_SUCCESS) {
goto ERR;
}
ERR:
CRYPT_EAL_MacDeinit(MacCtx);
CRYPT_EAL_MacFreeCtx(MacCtx);
return ret;
}
int32_t HITLS_AUTH_Spake2plusReqSetup(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer randnumx, BSL_Buffer *share)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
Spake2plusCtx *spakeCtx = (Spake2plusCtx *)HITLS_AUTH_PakeGetInternalCtx(ctx);
if (spakeCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_CONTEXT);
return HITLS_AUTH_NULL_INPUT;
}
int32_t ret = HITLS_AUTH_SUCCESS;
uint8_t randnum[MAX_ECC_PARAM_LEN] = { 0 };
uint32_t randnumLen = MAX_ECC_PARAM_LEN;
if (randnumx.data != NULL) {
randnumLen = randnumx.dataLen;
(void)memcpy_s(randnum, randnumx.dataLen, randnumx.data, randnumx.dataLen);
} else {
ret = Spake2PlusInit(spakeCtx, randnum, &randnumLen);
if (ret != HITLS_AUTH_SUCCESS) {
Spake2PlusFreeCtx(spakeCtx);
return ret;
}
}
spakeCtx->x.dataLen = randnumLen;
(void)memcpy_s(spakeCtx->x.data, randnumLen, randnum, randnumLen);
uint8_t shareP[MAX_ECC_KEY_LEN] = { 0 };
uint32_t sharePLen = MAX_ECC_KEY_LEN;
ret = Spake2PlusProverComputeX(spakeCtx, randnum, randnumLen, shareP, &sharePLen);
if (ret != HITLS_AUTH_SUCCESS) {
Spake2PlusFreeCtx(spakeCtx);
return ret;
}
spakeCtx->share.dataLen = sharePLen;
(void)memcpy_s(spakeCtx->share.data, sharePLen, shareP, sharePLen);
share->dataLen = sharePLen;
(void)memcpy_s(share->data, sharePLen, shareP, sharePLen);
return ret;
}
int32_t HITLS_AUTH_Spake2plusRespSetup(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer y, BSL_Buffer shareP,
BSL_Buffer *shareV, BSL_Buffer *confirmV)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
Spake2plusCtx *spakeCtx = (Spake2plusCtx *)HITLS_AUTH_PakeGetInternalCtx(ctx);
if (spakeCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_CONTEXT);
return HITLS_AUTH_NULL_INPUT;
}
int32_t ret = HITLS_AUTH_SUCCESS;
uint8_t randnum[MAX_ECC_PARAM_LEN] = { 0 };
uint32_t randnumLen = MAX_ECC_PARAM_LEN;
BSL_Buffer zBuffer = {.data = BSL_SAL_Malloc(MAX_ECC_KEY_LEN), .dataLen = MAX_ECC_KEY_LEN};
BSL_Buffer vBuffer = {.data = BSL_SAL_Malloc(MAX_ECC_KEY_LEN), .dataLen = MAX_ECC_KEY_LEN};
BSL_Buffer randnumBuffer = {.data = BSL_SAL_Malloc(MAX_ECC_PARAM_LEN), .dataLen = MAX_ECC_PARAM_LEN};
BSL_Buffer ttBuffer = {.data = NULL, .dataLen = 0};
BSL_Buffer kConfirmPBuffer = {.data = BSL_SAL_Malloc(MAX_KEY_LEN), .dataLen = MAX_KEY_LEN};
BSL_Buffer kConfirmVBuffer = {.data = BSL_SAL_Malloc(MAX_KEY_LEN), .dataLen = MAX_KEY_LEN};
BSL_Buffer kSharedBuffer = {.data = BSL_SAL_Malloc(MAX_KEY_LEN), .dataLen = MAX_KEY_LEN};
BSL_Buffer outHmacBuffer = {.data = BSL_SAL_Malloc(MAX_KEY_LEN), .dataLen = MAX_KEY_LEN};
if (zBuffer.data == NULL || vBuffer.data == NULL || randnumBuffer.data == NULL ||
kConfirmPBuffer.data == NULL || kConfirmVBuffer.data == NULL || kSharedBuffer.data == NULL ||
outHmacBuffer.data == NULL) {
ret = HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
goto err;
}
if (y.data != NULL) {
randnumLen = y.dataLen;
(void)memcpy_s(randnum, y.dataLen, y.data, y.dataLen);
} else {
ret = Spake2PlusInit(spakeCtx, randnum, &randnumLen);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
}
uint8_t shareV0[MAX_ECC_KEY_LEN] = {0};
uint32_t shareV0Len = MAX_ECC_KEY_LEN;
ret = Spake2PlusVerifierComputeY(spakeCtx, randnum, randnumLen, shareV0, &shareV0Len);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
shareV->dataLen = shareV0Len;
(void)memcpy_s(shareV->data, shareV0Len, shareV0, shareV0Len);
randnumBuffer.dataLen = randnumLen;
(void)memcpy_s(randnumBuffer.data, randnumLen, randnum, randnumLen);
ret = Spake2PlusVerifierFinish(spakeCtx, randnumBuffer, shareP, &zBuffer, &vBuffer);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
uint32_t ttSize = 0;
ret = Spake2PlusComputeTranscript(ctx, shareP, *shareV, zBuffer, vBuffer, NULL, &ttSize);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
ttBuffer.data = BSL_SAL_Malloc(ttSize);
ttBuffer.dataLen = ttSize;
ret = Spake2PlusComputeTranscript(ctx, shareP, *shareV, zBuffer, vBuffer, &ttBuffer, NULL);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
ret = Spake2PlusComputeKeySchedule(spakeCtx, ttBuffer, &kConfirmPBuffer, &kConfirmVBuffer, &kSharedBuffer);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
spakeCtx->key_shared.dataLen = kSharedBuffer.dataLen;
(void)memcpy_s(spakeCtx->key_shared.data, kSharedBuffer.dataLen, kSharedBuffer.data, kSharedBuffer.dataLen);
ret = Spake2PlusComputeExpectedConfirm(spakeCtx, kConfirmVBuffer, shareP, &outHmacBuffer);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
spakeCtx->confirmV.dataLen = outHmacBuffer.dataLen;
(void)memcpy_s(spakeCtx->confirmV.data, outHmacBuffer.dataLen, outHmacBuffer.data, outHmacBuffer.dataLen);
confirmV->dataLen = outHmacBuffer.dataLen;
(void)memcpy_s(confirmV->data, outHmacBuffer.dataLen, outHmacBuffer.data, outHmacBuffer.dataLen);
ret = Spake2PlusComputeExpectedConfirm(spakeCtx, kConfirmPBuffer, *shareV, &outHmacBuffer);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
spakeCtx->confirmP.dataLen = outHmacBuffer.dataLen;
(void)memcpy_s(spakeCtx->confirmP.data, outHmacBuffer.dataLen, outHmacBuffer.data, outHmacBuffer.dataLen);
err:
if (ret != HITLS_AUTH_SUCCESS) {
Spake2PlusFreeCtx(spakeCtx);
}
BSL_SAL_ClearFree(zBuffer.data, zBuffer.dataLen);
BSL_SAL_ClearFree(vBuffer.data, vBuffer.dataLen);
BSL_SAL_ClearFree(randnumBuffer.data, randnumBuffer.dataLen);
BSL_SAL_ClearFree(ttBuffer.data, ttBuffer.dataLen);
BSL_SAL_ClearFree(kConfirmPBuffer.data, kConfirmPBuffer.dataLen);
BSL_SAL_ClearFree(kConfirmVBuffer.data, kConfirmVBuffer.dataLen);
BSL_SAL_ClearFree(kSharedBuffer.data, kSharedBuffer.dataLen);
BSL_SAL_ClearFree(outHmacBuffer.data, outHmacBuffer.dataLen);
return ret;
}
int32_t HITLS_AUTH_Spake2plusReqDerive(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer shareV, BSL_Buffer confirmV,
BSL_Buffer *confirmP, BSL_Buffer *out)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
Spake2plusCtx *spakeCtx = (Spake2plusCtx*)HITLS_AUTH_PakeGetInternalCtx(ctx);
if (spakeCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_CONTEXT);
return HITLS_AUTH_NULL_INPUT;
}
int32_t ret = HITLS_AUTH_SUCCESS;
BSL_Buffer zBuffer = {.data = BSL_SAL_Malloc(MAX_ECC_KEY_LEN), .dataLen = MAX_ECC_KEY_LEN};
BSL_Buffer vBuffer = {.data = BSL_SAL_Malloc(MAX_ECC_KEY_LEN), .dataLen = MAX_ECC_KEY_LEN};
BSL_Buffer ttBuffer = {.data = NULL, .dataLen = 0};
BSL_Buffer kConfirmPBuffer = {.data = BSL_SAL_Malloc(MAX_KEY_LEN), .dataLen = MAX_KEY_LEN};
BSL_Buffer kConfirmVBuffer = {.data = BSL_SAL_Malloc(MAX_KEY_LEN), .dataLen = MAX_KEY_LEN};
BSL_Buffer kSharedBuffer = {.data = BSL_SAL_Malloc(MAX_KEY_LEN), .dataLen = MAX_KEY_LEN};
BSL_Buffer outHmacBuffer = {.data = BSL_SAL_Malloc(MAX_KEY_LEN), .dataLen = MAX_KEY_LEN};
if (zBuffer.data == NULL || vBuffer.data == NULL ||
kConfirmPBuffer.data == NULL || kConfirmVBuffer.data == NULL || kSharedBuffer.data == NULL ||
outHmacBuffer.data == NULL) {
ret = HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_MEMORY_ALLOC_FAIL);
goto err;
}
ret = Spake2PlusProverFinish(spakeCtx, spakeCtx->x, shareV, &zBuffer, &vBuffer);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
uint32_t ttSize = 0;
ret = Spake2PlusComputeTranscript(ctx, spakeCtx->share, shareV, zBuffer, vBuffer, NULL, &ttSize);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
ttBuffer.data = BSL_SAL_Malloc(ttSize);
ttBuffer.dataLen = ttSize;
ret = Spake2PlusComputeTranscript(ctx, spakeCtx->share, shareV, zBuffer, vBuffer, &ttBuffer, NULL);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
ret = Spake2PlusComputeKeySchedule(spakeCtx, ttBuffer, &kConfirmPBuffer, &kConfirmVBuffer, &kSharedBuffer);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
spakeCtx->key_shared.dataLen = kSharedBuffer.dataLen;
(void)memcpy_s(spakeCtx->key_shared.data, kSharedBuffer.dataLen, kSharedBuffer.data, kSharedBuffer.dataLen);
ret = Spake2PlusComputeExpectedConfirm(spakeCtx, kConfirmPBuffer, shareV, &outHmacBuffer);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
spakeCtx->confirmP.dataLen = outHmacBuffer.dataLen;
(void)memcpy_s(spakeCtx->confirmP.data, outHmacBuffer.dataLen, outHmacBuffer.data, outHmacBuffer.dataLen);
confirmP->dataLen = outHmacBuffer.dataLen;
(void)memcpy_s(confirmP->data, outHmacBuffer.dataLen, outHmacBuffer.data, outHmacBuffer.dataLen);
ret = Spake2PlusComputeExpectedConfirm(spakeCtx, kConfirmVBuffer, spakeCtx->share, &outHmacBuffer);
if (ret != HITLS_AUTH_SUCCESS) {
goto err;
}
spakeCtx->confirmV.dataLen = outHmacBuffer.dataLen;
(void)memcpy_s(spakeCtx->confirmV.data, outHmacBuffer.dataLen, outHmacBuffer.data, outHmacBuffer.dataLen);
if (memcmp(spakeCtx->confirmV.data, confirmV.data, confirmV.dataLen) != 0 &&
spakeCtx->confirmV.dataLen == confirmV.dataLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_PARAM);
goto err;
}
out->dataLen = kSharedBuffer.dataLen;
(void)memcpy_s(out->data, kSharedBuffer.dataLen, kSharedBuffer.data, kSharedBuffer.dataLen);
err:
if (ret != HITLS_AUTH_SUCCESS) {
Spake2PlusFreeCtx(spakeCtx);
}
BSL_SAL_ClearFree(zBuffer.data, zBuffer.dataLen);
BSL_SAL_ClearFree(vBuffer.data, vBuffer.dataLen);
BSL_SAL_ClearFree(ttBuffer.data, ttBuffer.dataLen);
BSL_SAL_ClearFree(kConfirmPBuffer.data, kConfirmPBuffer.dataLen);
BSL_SAL_ClearFree(kConfirmVBuffer.data, kConfirmVBuffer.dataLen);
BSL_SAL_ClearFree(kSharedBuffer.data, kSharedBuffer.dataLen);
BSL_SAL_ClearFree(outHmacBuffer.data, outHmacBuffer.dataLen);
return ret;
}
int32_t HITLS_AUTH_Spake2plusRespDerive(HITLS_AUTH_PakeCtx *ctx, BSL_Buffer confirmP, BSL_Buffer *out)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_NULL_INPUT);
return HITLS_AUTH_NULL_INPUT;
}
Spake2plusCtx *spakeCtx = (Spake2plusCtx *)HITLS_AUTH_PakeGetInternalCtx(ctx);
if (spakeCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_CONTEXT);
return HITLS_AUTH_NULL_INPUT;
}
if (memcmp(spakeCtx->confirmP.data, confirmP.data, confirmP.dataLen) != 0 &&
spakeCtx->confirmP.dataLen == confirmP.dataLen) {
Spake2PlusFreeCtx(spakeCtx);
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PAKE_INVALID_PARAM);
return HITLS_AUTH_PAKE_INVALID_PARAM;
}
out->dataLen = spakeCtx->key_shared.dataLen;
(void)memcpy_s(out->data, spakeCtx->key_shared.dataLen, spakeCtx->key_shared.data, spakeCtx->key_shared.dataLen);
return HITLS_AUTH_SUCCESS;
}
| 2401_83913325/openHiTLS_1 | auth/pake/spake2plus/src/spake2plus.c | C | unknown | 49,166 |
/*
* 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 PRIVPASS_TOKEN_H
#define PRIVPASS_TOKEN_H
#include <stdint.h>
#include "bsl_types.h"
#include "bsl_params.h"
#include "auth_params.h"
#include "auth_privpass_token.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Constants for Private Pass Token */
#define PRIVPASS_PUBLIC_VERIFY_TOKENTYPE ((uint16_t)0x0002)
#define PRIVPASS_TOKEN_NK 256 // RSA-2048 key size in bytes
#define PRIVPASS_TOKEN_SHA256_SIZE 32 // SHA256 hash size in bytes
#define PRIVPASS_TOKEN_NONCE_LEN 32 // Random nonce length
#define PRIVPASS_MAX_ISSUER_NAME_LEN 65535
#define PRIVPASS_REDEMPTION_LEN 32
#define PRIVPASS_MAX_ORIGIN_INFO_LEN 65535
// 2(tokenType) + 32(nonce) + 32(challengeDigest) + 32(tokenKeyId)
#define HITLS_AUTH_PRIVPASS_TOKEN_INPUT_LEN (2 + 32 + 32 + 32)
/* Structure for token challenge request */
typedef struct {
uint8_t *challengeReq; // Challenge request data
uint32_t challengeReqLen; // Length of challenge request
} PrivPass_TokenChallengeReq;
/* Structure for token challenge from server */
typedef struct {
uint16_t tokenType; // Token type (e.g., Blind RSA 2048-bit)
BSL_Buffer issuerName; // Name of the token issuer
BSL_Buffer redemption; // Redemption information
BSL_Buffer originInfo; // Origin information
} PrivPass_TokenChallenge;
typedef struct {
uint16_t tokenType;
uint8_t truncatedTokenKeyId;
BSL_Buffer blindedMsg;
} PrivPass_TokenRequest;
typedef struct {
uint8_t *blindSig;
uint32_t blindSigLen;
} PrivPass_TokenPubResponse;
typedef enum {
HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB = 1,
} PrivPass_TokenResponseType;
typedef struct {
int32_t type;
union {
PrivPass_TokenPubResponse pubResp;
} st;
} PrivPass_TokenResponse;
typedef struct {
uint16_t tokenType;
uint8_t nonce[PRIVPASS_TOKEN_NONCE_LEN];
uint8_t challengeDigest[PRIVPASS_TOKEN_SHA256_SIZE];
uint8_t tokenKeyId[PRIVPASS_TOKEN_SHA256_SIZE];
BSL_Buffer authenticator;
} PrivPass_TokenInstance;
struct PrivPass_Token {
int32_t type;
union {
PrivPass_TokenChallengeReq *tokenChallengeReq;
PrivPass_TokenChallenge *tokenChallenge;
PrivPass_TokenRequest *tokenRequest;
PrivPass_TokenResponse *tokenResponse;
PrivPass_TokenInstance *token;
} st;
};
typedef struct {
HITLS_AUTH_PrivPassNewPkeyCtx newPkeyCtx;
HITLS_AUTH_PrivPassFreePkeyCtx freePkeyCtx;
HITLS_AUTH_PrivPassDigest digest;
HITLS_AUTH_PrivPassBlind blind;
HITLS_AUTH_PrivPassUnblind unBlind;
HITLS_AUTH_PrivPassSignData signData;
HITLS_AUTH_PrivPassVerify verify;
HITLS_AUTH_PrivPassDecodePubKey decodePubKey;
HITLS_AUTH_PrivPassDecodePrvKey decodePrvKey;
HITLS_AUTH_PrivPassCheckKeyPair checkKeyPair;
HITLS_AUTH_PrivPassRandom random;
} PrivPassCryptCb;
/* Main context structure for Private Pass operations */
struct PrivPass_Ctx {
void *prvKeyCtx; // Private key context
void *pubKeyCtx; // Public key context
uint8_t tokenKeyId[PRIVPASS_TOKEN_SHA256_SIZE]; // Token key identifier
uint8_t nonce[PRIVPASS_TOKEN_NONCE_LEN]; // Random nonce
PrivPassCryptCb method; // Cryptographic callbacks
};
/**
* @brief Get the default cryptographic callback functions.
* @retval PrivPassCryptCb structure containing default callbacks.
*/
PrivPassCryptCb PrivPassCryptPubCb(void);
#ifdef __cplusplus
}
#endif
#endif // PRIVPASS_TOKEN_H
| 2401_83913325/openHiTLS_1 | auth/privpass_token/include/privpass_token.h | C | unknown | 3,994 |
/*
* 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 "securec.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "bsl_bytes.h"
#include "auth_errno.h"
#include "auth_params.h"
#include "auth_privpass_token.h"
#include "privpass_token.h"
#define PRIVPASS_TOKEN_MAX_ENCODE_PUBKEY_LEN 1024
static int32_t SetAndValidateTokenType(const BSL_Param *param, PrivPass_TokenChallenge *tokenChallenge)
{
const BSL_Param *temp = BSL_PARAM_FindConstParam(param, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_TYPE);
if (temp == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_TYPE);
return HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_TYPE;
}
uint32_t tokenTypeLen = (uint32_t)sizeof(tokenChallenge->tokenType);
uint16_t tokenType = 0;
int32_t ret = BSL_PARAM_GetValue(temp, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_TYPE, BSL_PARAM_TYPE_UINT16,
&tokenType, &tokenTypeLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
tokenChallenge->tokenType = tokenType;
return HITLS_AUTH_SUCCESS;
}
static int32_t SetIssuerName(const BSL_Param *param, PrivPass_TokenChallenge *tokenChallenge)
{
const BSL_Param *temp = BSL_PARAM_FindConstParam(param, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ISSUERNAME);
if (temp == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_ISSUERNAME);
return HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_ISSUERNAME;
}
if (temp->valueLen == 0 || temp->valueLen > PRIVPASS_MAX_ISSUER_NAME_LEN) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_ISSUER_NAME);
return HITLS_AUTH_PRIVPASS_INVALID_ISSUER_NAME;
}
tokenChallenge->issuerName.data = BSL_SAL_Dump(temp->value, temp->valueLen);
if (tokenChallenge->issuerName.data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenChallenge->issuerName.dataLen = temp->valueLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t SetOptionalFields(const BSL_Param *param, PrivPass_TokenChallenge *tokenChallenge)
{
// Set redemption
const BSL_Param *temp = BSL_PARAM_FindConstParam(param, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_REDEMPTION);
if (temp == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_REDEMPTION);
return HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_REDEMPTION;
}
if (temp->valueLen != 0) {
if (temp->valueLen != PRIVPASS_REDEMPTION_LEN) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_REDEMPTION);
return HITLS_AUTH_PRIVPASS_INVALID_REDEMPTION;
}
tokenChallenge->redemption.data = BSL_SAL_Dump(temp->value, temp->valueLen);
if (tokenChallenge->redemption.data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenChallenge->redemption.dataLen = temp->valueLen;
}
// Set originInfo (optional)
temp = BSL_PARAM_FindConstParam(param, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ORIGININFO);
if (temp != NULL && temp->valueLen > 0) {
if (temp->valueLen > PRIVPASS_MAX_ORIGIN_INFO_LEN) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_ORIGIN_INFO);
return HITLS_AUTH_PRIVPASS_INVALID_ORIGIN_INFO;
}
tokenChallenge->originInfo.data = BSL_SAL_Dump(temp->value, temp->valueLen);
if (tokenChallenge->originInfo.data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenChallenge->originInfo.dataLen = temp->valueLen;
}
return HITLS_AUTH_SUCCESS;
}
int32_t HITLS_AUTH_PrivPassGenTokenChallenge(HITLS_AUTH_PrivPassCtx *ctx, const BSL_Param *param,
HITLS_AUTH_PrivPassToken **challenge)
{
(void)ctx;
if (param == NULL || challenge == NULL || *challenge != NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
HITLS_AUTH_PrivPassToken *output = HITLS_AUTH_PrivPassNewToken(HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE);
if (output == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
uint64_t challengeLen;
PrivPass_TokenChallenge *tokenChallenge = output->st.tokenChallenge;
int32_t ret = SetAndValidateTokenType(param, tokenChallenge);
if (ret != HITLS_AUTH_SUCCESS) {
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
ret = SetIssuerName(param, tokenChallenge);
if (ret != HITLS_AUTH_SUCCESS) {
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
ret = SetOptionalFields(param, tokenChallenge);
if (ret != HITLS_AUTH_SUCCESS) {
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
challengeLen = sizeof(tokenChallenge->tokenType) + tokenChallenge->issuerName.dataLen +
tokenChallenge->redemption.dataLen + tokenChallenge->originInfo.dataLen;
if (challengeLen > UINT32_MAX) {
HITLS_AUTH_PrivPassFreeToken(output);
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_PARAM);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_PARAM;
}
*challenge = output;
return HITLS_AUTH_SUCCESS;
}
static int32_t ParamCheckOfGenTokenReq(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
HITLS_AUTH_PrivPassToken **tokenRequest)
{
if (ctx == NULL || ctx->method.blind == NULL || ctx->method.digest == NULL || ctx->method.random == NULL ||
tokenChallenge == NULL || tokenChallenge->type != HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE ||
tokenRequest == NULL || *tokenRequest != NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (tokenChallenge->st.tokenChallenge->tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
return HITLS_AUTH_SUCCESS;
}
static uint32_t ObtainAuthenticatorLen(uint16_t tokenType)
{
if (tokenType == PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
return (uint32_t)PRIVPASS_TOKEN_NK;
}
return 0;
}
static int32_t GenerateChallengeDigest(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
uint8_t *challengeDigest)
{
uint8_t *challenge = NULL;
uint32_t challengeLen = 0;
uint32_t challengeDigestLen = PRIVPASS_TOKEN_SHA256_SIZE;
int32_t ret = HITLS_AUTH_PrivPassSerialization(ctx, tokenChallenge, NULL, &challengeLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
challenge = BSL_SAL_Malloc(challengeLen);
if (challenge == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
ret = HITLS_AUTH_PrivPassSerialization(ctx, tokenChallenge, challenge, &challengeLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_SAL_Free(challenge);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = ctx->method.digest(NULL, NULL, HITLS_AUTH_PRIVPASS_CRYPTO_SHA256, challenge, challengeLen, challengeDigest,
&challengeDigestLen);
BSL_SAL_Free(challenge);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t HITLS_AUTH_PrivPassGenTokenReq(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
HITLS_AUTH_PrivPassToken **tokenRequest)
{
int32_t ret = ParamCheckOfGenTokenReq(ctx, tokenChallenge, tokenRequest);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
HITLS_AUTH_PrivPassToken *output = HITLS_AUTH_PrivPassNewToken(HITLS_AUTH_PRIVPASS_TOKEN_REQUEST);
if (output == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
uint8_t challengeDigest[PRIVPASS_TOKEN_SHA256_SIZE];
const PrivPass_TokenChallenge *challenge = tokenChallenge->st.tokenChallenge;
PrivPass_TokenRequest *request = output->st.tokenRequest;
uint32_t authenticatorLen = ObtainAuthenticatorLen(challenge->tokenType); // challenge->tokenType has been checked.
// Construct token_input = concat(token_type, nonce, challenge_digest, token_key_id)
uint8_t tokenInput[HITLS_AUTH_PRIVPASS_TOKEN_INPUT_LEN];
size_t offset = 0;
// Copy token type from challenge
request->tokenType = challenge->tokenType;
request->truncatedTokenKeyId = ctx->tokenKeyId[PRIVPASS_TOKEN_SHA256_SIZE - 1];
// cal tokenChallengeDigest
ret = GenerateChallengeDigest(ctx, tokenChallenge, challengeDigest);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// Generate nonce
ret = ctx->method.random(ctx->nonce, PRIVPASS_TOKEN_NONCE_LEN);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// Add token type (2 bytes)
BSL_Uint16ToByte(challenge->tokenType, tokenInput);
offset += 2; // offset 2 bytes.
// Add nonce
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_NONCE_LEN, ctx->nonce, PRIVPASS_TOKEN_NONCE_LEN);
offset += PRIVPASS_TOKEN_NONCE_LEN;
// Add challenge digest
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_SHA256_SIZE, challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Add token key id
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_SHA256_SIZE, ctx->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE);
// Calculate blinded message
request->blindedMsg.data = BSL_SAL_Malloc(authenticatorLen);
if (request->blindedMsg.data == NULL) {
ret = BSL_MALLOC_FAIL;
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
goto ERR;
}
request->blindedMsg.dataLen = authenticatorLen;
ret = ctx->method.blind(ctx->pubKeyCtx, HITLS_AUTH_PRIVPASS_CRYPTO_SHA384, tokenInput,
HITLS_AUTH_PRIVPASS_TOKEN_INPUT_LEN, request->blindedMsg.data, &request->blindedMsg.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
*tokenRequest = output;
return HITLS_AUTH_SUCCESS;
ERR:
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
static int32_t ParamCheckOfGenTokenResp(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenRequest,
HITLS_AUTH_PrivPassToken **tokenResponse)
{
if (ctx == NULL || ctx->method.signData == NULL ||
tokenRequest == NULL || tokenRequest->type != HITLS_AUTH_PRIVPASS_TOKEN_REQUEST ||
tokenResponse == NULL || *tokenResponse != NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (tokenRequest->st.tokenRequest->tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
if (ctx->prvKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PRVKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PRVKEY_INFO;
}
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
return HITLS_AUTH_SUCCESS;
}
int32_t HITLS_AUTH_PrivPassGenTokenResponse(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenRequest,
HITLS_AUTH_PrivPassToken **tokenResponse)
{
int32_t ret = ParamCheckOfGenTokenResp(ctx, tokenRequest, tokenResponse);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
const PrivPass_TokenRequest *request = tokenRequest->st.tokenRequest;
uint32_t authenticatorLen = ObtainAuthenticatorLen(request->tokenType); // request->tokenType has been checked.
if (request->truncatedTokenKeyId != ctx->tokenKeyId[PRIVPASS_TOKEN_SHA256_SIZE - 1]) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_KEYID);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_KEYID;
}
if (request->blindedMsg.dataLen != authenticatorLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_BLINDED_MSG);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_BLINDED_MSG;
}
HITLS_AUTH_PrivPassToken *output = HITLS_AUTH_PrivPassNewToken(HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE);
if (output == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
PrivPass_TokenResponse *response = output->st.tokenResponse;
response->type = HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB;
// Calculate blind signature
response->st.pubResp.blindSig = BSL_SAL_Malloc(authenticatorLen);
if (response->st.pubResp.blindSig == NULL) {
ret = BSL_MALLOC_FAIL;
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
goto ERR;
}
response->st.pubResp.blindSigLen = authenticatorLen;
ret = ctx->method.signData(ctx->prvKeyCtx, request->blindedMsg.data, request->blindedMsg.dataLen,
response->st.pubResp.blindSig, &response->st.pubResp.blindSigLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
*tokenResponse = output;
return HITLS_AUTH_SUCCESS;
ERR:
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
static int32_t ParamCheckOfGenToken(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
const HITLS_AUTH_PrivPassToken *tokenResponse, HITLS_AUTH_PrivPassToken **token)
{
if (ctx == NULL || ctx->method.unBlind == NULL ||
tokenChallenge == NULL || tokenChallenge->type != HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE ||
tokenResponse == NULL || tokenResponse->type != HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE ||
token == NULL || *token != NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
if (tokenChallenge->st.tokenChallenge->tokenType == PRIVPASS_PUBLIC_VERIFY_TOKENTYPE &&
tokenResponse->st.tokenResponse->type == HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB) {
return HITLS_AUTH_SUCCESS;
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
int32_t HITLS_AUTH_PrivPassGenToken(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
const HITLS_AUTH_PrivPassToken *tokenResponse, HITLS_AUTH_PrivPassToken **token)
{
int32_t ret = ParamCheckOfGenToken(ctx, tokenChallenge, tokenResponse, token);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
HITLS_AUTH_PrivPassToken *output = HITLS_AUTH_PrivPassNewToken(HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE);
if (output == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
uint8_t challengeDigest[PRIVPASS_TOKEN_SHA256_SIZE];
PrivPass_TokenInstance *finalToken = output->st.token;
const PrivPass_TokenChallenge *challenge = tokenChallenge->st.tokenChallenge;
const PrivPass_TokenResponse *response = tokenResponse->st.tokenResponse;
uint32_t outputLen = ObtainAuthenticatorLen(challenge->tokenType);
// Copy token type from challenge
finalToken->tokenType = challenge->tokenType;
// cal tokenChallengeDigest
ret = GenerateChallengeDigest(ctx, tokenChallenge, challengeDigest);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// Copy nonce from ctx
(void)memcpy_s(finalToken->nonce, PRIVPASS_TOKEN_NONCE_LEN, ctx->nonce, PRIVPASS_TOKEN_NONCE_LEN);
// Copy challenge digest from ctx
(void)memcpy_s(finalToken->challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE,
challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE);
// Copy token key ID from ctx
(void)memcpy_s(finalToken->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE, ctx->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE);
// Copy authenticator from tokenResponse
finalToken->authenticator.data = BSL_SAL_Malloc(outputLen);
if (finalToken->authenticator.data == NULL) {
ret = BSL_MALLOC_FAIL;
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
goto ERR;
}
ret = ctx->method.unBlind(ctx->pubKeyCtx, response->st.pubResp.blindSig, response->st.pubResp.blindSigLen,
finalToken->authenticator.data, &outputLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
finalToken->authenticator.dataLen = outputLen;
*token = output;
return HITLS_AUTH_SUCCESS;
ERR:
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
static int32_t ParamCheckOfVerifyToken(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
const HITLS_AUTH_PrivPassToken *token)
{
if (ctx == NULL || ctx->method.verify == NULL ||
tokenChallenge == NULL || tokenChallenge->type != HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE ||
token == NULL || token->type != HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (tokenChallenge->st.tokenChallenge->tokenType != token->st.token->tokenType) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (tokenChallenge->st.tokenChallenge->tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
PrivPass_TokenInstance *finalToken = token->st.token;
if (memcmp(finalToken->tokenKeyId, ctx->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE) != 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_KEYID);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_KEYID;
}
uint8_t challengeDigest[PRIVPASS_TOKEN_SHA256_SIZE];
int32_t ret = GenerateChallengeDigest(ctx, tokenChallenge, challengeDigest);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (memcmp(finalToken->challengeDigest, challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE) != 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_DIGEST);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_DIGEST;
}
return HITLS_AUTH_SUCCESS;
}
int32_t HITLS_AUTH_PrivPassVerifyToken(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
const HITLS_AUTH_PrivPassToken *token)
{
int32_t ret = ParamCheckOfVerifyToken(ctx, tokenChallenge, token);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
PrivPass_TokenInstance *finalToken = token->st.token;
uint32_t authenticatorLen = ObtainAuthenticatorLen(finalToken->tokenType);
if (finalToken->authenticator.data == NULL || authenticatorLen != finalToken->authenticator.dataLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_INSTANCE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_INSTANCE;
}
// Construct token_input = concat(token_type, nonce, challenge_digest, token_key_id)
uint8_t tokenInput[HITLS_AUTH_PRIVPASS_TOKEN_INPUT_LEN];
size_t offset = 0;
// Add token type (2 bytes)
BSL_Uint16ToByte(finalToken->tokenType, tokenInput);
offset += 2; // offset 2 bytes.
// Add nonce
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_NONCE_LEN, finalToken->nonce, PRIVPASS_TOKEN_NONCE_LEN);
offset += PRIVPASS_TOKEN_NONCE_LEN;
// Add challenge digest
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_SHA256_SIZE,
finalToken->challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Add token key id
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_SHA256_SIZE, finalToken->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE);
// Verify the token using ctx's verify method
ret = ctx->method.verify(ctx->pubKeyCtx, HITLS_AUTH_PRIVPASS_CRYPTO_SHA384, tokenInput,
HITLS_AUTH_PRIVPASS_TOKEN_INPUT_LEN, finalToken->authenticator.data, PRIVPASS_TOKEN_NK);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t HITLS_AUTH_PrivPassSetPubkey(HITLS_AUTH_PrivPassCtx *ctx, uint8_t *pki, uint32_t pkiLen)
{
if (ctx == NULL || ctx->method.decodePubKey == NULL || ctx->method.freePkeyCtx == NULL ||
ctx->method.digest == NULL || pki == NULL || pkiLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
uint32_t tokenKeyIdLen = PRIVPASS_TOKEN_SHA256_SIZE;
void *pubKeyCtx = NULL;
int32_t ret = ctx->method.decodePubKey(NULL, NULL, pki, pkiLen, &pubKeyCtx);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (ctx->prvKeyCtx != NULL) {
if (ctx->method.checkKeyPair == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_KEYPAIR_CHECK_CALLBACK);
ret = HITLS_AUTH_PRIVPASS_NO_KEYPAIR_CHECK_CALLBACK;
goto ERR;
}
ret = ctx->method.checkKeyPair(pubKeyCtx, ctx->prvKeyCtx);
if (ret != HITLS_AUTH_SUCCESS) {
ret = HITLS_AUTH_PRIVPASS_CHECK_KEYPAIR_FAILED;
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_CHECK_KEYPAIR_FAILED);
goto ERR;
}
}
ret = ctx->method.digest(NULL, NULL, HITLS_AUTH_PRIVPASS_CRYPTO_SHA256, pki, pkiLen, ctx->tokenKeyId,
&tokenKeyIdLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
if (ctx->pubKeyCtx != NULL) {
ctx->method.freePkeyCtx(ctx->pubKeyCtx);
}
ctx->pubKeyCtx = pubKeyCtx;
return HITLS_AUTH_SUCCESS;
ERR:
ctx->method.freePkeyCtx(pubKeyCtx);
return ret;
}
int32_t HITLS_AUTH_PrivPassSetPrvkey(HITLS_AUTH_PrivPassCtx *ctx, void *param, uint8_t *ski, uint32_t skiLen)
{
if (ctx == NULL || ctx->method.decodePrvKey == NULL || ctx->method.freePkeyCtx == NULL ||
ski == NULL || skiLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
void *prvKeyCtx = NULL;
int32_t ret = ctx->method.decodePrvKey(NULL, NULL, param, ski, skiLen, &prvKeyCtx);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (ctx->pubKeyCtx != NULL) {
if (ctx->method.checkKeyPair == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_KEYPAIR_CHECK_CALLBACK);
ret = HITLS_AUTH_PRIVPASS_NO_KEYPAIR_CHECK_CALLBACK;
goto ERR;
}
ret = ctx->method.checkKeyPair(ctx->pubKeyCtx, prvKeyCtx);
if (ret != HITLS_AUTH_SUCCESS) {
ret = HITLS_AUTH_PRIVPASS_CHECK_KEYPAIR_FAILED;
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_CHECK_KEYPAIR_FAILED);
goto ERR;
}
}
if (ctx->prvKeyCtx != NULL) {
ctx->method.freePkeyCtx(ctx->prvKeyCtx);
}
ctx->prvKeyCtx = prvKeyCtx;
return HITLS_AUTH_SUCCESS;
ERR:
ctx->method.freePkeyCtx(prvKeyCtx);
return ret;
}
| 2401_83913325/openHiTLS_1 | auth/privpass_token/src/privpass_token.c | C | unknown | 24,225 |
/*
* 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 "securec.h"
#include "bsl_errno.h"
#include "auth_errno.h"
#include "auth_privpass_token.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "bsl_bytes.h"
#include "privpass_token.h"
static int32_t DecodeTokenChallengeReq(PrivPass_TokenChallengeReq *tokenChallengeReq, const uint8_t *buffer,
uint32_t buffLen)
{
// Allocate memory for the new buffer
uint8_t *data = (uint8_t *)BSL_SAL_Dump(buffer, buffLen);
if (data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenChallengeReq->challengeReq = data;
tokenChallengeReq->challengeReqLen = buffLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t EncodeTokenChallengeReq(const PrivPass_TokenChallengeReq *tokenChallengeReq, uint8_t *buffer,
uint32_t *buffLen)
{
if (tokenChallengeReq->challengeReqLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_REQ);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_REQ;
}
if (buffer == NULL) {
*buffLen = tokenChallengeReq->challengeReqLen;
return HITLS_AUTH_SUCCESS;
}
if (*buffLen < tokenChallengeReq->challengeReqLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(buffer, tokenChallengeReq->challengeReqLen, tokenChallengeReq->challengeReq,
tokenChallengeReq->challengeReqLen);
*buffLen = tokenChallengeReq->challengeReqLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t ValidateInitialParams(uint32_t remainLen)
{
// MinLength: tokenType(2) + issuerNameLen(2) + redemptionLen(1) + originInfoLen(2)
if (remainLen < 2 + 2 + 1 + 2) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeTokenTypeAndValidate(uint16_t *tokenType, const uint8_t **curr, uint32_t *remainLen)
{
*tokenType = BSL_ByteToUint16(*curr);
if (*tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
*curr += 2; // offset 2 bytes.
*remainLen -= 2;
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeIssuerName(uint8_t **issueName, uint32_t *issuerNameLen, const uint8_t **curr, uint32_t *remainLen)
{
*issuerNameLen = (uint32_t)BSL_ByteToUint16(*curr);
*curr += 2; // offset 2 bytes.
*remainLen -= 2;
if (*issuerNameLen == 0 || *remainLen < *issuerNameLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
*issueName = BSL_SAL_Dump(*curr, *issuerNameLen);
if (*issueName == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
*curr += *issuerNameLen;
*remainLen -= *issuerNameLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeRedemption(uint8_t **redemption, uint32_t *redemptionLen, const uint8_t **curr,
uint32_t *remainLen)
{
if (*remainLen < 1) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
*redemptionLen = (uint32_t)**curr;
*curr += 1;
*remainLen -= 1;
if (*remainLen < *redemptionLen || (*redemptionLen != PRIVPASS_REDEMPTION_LEN && *redemptionLen != 0)) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
if (*redemptionLen != 0) {
*redemption = BSL_SAL_Dump(*curr, *redemptionLen);
if (*redemption == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
*curr += *redemptionLen;
*remainLen -= *redemptionLen;
}
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeOriginInfo(uint8_t **originInfo, uint32_t *originInfoLen, const uint8_t **curr,
uint32_t *remainLen)
{
if (*remainLen < 2) { // len needs 2 bytes to store.
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
*originInfoLen = (uint32_t)BSL_ByteToUint16(*curr);
*curr += 2; // offset 2 bytes.
*remainLen -= 2;
if (*remainLen != *originInfoLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
if (*originInfoLen > 0) {
*originInfo = BSL_SAL_Dump(*curr, *originInfoLen);
if (*originInfo == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
}
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeTokenChallenge(PrivPass_TokenChallenge *challenge, const uint8_t *buffer, uint32_t buffLen)
{
int32_t ret = ValidateInitialParams(buffLen);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
const uint8_t *curr = buffer;
uint32_t remainLen = buffLen;
// Decode each component
ret = DecodeTokenTypeAndValidate(&challenge->tokenType, &curr, &remainLen);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
ret = DecodeIssuerName(&challenge->issuerName.data, &challenge->issuerName.dataLen, &curr, &remainLen);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
ret = DecodeRedemption(&challenge->redemption.data, &challenge->redemption.dataLen, &curr, &remainLen);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
return DecodeOriginInfo(&challenge->originInfo.data, &challenge->originInfo.dataLen, &curr, &remainLen);
}
static int32_t CheckTokenChallengeParam(const PrivPass_TokenChallenge *challenge)
{
if (challenge->issuerName.dataLen == 0 || challenge->issuerName.dataLen > PRIVPASS_MAX_ISSUER_NAME_LEN ||
challenge->originInfo.dataLen > PRIVPASS_MAX_ORIGIN_INFO_LEN ||
(challenge->redemption.dataLen != 0 && challenge->redemption.dataLen != PRIVPASS_REDEMPTION_LEN)) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
return HITLS_AUTH_SUCCESS;
}
static int32_t EncodeTokenChallenge(const PrivPass_TokenChallenge *challenge,
uint8_t *buffer, uint32_t *outBuffLen)
{
int32_t ret = CheckTokenChallengeParam(challenge);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
// 2(tokenType) + 2(issuerNameLen) + issuerName + 1(redemptionLen) + redemption + 2(originInfoLen) + originInfo
uint64_t totalLen = 2 + 2 + challenge->issuerName.dataLen + 1 + challenge->redemption.dataLen + 2 +
(uint64_t)challenge->originInfo.dataLen;
if (totalLen > UINT32_MAX) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
if (buffer == NULL) {
*outBuffLen = (uint32_t)totalLen;
return HITLS_AUTH_SUCCESS;
}
if (*outBuffLen < (uint32_t)totalLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
uint8_t *curr = buffer;
BSL_Uint16ToByte(challenge->tokenType, curr); // Write tokenType (2 bytes)
BSL_Uint16ToByte((uint16_t)challenge->issuerName.dataLen, curr + 2); // Write IssuerName length (2 bytes) and data
curr += 4; // offset 4 bytes.
if (challenge->issuerName.dataLen > 0 && challenge->issuerName.data != NULL) {
(void)memcpy_s(curr, challenge->issuerName.dataLen, challenge->issuerName.data,
challenge->issuerName.dataLen);
curr += challenge->issuerName.dataLen;
}
// Write redemptionContext (1 byte)
*curr++ = (uint8_t)challenge->redemption.dataLen;
if (challenge->redemption.dataLen > 0 && challenge->redemption.data != NULL) {
(void)memcpy_s(curr, challenge->redemption.dataLen, challenge->redemption.data,
challenge->redemption.dataLen);
curr += challenge->redemption.dataLen;
}
// Write originInfo length (2 bytes) and data
BSL_Uint16ToByte((uint16_t)challenge->originInfo.dataLen, curr);
curr += 2; // offset 2 bytes.
if (challenge->originInfo.dataLen > 0 && challenge->originInfo.data != NULL) {
(void)memcpy_s(curr, challenge->originInfo.dataLen, challenge->originInfo.data,
challenge->originInfo.dataLen);
}
*outBuffLen = (uint32_t)totalLen;
return HITLS_AUTH_SUCCESS;
}
static uint32_t ObtainAuthenticatorLen(uint16_t tokenType)
{
if (tokenType == PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
return (uint32_t)PRIVPASS_TOKEN_NK;
}
return 0;
}
static int32_t DecodeTokenRequest(PrivPass_TokenRequest *tokenRequest, const uint8_t *buffer, uint32_t buffLen)
{
// Check minimum length for tokenType (2 bytes)
if (buffLen < 2) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
// Decode and verify tokenType first (2 bytes, network byte order)
uint16_t tokenType = BSL_ByteToUint16(buffer);
if (tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_REQUEST);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_REQUEST;
}
uint32_t blindedMsgLen = ObtainAuthenticatorLen(tokenType);
// Now check the complete buffer length: 2(tokenType) + 1(truncatedTokenKeyId) + blindedMsgLen
if (buffLen != (2 + 1 + blindedMsgLen)) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
int32_t offset = 2; // Skip tokenType which we've already processed
// Decode truncatedTokenKeyId (1 byte)
uint8_t truncatedTokenKeyId = buffer[offset++];
// Decode blindedMsg
uint8_t *blindedMsg = (uint8_t *)BSL_SAL_Dump(buffer + offset, blindedMsgLen);
if (blindedMsg == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenRequest->tokenType = tokenType;
tokenRequest->blindedMsg.data = blindedMsg;
tokenRequest->blindedMsg.dataLen = blindedMsgLen;
tokenRequest->truncatedTokenKeyId = truncatedTokenKeyId;
return HITLS_AUTH_SUCCESS;
}
static int32_t CheckTokenRequest(const PrivPass_TokenRequest *request)
{
if (request->tokenType == PRIVPASS_PUBLIC_VERIFY_TOKENTYPE &&
(request->blindedMsg.data != NULL && request->blindedMsg.dataLen == PRIVPASS_TOKEN_NK)) {
return HITLS_AUTH_SUCCESS;
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_REQUEST);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_REQUEST;
}
static int32_t EncodeTokenRequest(const PrivPass_TokenRequest *request, uint8_t *buffer, uint32_t *outBuffLen)
{
// Verify tokenType
int32_t ret = CheckTokenRequest(request);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
uint32_t authenticatorLen = ObtainAuthenticatorLen(request->tokenType);
// Calculate total length: 2(tokenType) + 1(truncatedTokenKeyId) + (blindedMsg)
uint32_t totalLen = 2 + 1 + authenticatorLen;
if (buffer == NULL) {
*outBuffLen = totalLen;
return HITLS_AUTH_SUCCESS;
}
if (*outBuffLen < totalLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
// Encode data
int32_t offset = 0;
// Encode tokenType (2 bytes, network byte order)
BSL_Uint16ToByte(request->tokenType, buffer);
offset += 2; // offset 2 bytes.
// Encode truncatedTokenKeyId (1 byte)
buffer[offset++] = request->truncatedTokenKeyId;
// Encode blindedMsg
(void)memcpy_s(buffer + offset, authenticatorLen, request->blindedMsg.data, authenticatorLen);
*outBuffLen = totalLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodePubTokenResp(PrivPass_TokenResponse *tokenResp, const uint8_t *buffer, uint32_t buffLen)
{
// Allocate memory for the new buffer
tokenResp->st.pubResp.blindSig = (uint8_t *)BSL_SAL_Dump(buffer, buffLen);
if (tokenResp->st.pubResp.blindSig == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenResp->st.pubResp.blindSigLen = buffLen;
tokenResp->type = HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB;
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeTokenResp(PrivPass_TokenResponse *tokenResp, const uint8_t *buffer, uint32_t buffLen)
{
if (buffLen == PRIVPASS_TOKEN_NK) {
return DecodePubTokenResp(tokenResp, buffer, buffLen);
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
static int32_t EncodeTokenPubResp(const PrivPass_TokenPubResponse *resp, uint8_t *buffer, uint32_t *buffLen)
{
if (resp->blindSig == NULL || resp->blindSigLen != PRIVPASS_TOKEN_NK) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_RESPONSE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_RESPONSE;
}
if (buffer == NULL) {
*buffLen = resp->blindSigLen;
return HITLS_AUTH_SUCCESS;
}
// Check buffer length
if (*buffLen < resp->blindSigLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
// Copy token data to buffer
(void)memcpy_s(buffer, resp->blindSigLen, resp->blindSig, resp->blindSigLen);
*buffLen = resp->blindSigLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t EncodeTokenResp(const PrivPass_TokenResponse *resp, uint8_t *buffer, uint32_t *buffLen)
{
if (resp->type == HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB) {
return EncodeTokenPubResp(&resp->st.pubResp, buffer, buffLen);
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_RESPONSE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_RESPONSE;
}
static int32_t CheckToken(const PrivPass_TokenInstance *token)
{
if (token->tokenType == PRIVPASS_PUBLIC_VERIFY_TOKENTYPE &&
(token->authenticator.data != NULL && token->authenticator.dataLen == PRIVPASS_TOKEN_NK)) {
return HITLS_AUTH_SUCCESS;
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_INSTANCE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_INSTANCE;
}
static int32_t EncodeToken(const PrivPass_TokenInstance *token, uint8_t *buffer, uint32_t *outBuffLen)
{
// Verify tokenType
int32_t ret = CheckToken(token);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
// Calculate total length: 2(tokenType) + 32(nonce) + 32(challengeDigest) + 32(tokenKeyId) + authenticatorLen
uint32_t totalLen = 2 + PRIVPASS_TOKEN_NONCE_LEN + PRIVPASS_TOKEN_SHA256_SIZE + PRIVPASS_TOKEN_SHA256_SIZE +
token->authenticator.dataLen;
if (buffer == NULL) {
*outBuffLen = totalLen;
return HITLS_AUTH_SUCCESS;
}
if (*outBuffLen < totalLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
int32_t offset = 0;
// Encode tokenType (network byte order)
BSL_Uint16ToByte(token->tokenType, buffer);
offset += 2; // offset 2 bytes.
// Encode nonce
(void)memcpy_s(buffer + offset, PRIVPASS_TOKEN_NONCE_LEN, token->nonce, PRIVPASS_TOKEN_NONCE_LEN);
offset += PRIVPASS_TOKEN_NONCE_LEN;
// Encode challengeDigest
(void)memcpy_s(buffer + offset, PRIVPASS_TOKEN_SHA256_SIZE, token->challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Encode tokenKeyId
(void)memcpy_s(buffer + offset, PRIVPASS_TOKEN_SHA256_SIZE, token->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Encode authenticator
(void)memcpy_s(buffer + offset, token->authenticator.dataLen, token->authenticator.data,
token->authenticator.dataLen);
*outBuffLen = totalLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeToken(PrivPass_TokenInstance *token, const uint8_t *buffer, uint32_t buffLen)
{
// First check if there are enough bytes to read tokenType(2 bytes).
if (buffLen < 2) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
// Decode and verify tokenType first (network byte order)
uint16_t tokenType = BSL_ByteToUint16(buffer);
if (tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
token->tokenType = tokenType;
uint32_t authenticatorLen = ObtainAuthenticatorLen(tokenType);
// Calculate total length: 2(tokenType) + 32(nonce) + 32(challengeDigest) + 32(tokenKeyId) + authenticatorLen
if (buffLen != (2 + PRIVPASS_TOKEN_NONCE_LEN + PRIVPASS_TOKEN_SHA256_SIZE + PRIVPASS_TOKEN_SHA256_SIZE +
authenticatorLen)) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
int32_t offset = 2; // Skip tokenType which we've already read
// Decode nonce
(void)memcpy_s(token->nonce, PRIVPASS_TOKEN_NONCE_LEN, buffer + offset, PRIVPASS_TOKEN_NONCE_LEN);
offset += PRIVPASS_TOKEN_NONCE_LEN;
// Decode challengeDigest
(void)memcpy_s(token->challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE, buffer + offset, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Decode tokenKeyId
(void)memcpy_s(token->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE, buffer + offset, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Decode authenticator
token->authenticator.data = (uint8_t *)BSL_SAL_Dump(buffer + offset, authenticatorLen);
if (token->authenticator.data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
token->authenticator.dataLen = authenticatorLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t CheckDeserializationInput(int32_t tokenType, const uint8_t *buffer, uint32_t buffLen,
HITLS_AUTH_PrivPassToken **object)
{
if (buffer == NULL || buffLen == 0 || object == NULL || *object != NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
switch (tokenType) {
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST:
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE:
case HITLS_AUTH_PRIVPASS_TOKEN_REQUEST:
case HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE:
case HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE:
return HITLS_AUTH_SUCCESS;
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
}
int32_t HITLS_AUTH_PrivPassDeserialization(HITLS_AUTH_PrivPassCtx *ctx, int32_t tokenType, const uint8_t *buffer,
uint32_t buffLen, HITLS_AUTH_PrivPassToken **object)
{
(void)ctx;
int32_t ret = CheckDeserializationInput(tokenType, buffer, buffLen, object);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
// Allocate the token object
HITLS_AUTH_PrivPassToken *output = HITLS_AUTH_PrivPassNewToken(tokenType);
if (output == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
switch (tokenType) {
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST:
ret = DecodeTokenChallengeReq(output->st.tokenChallengeReq, buffer, buffLen);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE:
ret = DecodeTokenChallenge(output->st.tokenChallenge, buffer, buffLen);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_REQUEST:
ret = DecodeTokenRequest(output->st.tokenRequest, buffer, buffLen);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE:
ret = DecodeTokenResp(output->st.tokenResponse, buffer, buffLen);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE:
ret = DecodeToken(output->st.token, buffer, buffLen);
break;
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
ret = HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
break;
}
if (ret != HITLS_AUTH_SUCCESS) {
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
*object = output;
return HITLS_AUTH_SUCCESS;
}
int32_t HITLS_AUTH_PrivPassSerialization(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *object,
uint8_t *buffer, uint32_t *outBuffLen)
{
(void)ctx;
if (object == NULL || outBuffLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
switch (object->type) {
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST:
return EncodeTokenChallengeReq(object->st.tokenChallengeReq, buffer, outBuffLen);
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE:
return EncodeTokenChallenge(object->st.tokenChallenge, buffer, outBuffLen);
case HITLS_AUTH_PRIVPASS_TOKEN_REQUEST:
return EncodeTokenRequest(object->st.tokenRequest, buffer, outBuffLen);
case HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE:
return EncodeTokenResp(object->st.tokenResponse, buffer, outBuffLen);
case HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE:
return EncodeToken(object->st.token, buffer, outBuffLen);
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
}
HITLS_AUTH_PrivPassToken *HITLS_AUTH_PrivPassNewToken(int32_t tokenType)
{
HITLS_AUTH_PrivPassToken *object = (HITLS_AUTH_PrivPassToken *)BSL_SAL_Calloc(1u, sizeof(HITLS_AUTH_PrivPassToken));
if (object == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
switch (tokenType) {
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST:
object->st.tokenChallengeReq = (PrivPass_TokenChallengeReq *)BSL_SAL_Calloc(1u,
sizeof(PrivPass_TokenChallengeReq));
if (object->st.tokenChallengeReq == NULL) {
goto ERR;
}
break;
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE:
object->st.tokenChallenge = (PrivPass_TokenChallenge *)BSL_SAL_Calloc(1u, sizeof(PrivPass_TokenChallenge));
if (object->st.tokenChallenge == NULL) {
goto ERR;
}
break;
case HITLS_AUTH_PRIVPASS_TOKEN_REQUEST:
object->st.tokenRequest = (PrivPass_TokenRequest *)BSL_SAL_Calloc(1u, sizeof(PrivPass_TokenRequest));
if (object->st.tokenRequest == NULL) {
goto ERR;
}
break;
case HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE:
object->st.tokenResponse = (PrivPass_TokenResponse *)BSL_SAL_Calloc(1u, sizeof(PrivPass_TokenResponse));
if (object->st.tokenResponse == NULL) {
goto ERR;
}
break;
case HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE:
object->st.token = (PrivPass_TokenInstance *)BSL_SAL_Calloc(1u, sizeof(PrivPass_TokenInstance));
if (object->st.token == NULL) {
goto ERR;
}
break;
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
BSL_SAL_Free(object);
return NULL;
}
object->type = tokenType;
return object;
ERR:
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
BSL_SAL_Free(object);
return NULL;
}
static void FreeTokenChallengeReq(PrivPass_TokenChallengeReq *challengeReq)
{
if (challengeReq == NULL) {
return;
}
BSL_SAL_FREE(challengeReq->challengeReq);
BSL_SAL_Free(challengeReq);
}
static void FreeTokenChallenge(PrivPass_TokenChallenge *challenge)
{
if (challenge == NULL) {
return;
}
BSL_SAL_FREE(challenge->issuerName.data);
BSL_SAL_FREE(challenge->originInfo.data);
BSL_SAL_FREE(challenge->redemption.data);
BSL_SAL_Free(challenge);
}
static void FreeTokenResponse(PrivPass_TokenResponse *response)
{
if (response == NULL) {
return;
}
if (response->type == HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB) {
BSL_SAL_FREE(response->st.pubResp.blindSig);
}
BSL_SAL_Free(response);
}
static void FreeTokenRequest(PrivPass_TokenRequest *request)
{
if (request == NULL) {
return;
}
BSL_SAL_FREE(request->blindedMsg.data);
BSL_SAL_Free(request);
}
static void FreeToken(PrivPass_TokenInstance *token)
{
if (token == NULL) {
return;
}
BSL_SAL_FREE(token->authenticator.data);
BSL_SAL_Free(token);
}
void HITLS_AUTH_PrivPassFreeToken(HITLS_AUTH_PrivPassToken *object)
{
if (object == NULL) {
return;
}
switch (object->type) {
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST:
FreeTokenChallengeReq(object->st.tokenChallengeReq);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE:
FreeTokenChallenge(object->st.tokenChallenge);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_REQUEST:
FreeTokenRequest(object->st.tokenRequest);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE:
FreeTokenResponse(object->st.tokenResponse);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE:
FreeToken(object->st.token);
break;
default:
break;
}
BSL_SAL_Free(object);
}
HITLS_AUTH_PrivPassCtx *HITLS_AUTH_PrivPassNewCtx(int32_t protocolType)
{
if (protocolType != HITLS_AUTH_PRIVPASS_PUB_VERIFY_TOKENS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOEKN_PROTOCOL_TYPE);
return NULL;
}
HITLS_AUTH_PrivPassCtx *ctx = (HITLS_AUTH_PrivPassCtx *)BSL_SAL_Calloc(1u, sizeof(HITLS_AUTH_PrivPassCtx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
ctx->method = PrivPassCryptPubCb();
return ctx;
}
void HITLS_AUTH_PrivPassFreeCtx(HITLS_AUTH_PrivPassCtx *ctx)
{
if (ctx == NULL) {
return;
}
if (ctx->method.freePkeyCtx != NULL) {
if (ctx->prvKeyCtx != NULL) {
ctx->method.freePkeyCtx(ctx->prvKeyCtx);
}
if (ctx->pubKeyCtx != NULL) {
ctx->method.freePkeyCtx(ctx->pubKeyCtx);
}
}
BSL_SAL_Free(ctx);
}
int32_t HITLS_AUTH_PrivPassSetCryptCb(HITLS_AUTH_PrivPassCtx *ctx, int32_t cbType, void *cryptCb)
{
if (ctx == NULL || cryptCb == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
switch (cbType) {
case HITLS_AUTH_PRIVPASS_NEW_PKEY_CTX_CB:
ctx->method.newPkeyCtx = (HITLS_AUTH_PrivPassNewPkeyCtx)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_FREE_PKEY_CTX_CB:
ctx->method.freePkeyCtx = (HITLS_AUTH_PrivPassFreePkeyCtx)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_DIGEST_CB:
ctx->method.digest = (HITLS_AUTH_PrivPassDigest)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_BLIND_CB:
ctx->method.blind = (HITLS_AUTH_PrivPassBlind)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_UNBLIND_CB:
ctx->method.unBlind = (HITLS_AUTH_PrivPassUnblind)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_SIGNDATA_CB:
ctx->method.signData = (HITLS_AUTH_PrivPassSignData)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_VERIFY_CB:
ctx->method.verify = (HITLS_AUTH_PrivPassVerify)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_DECODE_PUBKEY_CB:
ctx->method.decodePubKey = (HITLS_AUTH_PrivPassDecodePubKey)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_DECODE_PRVKEY_CB:
ctx->method.decodePrvKey = (HITLS_AUTH_PrivPassDecodePrvKey)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_CHECK_KEYPAIR_CB:
ctx->method.checkKeyPair = (HITLS_AUTH_PrivPassCheckKeyPair)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_RANDOM_CB:
ctx->method.random = (HITLS_AUTH_PrivPassRandom)cryptCb;
break;
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_CRYPTO_CALLBACK_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_CRYPTO_CALLBACK_TYPE;
}
return HITLS_AUTH_SUCCESS;
}
static int32_t PrivPassGetTokenChallengeRequest(HITLS_AUTH_PrivPassToken *ctx, BSL_Param *param)
{
if (param == NULL || ctx->type != HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST ||
ctx->st.tokenChallengeReq == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (ctx->st.tokenChallengeReq->challengeReq == NULL || ctx->st.tokenChallengeReq->challengeReqLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_REQUEST);
return HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_REQUEST;
}
BSL_Param *output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_REQUEST);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < ctx->st.tokenChallengeReq->challengeReqLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
(void)memcpy_s(output->value, output->valueLen, ctx->st.tokenChallengeReq->challengeReq,
ctx->st.tokenChallengeReq->challengeReqLen);
output->useLen = ctx->st.tokenChallengeReq->challengeReqLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t GetTokenChallengeContent(PrivPass_TokenChallenge *challenge, BSL_Param *param, int32_t target,
uint8_t *targetBuff, uint32_t targetLen)
{
BSL_Param *output = BSL_PARAM_FindParam(param, target);
if (target == AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_TYPE) {
if (output != NULL && output->valueType == BSL_PARAM_TYPE_UINT16) {
return BSL_PARAM_SetValue(output, target, BSL_PARAM_TYPE_UINT16, &challenge->tokenType, targetLen);
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < targetLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, targetBuff, targetLen);
output->useLen = targetLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t PrivPassGetTokenChallengeContent(HITLS_AUTH_PrivPassToken *obj, int32_t cmd, BSL_Param *param)
{
if (param == NULL || obj->type != HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE || obj->st.tokenChallenge == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
PrivPass_TokenChallenge *challenge = obj->st.tokenChallenge;
int32_t target = 0;
uint8_t *targetBuff = 0;
uint32_t targetLen = 0;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_TYPE:
target = AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_TYPE;
targetLen = (uint32_t)sizeof(challenge->tokenType);
break;
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_ISSUERNAME:
if (challenge->issuerName.data == NULL || challenge->issuerName.dataLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_ISSUERNAME);
return HITLS_AUTH_PRIVPASS_NO_ISSUERNAME;
}
target = AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ISSUERNAME;
targetBuff = challenge->issuerName.data;
targetLen = challenge->issuerName.dataLen;
break;
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_REDEMPTION:
target = AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_REDEMPTION;
targetBuff = challenge->redemption.data; // the redemption can be null
targetLen = challenge->redemption.dataLen;
break;
default:
target = AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ORIGININFO;
targetBuff = challenge->originInfo.data; // the originInfo can be null
targetLen = challenge->originInfo.dataLen;
break;
}
return GetTokenChallengeContent(challenge, param, target, targetBuff, targetLen);
}
static int32_t PrivPassGetTokenRequestContent(HITLS_AUTH_PrivPassToken *obj, int32_t cmd, BSL_Param *param)
{
if (param == NULL || obj->type != HITLS_AUTH_PRIVPASS_TOKEN_REQUEST || obj->st.tokenRequest == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
PrivPass_TokenRequest *request = obj->st.tokenRequest;
BSL_Param *output = NULL;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_TOKENREQUEST_TYPE:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_TOKENREQUEST_TYPE);
if (output != NULL && output->valueType == BSL_PARAM_TYPE_UINT16) {
return BSL_PARAM_SetValue(output, AUTH_PARAM_PRIVPASS_TOKENREQUEST_TYPE, BSL_PARAM_TYPE_UINT16,
&request->tokenType, (uint32_t)sizeof(request->tokenType));
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
case HITLS_AUTH_PRIVPASS_GET_TOKENREQUEST_TRUNCATEDTOKENKEYID:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_TOKENREQUEST_TRUNCATEDTOKENKEYID);
if (output != NULL && output->valueType == BSL_PARAM_TYPE_UINT8) {
return BSL_PARAM_SetValue(output, AUTH_PARAM_PRIVPASS_TOKENREQUEST_TRUNCATEDTOKENKEYID,
BSL_PARAM_TYPE_UINT8, &request->truncatedTokenKeyId, 1); // 1 byte.
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
default:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_TOKENREQUEST_BLINDEDMSG);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (request->blindedMsg.data == NULL || request->blindedMsg.dataLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_BLINDEDMSG);
return HITLS_AUTH_PRIVPASS_NO_BLINDEDMSG;
}
if (output->valueLen < request->blindedMsg.dataLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, request->blindedMsg.data, request->blindedMsg.dataLen);
output->useLen = request->blindedMsg.dataLen;
return HITLS_AUTH_SUCCESS;
}
}
static int32_t PrivPassGetTokenResponseContent(HITLS_AUTH_PrivPassToken *ctx, BSL_Param *param)
{
if (param == NULL || ctx->type != HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE || ctx->st.tokenResponse == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (ctx->st.tokenResponse->st.pubResp.blindSig == NULL || ctx->st.tokenResponse->st.pubResp.blindSigLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_RESPONSE_INFO);
return HITLS_AUTH_PRIVPASS_NO_RESPONSE_INFO;
}
BSL_Param *output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_TOKENRESPONSE_INFO);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < ctx->st.tokenResponse->st.pubResp.blindSigLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, ctx->st.tokenResponse->st.pubResp.blindSig,
ctx->st.tokenResponse->st.pubResp.blindSigLen);
output->useLen = ctx->st.tokenResponse->st.pubResp.blindSigLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t CopyTokenContent(PrivPass_TokenInstance *token, BSL_Param *param, int32_t target, uint8_t *targetBuff,
uint32_t targetLen)
{
BSL_Param *output = BSL_PARAM_FindParam(param, target);
if (target == AUTH_PARAM_PRIVPASS_TOKEN_TYPE) {
if (output != NULL && output->valueType == BSL_PARAM_TYPE_UINT16) {
return BSL_PARAM_SetValue(output, target, BSL_PARAM_TYPE_UINT16, &token->tokenType,
(uint32_t)sizeof(token->tokenType));
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (target == AUTH_PARAM_PRIVPASS_TOKEN_AUTHENTICATOR && targetBuff == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_AUTHENTICATOR);
return HITLS_AUTH_PRIVPASS_NO_AUTHENTICATOR;
}
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < targetLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, targetBuff, targetLen);
output->useLen = targetLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t PrivPassGetTokenContent(HITLS_AUTH_PrivPassToken *obj, int32_t cmd, BSL_Param *param)
{
if (param == NULL || obj->type != HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE || obj->st.token == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
PrivPass_TokenInstance *token = obj->st.token;
int32_t target;
uint8_t *targetBuff = 0;
uint32_t targetLen = 0;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_TOKEN_TYPE:
target = AUTH_PARAM_PRIVPASS_TOKEN_TYPE;
targetLen = (uint32_t)sizeof(token->tokenType);
break;
case HITLS_AUTH_PRIVPASS_GET_TOKEN_NONCE:
target = AUTH_PARAM_PRIVPASS_TOKEN_NONCE;
targetBuff = token->nonce;
targetLen = PRIVPASS_TOKEN_NONCE_LEN;
break;
case HITLS_AUTH_PRIVPASS_GET_TOKEN_CHALLENGEDIGEST:
target = AUTH_PARAM_PRIVPASS_TOKEN_CHALLENGEDIGEST;
targetBuff = token->challengeDigest;
targetLen = PRIVPASS_TOKEN_SHA256_SIZE;
break;
case HITLS_AUTH_PRIVPASS_GET_TOKEN_TOKENKEYID:
target = AUTH_PARAM_PRIVPASS_TOKEN_TOKENKEYID;
targetBuff = token->tokenKeyId;
targetLen = PRIVPASS_TOKEN_SHA256_SIZE;
break;
default:
target = AUTH_PARAM_PRIVPASS_TOKEN_AUTHENTICATOR;
targetBuff = token->authenticator.data;
targetLen = token->authenticator.dataLen;
break;
}
return CopyTokenContent(token, param, target, targetBuff, targetLen);
}
int32_t HITLS_AUTH_PrivPassTokenCtrl(HITLS_AUTH_PrivPassToken *object, int32_t cmd, void *param, uint32_t paramLen)
{
if (object == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
(void)paramLen;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGEREQUEST_INFO:
return PrivPassGetTokenChallengeRequest(object, param);
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_TYPE:
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_ISSUERNAME:
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_REDEMPTION:
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_ORIGININFO:
return PrivPassGetTokenChallengeContent(object, cmd, param);
case HITLS_AUTH_PRIVPASS_GET_TOKENREQUEST_TYPE:
case HITLS_AUTH_PRIVPASS_GET_TOKENREQUEST_TRUNCATEDTOKENKEYID:
case HITLS_AUTH_PRIVPASS_GET_TOKENREQUEST_BLINDEDMSG:
return PrivPassGetTokenRequestContent(object, cmd, param);
case HITLS_AUTH_PRIVPASS_GET_TOKENRESPONSE_INFO:
return PrivPassGetTokenResponseContent(object, param);
case HITLS_AUTH_PRIVPASS_GET_TOKEN_TYPE:
case HITLS_AUTH_PRIVPASS_GET_TOKEN_NONCE:
case HITLS_AUTH_PRIVPASS_GET_TOKEN_CHALLENGEDIGEST:
case HITLS_AUTH_PRIVPASS_GET_TOKEN_TOKENKEYID:
case HITLS_AUTH_PRIVPASS_GET_TOKEN_AUTHENTICATOR:
return PrivPassGetTokenContent(object, cmd, param);
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_CMD);
return HITLS_AUTH_PRIVPASS_INVALID_CMD;
}
}
static int32_t PrivPassGetCtxContent(HITLS_AUTH_PrivPassCtx *ctx, int32_t cmd, BSL_Param *param)
{
BSL_Param *output = NULL;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_CTX_NONCE:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_CTX_NONCE);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < PRIVPASS_TOKEN_NONCE_LEN) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, ctx->nonce, PRIVPASS_TOKEN_NONCE_LEN);
output->useLen = PRIVPASS_TOKEN_NONCE_LEN;
return HITLS_AUTH_SUCCESS;
case HITLS_AUTH_PRIVPASS_GET_CTX_TRUNCATEDTOKENKEYID:
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_CTX_TRUNCATEDTOKENKEYID);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_UINT8) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
return BSL_PARAM_SetValue(output, AUTH_PARAM_PRIVPASS_CTX_TRUNCATEDTOKENKEYID, BSL_PARAM_TYPE_UINT8,
&ctx->tokenKeyId[PRIVPASS_TOKEN_SHA256_SIZE - 1], 1); // 1 byte
default:
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_CTX_TOKENKEYID);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < PRIVPASS_TOKEN_SHA256_SIZE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, ctx->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE);
output->useLen = PRIVPASS_TOKEN_SHA256_SIZE;
return HITLS_AUTH_SUCCESS;
}
}
int32_t HITLS_AUTH_PrivPassCtxCtrl(HITLS_AUTH_PrivPassCtx *ctx, int32_t cmd, void *param, uint32_t paramLen)
{
if (ctx == NULL || param == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
(void)paramLen;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_CTX_TOKENKEYID:
case HITLS_AUTH_PRIVPASS_GET_CTX_TRUNCATEDTOKENKEYID:
case HITLS_AUTH_PRIVPASS_GET_CTX_NONCE:
return PrivPassGetCtxContent(ctx, cmd, param);
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_CMD);
return HITLS_AUTH_PRIVPASS_INVALID_CMD;
}
} | 2401_83913325/openHiTLS_1 | auth/privpass_token/src/privpass_token_util.c | C | unknown | 45,269 |
/*
* 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 "crypt_eal_pkey.h"
#include "crypt_eal_rand.h"
#include "auth_params.h"
#include "auth_errno.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "crypt_eal_md.h"
#include "crypt_eal_rand.h"
#include "crypt_errno.h"
#include "crypt_eal_codecs.h"
#include "auth_privpass_token.h"
#include "privpass_token.h"
#include "bsl_sal.h"
static void *PrivPassNewPkeyCtx(void *libCtx, const char *attrName, int32_t algId)
{
(void)libCtx;
(void)attrName;
return CRYPT_EAL_PkeyNewCtx(algId);
}
static void PrivPassFreePkeyCtx(void *pkeyCtx)
{
CRYPT_EAL_PkeyFreeCtx(pkeyCtx);
}
int32_t PrivPassPubDigest(void *libCtx, const char *attrName, int32_t algId, const uint8_t *input,
uint32_t inputLen, uint8_t *digest, uint32_t *digestLen)
{
(void)libCtx;
(void)attrName;
if (input == NULL || inputLen == 0 || digest == NULL || digestLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
uint32_t mdSize = CRYPT_EAL_MdGetDigestSize(algId);
if (mdSize == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (*digestLen < mdSize) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(algId);
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
int32_t ret = CRYPT_EAL_MdInit(ctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_EAL_MdFreeCtx(ctx);
return ret;
}
ret = CRYPT_EAL_MdUpdate(ctx, input, inputLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_EAL_MdFreeCtx(ctx);
return ret;
}
ret = CRYPT_EAL_MdFinal(ctx, digest, digestLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_EAL_MdFreeCtx(ctx);
return ret;
}
CRYPT_EAL_MdFreeCtx(ctx);
return CRYPT_SUCCESS;
}
static int32_t SetRsaBssaFlag(CRYPT_EAL_PkeyCtx *ctx, bool setPadding)
{
uint32_t flag = CRYPT_RSA_BSSA;
uint32_t padType = 0;
int32_t ret;
if (setPadding == true) {
padType = CRYPT_EMSA_PSS;
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_PADDING, &padType, sizeof(padType));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
} else {
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(padType));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (padType != CRYPT_EMSA_PSS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_ALG);
return HITLS_AUTH_PRIVPASS_INVALID_ALG;
}
}
return CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t));
}
static int32_t PrivPassPubBlind(void *pkeyCtx, int32_t algId, const uint8_t *data, uint32_t dataLen,
uint8_t *blindedData, uint32_t *blindedDataLen)
{
if (pkeyCtx == NULL || data == NULL || dataLen == 0 || blindedData == NULL || blindedDataLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = (CRYPT_EAL_PkeyCtx *)pkeyCtx;
int32_t ret = SetRsaBssaFlag(ctx, false); // false means get and verify padding type
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_EAL_PkeyBlind(ctx, algId, data, dataLen, blindedData, blindedDataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t PrivPassPubUnBlind(void *pkeyCtx, const uint8_t *blindedData, uint32_t blindedDataLen, uint8_t *data,
uint32_t *dataLen)
{
if (pkeyCtx == NULL || blindedData == NULL || blindedDataLen == 0 || data == NULL || dataLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = (CRYPT_EAL_PkeyCtx *)pkeyCtx;
return CRYPT_EAL_PkeyUnBlind(ctx, blindedData, blindedDataLen, data, dataLen);
}
static int32_t PrivPassPubSignData(void *pkeyCtx, const uint8_t *data, uint32_t dataLen, uint8_t *sign,
uint32_t *signLen)
{
if (pkeyCtx == NULL || data == NULL || dataLen == 0 || sign == NULL || signLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = (CRYPT_EAL_PkeyCtx *)pkeyCtx;
int32_t ret = SetRsaBssaFlag(ctx, true); // true means set padding type to CRYPT_EMSA_PSS
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return CRYPT_EAL_PkeySignData(ctx, data, dataLen, sign, signLen);
}
static int32_t PrivPassPubVerify(void *pkeyCtx, int32_t algId, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen)
{
if (pkeyCtx == NULL || data == NULL || dataLen == 0 || sign == NULL || signLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = (CRYPT_EAL_PkeyCtx *)pkeyCtx;
int32_t ret = SetRsaBssaFlag(ctx, false); // false means get and verify padding type
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return CRYPT_EAL_PkeyVerify(ctx, algId, data, dataLen, sign, signLen);
}
static int32_t PubKeyCheck(CRYPT_EAL_PkeyCtx *ctx)
{
uint32_t padType = 0;
uint32_t keyBits = 0;
CRYPT_MD_AlgId mdType = 0;
int32_t ret = CRYPT_EAL_PkeyGetId(ctx);
if (ret != CRYPT_PKEY_RSA) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_TYPE;
}
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(padType));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (padType != CRYPT_EMSA_PSS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_PADDING_INFO);
return HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_PADDING_INFO;
}
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_RSA_MD, &mdType, sizeof(CRYPT_MD_AlgId));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (mdType != CRYPT_MD_SHA384) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_PADDING_MD);
return HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_PADDING_MD;
}
keyBits = CRYPT_EAL_PkeyGetKeyBits(ctx);
if (keyBits != 2048) { // now only support rsa-2048
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_BITS);
return HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_BITS;
}
return CRYPT_SUCCESS;
}
static int32_t PrivPassPubDecodePubKey(void *libCtx, const char *attrName, uint8_t *pubKey, uint32_t pubKeyLen,
void **pkeyCtx)
{
(void)libCtx;
(void)attrName;
if (pkeyCtx == NULL || *pkeyCtx != NULL || pubKey == NULL || pubKeyLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = NULL;
BSL_Buffer encode = {.data = pubKey, .dataLen = pubKeyLen};
int32_t ret = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_ASN1, CRYPT_PUBKEY_SUBKEY, &encode, NULL, 0, &ctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = PubKeyCheck(ctx);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(ctx);
return ret;
}
*pkeyCtx = ctx;
return CRYPT_SUCCESS;
}
static int32_t PrivPassPubDecodePrvKey(void *libCtx, const char *attrName, void *param, uint8_t *prvKey,
uint32_t prvKeyLen, void **pkeyCtx)
{
(void)libCtx;
(void)attrName;
(void)param;
if (pkeyCtx == NULL || *pkeyCtx != NULL || prvKey == NULL || prvKeyLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = NULL;
uint32_t keyBits = 0;
uint8_t *tmpBuff = BSL_SAL_Malloc(prvKeyLen + 1);
if (tmpBuff == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
(void)memcpy_s(tmpBuff, prvKeyLen, prvKey, prvKeyLen);
tmpBuff[prvKeyLen] = '\0';
BSL_Buffer encode = {.data = tmpBuff, .dataLen = prvKeyLen};
int32_t ret = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, CRYPT_PRIKEY_PKCS8_UNENCRYPT, &encode, NULL, 0, &ctx);
(void)memset_s(tmpBuff, prvKeyLen, 0, prvKeyLen);
BSL_SAL_Free(tmpBuff);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (CRYPT_EAL_PkeyGetId(ctx) != CRYPT_PKEY_RSA) {
CRYPT_EAL_PkeyFreeCtx(ctx);
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PRVKEY_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_PRVKEY_TYPE;
}
keyBits = CRYPT_EAL_PkeyGetKeyBits(ctx);
if (keyBits != 2048) { // now only support rsa-2048
CRYPT_EAL_PkeyFreeCtx(ctx);
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PRVKEY_BITS);
return HITLS_AUTH_PRIVPASS_INVALID_PRVKEY_BITS;
}
*pkeyCtx = ctx;
return CRYPT_SUCCESS;
}
static int32_t PrivPassPubCheckKeyPair(void *pubKeyCtx, void *prvKeyCtx)
{
if (pubKeyCtx == NULL || prvKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
int32_t ret = CRYPT_EAL_PkeyPairCheck(pubKeyCtx, prvKeyCtx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t PrivPassPubRandom(uint8_t *buffer, uint32_t bufferLen)
{
if (buffer == NULL || bufferLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
return CRYPT_EAL_RandbytesEx(NULL, buffer, bufferLen);
}
PrivPassCryptCb PrivPassCryptPubCb(void)
{
PrivPassCryptCb method = {
.newPkeyCtx = PrivPassNewPkeyCtx,
.freePkeyCtx = PrivPassFreePkeyCtx,
.digest = PrivPassPubDigest,
.blind = PrivPassPubBlind,
.unBlind = PrivPassPubUnBlind,
.signData = PrivPassPubSignData,
.verify = PrivPassPubVerify,
.decodePubKey = PrivPassPubDecodePubKey,
.decodePrvKey = PrivPassPubDecodePrvKey,
.checkKeyPair = PrivPassPubCheckKeyPair,
.random = PrivPassPubRandom,
};
return method;
} | 2401_83913325/openHiTLS_1 | auth/privpass_token/src/privpass_token_wrapper.c | C | unknown | 11,243 |
/*
* 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 BSL_ASN1_INTERNAL_H
#define BSL_ASN1_INTERNAL_H
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include "bsl_list.h"
#include "bsl_uio.h"
#include "bsl_asn1.h"
#ifdef __cplusplus
extern "C" {
#endif
#define BSL_ASN1_MAX_TEMPLATE_DEPTH 6
#define BSL_ASN1_UTCTIME_LEN 13 // YYMMDDHHMMSSZ
#define BSL_ASN1_GENERALIZEDTIME_LEN 15 // YYYYMMDDHHMMSSZ
typedef enum {
BSL_ASN1_TYPE_GET_ANY_TAG = 0,
BSL_ASN1_TYPE_CHECK_CHOICE_TAG = 1
} BSL_ASN1_CALLBACK_TYPE;
/**
* @ingroup bsl_asn1
* @brief Obtain the length of V or LV in an ASN1 TLV structure.
*
* @param encode [IN/OUT] Data to be decoded. Update the offset after decoding.
* @param encLen [IN/OUT] The length of the data to be decoded.
* @param completeLen [IN] True: Get the length of L+V; False: Get the length of V.
* @param len [OUT] Output.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_DecodeLen(uint8_t **encode, uint32_t *encLen, bool completeLen, uint32_t *len);
/**
* @ingroup bsl_asn1
* @brief Decoding of primitive type data.
*
* @param asn [IN] The data to be decoded.
* @param decodeData [OUT] Decoding result.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_DecodePrimitiveItem(BSL_ASN1_Buffer *asn, void *decodeData);
/**
* @ingroup bsl_asn1
* @brief Decode one asn1 item.
*
* @param encode [IN/OUT] Data to be decoded. Update the offset after decoding.
* @param encLen [IN/OUT] The length of the data to be decoded.
* @param asnItem [OUT] Output.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_DecodeItem(uint8_t **encode, uint32_t *encLen, BSL_ASN1_Buffer *asnItem);
/**
* @ingroup bsl_asn1
* @brief Obtain the length of an ASN1 TLV structure.
*
* @param data [IN] Data to be decoded. Update the offset after decoding.
* @param dataLen [OUT] Decoding result.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_GetCompleteLen(uint8_t *data, uint32_t *dataLen);
/**
* @ingroup bsl_asn1
* @brief Encode the smaller positive integer.
*
* @param tag [IN] BSL_ASN1_TAG_INTEGER or BSL_ASN1_TAG_ENUMERATED
* @param limb [IN] Positive integer.
* @param asn [OUT] Encoding result.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_EncodeLimb(uint8_t tag, uint64_t limb, BSL_ASN1_Buffer *asn);
/**
* @ingroup bsl_asn1
* @brief Calculate the total encoding length for a ASN.1 type through the content length.
*
* @param contentLen [IN] The length of the content to be encoded.
* @param encodeLen [OUT] The total number of bytes needed for DER encoding.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_GetEncodeLen(uint32_t contentLen, uint32_t *encodeLen);
#ifdef __cplusplus
}
#endif
#endif // BSL_ASN1_INTERNAL_H
| 2401_83913325/openHiTLS_1 | bsl/asn1/include/bsl_asn1_internal.h | C | unknown | 3,544 |
/*
* 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 "securec.h"
#include "bsl_err.h"
#include "bsl_log_internal.h"
#include "bsl_binlog_id.h"
#include "bsl_asn1_local.h"
#include "bsl_sal.h"
#include "sal_time.h"
#define BSL_ASN1_INDEFINITE_LENGTH 0x80
#define BSL_ASN1_DEFINITE_MAX_CONTENT_OCTET_NUM 0x7F // 127
typedef struct {
BSL_ASN1_DecodeListParam *param;
BSL_ASN1_Buffer *asn;
BSL_ASN1_ParseListAsnItem parseListItemCb;
void *cbParam;
BSL_ASN1_List *list;
} BSL_ASN1_DecodeListInternalParam;
int32_t BSL_ASN1_DecodeLen(uint8_t **encode, uint32_t *encLen, bool completeLen, uint32_t *len)
{
if (encode == NULL || *encode == NULL || encLen == NULL || len == NULL) {
return BSL_NULL_INPUT;
}
uint8_t *temp = *encode;
uint32_t tempLen = *encLen;
uint32_t parseLen = 0;
if (tempLen < 1) {
return BSL_ASN1_ERR_DECODE_LEN;
}
if ((*temp & BSL_ASN1_INDEFINITE_LENGTH) == 0) {
parseLen = *temp;
temp++;
tempLen--;
parseLen += ((completeLen) ? 1 : 0);
} else {
uint32_t index = *temp - BSL_ASN1_INDEFINITE_LENGTH;
if (index > sizeof(int32_t)) {
return BSL_ASN1_ERR_MAX_LEN_NUM;
}
temp++;
tempLen--;
if (tempLen < index) {
return BSL_ASN1_ERR_BUFF_NOT_ENOUGH;
}
for (uint32_t iter = 0; iter < index; iter++) {
parseLen = (parseLen << 8) | *temp; // one byte = 8 bits
temp++;
tempLen--;
}
// anti-flip
if (parseLen >= ((((uint64_t)1 << 32) - 1) - index - 2)) { // 1<<32:U32_MAX; 2: Tag + length(0x8x)
return BSL_ASN1_ERR_MAX_LEN_NUM;
}
parseLen += ((completeLen) ? (index + 1) : 0);
}
uint32_t length = (completeLen) ? *encLen : tempLen;
/* The length supports a maximum of 4 bytes */
if (parseLen > length) {
return BSL_ASN1_ERR_DECODE_LEN;
}
*len = parseLen;
*encode = temp;
*encLen = tempLen;
return BSL_SUCCESS;
}
int32_t BSL_ASN1_GetCompleteLen(uint8_t *data, uint32_t *dataLen)
{
uint8_t *tmp = data;
uint32_t tmpLen = *dataLen;
uint32_t len = 0;
if (tmpLen < 1) {
return BSL_ASN1_ERR_BUFF_NOT_ENOUGH;
}
tmp++;
tmpLen--;
int32_t ret = BSL_ASN1_DecodeLen(&tmp, &tmpLen, true, &len);
if (ret != BSL_SUCCESS) {
return ret;
}
*dataLen = len + 1;
return BSL_SUCCESS;
}
int32_t BSL_ASN1_DecodeTagLen(uint8_t tag, uint8_t **encode, uint32_t *encLen, uint32_t *valLen)
{
if (encode == NULL || *encode == NULL || encLen == NULL || valLen == NULL) {
return BSL_NULL_INPUT;
}
uint8_t *temp = *encode;
uint32_t tempLen = *encLen;
if (tempLen < 1) {
return BSL_INVALID_ARG;
}
if (tag != *temp) {
return BSL_ASN1_ERR_MISMATCH_TAG;
}
temp++;
tempLen--;
uint32_t len;
int32_t ret = BSL_ASN1_DecodeLen(&temp, &tempLen, false, &len);
if (ret != BSL_SUCCESS) {
return ret;
}
if (len > tempLen) {
return BSL_ASN1_ERR_BUFF_NOT_ENOUGH;
}
*valLen = len;
*encode = temp;
*encLen = tempLen;
return BSL_SUCCESS;
}
int32_t BSL_ASN1_DecodeItem(uint8_t **encode, uint32_t *encLen, BSL_ASN1_Buffer *asnItem)
{
if (encode == NULL || *encode == NULL || encLen == NULL || asnItem == NULL) {
return BSL_NULL_INPUT;
}
uint8_t tag;
uint32_t len;
uint8_t *temp = *encode;
uint32_t tempLen = *encLen;
if (tempLen < 1) {
return BSL_INVALID_ARG;
}
tag = *temp;
temp++;
tempLen--;
int32_t ret = BSL_ASN1_DecodeLen(&temp, &tempLen, false, &len);
if (ret != BSL_SUCCESS) {
return ret;
}
asnItem->tag = tag;
asnItem->len = len;
asnItem->buff = temp;
temp += len;
tempLen -= len;
*encode = temp;
*encLen = tempLen;
return BSL_SUCCESS;
}
static int32_t ParseBool(uint8_t *val, uint32_t len, bool *decodeData)
{
if (len != 1) {
return BSL_ASN1_ERR_DECODE_BOOL;
}
*decodeData = (*val != 0) ? 1 : 0;
return BSL_SUCCESS;
}
static int32_t ParseInt(uint8_t *val, uint32_t len, int *decodeData)
{
uint8_t *temp = val;
if (len < 1 || len > sizeof(int)) {
return BSL_ASN1_ERR_DECODE_INT;
}
*decodeData = 0;
for (uint32_t i = 0; i < len; i++) {
*decodeData = (*decodeData << 8) | *temp;
temp++;
}
return BSL_SUCCESS;
}
static int32_t ParseBitString(uint8_t *val, uint32_t len, BSL_ASN1_BitString *decodeData)
{
if (len < 1 || *val > BSL_ASN1_VAL_MAX_BIT_STRING_LEN) {
return BSL_ASN1_ERR_DECODE_BIT_STRING;
}
decodeData->unusedBits = *val;
decodeData->buff = val + 1;
decodeData->len = len - 1;
return BSL_SUCCESS;
}
// len max support 4
static uint32_t DecodeAsciiNum(uint8_t **encode, uint32_t len)
{
uint32_t temp = 0;
uint8_t *data = *encode;
for (uint32_t i = 0; i < len; i++) {
temp *= 10; // 10: Process decimal numbers.
temp += (data[i] - '0');
}
*encode += len;
return temp;
}
static int32_t CheckTime(uint8_t *data, uint32_t len)
{
for (uint32_t i = 0; i < len; i++) {
if (data[i] > '9' || data[i] < '0') {
return BSL_ASN1_ERR_DECODE_TIME;
}
}
return BSL_SUCCESS;
}
// Support utcTime for YYMMDDHHMMSS[Z] and generalizedTime for YYYYMMDDHHMMSS[Z].
static int32_t ParseTime(uint8_t tag, uint8_t *val, uint32_t len, BSL_TIME *decodeData)
{
int32_t ret;
uint8_t *temp = val;
if (tag == BSL_ASN1_TAG_UTCTIME && (len != 12 && len != 13)) { // 12 YYMMDDHHMMSS, 13 YYMMDDHHMMSSZ
return BSL_ASN1_ERR_DECODE_UTC_TIME;
}
if (tag == BSL_ASN1_TAG_GENERALIZEDTIME && (len != 14 && len != 15)) { // 14 YYYYMMDDHHMMSS, 15 YYYYMMDDHHMMSSZ
return BSL_ASN1_ERR_DECODE_GENERAL_TIME;
}
// Check if the encoding is within the expected range and prepare for conversion
ret = tag == BSL_ASN1_TAG_UTCTIME ? CheckTime(val, 12) : CheckTime(val, 14); // 12|14: ignoring Z
if (ret != BSL_SUCCESS) {
return ret;
}
if (tag == BSL_ASN1_TAG_UTCTIME) {
decodeData->year = (uint16_t)DecodeAsciiNum(&temp, 2); // 2: YY
if (decodeData->year < 50) {
decodeData->year += 2000;
} else {
decodeData->year += 1900;
}
} else {
decodeData->year = (uint16_t)DecodeAsciiNum(&temp, 4); // 4: YYYY
}
decodeData->month = (uint8_t)DecodeAsciiNum(&temp, 2); // 2:MM
decodeData->day = (uint8_t)DecodeAsciiNum(&temp, 2); // 2: DD
decodeData->hour = (uint8_t)DecodeAsciiNum(&temp, 2); // 2: HH
decodeData->minute = (uint8_t)DecodeAsciiNum(&temp, 2); // 2: MM
decodeData->second = (uint8_t)DecodeAsciiNum(&temp, 2); // 2: SS
return BSL_DateTimeCheck(decodeData) ? BSL_SUCCESS : BSL_ASN1_ERR_CHECK_TIME;
}
static int32_t DecodeTwoLayerListInternal(uint32_t layer, BSL_ASN1_Buffer *asn,
BSL_ASN1_DecodeListInternalParam *internalParam)
{
int32_t ret;
uint8_t tag;
uint32_t encLen;
uint8_t *buff = asn->buff;
uint32_t len = asn->len;
BSL_ASN1_Buffer item;
while (len > 0) {
if (*buff != internalParam->param->expTag[layer - 1]) {
return BSL_ASN1_ERR_MISMATCH_TAG;
}
tag = *buff;
buff++;
len--;
ret = BSL_ASN1_DecodeLen(&buff, &len, false, &encLen);
if (ret != BSL_SUCCESS) {
return ret;
}
item.tag = tag;
item.len = encLen;
item.buff = buff;
ret = internalParam->parseListItemCb(layer, &item, internalParam->cbParam, internalParam->list);
if (ret != BSL_SUCCESS) {
return ret;
}
buff += encLen;
len -= encLen;
}
return BSL_SUCCESS;
}
static int32_t DecodeOneLayerList(BSL_ASN1_DecodeListInternalParam *internalParam)
{
return DecodeTwoLayerListInternal(1, internalParam->asn, internalParam);
}
static int32_t DecodeTwoLayerList(BSL_ASN1_DecodeListInternalParam *internalParam)
{
int32_t ret;
uint8_t tag;
uint32_t encLen;
uint8_t *buff = internalParam->asn->buff;
uint32_t len = internalParam->asn->len;
BSL_ASN1_Buffer item;
while (len > 0) {
if (*buff != internalParam->param->expTag[0]) {
return BSL_ASN1_ERR_MISMATCH_TAG;
}
tag = *buff;
buff++;
len--;
ret = BSL_ASN1_DecodeLen(&buff, &len, false, &encLen);
if (ret != BSL_SUCCESS) {
return ret;
}
item.tag = tag;
item.len = encLen;
item.buff = buff;
ret = internalParam->parseListItemCb(1, &item, internalParam->cbParam, internalParam->list);
if (ret != BSL_SUCCESS) {
return ret;
}
ret = DecodeTwoLayerListInternal(2, &item, internalParam); // Level 2 List.
if (ret != BSL_SUCCESS) {
return ret;
}
buff += encLen;
len -= encLen;
}
return BSL_SUCCESS;
}
int32_t BSL_ASN1_DecodeListItem(BSL_ASN1_DecodeListParam *param, BSL_ASN1_Buffer *asn,
BSL_ASN1_ParseListAsnItem parseListItemCb, void *cbParam, BSL_ASN1_List *list)
{
if (param == NULL || asn == NULL || parseListItemCb == NULL || list == NULL) {
return BSL_INVALID_ARG;
}
// Currently, it supports a maximum of 2 layers
if (param->layer > BSL_ASN1_MAX_LIST_NEST_EPTH) {
return BSL_ASN1_ERR_EXCEED_LIST_DEPTH;
}
BSL_ASN1_DecodeListInternalParam internalParam = {param, asn, parseListItemCb, cbParam, list};
return param->layer == 1 ? DecodeOneLayerList(&internalParam)
: DecodeTwoLayerList(&internalParam);
}
static int32_t ParseBMPString(const uint8_t *bmp, uint32_t bmpLen, BSL_ASN1_Buffer *decode)
{
if (bmp == NULL || bmpLen == 0 || decode == NULL) {
return BSL_NULL_INPUT;
}
if (bmpLen % 2 != 0) { // multiple of 2
return BSL_INVALID_ARG;
}
uint8_t *tmp = (uint8_t *)BSL_SAL_Malloc(bmpLen / 2); // decodeLen = bmpLen/2
if (tmp == NULL) {
return BSL_MALLOC_FAIL;
}
for (uint32_t i = 0; i < bmpLen / 2; i++) { // decodeLen = bmpLen/2
tmp[i] = bmp[i * 2 + 1];
}
decode->buff = tmp;
decode->len = bmpLen / 2; // decodeLen = bmpLen/2
return BSL_SUCCESS;
}
static void EncodeT61String(const uint8_t *in, uint32_t inLen, uint8_t *encode, uint32_t *offset)
{
(void)memcpy_s(encode + *offset, inLen, in, inLen);
*offset += inLen;
return;
}
static void EncodeBMPString(const uint8_t *in, uint32_t inLen, uint8_t *encode, uint32_t *offset)
{
uint8_t *output = encode + *offset;
for (uint32_t i = 0; i < inLen; i++) {
output[2 * i + 1] = in[i]; // need 2 space, [0,0] -> after encode = [0, data];
output[2 * i + 0] = 0;
}
*offset += inLen * 2; // encodeLen = 2 * inLen
return;
}
/**
* Big numbers do not need to call this interface,
* the filled leading 0 has no effect on the result of large numbers, big numbers can be directly used asn's buff.
*
* It has been ensured at parsing time that the content to which the buff points is security for length within asn'len
*/
int32_t BSL_ASN1_DecodePrimitiveItem(BSL_ASN1_Buffer *asn, void *decodeData)
{
if (asn == NULL || decodeData == NULL) {
return BSL_NULL_INPUT;
}
switch (asn->tag) {
case BSL_ASN1_TAG_BOOLEAN:
return ParseBool(asn->buff, asn->len, decodeData);
case BSL_ASN1_TAG_INTEGER:
case BSL_ASN1_TAG_ENUMERATED:
return ParseInt(asn->buff, asn->len, decodeData);
case BSL_ASN1_TAG_BITSTRING:
return ParseBitString(asn->buff, asn->len, decodeData);
case BSL_ASN1_TAG_UTCTIME:
case BSL_ASN1_TAG_GENERALIZEDTIME:
return ParseTime(asn->tag, asn->buff, asn->len, decodeData);
case BSL_ASN1_TAG_BMPSTRING:
return ParseBMPString(asn->buff, asn->len, decodeData);
default:
break;
}
return BSL_ASN1_FAIL;
}
static int32_t BSL_ASN1_AnyOrChoiceTagProcess(bool isAny, BSL_ASN1_AnyOrChoiceParam *tagCbinfo, uint8_t *tag)
{
if (tagCbinfo->tagCb == NULL) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05065, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: callback is null", 0, 0, 0, 0);
return BSL_ASN1_ERR_NO_CALLBACK;
}
int32_t type = isAny == true ? BSL_ASN1_TYPE_GET_ANY_TAG : BSL_ASN1_TYPE_CHECK_CHOICE_TAG;
int32_t ret = tagCbinfo->tagCb(type, tagCbinfo->idx, tagCbinfo->previousAsnOrTag, tag);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05066, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: callback is err %x", ret, 0, 0, 0);
}
return ret;
}
static int32_t BSL_ASN1_ProcessWithoutDefOrOpt(BSL_ASN1_AnyOrChoiceParam *tagCbinfo, uint8_t realTag, uint8_t *expTag)
{
int32_t ret;
uint8_t tag = *expTag;
// Any and choice will not have a coexistence scenario, which is meaningless.
if (tag == BSL_ASN1_TAG_CHOICE) {
tagCbinfo->previousAsnOrTag = &realTag;
return BSL_ASN1_AnyOrChoiceTagProcess(false, tagCbinfo, expTag);
}
// The tags of any and normal must be present
if (tag == BSL_ASN1_TAG_ANY) {
ret = BSL_ASN1_AnyOrChoiceTagProcess(true, tagCbinfo, &tag);
if (ret != BSL_SUCCESS) {
return ret;
}
}
if (tag != realTag) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05067, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: expected tag %x is not match %x", tag, realTag, 0, 0);
return BSL_ASN1_ERR_TAG_EXPECTED;
}
*expTag = realTag;
return BSL_SUCCESS;
}
/**
* Reference: X.690 Information technology - ASN.1 encoding rules: 8.3
* If the contents octect of an integer value encoding consist of more than one octet,
* then the bits of the first octet and bit 8 of the second octet:
* a): shall not all be ones; and
* b): shall not all be zero.
*
* Note: Currently, only positive integers are supported, and negative integers are not supported.
*/
int32_t ProcessIntegerType(uint8_t *temp, uint32_t len, BSL_ASN1_Buffer *asn)
{
// Check if it is a negative number
if (*temp & 0x80) {
return BSL_ASN1_ERR_DECODE_INT;
}
// Check if the first octet is 0 and the second octet is not 0
if (*temp == 0 && len > 1 && (*(temp + 1) & 0x80) == 0) {
return BSL_ASN1_ERR_DECODE_INT;
}
// Calculate the actual length (remove leading zeros)
uint32_t actualLen = len;
uint8_t *actualBuff = temp;
while (actualLen > 1 && *actualBuff == 0) {
actualLen--;
actualBuff++;
}
asn->len = actualLen;
asn->buff = actualBuff;
return BSL_SUCCESS;
}
static int32_t ProcessTag(uint8_t flags, BSL_ASN1_AnyOrChoiceParam *tagCbinfo, uint8_t *temp, uint32_t tempLen,
uint8_t *tag, BSL_ASN1_Buffer *asn)
{
int32_t ret = BSL_SUCCESS;
if ((flags & BSL_ASN1_FLAG_OPTIONAL_DEFAUL) != 0) {
if (tempLen < 1) {
asn->tag = 0;
asn->len = 0;
asn->buff = NULL;
return BSL_SUCCESS;
}
if (*tag == BSL_ASN1_TAG_ANY) {
ret = BSL_ASN1_AnyOrChoiceTagProcess(true, tagCbinfo, tag);
if (ret != BSL_SUCCESS) {
return ret;
}
}
if (*tag == BSL_ASN1_TAG_CHOICE) {
tagCbinfo->previousAsnOrTag = temp;
ret = BSL_ASN1_AnyOrChoiceTagProcess(false, tagCbinfo, tag);
if (ret != BSL_SUCCESS) {
return ret;
}
}
if (*tag == BSL_ASN1_TAG_EMPTY) {
return BSL_ASN1_ERR_TAG_EXPECTED;
}
if (*tag != *temp) { // The optional or default scene is not encoded
asn->tag = 0;
asn->len = 0;
asn->buff = NULL;
}
} else {
/* No optional or default scenes, tag must exist */
if (tempLen < 1) {
return BSL_ASN1_ERR_DECODE_LEN;
}
ret = BSL_ASN1_ProcessWithoutDefOrOpt(tagCbinfo, *temp, tag);
}
return ret;
}
static int32_t BSL_ASN1_ProcessNormal(BSL_ASN1_AnyOrChoiceParam *tagCbinfo,
BSL_ASN1_TemplateItem *item, uint8_t **encode, uint32_t *encLen, BSL_ASN1_Buffer *asn)
{
uint32_t len;
uint8_t tag = item->tag;
uint8_t *temp = *encode;
uint32_t tempLen = *encLen;
asn->tag = tag; // init tag
int32_t ret = ProcessTag(item->flags, tagCbinfo, temp, tempLen, &tag, asn);
if (ret != BSL_SUCCESS || asn->tag == 0) {
return ret;
}
temp++;
tempLen--;
ret = BSL_ASN1_DecodeLen(&temp, &tempLen, false, &len);
if (ret != BSL_SUCCESS) {
return ret;
}
asn->tag = tag; // update tag
if ((tag == BSL_ASN1_TAG_INTEGER || tag == BSL_ASN1_TAG_ENUMERATED) && len > 0) {
ret = ProcessIntegerType(temp, len, asn);
if (ret != BSL_SUCCESS) {
return ret;
}
} else {
asn->len = len;
asn->buff = (tag == BSL_ASN1_TAG_NULL) ? NULL : temp;
}
/* struct type, headerOnly flag is set, only the whole is parsed, otherwise the parsed content is traversed */
if (((item->tag & BSL_ASN1_TAG_CONSTRUCTED) != 0 && (item->flags & BSL_ASN1_FLAG_HEADERONLY) != 0) ||
(item->tag & BSL_ASN1_TAG_CONSTRUCTED) == 0) {
temp += len;
tempLen -= len;
}
*encode = temp;
*encLen = tempLen;
return BSL_SUCCESS;
}
uint32_t BSL_ASN1_SkipChildNode(uint32_t idx, BSL_ASN1_TemplateItem *item, uint32_t count)
{
uint32_t i = idx + 1;
for (; i < count; i++) {
if (item[i].depth <= item[idx].depth) {
break;
}
}
return i - idx;
}
static bool BSL_ASN1_IsConstructItem(BSL_ASN1_TemplateItem *item)
{
return item->tag & BSL_ASN1_TAG_CONSTRUCTED;
}
static int32_t BSL_ASN1_FillConstructItemWithNull(BSL_ASN1_Template *templ, uint32_t *templIdx,
BSL_ASN1_Buffer *asnArr, uint32_t arrNum, uint32_t *arrIdx)
{
// The construct type value is marked headeronly
if ((templ->templItems[*templIdx].flags & BSL_ASN1_FLAG_HEADERONLY) != 0) {
if (*arrIdx >= arrNum) {
return BSL_ASN1_ERR_OVERFLOW;
} else {
asnArr[*arrIdx].tag = 0;
asnArr[*arrIdx].len = 0;
asnArr[*arrIdx].buff = 0;
(*arrIdx)++;
}
(*templIdx) += BSL_ASN1_SkipChildNode(*templIdx, templ->templItems, templ->templNum);
} else {
// This scenario does not record information about the parent node
(*templIdx)++;
}
return BSL_SUCCESS;
}
int32_t BSL_ASN1_SkipChildNodeAndFill(uint32_t *idx, BSL_ASN1_Template *templ,
BSL_ASN1_Buffer *asnArr, uint32_t arrNum, uint32_t *arrIndex)
{
uint32_t arrIdx = *arrIndex;
uint32_t i = *idx;
for (; i < templ->templNum;) {
if (templ->templItems[i].depth <= templ->templItems[*idx].depth && i > *idx) {
break;
}
// There are also struct types under the processing parent
if (BSL_ASN1_IsConstructItem(&templ->templItems[i])) {
int32_t ret = BSL_ASN1_FillConstructItemWithNull(templ, &i, asnArr, arrNum, &arrIdx);
if (ret != BSL_SUCCESS) {
return ret;
}
} else {
asnArr[arrIdx].tag = 0;
asnArr[arrIdx].len = 0;
asnArr[arrIdx].buff = 0;
arrIdx++;
i++;
}
}
*arrIndex = arrIdx;
*idx = i;
return BSL_SUCCESS;
}
int32_t BSL_ASN1_ProcessConstructResult(BSL_ASN1_Template *templ, uint32_t *templIdx, BSL_ASN1_Buffer *asn,
BSL_ASN1_Buffer *asnArr, uint32_t arrNum, uint32_t *arrIdx)
{
int32_t ret;
// Optional or default construct type, without any data to be parsed, need to skip all child nodes
if ((templ->templItems[*templIdx].flags & BSL_ASN1_FLAG_OPTIONAL_DEFAUL) != 0 && asn->tag == 0) {
ret = BSL_ASN1_SkipChildNodeAndFill(templIdx, templ, asnArr, arrNum, arrIdx);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05068, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: skip and fill node err %x, idx %u", ret, *templIdx, 0, 0);
return ret;
}
return BSL_SUCCESS;
}
if ((templ->templItems[*templIdx].flags & BSL_ASN1_FLAG_HEADERONLY) != 0) {
if (*arrIdx >= arrNum) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05069, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: array idx %u, overflow %u, templ %u", *arrIdx, arrNum, *templIdx, 0);
return BSL_ASN1_ERR_OVERFLOW;
} else {
// Shallow copy of structure
asnArr[*arrIdx].tag = asn->tag;
asnArr[*arrIdx].len = asn->len;
asnArr[*arrIdx].buff = asn->buff;
(*arrIdx)++;
}
(*templIdx) += BSL_ASN1_SkipChildNode(*templIdx, templ->templItems, templ->templNum);
} else {
(*templIdx)++; // Non header only flags, do not fill this parse
}
return BSL_SUCCESS;
}
static inline bool IsInvalidTempl(BSL_ASN1_Template *templ)
{
return templ == NULL || templ->templNum == 0 || templ->templItems == NULL;
}
static inline bool IsInvalidAsns(BSL_ASN1_Buffer *asnArr, uint32_t arrNum)
{
return asnArr == NULL || arrNum == 0;
}
int32_t BSL_ASN1_DecodeTemplate(BSL_ASN1_Template *templ, BSL_ASN1_DecTemplCallBack decTemlCb,
uint8_t **encode, uint32_t *encLen, BSL_ASN1_Buffer *asnArr, uint32_t arrNum)
{
int32_t ret;
if (IsInvalidTempl(templ) || encode == NULL || *encode == NULL || encLen == NULL || IsInvalidAsns(asnArr, arrNum)) {
return BSL_NULL_INPUT;
}
uint8_t *temp = *encode;
uint32_t tempLen = *encLen;
BSL_ASN1_Buffer asn = {0}; // temp var
uint32_t arrIdx = 0;
BSL_ASN1_Buffer previousAsn = {0};
BSL_ASN1_AnyOrChoiceParam tagCbinfo = {0, NULL, decTemlCb};
for (uint32_t i = 0; i < templ->templNum;) {
if (templ->templItems[i].depth > BSL_ASN1_MAX_TEMPLATE_DEPTH) {
return BSL_ASN1_ERR_MAX_DEPTH;
}
tagCbinfo.previousAsnOrTag = &previousAsn;
tagCbinfo.idx = i;
if (BSL_ASN1_IsConstructItem(&templ->templItems[i])) {
ret = BSL_ASN1_ProcessNormal(&tagCbinfo, &templ->templItems[i], &temp, &tempLen, &asn);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05070, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: parse construct item err %x, idx %u", ret, i, 0, 0);
return ret;
}
ret = BSL_ASN1_ProcessConstructResult(templ, &i, &asn, asnArr, arrNum, &arrIdx);
if (ret != BSL_SUCCESS) {
return ret;
}
} else {
ret = BSL_ASN1_ProcessNormal(&tagCbinfo, &templ->templItems[i], &temp, &tempLen, &asn);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05071, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: parse primitive item err %x, idx %u", ret, i, 0, 0);
return ret;
}
// Process no construct result
if (arrIdx >= arrNum) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05072, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: array idx %u, overflow %u, templ %u", arrIdx, arrNum, i, 0);
return BSL_ASN1_ERR_OVERFLOW;
} else {
asnArr[arrIdx++] = asn; // Shallow copy of structure
}
i++;
}
previousAsn = asn;
}
*encode = temp;
*encLen = tempLen;
return BSL_SUCCESS;
}
/* Init the depth and flags of the items. */
static int32_t EncodeInitItemFlag(BSL_ASN1_EncodeItem *eItems, BSL_ASN1_TemplateItem *tItems, uint32_t eleNum)
{
uint32_t stack[BSL_ASN1_MAX_TEMPLATE_DEPTH + 1] = {0}; // store the index of the items
int32_t peek = 0;
/* Stack the first item */
if (tItems[0].depth > BSL_ASN1_MAX_TEMPLATE_DEPTH) {
return BSL_ASN1_ERR_MAX_DEPTH;
}
eItems[0].depth = tItems[0].depth;
eItems[0].optional = tItems[0].flags & BSL_ASN1_FLAG_OPTIONAL_DEFAUL;
stack[peek] = 0;
for (uint32_t i = 1; i < eleNum; i++) {
if (tItems[i].depth > BSL_ASN1_MAX_TEMPLATE_DEPTH) {
return BSL_ASN1_ERR_MAX_DEPTH;
}
eItems[i].depth = tItems[i].depth;
while (eItems[i].depth <= eItems[stack[peek]].depth) {
peek--;
}
/* After the above processing, the top of the stack is the parent node of the current node. */
/* The null type only inherits the optional tag of the parent node. */
eItems[i].optional = eItems[stack[peek]].optional;
if (tItems[i].tag != BSL_ASN1_TAG_NULL) {
eItems[i].optional |= (tItems[i].flags & BSL_ASN1_FLAG_OPTIONAL_DEFAUL);
}
eItems[i].skip = eItems[stack[peek]].skip == 1 || (tItems[stack[peek]].flags & BSL_ASN1_FLAG_HEADERONLY) != 0;
stack[++peek] = i;
}
return BSL_SUCCESS;
}
static inline bool IsAnyOrChoice(uint8_t tag)
{
return tag == BSL_ASN1_TAG_ANY || tag == BSL_ASN1_TAG_CHOICE;
}
static uint8_t GetOctetNumOfUint(uint64_t number)
{
uint8_t cnt = 0;
for (uint64_t i = number; i != 0; i >>= 8) { // one byte = 8 bits
cnt++;
}
return cnt;
}
static uint8_t GetLenOctetNum(uint32_t contentOctetNum)
{
return contentOctetNum <= BSL_ASN1_DEFINITE_MAX_CONTENT_OCTET_NUM ? 1 : 1 + GetOctetNumOfUint(contentOctetNum);
}
static int32_t GetContentLenOfInt(uint8_t *buff, uint32_t len, uint32_t *outLen)
{
if (len == 0) {
*outLen = 0;
return BSL_SUCCESS;
}
uint32_t res = len;
for (uint32_t i = 0; i < len; i++) {
if (buff[i] != 0) {
break;
}
res--;
}
if (res == 0) { // The current int value is 0
*outLen = 1;
return BSL_SUCCESS;
}
uint8_t high = buff[len - res] & 0x80;
if (high) {
if (res == UINT32_MAX) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
res++;
}
*outLen = res;
return BSL_SUCCESS;
}
static int32_t GetContentLen(BSL_ASN1_Buffer *asn, uint32_t *len)
{
if (asn == NULL || len == NULL) {
return BSL_NULL_INPUT;
}
switch (asn->tag) {
case BSL_ASN1_TAG_NULL:
*len = 0;
return BSL_SUCCESS;
case BSL_ASN1_TAG_INTEGER:
case BSL_ASN1_TAG_ENUMERATED:
return GetContentLenOfInt(asn->buff, asn->len, len);
case BSL_ASN1_TAG_BITSTRING:
*len = ((BSL_ASN1_BitString *)asn->buff)->len;
if (*len == UINT32_MAX) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
*len += 1;
return BSL_SUCCESS;
case BSL_ASN1_TAG_UTCTIME:
*len = BSL_ASN1_UTCTIME_LEN;
return BSL_SUCCESS;
case BSL_ASN1_TAG_GENERALIZEDTIME:
*len = BSL_ASN1_GENERALIZEDTIME_LEN;
return BSL_SUCCESS;
case BSL_ASN1_TAG_BMPSTRING:
if (asn->len > UINT32_MAX / 2) { // 2: Each character is 2 bytes
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
*len = asn->len * 2; // 2: Each character is 2 bytes
return BSL_SUCCESS;
case BSL_ASN1_TAG_T61STRING:
*len = asn->len;
return BSL_SUCCESS;
default:
*len = asn->len;
return BSL_SUCCESS;
}
}
static int32_t ComputeOctetNum(bool optional, BSL_ASN1_EncodeItem *item, BSL_ASN1_Buffer *asn)
{
if (optional && asn->len == 0 && (asn->tag != BSL_ASN1_TAG_NULL)) {
return BSL_SUCCESS;
}
uint32_t contentOctetNum = 0;
if (asn->len != 0) {
int32_t ret = GetContentLen(asn, &contentOctetNum);
if (ret != BSL_SUCCESS) {
return ret;
}
}
item->lenOctetNum = GetLenOctetNum(contentOctetNum);
uint64_t tmp = (uint64_t)item->lenOctetNum + contentOctetNum;
if (tmp > UINT32_MAX - 1) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
item->asnOctetNum = 1 + item->lenOctetNum + contentOctetNum;
return BSL_SUCCESS;
}
static int32_t ComputeConstructAsnOctetNum(bool optional, BSL_ASN1_TemplateItem *templ, BSL_ASN1_EncodeItem *item,
uint32_t itemNum, uint32_t curIdx)
{
uint8_t curDepth = templ[curIdx].depth;
uint32_t contentOctetNum = 0;
for (uint32_t i = curIdx + 1; i < itemNum && templ[i].depth != curDepth; i++) {
if (templ[i].depth - curDepth == 1) {
if (item[i].asnOctetNum > UINT32_MAX - contentOctetNum) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
contentOctetNum += item[i].asnOctetNum;
}
}
if (contentOctetNum == 0 && optional) {
return BSL_SUCCESS;
}
item[curIdx].lenOctetNum = GetLenOctetNum(contentOctetNum);
// Use 64-bit math to prevent overflow during calculation
uint64_t totalLen = (uint64_t)item[curIdx].lenOctetNum + contentOctetNum;
// Check for 32-bit overflow (ASN.1 length must fit in uint32_t)
if (totalLen > UINT32_MAX - 1) { // -1 accounts for tag byte
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
item[curIdx].asnOctetNum = 1 + item[curIdx].lenOctetNum + contentOctetNum;
return BSL_SUCCESS;
}
/**
* ASN.1 Encode Init Item Content:
* 1. Reverse traversal template items (from deepest to root node)
* 2. Process two types:
* - Construct type (SEQUENCE/SET): Calculate total length of contained sub-items
* - Basic type: Validate tag and calculate encoding length
*/
static int32_t EncodeInitItemContent(BSL_ASN1_EncodeItem *eItems, BSL_ASN1_TemplateItem *tItems, uint32_t itemNum,
BSL_ASN1_Buffer *asnArr, uint32_t *asnNum)
{
int64_t asnIdx = (int64_t)*asnNum - 1;
uint8_t lastDepth = 0;
int32_t ret;
for (int64_t i = itemNum - 1; i >= 0; i--) {
if (eItems[i].skip == 1) {
continue;
}
if (tItems[i].depth < lastDepth) {
eItems[i].tag = tItems[i].tag;
ret = ComputeConstructAsnOctetNum(eItems[i].optional, tItems, eItems, itemNum, i);
if (ret != BSL_SUCCESS) {
return ret;
}
} else {
if (asnIdx < 0) {
return BSL_ASN1_ERR_ENCODE_ASN_LACK;
}
if (eItems[i].optional == false && asnArr[asnIdx].tag != tItems[i].tag && !IsAnyOrChoice(tItems[i].tag)) {
return BSL_ASN1_ERR_TAG_EXPECTED;
}
ret = ComputeOctetNum(eItems[i].optional, eItems + i, asnArr + asnIdx);
if (ret != BSL_SUCCESS) {
return ret;
}
eItems[i].tag = asnArr[asnIdx].tag;
eItems[i].asn = asnArr + asnIdx; // Shallow copy.
asnIdx--;
}
lastDepth = tItems[i].depth;
}
*asnNum = asnIdx + 1; // Update the number of used ASN buffers
return BSL_SUCCESS;
}
static void EncodeNumber(uint64_t data, uint32_t encodeLen, uint8_t *encode, uint32_t *offset)
{
uint64_t tmp = data;
/* Encode from back to front. */
uint32_t initOff = *offset + encodeLen - 1;
for (uint32_t i = 0; i < encodeLen; i++) {
*(encode + initOff - i) = (uint8_t)tmp;
tmp >>= 8; // one byte = 8 bits
}
*offset += encodeLen;
}
static void EncodeLength(uint8_t lenOctetNum, uint32_t contentOctetNum, uint8_t *encode, uint32_t *offset)
{
if (contentOctetNum <= BSL_ASN1_DEFINITE_MAX_CONTENT_OCTET_NUM) {
*(encode + *offset) = (uint8_t)contentOctetNum;
*offset += 1;
return;
}
// the initial octet
*(encode + *offset) = BSL_ASN1_INDEFINITE_LENGTH | (lenOctetNum - 1);
*offset += 1;
// the subsequent octets
EncodeNumber(contentOctetNum, lenOctetNum - 1, encode, offset);
}
static inline void EncodeBool(bool *data, uint8_t *encode, uint32_t *offset)
{
*(encode + *offset) = *data == true ? 0xFF : 0x00;
*offset += 1;
}
static void EncodeBitString(BSL_ASN1_BitString *data, uint32_t encodeLen, uint8_t *encode, uint32_t *offset)
{
*(encode + *offset) = data->unusedBits;
for (uint32_t i = 0; i < encodeLen - 1; i++) {
*(encode + *offset + i + 1) = *(data->buff + i);
}
// Last octet: Set unused bits to 0
*(encode + *offset + encodeLen - 1) >>= data->unusedBits;
*(encode + *offset + encodeLen - 1) <<= data->unusedBits;
*offset += encodeLen;
}
static void EncodeNum2Ascii(uint8_t *encode, uint32_t *offset, uint8_t encodeLen, uint16_t number)
{
uint16_t tmp = number;
/* Encode from back to front. */
uint32_t initOff = *offset + encodeLen - 1;
for (uint32_t i = 0; i < encodeLen; i++) {
*(encode + initOff - i) = tmp % 10 + '0'; // 10: Take the lowest digit of a decimal number.
tmp /= 10; // 10: Get the number in decimal except for the lowest bit.
}
*offset += encodeLen;
}
static void EncodeTime(BSL_TIME *time, uint8_t tag, uint8_t *encode, uint32_t *offset)
{
if (tag == BSL_ASN1_TAG_UTCTIME) {
EncodeNum2Ascii(encode, offset, 2, time->year % 100); // 2: YY, %100: Get the lower 2 digits of the number
} else {
EncodeNum2Ascii(encode, offset, 4, time->year); // 4: YYYY
}
EncodeNum2Ascii(encode, offset, 2, time->month); // 2: MM
EncodeNum2Ascii(encode, offset, 2, time->day); // 2: DD
EncodeNum2Ascii(encode, offset, 2, time->hour); // 2: HH
EncodeNum2Ascii(encode, offset, 2, time->minute); // 2: MM
EncodeNum2Ascii(encode, offset, 2, time->second); // 2: SS
*(encode + *offset) = 'Z';
*offset += 1;
}
static void EncodeInt(BSL_ASN1_Buffer *asn, uint32_t encodeLen, uint8_t *encode, uint32_t *offset)
{
if (encodeLen < asn->len) {
/* Skip the copying of high-order octets with all zeros. */
(void)memcpy_s(encode + *offset, encodeLen, asn->buff + (asn->len - encodeLen), encodeLen);
} else {
/* the high bit of positive number octet is 1 */
(void)memcpy_s(encode + *offset + (encodeLen - asn->len), asn->len, asn->buff, asn->len);
}
*offset += encodeLen;
}
static void EncodeContent(BSL_ASN1_Buffer *asn, uint32_t encodeLen, uint8_t *encode, uint32_t *offset)
{
switch (asn->tag) {
case BSL_ASN1_TAG_BOOLEAN:
EncodeBool((bool *)asn->buff, encode, offset);
return;
case BSL_ASN1_TAG_INTEGER:
case BSL_ASN1_TAG_ENUMERATED:
EncodeInt(asn, encodeLen, encode, offset);
return;
case BSL_ASN1_TAG_BITSTRING:
EncodeBitString((BSL_ASN1_BitString *)asn->buff, encodeLen, encode, offset);
return;
case BSL_ASN1_TAG_UTCTIME:
case BSL_ASN1_TAG_GENERALIZEDTIME:
EncodeTime((BSL_TIME *)asn->buff, asn->tag, encode, offset);
return;
case BSL_ASN1_TAG_BMPSTRING:
EncodeBMPString(asn->buff, asn->len, encode, offset);
return;
case BSL_ASN1_TAG_T61STRING:
EncodeT61String(asn->buff, asn->len, encode, offset);
return;
default:
(void)memcpy_s(encode + *offset, encodeLen, asn->buff, encodeLen);
*offset += encodeLen;
return;
}
}
static void EncodeItem(BSL_ASN1_EncodeItem *eItems, uint32_t itemNum, uint8_t *encode)
{
uint8_t *temp = encode;
uint32_t offset = 0;
uint32_t contentOctetNum;
for (uint32_t i = 0; i < itemNum; i++) {
if (eItems[i].asnOctetNum == 0) {
continue;
}
contentOctetNum = eItems[i].asnOctetNum - 1 - eItems[i].lenOctetNum;
/* tag */
*(temp + offset) = eItems[i].tag;
offset += 1;
/* length */
EncodeLength(eItems[i].lenOctetNum, contentOctetNum, encode, &offset);
/* content */
if (contentOctetNum != 0 && eItems[i].asn != NULL && eItems[i].asn->len != 0) {
EncodeContent(eItems[i].asn, contentOctetNum, encode, &offset);
}
}
}
static int32_t CheckBslTime(BSL_ASN1_Buffer *asn)
{
if (asn->len != sizeof(BSL_TIME)) {
return BSL_ASN1_ERR_CHECK_TIME;
}
BSL_TIME *time = (BSL_TIME *)asn->buff;
if (BSL_DateTimeCheck(time) == false) {
return BSL_ASN1_ERR_CHECK_TIME;
}
if (asn->tag == BSL_ASN1_TAG_UTCTIME && (time->year < 2000 || time->year > 2049)) { // Utc time range: [2000, 2049]
return BSL_ASN1_ERR_ENCODE_UTC_TIME;
}
if (asn->tag == BSL_ASN1_TAG_GENERALIZEDTIME &&
time->year > 9999) { // 9999: The number of digits for year must be 4.
return BSL_ASN1_ERR_ENCODE_GENERALIZED_TIME;
}
return BSL_SUCCESS;
}
static int32_t CheckBMPString(const BSL_ASN1_Buffer *asn)
{
for (uint32_t i = 0; i < asn->len; i++) {
if (asn->buff[i] > 127) { // max ascii 127.
return BSL_INVALID_ARG;
}
}
return BSL_SUCCESS;
}
static int32_t CheckAsn(BSL_ASN1_Buffer *asn)
{
switch (asn->tag) {
case BSL_ASN1_TAG_BOOLEAN:
return asn->len != sizeof(bool) ? BSL_ASN1_ERR_ENCODE_BOOL : BSL_SUCCESS;
case BSL_ASN1_TAG_BITSTRING:
if (asn->len != sizeof(BSL_ASN1_BitString)) {
return BSL_ASN1_ERR_ENCODE_BIT_STRING;
}
BSL_ASN1_BitString *bs = (BSL_ASN1_BitString *)asn->buff;
return bs->unusedBits > BSL_ASN1_VAL_MAX_BIT_STRING_LEN ? BSL_ASN1_ERR_ENCODE_BIT_STRING : BSL_SUCCESS;
case BSL_ASN1_TAG_UTCTIME:
case BSL_ASN1_TAG_GENERALIZEDTIME:
return CheckBslTime(asn);
case BSL_ASN1_TAG_BMPSTRING:
return CheckBMPString(asn);
default:
return BSL_SUCCESS;
}
}
static int32_t CheckAsnArr(BSL_ASN1_Buffer *asnArr, uint32_t arrNum)
{
int32_t ret;
for (uint32_t i = 0; i < arrNum; i++) {
if (asnArr[i].buff != NULL) {
ret = CheckAsn(asnArr + i);
if (ret != BSL_SUCCESS) {
return ret;
}
}
}
return BSL_SUCCESS;
}
static int32_t EncodeItemInit(BSL_ASN1_EncodeItem *eItems, BSL_ASN1_TemplateItem *tItems, uint32_t itemNum,
BSL_ASN1_Buffer *asnArr, uint32_t *arrNum)
{
int32_t ret = EncodeInitItemFlag(eItems, tItems, itemNum);
if (ret != BSL_SUCCESS) {
return ret;
}
return EncodeInitItemContent(eItems, tItems, itemNum, asnArr, arrNum);
}
static int32_t EncodeInit(BSL_ASN1_EncodeItem *eItems, BSL_ASN1_Template *templ, BSL_ASN1_Buffer *asnArr,
uint32_t arrNum, uint32_t *encodeLen)
{
uint32_t tempArrNum = arrNum;
uint32_t stBegin;
uint32_t stEnd = templ->templNum - 1;
int32_t ret;
uint32_t i = templ->templNum;
while (i-- > 0) {
if (templ->templItems[i].depth > BSL_ASN1_MAX_TEMPLATE_DEPTH) {
return BSL_ASN1_ERR_MAX_DEPTH;
}
if (templ->templItems[i].depth != 0) {
continue;
}
stBegin = i;
ret = EncodeItemInit(eItems + stBegin, templ->templItems + stBegin, stEnd - stBegin + 1, asnArr, &tempArrNum);
if (ret != BSL_SUCCESS) {
return ret;
}
if ((eItems + stBegin)->asnOctetNum > UINT32_MAX - *encodeLen) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
*encodeLen += (eItems + stBegin)->asnOctetNum;
stEnd = i - 1;
}
if (tempArrNum != 0) { // Check whether all the asn-item has been used.
return BSL_ASN1_ERR_ENCODE_ASN_TOO_MUCH;
}
return BSL_SUCCESS;
}
int32_t BSL_ASN1_EncodeTemplate(BSL_ASN1_Template *templ, BSL_ASN1_Buffer *asnArr, uint32_t arrNum, uint8_t **encode,
uint32_t *encLen)
{
if (IsInvalidTempl(templ) || IsInvalidAsns(asnArr, arrNum) || encode == NULL || *encode != NULL || encLen == NULL) {
return BSL_INVALID_ARG;
}
int32_t ret = CheckAsnArr(asnArr, arrNum);
if (ret != BSL_SUCCESS) {
return ret;
}
BSL_ASN1_EncodeItem *eItems = (BSL_ASN1_EncodeItem *)BSL_SAL_Calloc(templ->templNum, sizeof(BSL_ASN1_EncodeItem));
if (eItems == NULL) {
return BSL_MALLOC_FAIL;
}
uint32_t encodeLen = 0;
ret = EncodeInit(eItems, templ, asnArr, arrNum, &encodeLen);
if (ret != BSL_SUCCESS) {
BSL_SAL_Free(eItems);
return ret;
}
*encode = (uint8_t *)BSL_SAL_Calloc(1, encodeLen);
if (*encode == NULL) {
BSL_SAL_Free(eItems);
return BSL_MALLOC_FAIL;
}
EncodeItem(eItems, templ->templNum, *encode);
*encLen = encodeLen;
BSL_SAL_Free(eItems);
return BSL_SUCCESS;
}
int32_t BSL_ASN1_EncodeListItem(uint8_t tag, uint32_t listSize, BSL_ASN1_Template *templ, BSL_ASN1_Buffer *asnArr,
uint32_t arrNum, BSL_ASN1_Buffer *out)
{
if ((tag != BSL_ASN1_TAG_SEQUENCE && tag != BSL_ASN1_TAG_SET) || IsInvalidTempl(templ) ||
IsInvalidAsns(asnArr, arrNum) || listSize == 0 || arrNum % listSize != 0 || out == NULL || out->buff != NULL) {
return BSL_INVALID_ARG;
}
int32_t ret = CheckAsnArr(asnArr, arrNum);
if (ret != BSL_SUCCESS) {
return ret;
}
if (listSize > UINT32_MAX / templ->templNum) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
BSL_ASN1_EncodeItem *eItems =
(BSL_ASN1_EncodeItem *)BSL_SAL_Calloc(templ->templNum * listSize, sizeof(BSL_ASN1_EncodeItem));
if (eItems == NULL) {
return BSL_MALLOC_FAIL;
}
uint32_t encodeLen = 0;
uint32_t itemAsnNum;
for (uint32_t i = 0; i < listSize; i++) {
itemAsnNum = arrNum / listSize;
ret = EncodeItemInit(
eItems + i * templ->templNum, templ->templItems, templ->templNum, asnArr + i * itemAsnNum, &itemAsnNum);
if (ret != BSL_SUCCESS) {
BSL_SAL_Free(eItems);
return ret;
}
if (itemAsnNum != 0) {
BSL_SAL_Free(eItems);
return BSL_ASN1_ERR_ENCODE_ASN_TOO_MUCH;
}
if (eItems[i * templ->templNum].asnOctetNum > UINT32_MAX - encodeLen) {
BSL_SAL_Free(eItems);
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
encodeLen += eItems[i * templ->templNum].asnOctetNum;
}
out->buff = (uint8_t *)BSL_SAL_Calloc(1, encodeLen);
if (out->buff == NULL) {
BSL_SAL_Free(eItems);
return BSL_MALLOC_FAIL;
}
uint8_t *encode = out->buff;
for (uint32_t i = 0; i < listSize; i++) {
EncodeItem(eItems + i * templ->templNum, templ->templNum, encode);
encode += (eItems + i * templ->templNum)->asnOctetNum;
}
out->tag = tag | BSL_ASN1_TAG_CONSTRUCTED;
out->len = encodeLen;
BSL_SAL_Free(eItems);
return BSL_SUCCESS;
}
int32_t BSL_ASN1_EncodeLimb(uint8_t tag, uint64_t limb, BSL_ASN1_Buffer *asn)
{
if ((tag != BSL_ASN1_TAG_INTEGER && tag != BSL_ASN1_TAG_ENUMERATED) || asn == NULL || asn->buff != NULL) {
return BSL_INVALID_ARG;
}
asn->tag = tag;
asn->len = limb == 0 ? 1 : GetOctetNumOfUint(limb);
asn->buff = (uint8_t *)BSL_SAL_Calloc(1, asn->len);
if (asn->buff == NULL) {
return BSL_MALLOC_FAIL;
}
if (limb == 0) {
return BSL_SUCCESS;
}
uint32_t offset = 0;
EncodeNumber(limb, asn->len, asn->buff, &offset);
return BSL_SUCCESS;
}
int32_t BSL_ASN1_GetEncodeLen(uint32_t contentLen, uint32_t *encodeLen)
{
if (encodeLen == NULL) {
return BSL_NULL_INPUT;
}
uint8_t lenOctetNum = GetLenOctetNum(contentLen);
if (contentLen > (UINT32_MAX - lenOctetNum - 1)) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
*encodeLen = 1 + lenOctetNum + contentLen;
return BSL_SUCCESS;
}
| 2401_83913325/openHiTLS_1 | bsl/asn1/src/bsl_asn1.c | C | unknown | 44,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.
*/
#ifndef BSL_ASN1_LOCAL_H
#define BSL_ASN1_LOCAL_H
#include <stdint.h>
#include <stdlib.h>
#include "bsl_asn1_internal.h"
#ifdef __cplusplus
extern "C" {
#endif
#define BSL_ASN1_VAL_MAX_BIT_STRING_LEN 7
#define BSL_ASN1_MAX_LIST_NEST_EPTH 2
#define BSL_ASN1_FLAG_OPTIONAL_DEFAUL (BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_DEFAULT)
/* Gets the mask of the class */
#define BSL_ASN1_CLASS_MASK 0xC0
typedef struct _ASN1_AnyOrChoiceParam {
uint32_t idx;
void *previousAsnOrTag;
BSL_ASN1_DecTemplCallBack tagCb;
} BSL_ASN1_AnyOrChoiceParam;
typedef struct _BSL_ASN1_EncodeItem {
uint32_t asnOctetNum; // tag + len + content
BSL_ASN1_Buffer *asn;
uint8_t tag;
uint8_t depth;
uint8_t skip; // Whether to skip processing template item
uint8_t optional;
uint8_t lenOctetNum; // The maximum number of the length octets is 126 + 1
} BSL_ASN1_EncodeItem;
#ifdef __cplusplus
}
#endif
#endif // BSL_ASN1_LOCAL_H
| 2401_83913325/openHiTLS_1 | bsl/asn1/src/bsl_asn1_local.h | C | unknown | 1,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.
*/
#ifndef BSL_BASE64_INTERNAL_H
#define BSL_BASE64_INTERNAL_H
#include "hitls_build.h"
#ifdef HITLS_BSL_BASE64
#include "bsl_base64.h"
#ifdef __cplusplus
extern "C" {
#endif
struct BASE64_ControlBlock {
/* size of the unencoded block in the current buffer */
uint32_t num;
/*
* Size of the block for internal encoding and decoding.
* The size of the coding block is set to 48, and the size of the decoding block is set to 64.
*/
uint32_t length;
/* see BSL_BASE64_FLAGS*, for example: BSL_BASE64_FLAGS_NO_NEWLINE, means process without '\n' */
uint32_t flags;
uint32_t paddingCnt;
/* codec buffer */
uint8_t buf[HITLS_BASE64_CTX_BUF_LENGTH];
};
#define BASE64_ENCODE_BYTES 3 // encode 3 bytes at a time
#define BASE64_DECODE_BYTES 4 // decode 4 bytes at a time
#define BASE64_BLOCK_SIZE 1024
#define BASE64_PAD_MAX 2
#define BASE64_DECODE_BLOCKSIZE 64
#define BASE64_CTX_BUF_SIZE HITLS_BASE64_ENCODE_LENGTH(BASE64_BLOCK_SIZE) + 10
#define BSL_BASE64_ENC_ENOUGH_LEN(len) (((len) + 2) / 3 * 4 + 1)
#define BSL_BASE64_DEC_ENOUGH_LEN(len) (((len) + 3) / 4 * 3)
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* HITLS_BSL_BASE64 */
#endif /* conditional include */ | 2401_83913325/openHiTLS_1 | bsl/base64/include/bsl_base64_internal.h | C | unknown | 1,765 |
/*
* 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_BSL_BASE64
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "securec.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "bsl_base64_internal.h"
#include "bsl_base64.h"
/* BASE64 mapping table */
static const uint8_t BASE64_DECODE_MAP_TABLE[] = {
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 64U, 67U, 67U, 64U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 64U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 62U, 67U, 66U,
67U, 63U, 52U, 53U, 54U, 55U, 56U, 57U, 58U, 59U, 60U, 61U, 67U, 67U, 67U, 65U, 67U, 67U, 67U, 0U, 1U, 2U, 3U,
4U, 5U, 6U, 7U, 8U, 9U, 10U, 11U, 12U, 13U, 14U, 15U, 16U, 17U, 18U, 19U, 20U, 21U, 22U, 23U, 24U, 25U, 67U,
67U, 67U, 67U, 67U, 67U, 26U, 27U, 28U, 29U, 30U, 31U, 32U, 33U, 34U, 35U, 36U, 37U, 38U, 39U, 40U, 41U, 42U, 43U,
44U, 45U, 46U, 47U, 48U, 49U, 50U, 51U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U};
BSL_Base64Ctx *BSL_BASE64_CtxNew(void)
{
return BSL_SAL_Malloc(sizeof(BSL_Base64Ctx));
}
void BSL_BASE64_CtxFree(BSL_Base64Ctx *ctx)
{
BSL_SAL_FREE(ctx);
}
void BSL_BASE64_CtxClear(BSL_Base64Ctx *ctx)
{
BSL_SAL_CleanseData(ctx, (uint32_t)sizeof(BSL_Base64Ctx));
}
static int32_t BslBase64EncodeParamsValidate(const uint8_t *srcBuf, const uint32_t srcBufLen,
const char *dstBuf, uint32_t *dstBufLen)
{
if (srcBuf == NULL || srcBufLen == 0U || dstBuf == NULL || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
/* The length of dstBuf of the user must be at least (srcBufLen+2)/3*4+1 */
if (*dstBufLen < BSL_BASE64_ENC_ENOUGH_LEN(srcBufLen)) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
return BSL_SUCCESS;
}
static void BslBase64ArithEncodeProc(const uint8_t *srcBuf, const uint32_t srcBufLen,
char *dstBuf, uint32_t *dstBufLen)
{
/* base64-encoding mapping table */
static const char *base64Letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
uint32_t dstIdx = 0U;
const uint8_t *tmpBuf = srcBuf;
uint32_t tmpLen;
/* @alias Encode characters based on the BASE64 encoding rule. */
for (tmpLen = srcBufLen; tmpLen > 2U; tmpLen -= 3U) {
dstBuf[dstIdx] = base64Letter[(tmpBuf[0] >> 2U) & 0x3FU];
dstIdx++;
dstBuf[dstIdx] = base64Letter[((tmpBuf[0] & 0x3U) << 4U) | ((tmpBuf[1U] & 0xF0U) >> 4U)];
dstIdx++;
dstBuf[dstIdx] = base64Letter[((tmpBuf[1U] & 0x0FU) << 2U) | ((tmpBuf[2U] & 0xC0U) >> 6U)];
dstIdx++;
dstBuf[dstIdx] = base64Letter[tmpBuf[2U] & 0x3FU];
dstIdx++;
tmpBuf = &tmpBuf[3U];
}
/* Handle the case where the remaining length is not 0. */
if (tmpLen > 0U) {
/* Padded the first byte. */
dstBuf[dstIdx] = base64Letter[(tmpBuf[0] >> 2U) & 0x3FU];
dstIdx++;
if (tmpLen == 1U) {
/* Process the case where the remaining length is 1. */
dstBuf[dstIdx] = base64Letter[((tmpBuf[0U] & 0x3U) << 4U)];
dstIdx++;
dstBuf[dstIdx] = '=';
dstIdx++;
} else {
/* Process the case where the remaining length is 2. */
dstBuf[dstIdx] = base64Letter[((tmpBuf[0U] & 0x3U) << 4U) | ((tmpBuf[1U] & 0xF0U) >> 4U)];
dstIdx++;
dstBuf[dstIdx] = base64Letter[((tmpBuf[1U] & 0x0Fu) << 2U)];
dstIdx++;
}
/* Fill the last '='. */
dstBuf[dstIdx++] = '=';
}
/* Fill terminator. */
dstBuf[dstIdx] = '\0';
*dstBufLen = dstIdx;
}
/* Encode the entire ctx->buf, 48 characters in total, and return the number of decoded characters. */
static void BslBase64EncodeBlock(BSL_Base64Ctx *ctx, const uint8_t **srcBuf, uint32_t *srcBufLen,
char **dstBuf, uint32_t *dstBufLen, uint32_t remainLen)
{
uint32_t tmpOutLen = 0;
uint32_t offset = 0;
BslBase64ArithEncodeProc(*srcBuf, ctx->length, *dstBuf, &tmpOutLen);
ctx->num = 0;
offset = ((remainLen == 0) ? (ctx->length) : remainLen);
*srcBuf += offset;
*srcBufLen -= offset;
*dstBufLen += tmpOutLen;
*dstBuf += tmpOutLen;
if ((ctx->flags & BSL_BASE64_FLAGS_NO_NEWLINE) == 0) {
*(*dstBuf) = '\n';
(*dstBuf)++;
(*dstBufLen)++;
}
*(*dstBuf) = '\0';
}
static void BslBase64EncodeProcess(BSL_Base64Ctx *ctx, const uint8_t **srcBuf, uint32_t *srcBufLen,
char *dstBuf, uint32_t *dstBufLen)
{
uint32_t remainLen = 0;
const uint8_t *bufTmp = &(ctx->buf[0]);
char *dstBufTmp = dstBuf;
if (ctx->num != 0) {
remainLen = ctx->length - ctx->num;
(void)memcpy_s(&(ctx->buf[ctx->num]), remainLen, *srcBuf, remainLen);
BslBase64EncodeBlock(ctx, &bufTmp, srcBufLen, &dstBufTmp, dstBufLen, remainLen);
*srcBuf += remainLen;
remainLen = 0;
}
const uint8_t *srcBufTmp = *srcBuf;
/* Encoding every 48 characters. */
while (*srcBufLen >= ctx->length) {
BslBase64EncodeBlock(ctx, &srcBufTmp, srcBufLen, &dstBufTmp, dstBufLen, remainLen);
}
*srcBuf = srcBufTmp;
}
static int32_t BslBase64DecodeCheck(const char src, uint32_t *paddingCnt)
{
uint32_t padding = 0;
/* 66U is the header identifier '-' (invalid), and 66U or above are invalid characters beyond the range. */
if (BASE64_DECODE_MAP_TABLE[(uint8_t)src] == 66U) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_HEADER);
return BSL_BASE64_HEADER;
}
if (BASE64_DECODE_MAP_TABLE[(uint8_t)src] > 66U) {
BSL_ERR_PUSH_ERROR(BSL_INVALID_ARG);
return BSL_INVALID_ARG;
}
/* 65U is the padding character '=' and also EOF identifier. */
if (BASE64_DECODE_MAP_TABLE[(uint8_t)src] == 65U) {
if (*paddingCnt < BASE64_PAD_MAX) {
padding++;
} else { /* paddingCnt > 2 */
BSL_ERR_PUSH_ERROR(BSL_BASE64_INVALID);
return BSL_BASE64_INVALID;
}
}
/* illegal behavior: data after padding. */
if (*paddingCnt > 0 && BASE64_DECODE_MAP_TABLE[(uint8_t)src] < 64U) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_DATA_AFTER_PADDING);
return BSL_BASE64_DATA_AFTER_PADDING;
}
*paddingCnt += padding;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_Encode(const uint8_t *srcBuf, const uint32_t srcBufLen, char *dstBuf, uint32_t *dstBufLen)
{
int32_t ret = BslBase64EncodeParamsValidate(srcBuf, srcBufLen, (const char *)dstBuf, dstBufLen);
if (ret != BSL_SUCCESS) {
return ret;
}
BslBase64ArithEncodeProc(srcBuf, srcBufLen, dstBuf, dstBufLen); /* executes the encoding algorithm */
return BSL_SUCCESS;
}
static void BslBase64DecodeRemoveBlank(const uint8_t *buf, const uint32_t bufLen, uint8_t *destBuf, uint32_t *destLen)
{
uint32_t fast = 0;
uint32_t slow = 0;
for (; fast < bufLen; fast++) {
if (BASE64_DECODE_MAP_TABLE[buf[fast]] != 64U) { /* when the character is not ' ' or '\r', '\n' */
destBuf[slow++] = buf[fast];
}
}
*destLen = slow;
}
static int32_t BslBase64DecodeCheckAndRmvEqualSign(uint8_t *buf, uint32_t *bufLen)
{
int32_t ret = BSL_SUCCESS;
uint32_t i = 0;
bool hasEqualSign = false;
uint32_t len = *bufLen;
for (; i < len; i++) {
/* Check whether the characters are invalid characters in the Base64 mapping table. */
if (BASE64_DECODE_MAP_TABLE[buf[i]] > 65U) {
/* 66U is the status code of invalid characters. */
return BSL_BASE64_INVALID_CHARACTER;
}
/* Process the '=' */
if (BASE64_DECODE_MAP_TABLE[buf[i]] == 65U) {
hasEqualSign = true;
/* 65U is the status code with the '=' */
if (i == len - 1) {
break;
} else if (i == len - BASE64_PAD_MAX) {
ret = (buf[i + 1] == '=') ? BSL_SUCCESS : BSL_BASE64_INVALID_CHARACTER;
buf[i + 1] = '\0';
break;
} else {
return BSL_BASE64_INVALID_CHARACTER;
}
}
}
if (ret == BSL_SUCCESS) {
if (hasEqualSign == true) {
buf[i] = '\0';
}
*bufLen = i;
}
return ret;
}
static int32_t BslBase64Normalization(const char *srcBuf, const uint32_t srcBufLen, uint8_t *filterBuf,
uint32_t *filterBufLen)
{
(void)memset_s(filterBuf, *filterBufLen, 0, *filterBufLen);
BslBase64DecodeRemoveBlank((const uint8_t *)srcBuf, srcBufLen, filterBuf, filterBufLen);
if (*filterBufLen == 0 || ((*filterBufLen) % BASE64_DECODE_BYTES != 0)) {
return BSL_BASE64_INVALID_ENCODE;
}
return BslBase64DecodeCheckAndRmvEqualSign(filterBuf, filterBufLen);
}
/* can ensure that dstBuf and dstBufLen are sufficient and that srcBuf does not contain invalid characters */
static int32_t BslBase64DecodeBuffer(const uint8_t *srcBuf, const uint32_t srcBufLen, uint8_t *dstBuf,
uint32_t *dstBufLen)
{
uint32_t idx = 0U;
uint32_t tmpLen;
const uint8_t *tmp = srcBuf;
for (tmpLen = srcBufLen; tmpLen > 4U; tmpLen -= 4U) {
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[0U]] << 2U) | (BASE64_DECODE_MAP_TABLE[tmp[1U]] >> 4U);
idx++;
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[1U]] << 4U) | (BASE64_DECODE_MAP_TABLE[tmp[2U]] >> 2U);
idx++;
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[2U]] << 6U) | BASE64_DECODE_MAP_TABLE[tmp[3U]];
idx++;
tmp = &tmp[4U];
}
/* processing of less than four characters */
if (tmpLen > 1U) {
/* process the case of one character */
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[0U]] << 2U) | (BASE64_DECODE_MAP_TABLE[tmp[1U]] >> 4U);
idx++;
}
if (tmpLen > 2U) {
/* process the case of two characters */
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[1U]] << 4U) | (BASE64_DECODE_MAP_TABLE[tmp[2U]] >> 2U);
idx++;
}
if (tmpLen > 3U) {
/* process the case of three characters */
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[2U]] << 6U) | BASE64_DECODE_MAP_TABLE[tmp[3U]];
idx++;
}
*dstBufLen = idx;
return BSL_SUCCESS;
}
static int32_t BslBase64ArithDecodeProc(const char *srcBuf, const uint32_t srcBufLen, uint8_t *dstBuf,
uint32_t *dstBufLen)
{
uint8_t *buf = NULL;
uint32_t bufLen; /* length to be decoded after redundant characters are deleted */
int32_t ret;
buf = BSL_SAL_Malloc((uint32_t)srcBufLen);
if (buf == NULL) {
return BSL_MALLOC_FAIL;
}
bufLen = srcBufLen;
/* Delete the extra white space characters (\r\n, space, '=') */
ret = BslBase64Normalization(srcBuf, (const uint32_t)srcBufLen, buf, &bufLen);
if (ret != BSL_SUCCESS) {
BSL_SAL_FREE(buf);
return ret;
}
/* Decode the base64 character string. */
ret = BslBase64DecodeBuffer(buf, (const uint32_t)bufLen, dstBuf, dstBufLen);
if (ret != BSL_SUCCESS) {
BSL_SAL_FREE(buf);
return ret;
}
BSL_SAL_FREE(buf);
return BSL_SUCCESS;
}
/* Ensure that dstBuf and dstBufLen are correctly created. */
int32_t BSL_BASE64_Decode(const char *srcBuf, const uint32_t srcBufLen, uint8_t *dstBuf, uint32_t *dstBufLen)
{
int32_t ret;
/* An error is returned when a parameter is abnormal. */
if (srcBuf == NULL || dstBuf == NULL || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
/* The length of dstBuf of the user must be at least (srcBufLen+3)/4*3. */
if (*dstBufLen < BSL_BASE64_DEC_ENOUGH_LEN(srcBufLen)) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
ret = BslBase64ArithDecodeProc(srcBuf, srcBufLen, dstBuf, dstBufLen); /* start decoding */
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t BSL_BASE64_EncodeInit(BSL_Base64Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
ctx->length = HITLS_BASE64_CTX_LENGTH;
ctx->num = 0;
ctx->flags = 0;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_EncodeUpdate(BSL_Base64Ctx *ctx, const uint8_t *srcBuf, uint32_t srcBufLen,
char *dstBuf, uint32_t *dstBufLen)
{
/* ensure the validity of dstBuf */
if (ctx == NULL || srcBuf == NULL || dstBuf == NULL || srcBufLen == 0 || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (ctx->length != HITLS_BASE64_CTX_LENGTH) {
BSL_ERR_PUSH_ERROR(BSL_INVALID_ARG);
return BSL_INVALID_ARG;
}
/* By default, the user selects the line feed, considers the terminator,
and checks whether the length meets the (srcBufLen + ctx->num)/48*65+1 requirement. */
if (*dstBufLen < ((srcBufLen + ctx->num) / HITLS_BASE64_CTX_LENGTH * (BASE64_DECODE_BLOCKSIZE + 1) + 1)) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
*dstBufLen = 0;
/* If srcBuf is too short for a buf, store it in the buf first. */
if (srcBufLen < ctx->length - ctx->num) {
(void)memcpy_s(&(ctx->buf[ctx->num]), srcBufLen, srcBuf, srcBufLen);
ctx->num += srcBufLen;
return BSL_SUCCESS;
}
BslBase64EncodeProcess(ctx, &srcBuf, &srcBufLen, dstBuf, dstBufLen);
/* If the remaining bytes are less than 48 bytes, store the bytes in the buf and wait for next processing. */
if (srcBufLen != 0) {
/* Ensure that srcBufLen < 48 */
(void)memcpy_s(&(ctx->buf[0]), srcBufLen, srcBuf, srcBufLen);
}
ctx->num = srcBufLen;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_EncodeFinal(BSL_Base64Ctx *ctx, char *dstBuf, uint32_t *dstBufLen)
{
uint32_t tmpDstLen = 0;
if (ctx == NULL || dstBuf == NULL || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (ctx->num == 0) {
*dstBufLen = 0;
return BSL_SUCCESS;
}
if (*dstBufLen < BSL_BASE64_ENC_ENOUGH_LEN((ctx->num))) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
BslBase64ArithEncodeProc((const uint8_t *)ctx->buf, ctx->num, dstBuf, &tmpDstLen);
if ((ctx->flags & BSL_BASE64_FLAGS_NO_NEWLINE) == 0) {
dstBuf[tmpDstLen++] = '\n';
}
dstBuf[tmpDstLen] = '\0';
*dstBufLen = tmpDstLen;
ctx->num = 0;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_DecodeInit(BSL_Base64Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
ctx->num = 0;
ctx->length = 0;
ctx->flags = 0;
ctx->paddingCnt = 0;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_DecodeUpdate(BSL_Base64Ctx *ctx, const char *srcBuf, const uint32_t srcBufLen,
uint8_t *dstBuf, uint32_t *dstBufLen)
{
if (ctx == NULL || srcBuf == NULL || dstBuf == NULL || srcBufLen == 0 || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
/* Estimated maximum value. By default, the input srcBuf is without line feed. Each line contains 64 characters.
Check whether the length meets the (srcBufLen + ctx->num)/64*48 requirement. */
if (*dstBufLen < ((srcBufLen + ctx->num) / BASE64_DECODE_BLOCKSIZE * HITLS_BASE64_CTX_LENGTH)) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
uint32_t num = ctx->num;
uint32_t totalLen = 0;
uint32_t decodeLen = 0;
uint8_t *tmpBuf = ctx->buf;
int32_t ret = BSL_SUCCESS;
uint8_t *dstTmp = dstBuf;
for (uint32_t i = 0U; i < srcBufLen; i++) {
ret = BslBase64DecodeCheck(srcBuf[i], &ctx->paddingCnt);
if (ret != BSL_SUCCESS) {
*dstBufLen = 0;
if (ret == BSL_BASE64_HEADER) {
*dstBufLen = totalLen;
}
return ret;
}
if (BASE64_DECODE_MAP_TABLE[(uint8_t)srcBuf[i]] < 64U) { /* 0U ~ 63U are valid characters */
/* If num >= 64, it indicates that someone has modified the ctx.
If this happens, refuse to write any more data. */
if (num >= BASE64_DECODE_BLOCKSIZE) {
*dstBufLen = 0;
ctx->num = num;
BSL_ERR_PUSH_ERROR(BSL_BASE64_ILLEGALLY_MODIFIED);
return BSL_BASE64_ILLEGALLY_MODIFIED;
}
tmpBuf[num++] = (uint8_t)srcBuf[i]; /* save valid base64 characters */
}
/* A round of block decoding is performed every time the num reaches 64, and then the buf is cleared. */
if (num == BASE64_DECODE_BLOCKSIZE) {
ret = BslBase64DecodeBuffer(tmpBuf, num, dstTmp, &decodeLen);
if (ret != BSL_SUCCESS) {
*dstBufLen = 0;
ctx->num = 0;
BSL_ERR_PUSH_ERROR(BSL_BASE64_DECODE_FAILED);
return BSL_BASE64_DECODE_FAILED;
}
num = 0;
totalLen += decodeLen;
dstTmp += decodeLen;
}
}
*dstBufLen = totalLen;
ctx->num = num;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_DecodeFinal(BSL_Base64Ctx *ctx, uint8_t *dstBuf, uint32_t *dstBufLen)
{
int32_t ret = BSL_SUCCESS;
uint32_t totalLen = 0;
if (ctx == NULL || dstBuf == NULL || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (ctx->num == 0) {
*dstBufLen = 0;
return ret;
}
if (*dstBufLen < BSL_BASE64_DEC_ENOUGH_LEN((ctx->num))) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
ret = BslBase64DecodeBuffer((const uint8_t *)ctx->buf, ctx->num, dstBuf, &totalLen);
ctx->num = 0;
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_DECODE_FAILED);
return BSL_BASE64_DECODE_FAILED;
}
*dstBufLen = totalLen;
return ret;
}
int32_t BSL_BASE64_SetFlags(BSL_Base64Ctx *ctx, uint32_t flags)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
ctx->flags |= flags;
return BSL_SUCCESS;
}
#endif /* HITLS_BSL_BASE64 */
| 2401_83913325/openHiTLS_1 | bsl/base64/src/bsl_base64.c | C | unknown | 19,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 BSL_BUFFER_H
#define BSL_BUFFER_H
#include "hitls_build.h"
#ifdef HITLS_BSL_BUFFER
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
size_t length;
char *data;
size_t max;
} BSL_BufMem;
BSL_BufMem *BSL_BufMemNew(void);
void BSL_BufMemFree(BSL_BufMem *a);
size_t BSL_BufMemGrowClean(BSL_BufMem *str, size_t len);
#ifdef __cplusplus
}
#endif
#endif
#endif | 2401_83913325/openHiTLS_1 | bsl/buffer/include/bsl_buffer.h | C | unknown | 950 |
/*
* 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_BSL_BUFFER
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_buffer.h"
BSL_BufMem *BSL_BufMemNew(void)
{
BSL_BufMem *ret = NULL;
ret = (BSL_BufMem *)BSL_SAL_Malloc(sizeof(BSL_BufMem));
if (ret == NULL) {
return NULL;
}
ret->length = 0;
ret->max = 0;
ret->data = NULL;
return ret;
}
void BSL_BufMemFree(BSL_BufMem *a)
{
if (a == NULL) {
return;
}
if (a->data != NULL) {
BSL_SAL_FREE(a->data);
}
BSL_SAL_FREE(a);
}
size_t BSL_BufMemGrowClean(BSL_BufMem *str, size_t len)
{
char *ret = NULL;
if (str->length >= len) {
if (memset_s(&(str->data[len]), str->max - len, 0, str->length - len) != EOK) {
return 0;
}
str->length = len;
return len;
}
if (str->max >= len) {
if (memset_s(&(str->data[str->length]), str->max - str->length, 0, len - str->length) != EOK) {
return 0;
}
str->length = len;
return len;
}
const size_t n = ((len + 3) / 3) * 4; // actual growth size
if (n < len || n > UINT32_MAX) { // does not meet growth requirements or overflows
return 0;
}
ret = BSL_SAL_Malloc((uint32_t)n);
if (ret == NULL) {
return 0;
}
if (str->data != NULL && memcpy_s(ret, n, str->data, str->max) != EOK) {
BSL_SAL_FREE(ret);
return 0;
}
if (memset_s(&ret[str->length], n - str->length, 0, len - str->length) != EOK) {
BSL_SAL_FREE(ret);
return 0;
}
BSL_SAL_CleanseData(str->data, (uint32_t)str->max);
BSL_SAL_FREE(str->data);
str->data = ret;
str->max = n;
str->length = len;
return len;
}
#endif | 2401_83913325/openHiTLS_1 | bsl/buffer/src/bsl_buffer.c | C | unknown | 2,300 |
/*
* 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 BSL_CONF_H
#define BSL_CONF_H
#include "hitls_build.h"
#ifdef HITLS_BSL_CONF
#include "bsl_conf_def.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct BSL_CONF_Struct {
const BSL_CONF_Method *meth;
void *data;
} BSL_CONF;
/**
* @ingroup bsl
*
* @brief Retrieves the default configuration management methods structure
*
* @return const BSL_CONF_Method* a pointer to the static structure containing the default methods
*
* @details
* The structure includes the following default methods:
* - `DefaultCreate`: Creates a new configuration object
* - `DefaultDestroy`: Destroys an existing configuration object
* - `DefaultLoad`: Loads configuration data from a file
* - `DefaultLoadUio`: Loads configuration data from a UIO interface
* - `DefaultDump`: Dumps configuration data to a file
* - `DefaultDumpUio`: Dumps configuration data to a UIO interface
* - `DefaultGetSectionNode`: Retrieves a specific section node from the configuration
* - `DefaultGetString`: Retrieves a string value from the configuration
* - `DefaultGetNumber`: Retrieves a numeric value from the configuration
* - `DefaultGetSectionNames`: Retrieves the names of all sections in the configuration
*
*/
const BSL_CONF_Method *BSL_CONF_DefaultMethod(void);
/**
* @ingroup bsl
*
* @brief Create a new configuration object.
*
* @param meth [IN] Method structure defining the behavior of the configuration object
*
* @retval The configuration object is created successfully.
* @retval NULL Failed to create the configuration.
*/
BSL_CONF *BSL_CONF_New(const BSL_CONF_Method *meth);
/**
* @ingroup bsl
*
* @brief Free a configuration object.
*
* @param conf [IN] Configuration object to be freed
*/
void BSL_CONF_Free(BSL_CONF *conf);
/**
* @ingroup bsl
*
* @brief Load configuration information from a UIO object into the configuration object.
*
* @param conf [IN] Configuration object
* @param uio [IN] UIO object
*
* @retval BSL_SUCCESS Configuration loaded successfully.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf or uio is NULL).
* @retval BSL_CONF_LOAD_FAIL Failed to load configuration (e.g., loadUio method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_LoadByUIO(BSL_CONF *conf, BSL_UIO *uio);
/**
* @ingroup bsl
*
* @brief Load configuration information from a file into the configuration object.
*
* @param conf [IN] Configuration object
* @param file [IN] Configuration file path
*
* @retval BSL_SUCCESS Configuration loaded successfully.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf or file is NULL).
* @retval BSL_CONF_LOAD_FAIL Failed to load configuration (e.g., load method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_Load(BSL_CONF *conf, const char *file);
/**
* @ingroup bsl
*
* @brief Get a specific section from the configuration object.
*
* @param conf [IN] Configuration object
* @param section [IN] Section name to retrieve
*
* @retval BSL_LIST* a pointer to Section retrieved successfully.
* @retval NULL Failed to Get Section.
*/
BslList *BSL_CONF_GetSection(const BSL_CONF *conf, const char *section);
/**
* @ingroup bsl
*
* @brief Get a string value from the configuration object based on the specified section and name.
*
* @param conf [IN] Configuration object
* @param section [IN] Section name in the configuration
* @param name [IN] Name of the configuration item
* @param str [OUT] Buffer to store the retrieved string
* @param strLen [IN|OUT] Length of the buffer
*
* @retval BSL_SUCCESS String retrieved successfully.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf, section, name, str, or strLen is NULL).
* @retval BSL_CONF_GET_FAIL Failed to retrieve the string (e.g., getString method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_GetString(const BSL_CONF *conf, const char *section, const char *name, char *str, uint32_t *strLen);
/**
* @ingroup bsl
*
* @brief Get a numeric value from the configuration object based on the specified section and name.
*
* @param conf [IN] Configuration object
* @param section [IN] Section name in the configuration
* @param name [IN] Name of the configuration item
* @param value [OUT] Pointer to store the retrieved numeric value
*
* @retval BSL_SUCCESS Numeric value retrieved successfully.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf, section, name, or value is NULL).
* @retval BSL_CONF_GET_FAIL Failed to retrieve the numeric value (e.g., getNumber method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_GetNumber(const BSL_CONF *conf, const char *section, const char *name, long *value);
/**
* @ingroup bsl
*
* @brief Save the configuration object's contents to a specified file.
*
* @param conf [IN] Configuration object
* @param file [IN] File path to save the configuration
*
* @retval BSL_SUCCESS Configuration successfully saved to the file.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf or file is NULL).
* @retval BSL_CONF_DUMP_FAIL Failed to save the configuration (e.g., dump method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_Dump(const BSL_CONF *conf, const char *file);
/**
* @ingroup bsl
*
* @brief Save the configuration object's contents to a specified UIO object.
*
* @param conf [IN] Configuration object
* @param uio [IN] UIO object to save the configuration
*
* @retval BSL_SUCCESS Configuration successfully saved to the UIO.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf or uio is NULL).
* @retval BSL_CONF_DUMP_FAIL Failed to save the configuration (e.g., dumpUio method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_DumpUio(const BSL_CONF *conf, BSL_UIO *uio);
/**
* @ingroup bsl
*
* @brief Get the names of all sections from the configuration object.
*
* @param conf [IN] Configuration object
* @param namesSize [OUT] Pointer to store the size of the returned array
*
* @retval BSL_SUCCESS Successfully retrieved section names.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf or namesSize is NULL).
* @retval BSL_CONF_GET_FAIL Failed to retrieve section names (e.g., getSectionNames method is missing or fails).
* @retval char ** a pointer to the section names array, which is retrieved successfully.
* @retval NULL failed to get section names.
*/
char **BSL_CONF_GetSectionNames(const BSL_CONF *conf, uint32_t *namesSize);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_CONF */
#endif /* BSL_CONF_H */
| 2401_83913325/openHiTLS_1 | bsl/conf/include/bsl_conf.h | C | unknown | 7,124 |
/*
* 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 BSL_CONF_DEF_H
#define BSL_CONF_DEF_H
#include "hitls_build.h"
#ifdef HITLS_BSL_CONF
#include <stdint.h>
#include "bsl_uio.h"
#include "bsl_list.h"
#ifdef __cplusplus
extern "C" {
#endif
#define BSL_CONF_LINE_SIZE 513
#define BSL_CONF_SEC_SIZE 510
typedef struct BslConfDefaultKeyValue {
char *key;
char *value;
uint32_t keyLen;
uint32_t valueLen;
} BSL_CONF_KeyValue;
typedef struct BslConfDefaultSection {
BslList *keyValueList;
char *section;
uint32_t sectionLen;
} BSL_CONF_Section;
/* LIST(BslList)_____SECTION1(BSL_CONF_Section)_____LIST(BslList)_______KEY1, VALUE(BSL_CONF_KeyValue)
* | |__KEY2, VALUE(BSL_CONF_KeyValue)
* | |__KEY3, VALUE(BSL_CONF_KeyValue)
* |
* |__SECTION2(BSL_CONF_Section)_____LIST(BslList)_______KEY1, VALUE(BSL_CONF_KeyValue)
* | |__KEY2, VALUE(BSL_CONF_KeyValue)
* ...
*/
typedef BslList *(*BslConfCreate)(void);
typedef void (*BslConfDestroy)(BslList *sectionList);
typedef int32_t (*BslConfLoad)(BslList *sectionList, const char *file);
typedef int32_t (*BslConfLoadUio)(BslList *sectionList, BSL_UIO *uio);
typedef int32_t (*BslConfDump)(BslList *sectionList, const char *file);
typedef int32_t (*BslConfDumpUio)(BslList *sectionList, BSL_UIO *uio);
typedef BslList *(*BslConfGetSection)(BslList *sectionList, const char *section);
typedef int32_t (*BslConfGetString)(BslList *sectionList, const char *section, const char *key,
char *string, uint32_t *strLen);
typedef int32_t (*BslConfGetNumber)(BslList *sectionList, const char *section, const char *key, long int *num);
typedef char **(*BslConfGetSectionNames)(BslList *sectionList, uint32_t *namesSize);
typedef struct BSL_CONF_MethodStruct {
BslConfCreate create;
BslConfDestroy destroy;
BslConfLoad load;
BslConfLoadUio loadUio;
BslConfDump dump;
BslConfDumpUio dumpUio;
BslConfGetSection getSection;
BslConfGetString getString;
BslConfGetNumber getNumber;
BslConfGetSectionNames getSectionNames;
} BSL_CONF_Method;
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_CONF */
#endif /* BSL_CONF_DEF_H */ | 2401_83913325/openHiTLS_1 | bsl/conf/include/bsl_conf_def.h | C | unknown | 2,872 |
/*
* 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_BSL_CONF
#include "bsl_uio.h"
#include "bsl_sal.h"
#include "bsl_list.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "bsl_conf.h"
// Create a conf object based on BSL_CONF_Method
BSL_CONF *BSL_CONF_New(const BSL_CONF_Method *meth)
{
BSL_CONF *conf = (BSL_CONF *)BSL_SAL_Calloc(1, sizeof(BSL_CONF));
if (conf == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
if (meth == NULL) {
conf->meth = BSL_CONF_DefaultMethod();
} else {
conf->meth = meth;
}
if (conf->meth->create == NULL || conf->meth->destroy == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_INIT_FAIL);
BSL_SAL_FREE(conf);
return NULL;
}
conf->data = conf->meth->create();
if (conf->data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
BSL_SAL_FREE(conf);
return NULL;
}
return conf;
}
// release conf resources
void BSL_CONF_Free(BSL_CONF *conf)
{
if (conf == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return;
}
if (conf->meth != NULL && conf->meth->destroy != NULL) {
conf->meth->destroy(conf->data);
conf->data = NULL;
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_FREE_FAIL);
}
BSL_SAL_FREE(conf);
return;
}
// Read the conf information from the UIO.
int32_t BSL_CONF_LoadByUIO(BSL_CONF *conf, BSL_UIO *uio)
{
if (conf == NULL || uio == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->loadUio != NULL) {
return conf->meth->loadUio(conf->data, uio);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_LOAD_FAIL);
return BSL_CONF_LOAD_FAIL;
}
}
// Read the conf information from the file.
int32_t BSL_CONF_Load(BSL_CONF *conf, const char *file)
{
if (conf == NULL || file == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->load != NULL) {
return conf->meth->load(conf->data, file);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_LOAD_FAIL);
return BSL_CONF_LOAD_FAIL;
}
}
// Return the BslList that consists of all BslListNodes that store the BSL_CONF_KeyValue with the same section name.
BslList *BSL_CONF_GetSection(const BSL_CONF *conf, const char *section)
{
if (conf == NULL || section == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return NULL;
}
if (conf->meth != NULL && conf->meth->getSection != NULL) {
return conf->meth->getSection(conf->data, section);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return NULL;
}
}
// Obtain the value string corresponding to the name in the specified section.
int32_t BSL_CONF_GetString(const BSL_CONF *conf, const char *section, const char *name, char *str, uint32_t *strLen)
{
if (conf == NULL || section == NULL || name == NULL || str == NULL || strLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->getString != NULL) {
return conf->meth->getString(conf->data, section, name, str, strLen);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
}
// Obtain the integer value corresponding to the name in the specified section.
int32_t BSL_CONF_GetNumber(const BSL_CONF *conf, const char *section, const char *name, long *value)
{
if (conf == NULL || section == NULL || name == NULL || value == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->getNumber != NULL) {
return conf->meth->getNumber(conf->data, section, name, value);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
}
// Dump config contents to file.
int32_t BSL_CONF_Dump(const BSL_CONF *conf, const char *file)
{
if (conf == NULL || file == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->dump != NULL) {
return conf->meth->dump(conf->data, file);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_DUMP_FAIL);
return BSL_CONF_DUMP_FAIL;
}
}
// Dump config contents to uio.
int32_t BSL_CONF_DumpUio(const BSL_CONF *conf, BSL_UIO *uio)
{
if (conf == NULL || uio == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->dumpUio != NULL) {
return conf->meth->dumpUio(conf->data, uio);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_DUMP_FAIL);
return BSL_CONF_DUMP_FAIL;
}
}
// Get section name array.
char **BSL_CONF_GetSectionNames(const BSL_CONF *conf, uint32_t *namesSize)
{
if (conf == NULL || namesSize == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return NULL;
}
if (conf->meth != NULL && conf->meth->getSectionNames != NULL) {
return conf->meth->getSectionNames(conf->data, namesSize);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return NULL;
}
}
#endif /* HITLS_BSL_CONF */
| 2401_83913325/openHiTLS_1 | bsl/conf/src/bsl_conf.c | C | unknown | 5,797 |
/*
* 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_BSL_CONF
#include <ctype.h>
#include <limits.h>
#include "securec.h"
#include "bsl_uio.h"
#include "bsl_sal.h"
#include "bsl_list.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "bsl_conf_def.h"
#define BREAK_FLAG 1
#define CONTINUE_FLAG 2
static int32_t IsNameValid(const char *name)
{
const char table[128] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, // ',' '.'
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, // '0'-'9' ';'
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'A'-'Z'
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // '_'
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'a'-'z'
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
};
uint32_t nameLen = (uint32_t)strlen(name);
char pos = 0;
for (uint32_t i = 0; i < nameLen; i++) {
pos = name[i];
if (pos < 0 || table[(uint32_t)pos] != 1) { // invalid name.
return 0;
}
}
return 1;
}
static int32_t IsEscapeValid(char c)
{
char table[] = {
'#', ';', '$', '\\', '\"', '\''
};
uint32_t tableSize = (uint32_t)(sizeof(table) / sizeof(table[0]));
for (uint32_t i = 0; i < tableSize; i++) {
if (c == table[i]) {
return 1;
}
}
return 0;
}
static int32_t RemoveSpace(char *str)
{
if (str == NULL) {
return 0;
}
int32_t strLen = (int32_t)strlen(str);
if (strLen == 0) {
return 0;
}
int32_t head = 0;
int32_t tail = strLen - 1;
while (head <= tail) {
if (isspace((unsigned char)str[head])) {
head++;
} else {
break;
}
}
while (head <= tail) {
if (isspace((unsigned char)str[tail])) {
tail--;
} else {
break;
}
}
int32_t realLen = tail - head + 1;
if (realLen > 0) {
(void)memmove_s(str, strLen, str + head, realLen);
}
str[realLen] = '\0';
return realLen;
}
// Parses a string enclosed within quotes, handling escape sequences appropriately.
static int32_t ParseQuote(char *str, char quote)
{
int32_t cnt = 0;
int32_t strLen = (int32_t)strlen(str);
int32_t i = 0;
while (i < strLen) {
if (str[i] == quote) {
break; // Exit the loop when the quote character is encountered.
}
if (str[i] == '\\') {
if (IsEscapeValid(str[i + 1]) == 0 && str[i + 1] != 'n') {
return BSL_CONF_CONTEXT_ERR; // Return error if the escape sequence is invalid.
}
i++; // Skip the escaped character.
if (i >= strLen) {
return BSL_CONF_CONTEXT_ERR; // Return error if the index exceeds the string length.
}
if (str[i] == 'n') { // '\n'
str[i] = '\n';
}
}
str[cnt] = str[i];
cnt++;
i++;
}
str[cnt] = '\0'; // Add a null terminator at the end of the parsed string.
return BSL_SUCCESS;
}
// Removes escape characters and comments from a string.
static int32_t RemoveEscapeAndComments(char *buff)
{
bool isValue = false;
int32_t flag = 0;
int32_t cnt = 0;
int32_t len = (int32_t)strlen(buff);
int32_t i = 0;
while (i < len) {
if (buff[i] == '=') {
isValue = true; // Enter the value part when '=' is encountered.
}
if (buff[i] == ';' || buff[i] == '#') {
if (isValue) { // Encounter a comment symbol in the value part, stop processing.
break;
}
}
if (buff[i] == '\\') {
// Escape characters are not allowed in the name part, or the escape character is invalid.
if (isValue == false) {
return -1;
}
if (IsEscapeValid(buff[i + 1]) == 0 && buff[i + 1] != 'n') {
return -1;
}
flag++;
i++; // Skip the escape character.
if (i >= len) { // If the index exceeds the string length, return an error.
return -1;
}
if (buff[i] == 'n') { // '\n'
buff[i] = '\n';
}
}
buff[cnt] = buff[i];
cnt++;
i++;
}
buff[cnt] = '\0'; // Add a null terminator at the end of the processed string.
return flag;
}
static void FreeSectionNames(char **names, int32_t namesSize)
{
if (names == NULL) {
return;
}
for (int32_t i = 0; i < namesSize; i++) {
BSL_SAL_FREE(names[i]);
}
BSL_SAL_FREE(names);
}
char **DefaultGetSectionNames(BslList *sectionList, uint32_t *namesSize)
{
if (sectionList == NULL || namesSize == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return NULL;
}
int32_t cnt = 0;
int32_t num = BSL_LIST_COUNT(sectionList);
char **names = (char **)BSL_SAL_Calloc(num, sizeof(char *));
if (names == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
BSL_CONF_Section *secData = NULL;
BslListNode *node = BSL_LIST_FirstNode(sectionList);
while (node != NULL && cnt < num) {
secData = BSL_LIST_GetData(node);
if (secData == NULL) {
FreeSectionNames(names, num);
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return NULL;
}
names[cnt] = BSL_SAL_Calloc(secData->sectionLen + 1, 1);
if (names[cnt] == NULL) {
FreeSectionNames(names, num);
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
(void)memcpy_s(names[cnt], secData->sectionLen, secData->section, secData->sectionLen);
cnt++;
node = BSL_LIST_GetNextNode(sectionList, node);
}
if (cnt != num) {
FreeSectionNames(names, num);
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return NULL;
}
*namesSize = (uint32_t)num;
return names;
}
static int32_t CmpSectionFunc(const void *a, const void *b)
{
const BSL_CONF_Section *aData = (const BSL_CONF_Section *)a;
const char *bData = (const char *)b;
if (aData != NULL && aData->section != NULL && bData != NULL) {
if (strcmp(aData->section, bData) == 0) {
return 0;
}
}
return 1;
}
static int32_t CmpKeyFunc(const void *a, const void *b)
{
const BSL_CONF_KeyValue *aData = (const BSL_CONF_KeyValue *)a;
const char *bData = (const char *)b;
if (aData != NULL && aData->key != NULL && bData != NULL) {
if (strcmp(aData->key, bData) == 0) {
return 0;
}
}
return 1;
}
void DeleteKeyValueNodeFunc(void *data)
{
if (data == NULL) {
return;
}
BSL_CONF_KeyValue *keyValueNode = (BSL_CONF_KeyValue *)data;
BSL_SAL_FREE(keyValueNode->key);
BSL_SAL_FREE(keyValueNode->value);
BSL_SAL_FREE(keyValueNode);
}
void DeleteSectionNodeFunc(void *data)
{
if (data == NULL) {
return;
}
BSL_CONF_Section *sectionNode = (BSL_CONF_Section *)data;
BSL_LIST_FREE(sectionNode->keyValueList, DeleteKeyValueNodeFunc);
BSL_SAL_FREE(sectionNode->section);
BSL_SAL_FREE(sectionNode);
}
static int32_t UpdateKeyValue(BSL_CONF_KeyValue *keyValue, const char *value)
{
uint32_t newValueLen = (uint32_t)strlen(value);
char *newValue = (char *)BSL_SAL_Calloc(1, newValueLen + 1);
if (newValue == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
return BSL_CONF_MEM_ALLOC_FAIL;
}
(void)memcpy_s(newValue, newValueLen, value, newValueLen);
BSL_SAL_FREE(keyValue->value);
keyValue->value = newValue;
keyValue->valueLen = newValueLen;
return BSL_SUCCESS;
}
static int32_t AddKeyValue(BslList *keyValueList, const char * key, const char *value)
{
int32_t ret = BSL_SUCCESS;
if (IsNameValid(key) == 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_INVALID_NAME);
return BSL_CONF_INVALID_NAME;
}
BSL_CONF_KeyValue *keyValue = (BSL_CONF_KeyValue *)BSL_SAL_Calloc(1, sizeof(BSL_CONF_KeyValue));
if (keyValue == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
return BSL_CONF_MEM_ALLOC_FAIL;
}
keyValue->keyLen = (uint32_t)strlen(key);
keyValue->key = (char *)BSL_SAL_Calloc(1, keyValue->keyLen + 1);
if (keyValue->key == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
ret = BSL_CONF_MEM_ALLOC_FAIL;
goto EXIT;
}
keyValue->valueLen = (uint32_t)strlen(value);
keyValue->value = (char *)BSL_SAL_Calloc(1, keyValue->valueLen + 1);
if (keyValue->value == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
ret = BSL_CONF_MEM_ALLOC_FAIL;
goto EXIT;
}
(void)memcpy_s(keyValue->key, keyValue->keyLen, key, keyValue->keyLen);
(void)memcpy_s(keyValue->value, keyValue->valueLen, value, keyValue->valueLen);
ret = BSL_LIST_AddElement(keyValueList, keyValue, BSL_LIST_POS_END);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
return BSL_SUCCESS;
EXIT:
DeleteKeyValueNodeFunc(keyValue);
return ret;
}
static int32_t AddSection(BslList *sectionList, const char *section, const char *key, const char *value)
{
int32_t ret = BSL_SUCCESS;
if (IsNameValid(section) == 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_INVALID_NAME);
return BSL_CONF_INVALID_NAME;
}
BSL_CONF_Section *sectionNode = (BSL_CONF_Section *)BSL_SAL_Calloc(1, sizeof(BSL_CONF_Section));
if (sectionNode == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
return BSL_CONF_MEM_ALLOC_FAIL;
}
sectionNode->sectionLen = (uint32_t)strlen(section);
sectionNode->section = (char *)BSL_SAL_Calloc(1, sectionNode->sectionLen + 1);
if (sectionNode->section == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
ret = BSL_CONF_MEM_ALLOC_FAIL;
goto EXIT;
}
(void)memcpy_s(sectionNode->section, sectionNode->sectionLen, section, sectionNode->sectionLen);
sectionNode->keyValueList = BSL_LIST_New(sizeof(BslList));
if (sectionNode->keyValueList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
ret = BSL_CONF_MEM_ALLOC_FAIL;
goto EXIT;
}
if (strlen(key) != 0) {
ret = AddKeyValue(sectionNode->keyValueList, key, value);
if (ret != BSL_SUCCESS) {
goto EXIT;
}
}
ret = BSL_LIST_AddElement(sectionList, sectionNode, BSL_LIST_POS_END);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
return BSL_SUCCESS;
EXIT:
DeleteSectionNodeFunc(sectionNode);
return ret;
}
BslList *DefaultGetSectionNode(BslList *sectionList, const char *section)
{
if (sectionList == NULL || section == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return NULL;
}
BSL_CONF_Section *sectionNode = BSL_LIST_Search(sectionList, section, CmpSectionFunc, NULL);
if (sectionNode == NULL || sectionNode->keyValueList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return NULL;
}
return sectionNode->keyValueList;
}
int32_t DefaultGetString(BslList *sectionList, const char *section, const char *key, char *str, uint32_t *strLen)
{
if (sectionList == NULL || section == NULL || key == NULL || str == NULL || strLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
BSL_CONF_Section *secCtx = BSL_LIST_Search(sectionList, section, CmpSectionFunc, NULL);
if (secCtx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
BSL_CONF_KeyValue *keyValue = BSL_LIST_Search(secCtx->keyValueList, key, CmpKeyFunc, NULL);
if (keyValue == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_VALUE_NOT_FOUND);
return BSL_CONF_VALUE_NOT_FOUND;
}
if (*strLen < keyValue->valueLen + 1) { // 1 byte for '\0'
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
(void)memcpy_s(str, *strLen, keyValue->value, keyValue->valueLen);
str[keyValue->valueLen] = '\0';
*strLen = keyValue->valueLen;
return BSL_SUCCESS;
}
int32_t DefaultGetNumber(BslList *sectionList, const char *section, const char *key, long int *num)
{
char str[BSL_CONF_LINE_SIZE + 1] = {0};
uint32_t strLen = BSL_CONF_LINE_SIZE + 1;
int32_t ret = DefaultGetString(sectionList, section, key, str, &strLen);
if (ret != BSL_SUCCESS) {
return ret;
}
char *endPtr = NULL;
errno = 0;
long int tmpNum = strtol(str, &endPtr, 0);
if (strlen(endPtr) > 0 || endPtr == str || (tmpNum == LONG_MAX || tmpNum == LONG_MIN) || errno == ERANGE ||
(tmpNum == 0 && errno != 0)) {
BSL_ERR_PUSH_ERROR(BSL_CONF_CONTEXT_ERR);
return BSL_CONF_CONTEXT_ERR;
}
*num = tmpNum;
return BSL_SUCCESS;
}
BslList *DefaultCreate(void)
{
BslList *sectionList = BSL_LIST_New(sizeof(BslList));
if (sectionList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
return NULL;
}
int32_t ret = AddSection(sectionList, "default", "", "");
if (ret != BSL_SUCCESS) {
BSL_LIST_FREE(sectionList, NULL);
return NULL;
}
return sectionList;
}
void DefaultDestroy(BslList *sectionList)
{
if (sectionList == NULL) {
return;
}
BSL_LIST_FREE(sectionList, DeleteSectionNodeFunc);
}
static int32_t SetSection(BslList *sectionList, const char *section, const char * key, const char *value)
{
if (sectionList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
BSL_CONF_Section *secCtx = NULL;
BSL_CONF_KeyValue *keyValue = NULL;
if (strlen(section) == 0) { // default section.
if (strlen(key) == 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_CONTEXT_ERR);
return BSL_CONF_CONTEXT_ERR;
}
secCtx = BSL_LIST_Search(sectionList, "default", CmpSectionFunc, NULL);
if (secCtx == NULL || secCtx->keyValueList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
keyValue = BSL_LIST_Search(secCtx->keyValueList, key, CmpKeyFunc, NULL);
if (keyValue == NULL) {
return AddKeyValue(secCtx->keyValueList, key, value);
} else {
return UpdateKeyValue(keyValue, value);
}
} else {
secCtx = BSL_LIST_Search(sectionList, section, CmpSectionFunc, NULL);
if (secCtx == NULL) {
return AddSection(sectionList, section, key, value);
}
if (strlen(key) == 0) {
return BSL_SUCCESS;
}
if (secCtx->keyValueList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
keyValue = BSL_LIST_Search(secCtx->keyValueList, key, CmpKeyFunc, NULL);
if (keyValue == NULL) {
return AddKeyValue(secCtx->keyValueList, key, value);
} else {
return UpdateKeyValue(keyValue, value);
}
}
}
// Reads a line of data from a configuration file.
static int32_t ConfGetLine(BSL_UIO *uio, char *buff, int32_t buffSize, int32_t *offset, int32_t *flag)
{
int32_t tmpOffset = *offset;
int32_t buffLen = buffSize - tmpOffset; // Calculate the available buffer length
if (buffLen <= 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_BUFF_OVERFLOW);
return BSL_CONF_BUFF_OVERFLOW;
}
int32_t ret = BSL_UIO_Gets(uio, buff + tmpOffset, (uint32_t *)&buffLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
buffLen += tmpOffset; // Update the buffer length
if (buffLen == 0) {
*flag = BREAK_FLAG;
return BSL_SUCCESS;
}
bool isEof = false;
if (buff[buffLen - 1] != '\n') { // buffer might have been truncated.
ret = BSL_UIO_Ctrl(uio, BSL_UIO_FILE_GET_EOF, 1, &isEof);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (isEof != true) {
BSL_ERR_PUSH_ERROR(BSL_CONF_BUFF_OVERFLOW);
return BSL_CONF_BUFF_OVERFLOW;
}
(void)RemoveSpace(buff);
return BSL_SUCCESS;
}
buffLen = RemoveSpace(buff);
if (buffLen > 0) {
buffLen--;
}
if (buff[buffLen] == '\\') { // Handle multi-line cases
if (buffLen > 0 && buff[buffLen - 1] == '\\') { // Handle escape characters
tmpOffset = 0;
} else { // Normal case
tmpOffset = buffLen; // Set the temporary offset
*flag = CONTINUE_FLAG;
}
} else { // Single-line case
tmpOffset = 0;
}
*offset = tmpOffset;
return BSL_SUCCESS;
}
// Parses a line of configuration data.
static int32_t ConfParseLine(BslList *sectionList, char *buff, char *section, char *key, char *value)
{
int32_t ret = BSL_SUCCESS;
size_t len = strlen(buff);
int32_t n = 2; // sscanf_s is expected to return 2.
if (len < 1 || buff[0] == '#' || buff[0] == ';') { // empty or comments
return BSL_SUCCESS;
} else if (buff[0] == '[' && buff[len - 1] == ']') {
len -= 2; // remove '[' and ']' len - 2.
if (memcpy_s(section, BSL_CONF_SEC_SIZE, &buff[1], len) != 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_BUFF_OVERFLOW);
return BSL_CONF_BUFF_OVERFLOW;
}
section[len] = '\0';
} else if (sscanf_s(buff, "%[^=] = \"%[^\n]", key, BSL_CONF_LINE_SIZE, value, BSL_CONF_LINE_SIZE) == n) {
ret = ParseQuote(value, '\"');
} else if (sscanf_s(buff, "%[^=] = \'%[^\n]", key, BSL_CONF_LINE_SIZE, value, BSL_CONF_LINE_SIZE) == n) {
ret = ParseQuote(value, '\'');
} else if (RemoveEscapeAndComments(buff) < 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_CONTEXT_ERR);
return BSL_CONF_CONTEXT_ERR;
} else if (sscanf_s(buff, "%[^=]%[=]", key, BSL_CONF_LINE_SIZE, value, BSL_CONF_LINE_SIZE) == n) {
char *valPtr = strchr(buff, '=');
valPtr++;
len = strlen(valPtr);
(void)memcpy_s(value, len, valPtr, len);
value[len] = '\0';
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_CONTEXT_ERR);
return BSL_CONF_CONTEXT_ERR;
}
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)RemoveSpace(section);
(void)RemoveSpace(key);
(void)RemoveSpace(value);
return SetSection(sectionList, section, key, value);
}
// Loads configuration data from a UIO into a section list.
int32_t DefaultLoadUio(BslList *sectionList, BSL_UIO *uio)
{
if (sectionList == NULL || uio == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
int32_t ret;
int32_t offset = 0;
int32_t flag;
char *buff = (char *)BSL_SAL_Calloc(4, (BSL_CONF_LINE_SIZE + 1)); // 4 blocks for buff, secion, key, value.
if (buff == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
char *section = (char *)(buff + BSL_CONF_LINE_SIZE + 1);
char *key = (char *)(section + BSL_CONF_LINE_SIZE + 1);
char *value = (char *)(key + BSL_CONF_LINE_SIZE + 1);
while (true) {
flag = 0; // Reset flag.
// Read one line into buff.
ret = ConfGetLine(uio, buff, BSL_CONF_LINE_SIZE + 1, &offset, &flag);
if (ret != BSL_SUCCESS || flag == BREAK_FLAG) {
break;
}
if (flag == CONTINUE_FLAG) {
continue;
}
// Parse section, key, value from buff.
ret = ConfParseLine(sectionList, buff, section, key, value);
if (ret != BSL_SUCCESS) {
break;
}
// Clear buff, key, value, do not clear section.
(void)memset_s(buff, BSL_CONF_LINE_SIZE + 1, 0, BSL_CONF_LINE_SIZE + 1);
(void)memset_s(key, BSL_CONF_LINE_SIZE + 1, 0, BSL_CONF_LINE_SIZE + 1);
(void)memset_s(value, BSL_CONF_LINE_SIZE + 1, 0, BSL_CONF_LINE_SIZE + 1);
offset = 0; // Reset offset.
}
BSL_SAL_FREE(buff);
return ret;
}
int32_t DefaultLoad(BslList *sectionList, const char *file)
{
if (sectionList == NULL || file == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
BSL_UIO *in = BSL_UIO_New(BSL_UIO_FileMethod());
if (in == NULL) {
BSL_ERR_PUSH_ERROR(BSL_UIO_FAIL);
return BSL_UIO_FAIL;
}
int32_t ret = BSL_UIO_Ctrl(in, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_READ, (void *)(uintptr_t)file);
if (ret != BSL_SUCCESS) {
BSL_UIO_Free(in);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = DefaultLoadUio(sectionList, in);
BSL_UIO_Free(in);
return ret;
}
static int32_t DumpSection(BSL_UIO *uio, const BSL_CONF_Section *secData)
{
uint32_t strLen = secData->sectionLen + 4; // "[]\n\0" == 4
char *str = (char *)BSL_SAL_Calloc(1, strLen + 1);
if (str == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
int32_t usedLen = sprintf_s(str, strLen, "[%s]\n", secData->section);
if (usedLen < 0) {
BSL_SAL_FREE(str);
BSL_ERR_PUSH_ERROR(BSL_CONF_DUMP_FAIL);
return BSL_CONF_DUMP_FAIL;
}
if (usedLen > BSL_CONF_LINE_SIZE) {
BSL_SAL_FREE(str);
BSL_ERR_PUSH_ERROR(BSL_CONF_BUFF_OVERFLOW);
return BSL_CONF_BUFF_OVERFLOW;
}
int32_t ret = BSL_UIO_Puts(uio, str, (uint32_t *)&usedLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
BSL_SAL_FREE(str);
return ret;
}
static int32_t DumpKeyValue(BSL_UIO *uio, const BSL_CONF_KeyValue *keyValue)
{
uint32_t strLen = keyValue->keyLen + keyValue->valueLen * 2 + 3; // "=\n\0" == 3, valueLen * 2 for '\\'.
char *str = (char *)BSL_SAL_Calloc(1, strLen + 1);
if (str == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
int32_t usedLen = sprintf_s(str, strLen, "%s=", keyValue->key);
if (usedLen < 0) {
BSL_SAL_FREE(str);
BSL_ERR_PUSH_ERROR(BSL_CONF_DUMP_FAIL);
return BSL_CONF_DUMP_FAIL;
}
for (uint32_t i = 0; i < keyValue->valueLen; i++) {
if (IsEscapeValid(keyValue->value[i]) == 1) { // add '\\'.
str[usedLen] = '\\';
usedLen++;
}
if (keyValue->value[i] == '\n') {
str[usedLen] = '\\';
usedLen++;
str[usedLen] = 'n';
usedLen++;
continue;
}
str[usedLen] = keyValue->value[i];
usedLen++;
}
str[usedLen] = '\n';
usedLen++;
if (usedLen > BSL_CONF_LINE_SIZE) {
BSL_SAL_FREE(str);
BSL_ERR_PUSH_ERROR(BSL_CONF_BUFF_OVERFLOW);
return BSL_CONF_BUFF_OVERFLOW;
}
int32_t ret = BSL_UIO_Puts(uio, str, (uint32_t *)&usedLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
BSL_SAL_FREE(str);
return ret;
}
int32_t DefaultDumpUio(BslList *sectionList, BSL_UIO *uio)
{
if (sectionList == NULL || uio == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
int32_t ret = BSL_SUCCESS;
BSL_CONF_Section *secData = NULL;
BSL_CONF_KeyValue *keyValue = NULL;
BslListNode *keyValueNode = NULL;
BslListNode *node = BSL_LIST_FirstNode(sectionList);
while (node != NULL) {
secData = BSL_LIST_GetData(node);
if (secData == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
ret = DumpSection(uio, secData);
if (ret != BSL_SUCCESS) {
return ret;
}
keyValueNode = BSL_LIST_FirstNode(secData->keyValueList);
while (keyValueNode != NULL) {
keyValue = BSL_LIST_GetData(keyValueNode);
if (keyValue == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
ret = DumpKeyValue(uio, keyValue);
if (ret != BSL_SUCCESS) {
return ret;
}
keyValueNode = BSL_LIST_GetNextNode(secData->keyValueList, keyValueNode);
}
node = BSL_LIST_GetNextNode(sectionList, node);
}
return BSL_SUCCESS;
}
int32_t DefaultDump(BslList *sectionList, const char *file)
{
if (sectionList == NULL || file == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
BSL_UIO *out = BSL_UIO_New(BSL_UIO_FileMethod());
if (out == NULL) {
BSL_ERR_PUSH_ERROR(BSL_UIO_FAIL);
return BSL_UIO_FAIL;
}
int32_t ret = BSL_UIO_Ctrl(out, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_WRITE, (void *)(uintptr_t)file);
if (ret != BSL_SUCCESS) {
BSL_UIO_Free(out);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = DefaultDumpUio(sectionList, out);
BSL_UIO_SetIsUnderlyingClosedByUio(out, true);
BSL_UIO_Free(out);
return ret;
}
const BSL_CONF_Method *BSL_CONF_DefaultMethod(void)
{
static const BSL_CONF_Method DEFAULT_METHOD = {
DefaultCreate,
DefaultDestroy,
DefaultLoad,
DefaultLoadUio,
DefaultDump,
DefaultDumpUio,
DefaultGetSectionNode,
DefaultGetString,
DefaultGetNumber,
DefaultGetSectionNames,
};
return &DEFAULT_METHOD;
}
#endif /* HITLS_BSL_CONF */
| 2401_83913325/openHiTLS_1 | bsl/conf/src/bsl_conf_def.c | C | unknown | 26,113 |
/*
* 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 BSL_ERR_INTERNAL_H
#define BSL_ERR_INTERNAL_H
#include <stdint.h>
#include "hitls_build.h"
#include "bsl_err.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef HITLS_BSL_ERR
/**
* @ingroup bsl_err
* @brief Save the error information to the error information stack.
*
* @par Description:
* Save the error information to the error information stack.
*
* @attention err cannot be 0.
* @param err [IN] Error code. The most significant 16 bits indicate the submodule ID,
* and the least significant 16 bits indicate the error ID.
* @param file [IN] File name, excluding the directory path
* @param lineNo [IN] Number of the line where the error occurs.
*/
void BSL_ERR_PushError(int32_t err, const char *file, uint32_t lineNo);
/**
* @ingroup bsl_err
* @brief Save the error information to the error information stack.
*
* @par Description:
* Save the error information to the error information stack.
*
* @attention e cannot be 0.
*/
#define BSL_ERR_PUSH_ERROR(e) BSL_ERR_PushError((e), __FILENAME__, __LINE__)
#else
#define BSL_ERR_PUSH_ERROR(e)
#endif /* HITLS_BSL_ERR */
#ifdef __cplusplus
}
#endif
#endif // BSL_ERR_INTERNAL_H
| 2401_83913325/openHiTLS_1 | bsl/err/include/bsl_err_internal.h | C | unknown | 1,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 "hitls_build.h"
#ifdef HITLS_BSL_ERR
#include "bsl_sal.h"
#include "bsl_log_internal.h"
#include "bsl_log.h"
#include "bsl_binlog_id.h"
#include "avl.h"
// Maximum height of the AVL tree.
#define AVL_MAX_HEIGHT 64
static uint32_t GetMaxHeight(uint32_t a, uint32_t b)
{
if (a >= b) {
return a;
} else {
return b;
}
}
static uint32_t GetAvlTreeHeight(const BSL_AvlTree *node)
{
if (node == NULL) {
return 0;
} else {
return node->height;
}
}
static void UpdateAvlTreeHeight(BSL_AvlTree *node)
{
if (node != NULL) {
uint32_t leftHeight = GetAvlTreeHeight(node->leftNode);
uint32_t rightHeight = GetAvlTreeHeight(node->rightNode);
if (node->height >= AVL_MAX_HEIGHT) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05001, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"avl tree height exceed max limit", 0, 0, 0, 0);
return;
}
node->height = GetMaxHeight(leftHeight, rightHeight) + 1u;
}
}
BSL_AvlTree *BSL_AVL_MakeLeafNode(BSL_ElementData data)
{
BSL_AvlTree *curNode = (BSL_AvlTree *)BSL_SAL_Malloc(sizeof(BSL_AvlTree));
if (curNode == NULL) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05002, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"MALLOC for avl tree node failed", 0, 0, 0, 0);
return NULL;
}
curNode->height = 1;
curNode->rightNode = NULL;
curNode->leftNode = NULL;
curNode->data = data;
return curNode;
}
/**
* @brief AVL rotate left
* @param root [IN] Root node to be rotated
* @return rNode Root node after rotation
*/
static BSL_AvlTree *AVL_RotateLeft(BSL_AvlTree *root)
{
/* Rotate Left
10 20
5 20 --Rotate Left---> 10 30
30 5 40
40
In this case, the input root node is 10, and the output node is 20. */
BSL_AvlTree *rNode = root->rightNode;
BSL_AvlTree *lNode = rNode->leftNode;
root->rightNode = lNode;
rNode->leftNode = root;
UpdateAvlTreeHeight(root);
UpdateAvlTreeHeight(rNode);
return rNode;
}
/**
* @brief AVL rotate right
* @param root [IN] Root node to be rotated
* @return lNode Root node after rotation
*/
static BSL_AvlTree *AVL_RotateRight(BSL_AvlTree *root)
{
/* Rotate Right
40 30
/ \ / \
30 50 --Rotate Right---> 20 40
20 35 10 35 50
10
In this case, the input root node is 40, and the output node is 30. */
BSL_AvlTree *lNode = root->leftNode;
BSL_AvlTree *rNode = lNode->rightNode;
root->leftNode = rNode;
lNode->rightNode = root;
UpdateAvlTreeHeight(root);
UpdateAvlTreeHeight(lNode);
return lNode;
}
/**
* @brief AVL Right Balance
* @param root [IN] Root node to be balanced
* @return root: root node after balancing
*/
static BSL_AvlTree *AVL_RebalanceRight(BSL_AvlTree *root)
{
// The height difference between the left and right subtrees is only 1.
if ((GetAvlTreeHeight(root->leftNode) + 1u) >= GetAvlTreeHeight(root->rightNode)) {
UpdateAvlTreeHeight(root);
return root;
}
/* The height of the left subtree is greater than that of the right subtree. Rotate right and then left. */
BSL_AvlTree *curNode = root->rightNode;
if (GetAvlTreeHeight(curNode->leftNode) > GetAvlTreeHeight(curNode->rightNode)) {
root->rightNode = AVL_RotateRight(curNode);
}
return AVL_RotateLeft(root);
}
/**
* @brief AVL Left Balance
* @param root [IN] Root node to be balanced
* @return root: root node after balancing
*/
static BSL_AvlTree *AVL_RebalanceLeft(BSL_AvlTree *root)
{
// The height difference between the left and right subtrees is only 1.
if ((GetAvlTreeHeight(root->rightNode) + 1u) >= GetAvlTreeHeight(root->leftNode)) {
UpdateAvlTreeHeight(root);
return root;
}
/* The height of the right subtree is greater than that of the left subtree. Rotate left and then right. */
BSL_AvlTree *curNode = root->leftNode;
if (GetAvlTreeHeight(curNode->rightNode) > GetAvlTreeHeight(curNode->leftNode)) {
root->leftNode = AVL_RotateLeft(curNode);
}
return AVL_RotateRight(root);
}
static void AVL_FreeData(BSL_ElementData data, BSL_AVL_DATA_FREE_FUNC freeFunc)
{
if (freeFunc != NULL) {
freeFunc(data);
}
}
BSL_AvlTree *BSL_AVL_InsertNode(BSL_AvlTree *root, uint64_t nodeId, BSL_AvlTree *node)
{
if (root == NULL) {
node->nodeId = nodeId;
return node;
}
if (root->nodeId > nodeId) {
// If the nodeId is smaller than the root nodeId, insert the left subtree.
root->leftNode = BSL_AVL_InsertNode(root->leftNode, nodeId, node);
return AVL_RebalanceLeft(root);
} else if (root->nodeId < nodeId) {
// If the nodeId is greater than the root nodeId, insert the right subtree.
root->rightNode = BSL_AVL_InsertNode(root->rightNode, nodeId, node);
return AVL_RebalanceRight(root);
}
/* if the keys are the same and cannot be inserted */
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05003, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"AVL tree insert key nodeId(%llu) already exist", nodeId, 0, 0, 0);
return NULL;
}
BSL_AvlTree *BSL_AVL_SearchNode(BSL_AvlTree *root, uint64_t nodeId)
{
BSL_AvlTree *curNode = root;
while (curNode != NULL) {
// match the node
if (curNode->nodeId == nodeId) {
break;
} else if (curNode->nodeId > nodeId) {
// If the nodeId is smaller than the root nodeId, search the left subtree.
curNode = curNode->leftNode;
} else {
// If the nodeId is greater than the root nodeId, search the right subtree.
curNode = curNode->rightNode;
}
}
// If the specified node cannot be found, NULL is returned.
return curNode;
}
/**
* @brief Delete the specified AVL node that has both the left and right subnodes.
* @param rmNodeChild [IN] Child node of the AVL node to be deleted
* removeNode [IN] Avl node to be deleted.
* @return root Return the deleted root node of the AVL tree.
*/
static BSL_AvlTree *AVL_DeleteNodeWithTwoChilds(BSL_AvlTree *rmNodeChild, BSL_AvlTree *removeNode)
{
if (rmNodeChild == NULL || removeNode == NULL) {
return NULL;
}
if (rmNodeChild->rightNode == NULL) {
// Connect the left node and the grandfather node regardless of whether rmNodeChild has a left node.
BSL_AvlTree *curNode = rmNodeChild->leftNode;
removeNode->nodeId = rmNodeChild->nodeId;
removeNode->data = rmNodeChild->data;
BSL_SAL_FREE(rmNodeChild);
return curNode;
}
rmNodeChild->rightNode = AVL_DeleteNodeWithTwoChilds(rmNodeChild->rightNode, removeNode);
return AVL_RebalanceLeft(rmNodeChild);
}
BSL_AvlTree *BSL_AVL_DeleteNode(BSL_AvlTree *root, uint64_t nodeId, BSL_AVL_DATA_FREE_FUNC func)
{
if (root == NULL) {
return root;
}
if (root->nodeId == nodeId) {
if (root->leftNode == NULL) {
if (root->rightNode == NULL) {
// Both the left and right nodes are NULL.
AVL_FreeData(root->data, func);
BSL_SAL_FREE(root);
return NULL;
} else {
// Only have the right node.
BSL_AvlTree *curNode = root->rightNode;
AVL_FreeData(root->data, func);
BSL_SAL_FREE(root);
return (curNode);
}
} else if (root->rightNode == NULL) {
// Only have the right node.
BSL_AvlTree *curNode = root->leftNode;
AVL_FreeData(root->data, func);
BSL_SAL_FREE(root);
return (curNode);
} else {
// There are left and right nodes.
AVL_FreeData(root->data, func);
root->leftNode = AVL_DeleteNodeWithTwoChilds(root->leftNode, root);
return AVL_RebalanceRight(root);
}
}
if (root->nodeId > nodeId) {
root->leftNode = BSL_AVL_DeleteNode(root->leftNode, nodeId, func);
return AVL_RebalanceRight(root);
} else {
root->rightNode = BSL_AVL_DeleteNode(root->rightNode, nodeId, func);
return AVL_RebalanceLeft(root);
}
}
void BSL_AVL_DeleteTree(BSL_AvlTree *root, BSL_AVL_DATA_FREE_FUNC func)
{
if (root == NULL) {
return;
}
BSL_AVL_DeleteTree(root->leftNode, func);
BSL_AVL_DeleteTree(root->rightNode, func);
AVL_FreeData(root->data, func);
BSL_SAL_FREE(root);
}
#endif /* HITLS_BSL_ERR */
| 2401_83913325/openHiTLS_1 | bsl/err/src/avl.c | C | unknown | 9,427 |
/*
* 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 AVL_H
#define AVL_H
#include "hitls_build.h"
#ifdef HITLS_BSL_ERR
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef void *BSL_ElementData;
typedef void (*BSL_AVL_DATA_FREE_FUNC)(BSL_ElementData data);
/* AVL tree node structure */
typedef struct AvlTree {
uint32_t height;
uint64_t nodeId;
struct AvlTree *rightNode;
struct AvlTree *leftNode;
BSL_ElementData data;
} BSL_AvlTree;
/**
* @ingroup bsl_err
* @brief Create a tree node.
*
* @par Description:
* Create a tree node and set node data.
*
* @attention None
* @param data [IN] Data pointer of the tree node
* @retval BSL_AvlTree *curNode node returned after the application is successful.
* NULL application failed
*/
BSL_AvlTree *BSL_AVL_MakeLeafNode(BSL_ElementData data);
/**
* @ingroup bsl_err
* @brief Search for a node.
*
* @par Description:
* Query the node in the AVL tree by nodeId.
*
* @attention None
* @param root [IN] Pointer to the root node of the tree
* @param nodeId [IN] node ID of the tree, as the key
* @retval NULL No corresponding node is found.
* @retval not NULL Pointer to the corresponding node.
*/
BSL_AvlTree *BSL_AVL_SearchNode(BSL_AvlTree *root, uint64_t nodeId);
/**
* @ingroup bsl_err
* @brief Create a node in the tree.
*
* @par Description:
* Create a node in the tree.
*
* @attention If the nodeId already exists, the insertion fails.
* @param root [IN] Pointer to the root node of the tree.
* @param nodeId [IN] as the key of the created node
* @param node [IN] Tree node
* @retval The root node of a non-null tree or subtree
*/
BSL_AvlTree *BSL_AVL_InsertNode(BSL_AvlTree *root, uint64_t nodeId, BSL_AvlTree *node);
/**
* @ingroup bsl_err
* @brief Delete a specific tree node.
*
* @par Description:
* Delete the nodeId corresponding tree node.
*
* @attention None
* @param root [IN] Pointer to the root node of the tree.
* @param nodeId [IN] Key of the node to be deleted
* @param func [IN] Pointer to the function that releases the data of the deleted node.
* @retval NULL All nodes in the tree have been deleted.
* @retval not NULL Pointer to the root node of a tree or subtree.
*/
BSL_AvlTree *BSL_AVL_DeleteNode(BSL_AvlTree *root, uint64_t nodeId, BSL_AVL_DATA_FREE_FUNC func);
/**
* @ingroup bsl_err
* @brief Delete all nodes from the tree.
*
* @par Description:
* Delete all nodes in the tree.
*
* @attention None
* @param root [IN] Pointer to the root node of the tree
* @param func [IN] Pointer to the function that releases the data of the deleted node.
*/
void BSL_AVL_DeleteTree(BSL_AvlTree *root, BSL_AVL_DATA_FREE_FUNC func);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_ERR */
#endif // AVL_H | 2401_83913325/openHiTLS_1 | bsl/err/src/avl.h | C | unknown | 3,271 |
/*
* 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_BSL_ERR
#include <stdbool.h>
#include "securec.h"
#include "bsl_log_internal.h"
#include "bsl_log.h"
#include "bsl_sal.h"
#include "avl.h"
#include "bsl_err.h"
#include "bsl_errno.h"
#include "bsl_binlog_id.h"
#include "bsl_err_internal.h"
#define ERR_FLAG_POP_MARK 0x01
/* Error information stack size */
#define SAL_MAX_ERROR_STACK 20
/* Error information stack */
typedef struct {
/* Current point location to the stack. When the value is -1, the stack is empty. */
uint16_t bottom; /* Stack bottom */
uint16_t top; /* Stack top */
/* Prevent error stacks from being cleared. Currently, this parameter is used in asynchronous cases. */
uint32_t flag;
/* Store the error code information of a specific thread */
int32_t errorStack[SAL_MAX_ERROR_STACK];
/* Error code flag, which is used to partially clear and prevent side channel attack. */
uint32_t errorFlags[SAL_MAX_ERROR_STACK];
/* store the error file name. */
const char *filename[SAL_MAX_ERROR_STACK];
/* store the line number of the file where the error occurs */
uint32_t line[SAL_MAX_ERROR_STACK];
} ErrorCodeStack;
/* Avl tree root node of the error stack. */
static BSL_AvlTree *g_avlRoot = NULL;
/* Error description root node */
static BSL_AvlTree *g_descRoot = NULL;
/* Current number of AVL nodes */
static uint32_t g_avlNodeCount = 0;
/* Maximum number of nodes allowed by the AVL tree */
static uint32_t g_maxAvlNodes = 0x0000FFFF;
/* Check the initialization status. 0 means false, if the value is not 0, it means true. Run once. */
BSL_SAL_DECLARE_THREAD_ONCE(g_isErrInit);
/* Handle of the thread lock */
static BSL_SAL_ThreadLockHandle g_errLock = NULL;
static void ErrAutoInit(void)
{
/* Attempting self-initialization in abnormal conditions */
(void)BSL_ERR_Init();
}
int32_t BSL_ERR_Init(void)
{
if (g_errLock != NULL) {
return BSL_SUCCESS;
}
return BSL_SAL_ThreadLockNew(&g_errLock);
}
void BSL_ERR_DeInit(void)
{
(void)memset(&g_isErrInit, 0, sizeof(g_isErrInit));
if (g_errLock == NULL) {
return;
}
BSL_SAL_ThreadLockFree(g_errLock);
g_errLock = NULL;
return;
}
static void StackReset(ErrorCodeStack *stack)
{
if (stack != NULL) {
(void)memset_s(stack, sizeof(*stack), 0, sizeof(*stack));
}
}
static void StackResetIndex(ErrorCodeStack *stack, uint32_t i)
{
bool invalid = stack == NULL || i >= SAL_MAX_ERROR_STACK;
if (!invalid) {
stack->errorStack[i] = 0;
stack->line[i] = 0;
stack->filename[i] = NULL;
stack->errorFlags[i] = 0;
}
}
static void StackDataFree(BSL_ElementData data)
{
BSL_SAL_FREE(data);
}
static ErrorCodeStack *GetStack(void)
{
const uint64_t threadId = BSL_SAL_ThreadGetId();
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_avlRoot, threadId);
if (curNode != NULL) {
/* If an error stack exists, directly returned. */
return curNode->data;
}
/* need to create an error stack */
if (g_avlNodeCount >= g_maxAvlNodes) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05004, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"New Avl Node failed.", 0, 0, 0, 0);
return NULL;
}
ErrorCodeStack *stack = (ErrorCodeStack *)BSL_SAL_Calloc(1, sizeof(ErrorCodeStack));
if (stack == NULL) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05005, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"CALLOC error code stack failed", 0, 0, 0, 0);
return NULL;
}
BSL_AvlTree *node = BSL_AVL_MakeLeafNode(stack);
if (node == NULL) {
StackDataFree(stack);
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05006, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"avl insert node failed, threadId %lu", threadId, 0, 0, 0);
return NULL;
}
g_avlNodeCount++;
/* upper layer has ensured that the threadId node does not exist. */
g_avlRoot = BSL_AVL_InsertNode(g_avlRoot, threadId, node);
return stack;
}
void BSL_ERR_PushError(int32_t err, const char *file, uint32_t lineNo)
{
if (err == BSL_SUCCESS) {
/* push success is not allowed. */
return;
}
(void)BSL_SAL_ThreadRunOnce(&g_isErrInit, ErrAutoInit);
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05007, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"acquire lock failed when pushing error, threadId %llu, error code %d", BSL_SAL_ThreadGetId(), ret, 0, 0);
return;
}
ErrorCodeStack *stack = GetStack();
if (stack != NULL) {
if (stack->top == stack->bottom && stack->errorStack[stack->top] != 0) {
stack->bottom = (stack->bottom + 1) % SAL_MAX_ERROR_STACK;
}
stack->errorFlags[stack->top] = 0;
stack->errorStack[stack->top] = err;
stack->filename[stack->top] = file;
stack->line[stack->top] = lineNo;
stack->top = (stack->top + 1) % SAL_MAX_ERROR_STACK;
}
BSL_SAL_ThreadUnlock(g_errLock);
}
void BSL_ERR_ClearError(void)
{
(void)BSL_SAL_ThreadRunOnce(&g_isErrInit, ErrAutoInit);
uint64_t threadId = BSL_SAL_ThreadGetId();
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05008, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"acquire lock failed when clearing error, threadId %llu", threadId, 0, 0, 0);
return;
}
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_avlRoot, threadId);
if (curNode != NULL) {
/* Will not be NULL. */
ErrorCodeStack *errStack = curNode->data;
if (errStack->flag == 0) {
StackReset(errStack);
}
}
BSL_SAL_ThreadUnlock(g_errLock);
}
void BSL_ERR_RemoveErrorStack(bool isRemoveAll)
{
(void)BSL_SAL_ThreadRunOnce(&g_isErrInit, ErrAutoInit);
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05009, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"acquire lock failed when removing error stack, threadId %llu", BSL_SAL_ThreadGetId(), 0, 0, 0);
return;
}
if (g_avlRoot != NULL) {
if (isRemoveAll) {
BSL_AVL_DeleteTree(g_avlRoot, StackDataFree);
g_avlNodeCount = 0;
g_avlRoot = NULL;
} else {
uint64_t threadId = BSL_SAL_ThreadGetId();
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_avlRoot, threadId);
if (curNode != NULL) {
g_avlNodeCount--;
g_avlRoot = BSL_AVL_DeleteNode(g_avlRoot, threadId, StackDataFree);
}
}
}
BSL_SAL_ThreadUnlock(g_errLock);
}
/* Obtain the index. 'last' indicates that the last or first error code is obtained. */
static uint16_t GetIndex(ErrorCodeStack *errStack, bool last)
{
uint16_t idx;
if (last) {
idx = errStack->top - 1;
if (idx >= SAL_MAX_ERROR_STACK) {
idx = SAL_MAX_ERROR_STACK - 1;
}
} else {
idx = errStack->bottom;
}
return idx;
}
/* If clr is true, the external operation is get. If clr is false, the external operation is peek.
The get operation cleans up after the error information is obtained, while the peek operation does not.
If last is true, the last error code at the top of the stack is obtained.
If last is false, the first error code at the bottom of the stack is obtained. */
static int32_t GetErrorInfo(const char **file, uint32_t *lineNo, bool clr, bool last)
{
uint16_t idx;
int32_t ret = BSL_SAL_ThreadReadLock(g_errLock);
if (ret != BSL_SUCCESS) {
return BSL_ERR_ERR_ACQUIRE_READ_LOCK_FAIL;
}
if (g_avlRoot == NULL) {
/* If avlRoot is empty, no thread push error. Therefore, error should be success. */
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
const uint64_t threadId = BSL_SAL_ThreadGetId();
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_avlRoot, threadId);
if (curNode == NULL) {
/* If curNode is empty, the current thread does not have push error. Therefore, error should be success. */
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
ErrorCodeStack *errStack = curNode->data; /* will not be null */
idx = GetIndex(errStack, last);
if (errStack->errorStack[idx] == 0) { /* error stack is empty */
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
int32_t errorCode = errStack->errorStack[idx]; /* Obtain the specified error ID. */
uint32_t fileLine = errStack->line[idx]; /* Obtain the specified line number. */
const char *f = errStack->filename[idx]; /* Obtain the specified file name. */
if (clr) {
StackResetIndex(errStack, idx);
if (last) {
errStack->top = idx;
} else {
errStack->bottom = (idx + 1) % SAL_MAX_ERROR_STACK;
}
}
BSL_SAL_ThreadUnlock(g_errLock);
if (file != NULL && lineNo != NULL) { /* both together, there's no point in getting only one of them. */
if (f == NULL) {
*file = "NA";
*lineNo = 0;
} else {
*file = f;
*lineNo = fileLine;
}
}
return errorCode;
}
static int32_t GetLastErrorInfo(const char **file, uint32_t *lineNo, bool clr)
{
return GetErrorInfo(file, lineNo, clr, true);
}
static int32_t GetFirstErrorInfo(const char **file, uint32_t *lineNo, bool clr)
{
return GetErrorInfo(file, lineNo, clr, false);
}
int32_t BSL_ERR_GetLastErrorFileLine(const char **file, uint32_t *lineNo)
{
return GetLastErrorInfo(file, lineNo, true);
}
int32_t BSL_ERR_PeekLastErrorFileLine(const char **file, uint32_t *lineNo)
{
return GetLastErrorInfo(file, lineNo, false);
}
int32_t BSL_ERR_GetLastError(void)
{
return GetLastErrorInfo(NULL, NULL, true);
}
int32_t BSL_ERR_GetErrorFileLine(const char **file, uint32_t *lineNo)
{
return GetFirstErrorInfo(file, lineNo, true);
}
int32_t BSL_ERR_PeekErrorFileLine(const char **file, uint32_t *lineNo)
{
return GetFirstErrorInfo(file, lineNo, false);
}
int32_t BSL_ERR_GetError(void)
{
return GetFirstErrorInfo(NULL, NULL, true);
}
static int32_t AddErrDesc(const BSL_ERR_Desc *desc)
{
if (desc->error < 0) {
return BSL_INTERNAL_EXCEPTION;
}
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_descRoot, (uint64_t)desc->error);
if (curNode != NULL) {
curNode->data = (BSL_ElementData)(uintptr_t)(desc->string);
return BSL_SUCCESS;
}
BSL_AvlTree *node = BSL_AVL_MakeLeafNode((BSL_ElementData)(uintptr_t)(desc->string));
if (node == NULL) {
return BSL_INTERNAL_EXCEPTION;
}
g_descRoot = BSL_AVL_InsertNode(g_descRoot, (uint64_t)desc->error, node);
return BSL_SUCCESS;
}
int32_t BSL_ERR_AddErrStringBatch(const BSL_ERR_Desc *descList, uint32_t num)
{
if (descList == NULL || num == 0) {
return BSL_NULL_INPUT;
}
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
return ret;
}
for (uint32_t i = 0; i < num; i++) {
ret = AddErrDesc(&descList[i]);
if (ret != BSL_SUCCESS) {
break;
}
}
BSL_SAL_ThreadUnlock(g_errLock);
return ret;
}
void BSL_ERR_RemoveErrStringBatch(void)
{
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05010, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"acquire lock failed when removing error string, threadId %llu", BSL_SAL_ThreadGetId(), 0, 0, 0);
return;
}
if (g_descRoot != NULL) {
BSL_AVL_DeleteTree(g_descRoot, NULL);
g_descRoot = NULL;
}
BSL_SAL_ThreadUnlock(g_errLock);
}
const char *BSL_ERR_GetString(int32_t error)
{
if (error < 0) {
return NULL;
}
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
return NULL;
}
if (g_descRoot == NULL) {
BSL_SAL_ThreadUnlock(g_errLock);
return NULL;
}
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_descRoot, (uint64_t)error);
if (curNode == NULL) {
BSL_SAL_ThreadUnlock(g_errLock);
return NULL;
}
const char *str = curNode->data;
BSL_SAL_ThreadUnlock(g_errLock);
return str;
}
static int32_t BSL_LIST_WriteLockCreate(ErrorCodeStack **errStack, uint32_t *top)
{
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
return BSL_ERR_ERR_ACQUIRE_WRITE_LOCK_FAIL;
}
if (g_avlRoot == NULL) {
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_ERR_ERR_NO_STACK;
}
const uint64_t threadId = BSL_SAL_ThreadGetId();
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_avlRoot, threadId);
if (curNode == NULL) {
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_ERR_ERR_NO_STACK;
}
*errStack = curNode->data; /* will not be null */
if (top == NULL) {
return ret;
}
*top = (*errStack)->top - 1;
if (*top >= SAL_MAX_ERROR_STACK) {
*top = SAL_MAX_ERROR_STACK - 1;
}
return ret;
}
int32_t BSL_ERR_SetMark(void)
{
ErrorCodeStack *errStack = NULL;
uint32_t top = 0;
int32_t ret = BSL_LIST_WriteLockCreate(&errStack, &top);
if (ret != BSL_SUCCESS) {
return ret;
}
if (errStack->errorStack[top] == 0) { /* error stack is empty */
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_ERR_ERR_NO_ERROR;
}
errStack->errorFlags[top] |= ERR_FLAG_POP_MARK;
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
int32_t BSL_ERR_PopToMark(void)
{
ErrorCodeStack *errStack = NULL;
uint32_t top = 0;
int32_t ret = BSL_LIST_WriteLockCreate(&errStack, &top);
if (ret != BSL_SUCCESS) {
return ret;
}
while (errStack->errorStack[top] != 0 && ((errStack->errorFlags[top] & ERR_FLAG_POP_MARK) == 0)) {
StackResetIndex(errStack, top);
top--;
if (top >= SAL_MAX_ERROR_STACK) {
top = SAL_MAX_ERROR_STACK - 1;
}
}
errStack->top = (top + 1) % SAL_MAX_ERROR_STACK;
if (errStack->errorStack[top] == 0) {
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_ERR_ERR_NO_MARK;
}
errStack->errorFlags[top] &= ~ERR_FLAG_POP_MARK;
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
int32_t BSL_ERR_ClearLastMark(void)
{
ErrorCodeStack *errStack = NULL;
uint32_t top = 0;
int32_t ret = BSL_LIST_WriteLockCreate(&errStack, &top);
if (ret != BSL_SUCCESS) {
return ret;
}
while (errStack->errorStack[top] != 0 && ((errStack->errorFlags[top] & ERR_FLAG_POP_MARK) == 0)) {
top--;
if (top >= SAL_MAX_ERROR_STACK) {
top = SAL_MAX_ERROR_STACK - 1;
}
}
errStack->errorFlags[top] &= ~ERR_FLAG_POP_MARK;
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
#endif /* HITLS_BSL_ERR */
| 2401_83913325/openHiTLS_1 | bsl/err/src/err.c | C | unknown | 15,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.
*/
/**
* @defgroup bsl_hash hash table
* @ingroup bsl
*/
#ifndef BSL_HASH_H
#define BSL_HASH_H
#include "hitls_build.h"
#ifdef HITLS_BSL_HASH
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include "bsl_hash_list.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @ingroup bsl_hash
* @brief Handle of the hash table, which indicates the elements contained in the hash table.
*/
typedef struct BSL_HASH_Info BSL_HASH_Hash;
/**
* @ingroup bsl_hash
* @brief Definition of the iterator of the hash table, pointing to the hash node.
*/
typedef struct BSL_HASH_TagNode *BSL_HASH_Iterator;
/**
* @ingroup bsl_hash
* @brief Generates a hash table index based on the entered key.
* @param key [IN] hash key
* @param bktSize [IN] hash bucket size
*/
typedef uint32_t (*BSL_HASH_CodeCalcFunc)(uintptr_t key, uint32_t bktSize);
/**
* @ingroup bsl_hash
* @brief This function is used to match the input data with the key.
* Key1 stored in the hash table, and the key2 to be matched. If no, false is returned.
* @param key1 [IN] Key stored in the hash table
* @param key2 [IN] Key to be matched
* @retval #true key1 matches key2.
* @retval #false key1 and key2 do not match.
*/
typedef bool (*BSL_HASH_MatchFunc)(uintptr_t key1, uintptr_t key2);
/**
* @ingroup bsl_hash
* @brief Function for updating a node in the hash table.
* @par Description: This function is used to update the value of an existing node in the hash table.
* @attention
* 1. This function is called when a key already exists in the hash table and needs to be updated.
* 2. The user can provide a custom implementation of this function to handle specific update logic.
* @param hash [IN] Handle of the hash table.
* @param node [IN] Pointer to the node to be updated.
* @param value [IN] New value or address for storing the new value.
* @param valueSize [IN] Size of the new value. If the user has not registered a dupFunc, this parameter is not used.
* @retval #BSL_SUCCESS The node was successfully updated.
* @retval #BSL_INTERNAL_EXCEPTION Failed to update the node.
* @par Dependency: None
* @li bsl_hash.h: Header file where this function type is declared.
*/
typedef int32_t (*BSL_HASH_UpdateNodeFunc)(BSL_HASH_Hash *hash, BSL_HASH_Iterator node,
uintptr_t value, uint32_t valueSize);
/**
* @ingroup bsl_hash
* @brief Hash function.
* @par Description: Calculate the hash value based on the key value.
* The hash value does not modulate the size of the hash table and cannot be directly used for hash indexing.
* @attention
* 1. The key is the input parameter when the user invokes other interfaces.
* 2. If the key is an integer, you can use this function as the hashFunc parameter when creating a hash.
* @param key [IN] Key to be calculated.
* @param keySize [IN] Size of the key value.
* @retval #Hash value calculated based on the user key. The hash value is not modulated by the hash table size
* and cannot be directly used for hash indexing.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uint32_t BSL_HASH_CodeCalc(void *key, uint32_t keySize);
/**
* @ingroup bsl_hash
* @brief Default integer hash function.
* @par Default integer hash function.
* @attention
* 1. The key parameter is the input parameter when the user invokes other interfaces.
* 2. If the key is an integer, you can use this function as the hashFunc parameter when creating a hash.
* @param key [IN] Key to be calculated.
* @param bktSize [IN] Hash bucket size.
* @retval #Hash value calculated based on the user key.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uint32_t BSL_HASH_CodeCalcInt(uintptr_t key, uint32_t bktSize);
/**
* @ingroup bsl_hash
* @brief Default string hash function.
* @par Default string hash function.
* @attention
* 1. The key is an input parameter when the user invokes other interfaces.
* Ensure that the input key is a valid string start address.
* 2. If the key is a string, you can use this function as the hashFunc parameter when creating a hash.
* @param key [IN] Key to be calculated.
* @param bktSize [IN] Hash bucket size.
* @retval #Hash valueThe hash value calculated based on the user key.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uint32_t BSL_HASH_CodeCalcStr(uintptr_t key, uint32_t bktSize);
/**
* @ingroup bsl_hash
* @brief Default integer matching function.
* @par Default integer matching function.
* @attention
* 1. The key is the input parameter when the user invokes other interfaces.
* 2. If the key is an integer, you can use this function as the matchFunc parameter when creating a hash.
* @param key1 [IN] Key to be matched.
* @param key2 [IN] Key to be matched.
* @retval #true key1 matches key2.
* @retval #false key1 and key2 do not match.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
bool BSL_HASH_MatchInt(uintptr_t key1, uintptr_t key2);
/**
* @ingroup bsl_hash
* @brief Default string matching function.
* @par Default string matching function.
* @attention
* 1. Key1 is the input parameter when the user invokes other interfaces.
* Ensure that the input key1 is a valid string start address.
* 2. If the key is a string, you can use this function as the matchFunc parameter when creating the hash.
* @param key1 [IN] Key to be matched.
* @param key2 [IN] Key to be matched.
* @retval #true key1 matches key2.
* @retval #false key1 and key2 do not match.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
bool BSL_HASH_MatchStr(uintptr_t key1, uintptr_t key2);
/**
* @ingroup bsl_hash
* @brief Create a hash table and return the handle of the hash table.
* @attention
* 1. Copy functions for keys and data:
* You do not need to register the copy function in the following case:
* a) Data is the int type and the length <= sizeof(uintptr_t).
* The copy function must be registered in the following cases:
* a) Data is the int type, but the length is greater than sizeof(uintptr_t);
* b) string;
* c) User-defined data structure.
* 2. About the free function: Simply put, if the duplicate function is registered,
* the corresponding free function must be registered.
* 3. Provide the default integer and string hash functions: #BSL_HASH_CodeCalcInt and #BSL_HASH_CodeCalcStr.
* 4. Provide default integer and string matching functions: #BSL_HASH_MatchInt and #BSL_HASH_MatchStr.
* @param bktSize [IN] Number of hash buckets.
* @param hashCalcFunc [IN] Hash value calculation function.
* If the value is NULL, the default key is an integer. Use #BSL_HASH_CodeCalcInt.
* @param matchFunc [IN] hash key matching function.
* If the value is NULL, the default key is an integer. Use #BSL_HASH_MatchInt.
* @param keyFunc [IN] hash key copy and release function pair.
* If the keyFunc->dupFunc is not registered, the key is an integer by default.
* @param valueFunc [IN] hash data copy and release function pair.
* If the user has not registered valueFunc->dupFunc, the data type is an integer by default.
* @retval hash table handle. NULL indicates that the creation fails.
* @par Dependency: None
* @see #BSL_HASH_CodeCalcInt, #BSL_HASH_CodeCalcStr, #BSL_HASH_MatchInt, #BSL_HASH_MatchStr.
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Hash *BSL_HASH_Create(uint32_t bktSize, BSL_HASH_CodeCalcFunc hashFunc, BSL_HASH_MatchFunc matchFunc,
ListDupFreeFuncPair *keyFunc, ListDupFreeFuncPair *valueFunc);
/**
* @ingroup bsl_hash
* @brief Insert the hash data.
* @par Description: Create a node and insert data (key and value) into the hash table.
* @attention
* 1. Duplicate keys are not supported.
* 2. The key and value are integer values or addresses pointing to the user key or value.
* 3. If the life cycle of the extended data is shorter than the life cycle of the node,
* you need to register the copy function and release function when creating the hash table.
* @param hash [IN] handle of the hash table
* @param key [IN] key or address for storing the key
* @param keySize [IN] Copy length of key. If the user has not registered the dupFunc, this parameter is not used.
* @param value [IN] value or the address for storing the value.
* @param valueSize [IN] Copy length of value. If user has not registered the dupFunc, this parameter is not used.
* @retval #BSL_SUCCESS Succeeded in inserting the node.
* @retval #BSL_INTERNAL_EXCEPTION Insertion fails.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
int32_t BSL_HASH_Insert(BSL_HASH_Hash *hash, uintptr_t key, uint32_t keySize, uintptr_t value, uint32_t valueSize);
/**
* @ingroup bsl_hash
* @brief Insert or update the hash data.
* @par Description: This function is used to insert a nonexistent key into the hash table
* or update the value corresponding to an existing key.
* @attention
* 1. Duplicate keys are supported.
* 2. When the key does not exist, the usage of this function is the same as that of #BSL_HASH_Insert.
* 3. When the key exists, this function updates the value.
* @param hash [IN] Handle of the hash table.
* @param key [IN] key or address for storing the key.
* @param keySize [IN] Copy length of key. If the user has not registered the dupFunc, this parameter is not used.
* @param value [IN] value or the address for storing the value.
* @param valueSize [IN] Copy length of value. If user has not registered the dupFunc, this parameter is not used.
* @param updateNodeFunc [IN] Callback function for updating a node. If NULL, the default update function will be used.
* This function allows custom logic for updating existing nodes.
* @retval #BSL_SUCCESS Succeeded in inserting or updating the node.
* @retval #BSL_INTERNAL_EXCEPTION Failed to insert or update the node.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
int32_t BSL_HASH_Put(BSL_HASH_Hash *hash, uintptr_t key, uint32_t keySize, uintptr_t value, uint32_t valueSize,
BSL_HASH_UpdateNodeFunc updateNodeFunc);
/**
* @ingroup bsl_hash
* @brief Search for a node and return the node data.
* @par Description: Searches for and returns node data based on the key.
* @param hash [IN] Handle of the hash table.
* @param key [IN] key or address for storing the key.
* @param value [OUT] Data found.
* @retval #BSL_SUCCESS found successfully.
* @retval #BSL_INTERNAL_EXCEPTION query failed.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
int32_t BSL_HASH_At(const BSL_HASH_Hash *hash, uintptr_t key, uintptr_t *value);
/**
* @ingroup bsl_hash
* @brief Search for the iterator where the key is located.
* @par Description: Searches for and returns the iterator where the key is located based on the key.
* @param hash [IN] Handle of the hash table.
* @param key [IN] key or address for storing the key.
* @retval If the key exists, the iterator (pointing to the address of the node) where the key is located is returned.
* In other cases, #BSL_HASH_IterEnd() is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Iterator BSL_HASH_Find(const BSL_HASH_Hash *hash, uintptr_t key);
/**
* @ingroup bsl_hash
* @brief Check whether the current hash table is empty.
* @par Description: Check whether the current hash table is empty.
* If the hash table is empty, true is returned. Otherwise, false is returned.
* @param hash [IN] Handle of the hash table. The value range is valid pointer.
* @retval #true, indicating that the hash table is empty.
* @retval #false, indicating that the hash table is not empty.
* @see #BSL_HASH_Size
* @par Dependency: None
* @li bsl_hash.h: header file where the interface declaration is stored.
*/
bool BSL_HASH_Empty(const BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Obtain the number of nodes in the hash table.
* @par Description: Obtains the number of nodes in the hash table and returns the number of nodes.
* @param hash [IN] Handle of the hash table. The value range is valid pointer.
* @retval Number of hash nodes.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uint32_t BSL_HASH_Size(const BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Remove a specified node from the hash table.
* @par Description: Find the node based on the key, delete the node (release it),
* and release the memory of the corresponding node.
* @param hash [IN] Handle of the hash table. The value range is a valid pointer.
* @param key [IN] Remove a node key.
* @retval If the key exists,
* the next iterator (pointing to the address of the node) of the iterator where the key is located is returned.
* Otherwise, #BSL_HASH_IterEnd() is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Iterator BSL_HASH_Erase(BSL_HASH_Hash *hash, uintptr_t key);
/**
* @ingroup bsl_hash
* @brief Delete all nodes in the hash table.
* @par Description: Delete all nodes and reclaim the node memory. The hash table still exists, but there are no members
* @attention Note: If the user data contains private resources, need to register the free hook function during creation
* @param hash [IN] Handle of the hash table.
* @retval none.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
void BSL_HASH_Clear(BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Delete the hash table.
* @par Description: Delete the hash table. If a node exists in the table, delete the node first and reclaim the memory.
* @attention Note: If the user data contains private resources, need to register the free hook function during creation
* @param hash [IN] Handle of the hash table.
* @retval none.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
void BSL_HASH_Destory(BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Obtain the iterator of the first node in the hash table.
* @par Description: Obtains the iterator where the first node in the hash table is located.
* @param hash [IN] Handle of the hash table.
* @retval Iterator of the first node. If the hash is empty, #BSL_HASH_IterEnd() is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Iterator BSL_HASH_IterBegin(const BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Obtain the iterator reserved after the last node in the hash table.
* @par Description: Obtain the iterator reserved after the last node in the hash table.
* This node points to the last reserved hash bucket, which has no members.
* @param hash [IN] Handle of the hash table.
* @retval Iterator reserved after the last node.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Iterator BSL_HASH_IterEnd(const BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Obtain the iterator of the next node in the hash table.
* @par Description: Obtains the iterator of the next node in the hash table.
* @param hash [IN] Handle of the hash table.
* @param it [IN] Current iterator.
* @retval Next node iterator. If the current node is the last iterator, #BSL_HASH_IterEnd() is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Iterator BSL_HASH_IterNext(const BSL_HASH_Hash *hash, BSL_HASH_Iterator it);
/**
* @ingroup bsl_hash
* @brief Obtain the key of the iterator.
* @par Description: Obtains the current key of the iterator in the hash table.
* @attention
* 1. When the hash pointer is null or iterator it is equal to #BSL_HASH_IterEnd(), this function returns 0.
* This function cannot distinguish whether the error code or user data,
* 2. Before calling this function, ensure that hash is a valid pointer
* and iterator it is not equal to #BSL_HASH_IterEnd().
* @param hash [IN] Handle of the hash table.
* @param it [IN] Current iterator.
* @retval Key corresponding to the iterator. If iterator it equals #BSL_HASH_IterEnd(), 0 is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uintptr_t BSL_HASH_HashIterKey(const BSL_HASH_Hash *hash, BSL_HASH_Iterator it);
/**
* @ingroup bsl_hash
* @brief Obtain the value of the iterator.
* @par Description: Obtains the current value of the iterator in the hash table.
* @attention
* 1. When the hash pointer is null or it is equal to #BSL_HASH_IterEnd(), the interface returns 0.
* This function cannot distinguish whether the error code or user data,
* 2. Before calling this function, ensure that hash is a valid pointer
* and iterator it is not equal to #BSL_HASH_IterEnd().
* @param hash [IN] Handle of the hash table.
* @param it [IN] Current iterator.
* @retval Value corresponding to the iterator. If iterator it equals #BSL_HASH_IterEnd(), 0 is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uintptr_t BSL_HASH_IterValue(const BSL_HASH_Hash *hash, BSL_HASH_Iterator it);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_HASH */
#endif // BSL_HASH_H
| 2401_83913325/openHiTLS_1 | bsl/hash/include/bsl_hash.h | C | unknown | 18,600 |
/*
* 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 bsl_list bidirectional linked list
* @ingroup bsl
*/
#ifndef BSL_HASH_LIST_H
#define BSL_HASH_LIST_H
#include "hitls_build.h"
#ifdef HITLS_BSL_HASH
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @ingroup bsl_list
* @brief User data copy function prototype
* @attention Note: The source buffer length needs to be obtained by the caller.
* Because the data type and length are unknown, the hook function needs to be implemented by the service side.
* @param ptr [IN] Pointer to user data
* @param size [IN] User data copy length
* @retval Destination buffer. NULL indicates failure.
*/
typedef void *(*ListDupFunc)(void *ptr, size_t size);
/**
* @ingroup bsl_list
* @brief User memory release function prototype
* @par Description: resource release function prototype, which is generally used to release memory in batches.
* The memory may contain private resources, which need to be released by users.
* @param ptr [IN] Pointer to user data
* @retval None
*/
typedef void (*ListFreeFunc)(void *ptr);
/**
* @ingroup bsl_list
* @brief Match the function prototype.
* @par Description: used to match the query.
* @attention Note: Only the function prototype is defined here. Because the user query matching mechanism is unknown,
* the hook function needs to be implemented by the service side.
* @param node [IN] Algorithm structure node
* @param data [IN] Key information
* @retval true: Matching succeeded.
* @retval false Matching failure
*/
typedef bool (*ListMatchFunc)(const void *node, uintptr_t data);
/**
* @ingroup bsl_list
* @brief Compare function prototype
* @par Description: Compare function prototype, which is used in sorting.
* @attention Note: Only the comparison function prototype is defined here. The data type and length are unknown.
* Therefore, the hook function needs to be implemented by the service side.
* The current source code has a default comparison function. This function is not provided externally.
* If the default comparison method is not specified, it will be invoked.
* The comparison method is to convert the current data into a signed number for comparison,
* that is, to process the case with negative numbers in ascending order.
* If the data to be stored is of the unsigned integer type, The sorting result may not be expected at this time.
* To compare data in this case, we need to customize the comparison function.
* For example, for a BIGNUM A = uintptr_t(-1) and a BIGNUM B = 1ULL << 50, the current function considers A < B.
* Actually, A is greater than B.
* To sum up, the user should write the comparison function based on the data type
* (including descending order or other comparison rules).
*/
typedef int32_t (*ListKeyCmpFunc)(uintptr_t key1, uintptr_t key2);
/**
* @ingroup bsl_list
* @brief Hook for saving memory application and release.
*/
typedef struct {
ListDupFunc dupFunc;
ListFreeFunc freeFunc;
} ListDupFreeFuncPair;
/**
* @ingroup bsl_list
* list header
*/
typedef struct BslListSt BSL_List;
/**
* @ingroup bsl_list
* Linked list iterator (node) definition
*/
typedef struct BslListNodeSt *BSL_ListIterator;
/**
* @ingroup bsl_list
* @brief Initialize the linked list.
* @par Description: Initialize the linked list and
* register the user data dup function and user data resource free function as required.
* @attention
* 1. If the data to be stored is of the integer type and the length <= sizeof(uintptr_t),
* do not need to register dataFunc&dupFunc and assign it empty.
* 2. If the user data is string or other customized complex data type
* and the data life cycle is shorter than the node life cycle, user must register dataFunc->dupFunc for data copy.
* @param list [IN] Linked list
* @param dataFunc [IN] User data copy and release function pair. If dataFunc and dupFunc are not registered,
* the default data type is integer.
* @retval #BSL_SUCCESS 0 indicates that the linked list is successfully initialized.
*/
int32_t BSL_ListInit(BSL_List *list, const ListDupFreeFuncPair *dataFunc);
/**
* @ingroup bsl_list
* @brief Clear the node in the linked list and delete all nodes.
* @par Description: Clear the linked list node, delete all nodes, invoke the free function registered by the user
* to release user resources, and return to the status after initialization of the linked list.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The linked list is cleared successfully.
*/
int32_t BSL_ListClear(BSL_List *list);
/**
* @ingroup bsl_list
* @brief Deinitialize the linked list.
* @par Description: Deinitialize the linked list: Delete all nodes,
* invoke the free function registered by the user to release user resources, and deregister the hook function.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The linked list is successfully de-initialized.
*/
int32_t BSL_ListDeinit(BSL_List *list);
/**
* @ingroup bsl_list
* @brief Check whether the linked list is empty.
* @param list [IN] Linked list to be checked
* @retval #true 1: The linked list is null or no data exists.
* @retval #false 0: The linked list is not empty.
* @li bsl_list.h: header file where the API declaration is located.
*/
bool BSL_ListIsEmpty(const BSL_List *list);
/**
* @ingroup bsl_list
* @brief Obtain the number of nodes in the linked list.
* @param list [IN] Linked list
* @retval Number of linked list nodes
* @li bsl_list.h: header file where the API declaration is located.
*/
size_t BSL_ListSize(const BSL_List *list);
/**
* @ingroup bsl_list
* @brief Insert user data into the header of the linked list.
* @param list [IN] Linked list
* @param userData [IN] Data to be inserted or pointer to user private data
* @param userDataSize [IN] Data copy length. If the user has not registered the dupFunc, this parameter is not used.
* @retval #BSL_SUCCESS Data is successfully inserted.
* @li bsl_list.h: header file where this function declaration is located.
*/
int32_t BSL_ListPushFront(BSL_List *list, uintptr_t userData, size_t userDataSize);
/**
* @ingroup bsl_list
* @brief Insert user data to the end of the linked list.
* @param list [IN] Linked list
* @param userData [IN] Data to be inserted or pointer to user private data
* @param userDataSize [IN] Data copy length. If the user has not registered the dupFunc, this parameter is not used.
* @retval #BSL_SUCCESS Data is successfully inserted.
* @li bsl_list.h: header file where this function declaration is located.
*/
int32_t BSL_ListPushBack(BSL_List *list, uintptr_t userData, size_t userDataSize);
/**
* @ingroup bsl_list
* @brief POP a node from the header of the linked list.
* @par Description: Remove the head node from the linked list and release the node memory.
* If the free function is registered during initialization, the hook function is called to release private resources.
* If the linked list is empty, nothing will be done.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The header is removed successfully.
* @li bsl_list.h: header file where the API declaration is located.
*/
int32_t BSL_ListPopFront(BSL_List *list);
/**
* @ingroup bsl_list
* @brief POP a node from the end of the linked list.
* @par Description: Remove the tail node from the linked list and release the node memory.
* If the free function is registered during initialization, the hook function is called to release private resources.
* If the linked list is empty, nothing will be done.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The tail is removed successfully.
* @li bsl_list.h: header file where the API declaration is located.
*/
int32_t BSL_ListPopBack(BSL_List *list);
/**
* @ingroup bsl_list
* @brief Access the header node of the linked list and return the user data of the header node.
* @par Description: Access the header node of the linked list and return the user data of the header node.
* @attention Note: If the linked list is empty,
* it cannot be distinguished whether the linked list is empty and the returned data is 0.
* Therefore, before calling this function, we must check whether the linked list is empty.
* @param list [IN] Linked list
* @retval User data/pointer of the head node. If the linked list is empty, 0 is returned.
* @li bsl_list.h: header file where this function declaration is located.
*/
uintptr_t BSL_ListFront(const BSL_List *list);
/**
* @ingroup bsl_list
* @brief Access the tail node of the linked list and return the user data of the tail node.
* @attention Note: If the linked list is empty,
* it cannot be distinguished whether the linked list is empty and the returned data is 0.
* Therefore, we must check whether the linked list is empty before calling this function.
* @param list [IN] Linked list
* @retval User data/pointer of the tail node. If the linked list is empty, 0 is returned.
* @li bsl_list.h: header file where the API declaration is located.
*/
uintptr_t BSL_ListBack(const BSL_List *list);
/**
* @ingroup bsl_list
* @brief Obtain the iterator of the header node of the linked list.
* @param list [IN] Linked list
* @retval Head node iterator of the linked list. If the linked list is empty, it points to the header.
* @li bsl_list.h: header file where this function declaration is located.
*/
BSL_ListIterator BSL_ListIterBegin(const BSL_List *list);
/**
* @ingroup bsl_list
* @brief Obtain the iterator of the next node of the tail.
* @param list [IN] Linked list
* @attention If the input list is NULL, NULL will be returned. Therefore, user need to use correct parameters.
* @retval Next node iterator of the tail (pointing to the head of the linked list).
* @li bsl_list.h: header file where the API declaration is located.
*/
BSL_ListIterator BSL_ListIterEnd(BSL_List *list);
/**
* @ingroup bsl_list
* @brief Obtain the iterator of the previous node.
* @param list [IN] Linked list
* @param it [IN] Iterator
* @attention If the input list is NULL or iterator it is not a valid part of the list, NULL is returned.
* Therefore, user need to use the correct parameter.
* @retval list is not empty, return the previous node iterator.
* @retval list is NULL, and NULL is returned.
* @li bsl_list.h: header file where the API declaration is located.
*/
BSL_ListIterator BSL_ListIterPrev(const BSL_List *list, const BSL_ListIterator it);
/**
* @ingroup bsl_list
* @brief Obtain the iterator of the next node.
* @param list [IN] Linked list
* @param it [IN] Iterator
* @attention If the input list is NULL or iterator it is not a valid part of the list, NULL is returned.
* Therefore, user need to use the correct parameter.
* @retval Returns the iterator of the next node if the value is not null.
* @retval list is NULL, and NULL is returned.
* @li bsl_list.h: header file where the API declaration is located.
*/
BSL_ListIterator BSL_ListIterNext(const BSL_List *list, const BSL_ListIterator it);
/**
* @ingroup bsl_list
* @brief Insert data before the node pointed to by the specified iterator.
* @param list [IN] Linked list
* @param it [IN] Current iterator position
* @param userData [IN] Data to be inserted or pointer to user private data
* @param userDataSize [IN] Data copy length. If the user has not registered the dupFunc, this parameter is not used.
* @retval #BSL_SUCCESS Data is successfully inserted.
* @li bsl_list.h: header file where this function declaration is located.
*/
int32_t BSL_ListInsert(BSL_List *list, const BSL_ListIterator it, uintptr_t userData, size_t userDataSize);
/**
* @ingroup bsl_list
* @brief Delete a specified node from the linked list and release the node memory.
* @par Description: Delete the specified node from the linked list and release the node memory.
* If the free function is registered during initialization,
* the hook function is invoked to release private resources such as handles and pointers in user data
* @attention If the input list is NULL or iterator it is not a valid part of the list, NULL is returned.
* Therefore, user need to use the correct parameter.
* @param list [IN] Linked list
* @param it [IN] Iterator of the node to be deleted.
* @retval Next node iterator of the deleted node. If the deleted node is the tail node,
* the returned iterator points to the header of the linked list.
* @li bsl_list.h: header file where this function declaration is located.
*/
BSL_ListIterator BSL_ListIterErase(BSL_List *list, BSL_ListIterator it);
/**
* @ingroup bsl_list
* @brief Obtain user data.
* @attention The caller must ensure the validity of the parameter. If the input parameter is invalid, 0 is returned.
* The caller cannot distinguish whether the returned value 0 is normal data
* or whether the returned value is 0 due to invalid parameters.
* @param it [IN] Linked list iterator
* @retval User data
* @li bsl_list.h: header file where this function declaration is located.
*/
uintptr_t BSL_ListIterData(const BSL_ListIterator it);
/**
* @ingroup bsl_list
* @brief Searches for the desired iterator, that is, the node pointer,
* based on the user-defined iterator matching function.
* @par Description: Searches for the desired iterator, that is, the node pointer,
* based on the user-defined iterator matching function.
* @attention
* 1. Traversefrom the header and call the matching function for each node in turn
* until the first matching node is found or the traversal ends at the tail of the linked list.
* 2. The first input parameter address of the matching function hook entered by the user
* is the userdata of each node to be searched. The input parameter type is uintptr_t.
* 3. If the input list is NULL or the comparison function is NULL, NULL is returned.
* Therefore, user need to use correct parameters.
* @param list [IN] Linked list
* @param iterCmpFunc [IN] Hook of match function.
* @param data [IN] Data information
* @retval not NULL Query succeeded, the matching node iterator is returned.
* @retval NULL Query failed.
* @li bsl_list.h: header file where this function declaration is located.
*/
BSL_ListIterator BSL_ListIterFind(BSL_List *list, ListKeyCmpFunc iterCmpFunc, uintptr_t data);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_HASH */
#endif // BSL_HASH_LIST_H
| 2401_83913325/openHiTLS_1 | bsl/hash/include/bsl_hash_list.h | C | unknown | 15,245 |
/*
* 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 list_base Raw bidirectional linked list
* @ingroup bsl
*/
#ifndef LIST_BASE_H
#define LIST_BASE_H
#include "hitls_build.h"
#ifdef HITLS_BSL_HASH
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include "bsl_hash_list.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @ingroup bsl_base
* This struct is used to store the forward pointer and backward pointer of the node in the bidirectional linked list.
* This linked list does not contain a substantial data area and is generally used to organize (concatenate) data nodes.
*/
struct ListTagRawListNode {
struct ListTagRawListNode *next; /* points to the next node */
struct ListTagRawListNode *prev; /* points to the previous node */
};
/**
* @ingroup bsl_base
* list node
*/
typedef struct ListTagRawListNode ListRawNode;
/**
* @ingroup bsl_base
* Linked list header, which cannot store data.
*/
typedef struct {
ListRawNode head; /* list node */
/* Node memory release function, which needs to release nodes and other private resources on node */
ListFreeFunc freeFunc;
} RawList;
/**
* @ingroup bsl_base
* Linked list header, which can apply for data memory and is used by external functions.
*/
struct BslListSt {
RawList rawList; /* Linked list header */
ListDupFreeFuncPair dataFunc; /* used to store data */
};
/**
* @ingroup bsl_base
* Bidirectional linked list node.
* This structure is used to store the forward pointer and backward pointer of the nodes in the bidirectional list,
* and a small amount of user data or pointers.
*/
struct BslListNodeSt {
ListRawNode rawNode;
uintptr_t userdata;
};
/**
* @ingroup bsl_base
* @brief Initialize the linked list.
* @par Description: Initializes the list, registers the private resource release function in user data as required.
* This function does not apply for resources.
* @attention
* 1: The linked list nodes in the crawlist module are encapsulated and memory is applied for by users.
* The rawlist is only used to maintain the linked list, and its resources are released by users in freeFunc.
* 2: When a user adds data, the parameter transferred to the rawlist is the ListRawNode node.
* Therefore, the parameter transferred to the freeFunc by the rawlist is also the ListRawNode node.
* @param list [IN] Linked list.
* @param freeFunc [IN] User resource release function.
* @retval #BSL_SUCCESS 0. The linked list is successfully initialized.
*/
int32_t ListRawInit(RawList *list, ListFreeFunc freeFunc);
/**
* @ingroup bsl_base
* @brief Clear the node in the linked list and delete all nodes.
* @par Description: Clear the linked list node, delete all nodes,
* invoke the free function registered by the user to release private resources,
* and return to the status after initialization of the linked list.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The linked list is cleared successfully.
*/
int32_t ListRawClear(RawList *list);
/**
* @ingroup bsl_base
* @brief Deinitialize the linked list.
* @par Description: Deinitialize the linked list:
* Delete all nodes, invoke the free function registered by the user to release private resources,
* and deregister the hook function. But the list head is still there.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The linked list is successfully deinitialized.
*/
int32_t ListRawDeinit(RawList *list);
/**
* @ingroup bsl_base
* @brief Check whether the linked list is empty.
* @param list [IN] Linked list to be checked
* @retval #true 1. The linked list is empty or has no data.
* @retval #false 0. The linked list is not empty.
* @li bsl_base.h: header file where the function declaration is located.
*/
bool ListRawEmpty(const RawList *list);
/**
* @ingroup bsl_base
* @brief Obtain the number of nodes in the linked list.
* @param list [IN] Linked list
* @retval Number of linked list nodes
* @li bsl_base.h: header file where the function declaration is located.
*/
size_t ListRawSize(const RawList *list);
/**
* @ingroup bsl_base
* @brief Insert a node at the header of the linked list.
* @param list [IN] Linked list
* @param node [IN] Node to be inserted
* @retval #BSL_SUCCESS 0. Inserted successfully in the header of the linked list.
*/
int32_t ListRawPushFront(RawList *list, ListRawNode *node);
/**
* @ingroup bsl_base
* @brief Insert a node at the end of the linked list.
* @param list [IN] Linked list
* @param node [IN] Node to be inserted
* @retval #BSL_SUCCESS 0. Inserted successfully in the tail of the linked list.
*/
int32_t ListRawPushBack(RawList *list, ListRawNode *node);
/**
* @ingroup bsl_base
* @brief Insert a node before a specified node.
* @param curNode [IN] Specified node
* @param newNode [IN] Node to be inserted
* @retval #BSL_SUCCESS 0 indicates that the linked list is inserted successfully.
*/
int32_t ListRawInsert(const ListRawNode *curNode, ListRawNode *newNode);
/**
* @ingroup bsl_base
* @brief POP a node from the header of the linked list.
* @par Description: Removes the head node from the linked list.
* If the free function is registered during initialization, the hook function is also called to release user resources.
* If the linked list is empty, nothing will be done.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The header of the linked list is popped successfully.
*/
int32_t ListRawPopFront(RawList *list);
/**
* @ingroup bsl_base
* @brief POP a node from the end of the linked list.
* @par Description: Remove the tail node from the linked list.
* If the free function is registered during initialization, the hook function is also called to release user resources.
* If the linked list is empty, nothing will be done.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The tail of the linked list is popped successfully.
*/
int32_t ListRawPopBack(RawList *list);
/**
* @ingroup bsl_base
* @brief Delete a specified node from the linked list.
* @par Description:
* 1. If the list is NULL and the node is in the linked list, only the node is removed from the linked list.
* 2. If the list is not null and the node is in the linked list, the node is removed from the linked list.
* If the free function is registered during initialization, the hook function is invoked to release user resources.
* @param list [IN] Linked list
* @param node [IN] Node to be deleted
* @retval #BSL_SUCCESS 0. The linked list is deleted successfully.
* @li bsl_base.h: header file where the function declaration is located.
*/
int32_t ListRawRemove(RawList *list, ListRawNode *node);
/**
* @ingroup bsl_base
* @brief Return the head node pointer.
* @par Description: It is used only to access the head node and will not delete the node.
* If the linked list is NULL, NULL is returned.
* @param list [IN] Linked list
* @attention If the input parameter is incorrect, NULL is returned. The user needs to use the correct parameter.
* @retval not NULL Pointer to the head node.
* @retval NULL The linked list is NULL.
* @li bsl_base.h: header file where the function declaration is located.
*/
ListRawNode *ListRawFront(const RawList *list);
/**
* @ingroup bsl_base
* @brief Return the tail node pointer.
* @par Description: It is used only to access the tail node and will not delete the tail node.
* If the linked list is NULL, NULL is returned.
* @param list [IN] Linked list
* @attention If the input parameter is incorrect, NULL is returned. The user needs to use the correct parameter.
* @retval not NULL Pointer to the tail node.
* @retval NULL The linked list is NULL.
* @li bsl_base.h: header file where the function declaration is located.
*/
ListRawNode *ListRawBack(const RawList *list);
/**
* @ingroup bsl_base
* @brief Obtain the previous node of the current node.
* @par Description: Obtains the pointer of the previous node of the current node.
* If the current node is the head node, NULL is returned.
* @param list [IN] Linked list
* @param node [IN] Current node
* @attention If the input parameter is incorrect, NULL is returned. The user needs to use the correct parameter.
* @retval Non-NULL Previous node of the current node
* @retval NULL The previous node of the head node is empty.
* @li bsl_base.h: header file where the function declaration is located.
*/
ListRawNode *ListRawGetPrev(const RawList *list, const ListRawNode *node);
/**
* @ingroup bsl_base
* @brief Obtain the next node of the current node.
* @par Description: Obtains the pointer to the next node of the current node.
* If the current node is the tail node, NULL is returned.
* @param list [IN] Linked list
* @param node [IN] Current node
* @attention If the input parameter is incorrect, NULL is returned. The user needs to use the correct parameter.
* @retval: non-NULL node next to the current node
* @retval: NULL The next node of the tail node is null.
* @li bsl_base.h: header file where the function declaration is located.
*/
ListRawNode *ListRawGetNext(const RawList *list, const ListRawNode *node);
/**
* @ingroup bsl_base
* @brief Searches for the desired node based on the node matching function defined by the user.
* @par Description: Searches for the desired node based on the node matching function defined by the user.
* @attention
* 1. Traverse from the header of the linked list and call the matching function for each node in turn
* until the first matching node is found or the traversal ends at the tail of the linked list.
* 2. Hook of the matching function entered by the user.
* Its first input parameter address is the value of each node to be searched.
* The input parameter type is ListRawNode *.
* 3. For the implementation in the matching hook,
* needs to be offset to the user structure information according to the node address before matching and comparison.
* 4. If the input parameter is incorrect, NULL is returned. The user needs to use the correct parameter.
* @param list [IN] Linked list
* @param nodeMatchFunc [IN] hook of match function.
* @param data [IN] critical information
* @retval non-NULL The query is successful, the node pointer is returned.
* @retval NULL Query failed. No matching node is found.
* @li bsl_base.h: header file where the function declaration is located.
*/
ListRawNode *ListRawFindNode(const RawList *list, ListMatchFunc nodeMatchFunc, uintptr_t data);
/**
* @ingroup bsl_base
* @brief This API obtains the start address of the structure through a member variable of the structure.
* @par Description:
* This API obtains the start address of the structure through a member variable of the structure.
* This API is a special macro, and the input parameters depend on the implementation of the macro.
* @attention
* @param ptr [IN] The address of a member on a node. The value range is Data Type.
* @param type [IN] The node type structure to which the transferred member belongs. The value range is Data Type.
* @param member [IN] The name of a member variable in the structure. The value range is Data Type.
* @retval Address of the same structure as the input parameter type.
* @see none.
*/
#define BSL_CONTAINER_OF(ptr, type, member) \
((type *)((uintptr_t)(ptr) - (uintptr_t)(&(((type *)0)->member))))
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_HASH */
#endif // LIST_BASE_H
| 2401_83913325/openHiTLS_1 | bsl/hash/include/list_base.h | C | unknown | 11,982 |
/*
* 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_BSL_HASH
#include "securec.h"
#include "bsl_sal.h"
#include "list_base.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "hash_local.h"
#include "bsl_hash.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define BSL_CSTL_HASH_OPTION3 3
#define BSL_CSTL_HASH_OPTION2 2
#define BSL_CSTL_HASH_OPTION1 1
struct BSL_HASH_TagNode {
ListRawNode node; /**< Linked list node */
uintptr_t key; /**< Key or address for storing the key */
uintptr_t value; /**< value or address for storing the value */
};
typedef struct BSL_HASH_TagNode BSL_HASH_Node;
struct BSL_HASH_Info {
ListDupFreeFuncPair keyFunc; /**< key Copy and release function pair */
ListDupFreeFuncPair valueFunc; /**< value Copy and release function pair */
BSL_HASH_MatchFunc matchFunc; /**< matching function */
BSL_HASH_CodeCalcFunc hashFunc; /**< hash function */
uint32_t bucketSize; /**< hash table size */
uint32_t hashCount; /**< number of entries in the hash table */
RawList listArray[0]; /**< linked list control block array*/
};
/* murmurhash algorithm */
/* define constants */
#define HASH_VC1 0xCC9E2D51
#define HASH_VC2 0x1B873593
#define HASH_HC1 0xE6546B64
#define HASH_HC2 0x85EBCA6B
#define HASH_HC3 0xC2B2AE35
#define HASH_HC4 5
#define CHAR_BIT 8
#define CHAR_FOR_PER_LOOP 4
#define HASH_V_ROTATE 15
#define HASH_H_ROTATE 13
#define SYS_BUS_WIDTH sizeof(uint32_t)
#define HASH_SEED 0x3B9ACA07 /* large prime 1000000007. The seed can be random or specified. */
enum BSL_CstlByte {
ONE_BYTE = 1,
TWO_BYTE = 2,
};
enum BSL_CstlShiftBit { SHIFT8 = 8, SHIFT13 = 13, SHIFT16 = 16, SHIFT24 = 24 };
static uint32_t BSL_HASH_Rotate(uint32_t v, uint32_t offset)
{
return ((v << offset) | (v >> (SYS_BUS_WIDTH * CHAR_BIT - offset)));
}
static uint32_t BSL_HASH_MixV(uint32_t v)
{
uint32_t res = v;
res = res * HASH_VC1;
res = BSL_HASH_Rotate(res, HASH_V_ROTATE);
return res * HASH_VC2;
}
static uint32_t BSL_HASH_MixH(uint32_t h, uint32_t v)
{
uint32_t res = h;
res ^= v;
res = BSL_HASH_Rotate(res, HASH_H_ROTATE);
return res * HASH_HC4 + HASH_HC1;
}
uint32_t BSL_HASH_CodeCalc(void *key, uint32_t keySize)
{
uint8_t *tmpKey = (uint8_t *)key;
uint32_t i = 0;
uint32_t v;
uint32_t h = HASH_SEED;
uint8_t c0, c1, c2, c3;
uint32_t tmpLen = keySize - keySize % CHAR_FOR_PER_LOOP;
while ((i + CHAR_FOR_PER_LOOP) <= tmpLen) {
c0 = tmpKey[i++];
c1 = tmpKey[i++];
c2 = tmpKey[i++];
c3 = tmpKey[i++];
v = (uint32_t)c0 | ((uint32_t)c1 << SHIFT8) | ((uint32_t)c2 << SHIFT16) | ((uint32_t)c3 << SHIFT24);
v = BSL_HASH_MixV(v);
h = BSL_HASH_MixH(h, v);
}
v = 0;
switch (keySize & BSL_CSTL_HASH_OPTION3) {
case BSL_CSTL_HASH_OPTION3:
v ^= ((uint32_t)tmpKey[i + TWO_BYTE] << SHIFT16);
/* (keySize % 4) is equals 3, fallthrough, other branches are the same. */
/* fall-through */
case BSL_CSTL_HASH_OPTION2:
v ^= ((uint32_t)tmpKey[i + ONE_BYTE] << SHIFT8);
/* fall-through */
case BSL_CSTL_HASH_OPTION1:
v ^= tmpKey[i];
v = BSL_HASH_MixV(v);
h ^= v;
break;
default:
break;
}
h ^= h >> SHIFT16;
h *= HASH_HC2;
h ^= h >> SHIFT13;
h *= HASH_HC3;
h ^= h >> SHIFT16;
return h;
}
/* internal function definition */
static void BSL_HASH_HookRegister(BSL_HASH_Hash *hash, BSL_HASH_CodeCalcFunc hashFunc,
BSL_HASH_MatchFunc matchFunc, ListDupFreeFuncPair *keyFunc, ListDupFreeFuncPair *valueFunc)
{
ListDupFreeFuncPair *hashKeyFunc = &hash->keyFunc;
ListDupFreeFuncPair *hashValueFunc = &hash->valueFunc;
hash->hashFunc = hashFunc == NULL ? BSL_HASH_CodeCalcInt : hashFunc;
hash->matchFunc = matchFunc == NULL ? BSL_HASH_MatchInt : matchFunc;
if (keyFunc == NULL) {
hashKeyFunc->dupFunc = NULL;
hashKeyFunc->freeFunc = NULL;
} else {
hashKeyFunc->dupFunc = keyFunc->dupFunc;
hashKeyFunc->freeFunc = keyFunc->freeFunc;
}
if (valueFunc == NULL) {
hashValueFunc->dupFunc = NULL;
hashValueFunc->freeFunc = NULL;
} else {
hashValueFunc->dupFunc = valueFunc->dupFunc;
hashValueFunc->freeFunc = valueFunc->freeFunc;
}
}
static inline BSL_HASH_Iterator BSL_HASH_IterEndGet(const BSL_HASH_Hash *hash)
{
return (BSL_HASH_Iterator)(uintptr_t)(&hash->listArray[hash->bucketSize].head);
}
static BSL_HASH_Node *BSL_HASH_NodeCreate(
const BSL_HASH_Hash *hash, uintptr_t key, uint32_t keySize, uintptr_t value, uint32_t valueSize)
{
uintptr_t tmpKey;
uintptr_t tmpValue;
BSL_HASH_Node *hashNode = NULL;
void *tmpPtr = NULL;
hashNode = (BSL_HASH_Node *)BSL_SAL_Malloc(sizeof(BSL_HASH_Node));
if (hashNode == NULL) {
return NULL;
}
if (hash->keyFunc.dupFunc != NULL) {
tmpPtr = hash->keyFunc.dupFunc((void *)key, keySize);
tmpKey = (uintptr_t)tmpPtr;
if (tmpKey == (uintptr_t)NULL) {
BSL_SAL_FREE(hashNode);
return NULL;
}
} else {
tmpKey = key;
}
if (hash->valueFunc.dupFunc != NULL) {
tmpPtr = hash->valueFunc.dupFunc((void *)value, valueSize);
tmpValue = (uintptr_t)tmpPtr;
if (tmpValue == (uintptr_t)NULL) {
if (hash->keyFunc.freeFunc != NULL) {
hash->keyFunc.freeFunc((void *)tmpKey);
}
BSL_SAL_FREE(hashNode);
return NULL;
}
} else {
tmpValue = value;
}
hashNode->key = tmpKey;
hashNode->value = tmpValue;
return hashNode;
}
static BSL_HASH_Node *BSL_HASH_FindNode(const RawList *list, uintptr_t key, BSL_HASH_MatchFunc matchFunc)
{
BSL_HASH_Node *hashNode = NULL;
ListRawNode *rawListNode = NULL;
for (rawListNode = ListRawFront(list); rawListNode != NULL; rawListNode = ListRawGetNext(list, rawListNode)) {
hashNode = BSL_CONTAINER_OF(rawListNode, BSL_HASH_Node, node);
if (matchFunc(hashNode->key, key)) {
return hashNode;
}
}
return NULL;
}
static BSL_HASH_Iterator BSL_HASH_Front(const BSL_HASH_Hash *hash)
{
uint32_t i = 0;
const RawList *list = NULL;
ListRawNode *rawListNode = NULL;
while (i < hash->bucketSize) {
list = &hash->listArray[i];
rawListNode = ListRawFront(list);
if (rawListNode != NULL) {
return BSL_CONTAINER_OF(rawListNode, BSL_HASH_Node, node);
}
i++;
}
return BSL_HASH_IterEndGet(hash);
}
static BSL_HASH_Iterator BSL_HASH_Next(const BSL_HASH_Hash *hash, BSL_HASH_Iterator hashNode)
{
uint32_t i;
uint32_t hashCode;
const RawList *list = NULL;
ListRawNode *rawListNode = NULL;
hashCode = hash->hashFunc(hashNode->key, hash->bucketSize);
if (hashCode >= hash->bucketSize) {
return BSL_HASH_IterEndGet(hash);
}
list = hash->listArray + hashCode;
rawListNode = ListRawGetNext(list, &hashNode->node);
if (rawListNode != NULL) {
return BSL_CONTAINER_OF(rawListNode, BSL_HASH_Node, node);
}
for (i = hashCode + 1; i < hash->bucketSize; ++i) {
list = &hash->listArray[i];
rawListNode = ListRawFront(list);
if (rawListNode != NULL) {
return BSL_CONTAINER_OF(rawListNode, BSL_HASH_Node, node);
}
}
return BSL_HASH_IterEndGet(hash);
}
static void BSL_HASH_NodeFree(BSL_HASH_Hash *hash, BSL_HASH_Node *node)
{
ListFreeFunc keyFreeFunc = hash->keyFunc.freeFunc;
ListFreeFunc valueFreeFunc = hash->valueFunc.freeFunc;
if (keyFreeFunc != NULL) {
keyFreeFunc((void *)node->key);
}
if (valueFreeFunc != NULL) {
valueFreeFunc((void *)node->value);
}
BSL_SAL_FREE(node);
}
#ifdef HITLS_BIG_ENDIAN
static uintptr_t BSL_HASH_BigToLittleEndian(uintptr_t value)
{
uintptr_t result = 0;
size_t size = sizeof(uintptr_t);
// Manually flip byte order
for (size_t i = 0; i < size; i++) {
// Extract the i-th byte from big-endian order (starting from the most significant bit)
uintptr_t byte = (value >> CHAR_BIT * (size - 1 - i)) & 0xFF;
// Place at the i-th position in little-endian order (starting from the least significant bit)
result |= byte << (CHAR_BIT * i);
}
return result;
}
#endif
uint32_t BSL_HASH_CodeCalcInt(uintptr_t key, uint32_t bktSize)
{
uintptr_t convertKey =
#ifdef HITLS_BIG_ENDIAN
BSL_HASH_BigToLittleEndian(key);
#else
key;
#endif
return BSL_HASH_CodeCalc(&convertKey, sizeof(convertKey)) % bktSize;
}
bool BSL_HASH_MatchInt(uintptr_t key1, uintptr_t key2)
{
return key1 == key2;
}
uint32_t BSL_HASH_CodeCalcStr(uintptr_t key, uint32_t bktSize)
{
char *tmpKey = (char *)key;
return BSL_HASH_CodeCalc(tmpKey, (uint32_t)strlen(tmpKey)) % bktSize;
}
bool BSL_HASH_MatchStr(uintptr_t key1, uintptr_t key2)
{
char *tkey1 = (char *)key1;
char *tkey2 = (char *)key2;
return strcmp(tkey1, tkey2) == 0;
}
BSL_HASH_Hash *BSL_HASH_Create(uint32_t bktSize, BSL_HASH_CodeCalcFunc hashFunc, BSL_HASH_MatchFunc matchFunc,
ListDupFreeFuncPair *keyFunc, ListDupFreeFuncPair *valueFunc)
{
uint32_t i;
uint32_t size;
BSL_HASH_Hash *hash = NULL;
RawList *listAddr = NULL;
if (bktSize == 0U) {
return NULL;
}
size = (bktSize + 1) * sizeof(RawList);
if (IsMultiOverflow((bktSize + 1), sizeof(RawList)) || IsAddOverflow(size, sizeof(BSL_HASH_Hash))) {
return NULL;
}
size += sizeof(BSL_HASH_Hash);
hash = (BSL_HASH_Hash *)BSL_SAL_Malloc(size);
if (hash == NULL) {
return NULL;
}
(void)memset_s(hash, size, 0, size);
hash->bucketSize = bktSize;
BSL_HASH_HookRegister(hash, hashFunc, matchFunc, keyFunc, valueFunc);
listAddr = hash->listArray;
for (i = 0; i <= bktSize; ++i) {
ListRawInit(listAddr + i, NULL);
}
return hash;
}
static int32_t BSL_HASH_InsertNode(
BSL_HASH_Hash *hash, RawList *rawList, const BSL_CstlUserData *inputKey, const BSL_CstlUserData *inputValue)
{
BSL_HASH_Node *hashNode = BSL_HASH_NodeCreate(
hash, inputKey->inputData, inputKey->dataSize, inputValue->inputData, inputValue->dataSize);
if (hashNode == NULL) {
BSL_ERR_PUSH_ERROR(BSL_INTERNAL_EXCEPTION);
return BSL_INTERNAL_EXCEPTION;
}
ListRawPushBack(rawList, &hashNode->node);
hash->hashCount++;
return BSL_SUCCESS;
}
static int32_t BSL_HASH_UpdateNode(const BSL_HASH_Hash *hash, BSL_HASH_Node *node, uintptr_t value, uint32_t valueSize)
{
uintptr_t tmpValue;
void *tmpPtr = NULL;
if (hash->valueFunc.dupFunc != NULL) {
tmpPtr = hash->valueFunc.dupFunc((void *)value, valueSize);
tmpValue = (uintptr_t)tmpPtr;
if (tmpValue == (uintptr_t)NULL) {
BSL_ERR_PUSH_ERROR(BSL_INTERNAL_EXCEPTION);
return BSL_INTERNAL_EXCEPTION;
}
if (hash->valueFunc.freeFunc != NULL) {
hash->valueFunc.freeFunc((void *)node->value);
}
} else {
tmpValue = value;
}
node->value = tmpValue;
return BSL_SUCCESS;
}
static inline int32_t BSL_HASH_CodeCheck(const BSL_HASH_Hash *hash, uintptr_t key, uint32_t *hashCode)
{
if (hash == NULL) {
BSL_ERR_PUSH_ERROR(BSL_INTERNAL_EXCEPTION);
return BSL_INTERNAL_EXCEPTION;
}
*hashCode = hash->hashFunc(key, hash->bucketSize);
if (*hashCode >= hash->bucketSize) {
BSL_ERR_PUSH_ERROR(BSL_INTERNAL_EXCEPTION);
return BSL_INTERNAL_EXCEPTION;
}
return BSL_SUCCESS;
}
int32_t BSL_HASH_Insert(BSL_HASH_Hash *hash, uintptr_t key, uint32_t keySize, uintptr_t value, uint32_t valueSize)
{
int32_t ret;
uint32_t hashCode;
BSL_HASH_Node *hashNode = NULL;
RawList *rawList = NULL;
BSL_CstlUserData inputKey;
BSL_CstlUserData inputValue;
ret = BSL_HASH_CodeCheck(hash, key, &hashCode);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(BSL_INTERNAL_EXCEPTION);
return BSL_INTERNAL_EXCEPTION;
}
rawList = &hash->listArray[hashCode];
hashNode = BSL_HASH_FindNode(rawList, key, hash->matchFunc);
if (hashNode != NULL) {
BSL_ERR_PUSH_ERROR(BSL_INTERNAL_EXCEPTION);
return BSL_INTERNAL_EXCEPTION;
}
inputKey.inputData = key;
inputKey.dataSize = keySize;
inputValue.inputData = value;
inputValue.dataSize = valueSize;
return BSL_HASH_InsertNode(hash, rawList, &inputKey, &inputValue);
}
int32_t BSL_HASH_Put(BSL_HASH_Hash *hash, uintptr_t key, uint32_t keySize, uintptr_t value, uint32_t valueSize,
BSL_HASH_UpdateNodeFunc updateNodeFunc)
{
int32_t ret;
uint32_t hashCode;
RawList *rawList = NULL;
BSL_HASH_Node *hashNode = NULL;
BSL_CstlUserData inputValue;
BSL_CstlUserData inputKey;
ret = BSL_HASH_CodeCheck(hash, key, &hashCode);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(BSL_INTERNAL_EXCEPTION);
return BSL_INTERNAL_EXCEPTION;
}
rawList = &hash->listArray[hashCode];
hashNode = BSL_HASH_FindNode(rawList, key, hash->matchFunc);
if (hashNode != NULL) {
if (updateNodeFunc != NULL) {
return updateNodeFunc(hash, hashNode, value, valueSize);
} else {
return BSL_HASH_UpdateNode(hash, hashNode, value, valueSize);
}
}
inputKey.inputData = key;
inputKey.dataSize = keySize;
inputValue.inputData = value;
inputValue.dataSize = valueSize;
return BSL_HASH_InsertNode(hash, rawList, &inputKey, &inputValue);
}
int32_t BSL_HASH_At(const BSL_HASH_Hash *hash, uintptr_t key, uintptr_t *value)
{
BSL_HASH_Node *hashNode = BSL_HASH_Find(hash, key);
if (hashNode == BSL_HASH_IterEndGet(hash)) {
BSL_ERR_PUSH_ERROR(BSL_INTERNAL_EXCEPTION);
return BSL_INTERNAL_EXCEPTION;
}
*value = hashNode->value;
return BSL_SUCCESS;
}
BSL_HASH_Iterator BSL_HASH_Find(const BSL_HASH_Hash *hash, uintptr_t key)
{
uint32_t hashCode;
BSL_HASH_Node *hashNode = NULL;
int32_t ret = BSL_HASH_CodeCheck(hash, key, &hashCode);
if (ret != BSL_SUCCESS) {
return hash == NULL ? NULL : BSL_HASH_IterEndGet(hash);
}
hashNode = BSL_HASH_FindNode(&hash->listArray[hashCode], key, hash->matchFunc);
if (hashNode == NULL) {
return BSL_HASH_IterEndGet(hash);
}
return hashNode;
}
bool BSL_HASH_Empty(const BSL_HASH_Hash *hash)
{
return (hash == NULL) || (hash->hashCount == 0U);
}
uint32_t BSL_HASH_Size(const BSL_HASH_Hash *hash)
{
return hash == NULL ? 0 : hash->hashCount;
}
BSL_HASH_Iterator BSL_HASH_Erase(BSL_HASH_Hash *hash, uintptr_t key)
{
uint32_t hashCode;
BSL_HASH_Node *hashNode = NULL;
BSL_HASH_Node *nextHashNode = NULL;
BSL_HASH_MatchFunc matchFunc = NULL;
BSL_HASH_CodeCalcFunc hashFunc = NULL;
if (hash == NULL) {
return NULL;
}
hashFunc = hash->hashFunc;
hashCode = hashFunc(key, hash->bucketSize);
if (hashCode >= hash->bucketSize) {
return BSL_HASH_IterEndGet(hash);
}
matchFunc = hash->matchFunc;
hashNode = BSL_HASH_FindNode(&hash->listArray[hashCode], key, matchFunc);
if (hashNode == NULL) {
return BSL_HASH_IterEndGet(hash);
}
nextHashNode = BSL_HASH_Next(hash, hashNode);
ListRawRemove(&hash->listArray[hashCode], &hashNode->node);
BSL_HASH_NodeFree(hash, hashNode);
--hash->hashCount;
return nextHashNode;
}
void BSL_HASH_Clear(BSL_HASH_Hash *hash)
{
uint32_t i;
RawList *list = NULL;
BSL_HASH_Node *hashNode = NULL;
ListRawNode *rawListNode = NULL;
if (hash == NULL) {
return;
}
for (i = 0; i < hash->bucketSize; ++i) {
list = &hash->listArray[i];
while (!ListRawEmpty(list)) {
rawListNode = ListRawFront(list);
hashNode = BSL_CONTAINER_OF(rawListNode, BSL_HASH_Node, node);
ListRawRemove(list, rawListNode);
BSL_HASH_NodeFree(hash, hashNode);
}
}
hash->hashCount = 0;
}
void BSL_HASH_Destory(BSL_HASH_Hash *hash)
{
if (hash != NULL) {
BSL_HASH_Clear(hash);
BSL_SAL_Free(hash);
}
}
BSL_HASH_Iterator BSL_HASH_IterBegin(const BSL_HASH_Hash *hash)
{
return hash == NULL ? NULL : BSL_HASH_Front(hash);
}
BSL_HASH_Iterator BSL_HASH_IterEnd(const BSL_HASH_Hash *hash)
{
return hash == NULL ? NULL : BSL_HASH_IterEndGet(hash);
}
BSL_HASH_Iterator BSL_HASH_IterNext(const BSL_HASH_Hash *hash, BSL_HASH_Iterator it)
{
return (hash == NULL || it == BSL_HASH_IterEnd(hash)) ? BSL_HASH_IterEnd(hash) : BSL_HASH_Next(hash, it);
}
uintptr_t BSL_HASH_HashIterKey(const BSL_HASH_Hash *hash, BSL_HASH_Iterator it)
{
return (it == NULL || it == BSL_HASH_IterEnd(hash)) ? 0 : it->key;
}
uintptr_t BSL_HASH_IterValue(const BSL_HASH_Hash *hash, BSL_HASH_Iterator it)
{
return (it == NULL || it == BSL_HASH_IterEnd(hash)) ? 0 : it->value;
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* HITLS_BSL_HASH */
| 2401_83913325/openHiTLS_1 | bsl/hash/src/bsl_hash.c | C | unknown | 17,826 |
/*
* 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_BSL_HASH
#include <stdlib.h>
#include <stdint.h>
#include "list_base.h"
#include "bsl_errno.h"
#include "bsl_sal.h"
#include "bsl_hash_list.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct BslListNodeSt ListNode;
int32_t BSL_ListInit(BSL_List *list, const ListDupFreeFuncPair *dataFunc)
{
int32_t ret = (int32_t)BSL_INTERNAL_EXCEPTION;
if (list != NULL) {
ret = ListRawInit(&list->rawList, NULL);
if (dataFunc == NULL) {
list->dataFunc.dupFunc = NULL;
list->dataFunc.freeFunc = NULL;
} else {
list->dataFunc.dupFunc = dataFunc->dupFunc;
list->dataFunc.freeFunc = dataFunc->freeFunc;
}
}
return ret;
}
static int32_t ListRemoveNode(BSL_List *list, ListNode *node)
{
if (list->dataFunc.freeFunc != NULL) {
(list->dataFunc.freeFunc((void *)(node->userdata)));
}
int32_t ret = ListRawRemove(&list->rawList, &node->rawNode);
if (ret == BSL_SUCCESS) {
BSL_SAL_FREE(node);
}
return ret;
}
int32_t BSL_ListClear(BSL_List *list)
{
int32_t ret = (int32_t)BSL_INTERNAL_EXCEPTION;
ListNode *node = NULL;
const RawList *rawList = NULL;
const ListRawNode *head = NULL;
if (list != NULL) {
rawList = &list->rawList;
head = &rawList->head;
while (!ListRawEmpty(rawList)) {
node = BSL_CONTAINER_OF(head->next, ListNode, rawNode);
ret = ListRemoveNode(list, node);
if (ret != BSL_SUCCESS) {
break;
}
}
}
return ret;
}
int32_t BSL_ListDeinit(BSL_List *list)
{
int32_t ret = (int32_t)BSL_INTERNAL_EXCEPTION;
if (list != NULL) {
ret = BSL_ListClear(list);
list->dataFunc.dupFunc = NULL;
list->dataFunc.freeFunc = NULL;
}
return ret;
}
static int32_t ListWriteUserdata(const BSL_List *list, ListNode *node, uintptr_t userData, size_t userDataSize)
{
const void *copyBuff = NULL;
if (list->dataFunc.dupFunc == NULL) {
node->userdata = userData;
return BSL_SUCCESS;
}
copyBuff = list->dataFunc.dupFunc((void *)userData, userDataSize);
if (copyBuff == NULL) {
return BSL_INTERNAL_EXCEPTION;
}
node->userdata = (uintptr_t)copyBuff;
return BSL_SUCCESS;
}
static ListNode *NewNodeCreateByUserData(const BSL_List *list, uintptr_t userData, size_t userDataSize)
{
if (list == NULL) {
return NULL;
}
ListNode *node = (ListNode *)BSL_SAL_Malloc(sizeof(ListNode));
if (node != NULL) {
if (ListWriteUserdata(list, node, userData, userDataSize) != BSL_SUCCESS) {
BSL_SAL_Free(node);
node = NULL;
}
}
return node;
}
static int32_t ListPush(BSL_List *list, uintptr_t userData, size_t userDataSize, bool isFront)
{
ListNode *node = NewNodeCreateByUserData(list, userData, userDataSize);
if (node == NULL) {
return BSL_INTERNAL_EXCEPTION;
}
int32_t ret = isFront ? ListRawPushFront(&list->rawList, &node->rawNode) :
ListRawPushBack(&list->rawList, &node->rawNode);
if (ret != BSL_SUCCESS) {
if (list->dataFunc.freeFunc != NULL) {
list->dataFunc.freeFunc((void *)(node->userdata));
}
BSL_SAL_Free(node);
}
return ret;
}
int32_t BSL_ListPushFront(BSL_List *list, uintptr_t userData, size_t userDataSize)
{
return ListPush(list, userData, userDataSize, true);
}
int32_t BSL_ListPushBack(BSL_List *list, uintptr_t userData, size_t userDataSize)
{
return ListPush(list, userData, userDataSize, false);
}
int32_t BSL_ListInsert(BSL_List *list, const BSL_ListIterator it, uintptr_t userData, size_t userDataSize)
{
if (it == NULL) {
return BSL_INTERNAL_EXCEPTION;
}
ListNode *node = NewNodeCreateByUserData(list, userData, userDataSize);
if (node == NULL) {
return BSL_INTERNAL_EXCEPTION;
}
int32_t ret = ListRawInsert(&it->rawNode, &node->rawNode);
if (ret != BSL_SUCCESS) {
if (list->dataFunc.freeFunc != NULL) {
list->dataFunc.freeFunc((void *)(node->userdata));
}
BSL_SAL_Free(node);
}
return ret;
}
bool BSL_ListIsEmpty(const BSL_List *list)
{
return list == NULL ? true : ListRawEmpty(&list->rawList);
}
int32_t BSL_ListPopFront(BSL_List *list)
{
if (BSL_ListIsEmpty(list) == true) {
return BSL_INTERNAL_EXCEPTION;
}
ListNode *firstNode = BSL_CONTAINER_OF(list->rawList.head.next, ListNode, rawNode);
return ListRemoveNode(list, firstNode);
}
int32_t BSL_ListPopBack(BSL_List *list)
{
if (BSL_ListIsEmpty(list) == true) {
return BSL_INTERNAL_EXCEPTION;
}
ListNode *lastNode = BSL_CONTAINER_OF(list->rawList.head.prev, ListNode, rawNode);
return ListRemoveNode(list, lastNode);
}
BSL_ListIterator BSL_ListIterErase(BSL_List *list, BSL_ListIterator it)
{
if (BSL_ListIsEmpty(list) || (it == NULL) || (it == (BSL_ListIterator)(&list->rawList.head))) {
return NULL;
}
BSL_ListIterator retIt = BSL_CONTAINER_OF(it->rawNode.next, ListNode, rawNode);
return ListRemoveNode(list, it) == BSL_SUCCESS ? retIt : NULL;
}
uintptr_t BSL_ListFront(const BSL_List *list)
{
if (BSL_ListIsEmpty(list) == true) {
return 0;
}
const ListNode *node = BSL_CONTAINER_OF(list->rawList.head.next, ListNode, rawNode);
return node->userdata;
}
uintptr_t BSL_ListBack(const BSL_List *list)
{
if (BSL_ListIsEmpty(list) == true) {
return 0;
}
const ListNode *node = BSL_CONTAINER_OF(list->rawList.head.prev, ListNode, rawNode);
return node->userdata;
}
BSL_ListIterator BSL_ListIterBegin(const BSL_List *list)
{
return list == NULL ? NULL : BSL_CONTAINER_OF(list->rawList.head.next, ListNode, rawNode);
}
BSL_ListIterator BSL_ListIterEnd(BSL_List *list)
{
return list == NULL ? NULL : (BSL_ListIterator)(&list->rawList.head);
}
size_t BSL_ListSize(const BSL_List *list)
{
return list == NULL ? 0 : ListRawSize(&list->rawList);
}
BSL_ListIterator BSL_ListIterPrev(const BSL_List *list, const BSL_ListIterator it)
{
return (BSL_ListIsEmpty(list) == true || it == NULL) ? NULL : BSL_CONTAINER_OF(it->rawNode.prev, ListNode, rawNode);
}
BSL_ListIterator BSL_ListIterNext(const BSL_List *list, const BSL_ListIterator it)
{
return (BSL_ListIsEmpty(list) == true || it == NULL) ? NULL : BSL_CONTAINER_OF(it->rawNode.next, ListNode, rawNode);
}
uintptr_t BSL_ListIterData(const BSL_ListIterator it)
{
return it == NULL ? 0 : it->userdata;
}
/* Linked list node search function. The type of the first parameter of iterCmpFunc is userdata of each iterator. */
BSL_ListIterator BSL_ListIterFind(BSL_List *list, ListKeyCmpFunc iterCmpFunc, uintptr_t data)
{
if (list == NULL || iterCmpFunc == NULL) {
return NULL;
}
BSL_ListIterator headIt = (BSL_ListIterator)BSL_CONTAINER_OF(&list->rawList.head, ListNode, rawNode);
BSL_ListIterator it = BSL_CONTAINER_OF(list->rawList.head.next, ListNode, rawNode);
while (it != headIt) {
if (iterCmpFunc(it->userdata, data) == 0) {
return it;
}
it = BSL_CONTAINER_OF(it->rawNode.next, ListNode, rawNode);
}
return NULL;
}
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_HASH */
| 2401_83913325/openHiTLS_1 | bsl/hash/src/bsl_hash_list.c | C | unknown | 7,914 |
/*
* 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_BSL_HASH
#include "hash_local.h"
#ifdef __cplusplus
extern "C" {
#endif
bool IsMultiOverflow(uint32_t x, uint32_t y)
{
bool ret = false;
if ((x > 0) && (y > 0)) {
ret = ((SIZE_MAX / x) < y) ? true : false;
}
return ret;
}
bool IsAddOverflow(uint32_t x, uint32_t y)
{
return ((x + y) < x);
}
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_HASH */
| 2401_83913325/openHiTLS_1 | bsl/hash/src/hash_local.c | C | unknown | 965 |
/*
* 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 HASH_LOCAL_H
#define HASH_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_BSL_HASH
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
typedef struct {
uintptr_t inputData; /* Actual data input by the user. */
uint32_t dataSize; /* Actual input size */
} BSL_CstlUserData;
/* Check whether overflow occurs when two numbers are multiplied in the current system. */
bool IsMultiOverflow(uint32_t x, uint32_t y);
/* Check whether the sum of the two numbers overflows in the current system. */
bool IsAddOverflow(uint32_t x, uint32_t y);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_HASH */
#endif /* HASH_LOCAL_H */ | 2401_83913325/openHiTLS_1 | bsl/hash/src/hash_local.h | C | unknown | 1,258 |
/*
* 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_BSL_HASH
#include <stdlib.h>
#include "bsl_errno.h"
#include "list_base.h"
#ifdef __cplusplus
extern "C" {
#endif
/* internal function definition */
static inline bool ListRawNodeInList(const ListRawNode *node)
{
return (node->next != NULL) && (node->prev != NULL) &&
((const ListRawNode *)(node->next->prev) == node) &&
((const ListRawNode *)(node->prev->next) == node);
}
static inline bool IsListRawEmptyCheck(const RawList *list)
{
return (&list->head)->next == &list->head;
}
static inline void ListRawAddAfterNode(ListRawNode *node, ListRawNode *where)
{
node->next = (where)->next;
node->prev = (where);
where->next = node;
node->next->prev = node;
}
static inline void ListRawAddBeforeNode(ListRawNode *node, const ListRawNode *where)
{
ListRawAddAfterNode(node, where->prev);
}
static inline bool IsListRawFirstNode(const RawList *list, const ListRawNode *node)
{
return (const ListRawNode *)list->head.next == node;
}
static inline bool IsListRawLastNode(const RawList *list, const ListRawNode *node)
{
return (const ListRawNode *)list->head.prev == node;
}
/* Deleting the list node, internal function, input parameter validation is not required. */
static void ListRawRemoveNode(const RawList *list, ListRawNode *node)
{
node->prev->next = node->next;
node->next->prev = node->prev;
if (list->freeFunc != NULL) {
list->freeFunc((void *)node);
}
}
int32_t ListRawInit(RawList *list, ListFreeFunc freeFunc)
{
if (list == NULL) {
return BSL_INTERNAL_EXCEPTION;
}
list->head.next = &list->head;
list->head.prev = &list->head;
list->freeFunc = freeFunc;
return BSL_SUCCESS;
}
int32_t ListRawClear(RawList *list)
{
if (list == NULL) {
return BSL_INTERNAL_EXCEPTION;
}
while (!IsListRawEmptyCheck(list)) {
ListRawRemoveNode(list, (ListRawNode *)list->head.next);
}
return BSL_SUCCESS;
}
int32_t ListRawDeinit(RawList *list)
{
int32_t ret = (int32_t)BSL_INTERNAL_EXCEPTION;
if (list != NULL) {
ret = ListRawClear(list);
list->freeFunc = NULL;
}
return ret;
}
bool ListRawEmpty(const RawList *list)
{
return list == NULL ? true : IsListRawEmptyCheck(list);
}
static inline size_t ListRawSizeInner(const RawList *list)
{
size_t size = 0;
const ListRawNode *head = &list->head;
for (const ListRawNode *node = head->next; node != head; node = node->next) {
size++;
}
return size;
}
size_t ListRawSize(const RawList *list)
{
return (list == NULL || IsListRawEmptyCheck(list) == true) ? 0 : ListRawSizeInner(list);
}
int32_t ListRawPushFront(RawList *list, ListRawNode *node)
{
if (list == NULL || node == NULL) {
return BSL_INTERNAL_EXCEPTION;
}
ListRawAddAfterNode(node, &(list->head));
return BSL_SUCCESS;
}
int32_t ListRawPushBack(RawList *list, ListRawNode *node)
{
if (list == NULL || node == NULL) {
return BSL_INTERNAL_EXCEPTION;
}
ListRawAddBeforeNode(node, &(list->head));
return BSL_SUCCESS;
}
int32_t ListRawInsert(const ListRawNode *curNode, ListRawNode *newNode)
{
if ((curNode != NULL) && (newNode != NULL) && (ListRawNodeInList(curNode))) {
ListRawAddBeforeNode(newNode, curNode);
return BSL_SUCCESS;
}
return BSL_INTERNAL_EXCEPTION;
}
int32_t ListRawPopFront(RawList *list)
{
if (list == NULL || IsListRawEmptyCheck(list) == true) {
return BSL_INTERNAL_EXCEPTION;
}
ListRawNode *firstNode = list->head.next;
ListRawRemoveNode(list, firstNode);
return BSL_SUCCESS;
}
int32_t ListRawPopBack(RawList *list)
{
if (list == NULL || IsListRawEmptyCheck(list) == true) {
return BSL_INTERNAL_EXCEPTION;
}
ListRawNode *lastNode = list->head.prev;
ListRawRemoveNode(list, lastNode);
return BSL_SUCCESS;
}
static void ListRawRemoveInner(RawList *list, ListRawNode *node)
{
node->prev->next = node->next;
node->next->prev = node->prev;
if ((list != NULL) && !IsListRawEmptyCheck(list) && (list->freeFunc != NULL)) {
list->freeFunc((void *)node);
}
}
int32_t ListRawRemove(RawList *list, ListRawNode *node)
{
if (node == NULL || ListRawNodeInList(node) == false) {
return BSL_INTERNAL_EXCEPTION;
}
ListRawRemoveInner(list, node);
return BSL_SUCCESS;
}
ListRawNode *ListRawFront(const RawList *list)
{
return (list == NULL || IsListRawEmptyCheck(list) == true) ? NULL : list->head.next;
}
ListRawNode *ListRawBack(const RawList *list)
{
return (list == NULL || IsListRawEmptyCheck(list) == true) ? NULL : list->head.prev;
}
ListRawNode *ListRawGetPrev(const RawList *list, const ListRawNode *node)
{
return ((list == NULL) || (node == NULL) || (IsListRawEmptyCheck(list)) || (IsListRawFirstNode(list, node)) ||
(!ListRawNodeInList(node)))
? NULL
: node->prev;
}
ListRawNode *ListRawGetNext(const RawList *list, const ListRawNode *node)
{
return ((list == NULL) || (node == NULL) || (IsListRawEmptyCheck(list)) || (IsListRawLastNode(list, node)) ||
(!ListRawNodeInList(node)))
? NULL
: node->next;
}
/* Linked list node search function. The type of the first parameter of nodeMatchFunc must be (ListRawNode *) */
ListRawNode *ListRawFindNode(const RawList *list, ListMatchFunc nodeMatchFunc, uintptr_t data)
{
if (list == NULL || nodeMatchFunc == NULL) {
return NULL;
}
const ListRawNode *head = (const ListRawNode *)(&list->head);
ListRawNode *node = head->next;
while ((const ListRawNode *)node != head) {
if (nodeMatchFunc((void *)node, data)) {
return node;
}
node = node->next;
}
return NULL;
}
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_HASH */
| 2401_83913325/openHiTLS_1 | bsl/hash/src/list_base.c | C | unknown | 6,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.
*/
#ifndef BSL_BINLOG_ID_H
#define BSL_BINLOG_ID_H
#ifdef __cplusplus
extern "C" {
#endif
enum BSL_BINLOG_ID {
BINLOG_ID05001 = 5001, BINLOG_ID05002, BINLOG_ID05003, BINLOG_ID05004, BINLOG_ID05005,
BINLOG_ID05006, BINLOG_ID05007, BINLOG_ID05008, BINLOG_ID05009, BINLOG_ID05010,
BINLOG_ID05011, BINLOG_ID05012, BINLOG_ID05013, BINLOG_ID05014, BINLOG_ID05015,
BINLOG_ID05016, BINLOG_ID05017, BINLOG_ID05018, BINLOG_ID05019, BINLOG_ID05020,
BINLOG_ID05021, BINLOG_ID05022, BINLOG_ID05023, BINLOG_ID05024, BINLOG_ID05025,
BINLOG_ID05026, BINLOG_ID05027, BINLOG_ID05028, BINLOG_ID05029, BINLOG_ID05030,
BINLOG_ID05031, BINLOG_ID05032, BINLOG_ID05033, BINLOG_ID05034, BINLOG_ID05035,
BINLOG_ID05036, BINLOG_ID05037, BINLOG_ID05038, BINLOG_ID05039, BINLOG_ID05040,
BINLOG_ID05041, BINLOG_ID05042, BINLOG_ID05043, BINLOG_ID05044, BINLOG_ID05045,
BINLOG_ID05046, BINLOG_ID05047, BINLOG_ID05048, BINLOG_ID05049, BINLOG_ID05050,
BINLOG_ID05051, BINLOG_ID05052, BINLOG_ID05053, BINLOG_ID05054, BINLOG_ID05055,
BINLOG_ID05056, BINLOG_ID05057, BINLOG_ID05058, BINLOG_ID05059, BINLOG_ID05060,
BINLOG_ID05061, BINLOG_ID05062, BINLOG_ID05063, BINLOG_ID05064, BINLOG_ID05065,
BINLOG_ID05066, BINLOG_ID05067, BINLOG_ID05068, BINLOG_ID05069, BINLOG_ID05070,
BINLOG_ID05071, BINLOG_ID05072, BINLOG_ID05073, BINLOG_ID05074, BINLOG_ID05075,
BINLOG_ID05076, BINLOG_ID05077, BINLOG_ID05078, BINLOG_ID05079, BINLOG_ID05080,
BINLOG_ID05081, BINLOG_ID05082, BINLOG_ID05083, BINLOG_ID05084, BINLOG_ID05085,
BINLOG_ID05086
};
#ifdef __cplusplus
}
#endif
#endif
| 2401_83913325/openHiTLS_1 | bsl/include/bsl_binlog_id.h | C | unknown | 2,148 |
/*
* 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 BSL_BYTES_H
#define BSL_BYTES_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief convert uint8_t byte stream to uint16_t data
*
* @attention data cannot be empty
*
* @param data [IN] uint8_t byte stream
*
* @return uint16_t converted data
*/
static inline uint16_t BSL_ByteToUint16(const uint8_t *data)
{
/** Byte 0 is shifted by 8 bits to the left, and byte 1 remains unchanged. uint16_t is obtained after OR */
return ((uint16_t)data[0] << 8) | ((uint16_t)data[1]);
}
/**
* @brief convert uint16_t data to uint8_t byte stream
*
* @attention data cannot be empty
*
* @param num [IN] data to be converted
* @param data [OUT] converted data
*/
static inline void BSL_Uint16ToByte(uint16_t num, uint8_t *data)
{
/** convert to byte stream */
data[0] = (uint8_t)(num >> 8); // data is shifted rightwards by 8 bits and put in byte 0
data[1] = (uint8_t)(num & 0xffu); // data AND 0xffu, put in byte 1
return;
}
/**
* @brief convert uint8_t byte stream to uint24_t data
*
* @attention data cannot be empty
*
* @param data [IN] uint8_t byte stream
*
* @return uint24_t, converted data
*/
static inline uint32_t BSL_ByteToUint24(const uint8_t *data)
{
/** Byte 0 is shifted left by 16 bits, byte 1 is shifted left by 8 bits, and byte 2 remains unchanged,
uint24_t is obtained after the OR operation. */
return ((uint32_t)data[0] << 16) | ((uint32_t)data[1] << 8) | ((uint32_t)data[2]);
}
/**
* @brief convert uint24_t data to uint8_t byte stream
*
* @attention data cannot be empty
*
* @param num [IN] data to be converted
* @param data [OUT] converted data
*/
static inline void BSL_Uint24ToByte(uint32_t num, uint8_t *data)
{
/** convert to byte stream */
data[0] = (uint8_t)(num >> 16); // data is shifted rightwards by 16 bits and put in byte 0
data[1] = (uint8_t)(num >> 8); // data is shifted rightwards by 8 bits and placed in byte 1
data[2] = (uint8_t)(num & 0xffu); // data AND 0xffu, put in byte 2
return;
}
/**
* @brief convert uint8_t byte stream to uint32_t data
*
* @attention data cannot be empty
*
* @param data [IN] uint8_t byte stream
*
* @return uint32_t, converted data
*/
static inline uint32_t BSL_ByteToUint32(const uint8_t *data)
{
/** Byte 0 is shifted leftward by 24 bits, byte 1 is shifted leftward by 16 bits,
byte 2 is shifted leftward by 8 bits, and byte 3 remains unchanged, uint32_t is obtained after OR operation. */
return ((uint32_t)data[0] << 24) | ((uint32_t)data[1] << 16) | ((uint32_t)data[2] << 8) | ((uint32_t)data[3]);
}
/**
* @brief convert uint8_t byte stream to uint48_t data
*
* @attention data cannot be empty
*
* @param data [IN] uint8_t byte stream
*
* @return uint48_t, converted data
*/
static inline uint64_t BSL_ByteToUint48(const uint8_t *data)
{
/** Byte 0 is shifted leftward by 40 bits, byte 1 is shifted leftward by 32 bits,
byte 2 is shifted leftward by 24 bits, byte 3 is shifted leftward by 16 bits,
byte 4 is shifted leftward by 8 bits, and byte 5 remains unchanged, uint48_t is obtained after OR operation. */
return ((uint64_t)data[0] << 40) | ((uint64_t)data[1] << 32) | ((uint64_t)data[2] << 24) |
((uint64_t)data[3] << 16) | ((uint64_t)data[4] << 8) | ((uint64_t)data[5]);
}
/**
* @brief convert uint48_t data to uint8_t byte stream
*
* @attention data cannot be empty
*
* @param num [IN] data to be converted
* @param data [OUT] converted data
*/
static inline void BSL_Uint48ToByte(uint64_t num, uint8_t *data)
{
/** convert to byte stream */
data[0] = (uint8_t)(num >> 40); // data is shifted rightwards by 40 bits and put in byte 0
data[1] = (uint8_t)(num >> 32); // data is shifted rightwards by 32 bits and put in byte 1
data[2] = (uint8_t)(num >> 24); // data is shifted rightwards by 24 bits and put in byte 2
data[3] = (uint8_t)(num >> 16); // data is shifted rightwards by 16 bits and put in byte 3
data[4] = (uint8_t)(num >> 8); // data is shifted rightwards by 8 bits and put in byte 4
data[5] = (uint8_t)(num & 0xffu); // data AND 0xffu, put in byte 5
return;
}
/**
* @brief convert uint8_t byte stream to uint64_t data
*
* @attention data cannot be empty
*
* @param data [IN] uint8_t byte stream
*
* @return uint32_t, converted data
*/
static inline uint64_t BSL_ByteToUint64(const uint8_t *data)
{
/** Byte 0 is shifted leftward by 56 bits, byte 1 is shifted leftward by 48 bits,
byte 2 is shifted leftward by 40 bits, byte 3 is shifted leftward by 32 bits,
byte 4 is shifted leftward by 24 bits, byte 5 is shifted leftward by 16 bits,
byte 6 is shifted leftward by 8 bits, and byte 7 remains unchanged, uint64_t is obtained after OR operation. */
return ((uint64_t)data[0] << 56) | ((uint64_t)data[1] << 48) | ((uint64_t)data[2] << 40) |
((uint64_t)data[3] << 32) | ((uint64_t)data[4] << 24) | ((uint64_t)data[5] << 16) |
((uint64_t)data[6] << 8) | ((uint64_t)data[7]);
}
/**
* @brief convert uint32_t data to uint8_t byte stream
*
* @attention data cannot be empty
*
* @param num [IN] data to be converted
* @param data [OUT] converted data
*/
static inline void BSL_Uint32ToByte(uint32_t num, uint8_t *data)
{
/** convert to byte stream */
data[0] = (uint8_t)(num >> 24); // data is shifted rightwards by 24 bits and put in byte 0
data[1] = (uint8_t)(num >> 16); // data is shifted rightwards by 16 bits and put in byte 1
data[2] = (uint8_t)(num >> 8); // data is shifted rightwards by 8 bits and put in byte 2
data[3] = (uint8_t)(num & 0xffu); // data AND 0xffu, put in byte 3
return;
}
/**
* @brief convert uint64_t data to uint8_t byte stream
*
* @attention data cannot be empty
*
* @param num [IN] data to be converted
* @param data [OUT] converted data
*/
static inline void BSL_Uint64ToByte(uint64_t num, uint8_t *data)
{
/** convert to byte stream */
data[0] = (uint8_t)(num >> 56); // data is shifted rightwards by 56 bits and put in byte 0
data[1] = (uint8_t)(num >> 48); // data is shifted rightwards by 48 bits and put in byte 1
data[2] = (uint8_t)(num >> 40); // data is shifted rightwards by 40 bits and put in byte 2
data[3] = (uint8_t)(num >> 32); // data is shifted rightwards by 32 bits and put in byte 3
data[4] = (uint8_t)(num >> 24); // data is shifted rightwards by 24 bits and put in byte 4
data[5] = (uint8_t)(num >> 16); // data is shifted rightwards by 16 bits and put in byte 5
data[6] = (uint8_t)(num >> 8); // data is shifted rightwards by 8 bits and put in byte 6
data[7] = (uint8_t)(num & 0xffu); // data AND 0xffu, put in byte 7
return;
}
// if a's MSB is 0, output 0
// else if a' MSB is 1 output 0xffffffff
static inline uint32_t Uint32ConstTimeMsb(uint32_t a)
{
// 31 == (4 * 8 - 1)
return 0u - (a >> 31);
}
// if a is 0, output 0xffffffff, else output 0
static inline uint32_t Uint32ConstTimeIsZero(uint32_t a)
{
return Uint32ConstTimeMsb(~a & (a - 1));
}
// if a == b, output 0xffffffff, else output 0
static inline uint32_t Uint32ConstTimeEqual(uint32_t a, uint32_t b)
{
return Uint32ConstTimeIsZero(a ^ b);
}
// if mask == 0xffffffff, return a,
// else if mask == 0, return b
static inline uint32_t Uint32ConstTimeSelect(uint32_t mask, uint32_t a, uint32_t b)
{
return ((mask) & a) | ((~mask) & b);
}
static inline uint32_t Uint8ConstTimeSelect(uint32_t mask, uint8_t a, uint8_t b)
{
return (((mask) & a) | ((~mask) & b)) & 0xff;
}
// if a < b, output 0xffffffff, else output 0
static inline uint32_t Uint32ConstTimeLt(uint32_t a, uint32_t b)
{
return Uint32ConstTimeMsb(a ^ ((a ^ b) | ((a - b) ^ a)));
}
// if a >= b, output 0xffffffff, else output 0
static inline uint32_t Uint32ConstTimeGe(uint32_t a, uint32_t b)
{
return ~Uint32ConstTimeLt(a, b);
}
// if a > b, output 0xffffffff, else output 0
static inline uint32_t Uint32ConstTimeGt(uint32_t a, uint32_t b)
{
return Uint32ConstTimeLt(b, a);
}
static inline uint32_t Uint32ConstTimeLe(uint32_t a, uint32_t b)
{
return Uint32ConstTimeGe(b, a);
}
// if a == b, return 0xffffffff, else return 0
static inline uint32_t ConstTimeMemcmp(uint8_t *a, uint8_t *b, uint32_t l)
{
uint8_t r = 0;
for (uint32_t i = 0; i < l; i++) {
r |= a[i] ^ b[i];
}
return Uint32ConstTimeIsZero(r);
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif // BSL_BYTES_H
| 2401_83913325/openHiTLS_1 | bsl/include/bsl_bytes.h | C | unknown | 9,102 |
/*
* 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 BSL_MODULE_LIST_H
#define BSL_MODULE_LIST_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* This structure is used to store the forward and backward pointers of nodes in the bidirectional linked list.
* This linked list does not contain substantial data areas and is generally used to organize (concatenate) data nodes.
*/
typedef struct ListHeadSt {
struct ListHeadSt *next, *prev;
} ListHead;
/**
* @brief initialize the linked list when the linked list is reused
*
* @param head [IN] The address of the head node of the list
*/
#define LIST_INIT(head) (head)->next = (head)->prev = (head)
/**
* @brief Insert the 'item' node after the 'where' node.
Before the change: where->A->B. After the change: where->item->A->B
*
* @param where [IN] The address where the item will be inserted after
* @param item [IN] Address of the node(item) to be inserted
*/
#define LIST_ADD_AFTER(where, item) do { \
(item)->next = (where)->next; \
(item)->prev = (where); \
(where)->next = (item); \
(item)->next->prev = (item); \
} while (0)
/**
* @brief Insert the 'item' node before the 'where' node.
* Before change: A->where->B. After change: A->item->where->B
*
* @param where [IN] The address where the item will be inserted before
* @param item [IN] Address of the node to be inserted
*/
#define LIST_ADD_BEFORE(where, item) LIST_ADD_AFTER((where)->prev, (item))
/**
* @brief Delete the node item.
*
* @param item [IN] The address of the item to be removed
*/
#define LIST_REMOVE(item) do { \
(item)->prev->next = (item)->next; \
(item)->next->prev = (item)->prev; \
} while (0)
/**
* @brief Check whether a list is empty
*
* @param head [IN] The address of the list to be checked.
*/
#define LIST_IS_EMPTY(head) ((head)->next == (head))
/**
* @brief Travel through a list safety
*
* @param head [IN] Linked list to be traversed (The head of a list)
* @param temp [IN] Point to the current node to safely delete the current node
* @param item [IN] A temporary list node item for travelling the list
*/
#define LIST_FOR_EACH_ITEM_SAFE(item, temp, head) \
for ((item) = (head)->next, (temp) = (item)->next; (item) != (head); (item) = (temp), (temp) = (item)->next)
/**
* @brief Find the start address of the struct(large node) where the node is located
* through a node (small node) in the linked list.
*
* @param item [IN] The address of a list item
* @param type [IN] Type of the large node that contains the linked list node.
* @param member [IN] Name of the list node in the structure
*
* Note:
* Each struct variable forms a large node (including data and list nodes).
* The large node is connected through the list(small node).
* --------- --------- --------- -- ----
* | pre |<---| pre |<---| pre | |==>small node |
* | next |--->| next |--->| next | | |
* --------- --------- --------- -- | ===> Large node
* | data1 | | data1 | | data1 | |
* | data2 | | data2 | | data2 | |
* --------- --------- --------- ----
* The reason why the list is not directly used as the big node is that
* the list (ListHead type) has only the head and tail pointers and does not contain the data area.
* In this way, the list can be used for mounting any data and is universal.
*/
#define LIST_ENTRY(item, type, member) \
((type *)((uintptr_t)(char *)(item) - (uintptr_t)(&((type *)0)->member)))
#ifdef __cplusplus
}
#endif
#endif // BSL_MODULE_LIST_H | 2401_83913325/openHiTLS_1 | bsl/include/bsl_module_list.h | C | unknown | 4,268 |
/*
* 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 BSL_UTIL_INTERNAL_H
#define BSL_UTIL_INTERNAL_H
#ifdef __cplusplus
extern "C" {
#endif
// check if gcc/clang defined 128 bits int
#ifdef __SIZEOF_INT128__
typedef __int128_t int128_t;
typedef __uint128_t uint128_t;
#endif
#ifdef __cplusplus
}
#endif /* end __cplusplus */
#endif // BSL_UTIL_INTERNAL_H
| 2401_83913325/openHiTLS_1 | bsl/include/bsl_util_internal.h | C | unknown | 860 |
/*
* 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_BSL_INIT
#include "bsl_err.h"
#include "bsl_errno.h"
#ifdef HITLS_BSL_OBJ_CUSTOM
#include "bsl_obj_internal.h"
#endif // HITLS_BSL_OBJ
int32_t BSL_GLOBAL_Init(void)
{
return BSL_ERR_Init();
}
int32_t BSL_GLOBAL_DeInit(void)
{
BSL_ERR_RemoveErrStringBatch();
BSL_ERR_RemoveErrorStack(true);
BSL_ERR_DeInit();
#ifdef HITLS_BSL_OBJ_CUSTOM
BSL_OBJ_FreeSignHashTable();
BSL_OBJ_FreeHashTable();
#endif // HITLS_BSL_OBJ_CUSTOM
return BSL_SUCCESS;
}
#endif /* HITLS_BSL_INIT */
| 2401_83913325/openHiTLS_1 | bsl/init/bsl_init.c | C | unknown | 1,085 |