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 INDICATOR_H #define INDICATOR_H #include "hitls_build.h" #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define INDICATOR_ALERT_LEVEL_OFFSET 8 #define INDICATE_INFO_STATE_MASK 0x0FFF // 0000 1111 1111 1111 /** * @ingroup indicator * @brief Indicate the status or event to the upper layer through the infoCb * @param ctx [IN] TLS context * @param eventType [IN] * @param value [IN] Return value of a function in the event or alert type */ void INDICATOR_StatusIndicate(const HITLS_Ctx *ctx, int32_t eventType, int32_t value); /** * @ingroup indicator * @brief Indicate the status or event to the upper layer through msgCb * @param writePoint [IN] Message direction in the callback ">>>" or "<<<" * @param tlsVersion [IN] TLS version * @param contentType[IN] Type of the message to be processed. * @param msg [IN] Internal message processing instruction data in callback * @param msgLen [IN] Data length of the processing instruction * @param ctx [IN] HITLS context * @param arg [IN] User data such as BIO */ void INDICATOR_MessageIndicate(int32_t writePoint, uint32_t tlsVersion, int32_t contentType, const void *msg, uint32_t msgLen, HITLS_Ctx *ctx, void *arg); #ifdef __cplusplus } #endif #endif // INDICATOR_H
2302_82127028/openHiTLS-examples
tls/include/indicator.h
C
unknown
1,904
/* * 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 SECURITY_H #define SECURITY_H #include <stdint.h> #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define SECURITY_SUCCESS 1 #define SECURITY_ERR 0 /* set the default security level and security callback function */ void SECURITY_SetDefault(HITLS_Config *config); /* check TLS configuration security */ int32_t SECURITY_CfgCheck(const HITLS_Config *config, int32_t option, int32_t bits, int32_t id, void *other); /* check TLS link security */ int32_t SECURITY_SslCheck(const HITLS_Ctx *ctx, int32_t option, int32_t bits, int32_t id, void *other); /* get the security strength corresponding to the security level */ int32_t SECURITY_GetSecbits(int32_t level); #ifdef __cplusplus } #endif #endif // SECURITY_H
2302_82127028/openHiTLS-examples
tls/include/security.h
C
unknown
1,283
/* * 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 SESSION_H #define SESSION_H #include <stdint.h> #include <stdbool.h> #include "hitls_build.h" #include "sal_time.h" #include "hitls_session.h" #include "cert.h" #ifdef __cplusplus extern "C" { #endif #define MAX_MASTER_KEY_SIZE 256u /* <= tls1.2 master key is 48 bytes. TLS1.3 can be to 256 bytes. */ /* Increments the reference count for session */ void HITLS_SESS_UpRef(HITLS_Session *sess); /* Deep copy session */ HITLS_Session *SESS_Copy(HITLS_Session *src); /* Disable session */ void SESS_Disable(HITLS_Session *sess); /* set peerCert */ int32_t SESS_SetPeerCert(HITLS_Session *sess, CERT_Pair *peerCert, bool isClient); /* get peerCert */ int32_t SESS_GetPeerCert(HITLS_Session *sess, CERT_Pair **peerCert); /* set ticket */ int32_t SESS_SetTicket(HITLS_Session *sess, uint8_t *ticket, uint32_t ticketSize); /* get ticket */ int32_t SESS_GetTicket(const HITLS_Session *sess, uint8_t **ticket, uint32_t *ticketSize); /* set hostName */ int32_t SESS_SetHostName(HITLS_Session *sess, uint32_t hostNameSize, uint8_t *hostName); /* get hostName */ int32_t SESS_GetHostName(HITLS_Session *sess, uint32_t *hostNameSize, uint8_t **hostName); /* Check the validity of the session */ bool SESS_CheckValidity(HITLS_Session *sess, uint64_t curTime); uint64_t SESS_GetStartTime(HITLS_Session *sess); int32_t SESS_SetStartTime(HITLS_Session *sess, uint64_t startTime); int32_t SESS_SetTicketAgeAdd(HITLS_Session *sess, uint32_t ticketAgeAdd); uint32_t SESS_GetTicketAgeAdd(const HITLS_Session *sess); #ifdef __cplusplus } #endif #endif // SESSION_H
2302_82127028/openHiTLS-examples
tls/include/session.h
C
unknown
2,121
/* * 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 SESSION_MGR_H #define SESSION_MGR_H #include <stdint.h> #include <stdbool.h> #include "hitls_build.h" #include "hitls.h" #include "tls.h" #include "session.h" #include "tls_config.h" #ifdef __cplusplus extern "C" { #endif /* Application */ TLS_SessionMgr *SESSMGR_New(HITLS_Lib_Ctx *libCtx); /* Copy the number of references and increase the number of references by 1 */ TLS_SessionMgr *SESSMGR_Dup(TLS_SessionMgr *mgr); /* Release */ void SESSMGR_Free(TLS_SessionMgr *mgr); /* Configure the timeout period */ void SESSMGR_SetTimeout(TLS_SessionMgr *mgr, uint64_t sessTimeout); /* Obtain the timeout configuration */ uint64_t SESSMGR_GetTimeout(TLS_SessionMgr *mgr); /* Set the mode */ void SESSMGR_SetCacheMode(TLS_SessionMgr *mgr, HITLS_SESS_CACHE_MODE mode); /* Set the mode: Ensure that the pointer is not null */ HITLS_SESS_CACHE_MODE SESSMGR_GetCacheMode(TLS_SessionMgr *mgr); /* Set the maximum number of cache sessions */ void SESSMGR_SetCacheSize(TLS_SessionMgr *mgr, uint32_t sessCacheSize); /* Set the maximum number of cached sessions. Ensure that the pointer is not null */ uint32_t SESSMGR_GetCacheSize(TLS_SessionMgr *mgr); /* add */ void SESSMGR_InsertSession(TLS_SessionMgr *mgr, HITLS_Session *sess, bool isClient); /* Find the matching session and verify the validity of the session (time) */ HITLS_Session *SESSMGR_Find(TLS_SessionMgr *mgr, uint8_t *sessionId, uint8_t sessionIdSize); /* Search for the matching session without checking the validity of the session (time) */ bool SESSMGR_HasMacthSessionId(TLS_SessionMgr *mgr, uint8_t *sessionId, uint8_t sessionIdSize); /* Clear timeout sessions */ void SESSMGR_ClearTimeout(TLS_SessionMgr *mgr); /* Generate session IDs to prevent duplicate session IDs */ int32_t SESSMGR_GernerateSessionId(TLS_Ctx *ctx, uint8_t *sessionId, uint32_t sessionIdSize); void SESSMGR_SetTicketKeyCb(TLS_SessionMgr *mgr, HITLS_TicketKeyCb ticketKeyCb); HITLS_TicketKeyCb SESSMGR_GetTicketKeyCb(TLS_SessionMgr *mgr); /** * @brief Obtain the default ticket key of the HITLS. The key is used to encrypt and decrypt the ticket * in the new session ticket when the HITLS_TicketKeyCb callback function is not set. * * @attention The returned key value is as follows: 16-bytes key name + 32-bytes AES key + 32-bytes HMAC key * * @param mgr [IN] Session management context * @param key [OUT] Obtained ticket key * @param keySize [IN] Size of the key array * @param outSize [OUT] Size of the obtained ticket key * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t SESSMGR_GetTicketKey(const TLS_SessionMgr *mgr, uint8_t *key, uint32_t keySize, uint32_t *outSize); /** * @brief Set the default ticket key of the HITLS. The key is used to encrypt and decrypt tickets * in the new session ticket when the HITLS_TicketKeyCb callback function is not set. * * @attention The returned key value is as follows: 16-bytes key name + 32-bytes AES key + 32-bytes HMAC key * * @param mgr [OUT] Session management context * @param key [IN] Ticket key to be set * @param keySize [IN] Size of the ticket key * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t SESSMGR_SetTicketKey(TLS_SessionMgr *mgr, const uint8_t *key, uint32_t keySize); /** * @brief Encrypt the session ticket, which is invoked when a new session ticket is sent * * @param sessMgr [IN] Session management context * @param sess [IN] sess structure, used to generate ticket data * @param ticketBuf [OUT] ticket. The return value may be empty, that is, an empty new session ticket message is sent * @param ticketBufSize [IN] Size of the ticketBuf * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t SESSMGR_EncryptSessionTicket(TLS_Ctx *ctx, const TLS_SessionMgr *sessMgr, const HITLS_Session *sess, uint8_t **ticketBuf, uint32_t *ticketBufSize); /** * @brief Decrypt the session ticket. This interface is invoked when the session ticket of the clientHello is received * * @attention The output parameters are as follows: * If the sess field is empty and the ticketExcept field is set to true, the new session ticket message * is sent but the session is not resumed * If the sess field is empty and the ticketExcept field is false, the session is not resumed * and the new session ticket message is not sent * If sess is not empty and ticketExcept is true, the session is resumed and * a new session ticket message is sent, which means the session ticket is renewed * If sess is not empty and ticketExcept is false, * the session is resumed and the new session ticket message is not sent * * @param sessMgr [IN] Session management context * @param sess [OUT] Session structure generated by the ticket. The return value may be empty, * so that, the corresponding session cannot be generated and the session cannot be resumed * @param ticketBuf [IN] ticket data * @param ticketBufSize [IN] Ticket data size * @param isTicketExcept [OUT] Indicates whether to send a new session ticket. * The options are as follows: true: yes; false: no. * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t SESSMGR_DecryptSessionTicket(HITLS_Lib_Ctx *libCtx, const char *attrName, const TLS_SessionMgr *sessMgr, HITLS_Session **sess, const uint8_t *ticketBuf, uint32_t ticketBufSize, bool *isTicketExcept); #ifdef __cplusplus } #endif #endif // SESSION_MGR_H
2302_82127028/openHiTLS-examples
tls/include/session_mgr.h
C
unknown
6,194
/* * 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 SNI_H #define SNI_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef struct SniArg { char *serverName; int32_t alert; } SNI_Arg; /* compare whether the host names are the same */ int32_t SNI_StrcaseCmp(const char *s1, const char *s2); #ifdef __cplusplus } #endif #endif // ALPN_H
2302_82127028/openHiTLS-examples
tls/include/sni.h
C
unknown
863
/* * 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 TLS_H #define TLS_H #include <stdint.h> #include <stdbool.h> #include "hitls_build.h" #include "cipher_suite.h" #include "tls_config.h" #include "hitls_error.h" #ifdef __cplusplus extern "C" { #endif #define MAX_DIGEST_SIZE 64UL /* The longest known value is SHA512 */ #define DTLS_DEFAULT_PMTU 1500uL /* RFC 6083 4.1. Mapping of DTLS Records: The supported maximum length of SCTP user messages MUST be at least 2^14 + 2048 + 13 = 18445 bytes (2^14 + 2048 is the maximum length of the DTLSCiphertext.fragment, and 13 is the size of the DTLS record header). */ #define DTLS_SCTP_PMTU 18445uL #define IS_DTLS_VERSION(version) (((version) & 0x8u) == 0x8u) #define IS_SUPPORT_STREAM(versionBits) (((versionBits) & STREAM_VERSION_BITS) != 0x0u) #define IS_SUPPORT_DATAGRAM(versionBits) (((versionBits) & DATAGRAM_VERSION_BITS) != 0x0u) #define IS_SUPPORT_TLCP(versionBits) (((versionBits) & TLCP_VERSION_BITS) != 0x0u) #define DTLS_COOKIE_LEN 255 #define MAC_KEY_LEN 32u /* the length of mac key */ #define UNPROCESSED_APP_MSG_COUNT_MAX 50 /* number of APP data cached */ #define RANDOM_SIZE 32u /* the size of random number */ typedef struct TlsCtx TLS_Ctx; typedef struct HsCtx HS_Ctx; typedef struct CcsCtx CCS_Ctx; typedef struct AlertCtx ALERT_Ctx; typedef struct RecCtx REC_Ctx; typedef enum { CCS_CMD_RECV_READY, /* CCS allowed to be received */ CCS_CMD_RECV_EXIT_READY, /* CCS cannot be received */ CCS_CMD_RECV_ACTIVE_CIPHER_SPEC, /* CCS active change cipher spec */ } CCS_Cmd; /* Check whether the CCS message is received */ typedef bool (*IsRecvCcsCallback)(const TLS_Ctx *ctx); /* Send a CCS message */ typedef int32_t (*SendCcsCallback)(TLS_Ctx *ctx); /* Control the CCS */ typedef int32_t (*CtrlCcsCallback)(TLS_Ctx *ctx, CCS_Cmd cmd); typedef enum { ALERT_LEVEL_WARNING = 1, ALERT_LEVEL_FATAL = 2, ALERT_LEVEL_UNKNOWN = 255, } ALERT_Level; typedef enum { ALERT_CLOSE_NOTIFY = 0, ALERT_UNEXPECTED_MESSAGE = 10, ALERT_BAD_RECORD_MAC = 20, ALERT_DECRYPTION_FAILED = 21, ALERT_RECORD_OVERFLOW = 22, ALERT_DECOMPRESSION_FAILURE = 30, ALERT_HANDSHAKE_FAILURE = 40, ALERT_NO_CERTIFICATE_RESERVED = 41, ALERT_BAD_CERTIFICATE = 42, ALERT_UNSUPPORTED_CERTIFICATE = 43, ALERT_CERTIFICATE_REVOKED = 44, ALERT_CERTIFICATE_EXPIRED = 45, ALERT_CERTIFICATE_UNKNOWN = 46, ALERT_ILLEGAL_PARAMETER = 47, ALERT_UNKNOWN_CA = 48, ALERT_ACCESS_DENIED = 49, ALERT_DECODE_ERROR = 50, ALERT_DECRYPT_ERROR = 51, ALERT_EXPORT_RESTRICTION_RESERVED = 60, ALERT_PROTOCOL_VERSION = 70, ALERT_INSUFFICIENT_SECURITY = 71, ALERT_INTERNAL_ERROR = 80, ALERT_INAPPROPRIATE_FALLBACK = 86, ALERT_USER_CANCELED = 90, ALERT_NO_RENEGOTIATION = 100, ALERT_MISSING_EXTENSION = 109, ALERT_UNSUPPORTED_EXTENSION = 110, ALERT_CERTIFICATE_UNOBTAINABLE = 111, ALERT_UNRECOGNIZED_NAME = 112, ALERT_BAD_CERTIFICATE_STATUS_RESPONSE = 113, ALERT_BAD_CERTIFICATE_HASH_VALUE = 114, ALERT_UNKNOWN_PSK_IDENTITY = 115, ALERT_CERTIFICATE_REQUIRED = 116, ALERT_NO_APPLICATION_PROTOCOL = 120, ALERT_UNKNOWN = 255 } ALERT_Description; /** Connection management state */ typedef enum { CM_STATE_IDLE, CM_STATE_HANDSHAKING, CM_STATE_TRANSPORTING, CM_STATE_RENEGOTIATION, CM_STATE_ALERTING, CM_STATE_ALERTED, CM_STATE_CLOSED, CM_STATE_END } CM_State; /** post-handshake auth */ typedef enum { PHA_NONE, /* not support pha */ PHA_EXTENSION, /* pha extension send or received */ PHA_PENDING, /* try to send certificate request */ PHA_REQUESTED /* certificate request has been sent or received */ } PHA_State; /* Describes the handshake status */ typedef enum { TLS_IDLE, /* initial state */ TLS_CONNECTED, /* Handshake succeeded */ TRY_SEND_HELLO_REQUEST, /* sends hello request message */ TRY_SEND_CLIENT_HELLO, /* sends client hello message */ TRY_SEND_HELLO_RETRY_REQUEST, /* sends hello retry request message */ TRY_SEND_SERVER_HELLO, /* sends server hello message */ TRY_SEND_HELLO_VERIFY_REQUEST, /* sends hello verify request message */ TRY_SEND_ENCRYPTED_EXTENSIONS, /* sends encrypted extensions message */ TRY_SEND_CERTIFICATE, /* sends certificate message */ TRY_SEND_SERVER_KEY_EXCHANGE, /* sends server key exchange message */ TRY_SEND_CERTIFICATE_REQUEST, /* sends certificate request message */ TRY_SEND_SERVER_HELLO_DONE, /* sends server hello done message */ TRY_SEND_CLIENT_KEY_EXCHANGE, /* sends client key exchange message */ TRY_SEND_CERTIFICATE_VERIFY, /* sends certificate verify message */ TRY_SEND_NEW_SESSION_TICKET, /* sends new session ticket message */ TRY_SEND_CHANGE_CIPHER_SPEC, /* sends change cipher spec message */ TRY_SEND_END_OF_EARLY_DATA, /* sends end of early data message */ TRY_SEND_FINISH, /* sends finished message */ TRY_SEND_KEY_UPDATE, /* sends keyupdate message */ TRY_RECV_CLIENT_HELLO, /* attempts to receive client hello message */ TRY_RECV_SERVER_HELLO, /* attempts to receive server hello message */ TRY_RECV_HELLO_VERIFY_REQUEST, /* attempts to receive hello verify request message */ TRY_RECV_ENCRYPTED_EXTENSIONS, /* attempts to receive encrypted extensions message */ TRY_RECV_CERTIFICATE, /* attempts to receive certificate message */ TRY_RECV_SERVER_KEY_EXCHANGE, /* attempts to receive server key exchange message */ TRY_RECV_CERTIFICATE_REQUEST, /* attempts to receive certificate request message */ TRY_RECV_SERVER_HELLO_DONE, /* attempts to receive server hello done message */ TRY_RECV_CLIENT_KEY_EXCHANGE, /* attempts to receive client key exchange message */ TRY_RECV_CERTIFICATE_VERIFY, /* attempts to receive certificate verify message */ TRY_RECV_NEW_SESSION_TICKET, /* attempts to receive new session ticket message */ TRY_RECV_END_OF_EARLY_DATA, /* attempts to receive end of early data message */ TRY_RECV_FINISH, /* attempts to receive finished message */ TRY_RECV_KEY_UPDATE, /* attempts to receive keyupdate message */ TRY_RECV_HELLO_REQUEST, /* attempts to receive hello request message */ HS_STATE_BUTT = 255 /* enumerated Maximum Value */ } HITLS_HandshakeState; typedef enum { TLS_PROCESS_STATE_A, TLS_PROCESS_STATE_B } HitlsProcessState; typedef void (*SendAlertCallback)(const TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description); typedef bool (*GetAlertFlagCallback)(const TLS_Ctx *ctx); typedef int32_t (*UnexpectMsgHandleCallback)(TLS_Ctx *ctx, uint32_t msgType, const uint8_t *data, uint32_t dataLen, bool isPlain); /** Connection management configure */ typedef struct TLSCtxConfig { void *userData; /* user data */ uint16_t linkMtu; /* Maximum transport unit of a path (bytes), including IP header and udp/tcp header */ uint16_t pmtu; /* Maximum transport unit of a path (bytes) */ bool isSupportPto; /* is support process based TLS offload */ uint8_t reserved[1]; /* four-byte alignment */ TLS_Config tlsConfig; /* tls configure context */ } TLS_CtxConfig; typedef struct { uint32_t algRemainTime; /* current key usage times */ uint8_t preMacKey[MAC_KEY_LEN]; /* previous random key */ uint8_t macKey[MAC_KEY_LEN]; /* random key used by the current algorithm */ } CookieInfo; typedef struct { uint16_t version; /* negotiated version */ uint16_t clientVersion; /* version field of client hello */ uint32_t cookieSize; /* cookie length */ uint8_t *cookie; /* cookie data */ CookieInfo cookieInfo; /* cookie info with calculation and verification */ CipherSuiteInfo cipherSuiteInfo; /* cipher suite info */ HITLS_SignHashAlgo signScheme; /* sign algorithm used by the local */ uint8_t *alpnSelected; /* alpn proto */ uint32_t alpnSelectedSize; uint8_t clientVerifyData[MAX_DIGEST_SIZE]; /* client verify data */ uint8_t serverVerifyData[MAX_DIGEST_SIZE]; /* server verify data */ uint8_t clientRandom[RANDOM_SIZE]; /* client random number */ uint8_t serverRandom[RANDOM_SIZE]; /* server random number */ uint32_t clientVerifyDataSize; /* client verify data size */ uint32_t serverVerifyDataSize; /* server verify data size */ uint32_t renegotiationNum; /* the number of renegotiation */ uint32_t certReqSendTime; /* certificate request sending times */ uint32_t tls13BasicKeyExMode; /* TLS13_KE_MODE_PSK_ONLY || TLS13_KE_MODE_PSK_WITH_DHE || TLS13_CERT_AUTH_WITH_DHE */ uint16_t negotiatedGroup; /* negotiated group */ uint16_t recordSizeLimit; /* read record size limit */ uint16_t renegoRecordSizeLimit; uint16_t peerRecordSizeLimit; /* write record size limit */ bool isResume; /* whether to resume the session */ bool isRenegotiation; /* whether to renegotiate */ bool isSecureRenegotiation; /* whether security renegotiation */ bool isExtendedMasterSecret; /* whether to calculate the extended master sercret */ bool isEncryptThenMac; /* Whether to enable EncryptThenMac */ bool isEncryptThenMacRead; /* Whether to enable EncryptThenMacRead */ bool isEncryptThenMacWrite; /* Whether to enable EncryptThenMacWrite */ bool isTicket; /* whether to negotiate tickets, only below tls1.3 */ bool isSniStateOK; /* Whether server successfully processes the server_name callback */ } TLS_NegotiatedInfo; typedef struct { uint16_t *groups; /* all groups sent by the peer end */ uint32_t groupsSize; /* size of a group */ uint16_t *cipherSuites; /* all cipher suites sent by the peer end */ uint16_t cipherSuitesSize; /* size of a cipher suites */ HITLS_SignHashAlgo peerSignHashAlg; /* peer signature algorithm */ uint16_t *signatureAlgorithms; uint16_t signatureAlgorithmsSize; HITLS_ERROR verifyResult; /* record the certificate verification result of the peer end */ HITLS_TrustedCAList *caList; /* peer trusted ca list */ } PeerInfo; struct TlsCtx { bool isClient; /* is Client */ bool userShutDown; /* record whether the local end invokes the HITLS_Close */ bool userRenego; /* record whether the local end initiates renegotiation */ uint8_t rwstate; /* record the current internal read and write state */ CM_State preState; CM_State state; uint32_t shutdownState; /* Record the shutdown state */ void *rUio; /* read uio */ void *uio; /* write uio */ void *bUio; /* Storing uio */ HS_Ctx *hsCtx; /* handshake context */ CCS_Ctx *ccsCtx; /* ChangeCipherSpec context */ ALERT_Ctx *alertCtx; /* alert context */ REC_Ctx *recCtx; /* record context */ struct { IsRecvCcsCallback isRecvCCS; SendCcsCallback sendCCS; /* send a CCS message */ CtrlCcsCallback ctrlCCS; /* controlling CCS */ SendAlertCallback sendAlert; /* set the alert message to be sent */ GetAlertFlagCallback getAlertFlag; /* get alert state */ UnexpectMsgHandleCallback unexpectedMsgProcessCb; /* the callback for unexpected messages */ } method; PeerInfo peerInfo; /* Temporarily save the messages sent by the peer end */ TLS_CtxConfig config; /* private configuration */ TLS_Config *globalConfig; /* global configuration */ TLS_NegotiatedInfo negotiatedInfo; /* TLS negotiation information */ HITLS_Session *session; /* session information */ uint8_t clientAppTrafficSecret[MAX_DIGEST_SIZE]; /* TLS1.3 client app traffic secret */ uint8_t serverAppTrafficSecret[MAX_DIGEST_SIZE]; /* TLS1.3 server app traffic secret */ uint8_t resumptionMasterSecret[MAX_DIGEST_SIZE]; /* TLS1.3 session resume secret */ uint32_t bytesLeftToRead; /* bytes left to read after hs header has parsed */ uint32_t keyUpdateType; /* TLS1.3 key update type */ bool isKeyUpdateRequest; /* TLS1.3 Check whether there are unsent key update messages */ bool haveClientPointFormats; /* whether the EC point format extension in the client hello is processed */ uint8_t peekFlag; /* peekFlag equals 0, read mode; otherwise, peek mode */ bool hasParsedHsMsgHeader; /* has parsed current hs msg header */ int32_t errorCode; /* Record the tls error code */ HITLS_HASH_Ctx *phaHash; /* tls1.3 pha: Handshake main process hash */ HITLS_HASH_Ctx *phaCurHash; /* tls1.3 pha: Temporarily store the current pha hash */ PHA_State phaState; /* tls1.3 pha state */ uint8_t *certificateReqCtx; /* tls1.3 pha certificate_request_context */ uint32_t certificateReqCtxSize; /* tls1.3 pha certificate_request_context */ bool isDtlsListen; bool plainAlertForbid; /* tls1.3 forbid to receive plain alert message */ bool allowAppOut; /* whether user used HITLS_read to start renegotiation */ bool noQueryMtu; /* Don't query the mtu from bio */ bool needQueryMtu; /* whether need query mtu from bio */ bool mtuModified; /* whether mtu has been modified */ }; typedef struct { uint8_t **buf; // &hsCtx->msgbuf uint32_t *bufLen; // &hsCtx->bufferLen uint32_t *bufOffset; // &hsCtx->msgLen } PackPacket; #define LIBCTX_FROM_CTX(ctx) ((ctx == NULL) ? NULL : (ctx)->config.tlsConfig.libCtx) #define ATTRIBUTE_FROM_CTX(ctx) ((ctx == NULL) ? NULL : (ctx)->config.tlsConfig.attrName) #define CUSTOM_EXT_FROM_CTX(ctx) ((ctx == NULL) ? NULL : (ctx)->config.tlsConfig.customExts) #ifdef __cplusplus } #endif #endif /* TLS_H */
2302_82127028/openHiTLS-examples
tls/include/tls.h
C
unknown
15,877
/* * 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 TLS_BINLOG_ID_H #define TLS_BINLOG_ID_H #include <stdint.h> #include "hitls_build.h" #include "bsl_log.h" #include "bsl_log_internal.h" #ifdef __cplusplus extern "C" { #endif #ifdef HITLS_BSL_LOG #define BINGLOG_STR(str) (str) #else #define BINGLOG_STR(str) NULL #endif enum TLS_BINLOG_ID { BINLOG_ID15001 = 15001, BINLOG_ID15002, BINLOG_ID15003, BINLOG_ID15004, BINLOG_ID15005, BINLOG_ID15006, BINLOG_ID15007, BINLOG_ID15008, BINLOG_ID15009, BINLOG_ID15010, BINLOG_ID15011, BINLOG_ID15012, BINLOG_ID15013, BINLOG_ID15014, BINLOG_ID15015, BINLOG_ID15016, BINLOG_ID15017, BINLOG_ID15018, BINLOG_ID15019, BINLOG_ID15020, BINLOG_ID15021, BINLOG_ID15022, BINLOG_ID15023, BINLOG_ID15024, BINLOG_ID15025, BINLOG_ID15026, BINLOG_ID15027, BINLOG_ID15028, BINLOG_ID15029, BINLOG_ID15030, BINLOG_ID15031, BINLOG_ID15032, BINLOG_ID15033, BINLOG_ID15034, BINLOG_ID15035, BINLOG_ID15036, BINLOG_ID15037, BINLOG_ID15038, BINLOG_ID15039, BINLOG_ID15040, BINLOG_ID15041, BINLOG_ID15042, BINLOG_ID15043, BINLOG_ID15044, BINLOG_ID15045, BINLOG_ID15046, BINLOG_ID15047, BINLOG_ID15048, BINLOG_ID15049, BINLOG_ID15050, BINLOG_ID15051, BINLOG_ID15052, BINLOG_ID15053, BINLOG_ID15054, BINLOG_ID15055, BINLOG_ID15056, BINLOG_ID15057, BINLOG_ID15058, BINLOG_ID15059, BINLOG_ID15060, BINLOG_ID15061, BINLOG_ID15062, BINLOG_ID15063, BINLOG_ID15064, BINLOG_ID15065, BINLOG_ID15066, BINLOG_ID15067, BINLOG_ID15068, BINLOG_ID15069, BINLOG_ID15070, BINLOG_ID15071, BINLOG_ID15072, BINLOG_ID15073, BINLOG_ID15074, BINLOG_ID15075, BINLOG_ID15076, BINLOG_ID15077, BINLOG_ID15078, BINLOG_ID15079, BINLOG_ID15080, BINLOG_ID15081, BINLOG_ID15082, BINLOG_ID15083, BINLOG_ID15084, BINLOG_ID15085, BINLOG_ID15086, BINLOG_ID15087, BINLOG_ID15088, BINLOG_ID15089, BINLOG_ID15090, BINLOG_ID15091, BINLOG_ID15092, BINLOG_ID15093, BINLOG_ID15094, BINLOG_ID15095, BINLOG_ID15096, BINLOG_ID15097, BINLOG_ID15098, BINLOG_ID15099, BINLOG_ID15100, BINLOG_ID15101, BINLOG_ID15102, BINLOG_ID15103, BINLOG_ID15104, BINLOG_ID15105, BINLOG_ID15106, BINLOG_ID15107, BINLOG_ID15108, BINLOG_ID15109, BINLOG_ID15110, BINLOG_ID15111, BINLOG_ID15112, BINLOG_ID15113, BINLOG_ID15114, BINLOG_ID15115, BINLOG_ID15116, BINLOG_ID15117, BINLOG_ID15118, BINLOG_ID15119, BINLOG_ID15120, BINLOG_ID15121, BINLOG_ID15122, BINLOG_ID15123, BINLOG_ID15124, BINLOG_ID15125, BINLOG_ID15126, BINLOG_ID15127, BINLOG_ID15128, BINLOG_ID15129, BINLOG_ID15130, BINLOG_ID15131, BINLOG_ID15132, BINLOG_ID15133, BINLOG_ID15134, BINLOG_ID15135, BINLOG_ID15136, BINLOG_ID15137, BINLOG_ID15138, BINLOG_ID15139, BINLOG_ID15140, BINLOG_ID15141, BINLOG_ID15142, BINLOG_ID15143, BINLOG_ID15144, BINLOG_ID15145, BINLOG_ID15146, BINLOG_ID15147, BINLOG_ID15148, BINLOG_ID15149, BINLOG_ID15150, BINLOG_ID15151, BINLOG_ID15152, BINLOG_ID15153, BINLOG_ID15154, BINLOG_ID15155, BINLOG_ID15156, BINLOG_ID15157, BINLOG_ID15158, BINLOG_ID15159, BINLOG_ID15160, BINLOG_ID15161, BINLOG_ID15162, BINLOG_ID15163, BINLOG_ID15164, BINLOG_ID15165, BINLOG_ID15166, BINLOG_ID15167, BINLOG_ID15168, BINLOG_ID15169, BINLOG_ID15170, BINLOG_ID15171, BINLOG_ID15172, BINLOG_ID15173, BINLOG_ID15174, BINLOG_ID15175, BINLOG_ID15176, BINLOG_ID15177, BINLOG_ID15178, BINLOG_ID15179, BINLOG_ID15180, BINLOG_ID15181, BINLOG_ID15182, BINLOG_ID15183, BINLOG_ID15184, BINLOG_ID15185, BINLOG_ID15186, BINLOG_ID15187, BINLOG_ID15188, BINLOG_ID15189, BINLOG_ID15190, BINLOG_ID15191, BINLOG_ID15192, BINLOG_ID15193, BINLOG_ID15194, BINLOG_ID15195, BINLOG_ID15196, BINLOG_ID15197, BINLOG_ID15198, BINLOG_ID15199, BINLOG_ID15200, BINLOG_ID15201, BINLOG_ID15202, BINLOG_ID15203, BINLOG_ID15204, BINLOG_ID15205, BINLOG_ID15206, BINLOG_ID15207, BINLOG_ID15208, BINLOG_ID15209, BINLOG_ID15210, BINLOG_ID15211, BINLOG_ID15212, BINLOG_ID15213, BINLOG_ID15214, BINLOG_ID15215, BINLOG_ID15216, BINLOG_ID15217, BINLOG_ID15218, BINLOG_ID15219, BINLOG_ID15220, BINLOG_ID15221, BINLOG_ID15222, BINLOG_ID15223, BINLOG_ID15224, BINLOG_ID15225, BINLOG_ID15226, BINLOG_ID15227, BINLOG_ID15228, BINLOG_ID15229, BINLOG_ID15230, BINLOG_ID15231, BINLOG_ID15232, BINLOG_ID15233, BINLOG_ID15234, BINLOG_ID15235, BINLOG_ID15236, BINLOG_ID15237, BINLOG_ID15238, BINLOG_ID15239, BINLOG_ID15240, BINLOG_ID15241, BINLOG_ID15242, BINLOG_ID15243, BINLOG_ID15244, BINLOG_ID15245, BINLOG_ID15246, BINLOG_ID15247, BINLOG_ID15248, BINLOG_ID15249, BINLOG_ID15250, BINLOG_ID15251, BINLOG_ID15252, BINLOG_ID15253, BINLOG_ID15254, BINLOG_ID15255, BINLOG_ID15256, BINLOG_ID15257, BINLOG_ID15258, BINLOG_ID15259, BINLOG_ID15260, BINLOG_ID15261, BINLOG_ID15262, BINLOG_ID15263, BINLOG_ID15264, BINLOG_ID15265, BINLOG_ID15266, BINLOG_ID15267, BINLOG_ID15268, BINLOG_ID15269, BINLOG_ID15270, BINLOG_ID15271, BINLOG_ID15272, BINLOG_ID15273, BINLOG_ID15274, BINLOG_ID15275, BINLOG_ID15276, BINLOG_ID15277, BINLOG_ID15278, BINLOG_ID15279, BINLOG_ID15280, BINLOG_ID15281, BINLOG_ID15282, BINLOG_ID15283, BINLOG_ID15284, BINLOG_ID15285, BINLOG_ID15286, BINLOG_ID15287, BINLOG_ID15288, BINLOG_ID15289, BINLOG_ID15290, BINLOG_ID15291, BINLOG_ID15292, BINLOG_ID15293, BINLOG_ID15294, BINLOG_ID15295, BINLOG_ID15296, BINLOG_ID15297, BINLOG_ID15298, BINLOG_ID15299, BINLOG_ID15300, BINLOG_ID15301, BINLOG_ID15302, BINLOG_ID15303, BINLOG_ID15304, BINLOG_ID15305, BINLOG_ID15306, BINLOG_ID15307, BINLOG_ID15308, BINLOG_ID15309, BINLOG_ID15310, BINLOG_ID15311, BINLOG_ID15312, BINLOG_ID15313, BINLOG_ID15314, BINLOG_ID15315, BINLOG_ID15316, BINLOG_ID15317, BINLOG_ID15318, BINLOG_ID15319, BINLOG_ID15320, BINLOG_ID15321, BINLOG_ID15322, BINLOG_ID15323, BINLOG_ID15324, BINLOG_ID15325, BINLOG_ID15326, BINLOG_ID15327, BINLOG_ID15328, BINLOG_ID15329, BINLOG_ID15330, BINLOG_ID15331, BINLOG_ID15332, BINLOG_ID15333, BINLOG_ID15334, BINLOG_ID15335, BINLOG_ID15336, BINLOG_ID15337, BINLOG_ID15338, BINLOG_ID15339, BINLOG_ID15340, BINLOG_ID15341, BINLOG_ID15342, BINLOG_ID15343, BINLOG_ID15344, BINLOG_ID15345, BINLOG_ID15346, BINLOG_ID15347, BINLOG_ID15348, BINLOG_ID15349, BINLOG_ID15350, BINLOG_ID15351, BINLOG_ID15352, BINLOG_ID15353, BINLOG_ID15354, BINLOG_ID15355, BINLOG_ID15356, BINLOG_ID15357, BINLOG_ID15358, BINLOG_ID15359, BINLOG_ID15360, BINLOG_ID15361, BINLOG_ID15362, BINLOG_ID15363, BINLOG_ID15364, BINLOG_ID15365, BINLOG_ID15366, BINLOG_ID15367, BINLOG_ID15368, BINLOG_ID15369, BINLOG_ID15370, BINLOG_ID15371, BINLOG_ID15372, BINLOG_ID15373, BINLOG_ID15374, BINLOG_ID15375, BINLOG_ID15376, BINLOG_ID15377, BINLOG_ID15378, BINLOG_ID15379, BINLOG_ID15380, BINLOG_ID15381, BINLOG_ID15382, BINLOG_ID15383, BINLOG_ID15384, BINLOG_ID15385, BINLOG_ID15386, BINLOG_ID15387, BINLOG_ID15388, BINLOG_ID15389, BINLOG_ID15390, BINLOG_ID15391, BINLOG_ID15392, BINLOG_ID15393, BINLOG_ID15394, BINLOG_ID15395, BINLOG_ID15396, BINLOG_ID15397, BINLOG_ID15398, BINLOG_ID15399, BINLOG_ID15400, BINLOG_ID15401, BINLOG_ID15402, BINLOG_ID15403, BINLOG_ID15404, BINLOG_ID15405, BINLOG_ID15406, BINLOG_ID15407, BINLOG_ID15408, BINLOG_ID15409, BINLOG_ID15410, BINLOG_ID15411, BINLOG_ID15412, BINLOG_ID15413, BINLOG_ID15414, BINLOG_ID15415, BINLOG_ID15416, BINLOG_ID15417, BINLOG_ID15418, BINLOG_ID15419, BINLOG_ID15420, BINLOG_ID15421, BINLOG_ID15422, BINLOG_ID15423, BINLOG_ID15424, BINLOG_ID15425, BINLOG_ID15426, BINLOG_ID15427, BINLOG_ID15428, BINLOG_ID15429, BINLOG_ID15430, BINLOG_ID15431, BINLOG_ID15432, BINLOG_ID15433, BINLOG_ID15434, BINLOG_ID15435, BINLOG_ID15436, BINLOG_ID15437, BINLOG_ID15438, BINLOG_ID15439, BINLOG_ID15440, BINLOG_ID15441, BINLOG_ID15442, BINLOG_ID15443, BINLOG_ID15444, BINLOG_ID15445, BINLOG_ID15446, BINLOG_ID15447, BINLOG_ID15448, BINLOG_ID15449, BINLOG_ID15450, BINLOG_ID15451, BINLOG_ID15452, BINLOG_ID15453, BINLOG_ID15454, BINLOG_ID15455, BINLOG_ID15456, BINLOG_ID15457, BINLOG_ID15458, BINLOG_ID15459, BINLOG_ID15460, BINLOG_ID15461, BINLOG_ID15462, BINLOG_ID15463, BINLOG_ID15464, BINLOG_ID15465, BINLOG_ID15466, BINLOG_ID15467, BINLOG_ID15468, BINLOG_ID15469, BINLOG_ID15470, BINLOG_ID15471, BINLOG_ID15472, BINLOG_ID15473, BINLOG_ID15474, BINLOG_ID15475, BINLOG_ID15476, BINLOG_ID15477, BINLOG_ID15478, BINLOG_ID15479, BINLOG_ID15480, BINLOG_ID15481, BINLOG_ID15482, BINLOG_ID15483, BINLOG_ID15484, BINLOG_ID15485, BINLOG_ID15486, BINLOG_ID15487, BINLOG_ID15488, BINLOG_ID15489, BINLOG_ID15490, BINLOG_ID15491, BINLOG_ID15492, BINLOG_ID15493, BINLOG_ID15494, BINLOG_ID15495, BINLOG_ID15496, BINLOG_ID15497, BINLOG_ID15498, BINLOG_ID15499, BINLOG_ID15500, BINLOG_ID15501, BINLOG_ID15502, BINLOG_ID15503, BINLOG_ID15504, BINLOG_ID15505, BINLOG_ID15506, BINLOG_ID15507, BINLOG_ID15508, BINLOG_ID15509, BINLOG_ID15510, BINLOG_ID15511, BINLOG_ID15512, BINLOG_ID15513, BINLOG_ID15514, BINLOG_ID15515, BINLOG_ID15516, BINLOG_ID15517, BINLOG_ID15518, BINLOG_ID15519, BINLOG_ID15520, BINLOG_ID15521, BINLOG_ID15522, BINLOG_ID15523, BINLOG_ID15524, BINLOG_ID15525, BINLOG_ID15526, BINLOG_ID15527, BINLOG_ID15528, BINLOG_ID15529, BINLOG_ID15530, BINLOG_ID15531, BINLOG_ID15532, BINLOG_ID15533, BINLOG_ID15534, BINLOG_ID15535, BINLOG_ID15536, BINLOG_ID15537, BINLOG_ID15538, BINLOG_ID15539, BINLOG_ID15540, BINLOG_ID15541, BINLOG_ID15542, BINLOG_ID15543, BINLOG_ID15544, BINLOG_ID15545, BINLOG_ID15546, BINLOG_ID15547, BINLOG_ID15548, BINLOG_ID15549, BINLOG_ID15550, BINLOG_ID15551, BINLOG_ID15552, BINLOG_ID15553, BINLOG_ID15554, BINLOG_ID15555, BINLOG_ID15556, BINLOG_ID15557, BINLOG_ID15558, BINLOG_ID15559, BINLOG_ID15560, BINLOG_ID15561, BINLOG_ID15562, BINLOG_ID15563, BINLOG_ID15564, BINLOG_ID15565, BINLOG_ID15566, BINLOG_ID15567, BINLOG_ID15568, BINLOG_ID15569, BINLOG_ID15570, BINLOG_ID15571, BINLOG_ID15572, BINLOG_ID15573, BINLOG_ID15574, BINLOG_ID15575, BINLOG_ID15576, BINLOG_ID15577, BINLOG_ID15578, BINLOG_ID15579, BINLOG_ID15580, BINLOG_ID15581, BINLOG_ID15582, BINLOG_ID15583, BINLOG_ID15584, BINLOG_ID15585, BINLOG_ID15586, BINLOG_ID15587, BINLOG_ID15588, BINLOG_ID15589, BINLOG_ID15590, BINLOG_ID15591, BINLOG_ID15592, BINLOG_ID15593, BINLOG_ID15594, BINLOG_ID15595, BINLOG_ID15596, BINLOG_ID15597, BINLOG_ID15598, BINLOG_ID15599, BINLOG_ID15600, BINLOG_ID15601, BINLOG_ID15602, BINLOG_ID15603, BINLOG_ID15604, BINLOG_ID15605, BINLOG_ID15606, BINLOG_ID15607, BINLOG_ID15608, BINLOG_ID15609, BINLOG_ID15610, BINLOG_ID15611, BINLOG_ID15612, BINLOG_ID15613, BINLOG_ID15614, BINLOG_ID15615, BINLOG_ID15616, BINLOG_ID15617, BINLOG_ID15618, BINLOG_ID15619, BINLOG_ID15620, BINLOG_ID15621, BINLOG_ID15622, BINLOG_ID15623, BINLOG_ID15624, BINLOG_ID15625, BINLOG_ID15626, BINLOG_ID15627, BINLOG_ID15628, BINLOG_ID15629, BINLOG_ID15630, BINLOG_ID15631, BINLOG_ID15632, BINLOG_ID15633, BINLOG_ID15634, BINLOG_ID15635, BINLOG_ID15636, BINLOG_ID15637, BINLOG_ID15638, BINLOG_ID15639, BINLOG_ID15640, BINLOG_ID15641, BINLOG_ID15642, BINLOG_ID15643, BINLOG_ID15644, BINLOG_ID15645, BINLOG_ID15646, BINLOG_ID15647, BINLOG_ID15648, BINLOG_ID15649, BINLOG_ID15650, BINLOG_ID15651, BINLOG_ID15652, BINLOG_ID15653, BINLOG_ID15654, BINLOG_ID15655, BINLOG_ID15656, BINLOG_ID15657, BINLOG_ID15658, BINLOG_ID15659, BINLOG_ID15660, BINLOG_ID15661, BINLOG_ID15662, BINLOG_ID15663, BINLOG_ID15664, BINLOG_ID15665, BINLOG_ID15666, BINLOG_ID15667, BINLOG_ID15668, BINLOG_ID15669, BINLOG_ID15670, BINLOG_ID15671, BINLOG_ID15672, BINLOG_ID15673, BINLOG_ID15674, BINLOG_ID15675, BINLOG_ID15676, BINLOG_ID15677, BINLOG_ID15678, BINLOG_ID15679, BINLOG_ID15680, BINLOG_ID15681, BINLOG_ID15682, BINLOG_ID15683, BINLOG_ID15684, BINLOG_ID15685, BINLOG_ID15686, BINLOG_ID15687, BINLOG_ID15688, BINLOG_ID15689, BINLOG_ID15690, BINLOG_ID15691, BINLOG_ID15692, BINLOG_ID15693, BINLOG_ID15694, BINLOG_ID15695, BINLOG_ID15696, BINLOG_ID15697, BINLOG_ID15698, BINLOG_ID15699, BINLOG_ID15700, BINLOG_ID15701, BINLOG_ID15702, BINLOG_ID15703, BINLOG_ID15704, BINLOG_ID15705, BINLOG_ID15706, BINLOG_ID15707, BINLOG_ID15708, BINLOG_ID15709, BINLOG_ID15710, BINLOG_ID15711, BINLOG_ID15712, BINLOG_ID15713, BINLOG_ID15714, BINLOG_ID15715, BINLOG_ID15716, BINLOG_ID15717, BINLOG_ID15718, BINLOG_ID15719, BINLOG_ID15720, BINLOG_ID15721, BINLOG_ID15722, BINLOG_ID15723, BINLOG_ID15724, BINLOG_ID15725, BINLOG_ID15726, BINLOG_ID15727, BINLOG_ID15728, BINLOG_ID15729, BINLOG_ID15730, BINLOG_ID15731, BINLOG_ID15732, BINLOG_ID15733, BINLOG_ID15734, BINLOG_ID15735, BINLOG_ID15736, BINLOG_ID15737, BINLOG_ID15738, BINLOG_ID15739, BINLOG_ID15740, BINLOG_ID15741, BINLOG_ID15742, BINLOG_ID15743, BINLOG_ID15744, BINLOG_ID15745, BINLOG_ID15746, BINLOG_ID15747, BINLOG_ID15748, BINLOG_ID15749, BINLOG_ID15750, BINLOG_ID15751, BINLOG_ID15752, BINLOG_ID15753, BINLOG_ID15754, BINLOG_ID15755, BINLOG_ID15756, BINLOG_ID15757, BINLOG_ID15758, BINLOG_ID15759, BINLOG_ID15760, BINLOG_ID15761, BINLOG_ID15762, BINLOG_ID15763, BINLOG_ID15764, BINLOG_ID15765, BINLOG_ID15766, BINLOG_ID15767, BINLOG_ID15768, BINLOG_ID15769, BINLOG_ID15770, BINLOG_ID15771, BINLOG_ID15772, BINLOG_ID15773, BINLOG_ID15774, BINLOG_ID15775, BINLOG_ID15776, BINLOG_ID15777, BINLOG_ID15778, BINLOG_ID15779, BINLOG_ID15780, BINLOG_ID15781, BINLOG_ID15782, BINLOG_ID15783, BINLOG_ID15784, BINLOG_ID15785, BINLOG_ID15786, BINLOG_ID15787, BINLOG_ID15788, BINLOG_ID15789, BINLOG_ID15790, BINLOG_ID15791, BINLOG_ID15792, BINLOG_ID15793, BINLOG_ID15794, BINLOG_ID15795, BINLOG_ID15796, BINLOG_ID15797, BINLOG_ID15798, BINLOG_ID15799, BINLOG_ID15800, BINLOG_ID15801, BINLOG_ID15802, BINLOG_ID15803, BINLOG_ID15804, BINLOG_ID15805, BINLOG_ID15806, BINLOG_ID15807, BINLOG_ID15808, BINLOG_ID15809, BINLOG_ID15810, BINLOG_ID15811, BINLOG_ID15812, BINLOG_ID15813, BINLOG_ID15814, BINLOG_ID15815, BINLOG_ID15816, BINLOG_ID15817, BINLOG_ID15818, BINLOG_ID15819, BINLOG_ID15820, BINLOG_ID15821, BINLOG_ID15822, BINLOG_ID15823, BINLOG_ID15824, BINLOG_ID15825, BINLOG_ID15826, BINLOG_ID15827, BINLOG_ID15828, BINLOG_ID15829, BINLOG_ID15830, BINLOG_ID15831, BINLOG_ID15832, BINLOG_ID15833, BINLOG_ID15834, BINLOG_ID15835, BINLOG_ID15836, BINLOG_ID15837, BINLOG_ID15838, BINLOG_ID15839, BINLOG_ID15840, BINLOG_ID15841, BINLOG_ID15842, BINLOG_ID15843, BINLOG_ID15844, BINLOG_ID15845, BINLOG_ID15846, BINLOG_ID15847, BINLOG_ID15848, BINLOG_ID15849, BINLOG_ID15850, BINLOG_ID15851, BINLOG_ID15852, BINLOG_ID15853, BINLOG_ID15854, BINLOG_ID15855, BINLOG_ID15856, BINLOG_ID15857, BINLOG_ID15858, BINLOG_ID15859, BINLOG_ID15860, BINLOG_ID15861, BINLOG_ID15862, BINLOG_ID15863, BINLOG_ID15864, BINLOG_ID15865, BINLOG_ID15866, BINLOG_ID15867, BINLOG_ID15868, BINLOG_ID15869, BINLOG_ID15870, BINLOG_ID15871, BINLOG_ID15872, BINLOG_ID15873, BINLOG_ID15874, BINLOG_ID15875, BINLOG_ID15876, BINLOG_ID15877, BINLOG_ID15878, BINLOG_ID15879, BINLOG_ID15880, BINLOG_ID15881, BINLOG_ID15882, BINLOG_ID15883, BINLOG_ID15884, BINLOG_ID15885, BINLOG_ID15886, BINLOG_ID15887, BINLOG_ID15888, BINLOG_ID15889, BINLOG_ID15890, BINLOG_ID15891, BINLOG_ID15892, BINLOG_ID15893, BINLOG_ID15894, BINLOG_ID15895, BINLOG_ID15896, BINLOG_ID15897, BINLOG_ID15898, BINLOG_ID15899, BINLOG_ID15900, BINLOG_ID15901, BINLOG_ID15902, BINLOG_ID15903, BINLOG_ID15904, BINLOG_ID15905, BINLOG_ID15906, BINLOG_ID15907, BINLOG_ID15908, BINLOG_ID15909, BINLOG_ID15910, BINLOG_ID15911, BINLOG_ID15912, BINLOG_ID15913, BINLOG_ID15914, BINLOG_ID15915, BINLOG_ID15916, BINLOG_ID15917, BINLOG_ID15918, BINLOG_ID15919, BINLOG_ID15920, BINLOG_ID15921, BINLOG_ID15922, BINLOG_ID15923, BINLOG_ID15924, BINLOG_ID15925, BINLOG_ID15926, BINLOG_ID15927, BINLOG_ID15928, BINLOG_ID15929, BINLOG_ID15930, BINLOG_ID15931, BINLOG_ID15932, BINLOG_ID15933, BINLOG_ID15934, BINLOG_ID15935, BINLOG_ID15936, BINLOG_ID15937, BINLOG_ID15938, BINLOG_ID15939, BINLOG_ID15940, BINLOG_ID15941, BINLOG_ID15942, BINLOG_ID15943, BINLOG_ID15944, BINLOG_ID15945, BINLOG_ID15946, BINLOG_ID15947, BINLOG_ID15948, BINLOG_ID15949, BINLOG_ID15950, BINLOG_ID15951, BINLOG_ID15952, BINLOG_ID15953, BINLOG_ID15954, BINLOG_ID15955, BINLOG_ID15956, BINLOG_ID15957, BINLOG_ID15958, BINLOG_ID15959, BINLOG_ID15960, BINLOG_ID15961, BINLOG_ID15962, BINLOG_ID15963, BINLOG_ID15964, BINLOG_ID15965, BINLOG_ID15966, BINLOG_ID15967, BINLOG_ID15968, BINLOG_ID15969, BINLOG_ID15970, BINLOG_ID15971, BINLOG_ID15972, BINLOG_ID15973, BINLOG_ID15974, BINLOG_ID15975, BINLOG_ID15976, BINLOG_ID15977, BINLOG_ID15978, BINLOG_ID15979, BINLOG_ID15980, BINLOG_ID15981, BINLOG_ID15982, BINLOG_ID15983, BINLOG_ID15984, BINLOG_ID15985, BINLOG_ID15986, BINLOG_ID15987, BINLOG_ID15988, BINLOG_ID15989, BINLOG_ID15990, BINLOG_ID15991, BINLOG_ID15992, BINLOG_ID15993, BINLOG_ID15994, BINLOG_ID15995, BINLOG_ID15996, BINLOG_ID15997, BINLOG_ID15998, BINLOG_ID15999, BINLOG_ID16000, BINLOG_ID16001, BINLOG_ID16002, BINLOG_ID16003, BINLOG_ID16004, BINLOG_ID16005, BINLOG_ID16006, BINLOG_ID16007, BINLOG_ID16008, BINLOG_ID16009, BINLOG_ID16010, BINLOG_ID16011, BINLOG_ID16012, BINLOG_ID16013, BINLOG_ID16014, BINLOG_ID16015, BINLOG_ID16016, BINLOG_ID16017, BINLOG_ID16018, BINLOG_ID16019, BINLOG_ID16020, BINLOG_ID16021, BINLOG_ID16022, BINLOG_ID16023, BINLOG_ID16024, BINLOG_ID16025, BINLOG_ID16026, BINLOG_ID16027, BINLOG_ID16028, BINLOG_ID16029, BINLOG_ID16030, BINLOG_ID16031, BINLOG_ID16032, BINLOG_ID16033, BINLOG_ID16034, BINLOG_ID16035, BINLOG_ID16036, BINLOG_ID16037, BINLOG_ID16038, BINLOG_ID16039, BINLOG_ID16040, BINLOG_ID16041, BINLOG_ID16042, BINLOG_ID16043, BINLOG_ID16044, BINLOG_ID16045, BINLOG_ID16046, BINLOG_ID16047, BINLOG_ID16048, BINLOG_ID16049, BINLOG_ID16050, BINLOG_ID16051, BINLOG_ID16052, BINLOG_ID16053, BINLOG_ID16054, BINLOG_ID16055, BINLOG_ID16056, BINLOG_ID16057, BINLOG_ID16058, BINLOG_ID16059, BINLOG_ID16060, BINLOG_ID16061, BINLOG_ID16062, BINLOG_ID16063, BINLOG_ID16064, BINLOG_ID16065, BINLOG_ID16066, BINLOG_ID16067, BINLOG_ID16068, BINLOG_ID16069, BINLOG_ID16070, BINLOG_ID16071, BINLOG_ID16072, BINLOG_ID16073, BINLOG_ID16074, BINLOG_ID16075, BINLOG_ID16076, BINLOG_ID16077, BINLOG_ID16078, BINLOG_ID16079, BINLOG_ID16080, BINLOG_ID16081, BINLOG_ID16082, BINLOG_ID16083, BINLOG_ID16084, BINLOG_ID16085, BINLOG_ID16086, BINLOG_ID16087, BINLOG_ID16088, BINLOG_ID16089, BINLOG_ID16090, BINLOG_ID16091, BINLOG_ID16092, BINLOG_ID16093, BINLOG_ID16094, BINLOG_ID16095, BINLOG_ID16096, BINLOG_ID16097, BINLOG_ID16098, BINLOG_ID16099, BINLOG_ID16100, BINLOG_ID16101, BINLOG_ID16102, BINLOG_ID16103, BINLOG_ID16104, BINLOG_ID16105, BINLOG_ID16106, BINLOG_ID16107, BINLOG_ID16108, BINLOG_ID16109, BINLOG_ID16110, BINLOG_ID16111, BINLOG_ID16112, BINLOG_ID16113, BINLOG_ID16114, BINLOG_ID16115, BINLOG_ID16116, BINLOG_ID16117, BINLOG_ID16118, BINLOG_ID16119, BINLOG_ID16120, BINLOG_ID16121, BINLOG_ID16122, BINLOG_ID16123, BINLOG_ID16124, BINLOG_ID16125, BINLOG_ID16126, BINLOG_ID16127, BINLOG_ID16128, BINLOG_ID16129, BINLOG_ID16130, BINLOG_ID16131, BINLOG_ID16132, BINLOG_ID16133, BINLOG_ID16134, BINLOG_ID16135, BINLOG_ID16136, BINLOG_ID16137, BINLOG_ID16138, BINLOG_ID16139, BINLOG_ID16140, BINLOG_ID16141, BINLOG_ID16142, BINLOG_ID16143, BINLOG_ID16144, BINLOG_ID16145, BINLOG_ID16146, BINLOG_ID16147, BINLOG_ID16148, BINLOG_ID16149, BINLOG_ID16150, BINLOG_ID16151, BINLOG_ID16152, BINLOG_ID16153, BINLOG_ID16154, BINLOG_ID16155, BINLOG_ID16156, BINLOG_ID16157, BINLOG_ID16158, BINLOG_ID16159, BINLOG_ID16160, BINLOG_ID16161, BINLOG_ID16162, BINLOG_ID16163, BINLOG_ID16164, BINLOG_ID16165, BINLOG_ID16166, BINLOG_ID16167, BINLOG_ID16168, BINLOG_ID16169, BINLOG_ID16170, BINLOG_ID16171, BINLOG_ID16172, BINLOG_ID16173, BINLOG_ID16174, BINLOG_ID16175, BINLOG_ID16176, BINLOG_ID16177, BINLOG_ID16178, BINLOG_ID16179, BINLOG_ID16180, BINLOG_ID16181, BINLOG_ID16182, BINLOG_ID16183, BINLOG_ID16184, BINLOG_ID16185, BINLOG_ID16186, BINLOG_ID16187, BINLOG_ID16188, BINLOG_ID16189, BINLOG_ID16190, BINLOG_ID16191, BINLOG_ID16192, BINLOG_ID16193, BINLOG_ID16194, BINLOG_ID16195, BINLOG_ID16196, BINLOG_ID16197, BINLOG_ID16198, BINLOG_ID16199, BINLOG_ID16200, BINLOG_ID16201, BINLOG_ID16202, BINLOG_ID16203, BINLOG_ID16204, BINLOG_ID16205, BINLOG_ID16206, BINLOG_ID16207, BINLOG_ID16208, BINLOG_ID16209, BINLOG_ID16210, BINLOG_ID16211, BINLOG_ID16212, BINLOG_ID16213, BINLOG_ID16214, BINLOG_ID16215, BINLOG_ID16216, BINLOG_ID16217, BINLOG_ID16218, BINLOG_ID16219, BINLOG_ID16220, BINLOG_ID16221, BINLOG_ID16222, BINLOG_ID16223, BINLOG_ID16224, BINLOG_ID16225, BINLOG_ID16226, BINLOG_ID16227, BINLOG_ID16228, BINLOG_ID16229, BINLOG_ID16230, BINLOG_ID16231, BINLOG_ID16232, BINLOG_ID16233, BINLOG_ID16234, BINLOG_ID16235, BINLOG_ID16236, BINLOG_ID16237, BINLOG_ID16238, BINLOG_ID16239, BINLOG_ID16240, BINLOG_ID16241, BINLOG_ID16242, BINLOG_ID16243, BINLOG_ID16244, BINLOG_ID16245, BINLOG_ID16246, BINLOG_ID16247, BINLOG_ID16248, BINLOG_ID16249, BINLOG_ID16250, BINLOG_ID16251, BINLOG_ID16252, BINLOG_ID16253, BINLOG_ID16254, BINLOG_ID16255, BINLOG_ID16256, BINLOG_ID16257, BINLOG_ID16258, BINLOG_ID16259, BINLOG_ID16260, BINLOG_ID16261, BINLOG_ID16262, BINLOG_ID16263, BINLOG_ID16264, BINLOG_ID16265, BINLOG_ID16266, BINLOG_ID16267, BINLOG_ID16268, BINLOG_ID16269, BINLOG_ID16270, BINLOG_ID16271, BINLOG_ID16272, BINLOG_ID16273, BINLOG_ID16274, BINLOG_ID16275, BINLOG_ID16276, BINLOG_ID16277, BINLOG_ID16278, BINLOG_ID16279, BINLOG_ID16280, BINLOG_ID16281, BINLOG_ID16282, BINLOG_ID16283, BINLOG_ID16284, BINLOG_ID16285, BINLOG_ID16286, BINLOG_ID16287, BINLOG_ID16288, BINLOG_ID16289, BINLOG_ID16290, BINLOG_ID16291, BINLOG_ID16292, BINLOG_ID16293, BINLOG_ID16294, BINLOG_ID16295, BINLOG_ID16296, BINLOG_ID16297, BINLOG_ID16298, BINLOG_ID16299, BINLOG_ID16300, BINLOG_ID16301, BINLOG_ID16302, BINLOG_ID16303, BINLOG_ID16304, BINLOG_ID16305, BINLOG_ID16306, BINLOG_ID16307, BINLOG_ID16308, BINLOG_ID16309, BINLOG_ID16310, BINLOG_ID16311, BINLOG_ID16312, BINLOG_ID16313, BINLOG_ID16314, BINLOG_ID16315, BINLOG_ID16316, BINLOG_ID16317, BINLOG_ID16318, BINLOG_ID16319, BINLOG_ID16320, BINLOG_ID16321, BINLOG_ID16322, BINLOG_ID16323, BINLOG_ID16324, BINLOG_ID16325, BINLOG_ID16326, BINLOG_ID16327, BINLOG_ID16328, BINLOG_ID16329, BINLOG_ID16330, BINLOG_ID16331, BINLOG_ID16332, BINLOG_ID16333, BINLOG_ID16334, BINLOG_ID16335, BINLOG_ID16336, BINLOG_ID16337, BINLOG_ID16338, BINLOG_ID16339, BINLOG_ID16340, BINLOG_ID16341, BINLOG_ID16342, BINLOG_ID16343, BINLOG_ID16344, BINLOG_ID16345, BINLOG_ID16346, BINLOG_ID16347, BINLOG_ID16348, BINLOG_ID16349, BINLOG_ID16350, BINLOG_ID16351, BINLOG_ID16352, BINLOG_ID16353, BINLOG_ID16354, BINLOG_ID16355, BINLOG_ID16356, BINLOG_ID16357, BINLOG_ID16358, BINLOG_ID16359, BINLOG_ID16360, BINLOG_ID16361, BINLOG_ID16362, BINLOG_ID16363, BINLOG_ID16364, BINLOG_ID16365, BINLOG_ID16366, BINLOG_ID16367, BINLOG_ID16368, BINLOG_ID16369, BINLOG_ID16370, BINLOG_ID16371, BINLOG_ID16372, BINLOG_ID16373, BINLOG_ID16374, BINLOG_ID16375, BINLOG_ID16376, BINLOG_ID16377, BINLOG_ID16378, BINLOG_ID16379, BINLOG_ID16380, BINLOG_ID16381, BINLOG_ID16382, BINLOG_ID16383, BINLOG_ID16384, BINLOG_ID16385, BINLOG_ID16386, BINLOG_ID16387, BINLOG_ID16388, BINLOG_ID16389, BINLOG_ID16390, BINLOG_ID16391, BINLOG_ID16392, BINLOG_ID16393, BINLOG_ID16394, BINLOG_ID16395, BINLOG_ID16396, BINLOG_ID16397, BINLOG_ID16398, BINLOG_ID16399, BINLOG_ID16400, BINLOG_ID16401, BINLOG_ID16402, BINLOG_ID16403, BINLOG_ID16404, BINLOG_ID16405, BINLOG_ID16406, BINLOG_ID16407, BINLOG_ID16408, BINLOG_ID16409, BINLOG_ID16410, BINLOG_ID16411, BINLOG_ID16412, BINLOG_ID16413, BINLOG_ID16414, BINLOG_ID16415, BINLOG_ID16416, BINLOG_ID16417, BINLOG_ID16418, BINLOG_ID16419, BINLOG_ID16420, BINLOG_ID16421, BINLOG_ID16422, BINLOG_ID16423, BINLOG_ID16424, BINLOG_ID16425, BINLOG_ID16426, BINLOG_ID16427, BINLOG_ID16428, BINLOG_ID16429, BINLOG_ID16430, BINLOG_ID16431, BINLOG_ID16432, BINLOG_ID16433, BINLOG_ID16434, BINLOG_ID16435, BINLOG_ID16436, BINLOG_ID16437, BINLOG_ID16438, BINLOG_ID16439, BINLOG_ID16440, BINLOG_ID16441, BINLOG_ID16442, BINLOG_ID16443, BINLOG_ID16444, BINLOG_ID16445, BINLOG_ID16446, BINLOG_ID16447, BINLOG_ID16448, BINLOG_ID16449, BINLOG_ID16450, BINLOG_ID16451, BINLOG_ID16452, BINLOG_ID16453, BINLOG_ID16454, BINLOG_ID16455, BINLOG_ID16456, BINLOG_ID16457, BINLOG_ID16458, BINLOG_ID16459, BINLOG_ID16460, BINLOG_ID16461, BINLOG_ID16462, BINLOG_ID16463, BINLOG_ID16464, BINLOG_ID16465, BINLOG_ID16466, BINLOG_ID16467, BINLOG_ID16468, BINLOG_ID16469, BINLOG_ID16470, BINLOG_ID16471, BINLOG_ID16472, BINLOG_ID16473, BINLOG_ID16474, BINLOG_ID16475, BINLOG_ID16476, BINLOG_ID16477, BINLOG_ID16478, BINLOG_ID16479, BINLOG_ID16480, BINLOG_ID16481, BINLOG_ID16482, BINLOG_ID16483, BINLOG_ID16484, BINLOG_ID16485, BINLOG_ID16486, BINLOG_ID16487, BINLOG_ID16488, BINLOG_ID16489, BINLOG_ID16490, BINLOG_ID16491, BINLOG_ID16492, BINLOG_ID16493, BINLOG_ID16494, BINLOG_ID16495, BINLOG_ID16496, BINLOG_ID16497, BINLOG_ID16498, BINLOG_ID16499, BINLOG_ID16500, BINLOG_ID16501, BINLOG_ID16502, BINLOG_ID16503, BINLOG_ID16504, BINLOG_ID16505, BINLOG_ID16506, BINLOG_ID16507, BINLOG_ID16508, BINLOG_ID16509, BINLOG_ID16510, BINLOG_ID16511, BINLOG_ID16512, BINLOG_ID16513, BINLOG_ID16514, BINLOG_ID16515, BINLOG_ID16516, BINLOG_ID16517, BINLOG_ID16518, BINLOG_ID16519, BINLOG_ID16520, BINLOG_ID16521, BINLOG_ID16522, BINLOG_ID16523, BINLOG_ID16524, BINLOG_ID16525, BINLOG_ID16526, BINLOG_ID16527, BINLOG_ID16528, BINLOG_ID16529, BINLOG_ID16530, BINLOG_ID16531, BINLOG_ID16532, BINLOG_ID16533, BINLOG_ID16534, BINLOG_ID16535, BINLOG_ID16536, BINLOG_ID16537, BINLOG_ID16538, BINLOG_ID16539, BINLOG_ID16540, BINLOG_ID16541, BINLOG_ID16542, BINLOG_ID16543, BINLOG_ID16544, BINLOG_ID16545, BINLOG_ID16546, BINLOG_ID16547, BINLOG_ID16548, BINLOG_ID16549, BINLOG_ID16550, BINLOG_ID16551, BINLOG_ID16552, BINLOG_ID16553, BINLOG_ID16554, BINLOG_ID16555, BINLOG_ID16556, BINLOG_ID16557, BINLOG_ID16558, BINLOG_ID16559, BINLOG_ID16560, BINLOG_ID16561, BINLOG_ID16562, BINLOG_ID16563, BINLOG_ID16564, BINLOG_ID16565, BINLOG_ID16566, BINLOG_ID16567, BINLOG_ID16568, BINLOG_ID16569, BINLOG_ID16570, BINLOG_ID16571, BINLOG_ID16572, BINLOG_ID16573, BINLOG_ID16574, BINLOG_ID16575, BINLOG_ID16576, BINLOG_ID16577, BINLOG_ID16578, BINLOG_ID16579, BINLOG_ID16580, BINLOG_ID16581, BINLOG_ID16582, BINLOG_ID16583, BINLOG_ID16584, BINLOG_ID16585, BINLOG_ID16586, BINLOG_ID16587, BINLOG_ID16588, BINLOG_ID16589, BINLOG_ID16590, BINLOG_ID16591, BINLOG_ID16592, BINLOG_ID16593, BINLOG_ID16594, BINLOG_ID16595, BINLOG_ID16596, BINLOG_ID16597, BINLOG_ID16598, BINLOG_ID16599, BINLOG_ID16600, BINLOG_ID16601, BINLOG_ID16602, BINLOG_ID16603, BINLOG_ID16604, BINLOG_ID16605, BINLOG_ID16606, BINLOG_ID16607, BINLOG_ID16608, BINLOG_ID16609, BINLOG_ID16610, BINLOG_ID16611, BINLOG_ID16612, BINLOG_ID16613, BINLOG_ID16614, BINLOG_ID16615, BINLOG_ID16616, BINLOG_ID16617, BINLOG_ID16618, BINLOG_ID16619, BINLOG_ID16620, BINLOG_ID16621, BINLOG_ID16622, BINLOG_ID16623, BINLOG_ID16624, BINLOG_ID16625, BINLOG_ID16626, BINLOG_ID16627, BINLOG_ID16628, BINLOG_ID16629, BINLOG_ID16630, BINLOG_ID16631, BINLOG_ID16632, BINLOG_ID16633, BINLOG_ID16634, BINLOG_ID16635, BINLOG_ID16636, BINLOG_ID16637, BINLOG_ID16638, BINLOG_ID16639, BINLOG_ID16640, BINLOG_ID16641, BINLOG_ID16642, BINLOG_ID16643, BINLOG_ID16644, BINLOG_ID16645, BINLOG_ID16646, BINLOG_ID16647, BINLOG_ID16648, BINLOG_ID16649, BINLOG_ID16650, BINLOG_ID16651, BINLOG_ID16652, BINLOG_ID16653, BINLOG_ID16654, BINLOG_ID16655, BINLOG_ID16656, BINLOG_ID16657, BINLOG_ID16658, BINLOG_ID16659, BINLOG_ID16660, BINLOG_ID16661, BINLOG_ID16662, BINLOG_ID16663, BINLOG_ID16664, BINLOG_ID16665, BINLOG_ID16666, BINLOG_ID16667, BINLOG_ID16668, BINLOG_ID16669, BINLOG_ID16670, BINLOG_ID16671, BINLOG_ID16672, BINLOG_ID16673, BINLOG_ID16674, BINLOG_ID16675, BINLOG_ID16676, BINLOG_ID16677, BINLOG_ID16678, BINLOG_ID16679, BINLOG_ID16680, BINLOG_ID16681, BINLOG_ID16682, BINLOG_ID16683, BINLOG_ID16684, BINLOG_ID16685, BINLOG_ID16686, BINLOG_ID16687, BINLOG_ID16688, BINLOG_ID16689, BINLOG_ID16690, BINLOG_ID16691, BINLOG_ID16692, BINLOG_ID16693, BINLOG_ID16694, BINLOG_ID16695, BINLOG_ID16696, BINLOG_ID16697, BINLOG_ID16698, BINLOG_ID16699, BINLOG_ID16700, BINLOG_ID16701, BINLOG_ID16702, BINLOG_ID16703, BINLOG_ID16704, BINLOG_ID16705, BINLOG_ID16706, BINLOG_ID16707, BINLOG_ID16708, BINLOG_ID16709, BINLOG_ID16710, BINLOG_ID16711, BINLOG_ID16712, BINLOG_ID16713, BINLOG_ID16714, BINLOG_ID16715, BINLOG_ID16716, BINLOG_ID16717, BINLOG_ID16718, BINLOG_ID16719, BINLOG_ID16720, BINLOG_ID16721, BINLOG_ID16722, BINLOG_ID16723, BINLOG_ID16724, BINLOG_ID16725, BINLOG_ID16726, BINLOG_ID16727, BINLOG_ID16728, BINLOG_ID16729, BINLOG_ID16730, BINLOG_ID16731, BINLOG_ID16732, BINLOG_ID16733, BINLOG_ID16734, BINLOG_ID16735, BINLOG_ID16736, BINLOG_ID16737, BINLOG_ID16738, BINLOG_ID16739, BINLOG_ID16740, BINLOG_ID16741, BINLOG_ID16742, BINLOG_ID16743, BINLOG_ID16744, BINLOG_ID16745, BINLOG_ID16746, BINLOG_ID16747, BINLOG_ID16748, BINLOG_ID16749, BINLOG_ID16750, BINLOG_ID16751, BINLOG_ID16752, BINLOG_ID16753, BINLOG_ID16754, BINLOG_ID16755, BINLOG_ID16756, BINLOG_ID16757, BINLOG_ID16758, BINLOG_ID16759, BINLOG_ID16760, BINLOG_ID16761, BINLOG_ID16762, BINLOG_ID16763, BINLOG_ID16764, BINLOG_ID16765, BINLOG_ID16766, BINLOG_ID16767, BINLOG_ID16768, BINLOG_ID16769, BINLOG_ID16770, BINLOG_ID16771, BINLOG_ID16772, BINLOG_ID16773, BINLOG_ID16774, BINLOG_ID16775, BINLOG_ID16776, BINLOG_ID16777, BINLOG_ID16778, BINLOG_ID16779, BINLOG_ID16780, BINLOG_ID16781, BINLOG_ID16782, BINLOG_ID16783, BINLOG_ID16784, BINLOG_ID16785, BINLOG_ID16786, BINLOG_ID16787, BINLOG_ID16788, BINLOG_ID16789, BINLOG_ID16790, BINLOG_ID16791, BINLOG_ID16792, BINLOG_ID16793, BINLOG_ID16794, BINLOG_ID16795, BINLOG_ID16796, BINLOG_ID16797, BINLOG_ID16798, BINLOG_ID16799, BINLOG_ID16800, BINLOG_ID16801, BINLOG_ID16802, BINLOG_ID16803, BINLOG_ID16804, BINLOG_ID16805, BINLOG_ID16806, BINLOG_ID16807, BINLOG_ID16808, BINLOG_ID16809, BINLOG_ID16810, BINLOG_ID16811, BINLOG_ID16812, BINLOG_ID16813, BINLOG_ID16814, BINLOG_ID16815, BINLOG_ID16816, BINLOG_ID16817, BINLOG_ID16818, BINLOG_ID16819, BINLOG_ID16820, BINLOG_ID16821, BINLOG_ID16822, BINLOG_ID16823, BINLOG_ID16824, BINLOG_ID16825, BINLOG_ID16826, BINLOG_ID16827, BINLOG_ID16828, BINLOG_ID16829, BINLOG_ID16830, BINLOG_ID16831, BINLOG_ID16832, BINLOG_ID16833, BINLOG_ID16834, BINLOG_ID16835, BINLOG_ID16836, BINLOG_ID16837, BINLOG_ID16838, BINLOG_ID16839, BINLOG_ID16840, BINLOG_ID16841, BINLOG_ID16842, BINLOG_ID16843, BINLOG_ID16844, BINLOG_ID16845, BINLOG_ID16846, BINLOG_ID16847, BINLOG_ID16848, BINLOG_ID16849, BINLOG_ID16850, BINLOG_ID16851, BINLOG_ID16852, BINLOG_ID16853, BINLOG_ID16854, BINLOG_ID16855, BINLOG_ID16856, BINLOG_ID16857, BINLOG_ID16858, BINLOG_ID16859, BINLOG_ID16860, BINLOG_ID16861, BINLOG_ID16862, BINLOG_ID16863, BINLOG_ID16864, BINLOG_ID16865, BINLOG_ID16866, BINLOG_ID16867, BINLOG_ID16868, BINLOG_ID16869, BINLOG_ID16870, BINLOG_ID16871, BINLOG_ID16872, BINLOG_ID16873, BINLOG_ID16874, BINLOG_ID16875, BINLOG_ID16876, BINLOG_ID16877, BINLOG_ID16878, BINLOG_ID16879, BINLOG_ID16880, BINLOG_ID16881, BINLOG_ID16882, BINLOG_ID16883, BINLOG_ID16884, BINLOG_ID16885, BINLOG_ID16886, BINLOG_ID16887, BINLOG_ID16888, BINLOG_ID16889, BINLOG_ID16890, BINLOG_ID16891, BINLOG_ID16892, BINLOG_ID16893, BINLOG_ID16894, BINLOG_ID16895, BINLOG_ID16896, BINLOG_ID16897, BINLOG_ID16898, BINLOG_ID16899, BINLOG_ID16900, BINLOG_ID16901, BINLOG_ID16902, BINLOG_ID16903, BINLOG_ID16904, BINLOG_ID16905, BINLOG_ID16906, BINLOG_ID16907, BINLOG_ID16908, BINLOG_ID16909, BINLOG_ID16910, BINLOG_ID16911, BINLOG_ID16912, BINLOG_ID16913, BINLOG_ID16914, BINLOG_ID16915, BINLOG_ID16916, BINLOG_ID16917, BINLOG_ID16918, BINLOG_ID16919, BINLOG_ID16920, BINLOG_ID16921, BINLOG_ID16922, BINLOG_ID16923, BINLOG_ID16924, BINLOG_ID16925, BINLOG_ID16926, BINLOG_ID16927, BINLOG_ID16928, BINLOG_ID16929, BINLOG_ID16930, BINLOG_ID16931, BINLOG_ID16932, BINLOG_ID16933, BINLOG_ID16934, BINLOG_ID16935, BINLOG_ID16936, BINLOG_ID16937, BINLOG_ID16938, BINLOG_ID16939, BINLOG_ID16940, BINLOG_ID16941, BINLOG_ID16942, BINLOG_ID16943, BINLOG_ID16944, BINLOG_ID16945, BINLOG_ID16946, BINLOG_ID16947, BINLOG_ID16948, BINLOG_ID16949, BINLOG_ID16950, BINLOG_ID16951, BINLOG_ID16952, BINLOG_ID16953, BINLOG_ID16954, BINLOG_ID16955, BINLOG_ID16956, BINLOG_ID16957, BINLOG_ID16958, BINLOG_ID16959, BINLOG_ID16960, BINLOG_ID16961, BINLOG_ID16962, BINLOG_ID16963, BINLOG_ID16964, BINLOG_ID16965, BINLOG_ID16966, BINLOG_ID16967, BINLOG_ID16968, BINLOG_ID16969, BINLOG_ID16970, BINLOG_ID16971, BINLOG_ID16972, BINLOG_ID16973, BINLOG_ID16974, BINLOG_ID16975, BINLOG_ID16976, BINLOG_ID16977, BINLOG_ID16978, BINLOG_ID16979, BINLOG_ID16980, BINLOG_ID16981, BINLOG_ID16982, BINLOG_ID16983, BINLOG_ID16984, BINLOG_ID16985, BINLOG_ID16986, BINLOG_ID16987, BINLOG_ID16988, BINLOG_ID16989, BINLOG_ID16990, BINLOG_ID16991, BINLOG_ID16992, BINLOG_ID16993, BINLOG_ID16994, BINLOG_ID16995, BINLOG_ID16996, BINLOG_ID16997, BINLOG_ID16998, BINLOG_ID16999, BINLOG_ID17000, BINLOG_ID17001, BINLOG_ID17002, BINLOG_ID17003, BINLOG_ID17004, BINLOG_ID17005, BINLOG_ID17006, BINLOG_ID17007, BINLOG_ID17008, BINLOG_ID17009, BINLOG_ID17010, BINLOG_ID17011, BINLOG_ID17012, BINLOG_ID17013, BINLOG_ID17014, BINLOG_ID17015, BINLOG_ID17016, BINLOG_ID17017, BINLOG_ID17018, BINLOG_ID17019, BINLOG_ID17020, BINLOG_ID17021, BINLOG_ID17022, BINLOG_ID17023, BINLOG_ID17024, BINLOG_ID17025, BINLOG_ID17026, BINLOG_ID17027, BINLOG_ID17028, BINLOG_ID17029, BINLOG_ID17030, BINLOG_ID17031, BINLOG_ID17032, BINLOG_ID17033, BINLOG_ID17034, BINLOG_ID17035, BINLOG_ID17036, BINLOG_ID17037, BINLOG_ID17038, BINLOG_ID17039, BINLOG_ID17040, BINLOG_ID17041, BINLOG_ID17042, BINLOG_ID17043, BINLOG_ID17044, BINLOG_ID17045, BINLOG_ID17046, BINLOG_ID17047, BINLOG_ID17048, BINLOG_ID17049, BINLOG_ID17050, BINLOG_ID17051, BINLOG_ID17052, BINLOG_ID17053, BINLOG_ID17054, BINLOG_ID17055, BINLOG_ID17056, BINLOG_ID17057, BINLOG_ID17058, BINLOG_ID17059, BINLOG_ID17060, BINLOG_ID17061, BINLOG_ID17062, BINLOG_ID17063, BINLOG_ID17064, BINLOG_ID17065, BINLOG_ID17066, BINLOG_ID17067, BINLOG_ID17068, BINLOG_ID17069, BINLOG_ID17070, BINLOG_ID17071, BINLOG_ID17072, BINLOG_ID17073, BINLOG_ID17074, BINLOG_ID17075, BINLOG_ID17076, BINLOG_ID17077, BINLOG_ID17078, BINLOG_ID17079, BINLOG_ID17080, BINLOG_ID17081, BINLOG_ID17082, BINLOG_ID17083, BINLOG_ID17084, BINLOG_ID17085, BINLOG_ID17086, BINLOG_ID17087, BINLOG_ID17088, BINLOG_ID17089, BINLOG_ID17090, BINLOG_ID17091, BINLOG_ID17092, BINLOG_ID17093, BINLOG_ID17094, BINLOG_ID17095, BINLOG_ID17096, BINLOG_ID17097, BINLOG_ID17098, BINLOG_ID17099, BINLOG_ID17100, BINLOG_ID17101, BINLOG_ID17102, BINLOG_ID17103, BINLOG_ID17104, BINLOG_ID17105, BINLOG_ID17106, BINLOG_ID17107, BINLOG_ID17108, BINLOG_ID17109, BINLOG_ID17110, BINLOG_ID17111, BINLOG_ID17112, BINLOG_ID17113, BINLOG_ID17114, BINLOG_ID17115, BINLOG_ID17116, BINLOG_ID17117, BINLOG_ID17118, BINLOG_ID17119, BINLOG_ID17120, BINLOG_ID17121, BINLOG_ID17122, BINLOG_ID17123, BINLOG_ID17124, BINLOG_ID17125, BINLOG_ID17126, BINLOG_ID17127, BINLOG_ID17128, BINLOG_ID17129, BINLOG_ID17130, BINLOG_ID17131, BINLOG_ID17132, BINLOG_ID17133, BINLOG_ID17134, BINLOG_ID17135, BINLOG_ID17136, BINLOG_ID17137, BINLOG_ID17138, BINLOG_ID17139, BINLOG_ID17140, BINLOG_ID17141, BINLOG_ID17142, BINLOG_ID17143, BINLOG_ID17144, BINLOG_ID17145, BINLOG_ID17146, BINLOG_ID17147, BINLOG_ID17148, BINLOG_ID17149, BINLOG_ID17150, BINLOG_ID17151, BINLOG_ID17152, BINLOG_ID17153, BINLOG_ID17154, BINLOG_ID17155, BINLOG_ID17156, BINLOG_ID17157, BINLOG_ID17158, BINLOG_ID17159, BINLOG_ID17160, BINLOG_ID17161, BINLOG_ID17162, BINLOG_ID17163, BINLOG_ID17164, BINLOG_ID17165, BINLOG_ID17166, BINLOG_ID17167, BINLOG_ID17168, BINLOG_ID17169, BINLOG_ID17170, BINLOG_ID17171, BINLOG_ID17172, BINLOG_ID17173, BINLOG_ID17174, BINLOG_ID17175, BINLOG_ID17176, BINLOG_ID17177, BINLOG_ID17178, BINLOG_ID17179, BINLOG_ID17180, BINLOG_ID17181, BINLOG_ID17182, BINLOG_ID17183, BINLOG_ID17184, BINLOG_ID17185, BINLOG_ID17186, BINLOG_ID17187, BINLOG_ID17188, BINLOG_ID17189, BINLOG_ID17190, BINLOG_ID17191, BINLOG_ID17192, BINLOG_ID17193, BINLOG_ID17194, BINLOG_ID17195, BINLOG_ID17196, BINLOG_ID17197, BINLOG_ID17198, BINLOG_ID17199, BINLOG_ID17200, BINLOG_ID17201, BINLOG_ID17202, BINLOG_ID17203, BINLOG_ID17204, BINLOG_ID17205, BINLOG_ID17206, BINLOG_ID17207, BINLOG_ID17208, BINLOG_ID17209, BINLOG_ID17210, BINLOG_ID17211, BINLOG_ID17212, BINLOG_ID17213, BINLOG_ID17214, BINLOG_ID17215, BINLOG_ID17216, BINLOG_ID17217, BINLOG_ID17218, BINLOG_ID17219, BINLOG_ID17220, BINLOG_ID17221, BINLOG_ID17222, BINLOG_ID17223, BINLOG_ID17224, BINLOG_ID17225, BINLOG_ID17226, BINLOG_ID17227, BINLOG_ID17228, BINLOG_ID17229, BINLOG_ID17230, BINLOG_ID17231, BINLOG_ID17232, BINLOG_ID17233, BINLOG_ID17234, BINLOG_ID17235, BINLOG_ID17236, BINLOG_ID17237, BINLOG_ID17238, BINLOG_ID17239, BINLOG_ID17240, BINLOG_ID17241, BINLOG_ID17242, BINLOG_ID17243, BINLOG_ID17244, BINLOG_ID17245, BINLOG_ID17246, BINLOG_ID17247, BINLOG_ID17248, BINLOG_ID17249, BINLOG_ID17250, BINLOG_ID17251, BINLOG_ID17252, BINLOG_ID17253, BINLOG_ID17254, BINLOG_ID17255, BINLOG_ID17256, BINLOG_ID17257, BINLOG_ID17258, BINLOG_ID17259, BINLOG_ID17260, BINLOG_ID17261, BINLOG_ID17262, BINLOG_ID17263, BINLOG_ID17264, BINLOG_ID17265, BINLOG_ID17266, BINLOG_ID17267, BINLOG_ID17268, BINLOG_ID17269, BINLOG_ID17270, BINLOG_ID17271, BINLOG_ID17272, BINLOG_ID17273, BINLOG_ID17274, BINLOG_ID17275, BINLOG_ID17276, BINLOG_ID17277, BINLOG_ID17278, BINLOG_ID17279, BINLOG_ID17280, BINLOG_ID17281, BINLOG_ID17282, BINLOG_ID17283, BINLOG_ID17284, BINLOG_ID17285, BINLOG_ID17286, BINLOG_ID17287, BINLOG_ID17288, BINLOG_ID17289, BINLOG_ID17290, BINLOG_ID17291, BINLOG_ID17292, BINLOG_ID17293, BINLOG_ID17294, BINLOG_ID17295, BINLOG_ID17296, BINLOG_ID17297, BINLOG_ID17298, BINLOG_ID17299, BINLOG_ID17300, BINLOG_ID17301, BINLOG_ID17302, BINLOG_ID17303, BINLOG_ID17304, BINLOG_ID17305, BINLOG_ID17306, BINLOG_ID17307, BINLOG_ID17308, BINLOG_ID17309, BINLOG_ID17310, BINLOG_ID17311, BINLOG_ID17312, BINLOG_ID17313, BINLOG_ID17314, BINLOG_ID17315, BINLOG_ID17316, BINLOG_ID17317, BINLOG_ID17318, BINLOG_ID17319, BINLOG_ID17320, BINLOG_ID17321, BINLOG_ID17322, BINLOG_ID17323, BINLOG_ID17324, BINLOG_ID17325, BINLOG_ID17326, BINLOG_ID17327, BINLOG_ID17328, BINLOG_ID17329, BINLOG_ID17330, BINLOG_ID17331, BINLOG_ID17332, BINLOG_ID17333, BINLOG_ID17334, BINLOG_ID17335, BINLOG_ID17336, BINLOG_ID17337, BINLOG_ID17338, BINLOG_ID17339, BINLOG_ID17340, BINLOG_ID17341, BINLOG_ID17342, BINLOG_ID17343, BINLOG_ID17344, BINLOG_ID17345, BINLOG_ID17346, BINLOG_ID17347, BINLOG_ID17348, BINLOG_ID17349, BINLOG_ID17350, BINLOG_ID17351, BINLOG_ID17352, BINLOG_ID17353, BINLOG_ID17354, BINLOG_ID17355, BINLOG_ID17356, BINLOG_ID17357, BINLOG_ID17358, BINLOG_ID17359, BINLOG_ID17360, BINLOG_ID17361, BINLOG_ID17362, BINLOG_ID17363, BINLOG_ID17364, BINLOG_ID17365, BINLOG_ID17366, BINLOG_ID17367, BINLOG_ID17368, BINLOG_ID17369, BINLOG_ID17370, BINLOG_ID17371, BINLOG_ID17372, BINLOG_ID17373, BINLOG_ID17374, BINLOG_ID17375, BINLOG_ID17376 }; #ifdef HITLS_BSL_LOG int32_t ReturnErrorNumberProcess(int32_t err, uint32_t logId, const void *logStr); #define RETURN_ERROR_NUMBER_PROCESS(err, logId, logStr) ReturnErrorNumberProcess(err, logId, LOG_STR(logStr)) #else #define RETURN_ERROR_NUMBER_PROCESS(err, logId, logStr) (err) #endif /* HITLS_BSL_LOG */ #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples
tls/include/tls_binlog_id.h
C
unknown
41,126
/* * 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 TLS_CONFIG_H #define TLS_CONFIG_H #include <stdint.h> #include <stdbool.h> #include "hitls_build.h" #include "hitls_cert_type.h" #include "hitls_cert.h" #include "hitls_debug.h" #include "hitls_config.h" #include "hitls_session.h" #include "hitls_psk.h" #include "hitls_security.h" #include "hitls_sni.h" #include "hitls_alpn.h" #include "hitls_cookie.h" #include "sal_atomic.h" #ifdef HITLS_TLS_FEATURE_PROVIDER #include "crypt_eal_provider.h" #endif #ifdef __cplusplus extern "C" { #endif /** * @ingroup config * @brief Certificate management context */ typedef struct CertMgrCtxInner CERT_MgrCtx; typedef struct TlsSessionManager TLS_SessionMgr; /** * @ingroup config * @brief DTLS 1.0 */ #define HITLS_VERSION_DTLS10 0xfeffu #define HITLS_TICKET_KEY_NAME_SIZE 16u #define HITLS_TICKET_KEY_SIZE 32u #define HITLS_TICKET_IV_SIZE 16u /* the default number of tickets of TLS1.3 server is 2 */ #define HITLS_TLS13_TICKET_NUM_DEFAULT 2u #define HITLS_MAX_EMPTY_RECORDS 32 #ifdef HITLS_TLS_FEATURE_MAX_SEND_FRAGMENT #define HITLS_MAX_SEND_FRAGMENT_DEFAULT 16384 #endif /* max cert list is 100k */ #define HITLS_MAX_CERT_LIST_DEFAULT (1024 * 100) /** * @brief Group information */ typedef struct { char *name; // group name int32_t paraId; // parameter id CRYPT_PKEY_ParaId int32_t algId; // algorithm id CRYPT_PKEY_AlgId int32_t secBits; // security bits uint16_t groupId; // iana group id, HITLS_NamedGroup uint32_t pubkeyLen; // public key length(CH keyshare / SH keyshare) uint32_t sharedkeyLen; // shared key length uint32_t ciphertextLen; // ciphertext length(SH keyshare) uint32_t versionBits; // TLS_VERSION_MASK bool isKem; // true: KEM, false: KEX } TLS_GroupInfo; /** * @brief Signature scheme information */ typedef struct { char *name; uint16_t signatureScheme; // HITLS_SignHashAlgo, IANA specified int32_t keyType; // HITLS_CERT_KeyType int32_t paraId; // CRYPT_PKEY_ParaId int32_t signHashAlgId; // combined sign hash algorithm id int32_t signAlgId; // CRYPT_PKEY_AlgId int32_t hashAlgId; // CRYPT_MD_AlgId int32_t secBits; // security bits uint32_t certVersionBits; // TLS_VERSION_MASK uint32_t chainVersionBits; // TLS_VERSION_MASK } TLS_SigSchemeInfo; #ifdef HITLS_TLS_FEATURE_PROVIDER /** * @brief TLS capability data */ typedef struct { HITLS_Config *config; CRYPT_EAL_ProvMgrCtx *provMgrCtx; } TLS_CapabilityData; #define TLS_CAPABILITY_LIST_MALLOC_SIZE 10 #endif typedef struct CustomExtMethods HITLS_CustomExts; /** * @brief TLS Global Configuration */ typedef struct TlsConfig { BSL_SAL_RefCount references; /* reference count */ HITLS_Lib_Ctx *libCtx; /* library context */ const char *attrName; /* attrName */ #ifdef HITLS_TLS_FEATURE_PROVIDER TLS_GroupInfo *groupInfo; uint32_t groupInfolen; uint32_t groupInfoSize; TLS_SigSchemeInfo *sigSchemeInfo; uint32_t sigSchemeInfolen; uint32_t sigSchemeInfoSize; #endif uint32_t version; /* supported proto version */ uint32_t originVersionMask; /* the original supported proto version mask */ uint16_t minVersion; /* min supported proto version */ uint16_t maxVersion; /* max supported proto version */ uint32_t modeSupport; /* support mode */ uint16_t *tls13CipherSuites; /* tls13 cipher suite */ uint32_t tls13cipherSuitesSize; uint16_t *cipherSuites; /* cipher suite */ uint32_t cipherSuitesSize; uint8_t *pointFormats; /* ec point format */ uint32_t pointFormatsSize; /* According to RFC 8446 4.2.7, before TLS 1.3 is ec curves; TLS 1.3: supported groups for the key exchange */ uint16_t *groups; uint32_t groupsSize; uint16_t *signAlgorithms; /* signature algorithm */ uint32_t signAlgorithmsSize; uint8_t *alpnList; /* application layer protocols list */ uint32_t alpnListSize; /* bytes of alpn, excluding the tail 0 byte */ HITLS_SecurityCb securityCb; /* Security callback */ void *securityExData; /* Security ex data */ int32_t securityLevel; /* Security level */ uint8_t *serverName; /* server name */ uint32_t serverNameSize; /* server name size */ int32_t readAhead; /* need read more data into user buffer, nonzero indicates yes, otherwise no */ uint32_t emptyRecordsNum; /* the max number of empty records can be received */ /* TLS1.2 psk */ uint8_t *pskIdentityHint; /* psk identity hint */ uint32_t hintSize; HITLS_PskClientCb pskClientCb; /* psk client callback */ HITLS_PskServerCb pskServerCb; /* psk server callback */ /* TLS1.3 psk */ HITLS_PskFindSessionCb pskFindSessionCb; /* TLS1.3 PSK server callback */ HITLS_PskUseSessionCb pskUseSessionCb; /* TLS1.3 PSK client callback */ HITLS_DtlsTimerCb dtlsTimerCb; /* DTLS get the timeout callback */ uint32_t dtlsPostHsTimeoutVal; /* DTLS over UDP completed handshake timeout */ HITLS_CRYPT_Key *dhTmp; /* Temporary DH key set by the user */ HITLS_DhTmpCb dhTmpCb; /* Temporary ECDH key set by the user */ HITLS_InfoCb infoCb; /* information indicator callback */ HITLS_MsgCb msgCb; /* message callback function cb for observing all SSL/TLS protocol messages */ void *msgArg; /* set argument arg to the callback function */ HITLS_RecordPaddingCb recordPaddingCb; /* the callback to specify the padding for TLS 1.3 records */ void *recordPaddingArg; /* assign a value arg that is passed to the callback */ uint32_t keyExchMode; /* TLS1.3 psk exchange mode */ uint32_t maxCertList; /* the maximum size allowed for the peer's certificate chain */ HITLS_TrustedCAList *caList; /* the list of CAs sent to the peer */ CERT_MgrCtx *certMgrCtx; /* certificate management context */ uint32_t sessionIdCtxSize; /* the size of sessionId context */ uint8_t sessionIdCtx[HITLS_SESSION_ID_CTX_MAX_SIZE]; /* the sessionId context */ uint32_t ticketNums; /* TLS1.3 ticket number */ uint16_t maxSendFragment; /* max send fragment to restrict the amount of plaintext bytes in any record */ uint32_t recInbufferSize; /* Rec inbuffer inital size */ TLS_SessionMgr *sessMgr; /* session management */ void *userData; /* user data */ HITLS_ConfigUserDataFreeCb userDataFreeCb; bool needCheckKeyUsage; /* whether to check keyusage, default on */ bool needCheckPmsVersion; /* whether to verify the version in premastersecret */ bool isSupportRenegotiation; /* support renegotiation */ bool allowClientRenegotiate; /* allow a renegotiation initiated by the client */ bool allowLegacyRenegotiate; /* whether to abort handshake when server doesn't support SecRenegotiation */ bool isResumptionOnRenego; /* supports session resume during renegotiation */ bool isSupportDhAuto; /* the DH parameter to be automatically selected */ /* Certificate Verification Mode */ bool isSupportClientVerify; /* Enable dual-ended authentication. only for server */ bool isSupportNoClientCert; /* Authentication Passed When Client Sends Empty Certificate. only for server */ bool isSupportPostHandshakeAuth; /* TLS1.3 support post handshake auth. for server and client */ bool isSupportVerifyNone; /* The handshake will be continued regardless of the verification result. for server and client */ bool isSupportClientOnceVerify; /* only request a client certificate once during the connection. only for server */ bool isQuietShutdown; /* is support the quiet shutdown mode */ bool isEncryptThenMac; /* is EncryptThenMac on */ bool isFlightTransmitEnable; /* sending of handshake information in one flighttransmit */ bool isSupportExtendMasterSecret; /* is support extended master secret */ bool isSupportSessionTicket; /* is support session ticket */ bool isSupportServerPreference; /* server cipher suites can be preferentially selected */ /* DTLS */ #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) bool isSupportDtlsCookieExchange; /* is dtls support cookie exchange */ #endif /** * Configurations in the HITLS_Ctx are classified into private configuration and global configuration. * The following parameters directly reference the global configuration in tls. * Private configuration: ctx->config.tlsConfig * The global configuration: ctx->globalConfig * Modifying the globalConfig will affects all associated HITLS_Ctx */ HITLS_AlpnSelectCb alpnSelectCb; /* alpn callback */ void *alpnUserData; /* the user data for alpn callback */ void *sniArg; /* the args for servername callback */ HITLS_SniDealCb sniDealCb; /* server name callback function */ #ifdef HITLS_TLS_FEATURE_CLIENT_HELLO_CB HITLS_ClientHelloCb clientHelloCb; /* ClientHello callback */ void *clientHelloCbArg; /* the args for ClientHello callback */ #endif /* HITLS_TLS_FEATURE_CLIENT_HELLO_CB */ #ifdef HITLS_TLS_PROTO_DTLS12 HITLS_AppGenCookieCb appGenCookieCb; HITLS_AppVerifyCookieCb appVerifyCookieCb; #endif HITLS_NewSessionCb newSessionCb; /* negotiates to generate a session */ HITLS_KeyLogCb keyLogCb; /* the key log callback */ bool isKeepPeerCert; /* whether to save the peer certificate */ HITLS_CustomExts *customExts; bool isMiddleBoxCompat; /* whether to support middlebox compatibility */ } TLS_Config; #define LIBCTX_FROM_CONFIG(config) ((config == NULL) ? NULL : (config)->libCtx) #define ATTRIBUTE_FROM_CONFIG(config) ((config == NULL) ? NULL : (config)->attrName) #ifdef __cplusplus } #endif #endif // TLS_CONFIG_H
2302_82127028/openHiTLS-examples
tls/include/tls_config.h
C
unknown
11,164
/* * 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 REC_H #define REC_H #include <stdbool.h> #include <stdint.h> #include "hitls_build.h" #include "hitls_crypt_type.h" #include "tls.h" #ifdef __cplusplus extern "C" { #endif #define DTLS_MIN_MTU 256 /* Minimum MTU setting size */ #define REC_MAX_PLAIN_LENGTH 16384 /* Maximum plain length */ /* TLS13 Maximum MAC address padding */ #define REC_MAX_TLS13_ENCRYPTED_OVERHEAD 256u /* TLS13 Maximum ciphertext length */ #define REC_MAX_TLS13_ENCRYPTED_LEN (REC_MAX_PLAIN_LENGTH + REC_MAX_TLS13_ENCRYPTED_OVERHEAD) #define REC_MASTER_SECRET_LEN 48 #define REC_RANDOM_LEN 32 #define RECORD_HEADER 0x100 #define RECORD_INNER_CONTENT_TYPE 0x101 /** * record type */ typedef enum { REC_TYPE_CHANGE_CIPHER_SPEC = 20, REC_TYPE_ALERT = 21, REC_TYPE_HANDSHAKE = 22, REC_TYPE_APP = 23, REC_TYPE_UNKNOWN = 255 } REC_Type; /** * SecurityParameters, used to generate keys and initialize the connect state */ typedef struct { bool isClient; /* Connection Endpoint */ bool isClientTrafficSecret; /* TrafficSecret type */ HITLS_HashAlgo prfAlg; /* prf_algorithm */ HITLS_MacAlgo macAlg; /* mac algorithm */ HITLS_CipherAlgo cipherAlg; /* symmetric encryption algorithm */ HITLS_CipherType cipherType; /* encryption algorithm type */ /* key length */ uint8_t fixedIvLength; /* iv length. In TLS1.2 AEAD algorithm is the implicit IV length */ uint8_t encKeyLen; /* Length of the symmetric key */ uint8_t macKeyLen; /* MAC key length: If the AEAD algorithm is used, the MAC key length is 0 */ uint8_t blockLength; /* If the block length is not zero, the alignment should be handled. */ uint8_t recordIvLength; /* The explicit IV needs to be sent to the peer */ uint8_t macLen; /* MAC length. For AEAD, it is the mark length */ uint8_t masterSecret[MAX_DIGEST_SIZE]; /* tls1.2 master key. TLS1.3 carries the TrafficSecret */ uint8_t clientRandom[REC_RANDOM_LEN]; /* Client random number */ uint8_t serverRandom[REC_RANDOM_LEN]; /* service random number */ } REC_SecParameters; /** * @ingroup record * @brief Record initialization * * @param ctx [IN] TLS object * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * */ int32_t REC_Init(TLS_Ctx *ctx); /** * @ingroup record * @brief record deinitialize * * @param ctx [IN] TLS object */ void REC_DeInit(TLS_Ctx *ctx); /** * @ingroup record * @brief Check whether data exists in the read buffer of the reocrd * * @param ctx [IN] TLS object * @return whether data exists in the read buffer */ bool REC_ReadHasPending(const TLS_Ctx *ctx); /** * @ingroup record * @brief Reads a message in the unit of a record. Data is read from the uio of the CTX to the data pointer * * @attention recordType indicates the expected record type (app or handshake) * readLen indicates the length of read data. The maximum length is REC_MAX_PLAIN_LENGTH (16384) * @param ctx [IN] TLS object * @param recordType [IN] Expected record type(app or handshake) * @param data [OUT] Read buffer * @param readLen [OUT] Length of the read data * @param num [IN] The size of read buffer, which must be greater than or equal to the maximum size of the record * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION,Invalid null pointer * @retval HITLS_REC_ERR_BUFFER_NOT_ENOUGH The buffer space is insufficient * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY indicates that the buffer is empty and needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG An unexpected message is received and needs to be processed * @retval HITLS_REC_ERR_SN_WRAPPING Sequence number wrap */ int32_t REC_Read(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num); /** * @ingroup record * @brief Write a record in the unit of record * * @attention If the value of num exceeds the maximum length of the record, return error * * @param ctx [IN] TLS object * @param recordType [IN] record type * @param data [IN] Write data * @param num [IN] Attempt to write num bytes of plaintext data * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * @retval HITLS_REC_ERR_BUFFER_NOT_ENOUGH The buffer space is insufficient * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_REC_PMTU_TOO_SMALL The PMTU is too small * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_IO_BUSY I/O busy * @retval HITLS_REC_ERR_TOO_BIG_LENGTH The length of the plaintext data written by the upper layer exceeds the * maximum length of the plaintext data that can be written by a single record * @retval HITLS_REC_ERR_NOT_SUPPORT_CIPHER The key algorithm is not supported * @retval HITLS_REC_ERR_SN_WRAPPING Sequence number wrap */ int32_t REC_Write(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num); /** * @ingroup record * @brief Activate the expired write state. This API is invoked in the retransmission scenario * * @attention Reservation Interface * @param ctx [IN] TLS object * */ void REC_ActiveOutdatedWriteState(TLS_Ctx *ctx); /** * @ingroup record * @brief Disable the expired write status. This API is invoked in the retransmission scenario * * @attention Reservation Interface * @param ctx [IN] TLS object * */ void REC_DeActiveOutdatedWriteState(TLS_Ctx *ctx); /** * @ingroup record * @brief Initialize the pending state * * @param ctx [IN] TLS object * @param param [IN] Security parameter * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * */ int32_t REC_InitPendingState(const TLS_Ctx *ctx, const REC_SecParameters *param); /** * @ingroup record * @brief Activate the pending state, switch the pending state to the current state * * @attention ctx cannot be empty * @param ctx [IN] TLS object * @param isOut [IN] Indicates whether is the output type * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * */ int32_t REC_ActivePendingState(TLS_Ctx *ctx, bool isOut); /** * @brief Calculate the mtu * * @param ctx [IN] TLS_Ctx context * * @retval HITLS_SUCCESS * @retval ITLS_UIO_FAIL The uio ctrl failed */ int32_t REC_QueryMtu(TLS_Ctx *ctx); /** * @brief Obtain the maximum writable plaintext length of a single record * * @param ctx [IN] TLS_Ctx context * @param len [OUT] Maximum length of the plaintext * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * @retval HITLS_REC_PMTU_TOO_SMALL The PMTU is too small */ int32_t REC_GetMaxWriteSize(const TLS_Ctx *ctx, uint32_t *len); /** * @brief Obtain the maximum writable plaintext according to mtu * * @param ctx [IN] TLS_Ctx context * @param len [OUT] Maximum length of the plaintext * * @retval HITLS_SUCCESS * @retval HITLS_UIO_IO_TYPE_ERROR Not UDP uio * @retval HITLS_REC_PMTU_TOO_SMALL The PMTU is too small */ int32_t REC_GetMaxDataMtu(const TLS_Ctx *ctx, uint32_t *len); /** * @ingroup record * @brief TLS13 Initialize the pending state * * @param ctx [IN] TLS object * @param param [IN] Security parameter * @param isOut [IN] Indicates whether is the output type * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * */ int32_t REC_TLS13InitPendingState(const TLS_Ctx *ctx, const REC_SecParameters *param, bool isOut); /** * @ingroup record * @brief Retransmit a record * * @param recCtx [IN] Record context * @param recordType [IN] record type * @param data [IN] data * @param dataLen [IN] data length */ int32_t REC_RetransmitListAppend(REC_Ctx *recCtx, REC_Type recordType, const uint8_t *data, uint32_t dataLen); /** * @ingroup record * @brief Clean the retransmit list * * @param recCtx [IN] Record context */ void REC_RetransmitListClean(REC_Ctx *recCtx); /** * @ingroup record * @brief Flush the retransmit list * * @param ctx [IN] TLS object * @retval HITLS_SUCCESS */ int32_t REC_RetransmitListFlush(TLS_Ctx *ctx); REC_Type REC_GetUnexpectedMsgType(TLS_Ctx *ctx); bool REC_HaveReadSuiteInfo(const TLS_Ctx *ctx); /** * @ingroup app * @brief Obtain the length of the remaining readable app messages in the current record. * * @param ctx [IN] TLS object * @return Length of the remaining readable app message */ uint32_t APP_GetReadPendingBytes(const TLS_Ctx *ctx); int32_t REC_RecOutBufReSet(TLS_Ctx *ctx); /** * @ingroup record * @brief Flush the buffer uio * * @param ctx [IN] TLS object * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_IO_BUSY uio busy * @retval HITLS_REC_ERR_IO_EXCEPTION uio error */ int32_t REC_FlightTransmit(TLS_Ctx *ctx); /** * @brief Obtain the out buffer remaining size * * @param ctx [IN] TLS_Ctx context * * @retval the out buffer remaining size */ uint32_t REC_GetOutBufPendingSize(const TLS_Ctx *ctx); /** * @brief Flush the record out buffer * * @param ctx [IN] TLS_Ctx context * * @retval HITLS_SUCCESS Out buffer is empty or flush success * @retval HITLS_REC_NORMAL_IO_BUSY Out buffer is not empty, but the IO operation is busy */ int32_t REC_OutBufFlush(TLS_Ctx *ctx); #ifdef __cplusplus } #endif #endif /* REC_H */
2302_82127028/openHiTLS-examples
tls/record/include/rec.h
C
unknown
10,296
/* * 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_error.h" #include "tls.h" int32_t CovertRecordAlertToReturnValue(ALERT_Description description) { switch (description) { case ALERT_PROTOCOL_VERSION: return HITLS_REC_INVALID_PROTOCOL_VERSION; case ALERT_BAD_RECORD_MAC: return HITLS_REC_BAD_RECORD_MAC; case ALERT_DECODE_ERROR: return HITLS_REC_DECODE_ERROR; case ALERT_RECORD_OVERFLOW: return HITLS_REC_RECORD_OVERFLOW; case ALERT_UNEXPECTED_MESSAGE: return HITLS_REC_ERR_RECV_UNEXPECTED_MSG; default: return HITLS_REC_INVLAID_RECORD; } } int32_t RecordSendAlertMsg(TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description) { /* RFC6347 4.1.2.7. Handling Invalid Records: We choose to discard invalid dtls record message and do not generate alerts. */ if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } else { ctx->method.sendAlert(ctx, level, description); return CovertRecordAlertToReturnValue(description); } }
2302_82127028/openHiTLS-examples
tls/record/src/rec_alert.c
C
unknown
1,667
/* * 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 REC_ALERT_H #define REC_ALERT_H #include <stdint.h> #include "tls.h" #ifdef __cplusplus extern "C" { #endif /** * @brief record Send an alert and determine whether to discard invalid records * based on RFC6347 4.1.2.7. Handling Invalid Records * * @param ctx [IN] tls Context * @param level [IN] Alert level * @param description [IN] alert Description * * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY Discarding message * @retval Other invalid message error codes, such as HITLS_REC_INVLAID_RECORD and HITLS_REC_INVALID_PROTOCOL_VERSION */ int32_t RecordSendAlertMsg(TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples
tls/record/src/rec_alert.h
C
unknown
1,239
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) #include "rec_anti_replay.h" #define REC_SLID_WINDOW_SIZE 64 void RecAntiReplayReset(RecSlidWindow *w) { w->top = 0; w->window = 0; return; } bool RecAntiReplayCheck(const RecSlidWindow *w, uint64_t seq) { if (seq > w->top) { return false; } uint64_t bit = w->top - seq; if (bit >= REC_SLID_WINDOW_SIZE) { /* The sequence number must be smaller than or equal to the minimum value of the sliding window */ return true; } /* return true: The sequence number is equal to a certain value in the sliding window */ return (w->window & ((uint64_t)1 << bit)) != 0; } void RecAntiReplayUpdate(RecSlidWindow *w, uint64_t seq) { /* If the sequence number is too small, the flag bit is not updated */ if ((seq + REC_SLID_WINDOW_SIZE) <= w->top) { return; } /* If the sequence number is less than or equal to top, update the flag */ if (seq <= w->top) { uint64_t bit = w->top - seq; w->window |= (uint64_t)1 << bit; return; } /* If the sequence number is greater than top, update the maximum sliding window size */ uint64_t bit = seq - w->top; w->top = seq; if (bit >= REC_SLID_WINDOW_SIZE) { /* If the number exceeds the current number too much, all previous flags are cleared and the maximum value is * updated */ w->window = 1; } else { w->window <<= bit; w->window |= 1; } return; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */
2302_82127028/openHiTLS-examples
tls/record/src/rec_anti_replay.c
C
unknown
2,161
/* * 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 REC_ANTI_REPLAY_H #define REC_ANTI_REPLAY_H #include <stdint.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif /** * Anti-replay check function: * Use uint64_t variable to store flag bit,When receive a message, set the flag of corresponding sequence number to 1 * The least significant bit of the variable stores the maximum sequence number of the sliding window top, * when the top updates, shift the sliding window to the left * If a duplicate message or a message whose sequence number is smaller than the minimum sliding window value * is received, discard it * * window: 64 bits Range: [top-63, top) * 1. Initial state: * top - 63 top * | - - - - - - | * 2. hen the top + 2 message is received: * top - 61 top + 2 * | - - - - - - | */ typedef struct { uint64_t top; /* Stores the current maximum sequence number */ uint64_t window; /* Sliding window for storing flag bits */ } RecSlidWindow; /** * @brief Reset of the anti-replay module * The invoker must ensure that the input parameter is not empty * * @param w [IN] Sliding window */ void RecAntiReplayReset(RecSlidWindow *w); /** * @brief Anti-Replay Check * The invoker must ensure that the input parameter is not empty * * @param w [IN] Sliding window * @param seq [IN] Sequence number to be checked * * @retval true The sequence number is duplicate * @retval false The sequence number is not duplicate */ bool RecAntiReplayCheck(const RecSlidWindow *w, uint64_t seq); /** * @brief Update the window * This function can be invoked only after the anti-replay check is passed * Ensure that the input parameter is not empty by the invoker * * @param w [IN] Sliding window. The input parameter correctness is ensured externally * @param seq [IN] Sequence number of the window to be updated */ void RecAntiReplayUpdate(RecSlidWindow *w, uint64_t seq); #ifdef __cplusplus } #endif #endif /* REC_ANTI_REPLAY_H */
2302_82127028/openHiTLS-examples
tls/record/src/rec_anti_replay.h
C
unknown
2,612
/* * 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 "securec.h" #include "bsl_sal.h" #include "bsl_list.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "hitls_error.h" #include "tls.h" #include "record.h" #include "rec_buf.h" RecBuf *RecBufNew(uint32_t bufSize) { RecBuf *buf = (RecBuf *)BSL_SAL_Calloc(1, sizeof(RecBuf)); if (buf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17210, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return NULL; } buf->buf = (uint8_t *)BSL_SAL_Calloc(1, bufSize); if (buf->buf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17211, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); BSL_SAL_FREE(buf); return NULL; } buf->isHoldBuffer = true; buf->bufSize = bufSize; return buf; } int32_t RecBufResize(RecBuf *recBuf, uint32_t size) { if (recBuf == NULL || recBuf->bufSize == size || recBuf->end - recBuf->start > size) { return HITLS_SUCCESS; } uint8_t *newBuf = BSL_SAL_Calloc(size, sizeof(uint8_t)); if (newBuf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17212, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(newBuf, size, &recBuf->buf[recBuf->start], recBuf->end - recBuf->start); recBuf->end = recBuf->end - recBuf->start; recBuf->start = 0; BSL_SAL_FREE(recBuf->buf); recBuf->buf = newBuf; recBuf->bufSize = size; return HITLS_SUCCESS; } void RecBufFree(RecBuf *buf) { if (buf != NULL) { if (buf->isHoldBuffer) { BSL_SAL_FREE(buf->buf); } BSL_SAL_FREE(buf); } return; } void RecBufClean(RecBuf *buf) { buf->start = 0; buf->end = 0; return; } RecBufList *RecBufListNew(void) { return BSL_LIST_New(sizeof(RecBuf)); } void RecBufListFree(RecBufList *bufList) { BSL_LIST_FREE(bufList, (void(*)(void*))RecBufFree); } int32_t RecBufListDereference(RecBufList *bufList) { RecBuf *recBuf = (RecBuf *)BSL_LIST_GET_FIRST(bufList); while (recBuf != NULL) { if (!recBuf->isHoldBuffer) { uint8_t *buf = (uint8_t *)BSL_SAL_Dump(recBuf->buf, recBuf->bufSize); if (buf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17215, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } recBuf->buf = buf; recBuf->isHoldBuffer = true; } recBuf = (RecBuf *)BSL_LIST_GET_NEXT(bufList); } return HITLS_SUCCESS; } bool RecBufListEmpty(RecBufList *bufList) { return BSL_LIST_GET_FIRST(bufList) == NULL; } int32_t RecBufListGetBuffer(RecBufList *bufList, uint8_t *buf, uint32_t bufLen, uint32_t *getLen, bool isPeek) { RecBuf *recBuf = (RecBuf *)BSL_LIST_GET_FIRST(bufList); if (recBuf == NULL || recBuf->buf == NULL) { *getLen = 0; return HITLS_SUCCESS; } uint32_t remain = recBuf->end - recBuf->start; uint32_t copyLen = (remain > bufLen) ? bufLen : remain; if (copyLen == 0) { if (recBuf->start == recBuf->end) { BSL_LIST_DeleteCurrent(bufList, (void(*)(void*))RecBufFree); } *getLen = 0; return HITLS_SUCCESS; } uint8_t *startBuf = &recBuf->buf[recBuf->start]; int32_t ret = memcpy_s(buf, bufLen, startBuf, copyLen); if (ret != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16242, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecBufListGetBuffer memcpy_s failed; buf may be nullptr", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } if (!isPeek) { recBuf->start += copyLen; } *getLen = copyLen; if (recBuf->start == recBuf->end) { BSL_LIST_DeleteCurrent(bufList, (void(*)(void*))RecBufFree); } return HITLS_SUCCESS; } int32_t RecBufListAddBuffer(RecBufList *bufList, RecBuf *buf) { RecBuf *newBuf = BSL_SAL_Calloc(1U, sizeof(RecBuf)); if (newBuf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17216, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(newBuf, sizeof(RecBuf), buf, sizeof(RecBuf)); if (BSL_LIST_AddElement(bufList, newBuf, BSL_LIST_POS_END) != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17217, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "AddElement fail", 0, 0, 0, 0); BSL_SAL_FREE(newBuf); return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; }
2302_82127028/openHiTLS-examples
tls/record/src/rec_buf.c
C
unknown
5,374
/* * 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 REC_BUF_H #define REC_BUF_H #include <stdint.h> #include "bsl_list.h" #ifdef __cplusplus extern "C" { #endif typedef struct { uint8_t *buf; uint32_t bufSize; uint32_t start; uint32_t end; uint32_t singleRecStart; uint32_t singleRecEnd; bool isHoldBuffer; } RecBuf; typedef struct BslList RecBufList; /** * @brief Allocate buffer * * @param bufSize [IN] buffer size * * @return RecBuf Buffer handle */ RecBuf *RecBufNew(uint32_t bufSize); /** * @brief Release the buffer * * @param buf [IN] Buffer handle. The buffer is released by the invoker */ void RecBufFree(RecBuf *buf); /** * @brief Release the data in buffer * * @param buf [IN] Buffer handle */ void RecBufClean(RecBuf *buf); RecBufList *RecBufListNew(void); void RecBufListFree(RecBufList *bufList); int32_t RecBufListDereference(RecBufList *bufList); bool RecBufListEmpty(RecBufList *bufList); int32_t RecBufListGetBuffer(RecBufList *bufList, uint8_t *buf, uint32_t bufLen, uint32_t *getLen, bool isPeek); int32_t RecBufListAddBuffer(RecBufList *bufList, RecBuf *buf); int32_t RecBufResize(RecBuf *recBuf, uint32_t size); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples
tls/record/src/rec_buf.h
C
unknown
1,740
/* * 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 <string.h> #include "securec.h" #include "hitls_build.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "crypt.h" #include "rec_alert.h" #include "rec_crypto.h" #include "rec_conn.h" #define KEY_EXPANSION_LABEL "key expansion" #ifdef HITLS_TLS_SUITE_CIPHER_CBC #define CBC_MAC_HEADER_LEN 13U #endif RecConnState *RecConnStateNew(void) { RecConnState *state = (RecConnState *)BSL_SAL_Calloc(1, sizeof(RecConnState)); if (state == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15382, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record conn:malloc fail.", 0, 0, 0, 0); return NULL; } return state; } void RecConnStateFree(RecConnState *state) { if (state == NULL) { return; } if (state->suiteInfo != NULL) { #ifdef HITLS_TLS_CALLBACK_CRYPT_HMAC_PRIMITIVES SAL_CRYPT_HmacFree(state->suiteInfo->macCtx); state->suiteInfo->macCtx = NULL; #endif SAL_CRYPT_CipherFree(state->suiteInfo->ctx); state->suiteInfo->ctx = NULL; } /* Clear sensitive information */ BSL_SAL_CleanseData(state->suiteInfo, sizeof(RecConnSuitInfo)); BSL_SAL_FREE(state->suiteInfo); BSL_SAL_FREE(state); return; } uint64_t RecConnGetSeqNum(const RecConnState *state) { return state->seq; } void RecConnSetSeqNum(RecConnState *state, uint64_t seq) { state->seq = seq; } #ifdef HITLS_TLS_PROTO_DTLS12 uint16_t RecConnGetEpoch(const RecConnState *state) { return state->epoch; } void RecConnSetEpoch(RecConnState *state, uint16_t epoch) { state->epoch = epoch; } #endif int32_t RecConnStateSetCipherInfo(RecConnState *state, RecConnSuitInfo *suitInfo) { if (state->suiteInfo != NULL) { SAL_CRYPT_CipherFree(state->suiteInfo->ctx); state->suiteInfo->ctx = NULL; #ifdef HITLS_TLS_CALLBACK_CRYPT_HMAC_PRIMITIVES SAL_CRYPT_HmacFree(state->suiteInfo->macCtx); state->suiteInfo->macCtx = NULL; #endif } /* Clear sensitive information */ BSL_SAL_CleanseData(state->suiteInfo, sizeof(RecConnSuitInfo)); // Ensure that no memory leak occurs BSL_SAL_FREE(state->suiteInfo); state->suiteInfo = (RecConnSuitInfo *)BSL_SAL_Malloc(sizeof(RecConnSuitInfo)); if (state->suiteInfo == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN( BINLOG_ID15383, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record conn: malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(state->suiteInfo, sizeof(RecConnSuitInfo), suitInfo, sizeof(RecConnSuitInfo)); return HITLS_SUCCESS; } #ifdef HITLS_TLS_SUITE_CIPHER_CBC uint32_t RecGetHashAlgoFromMACAlgo(HITLS_MacAlgo macAlgo) { switch (macAlgo) { case HITLS_MAC_1: return HITLS_HASH_SHA1; case HITLS_MAC_256: return HITLS_HASH_SHA_256; case HITLS_MAC_224: return HITLS_HASH_SHA_224; case HITLS_MAC_384: return HITLS_HASH_SHA_384; case HITLS_MAC_512: return HITLS_HASH_SHA_512; #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_MAC_SM3: return HITLS_HASH_SM3; #endif default: BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15388, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CBC encrypt error: unsupport MAC algorithm = %u.", macAlgo, 0, 0, 0); break; } return HITLS_HASH_BUTT; } int32_t RecConnGenerateMac(HITLS_Lib_Ctx *libCtx, const char *attrName, RecConnSuitInfo *suiteInfo, const REC_TextInput *plainMsg, uint8_t *mac, uint32_t *macLen) { int32_t ret = HITLS_SUCCESS; uint8_t header[CBC_MAC_HEADER_LEN] = {0}; uint32_t offset = 0; if (memcpy_s(header, CBC_MAC_HEADER_LEN, plainMsg->seq, REC_CONN_SEQ_SIZE) != EOK) { // sequence or epoch + seq return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMCPY_FAIL, BINLOG_ID17228, "memcpy fail"); } offset += REC_CONN_SEQ_SIZE; header[offset] = plainMsg->type; // The eighth byte is the record type offset++; BSL_Uint16ToByte(plainMsg->version, &header[offset]); // The 9th and 10th bytes are version numbers offset += sizeof(uint16_t); BSL_Uint16ToByte((uint16_t)plainMsg->textLen, &header[offset]); // The 11th and 12th bytes are the data length HITLS_HashAlgo hashAlgo = RecGetHashAlgoFromMACAlgo(suiteInfo->macAlg); if (hashAlgo == HITLS_HASH_BUTT) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_REC_ERR_GENERATE_MAC, BINLOG_ID17229, "RecGetHashAlgoFromMACAlgo fail"); } if (suiteInfo->macCtx == NULL) { suiteInfo->macCtx = SAL_CRYPT_HmacInit(libCtx, attrName, hashAlgo, suiteInfo->macKey, suiteInfo->macKeyLen); ret = suiteInfo->macCtx == NULL ? HITLS_REC_ERR_GENERATE_MAC : HITLS_SUCCESS; } else { ret = SAL_CRYPT_HmacReInit(suiteInfo->macCtx); } if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_GENERATE_MAC); return RETURN_ERROR_NUMBER_PROCESS(HITLS_REC_ERR_GENERATE_MAC, BINLOG_ID15389, "SAL_CRYPT_HmacInit fail"); } ret = SAL_CRYPT_HmacUpdate(suiteInfo->macCtx, header, CBC_MAC_HEADER_LEN); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17230, "HmacUpdate fail"); } ret = SAL_CRYPT_HmacUpdate(suiteInfo->macCtx, plainMsg->text, plainMsg->textLen); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17231, "HmacUpdate fail"); } ret = SAL_CRYPT_HmacFinal(suiteInfo->macCtx, mac, macLen); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17232, "HmacFinal fail"); } return HITLS_SUCCESS; } void RecConnInitGenerateMacInput(const REC_TextInput *in, const uint8_t *text, uint32_t textLen, REC_TextInput *out) { out->version = in->version; out->negotiatedVersion = in->negotiatedVersion; #ifdef HITLS_TLS_FEATURE_ETM out->isEncryptThenMac = in->isEncryptThenMac; #endif out->type = in->type; out->text = text; out->textLen = textLen; for (uint32_t i = 0u; i < REC_CONN_SEQ_SIZE; i++) { out->seq[i] = in->seq[i]; } } int32_t RecConnCheckMac(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, const REC_TextInput *cryptMsg, const uint8_t *text, uint32_t textLen) { REC_TextInput input = {0}; uint8_t mac[MAX_DIGEST_SIZE] = {0}; uint32_t macLen = MAX_DIGEST_SIZE; RecConnInitGenerateMacInput(cryptMsg, text, textLen - suiteInfo->macLen, &input); int32_t ret = RecConnGenerateMac(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), suiteInfo, &input, mac, &macLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17233, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnGenerateMac fail.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); } if (macLen != suiteInfo->macLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15929, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error: macLen = %u, required len = %u.", macLen, suiteInfo->macLen, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } if (memcmp(&text[textLen - suiteInfo->macLen], mac, macLen) != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15942, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error: MAC check failed.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_CIPHER_CBC */ int32_t RecConnEncrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { return RecGetCryptoFuncs(state->suiteInfo)->encryt(ctx, state, plainMsg, cipherText, cipherTextLen); } int32_t RecConnDecrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { const RecCryptoFunc *funcs = RecGetCryptoFuncs(state->suiteInfo); uint32_t ciphertextLen = funcs->calCiphertextLen(ctx, state->suiteInfo, 0, true); // The length of the record body to be decrypted must be greater than or equal to ciphertextLen if (cryptMsg->textLen < ciphertextLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15403, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnDecrypt Failed: record body length to be decrypted is %u, lower bound of ciphertext len is %u", cryptMsg->textLen, ciphertextLen, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } return funcs->decrypt(ctx, state, cryptMsg, data, dataLen); } static void PackSuitInfo(RecConnSuitInfo *suitInfo, const REC_SecParameters *param) { suitInfo->macAlg = param->macAlg; suitInfo->cipherAlg = param->cipherAlg; suitInfo->cipherType = param->cipherType; suitInfo->fixedIvLength = param->fixedIvLength; suitInfo->encKeyLen = param->encKeyLen; suitInfo->macKeyLen = param->macKeyLen; suitInfo->blockLength = param->blockLength; suitInfo->recordIvLength = param->recordIvLength; suitInfo->macLen = param->macLen; return; } static void RecConnCalcWriteKey(const REC_SecParameters *param, uint8_t *keyBuf, uint32_t keyBufLen, RecConnSuitInfo *client, RecConnSuitInfo *server) { if (keyBufLen == 0) { return; } uint32_t offset = 0; uint32_t totalOffset = 2 * param->macKeyLen + 2 * param->encKeyLen + 2 * param->fixedIvLength; if (keyBufLen < totalOffset) { return; } if (param->macKeyLen > 0u) { if (memcpy_s(client->macKey, sizeof(client->macKey), keyBuf, param->macKeyLen) != EOK) { return; } offset += param->macKeyLen; if (memcpy_s(server->macKey, sizeof(server->macKey), keyBuf + offset, param->macKeyLen) != EOK) { return; } offset += param->macKeyLen; } if (param->encKeyLen > 0u) { if (memcpy_s(client->key, sizeof(client->key), keyBuf + offset, param->encKeyLen) != EOK) { return; } offset += param->encKeyLen; if (memcpy_s(server->key, sizeof(server->key), keyBuf + offset, param->encKeyLen) != EOK) { return; } offset += param->encKeyLen; } if (param->fixedIvLength > 0u) { if (memcpy_s(client->iv, sizeof(client->iv), keyBuf + offset, param->fixedIvLength) != EOK) { return; } offset += param->fixedIvLength; if (memcpy_s(server->iv, sizeof(server->iv), keyBuf + offset, param->fixedIvLength) != EOK) { return; } } PackSuitInfo(client, param); PackSuitInfo(server, param); } int32_t RecConnKeyBlockGen(HITLS_Lib_Ctx *libCtx, const char *attrName, const REC_SecParameters *param, RecConnSuitInfo *client, RecConnSuitInfo *server) { /** Calculate the key length: 2MAC, 2key, 2IV */ uint32_t keyLen = ((uint32_t)param->macKeyLen * 2) + ((uint32_t)param->encKeyLen * 2) + ((uint32_t)param->fixedIvLength * 2); if (keyLen == 0u || param->macKeyLen > sizeof(client->macKey) || param->encKeyLen > sizeof(client->key) || param->fixedIvLength > sizeof(client->iv)) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_NOT_SUPPORT_CIPHER); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15943, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record Key: not support--length is invalid.", 0, 0, 0, 0); return HITLS_REC_ERR_NOT_SUPPORT_CIPHER; } /* Based on RFC5246 6.3 key_block = PRF(SecurityParameters.master_secret, "key expansion", SecurityParameters.server_random + SecurityParameters.client_random); */ CRYPT_KeyDeriveParameters keyDeriveParam = {0}; keyDeriveParam.hashAlgo = param->prfAlg; keyDeriveParam.secret = param->masterSecret; keyDeriveParam.secretLen = REC_MASTER_SECRET_LEN; keyDeriveParam.label = (const uint8_t *)KEY_EXPANSION_LABEL; keyDeriveParam.labelLen = strlen(KEY_EXPANSION_LABEL); keyDeriveParam.libCtx = libCtx; keyDeriveParam.attrName = attrName; uint8_t randomValue[REC_RANDOM_LEN * 2]; /** Random value of the replication server */ (void)memcpy_s(randomValue, sizeof(randomValue), param->serverRandom, REC_RANDOM_LEN); /** Random value of the replication client */ (void)memcpy_s(&randomValue[REC_RANDOM_LEN], sizeof(randomValue) - REC_RANDOM_LEN, param->clientRandom, REC_RANDOM_LEN); keyDeriveParam.seed = randomValue; // Total length of 2 random numbers keyDeriveParam.seedLen = REC_RANDOM_LEN * 2; /** Maximum key length: 2MAC, 2key, 2IV */ uint8_t keyBuf[REC_MAX_KEY_BLOCK_LEN]; int32_t ret = SAL_CRYPT_PRF(&keyDeriveParam, keyBuf, keyLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15944, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record Key:generate fail.", 0, 0, 0, 0); return ret; } RecConnCalcWriteKey(param, keyBuf, REC_MAX_KEY_BLOCK_LEN, client, server); BSL_SAL_CleanseData(keyBuf, sizeof(keyBuf)); return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 int32_t RecTLS13CalcWriteKey(CRYPT_KeyDeriveParameters *deriveInfo, uint8_t *key, uint32_t keyLen) { uint8_t label[] = "key"; deriveInfo->label = label; deriveInfo->labelLen = sizeof(label) - 1; return SAL_CRYPT_HkdfExpandLabel(deriveInfo, key, keyLen); } int32_t RecTLS13CalcWriteIv(CRYPT_KeyDeriveParameters *deriveInfo, uint8_t *iv, uint32_t ivLen) { uint8_t label[] = "iv"; deriveInfo->label = label; deriveInfo->labelLen = sizeof(label) - 1; return SAL_CRYPT_HkdfExpandLabel(deriveInfo, iv, ivLen); } int32_t RecTLS13ConnKeyBlockGen(HITLS_Lib_Ctx *libCtx, const char *attrName, const REC_SecParameters *param, RecConnSuitInfo *suitInfo) { const uint8_t *secret = (const uint8_t *)param->masterSecret; uint32_t secretLen = SAL_CRYPT_DigestSize(param->prfAlg); if (secretLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17234, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } uint32_t keyLen = param->encKeyLen; uint32_t ivLen = param->fixedIvLength; if (secretLen > sizeof(param->masterSecret) || keyLen > sizeof(suitInfo->key) || ivLen > sizeof(suitInfo->iv)) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_NOT_SUPPORT_CIPHER); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15408, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "length is invalid.", 0, 0, 0, 0); return HITLS_REC_ERR_NOT_SUPPORT_CIPHER; } CRYPT_KeyDeriveParameters deriveInfo = {0}; deriveInfo.hashAlgo = param->prfAlg; deriveInfo.secret = secret; deriveInfo.secretLen = secretLen; deriveInfo.libCtx = libCtx; deriveInfo.attrName = attrName; int32_t ret = RecTLS13CalcWriteKey(&deriveInfo, suitInfo->key, keyLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17235, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CalcWriteKey fail", 0, 0, 0, 0); return ret; } ret = RecTLS13CalcWriteIv(&deriveInfo, suitInfo->iv, ivLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17236, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CalcWriteIv fail", 0, 0, 0, 0); return ret; } PackSuitInfo(suitInfo, param); return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */
2302_82127028/openHiTLS-examples
tls/record/src/rec_conn.c
C
unknown
16,301
/* * 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 REC_CONN_H #define REC_CONN_H #include <stdint.h> #include <stddef.h> #include "rec.h" #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) #include "rec_anti_replay.h" #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ #ifdef __cplusplus extern "C" { #endif #define REC_MAX_MAC_KEY_LEN 64 #define REC_MAX_KEY_LENGTH 64 #define REC_MAX_IV_LENGTH 16 #define REC_MAX_KEY_BLOCK_LEN (REC_MAX_MAC_KEY_LEN * 2 + REC_MAX_KEY_LENGTH * 2 + REC_MAX_IV_LENGTH * 2) #define MAX_SHA1_SIZE 20 #define MAX_MD5_SIZE 16 #define REC_CONN_SEQ_SIZE 8u /* Sequence number size */ /** * Cipher suite information, which is required for local encryption and decryption * For details, see RFC5246 6.1 */ typedef struct { HITLS_MacAlgo macAlg; /* MAC algorithm */ HITLS_CipherAlgo cipherAlg; /* symmetric encryption algorithm */ HITLS_CipherType cipherType; /* encryption algorithm type */ HITLS_Cipher_Ctx *ctx; /* cipher context handle, only for record layer encryption and decryption */ HITLS_HMAC_Ctx *macCtx; /* mac context handle, only for record layer mac */ uint8_t macKey[REC_MAX_MAC_KEY_LEN]; uint8_t key[REC_MAX_KEY_LENGTH]; uint8_t iv[REC_MAX_IV_LENGTH]; bool isExportIV; /* Used by the TTO feature. The IV does not need to be randomly generated during CBC encryption If it is set by user */ /* key length */ uint8_t macKeyLen; /* Length of the MAC key. The length of the MAC key is 0 in AEAD algorithm */ uint8_t encKeyLen; /* Length of the symmetric key */ uint8_t fixedIvLength; /* iv length. It is the implicit IV length in AEAD algorithm */ /* result length */ uint8_t blockLength; /* If the block length is not zero, the alignment should be handled */ uint8_t recordIvLength; /* The explicit IV needs to be sent to the peer */ uint8_t macLen; /* Add the length of the MAC. Or the tag length in AEAD */ } RecConnSuitInfo; /* connection state */ typedef struct { RecConnSuitInfo *suiteInfo; /* Cipher suite information */ uint64_t seq; /* tls: 8 byte sequence number or dtls: 6 byte seq */ bool isWrapped; /* tls: Check whether the sequence number is wrapped */ uint16_t epoch; /* dtls: 2 byte epoch */ #if defined(HITLS_BSL_UIO_UDP) uint16_t reserve; /* Four-byte alignment is reserved */ RecSlidWindow window; /* dtls record sliding window (for anti-replay) */ #endif } RecConnState; /* see TLSPlaintext structure definition in rfc */ typedef struct { uint8_t type; // ccs(20), alert(21), hs(22), app data(23), (255) #ifdef HITLS_TLS_FEATURE_ETM bool isEncryptThenMac; #endif uint8_t reverse[2]; uint16_t version; uint16_t negotiatedVersion; uint8_t seq[REC_CONN_SEQ_SIZE]; /* 1. tls: sequence number 2.dtls: epoch + sequence */ uint32_t textLen; const uint8_t *text; // fragment } REC_TextInput; /** * @brief Initialize RecConnState */ RecConnState *RecConnStateNew(void); /** * @brief Release RecConnState */ void RecConnStateFree(RecConnState *state); /** * @brief Obtain the Sequence number * * @param state [IN] Connection state * * @retval Sequence number */ uint64_t RecConnGetSeqNum(const RecConnState *state); /** * @brief Set the Sequence number * * @param state [IN] Connection state * @param seq [IN] Sequence number * * @retval Sequence number */ void RecConnSetSeqNum(RecConnState *state, uint64_t seq); #ifdef HITLS_TLS_PROTO_DTLS12 /** * @brief Obtain the epoch * * @attention state can not be null pointer * * @param state [IN] Connection state * * @retval epoch */ uint16_t RecConnGetEpoch(const RecConnState *state); /** * @brief Set epoch * * @attention state can not be null pointer * @param state [IN] Connection state * @param epoch [IN] epoch * */ void RecConnSetEpoch(RecConnState *state, uint16_t epoch); #endif /** * @brief Set the key information * * @param state [IN] Connection state * @param suitInfo [IN] Ciphersuite information * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * @retval HITLS_MEMALLOC_FAIL Memory allocated failed */ int32_t RecConnStateSetCipherInfo(RecConnState *state, RecConnSuitInfo *suitInfo); /** * @brief Encrypt the record payload * * @param ctx [IN] tls Context * @param state RecState context * @param plainMsg [IN] Input data before encryption * @param cipherText [OUT] Encrypted content * @param cipherTextLen [IN] Length after encryption * * @retval HITLS_SUCCESS * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_REC_ERR_NOT_SUPPORT_CIPHER The key algorithm is not supported * @retval HITLS_REC_ERR_ENCRYPT Encryption failed * @see SAL_CRYPT_Encrypt */ int32_t RecConnEncrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen); /** * @brief Decrypt the record payload * * @param ctx [IN] tls Context * @param state RecState context * @param cryptMsg [IN] Content to be decrypted * @param data [OUT] Decrypted data * @param dataLen [IN/OUT] IN: length of data OUT: length after decryption * * @retval HITLS_SUCCESS * @retval HITLS_REC_ERR_NOT_SUPPORT_CIPHER The key algorithm is not supported * @retval HITLS_MEMCPY_FAIL Memory copy failed */ int32_t RecConnDecrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen); /** * @brief Key generation * * @param libCtx [IN] library context for provider * @param attrName [IN] attribute name of the provider, maybe NULL * @param param [IN] Security parameter * @param client [OUT] Client key material * @param server [OUT] Server key material * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * @retval Reference SAL_CRYPT_PRF */ int32_t RecConnKeyBlockGen(HITLS_Lib_Ctx *libCtx, const char *attrName, const REC_SecParameters *param, RecConnSuitInfo *client, RecConnSuitInfo *server); /** * @brief TLS1.3 Key generation * * @param libCtx [IN] library context for provider * @param attrName [IN] attribute name of the provider, maybe NULL * @param param [IN] Security parameter * @param suitInfo [OUT] key material * * @retval HITLS_SUCCESS * @retval HITLS_UNREGISTERED_CALLBACK Unregistered callback * @retval HITLS_CRYPT_ERR_DIGEST hash calculation failed * @retval HITLS_CRYPT_ERR_HKDF_EXPAND HKDF-Expand calculation fails * */ int32_t RecTLS13ConnKeyBlockGen(HITLS_Lib_Ctx *libCtx, const char *attrName, const REC_SecParameters *param, RecConnSuitInfo *suitInfo); /* * @brief check the mac * * @param ctx [IN] tls Context * @param suiteInfo [IN] ciphersuiteInfo * @param cryptMsg [IN] text info * @param text [IN] fragment * @param textLen [IN] fragment len * @retval HITLS_SUCCESS * @retval Reference hitls_error.h */ int32_t RecConnCheckMac(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, const REC_TextInput *cryptMsg, const uint8_t *text, uint32_t textLen); /* * @brief generate the mac * * @param libCtx [IN] library context for provider * @param attrName [IN] attribute name of the provider, maybe NULL * @param suiteInfo [IN] ciphersuiteInfo * @param plainMsg [IN] text info * @param mac [OUT] mac buffer * @param macLen [OUT] mac buffer len * @retval HITLS_SUCCESS * @retval Reference hitls_error.h */ int32_t RecConnGenerateMac(HITLS_Lib_Ctx *libCtx, const char *attrName, RecConnSuitInfo *suiteInfo, const REC_TextInput *plainMsg, uint8_t *mac, uint32_t *macLen); /* * @brief check the mac * * @param in [IN] plaintext info * @param text [IN] plaintext buf * @param textLen [IN] plaintext buf len * @param out [IN] mac info * @retval HITLS_SUCCESS * @retval Reference hitls_error.h */ void RecConnInitGenerateMacInput(const REC_TextInput *in, const uint8_t *text, uint32_t textLen, REC_TextInput *out); #ifdef HITLS_TLS_SUITE_CIPHER_CBC uint32_t RecGetHashAlgoFromMACAlgo(HITLS_MacAlgo macAlgo); #endif #ifdef __cplusplus } #endif #endif /* REC_CONN_H */
2302_82127028/openHiTLS-examples
tls/record/src/rec_conn.h
C
unknown
9,038
/* * 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 <string.h> #include "securec.h" #include "hitls_build.h" #include "bsl_bytes.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #ifdef HITLS_TLS_SUITE_CIPHER_AEAD #include "rec_crypto_aead.h" #endif #ifdef HITLS_TLS_SUITE_CIPHER_CBC #include "rec_crypto_cbc.h" #endif #include "tls_binlog_id.h" #include "rec_conn.h" #include "rec_alert.h" #include "indicator.h" #include "hs.h" #include "hitls_error.h" #ifdef HITLS_TLS_PROTO_TLS13 /* 16384 + 1: RFC8446 5.4. Record Padding the full encoded TLSInnerPlaintext MUST NOT exceed 2^14 + 1 octets. */ #define MAX_PADDING_LEN 16385 /* * * @brief Obtain the content and record message types from the decrypted TLSInnerPlaintext. * After TLS1.3 decryption, the TLSInnerPlaintext structure is used. The padding needs to be removed and the actual message type needs to be obtained. * * struct { * opaque content[TLSPlaintext.length]; * ContentType type; * uint8 zeros[length_of_padding]; * } TLSInnerPlaintext; * * @param text [IN] Decrypted content (TLSInnerPlaintext) * @param textLen [OUT] Input (length of TLSInnerPlaintext) * Length of the output content * @param recType [OUT] Message body length * * @return HITLS_SUCCESS succeeded * HITLS_ALERT_FATAL Unexpected Message */ int32_t RecParseInnerPlaintext(TLS_Ctx *ctx, const uint8_t *text, uint32_t *textLen, uint8_t *recType) { /* The receiver decrypts and scans the field from the end to the beginning until it finds a non-zero octet. This * non-zero byte is the message type of record If no non-zero bytes are found, an unexpected alert needs to be sent * and the chain is terminated */ uint32_t len = *textLen; for (uint32_t i = len; i > 0; i--) { if (text[i - 1] != 0) { *recType = text[i - 1]; // When the value is the same as the rectype index, the value is the length of the content *textLen = i - 1; return HITLS_SUCCESS; } } BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_RECV_UNEXPECTED_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15453, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Recved UNEXPECTED_MESSAGE.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } #endif /* HITLS_TLS_PROTO_TLS13 */ static int32_t DefaultDecryptPostProcess(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, REC_TextInput *encryptedMsg, uint8_t *data, uint32_t *dataLen) { (void)ctx; (void)suiteInfo; (void)encryptedMsg; (void)data; (void)dataLen; #ifdef HITLS_TLS_PROTO_TLS13 /* If the version is tls1.3 and encryption is required, you need to create a TLSInnerPlaintext message */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13 && suiteInfo != NULL) { return RecParseInnerPlaintext(ctx, data, dataLen, &encryptedMsg->type); } #endif return HITLS_SUCCESS; } static int32_t DefaultEncryptPreProcess(TLS_Ctx *ctx, uint8_t recordType, const uint8_t *data, uint32_t plainLen, RecordPlaintext *recPlaintext) { #ifdef HITLS_TLS_PROTO_TLS (void)ctx, (void)data; recPlaintext->recordType = recordType; recPlaintext->plainLen = plainLen; recPlaintext->plainData = NULL; #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version != HITLS_VERSION_TLS13 || ctx->recCtx->writeStates.currentState->suiteInfo == NULL) { return HITLS_SUCCESS; } recPlaintext->isTlsInnerPlaintext = true; /* Currently, the padding length is set to 0. If required, the padding length can be customized */ uint16_t recPaddingLength = 0; if (ctx->config.tlsConfig.recordPaddingCb != NULL) { recPaddingLength = (uint16_t)ctx->config.tlsConfig.recordPaddingCb(ctx, recordType, plainLen, ctx->config.tlsConfig.recordPaddingArg); } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate( 0, HS_GetVersion(ctx), RECORD_INNER_CONTENT_TYPE, &recordType, 1, ctx, ctx->config.tlsConfig.msgArg); #endif /* TlsInnerPlaintext see rfc 8446 section 5.2 */ /* tlsInnerPlaintext length = content length + record type length (1) + padding length */ uint32_t tlsInnerPlaintextLen = plainLen + sizeof(uint8_t) + recPaddingLength; if (tlsInnerPlaintextLen > MAX_PADDING_LEN) { BSL_ERR_PUSH_ERROR(HITLS_REC_RECORD_OVERFLOW); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15669, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Pack TlsInnerPlaintext length(%u) MUST NOT exceed 2^14 + 1 octets.", tlsInnerPlaintextLen, 0, 0, 0); return HITLS_REC_RECORD_OVERFLOW; } uint8_t *tlsInnerPlaintext = BSL_SAL_Calloc(1u, tlsInnerPlaintextLen); if (tlsInnerPlaintext == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17253, "Calloc fail"); } if (memcpy_s(tlsInnerPlaintext, tlsInnerPlaintextLen, data, plainLen) != EOK) { BSL_SAL_FREE(tlsInnerPlaintext); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMCPY_FAIL, BINLOG_ID17254, "memcpy fail"); } tlsInnerPlaintext[plainLen] = recordType; /* Padding is calloc when the memory is applied for. Therefore, the number of buffs to be supplemented is 0. You do * not need to perform any operation */ recPlaintext->plainLen = tlsInnerPlaintextLen; recPlaintext->plainData = tlsInnerPlaintext; /* tls1.3 Hide the actual record type during encryption */ recPlaintext->recordType = (uint8_t)REC_TYPE_APP; #endif /* HITLS_TLS_PROTO_TLS13 */ return HITLS_SUCCESS; #else (void)ctx, (void)recordType, (void)data, (void)plainLen, (void)recPlaintext; return HITLS_REC_ERR_NOT_SUPPORT_CIPHER; #endif /* HITLS_TLS_PROTO_TLS */ } static uint32_t PlainCalCiphertextLen(const TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t plantextLen, bool isRead) { (void)ctx; (void)suiteInfo; (void)isRead; return plantextLen; } static int32_t PlainCalPlantextBufLen(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t ciphertextLen, uint32_t *offset, uint32_t *plainLen) { (void)ctx; (void)suiteInfo; *offset = 0; *plainLen = ciphertextLen; return HITLS_SUCCESS; } static int32_t PlainDecrypt(TLS_Ctx *ctx, RecConnState *suiteInfo, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { (void)ctx; (void)suiteInfo; if (memcpy_s(data, *dataLen, cryptMsg->text, cryptMsg->textLen) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15404, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnDecrypt Failed: memcpy fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } // For empty ciphersuite case, the plaintext length is equal to ciphertext length *dataLen = cryptMsg->textLen; return HITLS_SUCCESS; } static int32_t PlainEncrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { (void)ctx; (void)state; if (memcpy_s(cipherText, cipherTextLen, plainMsg->text, plainMsg->textLen) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15926, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record:memcpy fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; } static int32_t UnsupoortDecrypt(TLS_Ctx *ctx, RecConnState *suiteInfo, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { (void)ctx; (void)suiteInfo; (void)cryptMsg; (void)data; (void)dataLen; return HITLS_REC_ERR_NOT_SUPPORT_CIPHER; } static int32_t UnsupoortEncrypt(TLS_Ctx *ctx, RecConnState *State, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { (void)ctx; (void)State; (void)plainMsg; (void)cipherText; (void)cipherTextLen; return HITLS_REC_ERR_NOT_SUPPORT_CIPHER; } const RecCryptoFunc *RecGetCryptoFuncs(const RecConnSuitInfo *suiteInfo) { static RecCryptoFunc cryptoFuncPlain = { PlainCalCiphertextLen, PlainCalPlantextBufLen, PlainDecrypt, DefaultDecryptPostProcess, PlainEncrypt, DefaultEncryptPreProcess }; if (suiteInfo == NULL) { return &cryptoFuncPlain; } switch (suiteInfo->cipherType) { #ifdef HITLS_TLS_SUITE_CIPHER_AEAD case HITLS_AEAD_CIPHER: return RecGetAeadCryptoFuncs(DefaultDecryptPostProcess, DefaultEncryptPreProcess); #endif #ifdef HITLS_TLS_SUITE_CIPHER_CBC case HITLS_CBC_CIPHER: return RecGetCbcCryptoFuncs(DefaultDecryptPostProcess, DefaultEncryptPreProcess); #endif default: break; } BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_NOT_SUPPORT_CIPHER); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16240, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Internal error, unsupport cipher.", 0, 0, 0, 0); static RecCryptoFunc cryptoFuncUnsupport = { PlainCalCiphertextLen, PlainCalPlantextBufLen, UnsupoortDecrypt, DefaultDecryptPostProcess, UnsupoortEncrypt, DefaultEncryptPreProcess }; return &cryptoFuncUnsupport; }
2302_82127028/openHiTLS-examples
tls/record/src/rec_crypto.c
C
unknown
9,838
/* * 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 REC_CRYPT_H #define REC_CRYPT_H #include "hitls_build.h" #include "hitls_error.h" #include "record.h" #include "rec_conn.h" #ifdef HITLS_TLS_PROTO_TLS typedef struct { REC_Type recordType; /* Protocol type */ uint32_t plainLen; /* message length */ uint8_t *plainData; /* message data */ #ifdef HITLS_TLS_PROTO_TLS13 /* Length of the tls1.3 padding content. Currently, the value is 0. The value can be used as required */ uint64_t recPaddingLength; #endif bool isTlsInnerPlaintext; /* Whether it is a TLSInnerPlaintext message for tls1.3 */ } RecordPlaintext; /* Record protocol data before encryption */ #else typedef struct DtlsRecordPlaintext RecordPlaintext; #endif typedef uint32_t (*CalCiphertextLenFunc)(const TLS_Ctx *ctx, RecConnSuitInfo *suitInfo, uint32_t plantextLen, bool isRead); typedef int32_t (*CalPlantextBufLenFunc)(TLS_Ctx *ctx, RecConnSuitInfo *suitInfo, uint32_t ciphertextLen, uint32_t *offset, uint32_t *plaintextLen); typedef int32_t (*DecryptFunc)(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen); typedef int32_t (*EncryptFunc)(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen); typedef int32_t (*DecryptPostProcess)(TLS_Ctx *ctx, RecConnSuitInfo *suitInfo, REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen); typedef int32_t (*EncryptPreProcess)(TLS_Ctx *ctx, uint8_t recordType, const uint8_t *data, uint32_t plainLen, RecordPlaintext *recPlaintext); typedef struct { CalCiphertextLenFunc calCiphertextLen; CalPlantextBufLenFunc calPlantextBufLen; DecryptFunc decrypt; DecryptPostProcess decryptPostProcess; EncryptFunc encryt; EncryptPreProcess encryptPreProcess; } RecCryptoFunc; const RecCryptoFunc *RecGetCryptoFuncs(const RecConnSuitInfo *suiteInfo); #endif
2302_82127028/openHiTLS-examples
tls/record/src/rec_crypto.h
C
unknown
2,452
/* * 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 <string.h> #include "hitls_build.h" #ifdef HITLS_TLS_SUITE_CIPHER_AEAD #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "crypt.h" #include "hitls_error.h" #include "record.h" #include "rec_alert.h" #include "rec_conn.h" #include "rec_crypto_aead.h" #define AEAD_AAD_TLS12_SIZE 13u /* TLS1.2 AEAD additional_data length */ #define AEAD_AAD_MAX_SIZE AEAD_AAD_TLS12_SIZE #define AEAD_NONCE_SIZE 12u /* The length of the AEAD nonce is fixed to 12 */ #define AEAD_NONCE_ZEROS_SIZE 4u /* The length of the AEAD nonce First 4 bytes */ #ifdef HITLS_TLS_PROTO_TLS13 #define AEAD_AAD_TLS13_SIZE 5u /* TLS1.3 AEAD additional_data length */ #endif static int32_t CleanSensitiveData(int32_t ret, uint8_t *nonce, uint8_t *aad, uint32_t outLen, uint32_t cipherLen) { BSL_SAL_CleanseData(nonce, AEAD_NONCE_SIZE); BSL_SAL_CleanseData(aad, AEAD_AAD_MAX_SIZE); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15480, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record:encrypt record error.", NULL, NULL, NULL, NULL); return ret; } if (outLen != cipherLen) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_ENCRYPT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15481, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record:encrypt error. outLen:%u cipherLen:%u", outLen, cipherLen, NULL, NULL); return HITLS_REC_ERR_ENCRYPT; } return HITLS_SUCCESS; } static int32_t AeadGetNonce(const RecConnSuitInfo *suiteInfo, uint8_t *nonce, uint8_t nonceLen, const uint8_t *seq, uint8_t seqLen) { uint8_t fixedIvLength = suiteInfo->fixedIvLength; uint8_t recordIvLength = suiteInfo->recordIvLength; if ((fixedIvLength + recordIvLength) != nonceLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17239, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "nonceLen err", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_AEAD_NONCE_PARAM); return HITLS_REC_ERR_AEAD_NONCE_PARAM; // The caller should ensure that the input is correct } if (recordIvLength == seqLen) { /* * According to the RFC5116 && RFC5288 AEAD_AES_128_GCM/AEAD_AES_256_GCM definition, the nonce length is fixed * to 12. 4 bytes + 8bytes(64 bits record sequence number, big endian) = 12 bytes 4 bytes the implicit part be * derived from iv. The first 4 bytes of the IV are obtained. */ (void)memcpy_s(nonce, nonceLen, suiteInfo->iv, fixedIvLength); (void)memcpy_s(&nonce[fixedIvLength], recordIvLength, seq, seqLen); return HITLS_SUCCESS; } else if (recordIvLength == 0) { /* * (same as defined in RFC7905 AEAD_CHACHA20_POLY1305) * The per-record nonce for the AEAD defined in RFC8446 5.3 * First 4 bytes (all 0s) + Last 8bytes(64 bits record sequence number, big endian) = 12 bytes * Perform XOR with the 12 bytes IV. The result is nonce. */ // First four bytes (all 0s) (void)memset_s(&nonce[0], nonceLen, 0, AEAD_NONCE_ZEROS_SIZE); // First 4 bytes (all 0s) + Last 8 bytes (64-bit record sequence number, big endian) (void)memcpy_s(&nonce[AEAD_NONCE_ZEROS_SIZE], nonceLen - AEAD_NONCE_ZEROS_SIZE, seq, seqLen); for (uint32_t i = 0; i < nonceLen; i++) { nonce[i] = nonce[i] ^ suiteInfo->iv[i]; } return HITLS_SUCCESS; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17240, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get nonce fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_AEAD_NONCE_PARAM); return HITLS_REC_ERR_AEAD_NONCE_PARAM; } static void AeadGetAad(uint8_t *aad, uint32_t *aadLen, const REC_TextInput *input, uint32_t plainDataLen) { #ifdef HITLS_TLS_PROTO_TLS13 /* TLS1.3 generation additional_data = TLSCiphertext.opaque_type || TLSCiphertext.legacy_record_version || TLSCiphertext.length */ if (input->negotiatedVersion == HITLS_VERSION_TLS13) { // The 0th byte is the record type aad[0] = input->type; uint32_t offset = 1; // The first and second bytes of indicate the version number BSL_Uint16ToByte(input->version, &aad[offset]); offset += sizeof(uint16_t); // The third and fourth bytes of indicate the data length BSL_Uint16ToByte((uint16_t)plainDataLen, &aad[offset]); *aadLen = AEAD_AAD_TLS13_SIZE; return; } #endif /* HITLS_TLS_PROTO_TLS13 */ /* non-TLS1.3 generation additional_data = seq_num + TLSCompressed.type + TLSCompressed.version + * TLSCompressed.length */ (void)memcpy_s(aad, AEAD_AAD_MAX_SIZE, input->seq, REC_CONN_SEQ_SIZE); uint32_t offset = REC_CONN_SEQ_SIZE; aad[offset] = input->type; // The eighth byte indicates the record type offset++; BSL_Uint16ToByte(input->version, &aad[offset]); // The ninth and tenth bytes indicate the version number. offset += sizeof(uint16_t); BSL_Uint16ToByte((uint16_t)plainDataLen, &aad[offset]); // The 11th and 12th bytse indicate the data length. *aadLen = AEAD_AAD_TLS12_SIZE; return; } static uint32_t AeadCalCiphertextLen(const TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t plantextLen, bool isRead) { (void)ctx; (void)isRead; return plantextLen + suiteInfo->macLen + suiteInfo->recordIvLength; } static int32_t AeadCalPlantextBufLen(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t ciphertextLen, uint32_t *offset, uint32_t *plainLen) { (void)ctx; *offset = suiteInfo->recordIvLength; uint32_t plantextLen = ciphertextLen - suiteInfo->macLen - suiteInfo->recordIvLength; if (plantextLen > ciphertextLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17241, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "plantextLen err", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } *plainLen = plantextLen; return HITLS_SUCCESS; } static int32_t AeadDecrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { RecConnSuitInfo *suiteInfo = state->suiteInfo; /** Initialize the encryption length offset */ uint32_t cipherOffset = 0u; HITLS_CipherParameters cipherParam = {0}; cipherParam.ctx = &suiteInfo->ctx; cipherParam.type = suiteInfo->cipherType; cipherParam.algo = suiteInfo->cipherAlg; cipherParam.key = (const uint8_t *)suiteInfo->key; cipherParam.keyLen = suiteInfo->encKeyLen; /** Read the explicit IV during AEAD decryption */ const uint8_t *recordIv; if (suiteInfo->recordIvLength > 0u) { recordIv = &cryptMsg->text[cipherOffset]; cipherOffset += REC_CONN_SEQ_SIZE; } else { // If no IV is displayed, use the serial number recordIv = cryptMsg->seq; } /** Calculate NONCE */ uint8_t nonce[AEAD_NONCE_SIZE] = {0}; int32_t ret = AeadGetNonce(suiteInfo, nonce, sizeof(nonce), recordIv, REC_CONN_SEQ_SIZE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15395, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record decrypt:get nonce failed.", 0, 0, 0, 0); return ret; } cipherParam.iv = nonce; cipherParam.ivLen = AEAD_NONCE_SIZE; /* Calculate additional_data */ uint8_t aad[AEAD_AAD_MAX_SIZE] = {0}; uint32_t aadLen = AEAD_AAD_MAX_SIZE; /* Definition of additional_data tls1.2 additional_data = seq_num + TLSCompressed.type + TLSCompressed.version + TLSCompressed.length; tls1.3 additional_data = TLSCiphertext.opaque_type || TLSCiphertext.legacy_record_version || TLSCiphertext.length diff: length */ uint32_t plainDataLen = cryptMsg->textLen; if (cryptMsg->negotiatedVersion != HITLS_VERSION_TLS13) { plainDataLen = cryptMsg->textLen - suiteInfo->recordIvLength - suiteInfo->macLen; } AeadGetAad(aad, &aadLen, cryptMsg, plainDataLen); cipherParam.aad = aad; cipherParam.aadLen = aadLen; /** Calculate the encryption length: GenericAEADCipher.content + aead tag */ uint32_t cipherLen = cryptMsg->textLen - cipherOffset; /** Decryption */ ret = SAL_CRYPT_Decrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, &cryptMsg->text[cipherOffset], cipherLen, data, dataLen); /* Clear sensitive information */ BSL_SAL_CleanseData(nonce, AEAD_NONCE_SIZE); BSL_SAL_CleanseData(aad, AEAD_AAD_MAX_SIZE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15396, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decrypt record error. ret:%d", ret, 0, 0, 0); if (BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); return HITLS_REC_BAD_RECORD_MAC; } return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } return HITLS_SUCCESS; } /** * @brief AEAD encryption * * @param state [IN] RecConnState Context * @param input [IN] Input data before encryption * @param cipherText [OUT] Encrypted content * @param cipherTextLen [IN] Length after encryption * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_INTERNAL_EXCEPTION: null pointer * @retval HITLS_MEMCPY_FAIL The copy fails. * @retval For details, see SAL_CRYPT_Encrypt. */ static int32_t AeadEncrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { /** Initialize the encryption length offset */ uint32_t cipherOffset = 0u; HITLS_CipherParameters cipherParam = {0}; cipherParam.ctx = &state->suiteInfo->ctx; cipherParam.type = state->suiteInfo->cipherType; cipherParam.algo = state->suiteInfo->cipherAlg; cipherParam.key = (const uint8_t *)state->suiteInfo->key; cipherParam.keyLen = state->suiteInfo->encKeyLen; /** During AEAD encryption, the sequence number is used as the explicit IV */ if (state->suiteInfo->recordIvLength > 0u) { if (memcpy_s(&cipherText[cipherOffset], cipherTextLen, plainMsg->seq, REC_CONN_SEQ_SIZE) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15384, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record encrypt:memcpy fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } cipherOffset += REC_CONN_SEQ_SIZE; } /** Calculate NONCE */ uint8_t nonce[AEAD_NONCE_SIZE] = {0}; int32_t ret = AeadGetNonce(state->suiteInfo, nonce, sizeof(nonce), plainMsg->seq, REC_CONN_SEQ_SIZE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15385, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record encrypt:get nonce failed.", 0, 0, 0, 0); return ret; } cipherParam.iv = nonce; cipherParam.ivLen = AEAD_NONCE_SIZE; /* Calculate additional_data */ uint8_t aad[AEAD_AAD_MAX_SIZE]; uint32_t aadLen = AEAD_AAD_MAX_SIZE; uint32_t textLen = #ifdef HITLS_TLS_PROTO_TLS13 (plainMsg->negotiatedVersion == HITLS_VERSION_TLS13) ? cipherTextLen : #endif /* HITLS_TLS_PROTO_TLS13 */ plainMsg->textLen; AeadGetAad(aad, &aadLen, plainMsg, textLen); cipherParam.aad = aad; cipherParam.aadLen = aadLen; /** Calculate the encryption length */ uint32_t cipherLen = cipherTextLen - cipherOffset; uint32_t outLen = cipherLen; /** Encryption */ ret = SAL_CRYPT_Encrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, plainMsg->text, plainMsg->textLen, &cipherText[cipherOffset], &outLen); /* Clear sensitive information */ return CleanSensitiveData(ret, nonce, aad, outLen, cipherLen); } const RecCryptoFunc *RecGetAeadCryptoFuncs(DecryptPostProcess decryptPostProcess, EncryptPreProcess encryptPreProcess) { static RecCryptoFunc cryptoFuncAead = { .calCiphertextLen = AeadCalCiphertextLen, .calPlantextBufLen = AeadCalPlantextBufLen, .decrypt = AeadDecrypt, .encryt = AeadEncrypt, }; cryptoFuncAead.decryptPostProcess = decryptPostProcess; cryptoFuncAead.encryptPreProcess = encryptPreProcess; return &cryptoFuncAead; } #endif
2302_82127028/openHiTLS-examples
tls/record/src/rec_crypto_aead.c
C
unknown
12,947
/* * 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 REC_CRYPT_AEAD_H #define REC_CRYPT_AEAD_H #include "rec_crypto.h" const RecCryptoFunc *RecGetAeadCryptoFuncs(DecryptPostProcess decryptPostProcess, EncryptPreProcess encryptPreProcess); #endif
2302_82127028/openHiTLS-examples
tls/record/src/rec_crypto_aead.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. */ #include "hitls_build.h" #ifdef HITLS_TLS_SUITE_CIPHER_CBC #include "securec.h" #include "hitls_error.h" #include "bsl_err_internal.h" #include "bsl_log_internal.h" #include "tls_binlog_id.h" #include "bsl_bytes.h" #include "crypt.h" #include "rec_alert.h" #include "rec_conn.h" #include "record.h" #include "rec_crypto_cbc.h" #define CBC_PADDING_LEN_TAG_SIZE 1u #define HMAC_MAX_BLEN 144 uint8_t RecConnGetCbcPaddingLen(uint8_t blockLen, uint32_t plaintextLen) { if (blockLen == 0) { return 0; } uint8_t remainder = (plaintextLen + CBC_PADDING_LEN_TAG_SIZE) % blockLen; if (remainder == 0) { return 0; } return blockLen - remainder; } static uint32_t CbcCalCiphertextLen(const TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t plantextLen, bool isRead) { uint32_t ciphertextLen = plantextLen; ciphertextLen += suiteInfo->recordIvLength; bool isEncryptThenMac = isRead ? ctx->negotiatedInfo.isEncryptThenMacRead : ctx->negotiatedInfo.isEncryptThenMacWrite; if (isEncryptThenMac) { ciphertextLen += RecConnGetCbcPaddingLen(suiteInfo->blockLength, ciphertextLen) + CBC_PADDING_LEN_TAG_SIZE; ciphertextLen += suiteInfo->macLen; } else { ciphertextLen += suiteInfo->macLen; ciphertextLen += RecConnGetCbcPaddingLen(suiteInfo->blockLength, ciphertextLen) + CBC_PADDING_LEN_TAG_SIZE; } return ciphertextLen; } static int32_t CbcCalPlantextBufLen(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t ciphertextLen, uint32_t *offset, uint32_t *plainLen) { uint32_t plantextLen = ciphertextLen; *offset = suiteInfo->recordIvLength; plantextLen -= *offset; if (ctx->negotiatedInfo.isEncryptThenMacRead) { plantextLen -= suiteInfo->macLen; } if (plantextLen > ciphertextLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17242, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "plantextLen err", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } *plainLen = plantextLen; return HITLS_SUCCESS; } static void RecConnInitCipherParam(HITLS_CipherParameters *cipherParam, const RecConnState *state) { cipherParam->ctx = &state->suiteInfo->ctx; cipherParam->type = state->suiteInfo->cipherType; cipherParam->algo = state->suiteInfo->cipherAlg; cipherParam->key = state->suiteInfo->key; cipherParam->keyLen = state->suiteInfo->encKeyLen; cipherParam->iv = state->suiteInfo->iv; cipherParam->ivLen = state->suiteInfo->fixedIvLength; } static int32_t RecConnCbcCheckCryptMsg(TLS_Ctx *ctx, const RecConnState *state, const REC_TextInput *cryptMsg, bool isEncryptThenMac) { uint8_t offset = 0; if (isEncryptThenMac) { offset = state->suiteInfo->macLen; } if ((state->suiteInfo->blockLength == 0) || ((cryptMsg->textLen - offset) % state->suiteInfo->blockLength != 0)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15397, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error: block length = %u, cipher text length = %u.", state->suiteInfo->blockLength, cryptMsg->textLen, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } return HITLS_SUCCESS; } static int32_t RecConnCbcDecCheckPaddingEtM(TLS_Ctx *ctx, const REC_TextInput *cryptMsg, uint8_t *plain, uint32_t plainLen, uint32_t offset) { const RecConnState *state = ctx->recCtx->readStates.currentState; uint8_t padLen = plain[plainLen - 1]; if (cryptMsg->isEncryptThenMac && (plainLen < padLen + CBC_PADDING_LEN_TAG_SIZE)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15399, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error: ciphertext len = %u, plaintext len = %u, mac len = %u, padding len = %u.", cryptMsg->textLen - offset - state->suiteInfo->macLen, plainLen, state->suiteInfo->macLen, padLen); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } for (uint32_t i = 1; i <= padLen; i++) { if (plain[plainLen - 1 - i] != padLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15400, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error: padding len = %u, %u-to-last padding data = %u.", padLen, i, plain[plainLen - 1 - i], 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } } return HITLS_SUCCESS; } static uint32_t GetHmacBLen(HITLS_MacAlgo macAlgo) { switch (macAlgo) { case HITLS_MAC_1: case HITLS_MAC_224: case HITLS_MAC_256: case HITLS_MAC_SM3: return 64; // Blen of upper hmac is 64. case HITLS_MAC_384: case HITLS_MAC_512: return 128; // Blen of upper hmac is 128. default: // should never be here. return 0; } } /** * a constant-time implemenation of HMAC to prevent side-channel attacks * reference: https://datatracker.ietf.org/doc/html/rfc2104#autoid-2 */ static int32_t ConstTimeHmac(RecConnSuitInfo *suiteInfo, HITLS_HASH_Ctx **hashCtx, uint32_t good, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t dataLen, uint8_t *mac, uint32_t *macLen) { HITLS_HASH_Ctx *obCtx = hashCtx[2]; uint32_t padLen = data[dataLen - 1]; padLen = Uint32ConstTimeSelect(good, padLen, 0); uint32_t plainLen = dataLen - (suiteInfo->macLen + padLen + 1); plainLen = Uint32ConstTimeSelect(good, plainLen, 0); uint32_t blen = GetHmacBLen(suiteInfo->macAlg); uint8_t ipad[HMAC_MAX_BLEN] = {0}; uint8_t opad[HMAC_MAX_BLEN * 2] = {0}; uint8_t key[HMAC_MAX_BLEN] = {0}; uint8_t ihash[MAX_DIGEST_SIZE] = {0}; uint32_t ihashLen = sizeof(ihash); (void)memcpy_s(key, sizeof(key), suiteInfo->macKey, suiteInfo->macKeyLen); for (uint32_t i = 0; i < blen; i++) { ipad[i] = key[i] ^ 0x36; opad[i] = key[i] ^ 0x5c; } // update K xor ipad (void)SAL_CRYPT_DigestUpdate(hashCtx[0], ipad, blen); // update the obscureHashCtx simultaneously (void)SAL_CRYPT_DigestUpdate(obCtx, ipad, blen); /** * constant-time update plaintext to resist lucky13 * ref: https://www.isg.rhul.ac.uk/tls/TLStiming.pdf */ uint8_t header[13] = {0}; // seq + record type uint32_t pos = 0; (void)memcpy_s(header, sizeof(header), cryptMsg->seq, REC_CONN_SEQ_SIZE); pos += REC_CONN_SEQ_SIZE; header[pos++] = cryptMsg->type; BSL_Uint16ToByte(cryptMsg->version, header + pos); pos += sizeof(uint16_t); BSL_Uint16ToByte((uint16_t)plainLen, header + pos); (void)SAL_CRYPT_DigestUpdate(hashCtx[0], header, sizeof(header)); (void)SAL_CRYPT_DigestUpdate(obCtx, header, sizeof(header)); uint32_t maxLen = dataLen - (suiteInfo->macLen + 1); maxLen = Uint32ConstTimeSelect(good, maxLen, dataLen); uint32_t flag = Uint32ConstTimeGt(maxLen, 256); // the value of 1 byte is up to 256 uint32_t minLen = Uint32ConstTimeSelect(flag, maxLen - 256, 0); (void)SAL_CRYPT_DigestUpdate(hashCtx[0], data, minLen); (void)SAL_CRYPT_DigestUpdate(obCtx, data, minLen); for (uint32_t i = minLen; i < maxLen; i++) { if (i < plainLen) { SAL_CRYPT_DigestUpdate(hashCtx[0], data + i, 1); } else { SAL_CRYPT_DigestUpdate(obCtx, data + i, 1); } } (void)SAL_CRYPT_DigestFinal(hashCtx[0], ihash, &ihashLen); (void)memcpy_s(opad + blen, MAX_DIGEST_SIZE, ihash, ihashLen); // update (K xor opad) + ihash (void)SAL_CRYPT_DigestUpdate(hashCtx[1], opad, blen + ihashLen); (void)SAL_CRYPT_DigestFinal(hashCtx[1], mac, macLen); BSL_SAL_CleanseData(ipad, sizeof(ipad)); BSL_SAL_CleanseData(opad, sizeof(opad)); BSL_SAL_CleanseData(key, sizeof(key)); return HITLS_SUCCESS; } static inline uint32_t ConstTimeSelectMemcmp(uint32_t good, uint8_t *a, uint8_t *b, uint32_t l) { uint8_t *t = (good == 0) ? b : a; return ConstTimeMemcmp(t, b, l); } static int32_t RecConnCbcDecMtECheckMacTls(TLS_Ctx *ctx, const REC_TextInput *cryptMsg, uint8_t *plain, uint32_t plainLen) { const RecConnState *state = ctx->recCtx->readStates.currentState; uint32_t hashAlg = RecGetHashAlgoFromMACAlgo(state->suiteInfo->macAlg); if (hashAlg == HITLS_HASH_BUTT) { return HITLS_CRYPT_ERR_HMAC; } HITLS_HASH_Ctx *ihashCtx = NULL; HITLS_HASH_Ctx *ohashCtx = NULL; HITLS_HASH_Ctx *obscureHashCtx = NULL; ihashCtx = SAL_CRYPT_DigestInit(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlg); ohashCtx = SAL_CRYPT_DigestCopy(ihashCtx); obscureHashCtx = SAL_CRYPT_DigestCopy(ihashCtx); if (ihashCtx == NULL || ohashCtx == NULL || obscureHashCtx == NULL) { SAL_CRYPT_DigestFree(ihashCtx); SAL_CRYPT_DigestFree(ohashCtx); SAL_CRYPT_DigestFree(obscureHashCtx); return HITLS_REC_ERR_GENERATE_MAC; } uint8_t mac[MAX_DIGEST_SIZE] = {0}; uint32_t macLen = sizeof(mac); uint8_t padLen = plain[plainLen - 1]; uint32_t good = Uint32ConstTimeGe(plainLen, state->suiteInfo->macLen + padLen + 1); // constant-time check padding bytes for (uint32_t i = 1; i <= 255; i++) { uint32_t mask = good & Uint32ConstTimeLe(i, padLen); good &= Uint32ConstTimeEqual(plain[plainLen - 1 - (i & mask)], padLen); } HITLS_HASH_Ctx *hashCtxs[3] = {ihashCtx, ohashCtx, obscureHashCtx}; ConstTimeHmac(state->suiteInfo, hashCtxs, good, cryptMsg, plain, plainLen, mac, &macLen); // check mac uint32_t retLen = Uint32ConstTimeSelect(good, padLen, 0); plainLen -= state->suiteInfo->macLen + retLen + 1; good &= ConstTimeSelectMemcmp(good, &plain[plainLen], mac, macLen); SAL_CRYPT_DigestFree(ihashCtx); SAL_CRYPT_DigestFree(ohashCtx); SAL_CRYPT_DigestFree(obscureHashCtx); return ~good; } static int32_t RecConnCbcDecryptByMacThenEncrypt(TLS_Ctx *ctx, const RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { /* Check whether the ciphertext length is an integral multiple of the ciphertext block length */ int32_t ret = RecConnCbcCheckCryptMsg(ctx, state, cryptMsg, false); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17243, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnCbcCheckCryptMsg fail", 0, 0, 0, 0); return ret; } /* Decryption start position */ uint32_t offset = 0; /* plaintext length */ uint32_t plaintextLen = *dataLen; HITLS_CipherParameters cipherParam = {0}; RecConnInitCipherParam(&cipherParam, state); /* In TLS1.1 and later versions, explicit iv is used as the first ciphertext block. Therefore, the first * ciphertext block does not need to be decrypted */ cipherParam.iv = cryptMsg->text; offset = state->suiteInfo->fixedIvLength; ret = SAL_CRYPT_Decrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, &cryptMsg->text[offset], cryptMsg->textLen - offset, data, &plaintextLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15398, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } /* Check padding and padding length */ ret = RecConnCbcDecMtECheckMacTls(ctx, cryptMsg, data, plaintextLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17244, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnCbcDecMtECheckMacTls fail", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } *dataLen = plaintextLen - (state->suiteInfo->macLen + data[plaintextLen - 1] + CBC_PADDING_LEN_TAG_SIZE); return ret; } static int32_t RecConnCbcDecryptByEncryptThenMac(TLS_Ctx *ctx, const RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { /* Check MAC */ int32_t ret = RecConnCheckMac(ctx, state->suiteInfo, cryptMsg, cryptMsg->text, cryptMsg->textLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17245, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "check mac fail", 0, 0, 0, 0); return ret; } /* Check whether the ciphertext length is an integral multiple of the ciphertext block length */ ret = RecConnCbcCheckCryptMsg(ctx, state, cryptMsg, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17246, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnCbcCheckCryptMsg fail", 0, 0, 0, 0); return ret; } /* Decryption start position */ uint32_t offset = 0; /* plaintext length */ uint32_t plaintextLen = *dataLen; uint8_t macLen = state->suiteInfo->macLen; HITLS_CipherParameters cipherParam = {0}; RecConnInitCipherParam(&cipherParam, state); /* In TLS1.1 and later versions, explicit iv is used as the first ciphertext block. Therefore, the first * ciphertext block does not need to be decrypted */ cipherParam.iv = cryptMsg->text; offset = state->suiteInfo->fixedIvLength; ret = SAL_CRYPT_Decrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, &cryptMsg->text[offset], cryptMsg->textLen - offset - macLen, data, &plaintextLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15915, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } /* Check padding and padding length */ uint8_t paddingLen = data[plaintextLen - 1]; ret = RecConnCbcDecCheckPaddingEtM(ctx, cryptMsg, data, plaintextLen, offset); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17247, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnCbcDecCheckPaddingEtM fail", 0, 0, 0, 0); return ret; } *dataLen = plaintextLen - paddingLen - CBC_PADDING_LEN_TAG_SIZE; return HITLS_SUCCESS; } static int32_t CbcDecrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { uint8_t *decryptData = data; uint32_t decryptDataLen = *dataLen; int32_t ret; if (ctx->negotiatedInfo.isEncryptThenMacRead) { ret = RecConnCbcDecryptByEncryptThenMac(ctx, state, cryptMsg, decryptData, &decryptDataLen); } else { ret = RecConnCbcDecryptByMacThenEncrypt(ctx, state, cryptMsg, decryptData, &decryptDataLen); } if (ret != HITLS_SUCCESS) { return ret; } *dataLen = decryptDataLen; return HITLS_SUCCESS; } static int32_t RecConnCopyIV(TLS_Ctx *ctx, const RecConnState *state, uint8_t *cipherText, uint32_t cipherTextLen) { if (!state->suiteInfo->isExportIV) { SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), state->suiteInfo->iv, state->suiteInfo->fixedIvLength); } /* The IV set by the user can only be used once */ state->suiteInfo->isExportIV = 0; if (memcpy_s(cipherText, cipherTextLen, state->suiteInfo->iv, state->suiteInfo->fixedIvLength) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15847, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: copy iv fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; } /* Data that needs to be encrypted (do not fill MAC) */ static int32_t GenerateCbcPlainTextBeforeMac(const RecConnState *state, const REC_TextInput *plainMsg, uint32_t cipherTextLen, uint8_t *plainText, uint32_t *textLen) { /* fill content */ if (memcpy_s(plainText, cipherTextLen, plainMsg->text, plainMsg->textLen) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15392, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: memcpy plainMsg fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } uint32_t plainTextLen = plainMsg->textLen; /* fill padding and padding length */ uint8_t paddingLen = RecConnGetCbcPaddingLen(state->suiteInfo->blockLength, plainTextLen); uint32_t count = paddingLen + CBC_PADDING_LEN_TAG_SIZE; if (memset_s(&plainText[plainTextLen], cipherTextLen - plainTextLen, paddingLen, count) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_ENCRYPT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15904, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: memset padding fail.", 0, 0, 0, 0); return HITLS_REC_ERR_ENCRYPT; } plainTextLen += count; *textLen = plainTextLen; return HITLS_SUCCESS; } static int32_t PreparePlainText(const RecConnState *state, const REC_TextInput *plainMsg, uint32_t cipherTextLen, uint8_t **plainText, uint32_t *plainTextLen) { *plainText = BSL_SAL_Calloc(1u, cipherTextLen); if (*plainText == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15927, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: out of memory.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } int32_t ret = GenerateCbcPlainTextBeforeMac(state, plainMsg, cipherTextLen, *plainText, plainTextLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(*plainText); } return ret; } /* Data that needs to be encrypted (after filling the mac) */ static int32_t GenerateCbcPlainTextAfterMac(HITLS_Lib_Ctx *libCtx, const char *attrName, const RecConnState *state, const REC_TextInput *plainMsg, uint32_t cipherTextLen, uint8_t *plainText, uint32_t *textLen) { /* Fill content */ if (memcpy_s(plainText, cipherTextLen, plainMsg->text, plainMsg->textLen) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15898, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: memcpy plainMsg fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } uint32_t plainTextLen = plainMsg->textLen; /* Fill MAC */ uint32_t macLen = state->suiteInfo->macLen; REC_TextInput input = {0}; RecConnInitGenerateMacInput(plainMsg, plainMsg->text, plainMsg->textLen, &input); int32_t ret = RecConnGenerateMac(libCtx, attrName, state->suiteInfo, &input, &plainText[plainTextLen], &macLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17248, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnGenerateMac fail.", 0, 0, 0, 0); return ret; } plainTextLen += macLen; /* Fill padding and padding length */ uint8_t paddingLen = RecConnGetCbcPaddingLen(state->suiteInfo->blockLength, plainTextLen); uint32_t count = paddingLen + CBC_PADDING_LEN_TAG_SIZE; if (memset_s(&plainText[plainTextLen], cipherTextLen - plainTextLen, paddingLen, count) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_ENCRYPT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15393, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: memset padding fail.", 0, 0, 0, 0); return HITLS_REC_ERR_ENCRYPT; } plainTextLen += count; *textLen = plainTextLen; return HITLS_SUCCESS; } static int32_t RecConnCbcEncryptThenMac(TLS_Ctx *ctx, const RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { uint32_t offset = 0; uint8_t *plainText = NULL; uint32_t plainTextLen = 0; int32_t ret = PreparePlainText(state, plainMsg, cipherTextLen, &plainText, &plainTextLen); if (ret != HITLS_SUCCESS) { return ret; } ret = RecConnCopyIV(ctx, state, cipherText, cipherTextLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(plainText); return ret; } offset += state->suiteInfo->fixedIvLength; uint32_t macLen = state->suiteInfo->macLen; uint32_t encLen = cipherTextLen - offset - macLen; HITLS_CipherParameters cipherParam = {0}; RecConnInitCipherParam(&cipherParam, state); ret = SAL_CRYPT_Encrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, plainText, plainTextLen, &cipherText[offset], &encLen); BSL_SAL_FREE(plainText); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15848, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CBC encrypt record error.", 0, 0, 0, 0); return ret; } if (encLen != (cipherTextLen - offset - macLen)) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_ENCRYPT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15903, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encrypt record (length) error.", 0, 0, 0, 0); return HITLS_REC_ERR_ENCRYPT; } /* fill MAC */ REC_TextInput input = {0}; RecConnInitGenerateMacInput(plainMsg, cipherText, cipherTextLen - macLen, &input); return RecConnGenerateMac(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), state->suiteInfo, &input, &cipherText[offset + encLen], &macLen); } int32_t RecConnCbcMacThenEncrypt(TLS_Ctx *ctx, const RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { uint32_t plainTextLen = 0; uint8_t *plainText = BSL_SAL_Calloc(1u, cipherTextLen); if (plainText == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15390, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: out of memory.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } int32_t ret = GenerateCbcPlainTextAfterMac(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), state, plainMsg, cipherTextLen, plainText, &plainTextLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(plainText); return ret; } uint32_t offset = 0; ret = RecConnCopyIV(ctx, state, cipherText, cipherTextLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(plainText); return ret; } offset += state->suiteInfo->fixedIvLength; uint32_t encLen = cipherTextLen - offset; HITLS_CipherParameters cipherParam = {0}; RecConnInitCipherParam(&cipherParam, state); ret = SAL_CRYPT_Encrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, plainText, plainTextLen, &cipherText[offset], &encLen); BSL_SAL_FREE(plainText); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15391, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CBC encrypt record error.", 0, 0, 0, 0); return ret; } if (encLen != (cipherTextLen - offset)) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_ENCRYPT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15922, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encrypt record (length) error.", 0, 0, 0, 0); return HITLS_REC_ERR_ENCRYPT; } return HITLS_SUCCESS; } static int32_t CbcEncrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { if (plainMsg->isEncryptThenMac) { return RecConnCbcEncryptThenMac(ctx, state, plainMsg, cipherText, cipherTextLen); } return RecConnCbcMacThenEncrypt(ctx, state, plainMsg, cipherText, cipherTextLen); } const RecCryptoFunc *RecGetCbcCryptoFuncs(DecryptPostProcess decryptPostProcess, EncryptPreProcess encryptPreProcess) { static RecCryptoFunc cryptoFuncCbc = { .calCiphertextLen = CbcCalCiphertextLen, .calPlantextBufLen = CbcCalPlantextBufLen, .decrypt = CbcDecrypt, .encryt = CbcEncrypt, }; cryptoFuncCbc.decryptPostProcess = decryptPostProcess; cryptoFuncCbc.encryptPreProcess = encryptPreProcess; return &cryptoFuncCbc; } #endif
2302_82127028/openHiTLS-examples
tls/record/src/rec_crypto_cbc.c
C
unknown
24,385
/* * 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 REC_CRYPT_CBC_H #define REC_CRYPT_CBC_H #include "rec_crypto.h" const RecCryptoFunc *RecGetCbcCryptoFuncs(DecryptPostProcess decryptPostProcess, EncryptPreProcess encryptPreProcess); #endif
2302_82127028/openHiTLS-examples
tls/record/src/rec_crypto_cbc.h
C
unknown
742
/* * 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 RECORD_HEADER_H #define RECORD_HEADER_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define REC_TLS_RECORD_HEADER_LEN 5u #define REC_TLS_RECORD_LENGTH_OFFSET 3 #define REC_TLS_SN_MAX_VALUE (~((uint64_t)0)) /* TLS sequence number wrap Threshold */ #ifdef HITLS_TLS_PROTO_DTLS12 #define REC_IP_UDP_HEAD_SIZE 28 /* IP protocol header 20 + UDP header 8 */ #define REC_DTLS_RECORD_HEADER_LEN 13 #define REC_DTLS_RECORD_EPOCH_OFFSET 3 #define REC_DTLS_RECORD_LENGTH_OFFSET 11 /* DTLS sequence number cannot be greater than this value. Otherwise, it will wrapped */ #define REC_DTLS_SN_MAX_VALUE 0xFFFFFFFFFFFFllu #define REC_SEQ_GET(n) ((n) & 0x0000FFFFFFFFFFFFull) #define REC_EPOCH_GET(n) ((uint16_t)((n) >> 48)) #define REC_EPOCHSEQ_CAL(epoch, seq) (((uint64_t)(epoch) << 48) | (seq)) /* Epoch cannot be greater than this value. Otherwise, it will wrapped */ #define REC_EPOCH_MAX_VALUE 0xFFFFu #endif typedef struct { uint8_t type; uint8_t reverse[3]; /* Reserved, 4-byte aligned */ uint16_t version; uint16_t bodyLen; /* body length */ #ifdef HITLS_TLS_PROTO_DTLS12 uint64_t epochSeq; /* only for dtls */ #endif } RecHdr; #ifdef __cplusplus } #endif #endif /* RECORD_HEADER_H */
2302_82127028/openHiTLS-examples
tls/record/src/rec_header.h
C
unknown
1,825
/* * 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 "securec.h" #include "bsl_sal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hitls_config.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "rec_alert.h" #ifdef HITLS_TLS_PROTO_TLS13 #include "hs_common.h" #endif #include "tls_config.h" #include "record.h" #ifdef HITLS_TLS_FEATURE_INDICATOR #include "indicator.h" #endif #include "hs_ctx.h" #include "hs.h" #include "rec_crypto.h" #include "bsl_list.h" RecConnState *GetReadConnState(const TLS_Ctx *ctx) { /** Obtains the record structure. */ RecCtx *recordCtx = (RecCtx *)ctx->recCtx; return recordCtx->readStates.currentState; } static bool IsNeedtoRead(const TLS_Ctx *ctx, const RecBuf *inBuf) { (void)ctx; uint32_t headLen = REC_TLS_RECORD_HEADER_LEN; #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { headLen = REC_DTLS_RECORD_HEADER_LEN; } #endif uint32_t lengthOffset = headLen - sizeof(uint16_t); uint32_t remain = inBuf->end - inBuf->start; if (remain < headLen) { return true; } uint8_t *recordHeader = &inBuf->buf[inBuf->start]; uint32_t recordLen = BSL_ByteToUint16(&recordHeader[lengthOffset]); if (remain < headLen + recordLen) { return true; } return false; } bool REC_HaveReadSuiteInfo(const TLS_Ctx *ctx) { if (ctx == NULL || ctx->recCtx == NULL || ctx->recCtx->readStates.currentState == NULL) { return false; } return ctx->recCtx->readStates.currentState->suiteInfo != NULL; } static REC_Type RecCastUintToRecType(TLS_Ctx *ctx, uint8_t value) { (void)ctx; REC_Type type; /* Convert to the record type */ switch (value) { case 20u: type = REC_TYPE_CHANGE_CIPHER_SPEC; break; case 21u: type = REC_TYPE_ALERT; break; case 22u: type = REC_TYPE_HANDSHAKE; break; case 23u: type = REC_TYPE_APP; break; default: type = REC_TYPE_UNKNOWN; break; } #ifdef HITLS_TLS_PROTO_TLS13 RecConnState *state = GetReadConnState(ctx); if (HS_GetVersion(ctx) == HITLS_VERSION_TLS13 && state->suiteInfo != NULL) { if (type != REC_TYPE_APP && type != REC_TYPE_ALERT && (type != REC_TYPE_CHANGE_CIPHER_SPEC || ctx->hsCtx == NULL)) { type = REC_TYPE_UNKNOWN; } } #endif /* HITLS_TLS_PROTO_TLS13 */ return type; } #define REC_GetMaxReadSize(ctx) REC_MAX_PLAIN_LENGTH static int32_t ProcessDecryptedRecord(TLS_Ctx *ctx, uint32_t dataLen, const REC_TextInput *encryptedMsg) { /* The TLSPlaintext.length MUST NOT exceed 2^14. An endpoint that receives a record that exceeds this length MUST terminate the connection with a record_overflow alert */ if (dataLen > REC_GetMaxReadSize(ctx)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16165, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "TLSPlaintext.length exceeds 2^14", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_RECORD_OVERFLOW); } if (encryptedMsg->type != REC_TYPE_APP && dataLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16166, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid length", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } if (!IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && ctx->negotiatedInfo.version != HITLS_VERSION_TLS13 && ctx->method.isRecvCCS(ctx) && encryptedMsg->type != REC_TYPE_HANDSHAKE) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_REC_ERR_DATA_BETWEEN_CCS_AND_FINISHED; } return HITLS_SUCCESS; } static int32_t EmptyRecordProcess(TLS_Ctx *ctx, uint8_t type) { if (REC_HaveReadSuiteInfo(ctx)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17255, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encryptedMsg->textLen is 0", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } if (type == REC_TYPE_ALERT || type == REC_TYPE_APP) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17256, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "type err", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } ctx->recCtx->emptyRecordCnt += 1; if (ctx->recCtx->emptyRecordCnt > ctx->config.tlsConfig.emptyRecordsNum) { BSL_LOG_BINLOG_FIXLEN( BINLOG_ID16187, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get too many empty records", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } else { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } } static int32_t RecordDecrypt(TLS_Ctx *ctx, RecBuf *decryptBuf, REC_TextInput *encryptedMsg) { if (encryptedMsg->textLen == 0) { return EmptyRecordProcess(ctx, encryptedMsg->type); } else { ctx->recCtx->emptyRecordCnt = 0; } RecConnState *state = GetReadConnState(ctx); const RecCryptoFunc *funcs = RecGetCryptoFuncs(state->suiteInfo); uint32_t offset = 0; int32_t ret = HITLS_SUCCESS; uint32_t minBufLen = 0; ret = funcs->calPlantextBufLen(ctx, state->suiteInfo, encryptedMsg->textLen, &offset, &minBufLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16266, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Invalid record length %u", encryptedMsg->textLen, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } if ((minBufLen > decryptBuf->bufSize || ctx->peekFlag != 0) && minBufLen != 0) { decryptBuf->buf = BSL_SAL_Calloc(minBufLen, sizeof(uint8_t)); if (decryptBuf->buf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17257, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } decryptBuf->bufSize = minBufLen; decryptBuf->isHoldBuffer = true; } decryptBuf->end = decryptBuf->bufSize; /* The decrypted record body is in data */ ret = RecConnDecrypt(ctx, state, encryptedMsg, decryptBuf->buf, &decryptBuf->end); if (ret != HITLS_SUCCESS) { goto ERR; } if (!IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { ret = funcs->decryptPostProcess(ctx, state->suiteInfo, encryptedMsg, decryptBuf->buf, &decryptBuf->end); if (ret != HITLS_SUCCESS) { goto ERR; } RecConnSetSeqNum(state, RecConnGetSeqNum(state) + 1); } ret = ProcessDecryptedRecord(ctx, decryptBuf->end, encryptedMsg); if (ret != HITLS_SUCCESS) { goto ERR; } return HITLS_SUCCESS; ERR: if (decryptBuf->isHoldBuffer) { BSL_SAL_FREE(decryptBuf->buf); } return ret; } static int32_t RecordUnexpectedMsg(TLS_Ctx *ctx, RecBuf *decryptBuf, REC_Type recordType) { int32_t ret = HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; ctx->recCtx->unexpectedMsgType = recordType; switch (recordType) { case REC_TYPE_HANDSHAKE: ret = RecBufListAddBuffer(ctx->recCtx->hsRecList, decryptBuf); break; case REC_TYPE_APP: ret = RecBufListAddBuffer(ctx->recCtx->appRecList, decryptBuf); break; case REC_TYPE_CHANGE_CIPHER_SPEC: case REC_TYPE_ALERT: default: ret = ctx->method.unexpectedMsgProcessCb(ctx, recordType, decryptBuf->buf, decryptBuf->end, false); if (decryptBuf->isHoldBuffer) { BSL_SAL_FREE(decryptBuf->buf); } return ret; } if (ret != HITLS_SUCCESS) { if (decryptBuf->isHoldBuffer) { BSL_SAL_FREE(decryptBuf->buf); } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17258, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "process recordType fail", 0, 0, 0, 0); return ret; } ret = RecDerefBufList(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17259, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecDerefBufList fail", 0, 0, 0, 0); return ret; } return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } #ifdef HITLS_TLS_PROTO_DTLS12 int32_t DtlsCheckVersionField(const TLS_Ctx *ctx, uint16_t version, uint8_t type) { /* Tolerate alerts with non-negotiated version. For example, after the server sends server hello, the client * replies with an earlier version alert */ if (ctx->negotiatedInfo.version == 0u || type == (uint8_t)REC_TYPE_ALERT) { if ((version != HITLS_VERSION_DTLS10) && (version != HITLS_VERSION_DTLS12) && (version != HITLS_VERSION_TLCP_DTLCP11)) { BSL_ERR_PUSH_ERROR(HITLS_REC_INVALID_PROTOCOL_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15436, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with illegal version(0x%x).", version, 0, 0, 0); return HITLS_REC_INVALID_PROTOCOL_VERSION; } } else { if (version != ctx->negotiatedInfo.version) { BSL_ERR_PUSH_ERROR(HITLS_REC_INVALID_PROTOCOL_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15437, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with illegal version(0x%x).", version, 0, 0, 0); return HITLS_REC_INVALID_PROTOCOL_VERSION; } } return HITLS_SUCCESS; } int32_t DtlsCheckRecordHeader(TLS_Ctx *ctx, const RecHdr *hdr) { /** Check the DTLS version, release the resource and return if the version is incorrect */ int32_t ret = DtlsCheckVersionField(ctx, hdr->version, hdr->type); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17261, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DtlsCheckVersionField fail, ret %d", ret, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); } if (RecCastUintToRecType(ctx, hdr->type) == REC_TYPE_UNKNOWN || hdr->bodyLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_RECV_UNEXPECTED_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15438, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid type or body length(0)", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } RecConnState *state = GetReadConnState(ctx); uint32_t maxLenth = (state->suiteInfo != NULL) ? REC_MAX_CIPHER_TEXT_LEN : REC_MAX_PLAIN_LENGTH; if (hdr->bodyLen > maxLenth) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_TOO_BIG_LENGTH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15439, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid length", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_RECORD_OVERFLOW); } uint16_t epoch = REC_EPOCH_GET(hdr->epochSeq); if (epoch == 0 && hdr->type == REC_TYPE_APP && BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_RECV_UNEXPECTED_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15440, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a UNEXPECTE record msg: epoch 0's app msg.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_REC_ERR_RECV_UNEXPECTED_MSG; } return HITLS_SUCCESS; } /** * @brief Read message data. * * @param uio [IN] UIO object. * @param inBuf [IN] inBuf Read the buffer. * * @retval HITLS_SUCCESS is successfully read. * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY Uncached data needs to be reread. */ static int32_t ReadDatagram(TLS_Ctx *ctx, RecBuf *inBuf) { if (inBuf->end > inBuf->start) { return HITLS_SUCCESS; } /* Attempt to read the message: The message is read of the whole message */ uint32_t recvLen = 0u; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_READING; #endif #ifdef HITLS_TLS_FEATURE_FLIGHT int32_t ret = BSL_UIO_Read(ctx->rUio, &(inBuf->buf[0]), inBuf->bufSize, &recvLen); #else int32_t ret = BSL_UIO_Read(ctx->uio, &(inBuf->buf[0]), inBuf->bufSize, &recvLen); #endif if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_IO_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15441, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record read: uio err.%d", ret, 0, 0, 0); return HITLS_REC_ERR_IO_EXCEPTION; } #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif if (recvLen == 0) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } inBuf->start = 0; // successfully read inBuf->end = recvLen; return HITLS_SUCCESS; } static int32_t DtlsGetRecordHeader(const uint8_t *msg, uint32_t len, RecHdr *hdr) { if (len < REC_DTLS_RECORD_HEADER_LEN) { BSL_ERR_PUSH_ERROR(HITLS_REC_DECODE_ERROR); BSL_LOG_BINLOG_FIXLEN( BINLOG_ID15442, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record:dtls packet's length err.", 0, 0, 0, 0); return HITLS_REC_DECODE_ERROR; } /* Parse the record header */ hdr->type = msg[0]; hdr->version = BSL_ByteToUint16(&msg[1]); hdr->bodyLen = BSL_ByteToUint16( &msg[REC_DTLS_RECORD_LENGTH_OFFSET]); // The 11th to 12th bytes of DTLS are the message length. hdr->epochSeq = BSL_ByteToUint64(&msg[REC_DTLS_RECORD_EPOCH_OFFSET]); return HITLS_SUCCESS; } /** * @brief Attempt to read a dtls record message. * * @param ctx [IN] TLS context * @param recordBody [OUT] record body * @param hdr [OUT] record head * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error */ static int32_t TryReadOneDtlsRecord(TLS_Ctx *ctx, uint8_t **recordBody, RecHdr *hdr) { int32_t ret; /** Obtain the record structure information */ RecCtx *recordCtx = (RecCtx *)ctx->recCtx; if (IsNeedtoRead(ctx, recordCtx->inBuf)) { ret = RecDerefBufList(ctx); if (ret != HITLS_SUCCESS) { return ret; } } /** Read the datagram message: The message may contain multiple records */ ret = ReadDatagram(ctx, recordCtx->inBuf); if (ret != HITLS_SUCCESS) { return ret; } uint8_t *msg = &recordCtx->inBuf->buf[recordCtx->inBuf->start]; uint32_t len = recordCtx->inBuf->end - recordCtx->inBuf->start; ret = DtlsGetRecordHeader(msg, len, hdr); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17262, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DtlsGetRecordHeader fail, ret %d", ret, 0, 0, 0); RecBufClean(recordCtx->inBuf); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(0, 0, RECORD_HEADER, msg, REC_DTLS_RECORD_HEADER_LEN, ctx, ctx->config.tlsConfig.msgArg); #endif /* Check whether the record length is greater than the buffer size */ if ((REC_DTLS_RECORD_HEADER_LEN + (uint32_t)hdr->bodyLen) > len) { RecBufClean(recordCtx->inBuf); BSL_ERR_PUSH_ERROR(HITLS_REC_DECODE_ERROR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15443, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record:dtls packet's length err.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_RECORD_OVERFLOW); } /** Release the read record */ recordCtx->inBuf->start += REC_DTLS_RECORD_HEADER_LEN + hdr->bodyLen; /** Update the read content */ *recordBody = msg + REC_DTLS_RECORD_HEADER_LEN; return HITLS_SUCCESS; } static inline void GenerateCryptMsg(const TLS_Ctx *ctx, const RecHdr *hdr, const uint8_t *recordBody, REC_TextInput *cryptMsg) { cryptMsg->negotiatedVersion = ctx->negotiatedInfo.version; #ifdef HITLS_TLS_FEATURE_ETM cryptMsg->isEncryptThenMac = ctx->negotiatedInfo.isEncryptThenMac; #endif cryptMsg->type = hdr->type; cryptMsg->version = hdr->version; cryptMsg->text = recordBody; cryptMsg->textLen = hdr->bodyLen; BSL_Uint64ToByte(hdr->epochSeq, cryptMsg->seq); } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) /** * @brief Check whether there are unprocessed handshake messages in the cache. * * @param unprocessedHsMsg [IN] Unprocessed handshake message handle * @param curEpoch [IN] Current epoch * * @retval true: cached * @retval false No cache */ static bool IsExistUnprocessedHsMsg(RecCtx *recCtx) { uint16_t curEpoch = recCtx->readEpoch; UnprocessedHsMsg *unprocessedHsMsg = &recCtx->unprocessedHsMsg; /* Check whether there are cached handshake messages. */ if (unprocessedHsMsg->recordBody == NULL) { return false; } uint16_t epoch = REC_EPOCH_GET(unprocessedHsMsg->hdr.epochSeq); if (curEpoch == epoch) { /* The handshake message of the current epoch needs to be processed */ return true; } if (curEpoch > epoch) { /* Expired messages need to be cleaned up */ (void)memset_s(&unprocessedHsMsg->hdr, sizeof(unprocessedHsMsg->hdr), 0, sizeof(unprocessedHsMsg->hdr)); BSL_SAL_FREE(unprocessedHsMsg->recordBody); } return false; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ static bool IsExistUnprocessedAppMsg(RecCtx *recCtx) { UnprocessedAppMsg *unprocessedAppMsgList = &recCtx->unprocessedAppMsgList; /* Check whether there are cached app messages. */ if (unprocessedAppMsgList->count == 0) { return false; } ListHead *node = NULL; ListHead *tmpNode = NULL; UnprocessedAppMsg *cur = NULL; uint16_t curEpoch = recCtx->readEpoch; LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(unprocessedAppMsgList->head)) { cur = LIST_ENTRY(node, UnprocessedAppMsg, head); uint16_t epoch = REC_EPOCH_GET(cur->hdr.epochSeq); if (curEpoch == epoch) { /* The app message of the current epoch needs to be processed */ return true; } } return false; } int32_t RecordBufferUnprocessedMsg(RecCtx *recordCtx, RecHdr *hdr, uint8_t *recordBody) { if (hdr->type == REC_TYPE_HANDSHAKE) { #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) CacheNextEpochHsMsg(&recordCtx->unprocessedHsMsg, hdr, recordBody); #endif } else { int32_t ret = UnprocessedAppMsgListAppend(&recordCtx->unprocessedAppMsgList, hdr, recordBody); if (ret != HITLS_SUCCESS) { return ret; } } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17263, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "recv normal disorder message", 0, 0, 0, 0); return HITLS_REC_NORMAL_RECV_DISORDER_MSG; } static int32_t DtlsRecordHeaderProcess(TLS_Ctx *ctx, uint8_t *recordBody, RecHdr *hdr) { int32_t ret = HITLS_SUCCESS; RecCtx *recordCtx = (RecCtx *)ctx->recCtx; ret = DtlsCheckRecordHeader(ctx, hdr); if (ret != HITLS_SUCCESS) { return ret; } uint16_t epoch = REC_EPOCH_GET(hdr->epochSeq); if (epoch != recordCtx->readEpoch) { /* Discard out-of-order messages in SCTP scenarios */ if (BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } #if defined(HITLS_BSL_UIO_UDP) /* Only the messages of the next epoch are cached */ if ((recordCtx->readEpoch + 1) == epoch) { return RecordBufferUnprocessedMsg(recordCtx, hdr, recordBody); } /* After receiving the message of the previous epoch, the system discards the message. */ return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); #endif } bool isCcsRecv = ctx->method.isRecvCCS(ctx); /* App messages arrive earlier than finished messages and need to be cached */ if (ctx->hsCtx != NULL && isCcsRecv == true && (hdr->type == REC_TYPE_APP || hdr->type == REC_TYPE_ALERT)) { return RecordBufferUnprocessedMsg(recordCtx, hdr, recordBody); } return HITLS_SUCCESS; } static uint8_t *GetUnprocessedMsg(RecCtx *recordCtx, REC_Type recordType, RecHdr *hdr) { uint8_t *recordBody = NULL; #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) if ((recordType == REC_TYPE_HANDSHAKE) && IsExistUnprocessedHsMsg(recordCtx)) { (void)memcpy_s(hdr, sizeof(RecHdr), &recordCtx->unprocessedHsMsg.hdr, sizeof(RecHdr)); recordBody = recordCtx->unprocessedHsMsg.recordBody; recordCtx->unprocessedHsMsg.recordBody = NULL; } #endif uint16_t curEpoch = recordCtx->readEpoch; if ((recordType == REC_TYPE_APP) && IsExistUnprocessedAppMsg(recordCtx)) { UnprocessedAppMsg *appMsg = UnprocessedAppMsgGet(&recordCtx->unprocessedAppMsgList, curEpoch); if (appMsg == NULL) { return NULL; } (void)memcpy_s(hdr, sizeof(RecHdr), &appMsg->hdr, sizeof(RecHdr)); recordBody = appMsg->recordBody; appMsg->recordBody = NULL; UnprocessedAppMsgFree(appMsg); } return recordBody; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) static int32_t AntiReplay(TLS_Ctx *ctx, RecHdr *hdr) { /* In non-UDP scenarios, anti-replay check is not required */ if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return HITLS_SUCCESS; } RecConnState *state = GetReadConnState(ctx); uint16_t epoch = REC_EPOCH_GET(hdr->epochSeq); uint64_t secquence = REC_SEQ_GET(hdr->epochSeq); if (RecAntiReplayCheck(&state->window, secquence) == true) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } if (ctx->isDtlsListen && epoch != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17264, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "epoch err", 0, 0, 0, 0); return HITLS_REC_ERR_RECV_UNEXPECTED_MSG; } return HITLS_SUCCESS; } #endif static int32_t DtlsTryReadAndCheckRecordMessage(TLS_Ctx *ctx, uint8_t **recordBody, RecHdr *hdr) { int32_t ret = HITLS_SUCCESS; /* Read the new record message */ ret = TryReadOneDtlsRecord(ctx, recordBody, hdr); if (ret != HITLS_SUCCESS) { return ret; } /* Check the record message header. If the message header is not the expected message, cache the message */ return DtlsRecordHeaderProcess(ctx, *recordBody, hdr); } static int32_t DtlsGetRecord(TLS_Ctx *ctx, REC_Type recordType, RecHdr *hdr, uint8_t **recordBody, uint8_t **cachRecord) { RecCtx *recordCtx = (RecCtx *)ctx->recCtx; int32_t ret = RecIoBufInit(ctx, recordCtx, true); if (ret != HITLS_SUCCESS) { return ret; } /* Check if there are cached messages that need to be processed */ *recordBody = GetUnprocessedMsg(recordCtx, recordType, hdr); *cachRecord = *recordBody; /* There are no cached messages to process */ if (*recordBody == NULL) { ret = DtlsTryReadAndCheckRecordMessage(ctx, recordBody, hdr); if (ret != HITLS_SUCCESS) { return ret; } } #if defined(HITLS_BSL_UIO_UDP) ret = AntiReplay(ctx, hdr); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(*cachRecord); } #endif return ret; } static int32_t DtlsProcessBufList(TLS_Ctx *ctx, REC_Type recordType, RecBufList *bufList, RecBuf *decryptBuf) { (void)recordType; int32_t ret = RecBufListAddBuffer(bufList, decryptBuf); if (ret != HITLS_SUCCESS) { if (decryptBuf->isHoldBuffer) { BSL_SAL_FREE(decryptBuf->buf); } return ret; } ret = RecDerefBufList(ctx); if (ret != HITLS_SUCCESS) { return ret; } return HITLS_SUCCESS; } /** * @brief Read a record in the DTLS protocol. * * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [OUT] Read data * @param len [OUT] Length of the data to be read * @param bufSize [IN] buffer length * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG Unexpected message received * @retval HITLS_REC_NORMAL_RECV_DISORDER_MSG Receives out-of-order messages. * */ int32_t DtlsRecordRead(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *len, uint32_t bufSize) { RecBufList *bufList = (recordType == REC_TYPE_HANDSHAKE) ? ctx->recCtx->hsRecList : ctx->recCtx->appRecList; if (!RecBufListEmpty(bufList)) { return RecBufListGetBuffer(bufList, data, bufSize, len, (ctx->peekFlag != 0 && (recordType == REC_TYPE_APP))); } RecHdr hdr = {0}; /* Pointer for storing buffered messages, which is used during release */ uint8_t *recordBody = NULL; uint8_t *cachRecord = NULL; int32_t ret = DtlsGetRecord(ctx, recordType, &hdr, &recordBody, &cachRecord); if (ret != HITLS_SUCCESS) { return ret; } /* Construct parameters before decryption */ REC_TextInput cryptMsg = {0}; GenerateCryptMsg(ctx, &hdr, recordBody, &cryptMsg); RecBuf decryptBuf = { .buf = data, .bufSize = bufSize }; ret = RecordDecrypt(ctx, &decryptBuf, &cryptMsg); BSL_SAL_FREE(cachRecord); if (ret != HITLS_SUCCESS) { return ret; } #if defined(HITLS_BSL_UIO_UDP) /* In UDP scenarios, update the sliding window flag */ if (BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { RecAntiReplayUpdate(&GetReadConnState(ctx)->window, REC_SEQ_GET(hdr.epochSeq)); } #endif RecClearAlertCount(ctx, cryptMsg.type); #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_RELEASE_BUFFERS) != 0 && (recordType == REC_TYPE_APP)) { RecTryFreeRecBuf(ctx, false); } #endif /* An unexpected packet is received */ // decryptBuf.isHoldBuffer == false if (recordType != cryptMsg.type) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16513, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "expect type %d, receive type %d", recordType, cryptMsg.type, 0, 0); return RecordUnexpectedMsg(ctx, &decryptBuf, cryptMsg.type); } if (decryptBuf.buf == data) { /* Update the read length */ *len = decryptBuf.end; return HITLS_SUCCESS; } ret = DtlsProcessBufList(ctx, recordType, bufList, &decryptBuf); if (ret != HITLS_SUCCESS) { return ret; } return RecBufListGetBuffer(bufList, data, bufSize, len, (ctx->peekFlag != 0 && (recordType == REC_TYPE_APP))); } #endif /* HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS static int32_t VersionProcess(TLS_Ctx *ctx, uint16_t version, uint8_t type) { if ((ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) && (version != HITLS_VERSION_TLS12)) { /* If the negotiated version is tls1.3, the record version must be tls1.2 */ BSL_ERR_PUSH_ERROR(HITLS_REC_INVALID_PROTOCOL_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15448, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with illegal version(0x%x).", version, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_REC_INVALID_PROTOCOL_VERSION; } else if ((ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) && (version != ctx->negotiatedInfo.version)) { BSL_ERR_PUSH_ERROR(HITLS_REC_INVALID_PROTOCOL_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15449, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with illegal version(0x%x).", version, 0, 0, 0); if (((version & 0xff00u) == (ctx->negotiatedInfo.version & 0xff00u)) && type == REC_TYPE_ALERT) { return HITLS_SUCCESS; } ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); return HITLS_REC_INVALID_PROTOCOL_VERSION; } return HITLS_SUCCESS; } int32_t TlsCheckVersionField(TLS_Ctx *ctx, uint16_t version, uint8_t type) { if (ctx->negotiatedInfo.version == 0u) { #ifdef HITLS_TLS_PROTO_TLCP11 if (((version >> 8u) != HITLS_VERSION_TLS_MAJOR) && (version != HITLS_VERSION_TLCP_DTLCP11)) { #else if ((version >> 8u) != HITLS_VERSION_TLS_MAJOR) { #endif BSL_ERR_PUSH_ERROR(HITLS_REC_INVALID_PROTOCOL_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16132, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with illegal version(0x%x).", version, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); return HITLS_REC_INVALID_PROTOCOL_VERSION; } } else { return VersionProcess(ctx, version, type); } return HITLS_SUCCESS; } int32_t TlsCheckRecordHeader(TLS_Ctx *ctx, const RecHdr *recordHdr) { if (RecCastUintToRecType(ctx, recordHdr->type) == REC_TYPE_UNKNOWN) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15450, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid type", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } int32_t ret = TlsCheckVersionField(ctx, recordHdr->version, recordHdr->type); if (ret != HITLS_SUCCESS) { return HITLS_REC_INVALID_PROTOCOL_VERSION; } if (recordHdr->bodyLen + REC_TLS_RECORD_HEADER_LEN > RecGetInitBufferSize(ctx, true)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15451, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid length", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_RECORD_OVERFLOW); } if (recordHdr->bodyLen + REC_TLS_RECORD_HEADER_LEN > ctx->recCtx->inBuf->bufSize) { ret = RecBufResize(ctx->recCtx->inBuf, recordHdr->bodyLen + REC_TLS_RECORD_HEADER_LEN); if (ret != HITLS_SUCCESS) { return ret; } } #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13 && recordHdr->bodyLen > REC_MAX_TLS13_ENCRYPTED_LEN) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16125, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid length", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_RECORD_OVERFLOW); } #endif return HITLS_SUCCESS; } /** * @brief Read data from the uio of the TLS context into inBuf * * @param ctx [IN] TLS context * @param inBuf [IN] inBuf Read buffer. * @param len [IN] len The length to read, it takes the value of the record header length (5 * bytes) or the entire record length (header + body) * * @retval HITLS_SUCCESS Read successfully * @retval HITLS_REC_ERR_IO_EXCEPTION IO error * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY No cached data needs to be re-read * @retval HITLS_REC_NORMAL_IO_EOF */ int32_t StreamRead(TLS_Ctx *ctx, RecBuf *inBuf, uint32_t len) { uint32_t bytesInRbuf = inBuf->end - inBuf->start; bool readAheadFlag = (ctx->config.tlsConfig.readAhead != 0); if (bytesInRbuf == 0) { inBuf->start = 0; inBuf->end = 0; } // there are enough data in the read buffer if (bytesInRbuf >= len) { return HITLS_SUCCESS; } // right-side available space is less then required len, move data leftwards if (inBuf->bufSize - inBuf->end < len) { for (uint32_t i = 0; i < bytesInRbuf; i++) { inBuf->buf[i] = inBuf->buf[inBuf->start + i]; } inBuf->start = 0; inBuf->end = bytesInRbuf; } uint32_t upperBnd = (!readAheadFlag && inBuf->bufSize >= inBuf->start + len - inBuf->end) ? inBuf->start + len : inBuf->bufSize; do { uint32_t recvLen = 0u; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_READING; #endif #ifdef HITLS_TLS_FEATURE_FLIGHT int32_t ret = BSL_UIO_Read(ctx->rUio, &(inBuf->buf[inBuf->end]), upperBnd - inBuf->end, &recvLen); #else int32_t ret = BSL_UIO_Read(ctx->uio, &(inBuf->buf[inBuf->end]), upperBnd - inBuf->end, &recvLen); #endif if (ret != BSL_SUCCESS) { if (ret == BSL_UIO_IO_EOF) { return HITLS_REC_NORMAL_IO_EOF; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15452, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Fail to call BSL_UIO_Read in StreamRead: [%d]", ret, 0, 0, 0); return HITLS_REC_ERR_IO_EXCEPTION; } #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif if (recvLen == 0) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } inBuf->end += recvLen; } while (inBuf->end - inBuf->start < len); return HITLS_SUCCESS; } /** * @brief Attempt to read a tls record message. * * @param ctx [IN] TLS context * @param recordBody [OUT] record body * @param hdr [OUT] record head * * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error */ int32_t TryReadOneTlsRecord(TLS_Ctx *ctx, uint8_t **recordBody, RecHdr *recHeader) { /* Buffer for reading data */ RecBuf *inBuf = ctx->recCtx->inBuf; if (IsNeedtoRead(ctx, inBuf)) { RecDerefBufList(ctx); } // read record header int32_t ret = StreamRead(ctx, inBuf, REC_TLS_RECORD_HEADER_LEN); if (ret != HITLS_SUCCESS) { return ret; } const uint8_t *recordHeader = &inBuf->buf[inBuf->start]; recHeader->type = recordHeader[0]; recHeader->version = BSL_ByteToUint16(recordHeader + sizeof(uint8_t)); recHeader->bodyLen = BSL_ByteToUint16(recordHeader + REC_TLS_RECORD_LENGTH_OFFSET); ret = TlsCheckRecordHeader(ctx, recHeader); if (ret != HITLS_SUCCESS) { #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(0, 0, RECORD_HEADER, recordHeader, REC_TLS_RECORD_HEADER_LEN, ctx, ctx->config.tlsConfig.msgArg); #endif return ret; } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(0, recHeader->version, RECORD_HEADER, recordHeader, REC_TLS_RECORD_HEADER_LEN, ctx, ctx->config.tlsConfig.msgArg); #endif uint32_t recHeaderAndBodyLen = REC_TLS_RECORD_HEADER_LEN + (uint32_t)recHeader->bodyLen; // read a whole record: head + body ret = StreamRead(ctx, inBuf, recHeaderAndBodyLen); if (ret != HITLS_SUCCESS) { return ret; } *recordBody = &inBuf->buf[inBuf->start] + REC_TLS_RECORD_HEADER_LEN; inBuf->start += recHeaderAndBodyLen; return HITLS_SUCCESS; } int32_t RecordDecryptPrepare(TLS_Ctx *ctx, uint16_t version, REC_Type recordType, REC_TextInput *cryptMsg) { (void)recordType; (void)version; RecConnState *state = GetReadConnState(ctx); if (state->isWrapped == true) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_SN_WRAPPING); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15454, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record read: sequence number wrap.", 0, 0, 0, 0); return HITLS_REC_ERR_SN_WRAPPING; } if (state->seq == REC_TLS_SN_MAX_VALUE) { state->isWrapped = true; } if (ctx->peekFlag != 0 && recordType != REC_TYPE_APP) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16170, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Peek mode applies only if record type is application.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } RecHdr recordHeader = { 0 }; uint8_t *recordBody = NULL; // read header and body from ctx int32_t ret = TryReadOneTlsRecord(ctx, &recordBody, &recordHeader); if (ret != HITLS_SUCCESS) { return ret; } uint32_t recordBodyLen = (uint32_t)recordHeader.bodyLen; #ifdef HITLS_TLS_PROTO_TLS13 if (HS_GetVersion(ctx) == HITLS_VERSION_TLS13) { if ((recordHeader.type == REC_TYPE_CHANGE_CIPHER_SPEC || recordHeader.type == REC_TYPE_ALERT) && recordBodyLen != 0) { ctx->recCtx->unexpectedMsgType = recordHeader.type; /* In the TLS1.3 scenario, process unencrypted CCS and Alert messages received */ return ctx->method.unexpectedMsgProcessCb(ctx, recordHeader.type, recordBody, recordBodyLen, true); } } #endif cryptMsg->negotiatedVersion = ctx->negotiatedInfo.version; #ifdef HITLS_TLS_FEATURE_ETM cryptMsg->isEncryptThenMac = ctx->negotiatedInfo.isEncryptThenMac; #endif cryptMsg->type = recordHeader.type; cryptMsg->version = recordHeader.version; cryptMsg->text = recordBody; cryptMsg->textLen = recordBodyLen; BSL_Uint64ToByte(state->seq, cryptMsg->seq); return HITLS_SUCCESS; } /** * @brief Read a record in the TLS protocol. * @attention: Handle record and handle transporting state to receive unexpected record type messages * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [OUT] Read data * @param readLen [OUT] Length of the read data * @param num [IN] The read buffer has num bytes * * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY Need to re-read * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_ERR_SN_WRAPPING The sequence number is rewound. * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG Unexpected message received. * */ int32_t TlsRecordRead(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num) { RecBufList *bufList = (recordType == REC_TYPE_HANDSHAKE) ? ctx->recCtx->hsRecList : ctx->recCtx->appRecList; if (!RecBufListEmpty(bufList)) { return RecBufListGetBuffer(bufList, data, num, readLen, (ctx->peekFlag != 0 && (recordType == REC_TYPE_APP))); } int32_t ret = RecIoBufInit(ctx, (RecCtx *)ctx->recCtx, true); if (ret != HITLS_SUCCESS) { return ret; } REC_TextInput encryptedMsg = { 0 }; ret = RecordDecryptPrepare(ctx, ctx->negotiatedInfo.version, recordType, &encryptedMsg); if (ret != HITLS_SUCCESS) { return ret; } RecBuf decryptBuf = {0}; decryptBuf.buf = data; decryptBuf.bufSize = num; ret = RecordDecrypt(ctx, &decryptBuf, &encryptedMsg); if (ret != HITLS_SUCCESS) { return ret; } RecClearAlertCount(ctx, encryptedMsg.type); #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_RELEASE_BUFFERS) != 0 && (recordType == REC_TYPE_APP)) { RecTryFreeRecBuf(ctx, false); } #endif /* An unexpected message is received */ if (recordType != encryptedMsg.type) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17260, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "expect type %d, receive type %d", recordType, encryptedMsg.type, 0, 0); return RecordUnexpectedMsg(ctx, &decryptBuf, encryptedMsg.type); } if (decryptBuf.buf == data) { /* Update the read length */ *readLen = decryptBuf.end; return HITLS_SUCCESS; } ret = RecBufListAddBuffer(bufList, &decryptBuf); if (ret != HITLS_SUCCESS) { if (decryptBuf.isHoldBuffer) { BSL_SAL_FREE(decryptBuf.buf); } return ret; } return RecBufListGetBuffer(bufList, data, num, readLen, (ctx->peekFlag != 0 && (recordType == REC_TYPE_APP))); } #endif /* HITLS_TLS_PROTO_TLS */ uint32_t APP_GetReadPendingBytes(const TLS_Ctx *ctx) { if (ctx == NULL || ctx->recCtx == NULL || RecBufListEmpty(ctx->recCtx->appRecList)) { return 0; } RecBuf *recBuf = (RecBuf *)BSL_LIST_GET_FIRST(ctx->recCtx->appRecList); if (recBuf == NULL) { return 0; } return recBuf->end - recBuf->start; }
2302_82127028/openHiTLS-examples
tls/record/src/rec_read.c
C
unknown
40,459
/* * 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 REC_READ_H #define REC_READ_H #include <stdint.h> #include "rec.h" #include "rec_buf.h" #ifdef __cplusplus extern "C" { #endif #ifdef HITLS_TLS_PROTO_DTLS12 /** * @brief Read a record in the DTLS protocol * * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [OUT] Read data * @param len [OUT] Read data length * @param bufSize [IN] buffer length * * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG Unexpected message received * @retval HITLS_REC_NORMAL_RECV_DISORDER_MSG Receives out-of-order messages * */ int32_t DtlsRecordRead(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *len, uint32_t bufSize); #endif /** * @brief Read a record in the TLS protocol * * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [OUT] Read data * @param readLen [OUT] Length of the read data * @param num [IN] The read buffer has num bytes * * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_ERR_SN_WRAPPING Sequence number wrap * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG Unexpected message received * */ int32_t TlsRecordRead(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num); /** * @brief Read data from the UIO of the TLS context to the inBuf * * @param ctx [IN] TLS context * @param inBuf [IN] * @param len [IN] len Length to be read * * @retval HITLS_SUCCESS * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again */ int32_t StreamRead(TLS_Ctx *ctx, RecBuf *inBuf, uint32_t len); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples
tls/record/src/rec_read.h
C
unknown
2,446
/* * 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 "bsl_sal.h" #include "bsl_module_list.h" #include "tls_binlog_id.h" #include "hitls_error.h" #include "rec.h" #include "bsl_uio.h" #include "record.h" #include "hs.h" #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t REC_RetransmitListAppend(REC_Ctx *recCtx, REC_Type type, const uint8_t *msg, uint32_t len) { RecRetransmitList *retransmitList = &recCtx->retransmitList; RecRetransmitList *retransmitNode = (RecRetransmitList *)BSL_SAL_Calloc(1u, sizeof(RecRetransmitList)); if (retransmitNode == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17277, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } LIST_INIT(&(retransmitNode->head)); retransmitNode->type = type; retransmitNode->msg = BSL_SAL_Dump(msg, len); if (retransmitNode->msg == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17278, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); BSL_SAL_FREE(retransmitNode); return HITLS_MEMALLOC_FAIL; } retransmitNode->len = len; if (type == REC_TYPE_CHANGE_CIPHER_SPEC) { retransmitList->isExistCcsMsg = true; } /* insert new node */ LIST_ADD_BEFORE(&retransmitList->head, &retransmitNode->head); return HITLS_SUCCESS; } void REC_RetransmitListClean(REC_Ctx *recCtx) { ListHead *head = NULL; ListHead *tmpHead = NULL; RecRetransmitList *retransmitList = &recCtx->retransmitList; RecRetransmitList *retransmitNode = NULL; retransmitList->isExistCcsMsg = false; LIST_FOR_EACH_ITEM_SAFE(head, tmpHead, &(retransmitList->head)) { LIST_REMOVE(head); retransmitNode = LIST_ENTRY(head, RecRetransmitList, head); BSL_SAL_FREE(retransmitNode->msg); BSL_SAL_FREE(retransmitNode); } return; } static int32_t WriteSingleRetransmitNode(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { int32_t ret = REC_QueryMtu(ctx); if (ret != HITLS_SUCCESS) { return ret; } ret = REC_RecOutBufReSet(ctx); if (ret != HITLS_SUCCESS) { return ret; } uint32_t maxRecPayloadLen = 0; ret = REC_GetMaxWriteSize(ctx, &maxRecPayloadLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17360, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetMaxWriteSize fail", 0, 0, 0, 0); return ret; } if (maxRecPayloadLen >= num) { /* Send to the record layer */ ret = REC_Write(ctx, recordType, data, num); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17361, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "send handshake msg to record fail.", 0, 0, 0, 0); return ret; } } else { ret = HS_DtlsSendFragmentHsMsg(ctx, maxRecPayloadLen, data); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } int32_t REC_RetransmitListFlush(TLS_Ctx *ctx) { REC_Ctx *recCtx = ctx->recCtx; RecRetransmitList *retransmitList = &recCtx->retransmitList; RecRetransmitList *retransmitNode = NULL; if (retransmitList->isExistCcsMsg == true) { REC_ActiveOutdatedWriteState(ctx); } int32_t ret = HITLS_SUCCESS; ListHead *head = NULL; ListHead *tmpHead = NULL; LIST_FOR_EACH_ITEM_SAFE(head, tmpHead, &(retransmitList->head)) { retransmitNode = LIST_ENTRY(head, RecRetransmitList, head); /* UDP does not fail to send. Therefore, the sending failure case does not need to be considered. */ ret = WriteSingleRetransmitNode(ctx, retransmitNode->type, retransmitNode->msg, retransmitNode->len); if (ret != HITLS_SUCCESS) { return ret; } if (retransmitNode->type == REC_TYPE_CHANGE_CIPHER_SPEC) { REC_DeActiveOutdatedWriteState(ctx); } } if (ctx->config.tlsConfig.isFlightTransmitEnable) { (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_FLUSH, 0, NULL); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */
2302_82127028/openHiTLS-examples
tls/record/src/rec_retransmit.c
C
unknown
4,707
/* * 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_TLS_PROTO_DTLS12 #include "securec.h" #include "bsl_module_list.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "hitls_error.h" #include "rec.h" #include "rec_unprocessed_msg.h" #ifdef HITLS_BSL_UIO_UDP void CacheNextEpochHsMsg(UnprocessedHsMsg *unprocessedHsMsg, const RecHdr *hdr, const uint8_t *recordBody) { /* only out-of-order finished messages need to be cached */ if (hdr->type != REC_TYPE_HANDSHAKE) { return; } /* only cache one */ if (unprocessedHsMsg->recordBody != NULL) { return; } unprocessedHsMsg->recordBody = (uint8_t *)BSL_SAL_Dump(recordBody, hdr->bodyLen); if (unprocessedHsMsg->recordBody == NULL) { return; } (void)memcpy_s(&unprocessedHsMsg->hdr, sizeof(RecHdr), hdr, sizeof(RecHdr)); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15446, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN, "cache next epoch hs msg", 0, 0, 0, 0); return; } #endif /* HITLS_BSL_UIO_UDP */ UnprocessedAppMsg *UnprocessedAppMsgNew(void) { UnprocessedAppMsg *msg = (UnprocessedAppMsg *)BSL_SAL_Calloc(1, sizeof(UnprocessedAppMsg)); if (msg == NULL) { return NULL; } LIST_INIT(&msg->head); return msg; } void UnprocessedAppMsgFree(UnprocessedAppMsg *msg) { if (msg != NULL) { BSL_SAL_FREE(msg->recordBody); BSL_SAL_FREE(msg); } return; } void UnprocessedAppMsgListInit(UnprocessedAppMsg *appMsgList) { if (appMsgList == NULL) { return; } appMsgList->count = 0; appMsgList->recordBody = NULL; LIST_INIT(&appMsgList->head); return; } void UnprocessedAppMsgListDeinit(UnprocessedAppMsg *appMsgList) { ListHead *node = NULL; ListHead *tmpNode = NULL; UnprocessedAppMsg *cur = NULL; LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(appMsgList->head)) { cur = LIST_ENTRY(node, UnprocessedAppMsg, head); LIST_REMOVE(node); /* releasing nodes and deleting user data */ UnprocessedAppMsgFree(cur); } appMsgList->count = 0; return; } int32_t UnprocessedAppMsgListAppend(UnprocessedAppMsg *appMsgList, const RecHdr *hdr, const uint8_t *recordBody) { /* prevent oversize */ if (appMsgList->count >= UNPROCESSED_APP_MSG_COUNT_MAX) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } UnprocessedAppMsg *appNode = UnprocessedAppMsgNew(); if (appNode == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15805, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Buffer app record: Malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } appNode->recordBody = (uint8_t*)BSL_SAL_Dump(recordBody, hdr->bodyLen); if (appNode->recordBody == NULL) { UnprocessedAppMsgFree(appNode); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15806, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Buffer app record: Malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(&appNode->hdr, sizeof(RecHdr), hdr, sizeof(RecHdr)); LIST_ADD_BEFORE(&appMsgList->head, &appNode->head); appMsgList->count++; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15807, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN, "Buffer app record: count is %u.", appMsgList->count, 0, 0, 0); return HITLS_SUCCESS; } UnprocessedAppMsg *UnprocessedAppMsgGet(UnprocessedAppMsg *appMsgList, uint16_t curEpoch) { ListHead *next = appMsgList->head.next; if (next == &appMsgList->head) { return NULL; } ListHead *node = NULL; ListHead *tmpNode = NULL; UnprocessedAppMsg *cur = NULL; LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(appMsgList->head)) { cur = LIST_ENTRY(node, UnprocessedAppMsg, head); uint16_t epoch = REC_EPOCH_GET(cur->hdr.epochSeq); if (curEpoch == epoch) { /* remove a node and release it by the outside */ LIST_REMOVE(node); appMsgList->count--; return cur; } } return NULL; } #endif /* HITLS_TLS_PROTO_DTLS12 */
2302_82127028/openHiTLS-examples
tls/record/src/rec_unprocessed_msg.c
C
unknown
4,766
/* * 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 REC_UNPROCESSED_MSG_H #define REC_UNPROCESSED_MSG_H #include <stdint.h> #include "bsl_module_list.h" #include "rec_header.h" #ifdef __cplusplus extern "C" { #endif #ifdef HITLS_TLS_PROTO_DTLS12 typedef struct { RecHdr hdr; /* record header */ uint8_t *recordBody; /* record body */ } UnprocessedHsMsg; /* Unprocessed handshake messages */ /* rfc6083 4.7 Handshake User messages that arrive between ChangeCipherSpec and Finished messages and use the new epoch have probably passed the Finished message and MUST be buffered by DTLS until the Finished message is read. */ typedef struct { ListHead head; uint32_t count; /* Number of cached record messages */ RecHdr hdr; /* record header */ uint8_t *recordBody; /* record body */ } UnprocessedAppMsg; /* Unprocessed App messages: App messages that are out of order with finished */ void CacheNextEpochHsMsg(UnprocessedHsMsg *unprocessedHsMsg, const RecHdr *hdr, const uint8_t *recordBody); UnprocessedAppMsg *UnprocessedAppMsgNew(void); void UnprocessedAppMsgFree(UnprocessedAppMsg *msg); void UnprocessedAppMsgListInit(UnprocessedAppMsg *appMsgList); void UnprocessedAppMsgListDeinit(UnprocessedAppMsg *appMsgList); int32_t UnprocessedAppMsgListAppend(UnprocessedAppMsg *appMsgList, const RecHdr *hdr, const uint8_t *recordBody); UnprocessedAppMsg *UnprocessedAppMsgGet(UnprocessedAppMsg *appMsgList, uint16_t curEpoch); #endif // HITLS_TLS_PROTO_DTLS12 #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples
tls/record/src/rec_unprocessed_msg.h
C
unknown
2,153
/* * 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 "securec.h" #include "bsl_sal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hitls_config.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "tls.h" #include "uio_base.h" #include "record.h" #include "hs_ctx.h" #ifdef HITLS_TLS_FEATURE_INDICATOR #include "indicator.h" #endif #include "hs.h" #include "rec_crypto.h" RecConnState *GetWriteConnState(const TLS_Ctx *ctx) { /** Obtain the record structure. */ RecCtx *recordCtx = (RecCtx *)ctx->recCtx; return recordCtx->writeStates.currentState; } static void OutbufUpdate(uint32_t *start, uint32_t startvalue, uint32_t *end, uint32_t endvalue) { /** Commit the record to be written */ *start = startvalue; *end = endvalue; return; } static int32_t CheckEncryptionLimits(TLS_Ctx *ctx, RecConnState *state) { (void)ctx; if (state->suiteInfo != NULL && #ifdef HITLS_TLS_FEATURE_KEY_UPDATE ctx->isKeyUpdateRequest == false && #endif (state->suiteInfo->cipherAlg == HITLS_CIPHER_AES_128_GCM || state->suiteInfo->cipherAlg == HITLS_CIPHER_AES_256_GCM) && RecConnGetSeqNum(state) > REC_MAX_AES_GCM_ENCRYPTION_LIMIT) { BSL_ERR_PUSH_ERROR(HITLS_REC_ENCRYPTED_NUMBER_OVERFLOW); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16188, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "AES-GCM record encrypted times overflow", 0, 0, 0, 0); return HITLS_REC_ENCRYPTED_NUMBER_OVERFLOW; } return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_DTLS12 // Write the data message. static int32_t DatagramWrite(TLS_Ctx *ctx, RecBuf *buf) { uint32_t total = buf->end - buf->start; /* Attempt to write */ uint32_t sendLen = 0u; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_WRITING; #endif int32_t ret = BSL_UIO_Write(ctx->uio, &(buf->buf[buf->start]), total, &sendLen); /* Two types of failures occur in the packet transfer scenario: * a. The bottom layer directly returns a failure message. * b. Only some data packets are sent. * (sendLen != total) && (sendLen != 0) checks whether the returned result is null, but only part of the data is sent */ if ((ret != BSL_SUCCESS) || ((sendLen != 0) && (sendLen != total))) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_IO_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15664, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record send: IO exception. %d\n", ret, 0, 0, 0); return HITLS_REC_ERR_IO_EXCEPTION; } if (sendLen == 0) { return HITLS_REC_NORMAL_IO_BUSY; } buf->start = 0; buf->end = 0; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif return HITLS_SUCCESS; } void DtlsPlainMsgGenerate(REC_TextInput *plainMsg, const TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t plainLen, uint64_t epochSeq) { plainMsg->type = recordType; plainMsg->text = data; plainMsg->textLen = plainLen; plainMsg->negotiatedVersion = ctx->negotiatedInfo.version; #ifdef HITLS_TLS_FEATURE_ETM plainMsg->isEncryptThenMac = ctx->negotiatedInfo.isEncryptThenMac; #endif if (ctx->negotiatedInfo.version == 0) { plainMsg->version = HITLS_VERSION_DTLS10; if (IS_SUPPORT_TLCP(ctx->config.tlsConfig.originVersionMask)) { plainMsg->version = HITLS_VERSION_TLCP_DTLCP11; } } else { plainMsg->version = ctx->negotiatedInfo.version; } BSL_Uint64ToByte(epochSeq, plainMsg->seq); } static inline void DtlsRecordHeaderPack(uint8_t *outBuf, REC_Type recordType, uint16_t version, uint64_t epochSeq, uint32_t cipherTextLen) { outBuf[0] = recordType; BSL_Uint16ToByte(version, &outBuf[1]); BSL_Uint64ToByte(epochSeq, &outBuf[REC_DTLS_RECORD_EPOCH_OFFSET]); BSL_Uint16ToByte((uint16_t)cipherTextLen, &outBuf[REC_DTLS_RECORD_LENGTH_OFFSET]); } static int32_t DtlsTrySendMessage(TLS_Ctx *ctx, RecCtx *recordCtx, REC_Type recordType, RecConnState *state) { /* Notify the uio whether the service message is being sent. rfc6083 4.4. Stream Usage: For non-app messages, the * sctp stream id number must be 0 */ bool isAppMsg = (recordType == REC_TYPE_APP); (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_SCTP_MASK_APP_MESSAGE, sizeof(isAppMsg), &isAppMsg); int32_t ret = DatagramWrite(ctx, recordCtx->outBuf); if (ret != HITLS_SUCCESS) { /* Does not cache messages in the DTLS */ recordCtx->outBuf->start = 0; recordCtx->outBuf->end = 0; return ret; } #if defined(HITLS_BSL_UIO_UDP) ret = RecDerefBufList(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_RELEASE_BUFFERS) != 0 && (recordType == REC_TYPE_APP)) { RecTryFreeRecBuf(ctx, true); } #endif /** Add the record sequence */ RecConnSetSeqNum(state, state->seq + 1); return HITLS_SUCCESS; } // Write a record for the DTLS protocol int32_t DtlsRecordWrite(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { /** Obtain the record structure */ RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecConnState *state = GetWriteConnState(ctx); if (state->seq > REC_DTLS_SN_MAX_VALUE) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_SN_WRAPPING); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15665, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: sequence number wrap.", 0, 0, 0, 0); return HITLS_REC_ERR_SN_WRAPPING; } uint32_t cipherTextLen = RecGetCryptoFuncs(state->suiteInfo)->calCiphertextLen(ctx, state->suiteInfo, num, false); if (cipherTextLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15666, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: cipherTextLen(0) error.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } int32_t ret = RecIoBufInit(ctx, recordCtx, false); if (ret != HITLS_SUCCESS) { return ret; } const uint32_t outBufLen = REC_DTLS_RECORD_HEADER_LEN + cipherTextLen; if (outBufLen > recordCtx->outBuf->bufSize) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_BUFFER_NOT_ENOUGH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15667, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DTLS record write error: msg len = %u, buf len = %u.", outBufLen, recordCtx->outBuf->bufSize, 0, 0); return HITLS_REC_ERR_BUFFER_NOT_ENOUGH; } /* Before encryption, construct plaintext parameters */ REC_TextInput plainMsg = {0}; uint64_t epochSeq = REC_EPOCHSEQ_CAL(RecConnGetEpoch(state), state->seq); DtlsPlainMsgGenerate(&plainMsg, ctx, recordType, data, num, epochSeq); /** Obtain the cache address */ uint8_t *outBuf = &recordCtx->outBuf->buf[0]; DtlsRecordHeaderPack(outBuf, recordType, plainMsg.version, epochSeq, cipherTextLen); ret = CheckEncryptionLimits(ctx, state); if (ret != HITLS_SUCCESS) { return ret; } /** Encrypt the record body */ ret = RecConnEncrypt(ctx, state, &plainMsg, &outBuf[REC_DTLS_RECORD_HEADER_LEN], cipherTextLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17280, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnEncrypt fail", 0, 0, 0, 0); return ret; } OutbufUpdate(&recordCtx->outBuf->start, 0, &recordCtx->outBuf->end, outBufLen); #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(1, 0, RECORD_HEADER, outBuf, REC_DTLS_RECORD_HEADER_LEN, ctx, ctx->config.tlsConfig.msgArg); #endif return DtlsTrySendMessage(ctx, recordCtx, recordType, state); } #endif /* HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS // Writes data to the UIO of the TLS context. int32_t StreamWrite(TLS_Ctx *ctx, RecBuf *buf) { uint32_t total = buf->end - buf->start; int32_t ret = BSL_SUCCESS; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_WRITING; #endif do { uint32_t sendLen = 0u; ret = BSL_UIO_Write(ctx->uio, &(buf->buf[buf->start]), total, &sendLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_IO_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15668, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record send: IO exception. %d\n", ret, 0, 0, 0); return HITLS_REC_ERR_IO_EXCEPTION; } if (sendLen == 0) { return HITLS_REC_NORMAL_IO_BUSY; } buf->start += sendLen; total -= sendLen; } while (buf->start < buf->end); buf->start = 0; buf->end = 0; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif return HITLS_SUCCESS; } static void TlsPlainMsgGenerate(REC_TextInput *plainMsg, const TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t plainLen) { plainMsg->type = recordType; plainMsg->text = data; plainMsg->textLen = plainLen; plainMsg->negotiatedVersion = ctx->negotiatedInfo.version; #ifdef HITLS_TLS_FEATURE_ETM plainMsg->isEncryptThenMac = ctx->negotiatedInfo.isEncryptThenMacWrite; #endif if (ctx->negotiatedInfo.version != 0) { plainMsg->version = #ifdef HITLS_TLS_PROTO_TLS13 (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) ? HITLS_VERSION_TLS12 : #endif ctx->negotiatedInfo.version; } else { plainMsg->version = #ifdef HITLS_TLS_PROTO_TLS13 (ctx->config.tlsConfig.maxVersion == HITLS_VERSION_TLS13) ? HITLS_VERSION_TLS12 : #endif ctx->config.tlsConfig.maxVersion; } if (ctx->hsCtx != NULL && ctx->hsCtx->state == TRY_SEND_CLIENT_HELLO && ctx->state != CM_STATE_RENEGOTIATION && #ifdef HITLS_TLS_PROTO_TLS13 ctx->hsCtx->haveHrr == false && #endif #ifdef HITLS_TLS_PROTO_TLCP11 ctx->config.tlsConfig.maxVersion != HITLS_VERSION_TLCP_DTLCP11 && #endif ctx->config.tlsConfig.maxVersion > HITLS_VERSION_TLS10) { plainMsg->version = HITLS_VERSION_TLS10; } BSL_Uint64ToByte(GetWriteConnState(ctx)->seq, plainMsg->seq); } static inline void TlsRecordHeaderPack(uint8_t *outBuf, REC_Type recordType, uint16_t version, uint32_t cipherTextLen) { outBuf[0] = recordType; BSL_Uint16ToByte(version, &outBuf[1]); BSL_Uint16ToByte((uint16_t)cipherTextLen, &outBuf[REC_TLS_RECORD_LENGTH_OFFSET]); } static int32_t SendRecord(TLS_Ctx *ctx, RecCtx *recordCtx, RecConnState *state, uint64_t seq, REC_Type recordType) { (void)recordType; int32_t ret = StreamWrite(ctx, recordCtx->outBuf); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_RELEASE_BUFFERS) != 0 && (recordType == REC_TYPE_APP)) { RecTryFreeRecBuf(ctx, true); } #endif /** Add the record sequence */ RecConnSetSeqNum(state, seq + 1); return HITLS_SUCCESS; } int32_t REC_OutBufFlush(TLS_Ctx *ctx) { RecBuf *writeBuf = ctx->recCtx->outBuf; if (writeBuf == NULL || writeBuf->start == writeBuf->end) { return HITLS_SUCCESS; // No data to flush } if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return HITLS_SUCCESS; } RecConnState *state = GetWriteConnState(ctx); /* The Recordtype is REC_TYPE_HANDSHAKE to not relase outbuffer in HITLS_MODE_RELEASE_BUFFERS mode */ int32_t ret = SendRecord(ctx, ctx->recCtx, state, state->seq, REC_TYPE_HANDSHAKE); if (ret != HITLS_SUCCESS) { return ret; } ctx->recCtx->pendingData = NULL; ctx->recCtx->pendingDataSize = 0; return HITLS_SUCCESS; } static int32_t SequenceCompare(RecConnState *state, uint64_t value) { if (state->isWrapped == true) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_SN_WRAPPING); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15670, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: sequence number wrap.", 0, 0, 0, 0); return HITLS_REC_ERR_SN_WRAPPING; } if (state->seq == value) { state->isWrapped = true; } return HITLS_SUCCESS; } static int32_t LengthCheck(uint32_t ciphertextLen, const uint32_t outBufLen, RecBuf *writeBuf) { if (ciphertextLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15671, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: cipherTextLen(0) error.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } if (outBufLen > writeBuf->bufSize) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_BUFFER_NOT_ENOUGH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15672, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: buffer is not enough.", 0, 0, 0, 0); return HITLS_REC_ERR_BUFFER_NOT_ENOUGH; } return HITLS_SUCCESS; } static const uint8_t *GetPlainMsgData(RecordPlaintext *recPlaintext, const uint8_t *data) { (void)recPlaintext; return #ifdef HITLS_TLS_PROTO_TLS13 recPlaintext->isTlsInnerPlaintext ? recPlaintext->plainData : #endif data; } // Write a record in the TLS protocol, serialize a record message, and send the message int32_t TlsRecordWrite(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { RecConnState *state = GetWriteConnState(ctx); RecordPlaintext recPlaintext = {0}; REC_TextInput plainMsg = {0}; int32_t ret = SequenceCompare(state, REC_TLS_SN_MAX_VALUE); if (ret != HITLS_SUCCESS) { return ret; } ret = RecIoBufInit(ctx, (RecCtx *)ctx->recCtx, false); if (ret != HITLS_SUCCESS) { return ret; } RecBuf *writeBuf = ctx->recCtx->outBuf; /* Check whether the cache exists */ if (writeBuf->end > writeBuf->start) { return SendRecord(ctx, ctx->recCtx, state, state->seq, recordType); } const RecCryptoFunc *funcs = RecGetCryptoFuncs(state->suiteInfo); ret = funcs->encryptPreProcess(ctx, recordType, data, num, &recPlaintext); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17281, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encryptPreProcess fail", 0, 0, 0, 0); return ret; } uint32_t ciphertextLen = funcs->calCiphertextLen(ctx, state->suiteInfo, recPlaintext.plainLen, false); const uint32_t outBufLen = REC_TLS_RECORD_HEADER_LEN + ciphertextLen; ret = LengthCheck(ciphertextLen, outBufLen, writeBuf); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(recPlaintext.plainData); return ret; } /* If the value is not tls13, use the input parameter data */ const uint8_t *plainMsgData = GetPlainMsgData(&recPlaintext, data); (void)TlsPlainMsgGenerate(&plainMsg, ctx, recPlaintext.recordType, plainMsgData, recPlaintext.plainLen); (void)TlsRecordHeaderPack(writeBuf->buf, recPlaintext.recordType, plainMsg.version, ciphertextLen); ret = CheckEncryptionLimits(ctx, state); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(recPlaintext.plainData); return ret; } /** Encrypt the record body */ ret = RecConnEncrypt(ctx, state, &plainMsg, writeBuf->buf + REC_TLS_RECORD_HEADER_LEN, ciphertextLen); BSL_SAL_FREE(recPlaintext.plainData); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(1, recordType, RECORD_HEADER, writeBuf->buf, REC_TLS_RECORD_HEADER_LEN, ctx, ctx->config.tlsConfig.msgArg); #endif OutbufUpdate(&writeBuf->start, 0, &writeBuf->end, outBufLen); return SendRecord(ctx, ctx->recCtx, state, state->seq, recordType); } #endif /* HITLS_TLS_PROTO_TLS */ #ifdef HITLS_TLS_FEATURE_FLIGHT int32_t REC_FlightTransmit(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) ret = REC_QueryMtu(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ ret = BSL_UIO_Ctrl(ctx->uio, BSL_UIO_FLUSH, 0, NULL); if (ret == BSL_UIO_IO_BUSY) { #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return HITLS_REC_NORMAL_IO_BUSY; } bool exceeded = false; (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_UDP_MTU_EXCEEDED, sizeof(bool), &exceeded); if (exceeded) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17362, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: get EMSGSIZE error.", 0, 0, 0, 0); ctx->needQueryMtu = true; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ return HITLS_REC_NORMAL_IO_BUSY; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_IO_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16110, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "fail to send handshake message in bUio.", 0, 0, 0, 0); return HITLS_REC_ERR_IO_EXCEPTION; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_FLIGHT */
2302_82127028/openHiTLS-examples
tls/record/src/rec_write.c
C
unknown
17,749
/* * 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 REC_WRITE_H #define REC_WRITE_H #include <stdint.h> #include "rec.h" #include "rec_buf.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Write a record in TLS * * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [IN] Data to be written * @param plainLen [IN] plain length * * @retval HITLS_SUCCESS * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_IO_BUSY I/O busy * @retval HITLS_REC_ERR_SN_WRAPPING Sequence number wrap */ int32_t TlsRecordWrite(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t plainLen); #ifdef HITLS_TLS_PROTO_DTLS12 /** * @brief Write a record in DTLS * * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [IN] Data to be written * @param plainLen [IN] plain length * * @retval HITLS_SUCCESS * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_IO_BUSY I/O busy * @retval HITLS_REC_ERR_SN_WRAPPING Sequence number wrap */ int32_t DtlsRecordWrite(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t plainLen); #endif /** * @brief Write data to the UIO of the TLS context * * @param ctx [IN] TLS context * @param buf [IN] Send buffer * * @retval HITLS_SUCCESS * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_IO_BUSY I/O busy */ int32_t StreamWrite(TLS_Ctx *ctx, RecBuf *buf); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples
tls/record/src/rec_write.h
C
unknown
2,025
/* * 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 "bsl_sal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hitls_config.h" #include "rec.h" #include "bsl_uio.h" #include "rec_write.h" #include "rec_read.h" #include "rec_crypto.h" #include "hs.h" #include "alert.h" #include "record.h" // Release RecStatesSuite static void RecConnStatesDeinit(RecCtx *recordCtx) { RecConnStateFree(recordCtx->readStates.currentState); RecConnStateFree(recordCtx->writeStates.currentState); return; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) static void RecCmpPmtu(const TLS_Ctx *ctx, uint32_t *recSize) { if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { uint32_t pmtuLimit = ctx->config.pmtu; /* If miniaturization is enabled in the dtls over udp scenario, the mtu size is used */ *recSize = (*recSize > pmtuLimit) ? pmtuLimit : *recSize; } } #endif #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS void RecTryFreeRecBuf(TLS_Ctx *ctx, bool isOut) { RecCtx *recordCtx = (RecCtx *)ctx->recCtx; if (isOut) { if (recordCtx->outBuf != NULL && recordCtx->outBuf->start == recordCtx->outBuf->end) { RecBufFree(recordCtx->outBuf); recordCtx->outBuf = NULL; } } else { if (recordCtx->inBuf != NULL && recordCtx->inBuf->start == recordCtx->inBuf->end) { RecBufFree(recordCtx->inBuf); recordCtx->inBuf = NULL; } } return; } #endif uint32_t REC_GetOutBufPendingSize(const TLS_Ctx *ctx) { RecBuf *writeBuf = ctx->recCtx->outBuf; if (writeBuf == NULL) { return 0; } return writeBuf->start > writeBuf->end ? 0 : writeBuf->end - writeBuf->start; } int32_t RecIoBufInit(TLS_Ctx *ctx, RecCtx *recordCtx, bool isRead) { RecBuf **ioBuf = isRead ? &recordCtx->inBuf : &recordCtx->outBuf; if (*ioBuf == NULL) { uint32_t initSize = RecGetInitBufferSize(ctx, isRead); if (isRead && ctx->config.tlsConfig.recInbufferSize != 0) { initSize = ctx->config.tlsConfig.recInbufferSize; } *ioBuf = RecBufNew(initSize); if (*ioBuf == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15532, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } } return HITLS_SUCCESS; } static uint32_t RecGetDefaultBufferSize(bool isDtls, bool isRead) { (void)isDtls; uint32_t recHeaderLen = #ifdef HITLS_TLS_PROTO_DTLS12 isDtls ? REC_DTLS_RECORD_HEADER_LEN : #endif REC_TLS_RECORD_HEADER_LEN; uint32_t overHead = REC_MAX_WRITE_ENCRYPTED_OVERHEAD; if (isRead) { overHead = REC_MAX_READ_ENCRYPTED_OVERHEAD; } return recHeaderLen + REC_MAX_PLAIN_TEXT_LENGTH + overHead; } static uint32_t RecGetReadBufferSize(const TLS_Ctx *ctx) { uint32_t recSize = RecGetDefaultBufferSize(IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask), true); if (ctx->negotiatedInfo.recordSizeLimit != 0 && ctx->negotiatedInfo.recordSizeLimit <= REC_MAX_PLAIN_TEXT_LENGTH) { recSize -= REC_MAX_PLAIN_TEXT_LENGTH - ctx->negotiatedInfo.recordSizeLimit; if (HS_GetVersion(ctx) == HITLS_VERSION_TLS13) { recSize--; } } return recSize; } static uint32_t RecGetWriteBufferSize(const TLS_Ctx *ctx) { uint32_t recSize = RecGetDefaultBufferSize(IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask), false); uint32_t maxSendFragment = #ifdef HITLS_TLS_FEATURE_MAX_SEND_FRAGMENT (uint32_t)ctx->config.tlsConfig.maxSendFragment == 0 ? REC_MAX_PLAIN_TEXT_LENGTH : (uint32_t)ctx->config.tlsConfig.maxSendFragment; #else REC_MAX_PLAIN_TEXT_LENGTH; #endif recSize -= REC_MAX_PLAIN_TEXT_LENGTH - maxSendFragment; if (ctx->negotiatedInfo.peerRecordSizeLimit != 0 && ctx->negotiatedInfo.peerRecordSizeLimit <= maxSendFragment) { recSize -= maxSendFragment - ctx->negotiatedInfo.peerRecordSizeLimit; if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { recSize--; } } #if defined(HITLS_BSL_UIO_UDP) RecCmpPmtu(ctx, &recSize); #endif return recSize; } uint32_t RecGetInitBufferSize(const TLS_Ctx *ctx, bool isRead) { /* If the TLS protocol is used, there is no PMTU limit */ return isRead ? RecGetReadBufferSize(ctx) : RecGetWriteBufferSize(ctx); } int32_t RecDerefBufList(TLS_Ctx *ctx) { int32_t ret = RecBufListDereference(ctx->recCtx->appRecList); if (ret != HITLS_SUCCESS) { return ret; } return RecBufListDereference(ctx->recCtx->hsRecList); } static int32_t InnerRecRead(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num) { (void)recordType; (void)readLen; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return DtlsRecordRead(ctx, recordType, data, readLen, num); } #endif #ifdef HITLS_TLS_PROTO_TLS return TlsRecordRead(ctx, recordType, data, readLen, num); #else BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17294, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "internal exception occurs", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; #endif } static int32_t InnerRecWrite(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif uint32_t maxWriteSize; int32_t ret = REC_GetMaxWriteSize(ctx, &maxWriteSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17295, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetMaxWriteSize fail", 0, 0, 0, 0); return ret; } if (num > maxWriteSize) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15539, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record wrtie: plain length is too long.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_TOO_BIG_LENGTH); return HITLS_REC_ERR_TOO_BIG_LENGTH; } #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { /* DTLS */ return DtlsRecordWrite(ctx, recordType, data, num); } #endif #ifdef HITLS_TLS_PROTO_TLS return TlsRecordWrite(ctx, recordType, data, num); #else BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17296, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "internal exception occurs", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; #endif } static int32_t RecConnStatesInit(RecCtx *recordCtx) { recordCtx->recRead = InnerRecRead; recordCtx->recWrite = InnerRecWrite; recordCtx->readStates.currentState = RecConnStateNew(); if (recordCtx->readStates.currentState == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17297, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "StateNew fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } recordCtx->writeStates.currentState = RecConnStateNew(); if (recordCtx->writeStates.currentState == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17298, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "StateNew fail", 0, 0, 0, 0); RecConnStateFree(recordCtx->readStates.currentState); recordCtx->readStates.currentState = NULL; BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } return HITLS_SUCCESS; } static int32_t RecBufInit(TLS_Ctx *ctx, RecCtx *newRecCtx) { #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_RELEASE_BUFFERS) == 0) { #endif int32_t ret = RecIoBufInit(ctx, newRecCtx, true); if (ret != HITLS_SUCCESS) { return ret; } ret = RecIoBufInit(ctx, newRecCtx, false); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS } #endif newRecCtx->hsRecList = RecBufListNew(); newRecCtx->appRecList = RecBufListNew(); if (newRecCtx->hsRecList == NULL || newRecCtx->appRecList == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17299, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "BufListNew fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } return HITLS_SUCCESS; } static void RecDeInit(RecCtx *recordCtx) { RecBufFree(recordCtx->outBuf); RecBufFree(recordCtx->inBuf); RecBufListFree(recordCtx->hsRecList); RecBufListFree(recordCtx->appRecList); RecConnStatesDeinit(recordCtx); RecConnStateFree(recordCtx->readStates.pendingState); RecConnStateFree(recordCtx->writeStates.pendingState); RecConnStateFree(recordCtx->readStates.outdatedState); RecConnStateFree(recordCtx->writeStates.outdatedState); #ifdef HITLS_TLS_PROTO_DTLS12 UnprocessedAppMsgListDeinit(&recordCtx->unprocessedAppMsgList); #if defined(HITLS_BSL_UIO_UDP) BSL_SAL_FREE(recordCtx->unprocessedHsMsg.recordBody); REC_RetransmitListClean(recordCtx); #endif #endif /* HITLS_TLS_PROTO_DTLS12 */ } int32_t REC_Init(TLS_Ctx *ctx) { if (ctx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17300, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ctx null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } if (ctx->recCtx != NULL) { return HITLS_SUCCESS; } RecCtx *newRecCtx = (RecCtx *)BSL_SAL_Calloc(1, sizeof(RecCtx)); if (newRecCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15531, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: malloc fail.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } #ifdef HITLS_TLS_PROTO_DTLS12 UnprocessedAppMsgListInit(&newRecCtx->unprocessedAppMsgList); #ifdef HITLS_BSL_UIO_UDP LIST_INIT(&newRecCtx->retransmitList.head); #endif #endif int32_t ret = RecBufInit(ctx, newRecCtx); if (ret != HITLS_SUCCESS) { goto ERR; } ret = RecConnStatesInit(newRecCtx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15534, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: init connect state fail.", 0, 0, 0, 0); goto ERR; } ctx->recCtx = newRecCtx; return HITLS_SUCCESS; ERR: RecDeInit(newRecCtx); BSL_SAL_FREE(newRecCtx); return ret; } void REC_DeInit(TLS_Ctx *ctx) { if (ctx != NULL && ctx->recCtx != NULL) { RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecDeInit(recordCtx); BSL_SAL_FREE(ctx->recCtx); } return; } bool REC_ReadHasPending(const TLS_Ctx *ctx) { if ((ctx == NULL) || (ctx->recCtx == NULL)) { return false; } RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecBuf *inBuf = recordCtx->inBuf; if (inBuf == NULL) { return false; } if (inBuf->end != inBuf->start) { return true; } return false; } int32_t REC_Read(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num) { if ((ctx == NULL) || (ctx->recCtx == NULL) || (data == NULL) || (ctx->alertCtx == NULL)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15535, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: input invalid parameter.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return HITLS_INTERNAL_EXCEPTION; } return ctx->recCtx->recRead(ctx, recordType, data, readLen, num); } int32_t REC_Write(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { if ((ctx == NULL) || (ctx->recCtx == NULL) || (num != 0 && data == NULL) || (num == 0 && recordType != REC_TYPE_APP)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15537, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: input null pointer.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } int32_t ret = ctx->recCtx->recWrite(ctx, recordType, data, num); #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) if (ret != HITLS_SUCCESS) { if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return ret; } bool exceeded = false; (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_UDP_MTU_EXCEEDED, sizeof(bool), &exceeded); if (exceeded) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17362, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: get EMSGSIZE error.", 0, 0, 0, 0); ctx->needQueryMtu = true; } } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ return ret; } #if defined(HITLS_BSL_UIO_UDP) void REC_ActiveOutdatedWriteState(TLS_Ctx *ctx) { RecCtx *recCtx = (RecCtx *)ctx->recCtx; RecConnStates *writeStates = &recCtx->writeStates; writeStates->pendingState = writeStates->currentState; writeStates->currentState = writeStates->outdatedState; writeStates->outdatedState = NULL; return; } void REC_DeActiveOutdatedWriteState(TLS_Ctx *ctx) { RecCtx *recCtx = (RecCtx *)ctx->recCtx; RecConnStates *writeStates = &recCtx->writeStates; writeStates->outdatedState = writeStates->currentState; writeStates->currentState = writeStates->pendingState; writeStates->pendingState = NULL; return; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ static void FreeDataAndState(RecConnSuitInfo *clientSuitInfo, RecConnSuitInfo *serverSuitInfo, RecConnState *readState, RecConnState *writeState) { BSL_SAL_CleanseData((void *)clientSuitInfo, sizeof(RecConnSuitInfo)); BSL_SAL_CleanseData((void *)serverSuitInfo, sizeof(RecConnSuitInfo)); RecConnStateFree(readState); RecConnStateFree(writeState); } int32_t REC_InitPendingState(const TLS_Ctx *ctx, const REC_SecParameters *param) { if (ctx == NULL || ctx->recCtx == NULL || param == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return RETURN_ERROR_NUMBER_PROCESS(HITLS_INTERNAL_EXCEPTION, BINLOG_ID15540, "Record: ctx null"); } int32_t ret = HITLS_MEMALLOC_FAIL; RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecConnSuitInfo clientSuitInfo = {0}; RecConnSuitInfo serverSuitInfo = {0}; RecConnSuitInfo *out = NULL; RecConnSuitInfo *in = NULL; RecConnState *readState = RecConnStateNew(); RecConnState *writeState = RecConnStateNew(); if (readState == NULL || writeState == NULL) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17301, "StateNew fail"); goto ERR; } /* 1.Generate a secret */ ret = RecConnKeyBlockGen(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), param, &clientSuitInfo, &serverSuitInfo); if (ret != HITLS_SUCCESS) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17302, "KeyBlockGen fail"); goto ERR; } /* 2.Set the corresponding read/write pending state */ out = (param->isClient == true) ? &clientSuitInfo : &serverSuitInfo; in = (param->isClient == true) ? &serverSuitInfo : &clientSuitInfo; ret = RecConnStateSetCipherInfo(writeState, out); if (ret != HITLS_SUCCESS) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17303, "SetCipherInfo fail"); goto ERR; } ret = RecConnStateSetCipherInfo(readState, in); if (ret != HITLS_SUCCESS) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17304, "SetCipherInfo fail"); goto ERR; } /* Clear sensitive information */ FreeDataAndState(&clientSuitInfo, &serverSuitInfo, recordCtx->readStates.pendingState, recordCtx->writeStates.pendingState); recordCtx->readStates.pendingState = readState; recordCtx->writeStates.pendingState = writeState; return HITLS_SUCCESS; ERR: /* Clear sensitive information */ FreeDataAndState(&clientSuitInfo, &serverSuitInfo, readState, writeState); BSL_ERR_PUSH_ERROR(ret); return ret; } #ifdef HITLS_TLS_PROTO_TLS13 int32_t REC_TLS13InitPendingState(const TLS_Ctx *ctx, const REC_SecParameters *param, bool isOut) { if (ctx == NULL || ctx->recCtx == NULL || param == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15542, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: ctx null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return HITLS_INTERNAL_EXCEPTION; } RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecConnSuitInfo suitInfo = {0}; RecConnState *state = RecConnStateNew(); if (state == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17305, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "StateNew fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } /* 1.Generate a secret */ int32_t ret = RecTLS13ConnKeyBlockGen(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), param, &suitInfo); if (ret != HITLS_SUCCESS) { RecConnStateFree(state); return ret; } /* 2.Set the corresponding read/write pending state */ RecConnStates *curState = NULL; if (isOut) { curState = &(recordCtx->writeStates); } else { curState = &(recordCtx->readStates); } ret = RecConnStateSetCipherInfo(state, &suitInfo); if (ret != HITLS_SUCCESS) { RecConnStateFree(state); return ret; } RecConnStateFree(curState->pendingState); curState->pendingState = state; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ int32_t REC_ActivePendingState(TLS_Ctx *ctx, bool isOut) { RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecConnStates *states = (isOut == true) ? &recordCtx->writeStates : &recordCtx->readStates; if (states->pendingState == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15543, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: pending state should not be null.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return HITLS_INTERNAL_EXCEPTION; } RecConnStateFree(states->outdatedState); states->outdatedState = states->currentState; states->currentState = states->pendingState; states->pendingState = NULL; RecConnSetSeqNum(states->currentState, 0); #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { if (isOut) { ++recordCtx->writeEpoch; RecConnSetEpoch(states->currentState, recordCtx->writeEpoch); } else { ++recordCtx->readEpoch; RecConnSetEpoch(states->currentState, recordCtx->readEpoch); #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) RecAntiReplayReset(&states->currentState->window); #endif } } #endif /* HITLS_TLS_PROTO_DTLS12 */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15544, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "Record: active pending state.", 0, 0, 0, 0); return HITLS_SUCCESS; } static uint32_t REC_GetRecordSizeLimitWriteLen(const TLS_Ctx *ctx) { uint32_t defaultLen = #ifdef HITLS_TLS_FEATURE_MAX_SEND_FRAGMENT (uint32_t)ctx->config.tlsConfig.maxSendFragment == 0 ? REC_MAX_PLAIN_TEXT_LENGTH : (uint32_t)ctx->config.tlsConfig.maxSendFragment; #else REC_MAX_PLAIN_TEXT_LENGTH; #endif if (ctx->negotiatedInfo.recordSizeLimit != 0 && ctx->negotiatedInfo.peerRecordSizeLimit <= defaultLen) { defaultLen = ctx->negotiatedInfo.peerRecordSizeLimit; if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { defaultLen--; } } return defaultLen; } int32_t REC_RecOutBufReSet(TLS_Ctx *ctx) { RecCtx *recCtx = ctx->recCtx; return RecBufResize(recCtx->outBuf, RecGetWriteBufferSize(ctx)); } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) static int32_t ChangeBufferSize(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; if (ctx->bUio == NULL) { ctx->mtuModified = false; return HITLS_SUCCESS; } uint32_t bufferLen = (uint32_t)ctx->config.pmtu; if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { ret = BSL_UIO_Ctrl(ctx->bUio, BSL_UIO_SET_BUFFER_SIZE, sizeof(uint32_t), &bufferLen); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17363, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "SET_BUFFER_SIZE fail, ret %d", ret, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_UIO_FAIL); return HITLS_UIO_FAIL; } } ctx->mtuModified = false; return HITLS_SUCCESS; } int32_t REC_QueryMtu(TLS_Ctx *ctx) { if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return HITLS_SUCCESS; } uint16_t originMtu = ctx->config.pmtu; if (ctx->config.linkMtu > 0) { uint8_t overhead = 0; (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_UDP_GET_MTU_OVERHEAD, sizeof(uint8_t), &overhead); ctx->config.pmtu = ctx->config.linkMtu - (uint16_t)overhead; ctx->config.linkMtu = 0; } if (ctx->needQueryMtu && !ctx->noQueryMtu) { uint32_t mtu = 0; int32_t ret = BSL_UIO_Ctrl(ctx->uio, BSL_UIO_UDP_QUERY_MTU, sizeof(uint32_t), &mtu); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17364, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "UIO_Ctrl fail, ret %d", ret, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_UIO_FAIL); return HITLS_UIO_FAIL; } uint8_t overhead = 0; (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_UDP_GET_MTU_OVERHEAD, sizeof(uint8_t), &overhead); uint16_t minMtu = (uint16_t)DTLS_MIN_MTU - (uint16_t)overhead; mtu = mtu > UINT16_MAX ? UINT16_MAX : mtu; ctx->config.pmtu = ((uint16_t)mtu < minMtu) ? minMtu : (uint16_t)mtu; } ctx->needQueryMtu = false; if (ctx->config.pmtu != originMtu || ctx->mtuModified) { return ChangeBufferSize(ctx); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ int32_t REC_GetMaxWriteSize(const TLS_Ctx *ctx, uint32_t *len) { if (ctx == NULL || ctx->recCtx == NULL || len == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15545, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: input null pointer.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } *len = REC_GetRecordSizeLimitWriteLen(ctx); #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) uint32_t mtuLen = 0; int32_t ret = REC_GetMaxDataMtu(ctx, &mtuLen); if (ret == HITLS_SUCCESS) { *len = (*len > mtuLen) ? mtuLen : *len; } if (ret != HITLS_UIO_IO_TYPE_ERROR) { return ret; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t REC_GetMaxDataMtu(const TLS_Ctx *ctx, uint32_t *len) { bool isUdp = false; RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecConnState *currentState = recordCtx->writeStates.currentState; uint32_t overHead; BSL_UIO *uio = ctx->uio; while (uio != NULL) { if (BSL_UIO_GetUioChainTransportType(uio, BSL_UIO_UDP)) { isUdp = true; break; } uio = BSL_UIO_Next(uio); } if (!isUdp) { /* In non-UDP scenarios, there is no PMTU limit */ return HITLS_UIO_IO_TYPE_ERROR; } /* In UDP scenarios, handshake packets and application data packets with miniaturization enabled have the MTU limit */ uint32_t encryptLen = RecGetCryptoFuncs(currentState->suiteInfo)->calCiphertextLen(ctx, currentState->suiteInfo, 0, false); overHead = REC_DTLS_RECORD_HEADER_LEN + encryptLen; if (ctx->config.pmtu <= overHead) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17306, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pmtu too small", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_REC_PMTU_TOO_SMALL); return HITLS_REC_PMTU_TOO_SMALL; } *len = ctx->config.pmtu - overHead; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ REC_Type REC_GetUnexpectedMsgType(TLS_Ctx *ctx) { return ctx->recCtx->unexpectedMsgType; } void RecClearAlertCount(TLS_Ctx *ctx, REC_Type recordType) { if (recordType != REC_TYPE_ALERT) { ALERT_ClearWarnCount(ctx); } return; }
2302_82127028/openHiTLS-examples
tls/record/src/record.c
C
unknown
25,244
/* * 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 RECORD_H #define RECORD_H #include "tls.h" #include "rec.h" #include "rec_header.h" #include "rec_unprocessed_msg.h" #include "rec_buf.h" #include "rec_conn.h" #ifdef __cplusplus extern "C" { #endif #define REC_MAX_PLAIN_TEXT_LENGTH 16384 /* Plain content length */ #define REC_MAX_ENCRYPTED_OVERHEAD 2048u /* Maximum Encryption Overhead rfc5246 */ #define REC_MAX_READ_ENCRYPTED_OVERHEAD REC_MAX_ENCRYPTED_OVERHEAD #define REC_MAX_WRITE_ENCRYPTED_OVERHEAD REC_MAX_ENCRYPTED_OVERHEAD #define REC_MAX_CIPHER_TEXT_LEN (REC_MAX_PLAIN_LENGTH + REC_MAX_ENCRYPTED_OVERHEAD) /* Maximum ciphertext length */ #define REC_MAX_AES_GCM_ENCRYPTION_LIMIT 23726566u /* RFC 8446 5.5 Limits on Key Usage AES-GCM SHOULD under 2^24.5 */ typedef struct { RecConnState *outdatedState; RecConnState *currentState; RecConnState *pendingState; } RecConnStates; typedef int32_t (*REC_ReadFunc)(TLS_Ctx *, REC_Type, uint8_t *, uint32_t *, uint32_t); typedef int32_t (*REC_WriteFunc)(TLS_Ctx *, REC_Type, const uint8_t *, uint32_t); typedef struct { ListHead head; /* Linked list header */ bool isExistCcsMsg; /* Check whether CCS messages exist in the retransmission message queue */ REC_Type type; /* message type */ uint8_t *msg; /* message data */ uint32_t len; /* message length */ } RecRetransmitList; typedef struct RecCtx { RecBuf *inBuf; /* Buffer for reading data */ RecBuf *outBuf; /* Buffer for writing data */ RecConnStates readStates; RecConnStates writeStates; RecBufList *hsRecList; /* hs plaintext data cache */ RecBufList *appRecList; /* app plaintext data cache */ uint32_t emptyRecordCnt; /* Count of empty records */ #ifdef HITLS_TLS_PROTO_DTLS12 uint16_t writeEpoch; uint16_t readEpoch; RecRetransmitList retransmitList; /* Cache the messages that may be retransmitted during the handshake */ /* Process out-of-order messages */ UnprocessedHsMsg unprocessedHsMsg; /* used to cache out-of-order finished messages */ /* unprocessed app message: app messages received in the CCS and finished receiving phases */ UnprocessedAppMsg unprocessedAppMsgList; #endif REC_ReadFunc recRead; void *rUserData; REC_WriteFunc recWrite; void *wUserData; REC_Type unexpectedMsgType; uint32_t pendingDataSize; /* Data length */ const uint8_t *pendingData; /* Plain Data content */ } RecCtx; /** * @brief Obtain the size of the buffer for read and write operations * * @param ctx [IN] TLS_Ctx context * @param isRead [IN] is read buffer * * @retval the size of the buffer for read and write operations */ uint32_t RecGetInitBufferSize(const TLS_Ctx *ctx, bool isRead); int32_t RecDerefBufList(TLS_Ctx *ctx); void RecClearAlertCount(TLS_Ctx *ctx, REC_Type recordType); /** * @brief free the record buffer * * @param ctx [IN] TLS_Ctx context * @param isOut [IN] is out buffer or not */ void RecTryFreeRecBuf(TLS_Ctx *ctx, bool isOut); /** * @brief Init the record io buffer * * @param ctx [IN] TLS_Ctx context * @param recordCtx [IN] record context * @param isRead [IN] Init in buffer or not * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL malloc fail */ int32_t RecIoBufInit(TLS_Ctx *ctx, RecCtx *recordCtx, bool isRead); #ifdef __cplusplus } #endif #endif /* RECORD_H */
2302_82127028/openHiTLS-examples
tls/record/src/record.h
C
unknown
4,034
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. cmake_minimum_required(VERSION 3.16 FATAL_ERROR) project(openHiTLS) set(HiTLS_SOURCE_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}) if(DEFINED BUILD_DIR) set(HiTLS_BUILD_DIR ${BUILD_DIR}) else() set(HiTLS_BUILD_DIR ${HiTLS_SOURCE_ROOT_DIR}/build) endif() execute_process(COMMAND python3 ${HiTLS_SOURCE_ROOT_DIR}/configure.py -m --build_dir ${HiTLS_BUILD_DIR}) include(${HiTLS_BUILD_DIR}/modules.cmake) install(DIRECTORY ${HiTLS_SOURCE_ROOT_DIR}/include/ DESTINATION ${CMAKE_INSTALL_PREFIX}/include/hitls/ FILES_MATCHING PATTERN "*.h")
2302_82127028/openHiTLS-examples_5985
CMakeLists.txt
CMake
unknown
1,079
/* * 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_CONF_H #define HITLS_APP_CONF_H #include <stdint.h> #include "bsl_obj.h" #include "bsl_conf.h" #include "hitls_pki_types.h" #include "hitls_pki_utils.h" #include "hitls_pki_csr.h" #include "hitls_pki_cert.h" #include "hitls_pki_crl.h" #include "hitls_pki_x509.h" #include "hitls_pki_pkcs12.h" #ifdef __cplusplus extern "C" { #endif /** * x509 v3 extensions */ #define HITLS_CFG_X509_EXT_AKI "authorityKeyIdentifier" #define HITLS_CFG_X509_EXT_SKI "subjectKeyIdentifier" #define HITLS_CFG_X509_EXT_BCONS "basicConstraints" #define HITLS_CFG_X509_EXT_KU "keyUsage" #define HITLS_CFG_X509_EXT_EXKU "extendedKeyUsage" #define HITLS_CFG_X509_EXT_SAN "subjectAltName" /* Key usage */ #define HITLS_CFG_X509_EXT_KU_DIGITAL_SIGN "digitalSignature" #define HITLS_CFG_X509_EXT_KU_NON_REPUDIATION "nonRepudiation" #define HITLS_CFG_X509_EXT_KU_KEY_ENCIPHERMENT "keyEncipherment" #define HITLS_CFG_X509_EXT_KU_DATA_ENCIPHERMENT "dataEncipherment" #define HITLS_CFG_X509_EXT_KU_KEY_AGREEMENT "keyAgreement" #define HITLS_CFG_X509_EXT_KU_KEY_CERT_SIGN "keyCertSign" #define HITLS_CFG_X509_EXT_KU_CRL_SIGN "cRLSign" #define HITLS_CFG_X509_EXT_KU_ENCIPHER_ONLY "encipherOnly" #define HITLS_CFG_X509_EXT_KU_DECIPHER_ONLY "decipherOnly" /* Extended key usage */ #define HITLS_CFG_X509_EXT_EXKU_SERVER_AUTH "serverAuth" #define HITLS_CFG_X509_EXT_EXKU_CLIENT_AUTH "clientAuth" #define HITLS_CFG_X509_EXT_EXKU_CODE_SING "codeSigning" #define HITLS_CFG_X509_EXT_EXKU_EMAIL_PROT "emailProtection" #define HITLS_CFG_X509_EXT_EXKU_TIME_STAMP "timeStamping" #define HITLS_CFG_X509_EXT_EXKU_OCSP_SIGN "OCSPSigning" /* Subject Alternative Name */ #define HITLS_CFG_X509_EXT_SAN_EMAIL "email" #define HITLS_CFG_X509_EXT_SAN_DNS "DNS" #define HITLS_CFG_X509_EXT_SAN_DIR_NAME "dirName" #define HITLS_CFG_X509_EXT_SAN_URI "URI" #define HITLS_CFG_X509_EXT_SAN_IP "IP" /* Authority key identifier */ #define HITLS_CFG_X509_EXT_AKI_KID (1 << 0) #define HITLS_CFG_X509_EXT_AKI_KID_ALWAYS (1 << 1) typedef struct { HITLS_X509_ExtAki aki; uint32_t flag; } HITLS_CFG_ExtAki; /** * @ingroup apps * * @brief Split String by character. * Remove spaces before and after separators. * * @param str [IN] String to be split. * @param separator [IN] Separator. * @param allowEmpty [IN] Indicates whether empty substrings can be contained. * @param strArr [OUT] String array. Only the first string needs to be released after use. * @param maxArrCnt [IN] String array. Only the first string needs to be released after use. * @param realCnt [OUT] Number of character strings after splitting。 * * @retval HITLS_APP_SUCCESS */ int32_t HITLS_APP_SplitString(const char *str, char separator, bool allowEmpty, char **strArr, uint32_t maxArrCnt, uint32_t *realCnt); /** * @ingroup apps * * @brief Process function of X509 extensions. * * @param cid [IN] Cid of extension * @param val [IN] Data pointer. * @param ctx [IN] Context. * * @retval HITLS_APP_SUCCESS */ typedef int32_t (*ProcExtCallBack)(BslCid cid, void *val, void *ctx); /** * @ingroup apps * * @brief Process function of X509 extensions. * * @param value [IN] conf * @param section [IN] The section name of x509 extension * @param extCb [IN] Callback function of one extension. * @param ctx [IN] Context of callback function. * * @retval HITLS_APP_SUCCESS */ int32_t HITLS_APP_CONF_ProcExt(BSL_CONF *cnf, const char *section, ProcExtCallBack extCb, void *ctx); /** * @ingroup apps * * @brief The callback function to add distinguish name * * @param ctx [IN] The context of callback function * @param nameList [IN] The linked list of subject name, the type is HITLS_X509_DN * * @retval HITLS_APP_SUCCESS */ typedef int32_t (*AddDnNameCb)(void *ctx, BslList *nameList); /** * @ingroup apps * * @brief The callback function to add subject name to csr * * @param ctx [IN] The context of callback function * @param nameList [IN] The linked list of subject name, the type is HITLS_X509_DN * * @retval HITLS_APP_SUCCESS */ int32_t HiTLS_AddSubjDnNameToCsr(void *csr, BslList *nameList); /** * @ingroup apps * * @brief Process distinguish name string. * The distinguish name format is /type0=value0/type1=value1/type2=... * * @param nameStr [IN] distinguish name string * @param cb [IN] The callback function to add distinguish name to csr or cert * @param ctx [IN] Context of callback function. * * @retval HITLS_APP_SUCCESS */ int32_t HITLS_APP_CFG_ProcDnName(const char *nameStr, AddDnNameCb cb, void *ctx); #ifdef __cplusplus } #endif #endif // HITLS_APP_CONF_H
2302_82127028/openHiTLS-examples_5985
apps/include/app_conf.h
C
unknown
5,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_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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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 <linux/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 #define BSL_SUCCESS 0 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_OptType; 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
2302_82127028/openHiTLS-examples_5985
apps/include/app_enc.h
C
unknown
1,853
/* * 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. */ HITLS_APP_MAX = 126, /* *< maximum of the error code */ }; #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5985
apps/include/app_errno.h
C
unknown
3,087
/* * 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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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_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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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_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
2302_82127028/openHiTLS-examples_5985
apps/include/app_opt.h
C
unknown
8,603
/* * 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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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_LOG_H #define HITLS_APP_LOG_H #include <stdio.h> #include <stdint.h> #include "bsl_uio.h" #ifdef __cplusplus extern "C" { #endif /** * @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
2302_82127028/openHiTLS-examples_5985
apps/include/app_print.h
C
unknown
1,527
/* * 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); #define HITLS_APP_FreeLibCtx CRYPT_EAL_LibCtxFree #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5985
apps/include/app_provider.h
C
unknown
1,083
/* * 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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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_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 "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 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. * * @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); #ifdef __cplusplus } #endif #endif // APP_UTILS_H
2302_82127028/openHiTLS-examples_5985
apps/include/app_utils.h
C
unknown
6,401
/* * 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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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: * * 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__) #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #else #error "only support linux" #endif #include "securec.h" #include "app_errno.h" #include "bsl_sal.h" #include "bsl_types.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; } 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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_conf.c
C
unknown
29,842
/* * 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 <linux/limits.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_types.h" #include "bsl_errno.h" #include "hitls_pki_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_rand.h" #include "crypt_errno.h" #include "app_opt.h" #include "app_function.h" #include "app_errno.h" #include "app_help.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} }; 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) { free(buf); (void)AppPrintError("Failed to obtain the standard input.\n"); break; } if ((crlDataSize + readLen) > MAX_CRLFILE_SIZE) { 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) { 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)) { free(buf); break; } 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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_crl.c
C
unknown
14,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. */ #include "app_dgst.h" #include <linux/limits.h> #include "string.h" #include "securec.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_eal_md.h" #include "bsl_errno.h" #include "app_opt.h" #include "app_function.h" #include "app_list.h" #include "app_errno.h" #include "app_help.h" #include "app_print.h" #define MAX_BUFSIZE (1024 * 8) // Indicates the length of a single digest during digest calculation. #define IS_SUPPORT_GET_EOF 1 #define DEFAULT_SHAKE256_SIZE 32 #define DEFAULT_SHAKE128_SIZE 16 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, } 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"}, {"file...", HITLS_APP_OPT_DGST_FILE, HITLS_APP_OPT_VALUETYPE_PARAMTERS, "Files to be digested"}, {NULL}}; typedef struct { char *algName; int32_t algId; uint32_t digestSize; // the length of default hash value of the algorithm } AlgInfo; static AlgInfo g_dgstInfo = {"sha256", CRYPT_MD_SHA256, 0}; 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); int32_t HITLS_DgstMain(int argc, char *argv[]) { char *outfile = NULL; int32_t mainRet = HITLS_APP_SUCCESS; CRYPT_EAL_MdCTX *ctx = NULL; mainRet = HITLS_APP_OptBegin(argc, argv, g_dgstOpts); if (mainRet != HITLS_APP_SUCCESS) { (void)AppPrintError("error in opt begin.\n"); goto end; } mainRet = OptParse(&outfile); if (mainRet != HITLS_APP_SUCCESS) { goto end; } g_argc = HITLS_APP_GetRestOptNum(); g_argv = HITLS_APP_GetRestOpt(); ctx = InitAlgDigest(g_dgstInfo.algId); if (ctx == NULL) { mainRet = HITLS_APP_CRYPTO_FAIL; goto end; } if (g_dgstInfo.algId == CRYPT_MD_SHAKE128) { g_dgstInfo.digestSize = DEFAULT_SHAKE128_SIZE; } else if (g_dgstInfo.algId == CRYPT_MD_SHAKE256) { g_dgstInfo.digestSize = DEFAULT_SHAKE256_SIZE; } else { g_dgstInfo.digestSize = CRYPT_EAL_MdGetDigestSize(g_dgstInfo.algId); if (g_dgstInfo.digestSize == 0) { mainRet = HITLS_APP_CRYPTO_FAIL; (void)AppPrintError("Failed to obtain the default length of the algorithm(%s)\n", g_dgstInfo.algName); goto end; } } mainRet = (g_argc == 0) ? StdSumAndOut(ctx, outfile) : FileSumAndOut(ctx, outfile); CRYPT_EAL_MdDeinit(ctx); // algorithm release end: CRYPT_EAL_MdFreeCtx(ctx); 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("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("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("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("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("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("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("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("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("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("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("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("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("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("Summary context deinit failed.\n"); return HITLS_APP_CRYPTO_FAIL; } outRet = CRYPT_EAL_MdInit(ctx); // md initialization if (outRet != CRYPT_SUCCESS) { (void)AppPrintError("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("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("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("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("Summary context deinit failed.\n"); return HITLS_APP_CRYPTO_FAIL; } outRet = CRYPT_EAL_MdInit(ctx); // md initialization if (outRet != CRYPT_SUCCESS) { (void)AppPrintError("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("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("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("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("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(NULL, id, "provider=default"); // creating an MD Context if (ctx == NULL) { (void)AppPrintError("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("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("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; default: return HITLS_APP_OPT_UNKOWN; } } return HITLS_APP_SUCCESS; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_dgst.c
C
unknown
19,488
/* * 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_help.h" #include "app_print.h" #include "app_opt.h" #include "bsl_sal.h" #include "sal_file.h" #include "ui_type.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" 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"}, {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_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, }; 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; } 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) { 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; } // enc check the validity of option parameters static int32_t CheckParam(EncCmdOpt *encOpt) { // 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) { // 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(&param, 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 if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default", NULL, 0, NULL) != CRYPT_SUCCESS || CRYPT_EAL_RandbytesEx(NULL, encOpt->keySet->salt, encOpt->keySet->saltLen) != CRYPT_SUCCESS) { AppPrintError("Failed to generate the salt value.\n"); return HITLS_APP_CRYPTO_FAIL; } // use the random number API to generate the iv value if (encOpt->keySet->ivLen > 0) { if (CRYPT_EAL_RandbytesEx(NULL, encOpt->keySet->iv, encOpt->keySet->ivLen) != CRYPT_SUCCESS) { AppPrintError("Failed to generate the iv value.\n"); return HITLS_APP_CRYPTO_FAIL; } } CRYPT_EAL_RandDeinitEx(NULL); 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; } static int32_t DriveKey(EncCmdOpt *encOpt) { if (CRYPT_EAL_CipherGetInfo(encOpt->cipherId, CRYPT_INFO_KEY_LEN, &encOpt->keySet->dKeyLen) != CRYPT_SUCCESS) { return HITLS_APP_CRYPTO_FAIL; } CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_PBKDF2); if (ctx == NULL) { return HITLS_APP_MEM_ALLOC_FAIL; } BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &encOpt->mdId, sizeof(encOpt->mdId)); (void)BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, encOpt->keySet->pass, encOpt->keySet->passLen); (void)BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, encOpt->keySet->salt, encOpt->keySet->saltLen); (void)BSL_PARAM_InitValue(&params[3], 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 (DriveKey(encOpt) != BSL_SUCCESS) { return HITLS_APP_CRYPTO_FAIL; } // Create a cipher context. encOpt->keySet->ctx = CRYPT_EAL_ProviderCipherNewCtx(NULL, encOpt->cipherId, "provider=default"); 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; } } 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; } // 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}; EncCmdOpt encOpt = {1, NULL, NULL, NULL, -1, -1, -1, 0, &keySet, &encUio}; 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; } if ((encRet = HandleIO(&encOpt)) != HITLS_APP_SUCCESS) { goto End; } if ((encRet = ApplyForSpace(&encOpt)) != HITLS_APP_SUCCESS) { goto End; } if ((encRet = HandlePasswd(&encOpt)) != HITLS_APP_SUCCESS) { goto End; } // 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) { // Random salt and IV are generated in encryption mode. if ((encRet = GenSaltAndIv(&encOpt)) != HITLS_APP_SUCCESS) { goto End; } } // If the user identifier is decrypted if (encOpt.encTag == 0) { // Decryption mode: Parse the file header data and receive the ciphertext in the input file. if ((encRet = HandleDecFileHeader(&encOpt)) != HITLS_APP_SUCCESS) { goto End; } } // Final encryption or decryption process if ((encRet = EncOrDecProc(&encOpt)) != HITLS_APP_SUCCESS) { goto End; } encRet = HITLS_APP_SUCCESS; End: 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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_enc.c
C
unknown
49,952
/* * 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" 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}, {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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_function.c
C
unknown
3,240
/* * 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 <linux/limits.h> #include "app_errno.h" #include "app_help.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 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 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_OUT, } 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"}, {"pkeyopt", HITLS_APP_OPT_PKEYOPT, HITLS_APP_OPT_VALUETYPE_STRING, "Set key options"}, {"", 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"}, {"out", HITLS_APP_OPT_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"}, {NULL}, }; typedef struct { char *algorithm; char *pkeyOptArg[MAX_PKEY_OPT_ARG]; uint32_t pkeyOptArgNum; } InputGenKeyPara; typedef struct { char *outFilePath; char *passOutArg; } 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 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 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 { (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 { (void)AppPrintError("genpkey: The %s algorithm is not supported.\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 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_OUT, GenPkeyOptOut}, }; 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; } // 4. Output the private key. return HITLS_APP_PrintPrvKey(optCtx->pkey, optCtx->outPara.outFilePath, BSL_FORMAT_PEM, 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; } 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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_genpkey.c
C
unknown
11,840
/* * 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 <linux/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} }; 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(&param, 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 = malloc(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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_genrsa.c
C
unknown
12,019
/* * 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} }; 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); }
2302_82127028/openHiTLS-examples_5985
apps/src/app_help.c
C
unknown
2,358
/* * 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 <linux/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_help.h" #include "app_print.h" #include "app_provider.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 } 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, {"kdfalg...", HITLS_APP_OPT_KDF_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Specify KDF algorithm (e.g.: pbkdf2)."}, {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; } 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; } } HITLS_APP_PROV_CASES(optType, kdfOpt->provider) if (ret != HITLS_APP_SUCCESS) { return ret; } } 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->macId == 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("mac: Use -help for summary.\n"); return HITLS_APP_OPT_UNKOWN; } return HITLS_APP_SUCCESS; } static int32_t CheckParam(KdfOpt *kdfOpt) { 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) { if (HITLS_APP_LoadProvider(kdfOpt->provider->providerPath, kdfOpt->provider->providerName) != HITLS_APP_SUCCESS) { return NULL; } 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) { if (kdfOpt->pass != NULL) { *passLen = strlen((const char*)kdfOpt->pass); *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) { if (kdfOpt->salt != NULL) { *saltLen = strlen((const char*)kdfOpt->salt); *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(&params[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(&params[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(&params[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(&params[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_FREE(pass); } 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; } 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_FREE(out); return HITLS_APP_CRYPTO_FAIL; } BSL_UIO *fileOutUio = HITLS_APP_UioOpen(kdfOpt->outFile, 'w', 0); if (fileOutUio == NULL) { BSL_SAL_FREE(out); (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_FREE(out); return ret; } int32_t HITLS_KdfMain(int argc, char *argv[]) { int32_t mainRet = HITLS_APP_SUCCESS; AppProvider appProvider = {"default", NULL, "provider=default"}; KdfOpt kdfOpt = {CRYPT_MAC_HMAC_SHA256, NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, 1000, &appProvider, 0}; CRYPT_EAL_KdfCTX *ctx = NULL; do { mainRet = HITLS_APP_OptBegin(argc, argv, g_kdfOpts); if (mainRet != HITLS_APP_SUCCESS) { HITLS_APP_OptEnd(); (void)AppPrintError("error in opt begin.\n"); break; } mainRet = ParseKdfOpt(&kdfOpt); if (mainRet != HITLS_APP_SUCCESS) { HITLS_APP_OptEnd(); break; } mainRet = GetKdfAlg(&kdfOpt); if (mainRet != HITLS_APP_SUCCESS) { HITLS_APP_OptEnd(); break; } HITLS_APP_OptEnd(); mainRet = CheckParam(&kdfOpt); if (mainRet != HITLS_APP_SUCCESS) { 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_OptEnd(); return mainRet; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_kdf.c
C
unknown
15,253
/* * 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}}; 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, "cbc-mac-sm4"}, }; #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_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"}, }; #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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_list.c
C
unknown
17,895
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "app_mac.h" #include <linux/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_help.h" #include "app_print.h" #include "app_provider.h" #include "app_utils.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 #define MAC_MAX_IV_LENGTH 16 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_OPT_MAC_IV, HITLS_APP_OPT_MAC_HEXIV, HITLS_APP_OPT_MAC_TAGLEN, HITLS_APP_PROV_ENUM } 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)."}, {"iv", HITLS_APP_OPT_MAC_IV, HITLS_APP_OPT_VALUETYPE_STRING, "Input initialization vector as a string."}, {"hexiv", HITLS_APP_OPT_MAC_HEXIV, HITLS_APP_OPT_VALUETYPE_STRING, "Input initialization vector in hexadecimal format (e.g., 0xAABBCCDD)."}, {"taglen", HITLS_APP_OPT_MAC_TAGLEN, HITLS_APP_OPT_VALUETYPE_INT, "Set authentication tag length."}, HITLS_APP_PROV_OPTIONS, {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; char *iv; char *hexIv; uint32_t tagLen; AppProvider *provider; } 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 MacOptIv(MacOpt *macOpt) { macOpt->iv = HITLS_APP_OptGetValueStr(); return HITLS_APP_SUCCESS; } static int32_t MacOptHexIv(MacOpt *macOpt) { macOpt->hexIv = HITLS_APP_OptGetValueStr(); return HITLS_APP_SUCCESS; } static int32_t MacOptBinary(MacOpt *macOpt) { macOpt->isBinary = 1; return HITLS_APP_SUCCESS; } static int32_t MacOptTagLen(MacOpt *macOpt) { int32_t ret = HITLS_APP_OptGetUint32(HITLS_APP_OptGetValueStr(), &(macOpt->tagLen)); if (ret != HITLS_APP_SUCCESS) { AppPrintError("mac: Invalid tagLen value.\n"); } return ret; } 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_IV, MacOptIv}, {HITLS_APP_OPT_MAC_HEXIV, MacOptHexIv}, {HITLS_APP_OPT_MAC_BINARY, MacOptBinary}, {HITLS_APP_OPT_MAC_TAGLEN, MacOptTagLen}, {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); 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 CheckParam(MacOpt *macOpt) { if (macOpt->algId < 0) { macOpt->algId = CRYPT_MAC_HMAC_SHA256; } 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; } if (macOpt->algId >= CRYPT_MAC_GMAC_AES128 && macOpt->algId <= CRYPT_MAC_GMAC_AES256) { if (macOpt->iv == NULL && macOpt->hexIv == NULL) { AppPrintError("mac: No iv entered.\n"); return HITLS_APP_OPT_VALUE_INVALID; } if (macOpt->iv != NULL && macOpt->hexIv != NULL) { AppPrintError("mac: Cannot specify both iv and hexiv.\n"); return HITLS_APP_OPT_VALUE_INVALID; } } else { if (macOpt->iv != NULL || macOpt->hexIv != NULL) { AppPrintError("mac: iv is not supported for this algorithm.\n"); BSL_SAL_FREE(macOpt->iv); BSL_SAL_FREE(macOpt->hexIv); } } 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; } static CRYPT_EAL_MacCtx *InitAlgMac(MacOpt *macOpt) { uint8_t *key = NULL; uint32_t keyLen = MAC_MAX_KEY_LEN; int32_t ret; if (macOpt->key != NULL) { keyLen = strlen((const char*)macOpt->key); key = (uint8_t*)macOpt->key; } else if (macOpt->hexKey != NULL) { ret = HITLS_APP_HexToByte(macOpt->hexKey, &key, &keyLen); if (ret == HITLS_APP_OPT_VALUE_INVALID) { AppPrintError("mac:Invalid key: %s.\n", macOpt->hexKey); return NULL; } } CRYPT_EAL_MacCtx *ctx = NULL; do { ret = HITLS_APP_LoadProvider(macOpt->provider->providerPath, macOpt->provider->providerName); if (ret != HITLS_APP_SUCCESS) { break; } 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); if (macOpt->hexKey != NULL) { BSL_SAL_FREE(key); } return ctx; } static int32_t MacParamSet(CRYPT_EAL_MacCtx *ctx, MacOpt *macOpt) { int32_t ret = HITLS_APP_SUCCESS; uint8_t *iv = NULL; uint32_t padding = CRYPT_PADDING_ZEROS; uint32_t ivLen = MAC_MAX_IV_LENGTH; 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); return HITLS_APP_CRYPTO_FAIL; } } if (macOpt->algId >= CRYPT_MAC_GMAC_AES128 && macOpt->algId <= CRYPT_MAC_GMAC_AES256) { if (macOpt->iv != NULL) { ivLen = strlen((const char*)macOpt->iv); iv = (uint8_t *)macOpt->iv; } else { ret = HITLS_APP_HexToByte(macOpt->hexIv, &iv, &ivLen); if (ret != HITLS_APP_SUCCESS) { AppPrintError("mac: Invalid iv: %s.\n", macOpt->hexIv); return ret; } } do { ret = CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_IV, macOpt->iv, ivLen); if (ret != CRYPT_SUCCESS) { (void)AppPrintError("mac:Failed to set GMAC IV, ret=%d\n", ret); ret = HITLS_APP_CRYPTO_FAIL; break; } ret = CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &(macOpt->tagLen), sizeof(int32_t)); if (ret != CRYPT_SUCCESS) { (void)AppPrintError("mac:Failed to set GMAC TAGLEN, ret=%d\n", ret); ret = HITLS_APP_CRYPTO_FAIL; break; } } while (0); if (macOpt->hexIv != NULL) { BSL_SAL_FREE(iv); } } 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; } int32_t HITLS_MacMain(int argc, char *argv[]) { int32_t mainRet = HITLS_APP_SUCCESS; AppProvider appProvider = {"default", NULL, "provider=default"}; MacOpt macOpt = {CRYPT_MAC_HMAC_SHA256, 0, 0, NULL, {0}, 0, NULL, NULL, NULL, 0, NULL, NULL, 0, &appProvider}; CRYPT_EAL_MacCtx *ctx = NULL; do { mainRet = HITLS_APP_OptBegin(argc, argv, g_macOpts); if (mainRet != HITLS_APP_SUCCESS) { HITLS_APP_OptEnd(); (void)AppPrintError("error in opt begin.\n"); break; } mainRet = ParseMacOpt(&macOpt); if (mainRet != HITLS_APP_SUCCESS) { HITLS_APP_OptEnd(); break; } HITLS_APP_OptEnd(); mainRet = CheckParam(&macOpt); if (mainRet != HITLS_APP_SUCCESS) { break; } ctx = InitAlgMac(&macOpt); if (ctx == NULL) { mainRet = HITLS_APP_CRYPTO_FAIL; break; } mainRet = MacParamSet(ctx, &macOpt); if (mainRet != CRYPT_SUCCESS) { (void)AppPrintError("mac:Failed to set mac params\n"); break; } mainRet = GetReadBuf(ctx, &macOpt); if (mainRet != HITLS_APP_SUCCESS) { break; } mainRet = MacResult(ctx, &macOpt); } while (0); CRYPT_EAL_MacDeinit(ctx); // algorithm release CRYPT_EAL_MacFreeCtx(ctx); HITLS_APP_OptEnd(); return mainRet; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_mac.c
C
unknown
17,333
/* * 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) { 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.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) { if (inBuf == NULL || outBuf == NULL || inBufLen == 0 || outBufLen == 0) { return HITLS_APP_INTERNAL_EXCEPTION; } // One byte is encoded into hex and becomes 2 bytes. int32_t hexCharSize = 2; char midBuf[outBufLen + 1]; // snprint_s will definitely increase '\ 0' for (uint32_t i = 0; i < inBufLen; ++i) { int ret = snprintf_s(midBuf + i * hexCharSize, outBufLen + 1, outBufLen, "%02x", inBuf[i]); if (ret == -1) { (void)AppPrintError("Failed to convert to hex format\n"); return HITLS_APP_ENCODE_FAIL; } } if (memcpy_s(outBuf, outBufLen, midBuf, strlen(midBuf)) != EOK) { return HITLS_APP_SECUREC_FAIL; } 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; // 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); 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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_opt.c
C
unknown
21,317
/* * 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 <linux/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} }; 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(&param, 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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_passwd.c
C
unknown
28,128
/* * 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 <linux/limits.h> #include "app_errno.h" #include "app_help.h" #include "app_print.h" #include "app_opt.h" #include "app_utils.h" #include "app_list.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} }; 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) { // If the user certificate is a root certificate, no action is required. bool selfSigned = false; int32_t ret = HITLS_X509_CheckIssued(opt->userCert, opt->userCert, &selfSigned); if (ret != HITLS_PKI_SUCCESS) { AppPrintError("pkcs12: Failed to check cert issued, errCode = 0x%x.\n", ret); return HITLS_APP_X509_FAIL; } opt->store = HITLS_X509_StoreCtxNew(); if (opt->store == NULL) { AppPrintError("pkcs12: Failed to create the store context.\n"); return HITLS_APP_X509_FAIL; } 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, &param, &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, &param, &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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_pkcs12.c
C
unknown
36,641
/* * 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 <linux/limits.h> #include "app_errno.h" #include "app_help.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}, }; 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, &param, &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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_pkey.c
C
unknown
8,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 <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; } }
2302_82127028/openHiTLS-examples_5985
apps/src/app_print.c
C
unknown
2,515
/* * 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 <linux/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 ret; } } 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 ret; } #endif // HITLS_CRYPTO_PROVIDER
2302_82127028/openHiTLS-examples_5985
apps/src/app_provider.c
C
unknown
1,903
/* * 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 <linux/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" #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, } HITLSOptType; 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"}, {NULL}}; static int32_t OptParse(char **outfile, int32_t *format); static int32_t RandNumOut(int32_t randNumLen, char *outfile, int format); int32_t HITLS_RandMain(int argc, char **argv) { char *outfile = NULL; // output file name int32_t format = HITLS_APP_FORMAT_BINARY; // default binary output int32_t randNumLen = 0; // length of the random number entered by the user int32_t mainRet = HITLS_APP_SUCCESS; // return value of the main function mainRet = HITLS_APP_OptBegin(argc, argv, g_randOpts); if (mainRet != HITLS_APP_SUCCESS) { goto end; } mainRet = OptParse(&outfile, &format); if (mainRet != HITLS_APP_SUCCESS) { goto end; } // 获取用户输入即要生成的随机数长度 int unParseParamNum = HITLS_APP_GetRestOptNum(); char** unParseParam = HITLS_APP_GetRestOpt(); if (unParseParamNum != 1) { (void)AppPrintError("Extra arguments given.\n"); (void)AppPrintError("rand: Use -help for summary.\n"); mainRet = HITLS_APP_OPT_UNKOWN; goto end; } else { mainRet = HITLS_APP_OptGetInt(unParseParam[0], &randNumLen); if (mainRet != HITLS_APP_SUCCESS || randNumLen <= 0) { mainRet = HITLS_APP_OPT_VALUE_INVALID; (void)AppPrintError("Valid Range[1, 2147483647]\n"); goto end; } } if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR, "provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) { mainRet = HITLS_APP_CRYPTO_FAIL; goto end; } mainRet = RandNumOut(randNumLen, outfile, format); end: CRYPT_EAL_RandDeinitEx(NULL); HITLS_APP_OptEnd(); return mainRet; } static int32_t OptParse(char **outfile, int32_t *format) { 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: *outfile = HITLS_APP_OptGetValueStr(); if (*outfile == NULL || strlen(*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_RAND_BASE64: *format = HITLS_APP_FORMAT_BASE64; break; case HITLS_APP_OPT_RAND_HEX: *format = HITLS_APP_FORMAT_HEX; break; default: break; } } return HITLS_APP_SUCCESS; } static int32_t RandNumOut(int32_t randNumLen, char *outfile, int format) { int ret = HITLS_APP_SUCCESS; BSL_UIO *uio; uio = HITLS_APP_UioOpen(outfile, 'w', 0); if (uio == NULL) { return HITLS_APP_UIO_FAIL; } if (outfile != NULL) { BSL_UIO_SetIsUnderlyingClosedByUio(uio, true); } while (randNumLen > 0) { uint8_t outBuf[MAX_RANDOM_LEN] = {0}; uint32_t outLen = randNumLen; if (outLen > MAX_RANDOM_LEN) { outLen = MAX_RANDOM_LEN; } int32_t randRet = CRYPT_EAL_RandbytesEx(NULL, outBuf, outLen); if (randRet != CRYPT_SUCCESS) { BSL_UIO_Free(uio); (void)AppPrintError("Failed to generate a random number.\n"); return HITLS_APP_CRYPTO_FAIL; } ret = HITLS_APP_OptWriteUio(uio, outBuf, outLen, format); if (ret != HITLS_APP_SUCCESS) { BSL_UIO_Free(uio); return ret; } randNumLen -= outLen; if (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); (void)AppPrintError("Failed to enter the newline character\n"); return ret; } } } BSL_UIO_Free(uio); return HITLS_APP_SUCCESS; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_rand.c
C
unknown
6,364
/* * 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 <linux/limits.h> #include "app_errno.h" #include "app_help.h" #include "app_print.h" #include "app_opt.h" #include "app_list.h" #include "bsl_ui.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_csr_local.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}, }; 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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_req.c
C
unknown
18,571
/* * 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 <linux/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_encode_decode_key.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}}; 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) { 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) { 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)) { free(buf); break; } 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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_rsa.c
C
unknown
11,175
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "app_utils.h" #include <stdio.h> #include <securec.h> #include <string.h> #include <linux/limits.h> #include "bsl_sal.h" #include "bsl_buffer.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_encode_decode_key.h" #include "app_print.h" #include "app_errno.h" #include "app_opt.h" #include "app_list.h" #include "hitls_pki_errno.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)) typedef struct defaultPassCBData { uint32_t maxLen; uint32_t minLen; } APP_DefaultPassCBData; 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 CheckFileSizeByUio(BSL_UIO *uio, uint32_t *fileSize) { uint64_t getFileSize = 0; int32_t ret = BSL_UIO_Ctrl(uio, BSL_UIO_PENDING, sizeof(getFileSize), &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 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; } BSL_UIO *rUio = HITLS_APP_UioOpen(inFilePath, 'r', 1); if (rUio == NULL) { return HITLS_APP_UIO_FAIL; } BSL_UIO_SetIsUnderlyingClosedByUio(rUio, true); uint32_t fileSize = 0; if (CheckFileSizeByUio(rUio, &fileSize) != HITLS_APP_SUCCESS) { BSL_UIO_Free(rUio); return HITLS_APP_UIO_FAIL; } // End after reading the following two strings in sequence: // -----BEGIN XXX----- // -----END XXX----- bool isParseHeader = false; uint8_t *data = (uint8_t *)BSL_SAL_Calloc(fileSize + 1, sizeof(uint8_t)); // +1 for the null terminator if (data == NULL) { BSL_UIO_Free(rUio); return HITLS_APP_MEM_ALLOC_FAIL; } char *tmp = (char *)data; uint32_t readLen = 0; while (readLen < fileSize) { uint32_t getsLen = APP_LINESIZE; if ((BSL_UIO_Gets(rUio, tmp, &getsLen) != BSL_SUCCESS) || (getsLen == 0)) { break; } if (*name == NULL) { *name = GetPemKeyFileName(tmp, getsLen); } else if (getsLen < 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, getsLen); isParseHeader = true; } tmp += getsLen; readLen += getsLen; } BSL_UIO_Free(rUio); if (readLen == 0 || *name == NULL) { AppPrintError("Failed to read the pem file.\n"); BSL_SAL_FREE(data); BSL_SAL_FREE(*name); return HITLS_APP_STDIN_FAIL; } *inData = 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; } 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"); } 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, &param, 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, &param }; BSL_Buffer prvKeyBuf = { 0 }; if (CRYPT_EAL_EncodeBuffKey(pkey, &paramEx, 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; } uint32_t hexIdx = 0; uint32_t binIdx = 0; char *endptr; char tmp[] = {'0', '0', '\0'}; while (hexIdx < hexLen) { if (hexIdx == 0 && hexLen % HEX_TO_BYTE == 1) { tmp[0] = '0'; } else { tmp[0] = num[hexIdx++]; } tmp[1] = num[hexIdx++]; res[binIdx++] = (uint32_t)strtol(tmp, &endptr, 16); // 16: hex if (*endptr != '\0') { BSL_SAL_Free(res); return HITLS_APP_OPT_VALUE_INVALID; } } *bin = res; return HITLS_APP_SUCCESS; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_utils.c
C
unknown
31,126
/* * 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 <linux/limits.h> #include "string.h" #include "securec.h" #include "bsl_sal.h" #include "bsl_errno.h" #include "crypt_errno.h" #include "app_function.h" #include "bsl_list.h" #include "app_errno.h" #include "app_opt.h" #include "app_help.h" #include "app_print.h" #include "app_conf.h" #include "app_utils.h" #include "crypt_eal_rand.h" #include "hitls_pki_errno.h" #include "hitls_cert_local.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} }; 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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_verify.c
C
unknown
9,988
/* * 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 <linux/limits.h> #include "bsl_list.h" #include "bsl_print.h" #include "bsl_buffer.h" #include "bsl_conf.h" #include "bsl_errno.h" #include "crypt_errno.h" #include "crypt_eal_rand.h" #include "crypt_encode_decode_key.h" #include "crypt_eal_codecs.h" #include "crypt_eal_md.h" #include "hitls_pki_errno.h" #include "app_errno.h" #include "app_help.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 #define X509_SHAKE128_DIGEST_LEN 16 #define X509_SHAKE256_DIGEST_LEN 32 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}, }; 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 = X509_SHAKE128_DIGEST_LEN; } else if (optCtx->printOpts.mdId == CRYPT_MD_SHAKE256) { mdLen = X509_SHAKE256_DIGEST_LEN; } 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; }
2302_82127028/openHiTLS-examples_5985
apps/src/app_x509.c
C
unknown
45,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. */ #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(APP_GetCurrent_LibCtx()); AppUninit(); return ret; }
2302_82127028/openHiTLS-examples_5985
apps/src/hitls.c
C
unknown
3,229
/* * 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
2302_82127028/openHiTLS-examples_5985
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; }
2302_82127028/openHiTLS-examples_5985
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; } }
2302_82127028/openHiTLS-examples_5985
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" void *PrivPassNewPkeyCtx(void *libCtx, const char *attrName, int32_t algId) { (void)libCtx; (void)attrName; return CRYPT_EAL_PkeyNewCtx(algId); } 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; } 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; uint32_t flag = CRYPT_RSA_BSSA; uint32_t padType = 0; int32_t 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; } ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t)); 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; } 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); } 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; uint32_t flag = CRYPT_RSA_BSSA; uint32_t padType = CRYPT_EMSA_PSS; int32_t ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_PADDING, &padType, sizeof(padType)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return CRYPT_EAL_PkeySignData(ctx, data, dataLen, sign, signLen); } 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; uint32_t flag = CRYPT_RSA_BSSA; uint32_t padType = 0; int32_t 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; } ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t)); 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; } 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; } 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; } 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; } 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; }
2302_82127028/openHiTLS-examples_5985
auth/privpass_token/src/privpass_token_wrapper.c
C
unknown
11,338
/* * 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
2302_82127028/openHiTLS-examples_5985
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_bytes.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 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_DecodeListParam *param, BSL_ASN1_Buffer *asn, BSL_ASN1_ParseListAsnItem parseListItemCb, void *cbParam, BSL_ASN1_List *list) { 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 != 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 = parseListItemCb(layer, &item, cbParam, list); if (ret != BSL_SUCCESS) { return ret; } buff += encLen; len -= encLen; } return BSL_SUCCESS; } static int32_t DecodeOneLayerList(BSL_ASN1_DecodeListParam *param, BSL_ASN1_Buffer *asn, BSL_ASN1_ParseListAsnItem parseListItemCb, void *cbParam, BSL_ASN1_List *list) { return DecodeTwoLayerListInternal(1, param, asn, parseListItemCb, cbParam, list); } static int32_t DecodeTwoLayerList(BSL_ASN1_DecodeListParam *param, BSL_ASN1_Buffer *asn, BSL_ASN1_ParseListAsnItem parseListItemCb, void *cbParam, BSL_ASN1_List *list) { 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 != 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 = parseListItemCb(1, &item, cbParam, list); if (ret != BSL_SUCCESS) { return ret; } ret = DecodeTwoLayerListInternal(2, param, &item, parseListItemCb, cbParam, 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; } return param->layer == 1 ? DecodeOneLayerList(param, asn, parseListItemCb, cbParam, list) : DecodeTwoLayerList(param, asn, parseListItemCb, cbParam, list); } 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 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; 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; 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(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; }
2302_82127028/openHiTLS-examples_5985
bsl/asn1/src/bsl_asn1.c
C
unknown
43,813
/* * 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
2302_82127028/openHiTLS-examples_5985
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 */
2302_82127028/openHiTLS-examples_5985
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 */
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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 */
2302_82127028/openHiTLS-examples_5985
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 */
2302_82127028/openHiTLS-examples_5985
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 */
2302_82127028/openHiTLS-examples_5985
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 */
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
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 */
2302_82127028/openHiTLS-examples_5985
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
2302_82127028/openHiTLS-examples_5985
bsl/err/src/avl.h
C
unknown
3,271